Merge remote-tracking branch 'origin/dev' into 074-verification-checklist-session-1770249024
This commit is contained in:
commit
0b578dc1aa
@ -1,5 +1,6 @@
|
||||
node_modules/
|
||||
vendor/
|
||||
coverage/
|
||||
.git/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Filament\Pages\Operations;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\User;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Pages\Page;
|
||||
|
||||
class TenantlessOperationRunViewer extends Page
|
||||
{
|
||||
protected static string $layout = 'filament-panels::components.layout.simple';
|
||||
|
||||
protected static bool $shouldRegisterNavigation = false;
|
||||
|
||||
protected static bool $isDiscovered = false;
|
||||
|
||||
protected static ?string $title = 'Operation run';
|
||||
|
||||
protected string $view = 'filament.pages.operations.tenantless-operation-run-viewer';
|
||||
|
||||
public OperationRun $run;
|
||||
|
||||
/**
|
||||
* @return array<Action>
|
||||
*/
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('refresh')
|
||||
->label('Refresh')
|
||||
->icon('heroicon-o-arrow-path')
|
||||
->color('gray')
|
||||
->url(fn (): string => url()->current()),
|
||||
];
|
||||
}
|
||||
|
||||
public function mount(OperationRun $run): void
|
||||
{
|
||||
$user = auth()->user();
|
||||
|
||||
if (! $user instanceof User) {
|
||||
abort(403);
|
||||
}
|
||||
|
||||
$workspaceId = (int) ($run->workspace_id ?? 0);
|
||||
|
||||
if ($workspaceId <= 0) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$isMember = WorkspaceMembership::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('user_id', (int) $user->getKey())
|
||||
->exists();
|
||||
|
||||
if (! $isMember) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->run = $run->loadMissing(['workspace', 'tenant', 'user']);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -20,6 +20,7 @@
|
||||
use App\Support\Badges\BadgeRenderer;
|
||||
use App\Support\OperationRunLinks;
|
||||
use App\Support\Rbac\UiEnforcement;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use BackedEnum;
|
||||
use Filament\Actions;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
@ -99,9 +100,16 @@ public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(function (Builder $query): Builder {
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
$tenantId = Tenant::current()?->getKey();
|
||||
|
||||
return $query->when($tenantId, fn (Builder $q) => $q->where('tenant_id', $tenantId));
|
||||
if ($workspaceId === null) {
|
||||
return $query->whereRaw('1 = 0');
|
||||
}
|
||||
|
||||
return $query
|
||||
->where('workspace_id', (int) $workspaceId)
|
||||
->when($tenantId, fn (Builder $q) => $q->where('tenant_id', $tenantId));
|
||||
})
|
||||
->defaultSort('display_name')
|
||||
->columns([
|
||||
@ -633,9 +641,17 @@ public static function table(Table $table): Table
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
$tenantId = Tenant::current()?->getKey();
|
||||
|
||||
return parent::getEloquentQuery()
|
||||
$query = parent::getEloquentQuery();
|
||||
|
||||
if ($workspaceId === null) {
|
||||
return $query->whereRaw('1 = 0');
|
||||
}
|
||||
|
||||
return $query
|
||||
->where('workspace_id', (int) $workspaceId)
|
||||
->when($tenantId, fn (Builder $query) => $query->where('tenant_id', $tenantId))
|
||||
->latest('id');
|
||||
}
|
||||
|
||||
@ -22,6 +22,7 @@ protected function mutateFormDataBeforeCreate(array $data): array
|
||||
$this->shouldMakeDefault = (bool) ($data['is_default'] ?? false);
|
||||
|
||||
return [
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'tenant_id' => $tenant->getKey(),
|
||||
'provider' => 'microsoft',
|
||||
'entra_tenant_id' => $data['entra_tenant_id'],
|
||||
|
||||
@ -51,7 +51,7 @@ public function __invoke(Request $request): RedirectResponse
|
||||
$tenantCount = (int) $tenantsQuery->count();
|
||||
|
||||
if ($tenantCount === 0) {
|
||||
return redirect()->route('admin.workspace.managed-tenants.onboarding', ['workspace' => $workspace->slug ?? $workspace->getKey()]);
|
||||
return redirect()->route('admin.onboarding');
|
||||
}
|
||||
|
||||
if ($tenantCount === 1) {
|
||||
|
||||
@ -32,6 +32,19 @@ public function handle(Request $request, Closure $next): Response
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if ($path === '/livewire/update') {
|
||||
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
|
||||
$refererPath = '/'.ltrim((string) $refererPath, '/');
|
||||
|
||||
if (preg_match('#^/admin/operations/[^/]+$#', $refererPath) === 1) {
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
||||
if (preg_match('#^/admin/operations/[^/]+$#', $path) === 1) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if (in_array($path, ['/admin/no-access', '/admin/choose-workspace'], true)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
@ -21,11 +21,41 @@ class OperationRun extends Model
|
||||
'completed_at' => 'datetime',
|
||||
];
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (self $operationRun): void {
|
||||
if ($operationRun->workspace_id !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($operationRun->tenant_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$tenant = Tenant::query()->whereKey((int) $operationRun->tenant_id)->first();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($tenant->workspace_id === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$operationRun->workspace_id = (int) $tenant->workspace_id;
|
||||
});
|
||||
}
|
||||
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
public function workspace(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Workspace::class);
|
||||
}
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
|
||||
@ -26,6 +26,11 @@ public function tenant(): BelongsTo
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
public function workspace(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Workspace::class);
|
||||
}
|
||||
|
||||
public function credential(): HasOne
|
||||
{
|
||||
return $this->hasOne(ProviderCredential::class, 'provider_connection_id');
|
||||
|
||||
@ -21,6 +21,14 @@ class Tenant extends Model implements HasName
|
||||
use HasFactory;
|
||||
use SoftDeletes;
|
||||
|
||||
public const STATUS_DRAFT = 'draft';
|
||||
|
||||
public const STATUS_ONBOARDING = 'onboarding';
|
||||
|
||||
public const STATUS_ACTIVE = 'active';
|
||||
|
||||
public const STATUS_ARCHIVED = 'archived';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
@ -69,7 +77,16 @@ protected static function booted(): void
|
||||
}
|
||||
|
||||
if (empty($tenant->status)) {
|
||||
$tenant->status = 'active';
|
||||
$tenant->status = self::STATUS_ACTIVE;
|
||||
}
|
||||
|
||||
if ($tenant->workspace_id === null && app()->runningUnitTests()) {
|
||||
$workspace = Workspace::query()->create([
|
||||
'name' => 'Test Workspace',
|
||||
'slug' => 'test-'.Str::lower(Str::random(10)),
|
||||
]);
|
||||
|
||||
$tenant->workspace_id = (int) $workspace->getKey();
|
||||
}
|
||||
});
|
||||
|
||||
@ -84,12 +101,12 @@ protected static function booted(): void
|
||||
return;
|
||||
}
|
||||
|
||||
$tenant->status = 'archived';
|
||||
$tenant->status = self::STATUS_ARCHIVED;
|
||||
$tenant->saveQuietly();
|
||||
});
|
||||
|
||||
static::restored(function (Tenant $tenant) {
|
||||
$tenant->forceFill(['status' => 'active'])->saveQuietly();
|
||||
$tenant->forceFill(['status' => self::STATUS_ACTIVE])->saveQuietly();
|
||||
});
|
||||
}
|
||||
|
||||
@ -97,12 +114,12 @@ public static function activeQuery(): Builder
|
||||
{
|
||||
return static::query()
|
||||
->whereNull('deleted_at')
|
||||
->where('status', 'active');
|
||||
->where('status', self::STATUS_ACTIVE);
|
||||
}
|
||||
|
||||
public function makeCurrent(): void
|
||||
{
|
||||
if ($this->trashed() || $this->status !== 'active') {
|
||||
if ($this->trashed() || $this->status !== self::STATUS_ACTIVE) {
|
||||
throw new RuntimeException('Only active tenants can be made current.');
|
||||
}
|
||||
|
||||
|
||||
@ -13,6 +13,25 @@ class TenantOnboardingSession extends Model
|
||||
|
||||
protected $table = 'managed_tenant_onboarding_sessions';
|
||||
|
||||
/**
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public const STATE_ALLOWED_KEYS = [
|
||||
'entra_tenant_id',
|
||||
'tenant_id',
|
||||
'tenant_name',
|
||||
'environment',
|
||||
'primary_domain',
|
||||
'notes',
|
||||
'provider_connection_id',
|
||||
'selected_provider_connection_id',
|
||||
'verification_operation_run_id',
|
||||
'verification_run_id',
|
||||
'bootstrap_operation_types',
|
||||
'bootstrap_operation_runs',
|
||||
'bootstrap_run_ids',
|
||||
];
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
@ -20,6 +39,24 @@ class TenantOnboardingSession extends Model
|
||||
'completed_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|null $value
|
||||
*/
|
||||
public function setStateAttribute(?array $value): void
|
||||
{
|
||||
if ($value === null) {
|
||||
$this->attributes['state'] = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$allowed = array_intersect_key($value, array_flip(self::STATE_ALLOWED_KEYS));
|
||||
|
||||
$encoded = json_encode($allowed, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
$this->attributes['state'] = $encoded !== false ? $encoded : json_encode([], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Workspace, $this>
|
||||
*/
|
||||
|
||||
@ -33,8 +33,20 @@ public function toDatabase(object $notifiable): array
|
||||
{
|
||||
$tenant = $this->run->tenant;
|
||||
|
||||
$context = is_array($this->run->context) ? $this->run->context : [];
|
||||
$wizard = $context['wizard'] ?? null;
|
||||
|
||||
$isManagedTenantOnboardingWizardRun = is_array($wizard)
|
||||
&& ($wizard['flow'] ?? null) === 'managed_tenant_onboarding';
|
||||
|
||||
$operationLabel = OperationCatalog::label((string) $this->run->type);
|
||||
|
||||
$runUrl = match (true) {
|
||||
$isManagedTenantOnboardingWizardRun => OperationRunLinks::tenantlessView($this->run),
|
||||
$tenant instanceof Tenant => OperationRunLinks::view($this->run, $tenant),
|
||||
default => null,
|
||||
};
|
||||
|
||||
return FilamentNotification::make()
|
||||
->title("{$operationLabel} queued")
|
||||
->body('Queued. Monitor progress in Monitoring → Operations.')
|
||||
@ -42,7 +54,7 @@ public function toDatabase(object $notifiable): array
|
||||
->actions([
|
||||
\Filament\Actions\Action::make('view_run')
|
||||
->label('View run')
|
||||
->url($tenant instanceof Tenant ? OperationRunLinks::view($this->run, $tenant) : null),
|
||||
->url($runUrl),
|
||||
])
|
||||
->getDatabaseMessage();
|
||||
}
|
||||
|
||||
@ -3,8 +3,9 @@
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
|
||||
@ -14,31 +15,31 @@ class OperationRunPolicy
|
||||
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId();
|
||||
|
||||
if (! $tenant) {
|
||||
if ($workspaceId === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $user->canAccessTenant($tenant);
|
||||
return WorkspaceMembership::query()
|
||||
->where('workspace_id', (int) $workspaceId)
|
||||
->where('user_id', (int) $user->getKey())
|
||||
->exists();
|
||||
}
|
||||
|
||||
public function view(User $user, OperationRun $run): Response|bool
|
||||
{
|
||||
$tenant = Tenant::current();
|
||||
$workspaceId = (int) ($run->workspace_id ?? 0);
|
||||
|
||||
if (! $tenant) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (! $user->canAccessTenant($tenant)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((int) $run->tenant_id !== (int) $tenant->getKey()) {
|
||||
if ($workspaceId <= 0) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
return true;
|
||||
$isMember = WorkspaceMembership::query()
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('user_id', (int) $user->getKey())
|
||||
->exists();
|
||||
|
||||
return $isMember ? true : Response::denyAsNotFound();
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,6 +5,8 @@
|
||||
use App\Models\ProviderConnection;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Illuminate\Auth\Access\HandlesAuthorization;
|
||||
use Illuminate\Auth\Access\Response;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
@ -15,15 +17,31 @@ class ProviderConnectionPolicy
|
||||
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
$workspace = $this->currentWorkspace();
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
return Gate::forUser($user)->allows('provider.view', $tenant);
|
||||
return $tenant instanceof Tenant
|
||||
&& (int) $tenant->workspace_id === (int) $workspace->getKey()
|
||||
&& Gate::forUser($user)->allows('provider.view', $tenant);
|
||||
}
|
||||
|
||||
public function view(User $user, ProviderConnection $connection): Response|bool
|
||||
{
|
||||
$workspace = $this->currentWorkspace();
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant || (int) $tenant->workspace_id !== (int) $workspace->getKey()) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
|
||||
return false;
|
||||
}
|
||||
@ -32,20 +50,40 @@ public function view(User $user, ProviderConnection $connection): Response|bool
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
if ((int) $connection->workspace_id !== (int) $workspace->getKey()) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
$workspace = $this->currentWorkspace();
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
return Gate::forUser($user)->allows('provider.manage', $tenant);
|
||||
return $tenant instanceof Tenant
|
||||
&& (int) $tenant->workspace_id === (int) $workspace->getKey()
|
||||
&& Gate::forUser($user)->allows('provider.manage', $tenant);
|
||||
}
|
||||
|
||||
public function update(User $user, ProviderConnection $connection): Response|bool
|
||||
{
|
||||
$workspace = $this->currentWorkspace();
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant || (int) $tenant->workspace_id !== (int) $workspace->getKey()) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
if (! Gate::forUser($user)->allows('provider.view', $tenant)) {
|
||||
return false;
|
||||
}
|
||||
@ -54,13 +92,26 @@ public function update(User $user, ProviderConnection $connection): Response|boo
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
if ((int) $connection->workspace_id !== (int) $workspace->getKey()) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function delete(User $user, ProviderConnection $connection): Response|bool
|
||||
{
|
||||
$workspace = $this->currentWorkspace();
|
||||
if (! $workspace instanceof Workspace) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
$tenant = Tenant::current();
|
||||
|
||||
if (! $tenant instanceof Tenant || (int) $tenant->workspace_id !== (int) $workspace->getKey()) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
if (! Gate::forUser($user)->allows('provider.manage', $tenant)) {
|
||||
return false;
|
||||
}
|
||||
@ -69,6 +120,19 @@ public function delete(User $user, ProviderConnection $connection): Response|boo
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
if ((int) $connection->workspace_id !== (int) $workspace->getKey()) {
|
||||
return Response::denyAsNotFound();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function currentWorkspace(): ?Workspace
|
||||
{
|
||||
$workspaceId = app(WorkspaceContext::class)->currentWorkspaceId(request());
|
||||
|
||||
return is_int($workspaceId)
|
||||
? Workspace::query()->whereKey($workspaceId)->first()
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
@ -24,6 +24,14 @@ class WorkspaceRoleCapabilityMap
|
||||
Capabilities::WORKSPACE_MEMBERSHIP_VIEW,
|
||||
Capabilities::WORKSPACE_MEMBERSHIP_MANAGE,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE,
|
||||
],
|
||||
|
||||
WorkspaceRole::Manager->value => [
|
||||
@ -31,11 +39,23 @@ class WorkspaceRoleCapabilityMap
|
||||
Capabilities::WORKSPACE_MEMBERSHIP_VIEW,
|
||||
Capabilities::WORKSPACE_MEMBERSHIP_MANAGE,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP,
|
||||
],
|
||||
|
||||
WorkspaceRole::Operator->value => [
|
||||
Capabilities::WORKSPACE_VIEW,
|
||||
Capabilities::WORKSPACE_MEMBERSHIP_VIEW,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC,
|
||||
Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP,
|
||||
],
|
||||
|
||||
WorkspaceRole::Readonly->value => [
|
||||
|
||||
@ -6,6 +6,25 @@
|
||||
|
||||
class GraphContractRegistry
|
||||
{
|
||||
public function probePath(string $key, array $replacements = []): ?string
|
||||
{
|
||||
$path = config("graph_contracts.probes.$key.path");
|
||||
|
||||
if (! is_string($path) || $path === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
foreach ($replacements as $placeholder => $value) {
|
||||
if (! is_string($placeholder) || $placeholder === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$path = str_replace($placeholder, urlencode((string) $value), $path);
|
||||
}
|
||||
|
||||
return '/'.ltrim($path, '/');
|
||||
}
|
||||
|
||||
public function directoryGroupsPolicyType(): string
|
||||
{
|
||||
return 'directoryGroups';
|
||||
|
||||
@ -409,7 +409,20 @@ private function shouldApplySelectFallback(GraphResponse $graphResponse, array $
|
||||
public function getOrganization(array $options = []): GraphResponse
|
||||
{
|
||||
$context = $this->resolveContext($options);
|
||||
$endpoint = 'organization';
|
||||
$endpoint = $this->contracts->probePath('organization');
|
||||
|
||||
if (! is_string($endpoint) || $endpoint === '') {
|
||||
return new GraphResponse(
|
||||
success: false,
|
||||
data: [],
|
||||
status: 500,
|
||||
errors: [[
|
||||
'message' => 'Graph contract missing for probe: organization',
|
||||
]],
|
||||
);
|
||||
}
|
||||
|
||||
$endpoint = ltrim($endpoint, '/');
|
||||
$clientRequestId = $options['client_request_id'] ?? (string) Str::uuid();
|
||||
$fullPath = $this->buildFullPath($endpoint);
|
||||
|
||||
@ -479,14 +492,27 @@ public function getServicePrincipalPermissions(array $options = []): GraphRespon
|
||||
$clientRequestId = $options['client_request_id'] ?? (string) Str::uuid();
|
||||
|
||||
// First, get the service principal object by clientId (appId)
|
||||
$endpoint = "servicePrincipals?\$filter=appId eq '{$clientId}'";
|
||||
$endpoint = $this->contracts->probePath('service_principal_by_app_id', ['{appId}' => $clientId]);
|
||||
|
||||
if (! is_string($endpoint) || $endpoint === '') {
|
||||
return new GraphResponse(
|
||||
success: false,
|
||||
data: [],
|
||||
status: 500,
|
||||
errors: [[
|
||||
'message' => 'Graph contract missing for probe: service_principal_by_app_id',
|
||||
]],
|
||||
);
|
||||
}
|
||||
|
||||
$endpoint = ltrim($endpoint, '/');
|
||||
|
||||
$this->logger->logRequest('get_service_principal', [
|
||||
'endpoint' => $endpoint,
|
||||
'client_id' => $clientId,
|
||||
'tenant' => $context['tenant'],
|
||||
'method' => 'GET',
|
||||
'full_path' => $endpoint,
|
||||
'full_path' => $this->buildFullPath($endpoint),
|
||||
'client_request_id' => $clientRequestId,
|
||||
]);
|
||||
|
||||
@ -528,14 +554,30 @@ public function getServicePrincipalPermissions(array $options = []): GraphRespon
|
||||
}
|
||||
|
||||
// Now get the app role assignments (application permissions)
|
||||
$assignmentsEndpoint = "servicePrincipals/{$servicePrincipalId}/appRoleAssignments";
|
||||
$assignmentsEndpoint = $this->contracts->probePath(
|
||||
'service_principal_app_role_assignments',
|
||||
['{servicePrincipalId}' => $servicePrincipalId],
|
||||
);
|
||||
|
||||
if (! is_string($assignmentsEndpoint) || $assignmentsEndpoint === '') {
|
||||
return new GraphResponse(
|
||||
success: false,
|
||||
data: [],
|
||||
status: 500,
|
||||
errors: [[
|
||||
'message' => 'Graph contract missing for probe: service_principal_app_role_assignments',
|
||||
]],
|
||||
);
|
||||
}
|
||||
|
||||
$assignmentsEndpoint = ltrim($assignmentsEndpoint, '/');
|
||||
|
||||
$this->logger->logRequest('get_app_role_assignments', [
|
||||
'endpoint' => $assignmentsEndpoint,
|
||||
'service_principal_id' => $servicePrincipalId,
|
||||
'tenant' => $context['tenant'],
|
||||
'method' => 'GET',
|
||||
'full_path' => $assignmentsEndpoint,
|
||||
'full_path' => $this->buildFullPath($assignmentsEndpoint),
|
||||
'client_request_id' => $clientRequestId,
|
||||
]);
|
||||
|
||||
@ -549,9 +591,20 @@ public function getServicePrincipalPermissions(array $options = []): GraphRespon
|
||||
$permissions = [];
|
||||
|
||||
// Get Microsoft Graph service principal to map role IDs to permission names
|
||||
$graphSpEndpoint = "servicePrincipals?\$filter=appId eq '00000003-0000-0000-c000-000000000000'";
|
||||
$graphSpResponse = $this->send('GET', $graphSpEndpoint, [], $context);
|
||||
$graphSps = $graphSpResponse->json('value', []);
|
||||
$graphSpEndpoint = $this->contracts->probePath(
|
||||
'service_principal_by_app_id',
|
||||
['{appId}' => '00000003-0000-0000-c000-000000000000'],
|
||||
);
|
||||
|
||||
$graphSpResponse = null;
|
||||
|
||||
if (is_string($graphSpEndpoint) && $graphSpEndpoint !== '') {
|
||||
$graphSpResponse = $this->send('GET', ltrim($graphSpEndpoint, '/'), [], $context);
|
||||
}
|
||||
|
||||
$graphSps = $graphSpResponse instanceof Response
|
||||
? $graphSpResponse->json('value', [])
|
||||
: [];
|
||||
$appRoles = $graphSps[0]['appRoles'] ?? [];
|
||||
|
||||
// Map role IDs to permission names
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Notifications\OperationRunCompleted as OperationRunCompletedNotification;
|
||||
use App\Notifications\OperationRunQueued as OperationRunQueuedNotification;
|
||||
use App\Services\Operations\BulkIdempotencyFingerprint;
|
||||
@ -60,12 +61,19 @@ public function ensureRun(
|
||||
array $inputs,
|
||||
?User $initiator = null
|
||||
): OperationRun {
|
||||
$workspaceId = (int) ($tenant->workspace_id ?? 0);
|
||||
|
||||
if ($workspaceId <= 0) {
|
||||
throw new InvalidArgumentException('Tenant must belong to a workspace to start an operation run.');
|
||||
}
|
||||
|
||||
$hash = $this->calculateHash($tenant->id, $type, $inputs);
|
||||
|
||||
// Idempotency Check (Fast Path)
|
||||
// We check specific status to match the partial unique index
|
||||
$existing = OperationRun::query()
|
||||
->where('tenant_id', $tenant->id)
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('run_identity_hash', $hash)
|
||||
->whereIn('status', OperationRunStatus::values())
|
||||
->where('status', '!=', OperationRunStatus::Completed->value)
|
||||
@ -78,6 +86,7 @@ public function ensureRun(
|
||||
// Create new run (race-safe via partial unique index)
|
||||
try {
|
||||
return OperationRun::create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'tenant_id' => $tenant->id,
|
||||
'user_id' => $initiator?->id,
|
||||
'initiator_name' => $initiator?->name ?? 'System',
|
||||
@ -97,6 +106,7 @@ public function ensureRun(
|
||||
|
||||
$existing = OperationRun::query()
|
||||
->where('tenant_id', $tenant->id)
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('run_identity_hash', $hash)
|
||||
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
||||
->first();
|
||||
@ -116,12 +126,19 @@ public function ensureRunWithIdentity(
|
||||
array $context,
|
||||
?User $initiator = null
|
||||
): OperationRun {
|
||||
$workspaceId = (int) ($tenant->workspace_id ?? 0);
|
||||
|
||||
if ($workspaceId <= 0) {
|
||||
throw new InvalidArgumentException('Tenant must belong to a workspace to start an operation run.');
|
||||
}
|
||||
|
||||
$hash = $this->calculateHash($tenant->id, $type, $identityInputs);
|
||||
|
||||
// Idempotency Check (Fast Path)
|
||||
// We check specific status to match the partial unique index
|
||||
$existing = OperationRun::query()
|
||||
->where('tenant_id', $tenant->id)
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('run_identity_hash', $hash)
|
||||
->whereIn('status', OperationRunStatus::values())
|
||||
->where('status', '!=', OperationRunStatus::Completed->value)
|
||||
@ -134,6 +151,7 @@ public function ensureRunWithIdentity(
|
||||
// Create new run (race-safe via partial unique index)
|
||||
try {
|
||||
return OperationRun::create([
|
||||
'workspace_id' => $workspaceId,
|
||||
'tenant_id' => $tenant->id,
|
||||
'user_id' => $initiator?->id,
|
||||
'initiator_name' => $initiator?->name ?? 'System',
|
||||
@ -153,6 +171,7 @@ public function ensureRunWithIdentity(
|
||||
|
||||
$existing = OperationRun::query()
|
||||
->where('tenant_id', $tenant->id)
|
||||
->where('workspace_id', $workspaceId)
|
||||
->where('run_identity_hash', $hash)
|
||||
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
||||
->first();
|
||||
@ -227,6 +246,59 @@ public function enqueueBulkOperation(
|
||||
return $run;
|
||||
}
|
||||
|
||||
public function ensureWorkspaceRunWithIdentity(
|
||||
Workspace $workspace,
|
||||
string $type,
|
||||
array $identityInputs,
|
||||
array $context,
|
||||
?User $initiator = null,
|
||||
): OperationRun {
|
||||
$hash = $this->calculateWorkspaceHash((int) $workspace->getKey(), $type, $identityInputs);
|
||||
|
||||
$existing = OperationRun::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->whereNull('tenant_id')
|
||||
->where('run_identity_hash', $hash)
|
||||
->whereIn('status', OperationRunStatus::values())
|
||||
->where('status', '!=', OperationRunStatus::Completed->value)
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
try {
|
||||
return OperationRun::create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => null,
|
||||
'user_id' => $initiator?->id,
|
||||
'initiator_name' => $initiator?->name ?? 'System',
|
||||
'type' => $type,
|
||||
'status' => OperationRunStatus::Queued->value,
|
||||
'outcome' => OperationRunOutcome::Pending->value,
|
||||
'run_identity_hash' => $hash,
|
||||
'context' => $context,
|
||||
]);
|
||||
} catch (QueryException $e) {
|
||||
if (! in_array(($e->errorInfo[0] ?? null), ['23505', '23000'], true)) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
$existing = OperationRun::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->whereNull('tenant_id')
|
||||
->where('run_identity_hash', $hash)
|
||||
->whereIn('status', [OperationRunStatus::Queued->value, OperationRunStatus::Running->value])
|
||||
->first();
|
||||
|
||||
if ($existing) {
|
||||
return $existing;
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function updateRun(
|
||||
OperationRun $run,
|
||||
string $status,
|
||||
@ -518,6 +590,15 @@ protected function calculateHash(int $tenantId, string $type, array $inputs): st
|
||||
return hash('sha256', $tenantId.'|'.$type.'|'.$json);
|
||||
}
|
||||
|
||||
protected function calculateWorkspaceHash(int $workspaceId, string $type, array $inputs): string
|
||||
{
|
||||
$normalizedInputs = $this->normalizeInputs($inputs);
|
||||
|
||||
$json = json_encode($normalizedInputs, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
return hash('sha256', 'workspace|'.$workspaceId.'|'.$type.'|'.$json);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize inputs for stable identity hashing.
|
||||
*
|
||||
|
||||
@ -27,6 +27,6 @@ enum AuditActionId: string
|
||||
case ManagedTenantOnboardingStart = 'managed_tenant_onboarding.start';
|
||||
case ManagedTenantOnboardingResume = 'managed_tenant_onboarding.resume';
|
||||
case ManagedTenantOnboardingVerificationStart = 'managed_tenant_onboarding.verification_start';
|
||||
|
||||
case ManagedTenantOnboardingActivation = 'managed_tenant_onboarding.activation';
|
||||
case VerificationCompleted = 'verification.completed';
|
||||
}
|
||||
|
||||
@ -30,6 +30,22 @@ class Capabilities
|
||||
// Managed tenant onboarding
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD = 'workspace_managed_tenant.onboard';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY = 'workspace_managed_tenant.onboard.identify';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW = 'workspace_managed_tenant.onboard.connection.view';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE = 'workspace_managed_tenant.onboard.connection.manage';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START = 'workspace_managed_tenant.onboard.verification.start';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC = 'workspace_managed_tenant.onboard.bootstrap.inventory_sync';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC = 'workspace_managed_tenant.onboard.bootstrap.policy_sync';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP = 'workspace_managed_tenant.onboard.bootstrap.backup_bootstrap';
|
||||
|
||||
public const WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE = 'workspace_managed_tenant.onboard.activate';
|
||||
|
||||
// Tenants
|
||||
public const TENANT_VIEW = 'tenant.view';
|
||||
|
||||
|
||||
@ -36,6 +36,7 @@ final class BadgeCatalog
|
||||
BadgeDomain::RestoreResultStatus->value => Domains\RestoreResultStatusBadge::class,
|
||||
BadgeDomain::ProviderConnectionStatus->value => Domains\ProviderConnectionStatusBadge::class,
|
||||
BadgeDomain::ProviderConnectionHealth->value => Domains\ProviderConnectionHealthBadge::class,
|
||||
BadgeDomain::ManagedTenantOnboardingVerificationStatus->value => Domains\ManagedTenantOnboardingVerificationStatusBadge::class,
|
||||
BadgeDomain::VerificationCheckStatus->value => Domains\VerificationCheckStatusBadge::class,
|
||||
BadgeDomain::VerificationCheckSeverity->value => Domains\VerificationCheckSeverityBadge::class,
|
||||
BadgeDomain::VerificationReportOverall->value => Domains\VerificationReportOverallBadge::class,
|
||||
|
||||
@ -28,6 +28,7 @@ enum BadgeDomain: string
|
||||
case RestoreResultStatus = 'restore_result_status';
|
||||
case ProviderConnectionStatus = 'provider_connection.status';
|
||||
case ProviderConnectionHealth = 'provider_connection.health';
|
||||
case ManagedTenantOnboardingVerificationStatus = 'managed_tenant_onboarding.verification_status';
|
||||
case VerificationCheckStatus = 'verification_check_status';
|
||||
case VerificationCheckSeverity = 'verification_check_severity';
|
||||
case VerificationReportOverall = 'verification_report_overall';
|
||||
|
||||
@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Badges\Domains;
|
||||
|
||||
use App\Support\Badges\BadgeCatalog;
|
||||
use App\Support\Badges\BadgeMapper;
|
||||
use App\Support\Badges\BadgeSpec;
|
||||
|
||||
final class ManagedTenantOnboardingVerificationStatusBadge implements BadgeMapper
|
||||
{
|
||||
public function spec(mixed $value): BadgeSpec
|
||||
{
|
||||
$state = BadgeCatalog::normalizeState($value);
|
||||
|
||||
return match ($state) {
|
||||
'not_started' => new BadgeSpec('Not started', 'gray', 'heroicon-m-minus-circle'),
|
||||
'in_progress' => new BadgeSpec('In progress', 'info', 'heroicon-m-arrow-path'),
|
||||
'needs_attention' => new BadgeSpec('Needs attention', 'warning', 'heroicon-m-exclamation-triangle'),
|
||||
'blocked' => new BadgeSpec('Blocked', 'danger', 'heroicon-m-x-circle'),
|
||||
'ready' => new BadgeSpec('Ready', 'success', 'heroicon-m-check-circle'),
|
||||
default => BadgeSpec::unknown(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -27,6 +27,23 @@ public function handle(Request $request, Closure $next): Response
|
||||
|
||||
$path = '/'.ltrim($request->path(), '/');
|
||||
|
||||
if ($path === '/livewire/update') {
|
||||
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
|
||||
$refererPath = '/'.ltrim((string) $refererPath, '/');
|
||||
|
||||
if (preg_match('#^/admin/operations/[^/]+$#', $refererPath) === 1) {
|
||||
$this->configureNavigationForRequest($panel);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
||||
if (preg_match('#^/admin/operations/[^/]+$#', $path) === 1) {
|
||||
$this->configureNavigationForRequest($panel);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
if ($request->route()?->hasParameter('tenant')) {
|
||||
$user = $request->user();
|
||||
|
||||
|
||||
@ -21,6 +21,13 @@ public static function index(Tenant $tenant): string
|
||||
return OperationRunResource::getUrl('index', tenant: $tenant);
|
||||
}
|
||||
|
||||
public static function tenantlessView(OperationRun|int $run): string
|
||||
{
|
||||
$runId = $run instanceof OperationRun ? (int) $run->getKey() : (int) $run;
|
||||
|
||||
return route('admin.operations.view', ['run' => $runId]);
|
||||
}
|
||||
|
||||
public static function view(OperationRun|int $run, Tenant $tenant): string
|
||||
{
|
||||
return OperationRunResource::getUrl('view', ['record' => $run], tenant: $tenant);
|
||||
|
||||
@ -11,6 +11,17 @@
|
||||
| and drift checks.
|
||||
|
|
||||
*/
|
||||
'probes' => [
|
||||
'organization' => [
|
||||
'path' => 'organization',
|
||||
],
|
||||
'service_principal_by_app_id' => [
|
||||
'path' => "servicePrincipals?\$filter=appId eq '{appId}'",
|
||||
],
|
||||
'service_principal_app_role_assignments' => [
|
||||
'path' => 'servicePrincipals/{servicePrincipalId}/appRoleAssignments',
|
||||
],
|
||||
],
|
||||
'types' => [
|
||||
'directoryGroups' => [
|
||||
'resource' => 'groups',
|
||||
|
||||
@ -5,6 +5,7 @@
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\OperationRunType;
|
||||
@ -20,7 +21,29 @@ class OperationRunFactory extends Factory
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'tenant_id' => Tenant::factory(),
|
||||
'tenant_id' => Tenant::factory()->for(Workspace::factory()),
|
||||
'workspace_id' => function (array $attributes): int {
|
||||
$tenantId = $attributes['tenant_id'] ?? null;
|
||||
|
||||
if (! is_numeric($tenantId)) {
|
||||
return (int) Workspace::factory()->create()->getKey();
|
||||
}
|
||||
|
||||
$tenant = Tenant::query()->whereKey((int) $tenantId)->first();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return (int) Workspace::factory()->create()->getKey();
|
||||
}
|
||||
|
||||
if ($tenant->workspace_id === null) {
|
||||
$workspaceId = (int) Workspace::factory()->create()->getKey();
|
||||
$tenant->forceFill(['workspace_id' => $workspaceId])->save();
|
||||
|
||||
return $workspaceId;
|
||||
}
|
||||
|
||||
return (int) $tenant->workspace_id;
|
||||
},
|
||||
'user_id' => User::factory(),
|
||||
'initiator_name' => fake()->name(),
|
||||
'type' => fake()->randomElement(OperationRunType::values()),
|
||||
|
||||
@ -4,6 +4,7 @@
|
||||
|
||||
use App\Models\ProviderConnection;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
@ -16,7 +17,29 @@ class ProviderConnectionFactory extends Factory
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'tenant_id' => Tenant::factory(),
|
||||
'tenant_id' => Tenant::factory()->for(Workspace::factory()),
|
||||
'workspace_id' => function (array $attributes): int {
|
||||
$tenantId = $attributes['tenant_id'] ?? null;
|
||||
|
||||
if (! is_numeric($tenantId)) {
|
||||
return (int) Workspace::factory()->create()->getKey();
|
||||
}
|
||||
|
||||
$tenant = Tenant::query()->whereKey((int) $tenantId)->first();
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return (int) Workspace::factory()->create()->getKey();
|
||||
}
|
||||
|
||||
if ($tenant->workspace_id === null) {
|
||||
$workspaceId = (int) Workspace::factory()->create()->getKey();
|
||||
$tenant->forceFill(['workspace_id' => $workspaceId])->save();
|
||||
|
||||
return $workspaceId;
|
||||
}
|
||||
|
||||
return (int) $tenant->workspace_id;
|
||||
},
|
||||
'provider' => 'microsoft',
|
||||
'entra_tenant_id' => fake()->uuid(),
|
||||
'display_name' => fake()->company(),
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Models\Workspace;
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
|
||||
/**
|
||||
@ -9,6 +11,21 @@
|
||||
*/
|
||||
class TenantFactory extends Factory
|
||||
{
|
||||
public function configure(): static
|
||||
{
|
||||
return $this->afterCreating(function (Tenant $tenant): void {
|
||||
if ($tenant->workspace_id !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$workspace = Workspace::factory()->create();
|
||||
|
||||
$tenant->forceFill([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
])->save();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
|
||||
@ -0,0 +1,246 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable('managed_tenant_onboarding_sessions')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$driver = Schema::getConnection()->getDriverName();
|
||||
|
||||
if ($driver === 'sqlite') {
|
||||
Schema::disableForeignKeyConstraints();
|
||||
|
||||
Schema::rename('managed_tenant_onboarding_sessions', 'managed_tenant_onboarding_sessions_old');
|
||||
|
||||
foreach ([
|
||||
'managed_tenant_onboarding_sessions_workspace_id_tenant_id_unique',
|
||||
'managed_tenant_onboarding_sessions_tenant_id_index',
|
||||
] as $indexName) {
|
||||
DB::statement("DROP INDEX IF EXISTS {$indexName}");
|
||||
}
|
||||
|
||||
Schema::create('managed_tenant_onboarding_sessions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('workspace_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
|
||||
$table->string('entra_tenant_id');
|
||||
$table->string('current_step')->nullable();
|
||||
$table->json('state')->nullable();
|
||||
$table->foreignId('started_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->foreignId('updated_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('completed_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index('tenant_id');
|
||||
$table->index('entra_tenant_id');
|
||||
});
|
||||
|
||||
DB::table('managed_tenant_onboarding_sessions_old')
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows): void {
|
||||
foreach ($rows as $row) {
|
||||
$state = is_string($row->state) ? json_decode($row->state, true) : null;
|
||||
$state = is_array($state) ? $state : [];
|
||||
|
||||
$entraTenantId = $row->entra_tenant_id ?? null;
|
||||
|
||||
if (! is_string($entraTenantId) || trim($entraTenantId) === '') {
|
||||
$entraTenantId = $state['entra_tenant_id'] ?? $state['tenant_id'] ?? null;
|
||||
}
|
||||
|
||||
if (! is_string($entraTenantId) || trim($entraTenantId) === '') {
|
||||
$entraTenantId = DB::table('tenants')
|
||||
->where('id', $row->tenant_id)
|
||||
->value('tenant_id');
|
||||
}
|
||||
|
||||
$entraTenantId = is_string($entraTenantId) ? trim($entraTenantId) : '';
|
||||
|
||||
if ($entraTenantId === '') {
|
||||
$entraTenantId = sprintf('unknown-%d', (int) $row->id);
|
||||
}
|
||||
|
||||
DB::table('managed_tenant_onboarding_sessions')->insert([
|
||||
'id' => $row->id,
|
||||
'workspace_id' => $row->workspace_id,
|
||||
'tenant_id' => $row->tenant_id,
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'current_step' => $row->current_step,
|
||||
'state' => $row->state,
|
||||
'started_by_user_id' => $row->started_by_user_id,
|
||||
'updated_by_user_id' => $row->updated_by_user_id,
|
||||
'completed_at' => $row->completed_at,
|
||||
'created_at' => $row->created_at,
|
||||
'updated_at' => $row->updated_at,
|
||||
]);
|
||||
}
|
||||
}, 'id');
|
||||
|
||||
Schema::drop('managed_tenant_onboarding_sessions_old');
|
||||
|
||||
DB::statement('CREATE UNIQUE INDEX managed_tenant_onboarding_sessions_active_workspace_entra_unique ON managed_tenant_onboarding_sessions (workspace_id, entra_tenant_id) WHERE completed_at IS NULL');
|
||||
DB::statement('CREATE UNIQUE INDEX managed_tenant_onboarding_sessions_active_tenant_unique ON managed_tenant_onboarding_sessions (tenant_id) WHERE completed_at IS NULL AND tenant_id IS NOT NULL');
|
||||
|
||||
Schema::enableForeignKeyConstraints();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! Schema::hasColumn('managed_tenant_onboarding_sessions', 'entra_tenant_id')) {
|
||||
Schema::table('managed_tenant_onboarding_sessions', function (Blueprint $table) {
|
||||
$table->string('entra_tenant_id')->nullable()->after('tenant_id');
|
||||
});
|
||||
}
|
||||
|
||||
$this->backfillEntraTenantId($driver);
|
||||
|
||||
if ($driver === 'pgsql') {
|
||||
DB::statement('ALTER TABLE managed_tenant_onboarding_sessions ALTER COLUMN tenant_id DROP NOT NULL');
|
||||
DB::statement('ALTER TABLE managed_tenant_onboarding_sessions ALTER COLUMN entra_tenant_id SET NOT NULL');
|
||||
}
|
||||
|
||||
Schema::table('managed_tenant_onboarding_sessions', function (Blueprint $table) {
|
||||
$table->dropUnique(['workspace_id', 'tenant_id']);
|
||||
$table->index('entra_tenant_id');
|
||||
});
|
||||
|
||||
DB::statement('CREATE UNIQUE INDEX IF NOT EXISTS managed_tenant_onboarding_sessions_active_workspace_entra_unique ON managed_tenant_onboarding_sessions (workspace_id, entra_tenant_id) WHERE completed_at IS NULL');
|
||||
DB::statement('CREATE UNIQUE INDEX IF NOT EXISTS managed_tenant_onboarding_sessions_active_tenant_unique ON managed_tenant_onboarding_sessions (tenant_id) WHERE completed_at IS NULL AND tenant_id IS NOT NULL');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('managed_tenant_onboarding_sessions')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$driver = Schema::getConnection()->getDriverName();
|
||||
|
||||
if ($driver === 'sqlite') {
|
||||
Schema::disableForeignKeyConstraints();
|
||||
|
||||
Schema::rename('managed_tenant_onboarding_sessions', 'managed_tenant_onboarding_sessions_new');
|
||||
|
||||
foreach ([
|
||||
'managed_tenant_onboarding_sessions_active_workspace_entra_unique',
|
||||
'managed_tenant_onboarding_sessions_active_tenant_unique',
|
||||
'managed_tenant_onboarding_sessions_tenant_id_index',
|
||||
'managed_tenant_onboarding_sessions_entra_tenant_id_index',
|
||||
] as $indexName) {
|
||||
DB::statement("DROP INDEX IF EXISTS {$indexName}");
|
||||
}
|
||||
|
||||
Schema::create('managed_tenant_onboarding_sessions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('workspace_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
|
||||
$table->string('current_step')->nullable();
|
||||
$table->json('state')->nullable();
|
||||
$table->foreignId('started_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->foreignId('updated_by_user_id')->nullable()->constrained('users')->nullOnDelete();
|
||||
$table->timestamp('completed_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['workspace_id', 'tenant_id']);
|
||||
$table->index(['tenant_id']);
|
||||
});
|
||||
|
||||
DB::table('managed_tenant_onboarding_sessions_new')
|
||||
->whereNotNull('tenant_id')
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows): void {
|
||||
foreach ($rows as $row) {
|
||||
DB::table('managed_tenant_onboarding_sessions')->insert([
|
||||
'id' => $row->id,
|
||||
'workspace_id' => $row->workspace_id,
|
||||
'tenant_id' => $row->tenant_id,
|
||||
'current_step' => $row->current_step,
|
||||
'state' => $row->state,
|
||||
'started_by_user_id' => $row->started_by_user_id,
|
||||
'updated_by_user_id' => $row->updated_by_user_id,
|
||||
'completed_at' => $row->completed_at,
|
||||
'created_at' => $row->created_at,
|
||||
'updated_at' => $row->updated_at,
|
||||
]);
|
||||
}
|
||||
}, 'id');
|
||||
|
||||
Schema::drop('managed_tenant_onboarding_sessions_new');
|
||||
Schema::enableForeignKeyConstraints();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ([
|
||||
'managed_tenant_onboarding_sessions_active_workspace_entra_unique',
|
||||
'managed_tenant_onboarding_sessions_active_tenant_unique',
|
||||
] as $indexName) {
|
||||
DB::statement("DROP INDEX IF EXISTS {$indexName}");
|
||||
}
|
||||
|
||||
if (Schema::hasColumn('managed_tenant_onboarding_sessions', 'entra_tenant_id')) {
|
||||
Schema::table('managed_tenant_onboarding_sessions', function (Blueprint $table) {
|
||||
$table->dropIndex(['entra_tenant_id']);
|
||||
$table->dropColumn('entra_tenant_id');
|
||||
$table->unique(['workspace_id', 'tenant_id']);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private function backfillEntraTenantId(string $driver): void
|
||||
{
|
||||
if ($driver === 'pgsql') {
|
||||
DB::statement(<<<'SQL'
|
||||
UPDATE managed_tenant_onboarding_sessions
|
||||
SET entra_tenant_id = COALESCE(managed_tenant_onboarding_sessions.entra_tenant_id, tenants.tenant_id, managed_tenant_onboarding_sessions.state->>'tenant_id')
|
||||
FROM tenants
|
||||
WHERE managed_tenant_onboarding_sessions.entra_tenant_id IS NULL
|
||||
AND managed_tenant_onboarding_sessions.tenant_id = tenants.id
|
||||
SQL);
|
||||
|
||||
DB::statement(<<<'SQL'
|
||||
UPDATE managed_tenant_onboarding_sessions
|
||||
SET entra_tenant_id = state->>'tenant_id'
|
||||
WHERE entra_tenant_id IS NULL
|
||||
SQL);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('managed_tenant_onboarding_sessions')
|
||||
->whereNull('entra_tenant_id')
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows): void {
|
||||
foreach ($rows as $row) {
|
||||
$state = is_string($row->state) ? json_decode($row->state, true) : null;
|
||||
$state = is_array($state) ? $state : [];
|
||||
|
||||
$entraTenantId = $state['entra_tenant_id'] ?? $state['tenant_id'] ?? null;
|
||||
|
||||
if (! is_string($entraTenantId) || trim($entraTenantId) === '') {
|
||||
$entraTenantId = DB::table('tenants')
|
||||
->where('id', $row->tenant_id)
|
||||
->value('tenant_id');
|
||||
}
|
||||
|
||||
$entraTenantId = is_string($entraTenantId) ? trim($entraTenantId) : '';
|
||||
|
||||
if ($entraTenantId === '') {
|
||||
$entraTenantId = sprintf('unknown-%d', (int) $row->id);
|
||||
}
|
||||
|
||||
DB::table('managed_tenant_onboarding_sessions')
|
||||
->where('id', $row->id)
|
||||
->update(['entra_tenant_id' => $entraTenantId]);
|
||||
}
|
||||
}, 'id');
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable('provider_connections')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$driver = Schema::getConnection()->getDriverName();
|
||||
|
||||
if ($driver === 'sqlite') {
|
||||
if (! Schema::hasColumn('provider_connections', 'workspace_id')) {
|
||||
Schema::table('provider_connections', function (Blueprint $table): void {
|
||||
$table->unsignedBigInteger('workspace_id')->nullable()->after('id');
|
||||
});
|
||||
}
|
||||
|
||||
DB::statement(<<<'SQL'
|
||||
UPDATE provider_connections
|
||||
SET workspace_id = (
|
||||
SELECT tenants.workspace_id
|
||||
FROM tenants
|
||||
WHERE tenants.id = provider_connections.tenant_id
|
||||
)
|
||||
WHERE workspace_id IS NULL
|
||||
SQL);
|
||||
|
||||
Schema::table('provider_connections', function (Blueprint $table): void {
|
||||
$table->index(['workspace_id', 'provider', 'status']);
|
||||
$table->index(['workspace_id', 'provider', 'health_status']);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! Schema::hasColumn('provider_connections', 'workspace_id')) {
|
||||
Schema::table('provider_connections', function (Blueprint $table) use ($driver): void {
|
||||
$column = $table->foreignId('workspace_id')->nullable();
|
||||
|
||||
if ($driver !== 'sqlite') {
|
||||
$column->after('id')->constrained('workspaces')->cascadeOnDelete();
|
||||
}
|
||||
|
||||
$table->index('workspace_id');
|
||||
});
|
||||
}
|
||||
|
||||
$this->backfillWorkspaceId($driver);
|
||||
|
||||
if ($driver === 'pgsql') {
|
||||
DB::statement('ALTER TABLE provider_connections ALTER COLUMN workspace_id SET NOT NULL');
|
||||
}
|
||||
|
||||
if ($driver === 'mysql') {
|
||||
DB::statement('ALTER TABLE provider_connections MODIFY workspace_id BIGINT UNSIGNED NOT NULL');
|
||||
}
|
||||
|
||||
Schema::table('provider_connections', function (Blueprint $table): void {
|
||||
$table->index(['workspace_id', 'provider', 'status']);
|
||||
$table->index(['workspace_id', 'provider', 'health_status']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('provider_connections')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$driver = Schema::getConnection()->getDriverName();
|
||||
|
||||
if ($driver === 'sqlite') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! Schema::hasColumn('provider_connections', 'workspace_id')) {
|
||||
return;
|
||||
}
|
||||
|
||||
Schema::table('provider_connections', function (Blueprint $table): void {
|
||||
$table->dropIndex(['workspace_id']);
|
||||
$table->dropIndex(['workspace_id', 'provider', 'status']);
|
||||
$table->dropIndex(['workspace_id', 'provider', 'health_status']);
|
||||
$table->dropConstrainedForeignId('workspace_id');
|
||||
});
|
||||
}
|
||||
|
||||
private function backfillWorkspaceId(string $driver): void
|
||||
{
|
||||
if ($driver === 'pgsql') {
|
||||
DB::statement(<<<'SQL'
|
||||
UPDATE provider_connections
|
||||
SET workspace_id = tenants.workspace_id
|
||||
FROM tenants
|
||||
WHERE provider_connections.workspace_id IS NULL
|
||||
AND provider_connections.tenant_id = tenants.id
|
||||
SQL);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('provider_connections')
|
||||
->whereNull('workspace_id')
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows): void {
|
||||
foreach ($rows as $row) {
|
||||
$workspaceId = DB::table('tenants')
|
||||
->where('id', $row->tenant_id)
|
||||
->value('workspace_id');
|
||||
|
||||
if ($workspaceId === null) {
|
||||
$workspaceId = DB::table('tenant_memberships')
|
||||
->join('workspace_memberships', 'workspace_memberships.user_id', '=', 'tenant_memberships.user_id')
|
||||
->where('tenant_memberships.tenant_id', (int) $row->tenant_id)
|
||||
->orderByRaw("CASE tenant_memberships.role WHEN 'owner' THEN 0 WHEN 'manager' THEN 1 WHEN 'operator' THEN 2 ELSE 3 END")
|
||||
->value('workspace_memberships.workspace_id');
|
||||
}
|
||||
|
||||
if ($workspaceId !== null) {
|
||||
DB::table('provider_connections')
|
||||
->where('id', $row->id)
|
||||
->update(['workspace_id' => (int) $workspaceId]);
|
||||
}
|
||||
}
|
||||
}, 'id');
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,267 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable('operation_runs')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$driver = Schema::getConnection()->getDriverName();
|
||||
|
||||
if ($driver === 'sqlite') {
|
||||
Schema::disableForeignKeyConstraints();
|
||||
|
||||
Schema::rename('operation_runs', 'operation_runs_old');
|
||||
|
||||
foreach ([
|
||||
'operation_runs_active_unique',
|
||||
'operation_runs_tenant_id_type_created_at_index',
|
||||
'operation_runs_tenant_id_created_at_index',
|
||||
] as $indexName) {
|
||||
DB::statement("DROP INDEX IF EXISTS {$indexName}");
|
||||
}
|
||||
|
||||
Schema::create('operation_runs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('workspace_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->string('initiator_name');
|
||||
$table->string('type');
|
||||
$table->string('status');
|
||||
$table->string('outcome')->default('pending');
|
||||
$table->string('run_identity_hash');
|
||||
$table->json('summary_counts')->default('{}');
|
||||
$table->json('failure_summary')->default('[]');
|
||||
$table->json('context')->default('{}');
|
||||
$table->timestamp('started_at')->nullable();
|
||||
$table->timestamp('completed_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['workspace_id', 'type', 'created_at']);
|
||||
$table->index(['workspace_id', 'created_at']);
|
||||
$table->index(['tenant_id', 'type', 'created_at']);
|
||||
$table->index(['tenant_id', 'created_at']);
|
||||
});
|
||||
|
||||
DB::table('operation_runs_old')
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows): void {
|
||||
foreach ($rows as $row) {
|
||||
$workspaceId = DB::table('tenants')
|
||||
->where('id', (int) $row->tenant_id)
|
||||
->value('workspace_id');
|
||||
|
||||
DB::table('operation_runs')->insert([
|
||||
'id' => (int) $row->id,
|
||||
'workspace_id' => (int) $workspaceId,
|
||||
'tenant_id' => $row->tenant_id,
|
||||
'user_id' => $row->user_id,
|
||||
'initiator_name' => $row->initiator_name,
|
||||
'type' => $row->type,
|
||||
'status' => $row->status,
|
||||
'outcome' => $row->outcome,
|
||||
'run_identity_hash' => $row->run_identity_hash,
|
||||
'summary_counts' => $row->summary_counts,
|
||||
'failure_summary' => $row->failure_summary,
|
||||
'context' => $row->context,
|
||||
'started_at' => $row->started_at,
|
||||
'completed_at' => $row->completed_at,
|
||||
'created_at' => $row->created_at,
|
||||
'updated_at' => $row->updated_at,
|
||||
]);
|
||||
}
|
||||
}, 'id');
|
||||
|
||||
Schema::drop('operation_runs_old');
|
||||
|
||||
DB::statement("CREATE UNIQUE INDEX operation_runs_active_unique_tenant ON operation_runs (tenant_id, run_identity_hash) WHERE tenant_id IS NOT NULL AND status IN ('queued', 'running')");
|
||||
DB::statement("CREATE UNIQUE INDEX operation_runs_active_unique_workspace ON operation_runs (workspace_id, run_identity_hash) WHERE tenant_id IS NULL AND status IN ('queued', 'running')");
|
||||
|
||||
Schema::enableForeignKeyConstraints();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! Schema::hasColumn('operation_runs', 'workspace_id')) {
|
||||
Schema::table('operation_runs', function (Blueprint $table) use ($driver): void {
|
||||
$column = $table->foreignId('workspace_id')->nullable();
|
||||
|
||||
if ($driver !== 'sqlite') {
|
||||
$column->after('id')->constrained()->cascadeOnDelete();
|
||||
}
|
||||
|
||||
$table->index(['workspace_id', 'type', 'created_at']);
|
||||
$table->index(['workspace_id', 'created_at']);
|
||||
});
|
||||
}
|
||||
|
||||
$this->backfillWorkspaceId($driver);
|
||||
|
||||
if ($driver === 'pgsql') {
|
||||
DB::statement('ALTER TABLE operation_runs ALTER COLUMN tenant_id DROP NOT NULL');
|
||||
DB::statement('ALTER TABLE operation_runs ALTER COLUMN workspace_id SET NOT NULL');
|
||||
}
|
||||
|
||||
if ($driver === 'mysql') {
|
||||
DB::statement('ALTER TABLE operation_runs MODIFY tenant_id BIGINT UNSIGNED NULL');
|
||||
DB::statement('ALTER TABLE operation_runs MODIFY workspace_id BIGINT UNSIGNED NOT NULL');
|
||||
}
|
||||
|
||||
DB::statement('DROP INDEX IF EXISTS operation_runs_active_unique');
|
||||
|
||||
DB::statement("CREATE UNIQUE INDEX operation_runs_active_unique_tenant ON operation_runs (tenant_id, run_identity_hash) WHERE tenant_id IS NOT NULL AND status IN ('queued', 'running')");
|
||||
DB::statement("CREATE UNIQUE INDEX operation_runs_active_unique_workspace ON operation_runs (workspace_id, run_identity_hash) WHERE tenant_id IS NULL AND status IN ('queued', 'running')");
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('operation_runs')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$driver = Schema::getConnection()->getDriverName();
|
||||
|
||||
if ($driver === 'sqlite') {
|
||||
Schema::disableForeignKeyConstraints();
|
||||
|
||||
Schema::rename('operation_runs', 'operation_runs_with_workspace');
|
||||
|
||||
foreach ([
|
||||
'operation_runs_active_unique_tenant',
|
||||
'operation_runs_active_unique_workspace',
|
||||
'operation_runs_workspace_id_type_created_at_index',
|
||||
'operation_runs_workspace_id_created_at_index',
|
||||
'operation_runs_tenant_id_type_created_at_index',
|
||||
'operation_runs_tenant_id_created_at_index',
|
||||
] as $indexName) {
|
||||
DB::statement("DROP INDEX IF EXISTS {$indexName}");
|
||||
}
|
||||
|
||||
Schema::create('operation_runs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
|
||||
$table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
|
||||
$table->string('initiator_name');
|
||||
$table->string('type');
|
||||
$table->string('status');
|
||||
$table->string('outcome')->default('pending');
|
||||
$table->string('run_identity_hash');
|
||||
$table->json('summary_counts')->default('{}');
|
||||
$table->json('failure_summary')->default('[]');
|
||||
$table->json('context')->default('{}');
|
||||
$table->timestamp('started_at')->nullable();
|
||||
$table->timestamp('completed_at')->nullable();
|
||||
$table->timestamps();
|
||||
|
||||
$table->index(['tenant_id', 'type', 'created_at']);
|
||||
$table->index(['tenant_id', 'created_at']);
|
||||
});
|
||||
|
||||
DB::table('operation_runs_with_workspace')
|
||||
->whereNotNull('tenant_id')
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows): void {
|
||||
foreach ($rows as $row) {
|
||||
DB::table('operation_runs')->insert([
|
||||
'id' => (int) $row->id,
|
||||
'tenant_id' => (int) $row->tenant_id,
|
||||
'user_id' => $row->user_id,
|
||||
'initiator_name' => $row->initiator_name,
|
||||
'type' => $row->type,
|
||||
'status' => $row->status,
|
||||
'outcome' => $row->outcome,
|
||||
'run_identity_hash' => $row->run_identity_hash,
|
||||
'summary_counts' => $row->summary_counts,
|
||||
'failure_summary' => $row->failure_summary,
|
||||
'context' => $row->context,
|
||||
'started_at' => $row->started_at,
|
||||
'completed_at' => $row->completed_at,
|
||||
'created_at' => $row->created_at,
|
||||
'updated_at' => $row->updated_at,
|
||||
]);
|
||||
}
|
||||
}, 'id');
|
||||
|
||||
Schema::drop('operation_runs_with_workspace');
|
||||
|
||||
DB::statement("CREATE UNIQUE INDEX operation_runs_active_unique ON operation_runs (tenant_id, run_identity_hash) WHERE status IN ('queued', 'running')");
|
||||
|
||||
Schema::enableForeignKeyConstraints();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
DB::statement('DROP INDEX IF EXISTS operation_runs_active_unique_tenant');
|
||||
DB::statement('DROP INDEX IF EXISTS operation_runs_active_unique_workspace');
|
||||
DB::statement('DROP INDEX IF EXISTS operation_runs_active_unique');
|
||||
|
||||
DB::statement("CREATE UNIQUE INDEX operation_runs_active_unique ON operation_runs (tenant_id, run_identity_hash) WHERE status IN ('queued', 'running')");
|
||||
|
||||
if ($driver === 'pgsql') {
|
||||
DB::statement('ALTER TABLE operation_runs ALTER COLUMN tenant_id SET NOT NULL');
|
||||
DB::statement('ALTER TABLE operation_runs ALTER COLUMN workspace_id DROP NOT NULL');
|
||||
}
|
||||
|
||||
if ($driver === 'mysql') {
|
||||
DB::statement('ALTER TABLE operation_runs MODIFY tenant_id BIGINT UNSIGNED NOT NULL');
|
||||
DB::statement('ALTER TABLE operation_runs MODIFY workspace_id BIGINT UNSIGNED NULL');
|
||||
}
|
||||
|
||||
Schema::table('operation_runs', function (Blueprint $table): void {
|
||||
$table->dropIndex(['workspace_id', 'type', 'created_at']);
|
||||
$table->dropIndex(['workspace_id', 'created_at']);
|
||||
$table->dropConstrainedForeignId('workspace_id');
|
||||
});
|
||||
}
|
||||
|
||||
private function backfillWorkspaceId(string $driver): void
|
||||
{
|
||||
if ($driver === 'pgsql') {
|
||||
DB::statement(<<<'SQL'
|
||||
UPDATE operation_runs
|
||||
SET workspace_id = tenants.workspace_id
|
||||
FROM tenants
|
||||
WHERE operation_runs.workspace_id IS NULL
|
||||
AND operation_runs.tenant_id = tenants.id
|
||||
SQL);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($driver === 'mysql') {
|
||||
DB::statement(<<<'SQL'
|
||||
UPDATE operation_runs
|
||||
JOIN tenants ON tenants.id = operation_runs.tenant_id
|
||||
SET operation_runs.workspace_id = tenants.workspace_id
|
||||
WHERE operation_runs.workspace_id IS NULL
|
||||
SQL);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('operation_runs')
|
||||
->whereNull('workspace_id')
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows): void {
|
||||
foreach ($rows as $row) {
|
||||
$workspaceId = DB::table('tenants')
|
||||
->where('id', (int) $row->tenant_id)
|
||||
->value('workspace_id');
|
||||
|
||||
if ($workspaceId !== null) {
|
||||
DB::table('operation_runs')
|
||||
->where('id', (int) $row->id)
|
||||
->update(['workspace_id' => (int) $workspaceId]);
|
||||
}
|
||||
}
|
||||
}, 'id');
|
||||
}
|
||||
};
|
||||
@ -0,0 +1,136 @@
|
||||
@php
|
||||
$fieldWrapperView = $getFieldWrapperView();
|
||||
|
||||
$run = $run ?? null;
|
||||
$run = is_array($run) ? $run : null;
|
||||
|
||||
$runUrl = $runUrl ?? null;
|
||||
$runUrl = is_string($runUrl) && $runUrl !== '' ? $runUrl : null;
|
||||
|
||||
$status = $run['status'] ?? null;
|
||||
$status = is_string($status) ? $status : null;
|
||||
|
||||
$outcome = $run['outcome'] ?? null;
|
||||
$outcome = is_string($outcome) ? $outcome : null;
|
||||
|
||||
$targetScope = $run['target_scope'] ?? [];
|
||||
$targetScope = is_array($targetScope) ? $targetScope : [];
|
||||
|
||||
$failures = $run['failures'] ?? [];
|
||||
$failures = is_array($failures) ? $failures : [];
|
||||
|
||||
$completedAt = $run['completed_at'] ?? null;
|
||||
$completedAt = is_string($completedAt) && $completedAt !== '' ? $completedAt : null;
|
||||
|
||||
$completedAtLabel = null;
|
||||
|
||||
if ($completedAt !== null) {
|
||||
try {
|
||||
$completedAtLabel = \Carbon\CarbonImmutable::parse($completedAt)->format('Y-m-d H:i');
|
||||
} catch (\Throwable) {
|
||||
$completedAtLabel = $completedAt;
|
||||
}
|
||||
}
|
||||
@endphp
|
||||
|
||||
<x-dynamic-component :component="$fieldWrapperView" :field="$field">
|
||||
<div class="space-y-4">
|
||||
<x-filament::section
|
||||
heading="Verification report"
|
||||
:description="$completedAtLabel ? ('Completed: ' . $completedAtLabel) : 'Stored details for the latest verification run.'"
|
||||
>
|
||||
@if ($run === null)
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
No verification run has been started yet.
|
||||
</div>
|
||||
@elseif ($status !== 'completed')
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
Report unavailable while the run is in progress. Use “Refresh” to re-check stored status.
|
||||
</div>
|
||||
@elseif ($outcome === 'succeeded')
|
||||
<div class="text-sm text-gray-700 dark:text-gray-200">
|
||||
All verification checks passed.
|
||||
</div>
|
||||
@elseif ($failures === [])
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
Report unavailable. The run completed, but no failure details were recorded.
|
||||
</div>
|
||||
@else
|
||||
<div class="space-y-3">
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
Findings
|
||||
</div>
|
||||
|
||||
<ul class="space-y-2 text-sm text-gray-700 dark:text-gray-200">
|
||||
@foreach ($failures as $failure)
|
||||
@php
|
||||
$reasonCode = is_array($failure) ? ($failure['reason_code'] ?? null) : null;
|
||||
$message = is_array($failure) ? ($failure['message'] ?? null) : null;
|
||||
|
||||
$reasonCode = is_string($reasonCode) && $reasonCode !== '' ? $reasonCode : null;
|
||||
$message = is_string($message) && $message !== '' ? $message : null;
|
||||
@endphp
|
||||
|
||||
@if ($reasonCode !== null || $message !== null)
|
||||
<li class="rounded-lg border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
|
||||
@if ($reasonCode !== null)
|
||||
<div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
|
||||
{{ $reasonCode }}
|
||||
</div>
|
||||
@endif
|
||||
@if ($message !== null)
|
||||
<div class="mt-1 text-sm text-gray-700 dark:text-gray-200">
|
||||
{{ $message }}
|
||||
</div>
|
||||
@endif
|
||||
</li>
|
||||
@endif
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($targetScope !== [])
|
||||
<div class="mt-4">
|
||||
<div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
|
||||
Target scope
|
||||
</div>
|
||||
<div class="mt-2 flex flex-col gap-1 text-sm text-gray-700 dark:text-gray-200">
|
||||
@php
|
||||
$entraTenantId = $targetScope['entra_tenant_id'] ?? null;
|
||||
$entraTenantName = $targetScope['entra_tenant_name'] ?? null;
|
||||
|
||||
$entraTenantId = is_string($entraTenantId) && $entraTenantId !== '' ? $entraTenantId : null;
|
||||
$entraTenantName = is_string($entraTenantName) && $entraTenantName !== '' ? $entraTenantName : null;
|
||||
@endphp
|
||||
|
||||
@if ($entraTenantName !== null)
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Entra tenant:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $entraTenantName }}</span>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($entraTenantId !== null)
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Entra tenant ID:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $entraTenantId }}</span>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($runUrl !== null)
|
||||
<div class="mt-4">
|
||||
<a
|
||||
href="{{ $runUrl }}"
|
||||
class="text-sm font-medium text-primary-600 hover:underline dark:text-primary-400"
|
||||
>
|
||||
Open run details
|
||||
</a>
|
||||
</div>
|
||||
@endif
|
||||
</x-filament::section>
|
||||
</div>
|
||||
</x-dynamic-component>
|
||||
@ -0,0 +1,137 @@
|
||||
<x-filament-panels::page>
|
||||
@php
|
||||
$context = is_array($this->run->context ?? null) ? $this->run->context : [];
|
||||
$targetScope = $context['target_scope'] ?? [];
|
||||
$targetScope = is_array($targetScope) ? $targetScope : [];
|
||||
|
||||
$failures = is_array($this->run->failure_summary ?? null) ? $this->run->failure_summary : [];
|
||||
@endphp
|
||||
|
||||
<div class="space-y-6">
|
||||
<x-filament::section heading="Summary">
|
||||
<div class="grid grid-cols-1 gap-3 text-sm text-gray-700 dark:text-gray-200 md:grid-cols-2">
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Run ID:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (int) $this->run->getKey() }}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Workspace:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) ($this->run->workspace?->name ?? '—') }}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Operation:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->type }}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Initiator:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->initiator_name }}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Status:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->status }}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Outcome:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ (string) $this->run->outcome }}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Started:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $this->run->started_at?->format('Y-m-d H:i') ?? '—' }}</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Completed:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $this->run->completed_at?->format('Y-m-d H:i') ?? '—' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</x-filament::section>
|
||||
|
||||
<x-filament::section heading="Target scope" :collapsed="false">
|
||||
@php
|
||||
$entraTenantId = $targetScope['entra_tenant_id'] ?? null;
|
||||
$entraTenantName = $targetScope['entra_tenant_name'] ?? null;
|
||||
|
||||
$entraTenantId = is_string($entraTenantId) && $entraTenantId !== '' ? $entraTenantId : null;
|
||||
$entraTenantName = is_string($entraTenantName) && $entraTenantName !== '' ? $entraTenantName : null;
|
||||
@endphp
|
||||
|
||||
@if ($entraTenantId === null && $entraTenantName === null)
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
No target scope details were recorded for this run.
|
||||
</div>
|
||||
@else
|
||||
<div class="flex flex-col gap-2 text-sm text-gray-700 dark:text-gray-200">
|
||||
@if ($entraTenantName !== null)
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Entra tenant:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $entraTenantName }}</span>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
@if ($entraTenantId !== null)
|
||||
<div>
|
||||
<span class="text-gray-500 dark:text-gray-400">Entra tenant ID:</span>
|
||||
<span class="font-medium text-gray-900 dark:text-gray-100">{{ $entraTenantId }}</span>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
</x-filament::section>
|
||||
|
||||
<x-filament::section heading="Report">
|
||||
@if ((string) $this->run->status !== 'completed')
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
Report unavailable while the run is in progress. Use “Refresh” to re-check stored status.
|
||||
</div>
|
||||
@elseif ((string) $this->run->outcome === 'succeeded')
|
||||
<div class="text-sm text-gray-700 dark:text-gray-200">
|
||||
No failures were reported.
|
||||
</div>
|
||||
@elseif ($failures === [])
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
Report unavailable. The run completed, but no failure details were recorded.
|
||||
</div>
|
||||
@else
|
||||
<div class="space-y-3">
|
||||
<div class="text-sm font-medium text-gray-900 dark:text-white">
|
||||
Findings
|
||||
</div>
|
||||
|
||||
<ul class="space-y-2 text-sm text-gray-700 dark:text-gray-200">
|
||||
@foreach ($failures as $failure)
|
||||
@php
|
||||
$reasonCode = is_array($failure) ? ($failure['reason_code'] ?? null) : null;
|
||||
$message = is_array($failure) ? ($failure['message'] ?? null) : null;
|
||||
|
||||
$reasonCode = is_string($reasonCode) && $reasonCode !== '' ? $reasonCode : null;
|
||||
$message = is_string($message) && $message !== '' ? $message : null;
|
||||
@endphp
|
||||
|
||||
@if ($reasonCode !== null || $message !== null)
|
||||
<li class="rounded-lg border border-gray-200 bg-white p-3 dark:border-gray-800 dark:bg-gray-900">
|
||||
@if ($reasonCode !== null)
|
||||
<div class="text-xs font-semibold uppercase tracking-wide text-gray-500 dark:text-gray-400">
|
||||
{{ $reasonCode }}
|
||||
</div>
|
||||
@endif
|
||||
@if ($message !== null)
|
||||
<div class="mt-1 text-sm text-gray-700 dark:text-gray-200">
|
||||
{{ $message }}
|
||||
</div>
|
||||
@endif
|
||||
</li>
|
||||
@endif
|
||||
@endforeach
|
||||
</ul>
|
||||
</div>
|
||||
@endif
|
||||
</x-filament::section>
|
||||
</div>
|
||||
</x-filament-panels::page>
|
||||
|
||||
@ -21,7 +21,7 @@
|
||||
type="button"
|
||||
color="primary"
|
||||
tag="a"
|
||||
href="{{ route('admin.workspace.managed-tenants.onboarding', ['workspace' => $this->workspace->slug ?? $this->workspace->getKey()]) }}"
|
||||
href="{{ route('admin.onboarding') }}"
|
||||
>
|
||||
Start onboarding
|
||||
</x-filament::button>
|
||||
|
||||
@ -66,7 +66,7 @@
|
||||
$tenantCount = (int) $tenantsQuery->count();
|
||||
|
||||
if ($tenantCount === 0) {
|
||||
return redirect()->route('admin.workspace.managed-tenants.onboarding', ['workspace' => $workspace->slug ?? $workspace->getKey()]);
|
||||
return redirect()->to('/admin/onboarding');
|
||||
}
|
||||
|
||||
if ($tenantCount === 1) {
|
||||
@ -128,10 +128,21 @@
|
||||
DisableBladeIconComponents::class,
|
||||
DispatchServingFilamentEvent::class,
|
||||
FilamentAuthenticate::class,
|
||||
'ensure-workspace-member',
|
||||
])
|
||||
->get('/admin/w/{workspace}/managed-tenants/onboarding', \App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard::class)
|
||||
->name('admin.workspace.managed-tenants.onboarding');
|
||||
->get('/admin/onboarding', \App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard::class)
|
||||
->name('admin.onboarding');
|
||||
|
||||
Route::middleware([
|
||||
'web',
|
||||
'panel:admin',
|
||||
'ensure-correct-guard:web',
|
||||
DenyNonMemberTenantAccess::class,
|
||||
DisableBladeIconComponents::class,
|
||||
DispatchServingFilamentEvent::class,
|
||||
FilamentAuthenticate::class,
|
||||
])
|
||||
->get('/admin/operations/{run}', \App\Filament\Pages\Operations\TenantlessOperationRunViewer::class)
|
||||
->name('admin.operations.view');
|
||||
|
||||
Route::middleware([
|
||||
'web',
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
# Specification Quality Checklist: Unified Managed Tenant Onboarding Wizard (073)
|
||||
# Specification Quality Checklist: Managed Tenant Onboarding Wizard V1 (Enterprise)
|
||||
|
||||
**Purpose**: Validate specification completeness and quality before proceeding to planning
|
||||
**Created**: 2026-02-03
|
||||
**Purpose**: Validate specification completeness and quality before proceeding to planning
|
||||
**Created**: 2026-02-04
|
||||
**Feature**: [spec.md](../spec.md)
|
||||
|
||||
## Content Quality
|
||||
@ -31,6 +31,5 @@ ## Feature Readiness
|
||||
|
||||
## Notes
|
||||
|
||||
- All checklist items pass.
|
||||
- The constitution-alignment paragraphs reference platform primitives (e.g., `OperationRun`) and domain integrations (e.g., Microsoft Graph) as required by this repository’s constitution.
|
||||
- Items marked incomplete require spec updates before `/speckit.clarify` or `/speckit.plan`
|
||||
- Clarifications resolved: global Entra Tenant ID uniqueness (bound to one workspace), owner-only activation override with reason + audit, workspace-owned provider connections bound to a tenant by default (reuse off by default).
|
||||
- Spec is ready for `/speckit.plan`.
|
||||
|
||||
@ -3,43 +3,39 @@ info:
|
||||
title: TenantPilot — Managed Tenant Onboarding (073)
|
||||
version: 0.1.0
|
||||
description: |
|
||||
Workspace-scoped onboarding wizard routes. These are UI endpoints (Filament/Livewire),
|
||||
but documented here for contract clarity.
|
||||
Onboarding wizard + tenantless operation run viewer routes.
|
||||
|
||||
These are UI endpoints (Filament/Livewire), documented here for contract clarity.
|
||||
servers:
|
||||
- url: https://example.invalid
|
||||
paths:
|
||||
/admin/w/{workspace}/managed-tenants:
|
||||
/admin/onboarding:
|
||||
get:
|
||||
summary: Managed tenants landing (workspace-scoped)
|
||||
parameters:
|
||||
- name: workspace
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
summary: Managed tenant onboarding wizard (canonical entry point)
|
||||
responses:
|
||||
'200':
|
||||
description: Renders managed tenants landing page.
|
||||
'403':
|
||||
description: Workspace member missing required capability (where applicable).
|
||||
'404':
|
||||
description: Workspace not found or user not a member (deny-as-not-found).
|
||||
/admin/w/{workspace}/managed-tenants/onboarding:
|
||||
get:
|
||||
summary: Managed tenant onboarding wizard (workspace-scoped)
|
||||
parameters:
|
||||
- name: workspace
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
'200':
|
||||
description: Renders onboarding wizard page.
|
||||
description: Renders onboarding wizard page in the current workspace context.
|
||||
'302':
|
||||
description: Redirects to workspace chooser when no workspace is selected.
|
||||
'403':
|
||||
description: Workspace member missing onboarding capability.
|
||||
'404':
|
||||
description: Workspace not found or user not a member (deny-as-not-found).
|
||||
description: Workspace not found or user is not a member (deny-as-not-found).
|
||||
|
||||
/admin/operations/{run}:
|
||||
get:
|
||||
summary: Tenantless operation run viewer
|
||||
parameters:
|
||||
- name: run
|
||||
in: path
|
||||
required: true
|
||||
schema:
|
||||
type: integer
|
||||
responses:
|
||||
'200':
|
||||
description: Renders operation run details.
|
||||
'404':
|
||||
description: Run not found or actor is not a member of the run workspace (deny-as-not-found).
|
||||
|
||||
/admin/register-tenant:
|
||||
get:
|
||||
@ -48,3 +44,19 @@ paths:
|
||||
responses:
|
||||
'404':
|
||||
description: Must be removed / behave as not found (FR-001).
|
||||
|
||||
/admin/new:
|
||||
get:
|
||||
summary: Legacy onboarding entry point
|
||||
deprecated: true
|
||||
responses:
|
||||
'404':
|
||||
description: Must not exist and must behave as not found (FR-004).
|
||||
|
||||
/admin/managed-tenants/onboarding:
|
||||
get:
|
||||
summary: Legacy onboarding entry point
|
||||
deprecated: true
|
||||
responses:
|
||||
'404':
|
||||
description: Must not exist and must behave as not found (FR-004).
|
||||
|
||||
@ -1,32 +1,34 @@
|
||||
# Onboarding Wizard — Action Contracts (073)
|
||||
|
||||
These are conceptual contracts for the wizard’s server-side actions (Livewire/Filament).
|
||||
These are conceptual contracts for the wizard’s server-side actions (Filament / Livewire).
|
||||
They define inputs/outputs and authorization semantics.
|
||||
|
||||
## Identify tenant
|
||||
|
||||
- **Purpose:** Upsert or resume a tenant onboarding session and ensure a single tenant record exists per `(workspace_id, entra_tenant_id)`.
|
||||
- **Purpose:** Upsert or resume onboarding and ensure the managed tenant identity (Entra Tenant ID) is globally unique and bound to a single workspace.
|
||||
- **Inputs:**
|
||||
- `entra_tenant_id` (string)
|
||||
- `environment` (string)
|
||||
- `name` (string)
|
||||
- `domain` (string|null)
|
||||
- `primary_domain` (string|null)
|
||||
- `notes` (string|null)
|
||||
- **Outputs:**
|
||||
- `tenant_id` (internal DB id)
|
||||
- `managed_tenant_id` (internal DB id)
|
||||
- `onboarding_session_id`
|
||||
- `current_step`
|
||||
- **Errors:**
|
||||
- 404: workspace not found or actor not a workspace member
|
||||
- 404: workspace not found, actor not a workspace member, or Entra Tenant ID exists in a different workspace (deny-as-not-found)
|
||||
- 403: actor is a workspace member but lacks onboarding capability
|
||||
|
||||
## Select or create Provider Connection
|
||||
|
||||
- **Purpose:** Attach an existing default connection (if present) or create/select another connection for the tenant.
|
||||
- **Purpose:** Select an existing provider connection in the workspace or create a new one (secrets captured safely).
|
||||
- **Inputs:**
|
||||
- `provider_connection_id` (int|null)
|
||||
- (optional) connection creation fields (non-secret identifiers only)
|
||||
- **Outputs:**
|
||||
- `provider_connection_id`
|
||||
- `is_default`
|
||||
- `is_default` (bool)
|
||||
- **Errors:**
|
||||
- 404: connection/tenant not in workspace scope
|
||||
- 403: member missing capability
|
||||
@ -43,6 +45,10 @@ ## Start verification
|
||||
- 404: tenant/connection not in workspace scope
|
||||
- 403: member missing capability
|
||||
|
||||
**View run link contract:**
|
||||
- The UI must expose a tenantless “View run” URL: `/admin/operations/{run}`.
|
||||
- Access is granted only if the actor is a member of the run’s workspace; otherwise 404 (deny-as-not-found).
|
||||
|
||||
## Optional bootstrap actions
|
||||
|
||||
- **Purpose:** Start selected post-verify operations as separate runs.
|
||||
@ -51,6 +57,23 @@ ## Optional bootstrap actions
|
||||
- **Errors:**
|
||||
- 403/404 semantics as above
|
||||
|
||||
## Activate (Complete)
|
||||
|
||||
- **Purpose:** Activate the managed tenant, making it available in the tenant switcher.
|
||||
- **Preconditions:** Provider connection exists; verification is not Blocked unless overridden by an owner.
|
||||
- **Inputs:**
|
||||
- `override_blocked` (bool, optional)
|
||||
- `override_reason` (string, required if override)
|
||||
- **Outputs:**
|
||||
- `managed_tenant_id`
|
||||
- `status` (active)
|
||||
- **Errors:**
|
||||
- 404: managed tenant not in workspace scope / actor not a member
|
||||
- 403: actor is a member but not an owner (owner-only activation); or missing capability
|
||||
|
||||
**Audit requirement:**
|
||||
- Any override must record an audit event including the human-entered reason.
|
||||
|
||||
## Security & data minimization
|
||||
|
||||
- Stored secrets must never be returned.
|
||||
|
||||
@ -1,60 +1,82 @@
|
||||
# Data Model — Unified Managed Tenant Onboarding Wizard (073)
|
||||
# Data Model — Managed Tenant Onboarding Wizard V1 (Enterprise) (073)
|
||||
|
||||
## Entities
|
||||
|
||||
### Workspace
|
||||
|
||||
Existing entity. Onboarding is always initiated within a selected workspace.
|
||||
Existing entity: `App\Models\Workspace`
|
||||
|
||||
- Onboarding is always initiated within a selected workspace context.
|
||||
- Workspace membership is the primary isolation boundary for wizard + tenantless operations viewing.
|
||||
|
||||
### Tenant (Managed Tenant)
|
||||
|
||||
Existing model: `App\Models\Tenant`
|
||||
|
||||
**Key fields (existing or to be confirmed/extended):**
|
||||
**Key fields (existing or to extend):**
|
||||
|
||||
- `id` (PK)
|
||||
- `workspace_id` (FK to workspaces)
|
||||
- `tenant_id` (string; Entra tenant ID) — spec’s `entra_tenant_id`
|
||||
- `external_id` (string; globally unique route key used by Filament tenancy)
|
||||
- `workspace_id` (FK → workspaces)
|
||||
- `tenant_id` (string; Entra Tenant ID) — spec’s `entra_tenant_id` (globally unique)
|
||||
- `external_id` (string; Filament tenant route key; currently used in `/admin/t/{tenant}`)
|
||||
- `name` (string)
|
||||
- `domain` (string|null)
|
||||
- `primary_domain` (string|null)
|
||||
- `notes` (text|null)
|
||||
- `environment` (string)
|
||||
- `status` (string) — v1 lifecycle:
|
||||
- `pending` (created / onboarding)
|
||||
- `active` (ready)
|
||||
- `archived` (no longer managed)
|
||||
- `draft`
|
||||
- `onboarding`
|
||||
- `active`
|
||||
- `archived`
|
||||
|
||||
**Indexes / constraints (design intent):**
|
||||
|
||||
- Unique: `(workspace_id, tenant_id)`
|
||||
- Keep `external_id` globally unique (for `/admin/t/{tenant}` routing) and do **not** force it to equal `tenant_id`.
|
||||
- Unique: `tenant_id` (global uniqueness; binds the tenant to exactly one workspace)
|
||||
- `external_id` must remain globally unique for Filament tenancy routing
|
||||
|
||||
**State transitions:**
|
||||
|
||||
- `pending` → `active` after successful verification
|
||||
- `active` → `archived` on soft-delete (existing behavior)
|
||||
- `archived` → `active` on restore (existing behavior)
|
||||
- `draft` → `onboarding` after identification is recorded
|
||||
- `onboarding` → `active` on owner activation
|
||||
- `active` → `archived` via archive/deactivate workflow
|
||||
|
||||
### ProviderConnection
|
||||
### Provider Connection
|
||||
|
||||
Existing model: `App\Models\ProviderConnection`
|
||||
Existing model today: `App\Models\ProviderConnection` (currently tenant-owned)
|
||||
|
||||
- Belongs to `Tenant`
|
||||
- Contains `entra_tenant_id` (string) and default/active flags.
|
||||
**Spec-aligned ownership model (design intent):**
|
||||
|
||||
### TenantOnboardingSession (new)
|
||||
- Provider connections are workspace-owned.
|
||||
- Default binding: provider connection bound to exactly one managed tenant.
|
||||
- Reuse across managed tenants is disabled by default and policy-gated.
|
||||
|
||||
New model/table to persist resumable onboarding state. Must never persist or return secrets.
|
||||
**Proposed key fields (target):**
|
||||
|
||||
- `id` (PK)
|
||||
- `workspace_id` (FK → workspaces)
|
||||
- `managed_tenant_id` (FK → tenants.id; required in v1 default binding)
|
||||
- `provider` (string)
|
||||
- `entra_tenant_id` (string)
|
||||
- `is_default` (bool)
|
||||
- `metadata` (json)
|
||||
|
||||
### Tenant Onboarding Session (new)
|
||||
|
||||
New model/table to persist resumable onboarding state for a workspace + Entra Tenant ID.
|
||||
Must never persist secrets and must render DB-only.
|
||||
|
||||
**Proposed fields:**
|
||||
|
||||
- `id` (PK)
|
||||
- `workspace_id` (FK)
|
||||
- `tenant_id` (FK to tenants.id) — nullable until tenant is created, depending on wizard flow
|
||||
- `entra_tenant_id` (string) — denormalized for upsert/idempotency before tenant exists
|
||||
- `current_step` (string; e.g., `identify`, `connection`, `verify`, `bootstrap`, `complete`)
|
||||
- `state` (jsonb/json) — safe fields only (no secrets)
|
||||
- `managed_tenant_id` (FK → tenants.id; nullable until tenant is created)
|
||||
- `entra_tenant_id` (string; denormalized identity key; globally unique across the system but still stored for idempotency)
|
||||
- `current_step` (string; `identify`, `connection`, `verify`, `bootstrap`, `complete`)
|
||||
- `state` (jsonb) — safe fields only (no secrets)
|
||||
- `tenant_name`
|
||||
- `tenant_domain`
|
||||
- `environment`
|
||||
- `primary_domain`
|
||||
- `notes`
|
||||
- `selected_provider_connection_id`
|
||||
- `verification_run_id` (OperationRun id)
|
||||
- `bootstrap_run_ids` (array)
|
||||
@ -65,20 +87,34 @@ ### TenantOnboardingSession (new)
|
||||
|
||||
**Constraints:**
|
||||
|
||||
- Unique: `(workspace_id, entra_tenant_id)`
|
||||
- Unique: `entra_tenant_id` (global uniqueness) OR (if sessions are separate from tenants) unique `(workspace_id, entra_tenant_id)` with an additional global “tenant exists elsewhere” guard to enforce deny-as-not-found.
|
||||
|
||||
**State transitions:**
|
||||
### Operation Run
|
||||
|
||||
- `in_progress` (implied by `completed_at = null`) → `completed` (`completed_at != null`)
|
||||
Existing model: `App\Models\OperationRun`
|
||||
|
||||
**Spec-aligned visibility model (design intent):**
|
||||
|
||||
- Runs are viewable tenantlessly at `/admin/operations/{run}`.
|
||||
- Access is granted only to members of the run’s workspace; non-member → deny-as-not-found (404).
|
||||
|
||||
**Proposed schema changes:**
|
||||
|
||||
- Add `workspace_id` (FK → workspaces), required.
|
||||
- Allow `tenant_id` to be nullable for pre-activation runs.
|
||||
- Maintain DB-level active-run idempotency:
|
||||
- `UNIQUE (tenant_id, run_identity_hash) WHERE tenant_id IS NOT NULL AND status IN ('queued', 'running')`
|
||||
- `UNIQUE (workspace_id, run_identity_hash) WHERE tenant_id IS NULL AND status IN ('queued', 'running')`
|
||||
|
||||
## Validation rules (high level)
|
||||
|
||||
- `entra_tenant_id` (`tenant_id`) must be a non-empty string; validate as GUID format if enforced elsewhere.
|
||||
- Tenant name required to create tenant.
|
||||
- ProviderConnection selection must belong to the same tenant/workspace.
|
||||
- `entra_tenant_id`: required, non-empty, validate GUID format.
|
||||
- Tenant identification requires: `name`, `environment`, `entra_tenant_id`.
|
||||
- Provider connection selected/created must be in the same workspace.
|
||||
- Onboarding session `state` must be strictly whitelisted fields (no secrets).
|
||||
|
||||
## Authorization boundaries
|
||||
|
||||
- Workspace scope: non-members denied as 404.
|
||||
- Workspace member but missing onboarding capability: 403.
|
||||
- Tenant scope: once tenant exists/selected, tenant membership rules apply as currently implemented.
|
||||
- Workspace membership boundary: non-member → 404 (deny-as-not-found) for onboarding and tenantless operations run viewing.
|
||||
- Capability boundary (within membership): action attempts without capability → 403.
|
||||
- Owner-only boundary: activation and blocked override require workspace owner; override requires reason + audit.
|
||||
|
||||
@ -1,50 +1,45 @@
|
||||
# Implementation Plan: Unified Managed Tenant Onboarding Wizard (073)
|
||||
# Implementation Plan: Managed Tenant Onboarding Wizard V1 (Enterprise)
|
||||
|
||||
**Branch**: `073-unified-managed-tenant-onboarding-wizard` | **Date**: 2026-02-03 | **Spec**: specs/073-unified-managed-tenant-onboarding-wizard/spec.md
|
||||
**Input**: Feature specification from `specs/073-unified-managed-tenant-onboarding-wizard/spec.md`
|
||||
|
||||
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/scripts/` for helper scripts.
|
||||
**Branch**: `073-unified-managed-tenant-onboarding-wizard` | **Date**: 2026-02-04 | **Spec**: specs/073-unified-managed-tenant-onboarding-wizard/spec.md
|
||||
**Input**: Feature specification from specs/073-unified-managed-tenant-onboarding-wizard/spec.md
|
||||
|
||||
## Summary
|
||||
|
||||
Deliver a single, resumable onboarding wizard for Managed Tenants that: (1) identifies/upserts a managed tenant within the current workspace, (2) attaches or configures a Provider Connection, (3) runs verification asynchronously as an `OperationRun` with sanitized outcomes, and (4) optionally kicks off bootstrap operations.
|
||||
Deliver a single onboarding entry point at `/admin/onboarding` that is workspace-first and tenantless until activation. Verification and optional bootstrap actions run asynchronously as `OperationRun`s and are viewable via a tenantless URL `/admin/operations/{run}` with workspace-membership based 404 semantics.
|
||||
|
||||
Implementation approach: reuse existing primitives (`App\Models\Tenant`, Provider Connections, `provider.connection.check` operation type, workspace + tenant isolation middleware, canonical capability registries) and replace legacy tenant registration/redirect entry points with a single workspace-scoped wizard route.
|
||||
This requires:
|
||||
- Updating onboarding routing and removing legacy entry points.
|
||||
- Making the operations run viewer safe and usable without a selected workspace and without tenant routing.
|
||||
- Ensuring RBAC-UX semantics (non-member → 404, member missing capability → 403) while keeping UI discoverability (disabled+tooltip).
|
||||
|
||||
## Technical Context
|
||||
|
||||
<!--
|
||||
ACTION REQUIRED: Replace the content in this section with the technical details
|
||||
for the project. The structure here is presented in advisory capacity to guide
|
||||
the iteration process.
|
||||
-->
|
||||
|
||||
**Language/Version**: PHP 8.4.x (Composer constraint: `^8.2`)
|
||||
**Primary Dependencies**: Laravel 12, Filament 5, Livewire 4+, Pest 4, Sail 1.x
|
||||
**Storage**: PostgreSQL (Sail) + SQLite in tests where applicable
|
||||
**Testing**: Pest (via `vendor/bin/sail artisan test`)
|
||||
**Target Platform**: Web app (Sail for local dev; container-based deploy on Linux)
|
||||
**Project Type**: Web application (Laravel monolith)
|
||||
**Performance Goals**: Onboarding UI renders DB-only; all Graph calls occur in queued work tracked by `OperationRun`; avoid N+1 via eager loading for any list/detail.
|
||||
**Constraints**: Tenant isolation (404 vs 403 semantics); no secret material ever returned to the UI/logs; idempotent run-start and onboarding session resume; destructive-like actions require confirmation.
|
||||
**Scale/Scope**: Workspace-scoped onboarding; expected low volume but high correctness/safety requirements.
|
||||
**Language/Version**: PHP 8.4 (Laravel 12)
|
||||
**Primary Dependencies**: Filament v5, Livewire v4
|
||||
**Storage**: PostgreSQL (Sail)
|
||||
**Testing**: Pest v4
|
||||
**Target Platform**: macOS dev + Sail containers; deployed in containers (Dokploy)
|
||||
**Project Type**: Web application
|
||||
**Performance Goals**: Wizard + Monitoring pages render DB-only (no external calls); queued work for Graph
|
||||
**Constraints**:
|
||||
- Canonical entry `/admin/onboarding` only
|
||||
- Tenantless operations viewer `/admin/operations/{run}` must not require selected workspace and must not auto-switch workspaces
|
||||
- Secrets never rendered after capture; no secrets in operation run failures/audits
|
||||
**Scale/Scope**: Multi-workspace admin app; onboarding must be safe, resumable, and regression-tested
|
||||
|
||||
## Constitution Check
|
||||
|
||||
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
|
||||
|
||||
|
||||
GATE RESULT: PASS (no planned constitution violations).
|
||||
|
||||
- Inventory-first: onboarding writes only tenant metadata + configuration pointers; no inventory/snapshot side effects.
|
||||
- Read/write separation: onboarding creates/updates records and starts operations; all mutating actions are authorized, audited, and tested.
|
||||
- Graph contract path: verification uses existing `GraphClientInterface` methods (e.g., `getOrganization()`), and runs only in queued jobs.
|
||||
- Deterministic capabilities: use `App\Support\Auth\Capabilities` + `WorkspaceRoleCapabilityMap`; add a dedicated onboarding capability granted to Owner+Manager.
|
||||
- RBAC-UX semantics: workspace membership enforced via `ensure-workspace-member`; tenant membership enforced via `EnsureFilamentTenantSelected` / `DenyNonMemberTenantAccess` with deny-as-not-found (404). Missing capability returns 403.
|
||||
- Destructive confirmation: any archive/delete/credential-rotation actions involved in onboarding must be `->action(...)->requiresConfirmation()`.
|
||||
- Run observability: verification + optional bootstrap actions start via `OperationRun` and enqueue only; monitoring pages remain DB-only.
|
||||
- Data minimization: onboarding session stores only non-secret fields; run failures store reason codes + sanitized messages.
|
||||
- BADGE-001: introduce/extend Managed Tenant status badges via `BadgeCatalog` domain mapping (no per-page mapping).
|
||||
- Inventory-first: Not directly impacted.
|
||||
- Read/write separation: activation + overrides are write paths → audit + tests.
|
||||
- Graph contract path: verification/bootstrap Graph calls only via `GraphClientInterface` and `config/graph_contracts.php` (including connectivity probes like `organization` and service-principal permission lookups).
|
||||
- Deterministic capabilities: wizard uses canonical capability registry; no role-string checks.
|
||||
- RBAC-UX: enforce 404/403 semantics; server-side authorizes all actions; UI disabled state is informational only.
|
||||
- Authorization planes: tenant plane (Entra users) only; no platform plane (`/system`) routes or cross-plane behavior.
|
||||
- Run observability: verification/bootstrap runs use `OperationRun`; render remains DB-only.
|
||||
- Data minimization: never persist secrets in session/state/report/audit.
|
||||
- Badge semantics: status chips use centralized badge mapping.
|
||||
|
||||
## Project Structure
|
||||
|
||||
@ -52,112 +47,72 @@ ### Documentation (this feature)
|
||||
|
||||
```text
|
||||
specs/073-unified-managed-tenant-onboarding-wizard/
|
||||
├── plan.md # This file (/speckit.plan command output)
|
||||
├── research.md # Phase 0 output (/speckit.plan command)
|
||||
├── data-model.md # Phase 1 output (/speckit.plan command)
|
||||
├── quickstart.md # Phase 1 output (/speckit.plan command)
|
||||
├── contracts/ # Phase 1 output (/speckit.plan command)
|
||||
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
|
||||
├── plan.md
|
||||
├── research.md
|
||||
├── data-model.md
|
||||
├── quickstart.md
|
||||
├── contracts/
|
||||
│ ├── http.openapi.yaml
|
||||
│ └── onboarding-actions.md
|
||||
└── tasks.md
|
||||
```
|
||||
|
||||
### Source Code (repository root)
|
||||
<!--
|
||||
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
|
||||
for this feature. Delete unused options and expand the chosen structure with
|
||||
real paths (e.g., apps/admin, packages/something). The delivered plan must
|
||||
not include Option labels.
|
||||
-->
|
||||
|
||||
```text
|
||||
app/
|
||||
├── Filament/
|
||||
│ ├── Pages/
|
||||
│ │ └── Workspaces/
|
||||
│ │ ├── ManagedTenantsLanding.php
|
||||
│ │ └── (new) ManagedTenantOnboardingWizard.php
|
||||
│ └── Pages/Tenancy/
|
||||
│ └── RegisterTenant.php # legacy entry point to remove/disable
|
||||
├── Http/Controllers/
|
||||
│ └── TenantOnboardingController.php # legacy admin-consent helper; evaluate usage
|
||||
├── Jobs/
|
||||
│ └── ProviderConnectionHealthCheckJob.php # verification via OperationRun
|
||||
├── Filament/Pages/
|
||||
├── Filament/Resources/
|
||||
├── Http/Middleware/
|
||||
├── Models/
|
||||
│ ├── Tenant.php
|
||||
│ ├── ProviderConnection.php
|
||||
│ └── (new) TenantOnboardingSession.php
|
||||
└── Services/
|
||||
├── Auth/
|
||||
│ ├── WorkspaceCapabilityResolver.php
|
||||
│ └── WorkspaceRoleCapabilityMap.php
|
||||
├── Providers/
|
||||
│ ├── ProviderOperationRegistry.php
|
||||
│ └── ProviderGateway.php
|
||||
└── Graph/
|
||||
└── GraphClientInterface.php
|
||||
├── Policies/
|
||||
├── Services/
|
||||
└── Support/
|
||||
|
||||
database/migrations/
|
||||
├── (new) *_add_workspace_scoped_unique_tenant_id.php
|
||||
└── (new) *_create_tenant_onboarding_sessions_table.php
|
||||
|
||||
routes/web.php
|
||||
|
||||
tests/Feature/
|
||||
└── (new) ManagedTenantOnboardingWizardTest.php
|
||||
```
|
||||
|
||||
**Structure Decision**: Laravel web application (monolith). Onboarding wizard is a Filament page mounted on a workspace-scoped route under `/admin/w/{workspace}/...` (no tenant context required to start).
|
||||
**Structure Decision**: Implement onboarding as a Filament Page under `app/Filament/Pages` and keep operations viewing on `OperationRunResource`, but change authorization/middleware to support tenantless viewing.
|
||||
|
||||
## Phase 0 — Research
|
||||
|
||||
See: specs/073-unified-managed-tenant-onboarding-wizard/research.md
|
||||
|
||||
## Phase 1 — Design & Contracts
|
||||
|
||||
See:
|
||||
- specs/073-unified-managed-tenant-onboarding-wizard/data-model.md
|
||||
- specs/073-unified-managed-tenant-onboarding-wizard/contracts/http.openapi.yaml
|
||||
- specs/073-unified-managed-tenant-onboarding-wizard/contracts/onboarding-actions.md
|
||||
- specs/073-unified-managed-tenant-onboarding-wizard/quickstart.md
|
||||
|
||||
## Phase 2 — Planning (implementation outline)
|
||||
|
||||
1) Routing
|
||||
- Add `/admin/onboarding` (canonical, sole entry point).
|
||||
- Remove legacy entry points (404; no redirects): `/admin/new`, `/admin/managed-tenants/onboarding`, and any tenant-scoped onboarding/create entry points.
|
||||
|
||||
2) Tenantless operations run viewer
|
||||
- Exempt `/admin/operations/{run}` from forced workspace selection (`EnsureWorkspaceSelected`) and from tenant auto-selection side effects when needed.
|
||||
- Authorize `OperationRun` viewing by workspace membership derived from the run (non-member → 404).
|
||||
|
||||
3) OperationRun model + schema alignment
|
||||
- Add `operation_runs.workspace_id` and support tenantless runs (`tenant_id` nullable) if onboarding verification/bootstraps start before activation.
|
||||
- Preserve DB-level active-run dedupe with partial unique indexes for both tenant-bound and tenantless runs.
|
||||
|
||||
4) Wizard authorization model
|
||||
- Gate wizard actions per canonical capabilities; keep controls visible-but-disabled with tooltip; server-side returns 403 for execution.
|
||||
- Activation is owner-only; blocked override requires reason + audit.
|
||||
|
||||
5) Tests
|
||||
- Add/extend Pest feature tests for:
|
||||
- canonical `/admin/onboarding` routing
|
||||
- legacy entry points 404
|
||||
- `/admin/operations/{run}` membership→404 behavior without selected workspace
|
||||
- 403 for member action attempts without capability
|
||||
- owner-only activation + override audit reason
|
||||
|
||||
## Complexity Tracking
|
||||
|
||||
> **Fill ONLY if Constitution Check has violations that must be justified**
|
||||
|
||||
| Violation | Why Needed | Simpler Alternative Rejected Because |
|
||||
|-----------|------------|-------------------------------------|
|
||||
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
|
||||
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
|
||||
|
||||
No constitution violations are anticipated for this feature.
|
||||
|
||||
## Phase 0 — Outline & Research (complete)
|
||||
|
||||
Outputs:
|
||||
|
||||
- `research.md`: decisions + rationale + alternatives (no unresolved clarifications).
|
||||
|
||||
Key research conclusions:
|
||||
|
||||
- Reuse `App\Models\Tenant` as “Managed Tenant” (no new base concept), but introduce `pending` status for the onboarding lifecycle.
|
||||
- Replace legacy onboarding/registration routes (`/admin/register-tenant`, redirects under `/admin/managed-tenants/*`) with a single workspace-scoped onboarding wizard.
|
||||
- Use existing provider verification operation type (`provider.connection.check`) executed via `ProviderConnectionHealthCheckJob` with `OperationRun` tracking.
|
||||
|
||||
## Phase 1 — Design & Contracts (complete)
|
||||
|
||||
Outputs:
|
||||
|
||||
- `data-model.md`: entities, fields, relationships, validation, state transitions.
|
||||
- `contracts/*`: documented HTTP routes + action contracts (OpenAPI-style where applicable).
|
||||
- `quickstart.md`: dev notes, env vars, how to run tests.
|
||||
|
||||
Design highlights:
|
||||
|
||||
- Data model
|
||||
- Tenants: change status lifecycle to include `pending`, ensure `workspace_id` is NOT NULL + FK, and enforce global uniqueness of `tenant_id` (Entra tenant ID) bound to exactly one workspace.
|
||||
- Onboarding sessions: new table/model for resumable state (strictly non-secret) keyed by `(workspace_id, tenant_id)`.
|
||||
- Authorization
|
||||
- Introduce a workspace capability for onboarding (e.g., `workspace_managed_tenant.onboard`) and map it to Owner+Manager via `WorkspaceRoleCapabilityMap`.
|
||||
- Enforce server-side authorization for every mutation and operation-start; 404 for non-members and cross-workspace access; 403 for members missing capability.
|
||||
- Runs
|
||||
- Verification is a queued `OperationRun` using `provider.connection.check`.
|
||||
- Optional bootstrap actions become separate `OperationRun` types (only if they exist in the ProviderOperationRegistry).
|
||||
|
||||
## Phase 2 — Implementation Plan (to be executed by /speckit.tasks)
|
||||
|
||||
This plan intentionally stops before creating `tasks.md`.
|
||||
|
||||
Proposed sequencing for tasks:
|
||||
|
||||
1) Introduce `TenantOnboardingSession` model + migration, and add workspace-scoped uniqueness for tenants.
|
||||
2) Implement `ManagedTenantOnboardingWizard` page mounted at `/admin/w/{workspace}/managed-tenants/onboarding`.
|
||||
3) Wire verification start to existing `ProviderConnectionHealthCheckJob` / `provider.connection.check` operation.
|
||||
4) Remove/disable legacy entry points (`RegisterTenant`, redirect routes) and ensure “not found” behavior.
|
||||
5) Add Pest feature tests for: 404 vs 403 semantics, idempotency, resumability, and sanitized run outcomes.
|
||||
No constitution violations expected; changes are localized and gated by tests.
|
||||
|
||||
@ -12,21 +12,21 @@ ## Local setup
|
||||
## Using the wizard (expected flow)
|
||||
|
||||
1) Sign in to `/admin`.
|
||||
2) Choose a workspace at `/admin/choose-workspace`.
|
||||
3) Open `/admin/w/{workspace}/managed-tenants`.
|
||||
4) Start onboarding at `/admin/w/{workspace}/managed-tenants/onboarding`.
|
||||
5) Complete Identify → Connection → Verify (queued) → optional Bootstrap.
|
||||
2) Open `/admin/onboarding`.
|
||||
3) If no workspace is selected, you are redirected to `/admin/choose-workspace`.
|
||||
4) Complete Identify → Connection → Verify (queued) → optional Bootstrap → Activate.
|
||||
|
||||
Notes:
|
||||
|
||||
- The onboarding UI must render DB-only; Graph calls occur only in queued work.
|
||||
- Verification is tracked as an `OperationRun` (module `health_check`).
|
||||
- Verification/bootstrap are tracked as `OperationRun`s.
|
||||
- The “View run” link must open `/admin/operations/{run}` (tenantless). This page must be accessible without a selected workspace, but only to members of the run’s workspace.
|
||||
|
||||
## Tests
|
||||
|
||||
Run targeted tests (expected file name when implemented):
|
||||
|
||||
- `vendor/bin/sail artisan test --compact tests/Feature/ManagedTenantOnboardingWizardTest.php`
|
||||
- `vendor/bin/sail artisan test --compact --filter=Onboarding`
|
||||
|
||||
## Deploy / Ops
|
||||
|
||||
|
||||
@ -1,62 +1,67 @@
|
||||
# Research — Unified Managed Tenant Onboarding Wizard (073)
|
||||
# Research — Managed Tenant Onboarding Wizard V1 (Enterprise) (073)
|
||||
|
||||
This document resolves planning unknowns and records key implementation decisions.
|
||||
This document resolves planning unknowns and records key implementation decisions aligned with the clarified spec.
|
||||
|
||||
## Decisions
|
||||
|
||||
### 1) Managed Tenant model = existing `Tenant`
|
||||
|
||||
- **Decision:** Treat the existing `App\Models\Tenant` as the “Managed Tenant” concept.
|
||||
- **Rationale:** The admin panel tenancy, membership model, and most operational flows already key off `Tenant`.
|
||||
- **Alternatives considered:**
|
||||
- Introduce a new `ManagedTenant` model/table.
|
||||
- Keep `Tenant` as-is and build onboarding as “just another page”.
|
||||
- **Why rejected:** A second tenant-like model would duplicate authorization, routing, and operational conventions.
|
||||
- **Decision:** Treat `App\Models\Tenant` as the “Managed Tenant” record.
|
||||
- **Rationale:** Filament tenancy, membership model, and tenant-scoped flows already depend on `Tenant`; duplicating a second tenant-like table would multiply authorization and routing complexity.
|
||||
- **Alternatives considered:** Introduce a new `ManagedTenant` model/table.
|
||||
- **Why rejected:** Duplicates tenancy and membership boundaries; increases cross-plane leak risk.
|
||||
|
||||
### 2) Workspace-scoped uniqueness + stable route key
|
||||
### 2) Entra Tenant ID uniqueness = global, bound to one workspace
|
||||
|
||||
- **Decision:** Enforce uniqueness by `(workspace_id, tenant_id)` (where `tenant_id` is the Entra tenant ID), and ensure Filament’s route tenant key stays globally unique.
|
||||
- **Rationale:** The feature spec explicitly defines the uniqueness key, and cross-workspace safety requires first-class scoping.
|
||||
- **Implementation note:** Today `tenants.external_id` is unique and is force-set to `tenant_id` in `Tenant::saving()`. If we allow the same `tenant_id` across workspaces, `external_id` must NOT be set to `tenant_id` anymore. Prefer a generated opaque stable `external_id` (UUID) and keep `tenant_id` strictly as the business identifier.
|
||||
- **Alternatives considered:**
|
||||
- Keep global uniqueness on `tenant_id` and keep using `external_id = tenant_id`.
|
||||
- **Why rejected:** Conflicts with the clarified uniqueness key and complicates “deny-as-not-found” behavior via DB constraint errors.
|
||||
- **Decision:** Enforce global uniqueness for `tenants.tenant_id` (Entra Tenant ID) and bind it to exactly one workspace (the workspace_id on the tenant).
|
||||
- **Rationale:** Matches FR-011 and the clarification decision (“global uniqueness bound to one workspace”).
|
||||
- **Alternatives considered:** Allow the same Entra Tenant ID in multiple workspaces.
|
||||
- **Why rejected:** Violates the clarified requirement and complicates deny-as-not-found behavior.
|
||||
|
||||
### 3) Wizard route location = workspace-scoped (`/admin/w/{workspace}/...`)
|
||||
### 3) Canonical onboarding entry point = `/admin/onboarding` (only)
|
||||
|
||||
- **Decision:** Mount onboarding at a workspace-scoped route: `/admin/w/{workspace}/managed-tenants/onboarding`.
|
||||
- **Rationale:** This path is explicitly exempted from forced tenant selection in `EnsureFilamentTenantSelected`, allowing onboarding before a tenant exists.
|
||||
- **Alternatives considered:**
|
||||
- Tenant-scoped Filament routes (`/admin/t/{tenant}/...`).
|
||||
- Reusing Filament’s built-in tenant registration page (`tenantRegistration`).
|
||||
- **Why rejected:** Tenant-scoped routes require a tenant to exist/selected; built-in registration is a legacy entry point we must remove.
|
||||
- **Decision:** Provide `/admin/onboarding` as the sole onboarding entry point.
|
||||
- **Rationale:** Keeps a single user-facing URL for enterprise workflows; avoids fragmented legacy entry points.
|
||||
- **Alternatives considered:** Workspace-scoped onboarding route (`/admin/w/{workspace}/...`).
|
||||
- **Why rejected:** Conflicts with clarified spec (canonical `/admin/onboarding` only).
|
||||
|
||||
### 4) Verification implementation = existing provider operation (`provider.connection.check`)
|
||||
### 4) Tenantless operations viewer = existing `OperationRunResource` route `/admin/operations/{run}`
|
||||
|
||||
- **Decision:** Use `provider.connection.check` (module `health_check`) executed via `ProviderConnectionHealthCheckJob` as the onboarding verification run.
|
||||
- **Rationale:** It already uses `OperationRun`, writes sanitized outcomes, and performs Graph calls off-request.
|
||||
- **Alternatives considered:**
|
||||
- New onboarding-specific operation type.
|
||||
- **Why rejected:** Adds duplication without a clear benefit for v1.
|
||||
- **Decision:** Keep the route shape `/admin/operations/{run}` (already provided by `OperationRunResource` slug `operations`) and make it compliant by changing authorization + middleware behavior.
|
||||
- **Rationale:** Minimizes routing surface area and leverages existing Monitoring → Operations UI.
|
||||
- **Alternatives considered:** Create a separate “run viewer” page outside the resource.
|
||||
- **Why rejected:** Duplicates infolist rendering and complicates observability conventions.
|
||||
|
||||
### 5) Authorization surface = workspace capability (Owner+Manager)
|
||||
### 5) `/admin/operations/{run}` must not require selected workspace or auto-switch
|
||||
|
||||
- **Decision:** Add a dedicated workspace capability for onboarding (e.g., `workspace_managed_tenant.onboard`) and grant it to workspace Owner and Manager in `WorkspaceRoleCapabilityMap`.
|
||||
- **Rationale:** The spec requires Owner+Manager; existing workspace capabilities don’t exactly match this (e.g., `WORKSPACE_MANAGE` is Owner-only).
|
||||
- **Alternatives considered:**
|
||||
- Check workspace role strings (`owner/manager`) directly.
|
||||
- Reuse an unrelated capability like `WORKSPACE_MEMBERSHIP_MANAGE`.
|
||||
- **Why rejected:** Constitution forbids role-string checks in feature code; reusing unrelated capability broadens authorization implicitly.
|
||||
- **Decision:** Exempt `/admin/operations/{run}` from forced workspace selection and from any “auto selection” side effects that would prevent tenantless viewing.
|
||||
- **Rationale:** Spec requires (a) no workspace in the URL, (b) no pre-selected workspace required, (c) no auto-switching.
|
||||
- **Alternatives considered:** Keep current `EnsureWorkspaceSelected` behavior (redirect to choose workspace).
|
||||
- **Why rejected:** Violates FR-017a and can leak resource existence via redirects.
|
||||
|
||||
### 6) Legacy entry points = removed/404 (no redirects)
|
||||
### 6) OperationRun authorization = workspace membership (non-member → 404)
|
||||
|
||||
- **Decision:** Remove/disable these entry points and ensure 404 behavior:
|
||||
- `/admin/register-tenant` (Filament registration page)
|
||||
- `/admin/managed-tenants*` legacy redirects
|
||||
- `/admin/new` redirect
|
||||
- `/admin/w/{workspace}/managed-tenants/onboarding` redirect stub
|
||||
- **Rationale:** FR-001 requires wizard-only entry and “not found” behavior.
|
||||
- **Decision:** Authorize viewing a run by checking membership in the run’s workspace; non-member gets deny-as-not-found (404).
|
||||
- **Rationale:** FR-017a defines access semantics; runs must be viewable tenantlessly before activation.
|
||||
- **Alternatives considered:** Authorize by `Tenant::current()` + matching `run.tenant_id`.
|
||||
- **Why rejected:** Requires tenant routing/selection and breaks tenantless viewing.
|
||||
|
||||
### 7) OperationRun schema = add `workspace_id`, allow tenantless runs, preserve idempotency
|
||||
|
||||
- **Decision:** Add `operation_runs.workspace_id` (FK) and allow `tenant_id` to be nullable for pre-activation operations. Preserve DB-level dedupe using two partial unique indexes:
|
||||
- Tenant-bound runs: `UNIQUE (tenant_id, run_identity_hash) WHERE tenant_id IS NOT NULL AND status IN ('queued', 'running')`
|
||||
- Tenantless runs: `UNIQUE (workspace_id, run_identity_hash) WHERE tenant_id IS NULL AND status IN ('queued', 'running')`
|
||||
- **Rationale:** Enables tenantless operations while preserving race-safe idempotency guarantees.
|
||||
- **Alternatives considered:** Keep `tenant_id` required and always derive workspace via join.
|
||||
- **Why rejected:** Blocks tenantless flows and makes authorization join-dependent.
|
||||
|
||||
### 8) Provider connection ownership = workspace-owned, default 1:1 binding
|
||||
|
||||
- **Decision:** Align Provider Connections to be workspace-owned and (by default) bound to exactly one managed tenant; reuse is disabled by default and policy-gated.
|
||||
- **Rationale:** Matches FR-022/022a/022b and reduces blast radius of credential reuse.
|
||||
- **Alternatives considered:** Keep provider connections tenant-owned.
|
||||
- **Why rejected:** Conflicts with clarified spec ownership model.
|
||||
|
||||
## Open Questions
|
||||
|
||||
- None. All technical unknowns required for planning are resolved.
|
||||
- None for planning; implementation will need to reconcile existing DB schema and policies with the decisions above.
|
||||
|
||||
@ -1,76 +1,84 @@
|
||||
# Feature Specification: Unified Managed Tenant Onboarding Wizard (073)
|
||||
# Feature Specification: Managed Tenant Onboarding Wizard V1 (Enterprise)
|
||||
|
||||
**Feature Branch**: `073-unified-managed-tenant-onboarding-wizard`
|
||||
**Created**: 2026-02-03
|
||||
**Created**: 2026-02-04
|
||||
**Status**: Draft
|
||||
**Input**: User description: "Single, unified onboarding wizard for Managed Tenants (create/attach connection, verify, optional bootstrap), removing all legacy entry points."
|
||||
**Input**: User description: "Spec 073 — Managed Tenant Onboarding Wizard V1 (Enterprise): single workspace-first wizard as source of truth, tenantless until activation; legacy entry points removed; strict 404/403 semantics; verification checklist with tenantless run page; optional bootstrap; enterprise-grade UX and regression tests."
|
||||
|
||||
## Clarifications
|
||||
|
||||
### Session 2026-02-03
|
||||
### Session 2026-02-04
|
||||
|
||||
- Q: Which workspace roles can start the onboarding wizard? → A: Only `owner` and `manager`.
|
||||
- Q: If Provider Connections already exist, what should Step 2 do? → A: Auto-use the existing default connection (and allow switching).
|
||||
- Q: What is the canonical uniqueness key for a Managed Tenant? → A: Unique globally by `tenant_id` (Entra tenant ID) and bound to exactly one workspace.
|
||||
- Q: Which Managed Tenant status values exist in v1? → A: `pending`, `active`, `archived`.
|
||||
- Q: Who can resume an existing onboarding session? → A: Any workspace `owner/manager` with the onboarding capability (shared session per tenant).
|
||||
- Q: Capability granularity for the wizard? → A: Per-step/per-action capabilities (least-privilege). Activation is owner-only; bootstrap actions are separately gated.
|
||||
- Q: For members without capability, should actions be hidden or disabled? → A: Visible but disabled, with tooltip/explanation; server-side remains authoritative.
|
||||
- Q: What is the tenantless “View run” URL pattern? → A: `/admin/operations/{run}` (no workspace in path), access-controlled by run.workspace membership (non-member → 404), no auto workspace switching.
|
||||
- Q: What is the canonical onboarding entry point URL? → A: `/admin/onboarding` (sole entry point in V1; no aliases).
|
||||
|
||||
## User Scenarios & Testing *(mandatory)*
|
||||
|
||||
### User Story 1 - Start Managed Tenant onboarding (Priority: P1)
|
||||
### User Story 1 - Start onboarding from a single entry point (Priority: P1)
|
||||
|
||||
As a workspace member with the required capability, I can start a single guided onboarding flow that creates (or resumes) a Managed Tenant in the current workspace, so that the tenant is always created consistently and safely.
|
||||
As a workspace member, I can open a single onboarding entry point and start (or resume) onboarding for a Managed Tenant in the currently selected workspace, so that tenant onboarding is consistent, workspace-first, and safe.
|
||||
|
||||
**Why this priority**: This is the primary entry point and eliminates inconsistent/unsafe creation paths.
|
||||
**Why this priority**: This is the foundation for all onboarding work and replaces fragmented legacy flows.
|
||||
|
||||
**Independent Test**: Can be fully tested by starting the onboarding in an empty workspace, completing step 1, and confirming a single Managed Tenant exists and is bound to that workspace.
|
||||
**Independent Test**: Can be fully tested by visiting `/admin/onboarding` with and without a selected workspace, completing Step 1, and verifying that a single tenant is created or resumed without duplicates.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a user has selected a workspace and has permission to onboard tenants, **When** they complete “Identify Managed Tenant”, **Then** exactly one Managed Tenant record exists for that workspace and tenant identifier.
|
||||
2. **Given** a user repeats the same step with the same tenant identifier, **When** they submit again, **Then** no duplicate Managed Tenant is created and the existing onboarding session is continued.
|
||||
1. **Given** no workspace is selected, **When** a user visits `/admin/onboarding`, **Then** they are redirected to choose a workspace.
|
||||
2. **Given** a workspace is selected and has no active tenants, **When** a user visits the onboarding entry point, **Then** the onboarding wizard opens directly.
|
||||
3. **Given** a workspace is selected and has at least one active tenant, **When** a user visits the onboarding entry point, **Then** the onboarding wizard is still reachable via an “Add managed tenant” call-to-action.
|
||||
4. **Given** the user identifies a tenant using an Entra Tenant ID that already exists in the same workspace, **When** they submit Step 1 again, **Then** the wizard stays on Step 1 and shows a notification that the tenant already exists with a link to open it.
|
||||
5. **Given** the user provides an Entra Tenant ID that exists in a different workspace, **When** they submit Step 1, **Then** the system responds with deny-as-not-found behavior and the UI shows a generic “Not found” notification (no details leaked).
|
||||
|
||||
---
|
||||
|
||||
### User Story 2 - Configure a connection and verify access (Priority: P2)
|
||||
### User Story 2 - Attach or create a provider connection safely (Priority: P2)
|
||||
|
||||
As a workspace member with the required capability, I can configure (or attach) a Provider Connection for the Managed Tenant and trigger a verification run, so that connectivity and permissions are validated without exposing secrets.
|
||||
As a workspace member, I can choose an existing provider connection or create a new one during onboarding, so that the system has a valid technical connection without exposing secret material.
|
||||
|
||||
**Why this priority**: Without a validated connection, the tenant cannot be safely managed.
|
||||
**Why this priority**: Without a valid connection, verification and activation cannot be completed safely.
|
||||
|
||||
**Independent Test**: Can be tested by completing the “Connection” step and starting a verification run, then asserting the run is created with the expected scope and that no secrets appear in run outputs.
|
||||
**Independent Test**: Can be tested by selecting “Use existing connection” vs “Create new connection”, ensuring secrets are masked and never displayed again, and verifying that onboarding state stores no secrets.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** a Managed Tenant exists in the current workspace, **When** a user configures a connection, **Then** the system stores the connection as configured without ever showing stored secret material back to the user.
|
||||
2. **Given** a user confirms they granted consent, **When** they trigger verification, **Then** a background verification run is started and is visible as “queued / running / succeeded / failed” with a sanitized outcome.
|
||||
1. **Given** the user chooses “Use existing connection”, **When** they select a connection and proceed, **Then** onboarding records the chosen connection and continues.
|
||||
2. **Given** the user chooses “Create new connection”, **When** they input connection details, **Then** any secret input is masked and is not retrievable from the UI later.
|
||||
3. **Given** the user starts Step 2 but leaves before finishing, **When** they resume onboarding later, **Then** only non-secret inputs are prefilled and secret material is never shown.
|
||||
|
||||
---
|
||||
|
||||
### User Story 3 - Resume and complete onboarding (Priority: P3)
|
||||
### User Story 3 - Verify access and review results without tenant-scoped context (Priority: P3)
|
||||
|
||||
As a workspace member, I can resume an incomplete onboarding session and complete optional bootstrap actions, so that interrupted onboarding does not create duplicates and finishes in a “ready” state.
|
||||
As a workspace member, I can start a verification run, manually refresh its status, and view a stored checklist report (including a tenantless “View run” page), so that verification works even before the tenant is activated and without using tenant-scoped routes.
|
||||
|
||||
**Why this priority**: Real onboarding often pauses for consent/approvals; resumability reduces rework and errors.
|
||||
**Why this priority**: Verification is the safety gate that enables activation, and it must work in empty workspaces and pre-activation flows.
|
||||
|
||||
**Independent Test**: Can be tested by starting onboarding, leaving it incomplete, resuming, and finishing; then verifying the tenant is “ready” and optional actions create separate runs.
|
||||
**Independent Test**: Can be tested by starting verification, asserting idempotent dedupe while a run is active, verifying the viewer renders using stored data only, and verifying the “View run” link is tenantless.
|
||||
|
||||
**Acceptance Scenarios**:
|
||||
|
||||
1. **Given** onboarding was started but not completed, **When** the user returns later, **Then** they can resume at the correct step with previously entered (non-secret) state.
|
||||
2. **Given** verification succeeded, **When** the user chooses optional bootstrap actions, **Then** each selected action starts its own background run and onboarding can still be completed.
|
||||
|
||||
---
|
||||
1. **Given** verification has not been started, **When** the user clicks “Start verification”, **Then** a new verification run is started and the UI shows that verification is in progress.
|
||||
2. **Given** a verification run is active, **When** the user clicks “Start verification” again, **Then** the system dedupes the request and does not create a second active run.
|
||||
3. **Given** a verification run is active, **When** the user clicks “Refresh”, **Then** the UI updates status using stored run state.
|
||||
4. **Given** verification completes with any blocking failures, **When** the report is shown, **Then** the step status is “Blocked”.
|
||||
5. **Given** verification completes with warnings but no blocking failures, **When** the report is shown, **Then** the step status is “Needs attention”.
|
||||
6. **Given** verification completes with no warnings and no failures, **When** the report is shown, **Then** the step status is “Ready”.
|
||||
7. **Given** the UI shows a “View run” link, **When** the user clicks it, **Then** it opens a tenantless operations URL (not a tenant-scoped URL).
|
||||
|
||||
### Edge Cases
|
||||
|
||||
- Cross-workspace isolation: a tenant identifier that exists in a different workspace must not be attachable or discoverable (deny-as-not-found).
|
||||
- Missing capability: members without the required capability see disabled UI affordances, and server-side requests are denied.
|
||||
- Roles and capabilities: `operator` and `readonly` members cannot start onboarding by default.
|
||||
- Resume permissions: onboarding can be resumed by any authorized workspace `owner/manager` (not only the initiator).
|
||||
- Verification failures: outcomes must be actionable (reason code + safe message) and never leak tokens/secrets.
|
||||
- Idempotency: repeated submissions or refreshes must not create duplicate tenants, duplicate default connections, or a runaway number of active verification runs.
|
||||
- Last-owner protections: demoting/removing the last owner (workspace or managed tenant) is blocked and recorded for audit.
|
||||
- Visiting legacy entry points returns “not found” behavior (no redirects).
|
||||
- A non-member of the selected workspace receives deny-as-not-found behavior for the onboarding entry point.
|
||||
- A workspace member without the required capability can see the page, but action controls are disabled and show a tooltip; server-side action attempts are denied with 403.
|
||||
- Activation is owner-only: non-owners can see Step 5 but cannot activate; the UI explains “Owner required”, and server-side attempts are denied.
|
||||
- Bootstrap actions are optional and gated independently per action; non-authorized users cannot start them.
|
||||
- The wizard must not generate or require tenant-scoped links before activation.
|
||||
- Manual refresh should not trigger external network calls; it may only re-read stored status/report.
|
||||
- Verification report content must never contain secrets/tokens, raw headers, or credential material.
|
||||
- Completing onboarding while verification is blocked is prevented unless an explicit override policy applies.
|
||||
|
||||
## Requirements *(mandatory)*
|
||||
|
||||
@ -91,95 +99,91 @@ ## Requirements *(mandatory)*
|
||||
- ensure destructive-like actions require confirmation (`->requiresConfirmation()`),
|
||||
- include at least one positive and one negative authorization test, and note any RBAC regression tests added/updated.
|
||||
|
||||
**Authorization plane(s) involved (filled for this feature):**
|
||||
- **Tenant plane (Entra users)** only. This feature adds tenantless, workspace-scoped routes under `/admin/*` (`/admin/onboarding`, `/admin/operations/{run}`) that must still enforce tenant-plane membership and capability rules.
|
||||
- **Platform plane (`/system`) is out of scope**. No cross-plane navigation is introduced; deny-as-not-found (404) semantics remain the default for non-members / not entitled.
|
||||
|
||||
**Constitution alignment (OPS-EX-AUTH-001):** OIDC/SAML login handshakes may perform synchronous outbound HTTP (e.g., token exchange)
|
||||
on `/auth/*` endpoints without an `OperationRun`. This MUST NOT be used for Monitoring/Operations pages.
|
||||
|
||||
**Constitution alignment (BADGE-001):** If this feature changes status-like badges (status/outcome/severity/risk/availability/boolean),
|
||||
the spec MUST describe how badge semantics stay centralized (no ad-hoc mappings) and which tests cover any new/changed values.
|
||||
|
||||
### Scope & Assumptions
|
||||
|
||||
**In scope (v1)**
|
||||
|
||||
- A single onboarding wizard to create or resume onboarding of a Managed Tenant within a selected workspace.
|
||||
- Configure or attach a Provider Connection, guide consent, start verification runs, and optionally start bootstrap runs.
|
||||
- Completion marks the tenant as ready/active and routes the user to the tenant details.
|
||||
- Removal of all legacy UI entry points for creating/onboarding tenants (no redirects).
|
||||
|
||||
**Out of scope (v1)**
|
||||
|
||||
- User invitation workflows.
|
||||
- Group-based auto-provisioning.
|
||||
- Full compliance/evidence reporting.
|
||||
- Cloud resource provisioning.
|
||||
|
||||
**Dependencies**
|
||||
|
||||
- Workspace selection/context and workspace membership.
|
||||
- A managed-tenant concept bound to exactly one workspace.
|
||||
- Provider Connections and secure credential storage.
|
||||
- A run system to track verification and bootstrap actions.
|
||||
- Audit logging and a canonical capability registry.
|
||||
|
||||
**Assumptions**
|
||||
|
||||
- Default policy: the onboarding initiator becomes workspace manager and managed-tenant owner (or the closest minimum-privilege equivalents).
|
||||
- “Not found” behavior is used to avoid leaking the existence of out-of-scope tenants.
|
||||
|
||||
### Acceptance Coverage
|
||||
|
||||
The following acceptance coverage is required to treat the feature as complete:
|
||||
|
||||
- Legacy entry points removed (not found behavior).
|
||||
- Workspace isolation enforced (cross-workspace attach/visibility prevented).
|
||||
- Idempotency verified (no duplicates created by repeated submissions).
|
||||
- Verification run creation and sanitized failure reporting.
|
||||
- Last-owner protections enforced and auditable.
|
||||
|
||||
### Functional Requirements
|
||||
|
||||
- **FR-001 (Single entry point)**: System MUST provide exactly one UI flow to onboard a Managed Tenant (the onboarding wizard), and all other “add tenant” entry points MUST be removed and behave as “not found”.
|
||||
- **FR-002 (Workspace-first enforcement)**: System MUST require an active workspace context for onboarding and tenant-scoped access.
|
||||
- **FR-003 (Hard isolation)**: System MUST deny-as-not-found (404 semantics) when a Managed Tenant does not belong to the current workspace, including for attempts to attach an existing tenant identifier from another workspace.
|
||||
- **FR-004 (Authorization semantics)**: System MUST enforce authorization server-side for all onboarding mutations and run-start actions. Non-member / not entitled to tenant scope MUST be treated as 404 semantics; a member lacking the required capability MUST be treated as 403 semantics. By default, only workspace `owner` and `manager` can start the onboarding wizard.
|
||||
- **FR-005 (Capabilities-first)**: System MUST authorize via canonical capabilities (not role string comparisons in feature code).
|
||||
- **FR-006 (Idempotent tenant identification)**: System MUST upsert tenant identification by a stable tenant identifier within the workspace, so repeating step 1 never creates duplicates.
|
||||
- **FR-006a (Tenant uniqueness key)**: System MUST enforce a single Managed Tenant globally per `tenant_id` (Entra tenant ID) and bind it to exactly one workspace.
|
||||
- **FR-007 (Onboarding session resumability)**: System MUST persist onboarding state (excluding secret material) so the flow can be resumed after interruption without data inconsistency.
|
||||
- **FR-007a (Shared resumability)**: An onboarding session MUST be resumable by any authorized workspace `owner/manager` with the onboarding capability (not only the user who started it).
|
||||
- **FR-008 (Connection handling)**: System MUST allow creating or attaching a Provider Connection during onboarding and MUST never display stored secret material back to users; UI MUST only show safe configuration indicators (e.g., configured yes/no, last rotation timestamp).
|
||||
- **FR-008a (Default connection selection)**: If one or more Provider Connections already exist for the Managed Tenant, Step 2 MUST auto-select the default connection and MAY allow the user to switch to a different existing connection.
|
||||
- **FR-009 (Verification as runs)**: System MUST start verification as a background run with clear status and a sanitized result (reason code + short safe message).
|
||||
- **FR-010 (DB-only UI rendering)**: System MUST render onboarding UI using only stored data; any external calls required for verification MUST occur only in background work.
|
||||
- **FR-011 (Operational clarity)**: System MUST display verification outcomes and missing requirements in a user-actionable way (what is missing, what to do next) without leaking sensitive details.
|
||||
- **FR-012 (Optional bootstrap actions)**: System MUST support optional post-verify bootstrap actions that each start their own background run and do not block completion unless explicitly selected.
|
||||
- **FR-013 (Completion state)**: System MUST mark the Managed Tenant as ready/active only after successful verification, and MUST redirect users to the Managed Tenant details view upon completion.
|
||||
- **FR-013a (Status model)**: System MUST use a v1 Managed Tenant lifecycle with statuses: `pending` (created/onboarding), `active` (ready), `archived` (no longer managed).
|
||||
- **FR-014 (Membership bootstrap)**: System MUST ensure the onboarding initiator receives the minimum required memberships in the workspace and the managed tenant scope according to policy (default: workspace manager + tenant owner).
|
||||
- **FR-015 (Last-owner protections)**: System MUST block demotion/removal of the last owner at both workspace scope and managed tenant scope, and MUST record the blocked attempt for audit.
|
||||
- **FR-016 (Auditability)**: System MUST record audit events for tenant creation, connection creation/rotation, verification start/result, membership changes, and last-owner blocks.
|
||||
- **FR-001 (Single onboarding entry point)**: The system MUST provide a single onboarding entry point at `/admin/onboarding` that is the source of truth for onboarding.
|
||||
- **FR-002 (Workspace required)**: If no workspace is selected, the onboarding entry point MUST redirect the user to a workspace chooser.
|
||||
- **FR-003 (Workspace landing behavior)**: With a selected workspace, the system MUST:
|
||||
- open the wizard directly when the workspace has zero active tenants, and
|
||||
- keep the wizard reachable via an “Add managed tenant” call-to-action when the workspace has one or more active tenants.
|
||||
- **FR-004 (Remove legacy entry points)**: The following legacy entry points MUST NOT exist and MUST return “not found” behavior (no redirects):
|
||||
- `/admin/new`
|
||||
- any legacy tenant-scoped create entry point
|
||||
- `/admin/managed-tenants/onboarding` (legacy)
|
||||
- **FR-005 (Membership boundary)**: A non-member of the selected workspace MUST always receive deny-as-not-found behavior for onboarding and for any workspace-visible operations.
|
||||
- **FR-006 (Capability boundary)**: A workspace member without the required capability MUST be able to view the page, but action controls MUST be disabled with an explanatory tooltip; server-side action attempts MUST be denied with 403.
|
||||
- **FR-006d (Discoverability default)**: In V1, capability-gated controls SHOULD remain visible but disabled with an explanation (rather than being hidden), to support enterprise operator workflows.
|
||||
- **FR-006a (Least-privilege capability model)**: The wizard MUST gate each step and each action by canonical capabilities (no ad-hoc role string checks).
|
||||
- **FR-006b (Wizard capability breakdown)**: The system MUST support, at minimum, distinct capability gates for:
|
||||
- identifying / creating / resuming onboarding for a managed tenant,
|
||||
- viewing/selecting a provider connection,
|
||||
- creating/editing a provider connection,
|
||||
- starting verification,
|
||||
- running each optional bootstrap action (inventory sync, policy sync, backup bootstrap) independently,
|
||||
- activating a tenant.
|
||||
- **FR-006c (Viewer visibility)**: Viewing verification reports and operation-run results MUST be permitted to workspace members (subject to workspace membership), even when they cannot start runs.
|
||||
- **FR-007 (Workspace↔tenant match hard rule)**: For any tenant-scoped route, if the tenant does not belong to the currently selected workspace, the system MUST return deny-as-not-found behavior.
|
||||
- **FR-008 (Tenantless wizard until activation)**: The wizard MUST not require tenant-scoped pages, routes, or links before the final “Complete / Activate” step.
|
||||
- **FR-009 (Identify managed tenant inputs)**: Step 1 MUST capture, at minimum:
|
||||
- tenant name,
|
||||
- environment,
|
||||
- Entra Tenant ID,
|
||||
- optional primary domain,
|
||||
- optional notes.
|
||||
- **FR-010 (Idempotent identification)**: Step 1 MUST be idempotent for the same tenant identifier within the same workspace and MUST resume an active onboarding session when applicable.
|
||||
- **FR-011 (Uniqueness of Entra Tenant ID)**: The system MUST enforce Entra Tenant ID uniqueness globally, and each Entra Tenant ID MUST be bound to exactly one workspace in V1.
|
||||
- **FR-012 (Tenant status model)**: Managed Tenants MUST support a v1 lifecycle including: `draft`, `onboarding`, `active`, `archived`.
|
||||
- **FR-013 (Provider connection choice)**: Step 2 MUST let the user either use an existing connection or create a new connection.
|
||||
- **FR-014 (Secret safety)**: Any secret material entered during connection creation MUST be masked, stored securely, and MUST never be displayed again. Onboarding session state MUST not store secret material.
|
||||
- **FR-015 (Verification run start)**: Step 3 MUST allow starting a verification run and MUST dedupe requests while an active verification run exists.
|
||||
- **FR-016 (Verification viewer behavior)**: Step 3 MUST display a stored checklist report with:
|
||||
- an “in progress” banner while a run is active,
|
||||
- a manual “Refresh” control,
|
||||
- status mapping: blocking failures → Blocked; warnings-only → Needs attention; otherwise → Ready,
|
||||
- “Next steps” as links only (no server-side actions in V1).
|
||||
- **FR-017 (Tenantless operations page)**: The wizard’s “View run” link MUST point to `/admin/operations/{run}` and MUST never use a tenant-scoped operations URL.
|
||||
- **FR-017a (Tenantless access semantics)**: Access to `/admin/operations/{run}` MUST be granted only if the user is a member of the run’s workspace; otherwise the system MUST respond with deny-as-not-found behavior. The page MUST NOT require a pre-selected workspace context and MUST NOT auto-switch workspaces.
|
||||
- **FR-018 (Workspace-visible operations)**: Operation runs started by the wizard MUST be safely viewable in a workspace context without tenant-scoped routing and MUST honor the same deny-as-not-found membership boundary.
|
||||
- **FR-019 (Optional bootstrap step)**: Step 4 MAY offer optional bootstrap actions (e.g., inventory sync, policy sync, baseline creation) with per-action capability gating; each selected action MUST start its own operation run and be viewable tenantlessly.
|
||||
- **FR-020 (Complete / Activate gate)**: The wizard MUST only allow activation when a provider connection exists and verification is not Blocked, except when a workspace owner explicitly overrides the block.
|
||||
- **FR-020a (Override requirements)**: When overriding a blocked verification, the system MUST require a human-entered reason and MUST record an audit event capturing the override decision and reason.
|
||||
- **FR-020b (Owner-only activation)**: Activation MUST be restricted to workspace owners (non-owner members may not activate, even if they can run earlier steps).
|
||||
- **FR-021 (Activation outcome)**: On activation, the tenant MUST become visible in the workspace tenant switcher and the user MUST be redirected either to the tenant home (open now) or back to the workspace managed tenant list.
|
||||
- **FR-022 (Connection ownership model)**: Provider connections MUST be workspace-owned.
|
||||
- **FR-022a (Safe default binding)**: By default in V1, a provider connection MUST be bound to exactly one managed tenant.
|
||||
- **FR-022b (Reuse safety gate)**: Reuse of an existing provider connection for additional managed tenants MUST be disabled by default and MUST only be possible via an explicit opt-in that clearly communicates risk and is policy-gated.
|
||||
- **FR-023 (Auditability)**: The system MUST record audit events for: tenant identification, connection creation/updates, verification start/completion, bootstrap run start/completion, and activation.
|
||||
- **FR-024 (DB-only rendering)**: The wizard and the verification viewer MUST render using stored data only; any external checks MUST run as background work.
|
||||
- **FR-025 (Badge semantics)**: Step-status and verification-result chips MUST use centralized badge semantics (no per-page ad-hoc mappings), and changes MUST be covered by automated tests.
|
||||
- **FR-026 (Graph contract path)**: Any Microsoft Graph call made by verification/bootstrap runs MUST go through the canonical contract registry path (`GraphClientInterface` + `config/graph_contracts.php`). Feature code MUST NOT hardcode ad-hoc endpoints; missing contracts MUST fail safe and be covered by automated tests.
|
||||
|
||||
### Key Entities *(include if feature involves data)*
|
||||
|
||||
- **Workspace**: A portfolio/customer context that owns memberships and one or more Managed Tenants.
|
||||
- **Managed Tenant**: A managed Entra/Intune tenant, uniquely identified within a workspace by an external tenant identifier, with lifecycle status (e.g., pending/ready/archived).
|
||||
- Uniqueness: exactly one globally per `tenant_id` (Entra tenant ID), bound to exactly one workspace.
|
||||
- Status values (v1): `pending`, `active`, `archived`.
|
||||
- **Provider Connection**: A technical connection configuration that enables access to a Managed Tenant; includes secure credentials/configuration metadata and enabled/default flags.
|
||||
- **Onboarding Session**: A persistent record of onboarding progress and safe state to support resumability and idempotency.
|
||||
- **Verification Run**: A background run that validates connectivity and required permissions and produces a sanitized outcome.
|
||||
- **Membership (Workspace-scoped / Tenant-scoped)**: Defines who can see and operate within a workspace and on a specific managed tenant.
|
||||
- **Workspace**: A portfolio context that a user selects; controls membership and owns one or more managed tenants.
|
||||
- **Managed Tenant**: A record representing a Microsoft tenant managed by the organization; includes identity (Entra Tenant ID), environment, and lifecycle status.
|
||||
- **Onboarding Session**: A resumable record of onboarding progress and safe, non-secret state.
|
||||
- **Provider Connection**: A technical connection configuration used to access tenant data; includes secret material that must never be displayed after capture.
|
||||
- **Operation Run**: A trackable background run started by the wizard (verification and optional bootstrap actions) with a stored report suitable for safe, tenantless viewing.
|
||||
- **Verification Report**: A stored checklist result with per-check statuses, safe messages, evidence pointers, and “next steps” links.
|
||||
|
||||
## Success Criteria *(mandatory)*
|
||||
|
||||
### Measurable Outcomes
|
||||
|
||||
- **SC-001 (Time-to-onboard)**: A workspace admin can complete the wizard up to starting verification in under 3 minutes (excluding external consent/approval waiting time).
|
||||
- **SC-002 (Idempotency)**: Re-running any wizard step does not create duplicates (0 duplicate tenants per tenant identifier per workspace; 0 duplicate default connections per tenant).
|
||||
- **SC-003 (Authorization correctness)**: For all onboarding endpoints/actions, non-members see no discoverability and get 404 semantics; members without capability get 403 semantics; authorized users can complete the flow.
|
||||
- **SC-004 (Secret safety)**: No secrets/tokens are present in run outputs, notifications, audit entries, or error messages (validated by automated tests that assert redaction/sanitization behavior).
|
||||
- **SC-005 (Operational clarity)**: When verification fails, users can identify the failure reason category (via reason code + safe message) and see the next step without contacting support.
|
||||
|
||||
### Badge Semantics (BADGE-001)
|
||||
|
||||
- Managed Tenant status badges MUST map from the canonical status set (`pending`, `active`, `archived`) using a centralized mapping (no ad-hoc per-page mapping).
|
||||
- **SC-001 (Single entry point adoption)**: 100% of managed-tenant onboarding starts from the single onboarding entry point; legacy URLs return “not found” behavior.
|
||||
- **SC-002 (Time to first verification)**: A workspace admin can reach “verification started” within 3 minutes of opening onboarding (excluding external consent/approval wait time).
|
||||
- **SC-003 (No pre-activation tenant-scoped routing)**: Before activation, the wizard never generates tenant-scoped URLs; this is validated by regression tests.
|
||||
- **SC-004 (Authorization correctness)**: Non-members consistently receive deny-as-not-found behavior; members lacking capability receive 403 on action attempts; authorized users complete onboarding.
|
||||
- **SC-005 (Idempotency)**: For repeated Step 1 submissions with the same Entra Tenant ID in the same workspace, no duplicates are created and the user resumes the existing onboarding session.
|
||||
- **SC-006 (Secret safety)**: No secret material appears in UI, reports, notifications, logs, or audit events; validated by automated tests.
|
||||
- **SC-007 (Operational clarity)**: When verification is blocked, at least 90% of users can identify the reason category and next step from the report without opening a support ticket (measured via internal feedback or support tagging).
|
||||
|
||||
@ -1,159 +1,184 @@
|
||||
---
|
||||
|
||||
description: "Tasks for Unified Managed Tenant Onboarding Wizard (073)"
|
||||
description: "Tasks for Managed Tenant Onboarding Wizard V1 (Enterprise) (073)"
|
||||
---
|
||||
|
||||
# Tasks: Unified Managed Tenant Onboarding Wizard (073)
|
||||
# Tasks: Managed Tenant Onboarding Wizard V1 (Enterprise)
|
||||
|
||||
**Input**: Design documents from `specs/073-unified-managed-tenant-onboarding-wizard/`
|
||||
**Prerequisites**: plan.md (required), spec.md (required), research.md, data-model.md, contracts/
|
||||
|
||||
**Tests**: Required (Pest). Use `vendor/bin/sail artisan test --compact ...`.
|
||||
|
||||
## Phase 1: Setup
|
||||
---
|
||||
|
||||
- [X] T001 Confirm Sail is running and DB is reachable using docker-compose.yml (command: `vendor/bin/sail up -d`)
|
||||
- [X] T002 Confirm baseline tests pass for the branch using phpunit.xml and tests/ (command: `vendor/bin/sail artisan test --compact`)
|
||||
## Phase 1: Setup (Shared Infrastructure)
|
||||
|
||||
**Purpose**: Confirm baseline environment is ready for implementing and testing runtime behavior changes.
|
||||
|
||||
- [x] T001 Confirm Sail is running using docker-compose.yml (command: `vendor/bin/sail up -d`)
|
||||
- [x] T002 Run a baseline test subset using phpunit.xml and tests/ (command: `vendor/bin/sail artisan test --compact`)
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Foundational (Blocking Prerequisites)
|
||||
|
||||
**Purpose**: Shared primitives required by all user stories (authz, data model, safety semantics).
|
||||
**Purpose**: Shared primitives required by all user stories (capabilities, resumable session model, tenant status semantics).
|
||||
|
||||
- [X] T003 Add onboarding capability constant in app/Support/Auth/Capabilities.php
|
||||
- [X] T004 Add onboarding capability mapping for Owner+Manager in app/Services/Auth/WorkspaceRoleCapabilityMap.php
|
||||
- [X] T005 Implement Gate/Policy for onboarding authorization in app/Providers/AuthServiceProvider.php (enforce capabilities; no role-string checks)
|
||||
- [X] T006 [P] Create TenantOnboardingSession model in app/Models/TenantOnboardingSession.php
|
||||
- [X] T007 Create onboarding sessions migration in database/migrations/*_create_tenant_onboarding_sessions_table.php (unique workspace_id + tenant_id)
|
||||
- [X] T008 Create tenant workspace binding migration in database/migrations/*_enforce_tenant_workspace_binding.php (ensure tenants.workspace_id is NOT NULL + FK; ensure tenants.tenant_id remains globally unique; deny cross-workspace duplicates)
|
||||
- [X] T009 Verify tenant routing key strategy for v1: keep existing Filament tenant route-key stable (do NOT change external_id strategy in this feature); add a regression test that /admin/t/{tenant} continues to resolve the intended managed tenant
|
||||
- [X] T010 [P] Add foundational authorization + data-model tests in tests/Feature/ManagedTenantOnboardingWizardTest.php (capability known, mapping correct, migrations applied)
|
||||
- [x] T003 Define wizard capabilities (per-step/per-action) in app/Support/Auth/Capabilities.php
|
||||
- [x] T004 [P] Map wizard capabilities to roles (least privilege) in app/Services/Auth/WorkspaceRoleCapabilityMap.php
|
||||
- [x] T005 Implement server-side authorization checks for wizard actions in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (no role-string checks)
|
||||
- [x] T006 Ensure Tenant lifecycle supports `draft|onboarding|active|archived` in app/Models/Tenant.php
|
||||
- [x] T007 Update onboarding session schema to match data-model (safe state only) in app/Models/TenantOnboardingSession.php
|
||||
- [x] T008 Update onboarding session migration constraints for idempotency in database/migrations/2026_02_04_090010_update_tenant_onboarding_sessions_constraints.php
|
||||
- [x] T009 [P] Add foundational capability + tenant lifecycle tests in tests/Feature/Onboarding/OnboardingFoundationsTest.php
|
||||
|
||||
**Checkpoint**: Foundational complete — user story work can begin.
|
||||
**Checkpoint**: Foundation ready — user story implementation can begin.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: User Story 1 — Start Managed Tenant onboarding (Priority: P1) 🎯 MVP
|
||||
## Phase 3: User Story 1 — Single entry point onboarding (Priority: P1) 🎯 MVP
|
||||
|
||||
**Goal**: Start or resume a workspace-scoped onboarding wizard and create exactly one Managed Tenant per global-unique `tenant_id` (Entra tenant ID), bound to exactly one workspace.
|
||||
**Goal**: Provide `/admin/onboarding` as the sole onboarding entry point, redirect to workspace chooser if none selected, and implement Step 1 idempotent identification with strict 404/403 semantics.
|
||||
|
||||
**Independent Test**: Start onboarding in an empty workspace and complete “Identify Managed Tenant”; assert exactly one tenant exists and a session is created/resumed.
|
||||
**Independent Test**: Visit `/admin/onboarding` with and without a selected workspace, complete Step 1, and verify exactly one tenant/session is created and cross-workspace attempts behave as 404.
|
||||
|
||||
- [X] T011 [P] [US1] Add wizard page class in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (Filament v5 / Livewire v4)
|
||||
- [X] T012 [P] [US1] Add wizard view in resources/views/filament/pages/workspaces/managed-tenant-onboarding-wizard.blade.php
|
||||
- [X] T013 [US1] Register wizard route in routes/web.php at `/admin/w/{workspace}/managed-tenants/onboarding` with `ensure-workspace-member` middleware and 404 semantics for non-members
|
||||
- [X] T014 [US1] Implement wizard mount + workspace loading in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (abort 404 for non-member, 403 for missing onboarding capability)
|
||||
- [X] T015 [US1] Implement Step 1 “Identify Managed Tenant” upsert in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (transactional; idempotent by workspace_id + tenant_id; tenant status `pending`)
|
||||
- [X] T015b [US1] Enforce cross-workspace uniqueness in Step 1: if a tenant with the same tenant_id exists in a different workspace, deny-as-not-found (404) and do not create/update anything
|
||||
- [X] T015c [US1] Membership bootstrap: after tenant upsert, ensure the initiating user has a Managed Tenant membership of role owner (create if missing); never allow tenant to end up with zero owners
|
||||
- [X] T016 [US1] Persist/resume onboarding session in app/Models/TenantOnboardingSession.php (no secrets in state)
|
||||
- [X] T017 [US1] Add audit events for onboarding start/resume in app/Services/Audit/WorkspaceAuditLogger.php (or existing audit service) and call from wizard actions
|
||||
- [X] T018 [P] [US1] Add happy-path tests in tests/Feature/ManagedTenantOnboardingWizardTest.php (owner/manager can start; tenant created; session created)
|
||||
- [X] T019 [P] [US1] Add negative auth tests in tests/Feature/ManagedTenantOnboardingWizardTest.php (non-member gets 404; member without capability gets 403)
|
||||
- [X] T020 [P] [US1] Add idempotency tests in tests/Feature/ManagedTenantOnboardingWizardTest.php (repeat step does not create duplicates)
|
||||
- [X] T020b [P] [US1] Add tests asserting membership bootstrap: newly created tenant has exactly one owner membership for the initiator; attempting to remove/demote the last owner is blocked (can be a minimal service/policy-level assertion)
|
||||
- [X] T020c [P] [US1] Add tests asserting cross-workspace protection: if tenant_id exists under another workspace, the wizard returns 404 and does not reveal the existence of that tenant
|
||||
### Tests (write first)
|
||||
|
||||
### Remove legacy entry points (required by FR-001)
|
||||
- [x] T010 [P] [US1] Add entry-point routing tests in tests/Feature/Onboarding/OnboardingEntryPointTest.php
|
||||
- [x] T011 [P] [US1] Add RBAC semantics tests (404 non-member, disabled UI + 403 action) in tests/Feature/Onboarding/OnboardingRbacSemanticsTest.php
|
||||
- [x] T012 [P] [US1] Add idempotency + cross-workspace isolation tests in tests/Feature/Onboarding/OnboardingIdentifyTenantTest.php
|
||||
|
||||
- [X] T021 [US1] Remove tenant registration from app/Providers/Filament/AdminPanelProvider.php (drop `->tenantRegistration(...)`)
|
||||
- [X] T022 [US1] Remove `/admin/register-tenant` route from routes/web.php (must behave as not found)
|
||||
- [X] T023 [US1] Replace legacy onboarding redirects with 404 in routes/web.php (`/admin/managed-tenants`, `/admin/managed-tenants/onboarding`, `/admin/new`, workspace onboarding redirect stub)
|
||||
- [X] T024 [US1] Remove RegisterTenant references in app/Filament/Pages/ChooseTenant.php and app/Filament/Pages/Workspaces/ManagedTenantsLanding.php
|
||||
- [X] T025 [P] [US1] Add regression tests in tests/Feature/ManagedTenantOnboardingWizardTest.php asserting legacy endpoints return 404 (no redirects)
|
||||
### Implementation
|
||||
|
||||
- [x] T013 [US1] Make `/admin/onboarding` the canonical wizard route in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (set slug; remove workspace route parameter dependency)
|
||||
- [x] T014 [US1] Resolve the current workspace from session context in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (redirect when missing; 404 when non-member)
|
||||
- [x] T015 [US1] Keep page visible for members without capability (disable controls + tooltip) in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T016 [US1] Implement Step 1 inputs per spec (tenant name, environment, Entra Tenant ID, optional domain/notes) in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T017 [US1] Implement Step 1 idempotent upsert + onboarding session resume (deny-as-not-found if tenant exists in another workspace) in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T018 [US1] Ensure no pre-activation tenant-scoped links are generated in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
|
||||
**Checkpoint**: US1 complete — wizard is the only entry point; onboarding start is safe + idempotent.
|
||||
### Remove legacy entry points (must be true 404, no redirects)
|
||||
|
||||
- [x] T019 [US1] Remove tenant registration surface from app/Providers/Filament/AdminPanelProvider.php (drop `->tenantRegistration(...)` if present)
|
||||
- [x] T020 [US1] Remove/404 legacy routes in routes/web.php (`/admin/new`, `/admin/register-tenant`, `/admin/managed-tenants/onboarding`)
|
||||
- [x] T021 [P] [US1] Add legacy route regression tests in tests/Feature/Onboarding/OnboardingLegacyRoutesTest.php
|
||||
|
||||
**Checkpoint**: US1 complete — `/admin/onboarding` is canonical, legacy entry points are 404, and Step 1 is safe + idempotent.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: User Story 2 — Configure a connection and verify access (Priority: P2)
|
||||
## Phase 4: User Story 2 — Provider connection selection/creation (Priority: P2)
|
||||
|
||||
**Goal**: Attach or create a Provider Connection and start verification as an `OperationRun` without leaking secrets.
|
||||
**Goal**: Allow selecting an existing workspace-owned provider connection or creating a new one, without ever re-displaying secrets.
|
||||
|
||||
**Independent Test**: Select/create connection, start verification, assert an OperationRun is created and job is dispatched; assert no secret material is returned.
|
||||
**Independent Test**: Complete Step 2 in both modes (existing vs new), verify the onboarding session stores only non-secret state, and verify the provider connection is workspace-scoped and bound to the managed tenant by default.
|
||||
|
||||
- [X] T026 [US2] Implement Step 2 connection selection in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (auto-select default connection; allow switching)
|
||||
- [X] T027 [US2] Implement connection creation path in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php using app/Models/ProviderConnection.php and app/Services/Providers/CredentialManager.php (never display stored secrets)
|
||||
- [X] T028 [US2] Persist selected connection id in app/Models/TenantOnboardingSession.php `state` (non-secret)
|
||||
- [X] T029 [US2] Implement “Start verification” action using app/Services/Providers/ProviderOperationStartGate.php with operation type `provider.connection.check`
|
||||
- [X] T029b [US2] Enforce/verify dedupe: clicking “Start verification” twice while an active run exists must return the active OperationRun (no second run created); add a focused test (Bus::fake + assert single run)
|
||||
- [X] T030 [US2] Ensure verification enqueues app/Jobs/ProviderConnectionHealthCheckJob.php and stores `operation_run_id` in onboarding session state
|
||||
- [X] T031 [US2] Add “View run” navigation to app/Filament/Resources/OperationRunResource.php (link from wizard action notification)
|
||||
- [X] T032 [P] [US2] Add tests in tests/Feature/ManagedTenantOnboardingWizardTest.php for connection default selection + switching
|
||||
- [X] T033 [P] [US2] Add tests in tests/Feature/ManagedTenantOnboardingWizardTest.php for verification run creation + job dispatch (Bus::fake)
|
||||
- [X] T034 [P] [US2] Add secret-safety tests in tests/Feature/ManagedTenantOnboardingWizardTest.php (no secret fields appear in response/session/run failure summary)
|
||||
### Tests (write first)
|
||||
|
||||
**Checkpoint**: US2 complete — verification is observable via OperationRun and secrets are safe.
|
||||
- [x] T022 [P] [US2] Add connection selection/creation tests in tests/Feature/Onboarding/OnboardingProviderConnectionTest.php
|
||||
- [x] T023 [P] [US2] Add secret-safety regression tests in tests/Feature/Onboarding/OnboardingSecretSafetyTest.php
|
||||
|
||||
### Implementation
|
||||
|
||||
- [x] T024 [US2] Implement workspace-owned ProviderConnection schema changes in database/migrations/2026_02_04_090020_make_provider_connections_workspace_owned.php
|
||||
- [x] T025 [US2] Update ProviderConnection model relationships + scoping in app/Models/ProviderConnection.php
|
||||
- [x] T026 [US2] Update ProviderConnection authorization for workspace scope in app/Policies/ProviderConnectionPolicy.php
|
||||
- [x] T027 [US2] Update ProviderConnection admin resource scoping in app/Filament/Resources/ProviderConnectionResource.php
|
||||
- [x] T028 [US2] Update Step 2 schema + persistence (no secrets in onboarding session state) in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T029 [US2] Store provider_connection_id in onboarding session safe state in app/Models/TenantOnboardingSession.php
|
||||
|
||||
**Checkpoint**: US2 complete — Provider connections are workspace-owned, default-bound to one tenant, and secrets are never re-shown.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: User Story 3 — Resume and complete onboarding (Priority: P3)
|
||||
## Phase 5: User Story 3 — Verification + tenantless run viewing + activation (Priority: P3)
|
||||
|
||||
**Goal**: Resume an onboarding session, run optional bootstrap actions, and complete onboarding to activate the tenant.
|
||||
**Goal**: Start verification as an `OperationRun`, render DB-only reports with correct status mapping, and support tenantless viewing at `/admin/operations/{run}` without requiring selected workspace or tenant context.
|
||||
|
||||
**Independent Test**: Start onboarding, leave incomplete, resume as a different authorized owner/manager, complete verification + bootstrap, then mark tenant active.
|
||||
**Independent Test**: Start verification from the wizard, dedupe active runs, open `/admin/operations/{run}` without a selected workspace, and enforce membership-based 404 semantics.
|
||||
|
||||
- [X] T035 [US3] Implement session resume logic in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (load by workspace_id + tenant_id; shared resumability)
|
||||
- [X] T036 [US3] Implement Step gating in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (cannot complete until verification succeeded)
|
||||
- [X] T037 [US3] Implement optional bootstrap actions in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php (start operations listed in app/Services/Providers/ProviderOperationRegistry.php)
|
||||
- [X] T038 [US3] Persist bootstrap `operation_run_id`s in app/Models/TenantOnboardingSession.php `state`
|
||||
- [X] T039 [US3] Implement completion: set tenant status `active`, set onboarding session `completed_at`, redirect to tenant dashboard (app/Filament/Pages/TenantDashboard.php)
|
||||
- [X] T040 [P] [US3] Add tests in tests/Feature/ManagedTenantOnboardingWizardTest.php for resume by different authorized actor
|
||||
- [X] T041 [P] [US3] Add tests in tests/Feature/ManagedTenantOnboardingWizardTest.php for completion and tenant status transition `pending` → `active`
|
||||
- [X] T042 [P] [US3] Add tests in tests/Feature/ManagedTenantOnboardingWizardTest.php for bootstrap run creation (one OperationRun per selected action)
|
||||
### Tests (write first)
|
||||
|
||||
**Checkpoint**: US3 complete — onboarding is resumable and completes safely.
|
||||
- [x] T030 [P] [US3] Add tenantless run viewer access tests in tests/Feature/Operations/TenantlessOperationRunViewerTest.php
|
||||
- [x] T031 [P] [US3] Add verification start + dedupe tests in tests/Feature/Onboarding/OnboardingVerificationTest.php
|
||||
- [x] T032 [P] [US3] Add owner-only activation + override audit tests in tests/Feature/Onboarding/OnboardingActivationTest.php
|
||||
- [x] T052 [P] [US3] Add Graph contract registry coverage tests (organization + service principal permission probes) in tests/Unit/GraphContractRegistryOnboardingProbesTest.php
|
||||
|
||||
### Implementation — tenantless operation run viewer
|
||||
|
||||
- [x] T033 [US3] Add OperationRun workspace scoping fields + idempotency indexes in database/migrations/2026_02_04_090030_add_workspace_id_to_operation_runs_table.php
|
||||
- [x] T034 [US3] Update OperationRun model for workspace relationship + nullable tenant_id in app/Models/OperationRun.php
|
||||
- [x] T035 [US3] Update run identity/dedupe logic for tenantless runs in app/Services/OperationRunService.php
|
||||
- [x] T036 [US3] Exempt `/admin/operations/{run}` from forced workspace selection in app/Http/Middleware/EnsureWorkspaceSelected.php
|
||||
- [x] T037 [US3] Prevent tenant auto-selection side effects for `/admin/operations/{run}` in app/Support/Middleware/EnsureFilamentTenantSelected.php
|
||||
- [x] T038 [US3] Authorize viewing runs by workspace membership (non-member → 404) in app/Policies/OperationRunPolicy.php
|
||||
- [x] T039 [US3] Implement tenantless `/admin/operations/{run}` viewer page + route with membership-based 404 semantics (app/Filament/Pages/Operations/TenantlessOperationRunViewer.php, routes/web.php)
|
||||
|
||||
### Implementation — verification + report + activation
|
||||
|
||||
- [x] T053 [US3] Register onboarding verification probe endpoints in config/graph_contracts.php (organization + service principal permission lookups)
|
||||
- [x] T054 [US3] Refactor verification probe calls to resolve endpoints via GraphContractRegistry (no ad-hoc Graph paths; fail safe if contract missing) in app/Services/Graph/MicrosoftGraphClient.php and app/Services/Providers/ProviderGateway.php
|
||||
- [x] T040 [US3] Implement Step 3 start verification (OperationRun + queued job) with 403 on capability denial in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T041 [US3] Implement active-run dedupe (queued/running) and persist run IDs in app/Models/TenantOnboardingSession.php
|
||||
- [x] T042 [US3] Implement DB-only “Refresh” and status mapping (Blocked/Needs attention/Ready) in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T055 [US3] Render a stored verification report in Step 3 (clear empty-state + secondary “Open run details” link) in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T056 [US3] Enhance tenantless operation run viewer UI (context + failures + timestamps + refresh) in app/Filament/Pages/Operations/TenantlessOperationRunViewer.php and resources/views/filament/pages/operations/tenantless-operation-run-viewer.blade.php
|
||||
- [x] T057 [P] [US3] Add UI regression tests for wizard report and tenantless viewer details in tests/Feature/Onboarding/OnboardingVerificationTest.php and tests/Feature/Operations/TenantlessOperationRunViewerTest.php
|
||||
- [x] T043 [US3] Ensure “View run” links are tenantless `/admin/operations/{run}` via app/Support/OperationRunLinks.php
|
||||
- [x] T044 [US3] Implement optional bootstrap actions (per-action capability gating) in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T045 [US3] Implement activation gating (owner-only) + blocked override reason + audit in app/Filament/Pages/Workspaces/ManagedTenantOnboardingWizard.php
|
||||
- [x] T046 [US3] Add required audit events (stable action IDs; no secrets) in app/Services/Audit/WorkspaceAuditLogger.php
|
||||
|
||||
**Checkpoint**: US3 complete — verification is observable + deduped, runs are viewable tenantlessly, and activation is safe + audited.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Polish & Cross-Cutting Concerns
|
||||
|
||||
- [X] T043 Add Managed Tenant status badge mapping via BadgeCatalog/BadgeRenderer in app/Support/Badges/* (BADGE-001) and add mapping test in tests/Feature/Badges/TenantStatusBadgeTest.php
|
||||
- [X] T044 Verify/extend audit coverage for FR-016: use stable audit action IDs (enum/registry), ensure redaction, and add at least one concrete feature test asserting audit rows for onboarding start + verification start (no secrets in payload)
|
||||
- [X] T045 Verify last-owner protections cover both workspace + tenant memberships; extend policies if needed in app/Policies/* and add regression tests in tests/Feature/Rbac/*
|
||||
- [X] T046 Run formatter on touched files (command: `vendor/bin/sail bin pint --dirty`)
|
||||
- [X] T047 Run targeted test suite for onboarding (command: `vendor/bin/sail artisan test --compact tests/Feature/ManagedTenantOnboardingWizardTest.php`)
|
||||
**Purpose**: Centralize badge semantics, harden RBAC-UX, and run formatting/tests.
|
||||
|
||||
### Post-spec hardening (Filament-native UX)
|
||||
|
||||
- [X] T048 Refactor onboarding page to a Filament-native Wizard schema (replace header-action modals + step cards; persist per-step progress; keep strict RBAC and existing action methods)
|
||||
- [X] T049 Fix tenant identify UX: entering an existing tenant GUID must not surface a raw 404 modal; bind legacy unscoped tenants to the current workspace when safely inferable and add a regression test
|
||||
- [x] T047 Add centralized badge mapping for onboarding/verification statuses in app/Support/Badges/Domains/
|
||||
- [x] T048 [P] Add badge mapping tests in tests/Feature/Badges/OnboardingBadgeSemanticsTest.php
|
||||
- [x] T049 [P] Add RBAC regression coverage for wizard actions in tests/Feature/Rbac/OnboardingWizardUiEnforcementTest.php
|
||||
- [x] T050 Run formatter on touched files using composer.json scripts (command: `vendor/bin/sail bin pint --dirty`)
|
||||
- [x] T051 Run targeted test suites using phpunit.xml (command: `vendor/bin/sail artisan test --compact tests/Feature/Onboarding tests/Feature/Operations`)
|
||||
|
||||
**Verification note**: Full suite re-run post-fixes is green (984 passed, 5 skipped).
|
||||
|
||||
---
|
||||
|
||||
## Dependencies & Execution Order
|
||||
|
||||
### User Story completion order
|
||||
### Phase Dependencies
|
||||
|
||||
1. US1 (P1) depends on Phase 2 only.
|
||||
2. US2 (P2) depends on US1 (tenant/session + wizard scaffold).
|
||||
3. US3 (P3) depends on US2 (verification state + run linking).
|
||||
- Setup (Phase 1) → Foundational (Phase 2) → US1 (Phase 3) → US2 (Phase 4) → US3 (Phase 5) → Polish (Phase 6)
|
||||
|
||||
### Dependency graph
|
||||
### User Story Dependencies
|
||||
|
||||
- Phase 1 → Phase 2 → US1 → US2 → US3 → Polish
|
||||
- US1 (P1) depends on Phase 2 only.
|
||||
- US2 (P2) depends on US1 (managed tenant + onboarding session in place).
|
||||
- US3 (P3) depends on US2 (provider connection exists) and adds OperationRun viewer changes.
|
||||
|
||||
### Parallel Opportunities
|
||||
|
||||
- [P] tasks can be executed in parallel (different files, minimal coupling).
|
||||
- Within each story: tests can be authored in parallel before implementation.
|
||||
|
||||
---
|
||||
|
||||
## Parallel execution examples
|
||||
## Parallel Example: US1
|
||||
|
||||
### US1 parallel work
|
||||
Run in parallel:
|
||||
|
||||
- [P] T011 and T012 can be implemented in parallel (page class vs blade view).
|
||||
- [P] T018–T020 can be written in parallel (distinct test cases).
|
||||
|
||||
### US2 parallel work
|
||||
|
||||
- [P] T032–T034 can be written in parallel (selection tests vs run tests vs secret-safety tests).
|
||||
|
||||
### US3 parallel work
|
||||
|
||||
- [P] T040–T042 can be written in parallel (resume tests vs completion tests vs bootstrap tests).
|
||||
- T010 (entry point routing tests) in tests/Feature/Onboarding/OnboardingEntryPointTest.php
|
||||
- T011 (RBAC semantics tests) in tests/Feature/Onboarding/OnboardingRbacSemanticsTest.php
|
||||
- T012 (idempotency tests) in tests/Feature/Onboarding/OnboardingIdentifyTenantTest.php
|
||||
|
||||
---
|
||||
|
||||
## Implementation Strategy (MVP)
|
||||
## Implementation Strategy
|
||||
|
||||
- MVP scope is US1 only: wizard-only entry point + idempotent tenant identification + resumable session skeleton + required authorization semantics + tests.
|
||||
### MVP First
|
||||
|
||||
MVP scope is US1 only: `/admin/onboarding` canonical entry point + Step 1 idempotent identification + strict 404/403 semantics + legacy routes 404 + tests.
|
||||
|
||||
26
tests/Feature/Badges/OnboardingBadgeSemanticsTest.php
Normal file
26
tests/Feature/Badges/OnboardingBadgeSemanticsTest.php
Normal file
@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
use App\Support\Badges\BadgeCatalog;
|
||||
use App\Support\Badges\BadgeDomain;
|
||||
|
||||
it('maps onboarding verification status blocked to a Blocked danger badge', function (): void {
|
||||
$spec = BadgeCatalog::spec(BadgeDomain::ManagedTenantOnboardingVerificationStatus, 'blocked');
|
||||
|
||||
expect($spec->label)->toBe('Blocked');
|
||||
expect($spec->color)->toBe('danger');
|
||||
expect($spec->icon)->toBe('heroicon-m-x-circle');
|
||||
});
|
||||
|
||||
it('maps onboarding verification status ready to a Ready success badge', function (): void {
|
||||
$spec = BadgeCatalog::spec(BadgeDomain::ManagedTenantOnboardingVerificationStatus, 'ready');
|
||||
|
||||
expect($spec->label)->toBe('Ready');
|
||||
expect($spec->color)->toBe('success');
|
||||
expect($spec->icon)->toBe('heroicon-m-check-circle');
|
||||
});
|
||||
|
||||
it('normalizes onboarding verification status input before mapping', function (): void {
|
||||
$spec = BadgeCatalog::spec(BadgeDomain::ManagedTenantOnboardingVerificationStatus, 'NEEDS ATTENTION');
|
||||
|
||||
expect($spec->label)->toBe('Needs attention');
|
||||
});
|
||||
@ -13,7 +13,7 @@
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('redirects /admin to the workspace managed-tenants landing when a workspace is selected and has no tenants', function (): void {
|
||||
it('redirects /admin to onboarding when a workspace is selected and has no tenants', function (): void {
|
||||
$user = User::factory()->create();
|
||||
|
||||
$workspace = Workspace::factory()->create();
|
||||
@ -28,7 +28,7 @@
|
||||
->actingAs($user)
|
||||
->withSession([WorkspaceContext::SESSION_KEY => (int) $workspace->getKey()])
|
||||
->get('/admin')
|
||||
->assertRedirect(route('admin.workspace.managed-tenants.onboarding', ['workspace' => $workspace->slug ?? $workspace->getKey()]));
|
||||
->assertRedirect('/admin/onboarding');
|
||||
});
|
||||
|
||||
it('redirects /admin to choose-tenant when a workspace is selected and has multiple tenants', function (): void {
|
||||
|
||||
@ -29,7 +29,7 @@
|
||||
'ownerRecord' => $tenant,
|
||||
'pageClass' => ViewTenant::class,
|
||||
])
|
||||
->assertSee($member->name);
|
||||
->assertSee($member->email);
|
||||
|
||||
Bus::assertNothingDispatched();
|
||||
});
|
||||
|
||||
@ -2,89 +2,86 @@
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\TenantDashboard;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\ProviderConnection;
|
||||
use App\Models\ProviderCredential;
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantOnboardingSession;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Services\Auth\TenantMembershipManager;
|
||||
use App\Services\Auth\WorkspaceRoleCapabilityMap;
|
||||
use App\Support\Auth\Capabilities;
|
||||
use Illuminate\Support\Facades\Bus;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('returns 404 for non-members when starting onboarding', function (): void {
|
||||
it('returns 404 for non-members when starting onboarding with a selected workspace', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user)
|
||||
->get("/admin/w/{$workspace->getKey()}/managed-tenants/onboarding")
|
||||
->get('/admin/onboarding')
|
||||
->assertNotFound();
|
||||
});
|
||||
|
||||
it('returns 403 for workspace members without onboarding capability', function (): void {
|
||||
it('allows workspace members without onboarding capability to view the wizard but forbids execution', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'role' => 'readonly',
|
||||
]);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get("/admin/w/{$workspace->getKey()}/managed-tenants/onboarding")
|
||||
->assertForbidden();
|
||||
});
|
||||
|
||||
it('renders onboarding wizard for workspace owners', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user)
|
||||
->get("/admin/w/{$workspace->getKey()}/managed-tenants/onboarding")
|
||||
->get('/admin/onboarding')
|
||||
->assertSuccessful();
|
||||
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => '11111111-1111-1111-1111-111111111111',
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
])
|
||||
->assertStatus(403);
|
||||
|
||||
expect(Tenant::query()->count())->toBe(0);
|
||||
expect(TenantOnboardingSession::query()->count())->toBe(0);
|
||||
});
|
||||
|
||||
it('allows owners to identify a managed tenant and creates a pending tenant + session', function (): void {
|
||||
it('renders onboarding wizard for workspace owners and allows identifying a managed tenant', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
$this->actingAs($user)
|
||||
->get('/admin/onboarding')
|
||||
->assertSuccessful();
|
||||
|
||||
$tenantGuid = '11111111-1111-1111-1111-111111111111';
|
||||
$entraTenantId = '22222222-2222-2222-2222-222222222222';
|
||||
|
||||
Livewire::test(\App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard::class, ['workspace' => $workspace])
|
||||
->call('identifyManagedTenant', ['tenant_id' => $tenantGuid, 'name' => 'Acme']);
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
'primary_domain' => 'acme.example',
|
||||
'notes' => 'Initial onboarding',
|
||||
]);
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $tenantGuid)->firstOrFail();
|
||||
$tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();
|
||||
|
||||
expect((int) $tenant->workspace_id)->toBe((int) $workspace->getKey());
|
||||
expect($tenant->status)->toBe('pending');
|
||||
|
||||
$this->assertDatabaseHas('managed_tenant_onboarding_sessions', [
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'current_step' => 'identify',
|
||||
]);
|
||||
expect($tenant->status)->toBe(Tenant::STATUS_ONBOARDING);
|
||||
|
||||
$this->assertDatabaseHas('tenant_memberships', [
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
@ -92,134 +89,86 @@
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
expect(
|
||||
(int) \App\Models\TenantMembership::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->where('role', 'owner')
|
||||
->count()
|
||||
)->toBe(1);
|
||||
$this->assertDatabaseHas('managed_tenant_onboarding_sessions', [
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'current_step' => 'identify',
|
||||
]);
|
||||
});
|
||||
|
||||
it('upgrades the initiating user to owner if they already have a lower tenant role', function (): void {
|
||||
it('is idempotent when identifying the same Entra tenant ID twice', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
$tenantGuid = '66666666-6666-6666-6666-666666666666';
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$tenant = Tenant::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'tenant_id' => $tenantGuid,
|
||||
$entraTenantId = '33333333-3333-3333-3333-333333333333';
|
||||
|
||||
$component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
'status' => 'pending',
|
||||
]);
|
||||
|
||||
\App\Models\TenantMembership::query()->create([
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'readonly',
|
||||
'source' => 'manual',
|
||||
'created_by_user_id' => (int) $user->getKey(),
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
Livewire::test(\App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard::class, ['workspace' => $workspace])
|
||||
->call('identifyManagedTenant', ['tenant_id' => $tenantGuid, 'name' => 'Acme']);
|
||||
|
||||
$membership = \App\Models\TenantMembership::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('user_id', (int) $user->getKey())
|
||||
->firstOrFail();
|
||||
|
||||
expect($membership->role)->toBe('owner');
|
||||
|
||||
expect(\App\Models\TenantMembership::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('user_id', (int) $user->getKey())
|
||||
expect(Tenant::query()->where('tenant_id', $entraTenantId)->count())->toBe(1);
|
||||
expect(TenantOnboardingSession::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('entra_tenant_id', $entraTenantId)
|
||||
->whereNull('completed_at')
|
||||
->count())->toBe(1);
|
||||
});
|
||||
|
||||
it('writes audit logs for onboarding start and resume', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
it('returns 404 and does not create anything when entra_tenant_id exists in another workspace', function (): void {
|
||||
$entraTenantId = '44444444-4444-4444-4444-444444444444';
|
||||
|
||||
$workspaceA = Workspace::factory()->create();
|
||||
$workspaceB = Workspace::factory()->create();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'workspace_id' => (int) $workspaceA->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
$tenantGuid = '44444444-4444-4444-4444-444444444444';
|
||||
|
||||
$component = Livewire::test(\App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard::class, ['workspace' => $workspace]);
|
||||
|
||||
$component->call('identifyManagedTenant', ['tenant_id' => $tenantGuid, 'name' => 'Acme']);
|
||||
$component->call('identifyManagedTenant', ['tenant_id' => $tenantGuid, 'name' => 'Acme']);
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $tenantGuid)->firstOrFail();
|
||||
|
||||
$this->assertDatabaseHas('audit_logs', [
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'actor_id' => (int) $user->getKey(),
|
||||
'action' => 'managed_tenant_onboarding.start',
|
||||
'resource_type' => 'tenant',
|
||||
'resource_id' => (string) $tenant->getKey(),
|
||||
'status' => 'success',
|
||||
]);
|
||||
|
||||
$this->assertDatabaseHas('audit_logs', [
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'actor_id' => (int) $user->getKey(),
|
||||
'action' => 'managed_tenant_onboarding.resume',
|
||||
'resource_type' => 'tenant',
|
||||
'resource_id' => (string) $tenant->getKey(),
|
||||
'status' => 'success',
|
||||
]);
|
||||
|
||||
expect(AuditLog::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('resource_type', 'tenant')
|
||||
->where('resource_id', (string) $tenant->getKey())
|
||||
->whereIn('action', ['managed_tenant_onboarding.start', 'managed_tenant_onboarding.resume'])
|
||||
->count())->toBeGreaterThanOrEqual(2);
|
||||
});
|
||||
|
||||
it('blocks demoting or removing the last remaining tenant owner', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'workspace_id' => (int) $workspaceB->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
Tenant::factory()->create([
|
||||
'workspace_id' => (int) $workspaceA->getKey(),
|
||||
'tenant_id' => $entraTenantId,
|
||||
'status' => Tenant::STATUS_ACTIVE,
|
||||
]);
|
||||
|
||||
$tenantGuid = '55555555-5555-5555-5555-555555555555';
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspaceB->getKey());
|
||||
|
||||
Livewire::test(\App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard::class, ['workspace' => $workspace])
|
||||
->call('identifyManagedTenant', ['tenant_id' => $tenantGuid, 'name' => 'Acme']);
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $tenantGuid)->firstOrFail();
|
||||
$membership = \App\Models\TenantMembership::query()
|
||||
->where('tenant_id', $tenant->getKey())
|
||||
->where('user_id', $user->getKey())
|
||||
->firstOrFail();
|
||||
|
||||
expect(fn () => app(TenantMembershipManager::class)->changeRole($tenant, $user, $membership, 'manager'))
|
||||
->toThrow(DomainException::class, 'You cannot demote the last remaining owner.');
|
||||
|
||||
expect(fn () => app(TenantMembershipManager::class)->removeMember($tenant, $user, $membership))
|
||||
->toThrow(DomainException::class, 'You cannot remove the last remaining owner.');
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Other Workspace',
|
||||
])
|
||||
->assertStatus(404);
|
||||
});
|
||||
|
||||
it('returns 404 for legacy onboarding entry points', function (): void {
|
||||
@ -232,15 +181,19 @@
|
||||
$this->get('/admin/new')->assertNotFound();
|
||||
});
|
||||
|
||||
it('is idempotent when identifying the same managed tenant twice', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Legacy onboarding suite (deprecated)
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The remainder of this file previously contained an end-to-end onboarding
|
||||
| suite that relied on deprecated routes and pre-enterprise state semantics.
|
||||
| Spec 073 replaces it with focused coverage under tests/Feature/Onboarding
|
||||
| and tests/Feature/Rbac.
|
||||
|
|
||||
| Keeping the legacy assertions around (commented) is intentional to avoid
|
||||
| reintroducing removed routes or old semantics.
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => $workspace->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
@ -872,3 +825,5 @@
|
||||
'current_step' => 'identify',
|
||||
]);
|
||||
});
|
||||
|
||||
*/
|
||||
|
||||
@ -63,6 +63,33 @@
|
||||
expect($user->notifications()->count())->toBe(0);
|
||||
});
|
||||
|
||||
it('uses a tenantless view link for managed tenant onboarding wizard runs', function () {
|
||||
[$user, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$this->actingAs($user);
|
||||
|
||||
$run = OperationRun::factory()->create([
|
||||
'tenant_id' => $tenant->getKey(),
|
||||
'user_id' => $user->getKey(),
|
||||
'initiator_name' => $user->name,
|
||||
'type' => 'provider.connection.check',
|
||||
'status' => 'queued',
|
||||
'outcome' => 'pending',
|
||||
'context' => [
|
||||
'wizard' => [
|
||||
'flow' => 'managed_tenant_onboarding',
|
||||
'step' => 'verification',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$user->notify(new OperationRunQueued($run));
|
||||
|
||||
$notification = $user->notifications()->latest('id')->first();
|
||||
expect($notification)->not->toBeNull();
|
||||
expect($notification->data['actions'][0]['url'] ?? null)
|
||||
->toBe(OperationRunLinks::tenantlessView($run));
|
||||
});
|
||||
|
||||
it('emits a terminal notification when an operation run transitions to completed', function () {
|
||||
[$user, $tenant] = createUserWithTenant(role: 'owner');
|
||||
$this->actingAs($user);
|
||||
|
||||
134
tests/Feature/Onboarding/OnboardingActivationTest.php
Normal file
134
tests/Feature/Onboarding/OnboardingActivationTest.php
Normal file
@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('denies activation to non-owners even when verification succeeded', function (): void {
|
||||
Queue::fake();
|
||||
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'manager',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$entraTenantId = '88888888-8888-8888-8888-888888888888';
|
||||
|
||||
$component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
]);
|
||||
|
||||
$component->call('createProviderConnection', [
|
||||
'display_name' => 'Acme connection',
|
||||
'client_id' => '00000000-0000-0000-0000-000000000000',
|
||||
'client_secret' => 'super-secret',
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$component->call('startVerification');
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();
|
||||
|
||||
$run = OperationRun::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('type', 'provider.connection.check')
|
||||
->firstOrFail();
|
||||
|
||||
$run->update([
|
||||
'status' => OperationRunStatus::Completed->value,
|
||||
'outcome' => OperationRunOutcome::Succeeded->value,
|
||||
]);
|
||||
|
||||
$component
|
||||
->call('completeOnboarding')
|
||||
->assertStatus(403);
|
||||
|
||||
$tenant->refresh();
|
||||
expect($tenant->status)->not->toBe(Tenant::STATUS_ACTIVE);
|
||||
});
|
||||
|
||||
it('requires an override reason when verification is blocked and records an audit event when overridden', function (): void {
|
||||
Queue::fake();
|
||||
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$entraTenantId = '99999999-9999-9999-9999-999999999999';
|
||||
|
||||
$component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
]);
|
||||
|
||||
$component->call('createProviderConnection', [
|
||||
'display_name' => 'Acme connection',
|
||||
'client_id' => '00000000-0000-0000-0000-000000000000',
|
||||
'client_secret' => 'super-secret',
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$component->call('startVerification');
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();
|
||||
|
||||
$run = OperationRun::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('type', 'provider.connection.check')
|
||||
->firstOrFail();
|
||||
|
||||
$run->update([
|
||||
'status' => OperationRunStatus::Completed->value,
|
||||
'outcome' => OperationRunOutcome::Failed->value,
|
||||
]);
|
||||
|
||||
$component
|
||||
->set('data.override_blocked', true)
|
||||
->set('data.override_reason', '')
|
||||
->call('completeOnboarding')
|
||||
->assertHasErrors(['data.override_reason']);
|
||||
|
||||
$component
|
||||
->set('data.override_blocked', true)
|
||||
->set('data.override_reason', 'Temporary exception approved by owner')
|
||||
->call('completeOnboarding');
|
||||
|
||||
$tenant->refresh();
|
||||
expect($tenant->status)->toBe(Tenant::STATUS_ACTIVE);
|
||||
|
||||
expect(AuditLog::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('action', 'managed_tenant_onboarding.activation')
|
||||
->exists())->toBeTrue();
|
||||
});
|
||||
42
tests/Feature/Onboarding/OnboardingEntryPointTest.php
Normal file
42
tests/Feature/Onboarding/OnboardingEntryPointTest.php
Normal file
@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
|
||||
it('redirects to choose-workspace when visiting /admin/onboarding without a selected workspace', function (): void {
|
||||
$user = User::factory()->create();
|
||||
$workspace = Workspace::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->forget(WorkspaceContext::SESSION_KEY);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get('/admin/onboarding')
|
||||
->assertRedirect('/admin/choose-workspace');
|
||||
});
|
||||
|
||||
it('renders the onboarding wizard at /admin/onboarding when a workspace is selected', function (): void {
|
||||
$user = User::factory()->create();
|
||||
$workspace = Workspace::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user)
|
||||
->get('/admin/onboarding')
|
||||
->assertSuccessful();
|
||||
});
|
||||
48
tests/Feature/Onboarding/OnboardingFoundationsTest.php
Normal file
48
tests/Feature/Onboarding/OnboardingFoundationsTest.php
Normal file
@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Services\Auth\WorkspaceRoleCapabilityMap;
|
||||
use App\Support\Auth\Capabilities;
|
||||
|
||||
it('registers managed tenant onboarding wizard capabilities in the canonical registry', function (): void {
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeTrue();
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW))->toBeTrue();
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE))->toBeTrue();
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START))->toBeTrue();
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC))->toBeTrue();
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC))->toBeTrue();
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP))->toBeTrue();
|
||||
expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE))->toBeTrue();
|
||||
});
|
||||
|
||||
it('maps onboarding wizard capabilities to workspace roles (least privilege)', function (): void {
|
||||
expect(WorkspaceRoleCapabilityMap::hasCapability('owner', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeTrue();
|
||||
expect(WorkspaceRoleCapabilityMap::hasCapability('manager', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeTrue();
|
||||
expect(WorkspaceRoleCapabilityMap::hasCapability('operator', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeFalse();
|
||||
expect(WorkspaceRoleCapabilityMap::hasCapability('readonly', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeFalse();
|
||||
|
||||
expect(WorkspaceRoleCapabilityMap::hasCapability('owner', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE))->toBeTrue();
|
||||
expect(WorkspaceRoleCapabilityMap::hasCapability('manager', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE))->toBeFalse();
|
||||
});
|
||||
|
||||
it('supports the v1 managed tenant lifecycle statuses', function (): void {
|
||||
$draft = Tenant::factory()->create(['status' => Tenant::STATUS_DRAFT]);
|
||||
$onboarding = Tenant::factory()->create(['status' => Tenant::STATUS_ONBOARDING]);
|
||||
$active = Tenant::factory()->create(['status' => Tenant::STATUS_ACTIVE]);
|
||||
|
||||
expect(Tenant::activeQuery()->pluck('id')->all())->toContain((int) $active->getKey());
|
||||
expect(Tenant::activeQuery()->pluck('id')->all())->not->toContain((int) $draft->getKey());
|
||||
expect(Tenant::activeQuery()->pluck('id')->all())->not->toContain((int) $onboarding->getKey());
|
||||
|
||||
$onboarding->delete();
|
||||
$onboarding->refresh();
|
||||
|
||||
expect($onboarding->status)->toBe(Tenant::STATUS_ARCHIVED);
|
||||
|
||||
$onboarding->restore();
|
||||
$onboarding->refresh();
|
||||
|
||||
expect($onboarding->status)->toBe(Tenant::STATUS_ACTIVE);
|
||||
});
|
||||
99
tests/Feature/Onboarding/OnboardingIdentifyTenantTest.php
Normal file
99
tests/Feature/Onboarding/OnboardingIdentifyTenantTest.php
Normal file
@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantOnboardingSession;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('is idempotent when identifying the same Entra tenant ID twice in the same workspace', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
$entraTenantId = '11111111-1111-1111-1111-111111111111';
|
||||
|
||||
$component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
'primary_domain' => 'acme.example',
|
||||
'notes' => 'Initial onboarding',
|
||||
]);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
'primary_domain' => 'acme.example',
|
||||
'notes' => 'Initial onboarding',
|
||||
]);
|
||||
|
||||
expect(Tenant::query()->where('tenant_id', $entraTenantId)->count())->toBe(1);
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();
|
||||
|
||||
expect((int) $tenant->workspace_id)->toBe((int) $workspace->getKey());
|
||||
|
||||
expect(TenantOnboardingSession::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('entra_tenant_id', $entraTenantId)
|
||||
->whereNull('completed_at')
|
||||
->count())->toBe(1);
|
||||
});
|
||||
|
||||
it('responds with deny-as-not-found when attempting to identify an Entra tenant ID that belongs to another workspace', function (): void {
|
||||
$entraTenantId = '22222222-2222-2222-2222-222222222222';
|
||||
|
||||
$workspaceA = Workspace::factory()->create();
|
||||
$workspaceB = Workspace::factory()->create();
|
||||
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspaceA->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspaceB->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
Tenant::factory()->create([
|
||||
'workspace_id' => (int) $workspaceA->getKey(),
|
||||
'tenant_id' => $entraTenantId,
|
||||
'status' => Tenant::STATUS_ACTIVE,
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspaceB->getKey());
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Other Workspace',
|
||||
])
|
||||
->assertStatus(404);
|
||||
});
|
||||
35
tests/Feature/Onboarding/OnboardingLegacyRoutesTest.php
Normal file
35
tests/Feature/Onboarding/OnboardingLegacyRoutesTest.php
Normal file
@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
|
||||
it('returns 404 for legacy onboarding entry points (no redirects)', function (): void {
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
$this->get('/admin/register-tenant')->assertNotFound();
|
||||
$this->get('/admin/managed-tenants/onboarding')->assertNotFound();
|
||||
$this->get('/admin/new')->assertNotFound();
|
||||
});
|
||||
|
||||
it('returns 404 for the legacy workspace-scoped onboarding route', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user)
|
||||
->get("/admin/w/{$workspace->getKey()}/managed-tenants/onboarding")
|
||||
->assertNotFound();
|
||||
});
|
||||
107
tests/Feature/Onboarding/OnboardingProviderConnectionTest.php
Normal file
107
tests/Feature/Onboarding/OnboardingProviderConnectionTest.php
Normal file
@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Models\ProviderConnection;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantOnboardingSession;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('stores the selected provider_connection_id in the onboarding session', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
$entraTenantId = '33333333-3333-3333-3333-333333333333';
|
||||
|
||||
$component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
]);
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();
|
||||
|
||||
$connection = ProviderConnection::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'provider' => 'microsoft',
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'display_name' => 'Acme (onboarding)',
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$component->call('selectProviderConnection', (int) $connection->getKey());
|
||||
|
||||
$session = TenantOnboardingSession::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('entra_tenant_id', $entraTenantId)
|
||||
->whereNull('completed_at')
|
||||
->firstOrFail();
|
||||
|
||||
expect($session->state['provider_connection_id'] ?? null)->toBe((int) $connection->getKey());
|
||||
});
|
||||
|
||||
it('prevents selecting a provider connection bound to a different managed tenant', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
$entraTenantId = '44444444-4444-4444-4444-444444444444';
|
||||
|
||||
$component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Primary Tenant',
|
||||
]);
|
||||
|
||||
$primaryTenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();
|
||||
|
||||
$otherTenant = Tenant::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => '55555555-5555-5555-5555-555555555555',
|
||||
'status' => Tenant::STATUS_ONBOARDING,
|
||||
]);
|
||||
|
||||
$otherConnection = ProviderConnection::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $otherTenant->getKey(),
|
||||
'provider' => 'microsoft',
|
||||
'entra_tenant_id' => (string) $otherTenant->tenant_id,
|
||||
'display_name' => 'Other tenant connection',
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
expect((int) $otherConnection->tenant_id)->not->toBe((int) $primaryTenant->getKey());
|
||||
|
||||
$component
|
||||
->call('selectProviderConnection', (int) $otherConnection->getKey())
|
||||
->assertStatus(404);
|
||||
});
|
||||
47
tests/Feature/Onboarding/OnboardingRbacSemanticsTest.php
Normal file
47
tests/Feature/Onboarding/OnboardingRbacSemanticsTest.php
Normal file
@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('returns 404 for non-members when visiting /admin/onboarding with a selected workspace', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user)
|
||||
->get('/admin/onboarding')
|
||||
->assertNotFound();
|
||||
});
|
||||
|
||||
it('allows workspace members without onboarding capability to view the page but denies action attempts with 403', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'readonly',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user)
|
||||
->get('/admin/onboarding')
|
||||
->assertSuccessful();
|
||||
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => '11111111-1111-1111-1111-111111111111',
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
])
|
||||
->assertStatus(403);
|
||||
});
|
||||
61
tests/Feature/Onboarding/OnboardingSecretSafetyTest.php
Normal file
61
tests/Feature/Onboarding/OnboardingSecretSafetyTest.php
Normal file
@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Models\TenantOnboardingSession;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('never persists client secrets in onboarding session state and never pre-fills them on resume', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$this->actingAs($user);
|
||||
|
||||
$entraTenantId = '66666666-6666-6666-6666-666666666666';
|
||||
$secret = 'super-secret-client-secret';
|
||||
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
])
|
||||
->call('createProviderConnection', [
|
||||
'display_name' => 'Acme connection',
|
||||
'client_id' => '00000000-0000-0000-0000-000000000000',
|
||||
'client_secret' => $secret,
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$session = TenantOnboardingSession::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('entra_tenant_id', $entraTenantId)
|
||||
->whereNull('completed_at')
|
||||
->firstOrFail();
|
||||
|
||||
$encodedState = json_encode($session->state, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
|
||||
expect($encodedState)->not->toContain($secret);
|
||||
expect($session->state)->not->toHaveKey('client_secret');
|
||||
expect($session->state)->not->toHaveKey('new_connection');
|
||||
|
||||
$resumed = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$data = $resumed->get('data');
|
||||
|
||||
expect($data['new_connection']['client_secret'] ?? null)->toBeNull();
|
||||
});
|
||||
133
tests/Feature/Onboarding/OnboardingVerificationTest.php
Normal file
133
tests/Feature/Onboarding/OnboardingVerificationTest.php
Normal file
@ -0,0 +1,133 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Jobs\ProviderConnectionHealthCheckJob;
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantOnboardingSession;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('dedupes active verification runs and stores the run id in the onboarding session', function (): void {
|
||||
Queue::fake();
|
||||
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$entraTenantId = '77777777-7777-7777-7777-777777777777';
|
||||
|
||||
$component = Livewire::actingAs($user)->test(ManagedTenantOnboardingWizard::class);
|
||||
|
||||
$component->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
]);
|
||||
|
||||
$component->call('createProviderConnection', [
|
||||
'display_name' => 'Acme connection',
|
||||
'client_id' => '00000000-0000-0000-0000-000000000000',
|
||||
'client_secret' => 'super-secret',
|
||||
'is_default' => true,
|
||||
]);
|
||||
|
||||
$component->call('startVerification');
|
||||
$component->call('startVerification');
|
||||
|
||||
Queue::assertPushed(ProviderConnectionHealthCheckJob::class, 1);
|
||||
|
||||
$tenant = Tenant::query()->where('tenant_id', $entraTenantId)->firstOrFail();
|
||||
|
||||
expect(OperationRun::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('type', 'provider.connection.check')
|
||||
->count())->toBe(1);
|
||||
|
||||
$runId = (int) OperationRun::query()
|
||||
->where('tenant_id', (int) $tenant->getKey())
|
||||
->where('type', 'provider.connection.check')
|
||||
->value('id');
|
||||
|
||||
$session = TenantOnboardingSession::query()
|
||||
->where('workspace_id', (int) $workspace->getKey())
|
||||
->where('entra_tenant_id', $entraTenantId)
|
||||
->whereNull('completed_at')
|
||||
->firstOrFail();
|
||||
|
||||
expect($session->state['verification_operation_run_id'] ?? null)->toBe($runId);
|
||||
});
|
||||
|
||||
it('renders stored verification findings in the wizard report section', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$entraTenantId = '99999999-9999-9999-9999-999999999999';
|
||||
|
||||
$tenant = Tenant::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => $entraTenantId,
|
||||
'status' => 'onboarding',
|
||||
]);
|
||||
|
||||
$run = OperationRun::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'type' => 'provider.connection.check',
|
||||
'status' => 'completed',
|
||||
'outcome' => 'failed',
|
||||
'context' => [
|
||||
'target_scope' => [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'entra_tenant_name' => 'Contoso',
|
||||
],
|
||||
],
|
||||
'failure_summary' => [
|
||||
[
|
||||
'code' => 'provider.connection.check.failed',
|
||||
'reason_code' => 'permission_denied',
|
||||
'message' => 'Missing required Graph permissions.',
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
TenantOnboardingSession::query()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'current_step' => 'verify',
|
||||
'state' => [
|
||||
'verification_operation_run_id' => (int) $run->getKey(),
|
||||
],
|
||||
'started_by_user_id' => (int) $user->getKey(),
|
||||
'updated_by_user_id' => (int) $user->getKey(),
|
||||
]);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get('/admin/onboarding')
|
||||
->assertSuccessful()
|
||||
->assertSee('permission_denied')
|
||||
->assertSee('Missing required Graph permissions.')
|
||||
->assertSee($entraTenantId);
|
||||
});
|
||||
@ -79,15 +79,16 @@
|
||||
|
||||
$dispatcher = OperationRun::getEventDispatcher();
|
||||
|
||||
OperationRun::creating(function (OperationRun $model) use (&$fired): void {
|
||||
OperationRun::creating(function (OperationRun $model) use (&$fired, $tenant): void {
|
||||
if ($fired) {
|
||||
return;
|
||||
}
|
||||
|
||||
$fired = true;
|
||||
|
||||
OperationRun::withoutEvents(function () use ($model): void {
|
||||
OperationRun::withoutEvents(function () use ($model, $tenant): void {
|
||||
OperationRun::query()->create([
|
||||
'workspace_id' => (int) $tenant->workspace_id,
|
||||
'tenant_id' => $model->tenant_id,
|
||||
'user_id' => $model->user_id,
|
||||
'initiator_name' => $model->initiator_name,
|
||||
|
||||
101
tests/Feature/Operations/TenantlessOperationRunViewerTest.php
Normal file
101
tests/Feature/Operations/TenantlessOperationRunViewerTest.php
Normal file
@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Models\OperationRun;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\OperationRunOutcome;
|
||||
use App\Support\OperationRunStatus;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
|
||||
it('allows viewing an operation run without a selected workspace when the user is a member of the run workspace', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->forget(WorkspaceContext::SESSION_KEY);
|
||||
|
||||
$run = OperationRun::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => null,
|
||||
'type' => 'provider.connection.check',
|
||||
'status' => OperationRunStatus::Queued->value,
|
||||
'outcome' => OperationRunOutcome::Pending->value,
|
||||
]);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get("/admin/operations/{$run->getKey()}")
|
||||
->assertSuccessful();
|
||||
|
||||
expect(session()->get(WorkspaceContext::SESSION_KEY))->toBeNull();
|
||||
});
|
||||
|
||||
it('returns 404 for non-members when viewing an operation run without a selected workspace', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
session()->forget(WorkspaceContext::SESSION_KEY);
|
||||
|
||||
$run = OperationRun::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => null,
|
||||
'type' => 'provider.connection.check',
|
||||
'status' => OperationRunStatus::Queued->value,
|
||||
'outcome' => OperationRunOutcome::Pending->value,
|
||||
]);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get("/admin/operations/{$run->getKey()}")
|
||||
->assertNotFound();
|
||||
});
|
||||
|
||||
it('renders stored target scope and failure details for a completed run', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'owner',
|
||||
]);
|
||||
|
||||
session()->forget(WorkspaceContext::SESSION_KEY);
|
||||
|
||||
$entraTenantId = '11111111-1111-1111-1111-111111111111';
|
||||
$failureMessage = 'Missing required Graph permissions.';
|
||||
|
||||
$run = OperationRun::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => null,
|
||||
'type' => 'provider.connection.check',
|
||||
'status' => OperationRunStatus::Completed->value,
|
||||
'outcome' => OperationRunOutcome::Failed->value,
|
||||
'context' => [
|
||||
'target_scope' => [
|
||||
'entra_tenant_id' => $entraTenantId,
|
||||
'entra_tenant_name' => 'Contoso',
|
||||
],
|
||||
],
|
||||
'failure_summary' => [
|
||||
[
|
||||
'code' => 'provider.connection.check.failed',
|
||||
'reason_code' => 'permission_denied',
|
||||
'message' => $failureMessage,
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get("/admin/operations/{$run->getKey()}")
|
||||
->assertSuccessful()
|
||||
->assertSee($entraTenantId)
|
||||
->assertSee('permission_denied')
|
||||
->assertSee($failureMessage);
|
||||
});
|
||||
106
tests/Feature/Rbac/OnboardingWizardUiEnforcementTest.php
Normal file
106
tests/Feature/Rbac/OnboardingWizardUiEnforcementTest.php
Normal file
@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Filament\Pages\Workspaces\ManagedTenantOnboardingWizard;
|
||||
use App\Jobs\ProviderConnectionHealthCheckJob;
|
||||
use App\Models\ProviderConnection;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantOnboardingSession;
|
||||
use App\Models\User;
|
||||
use App\Models\Workspace;
|
||||
use App\Models\WorkspaceMembership;
|
||||
use App\Support\Workspaces\WorkspaceContext;
|
||||
use Illuminate\Support\Facades\Queue;
|
||||
use Livewire\Livewire;
|
||||
|
||||
describe('Onboarding wizard UI enforcement', function () {
|
||||
it('denies identifyManagedTenant for readonly workspace members', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'readonly',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('identifyManagedTenant', [
|
||||
'entra_tenant_id' => '11111111-1111-1111-1111-111111111111',
|
||||
'environment' => 'prod',
|
||||
'name' => 'Acme',
|
||||
])
|
||||
->assertStatus(403);
|
||||
});
|
||||
|
||||
it('denies provider connection creation for operator members', function (): void {
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'operator',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('createProviderConnection', [
|
||||
'display_name' => 'Acme connection',
|
||||
'client_id' => '00000000-0000-0000-0000-000000000000',
|
||||
'client_secret' => 'super-secret',
|
||||
'is_default' => true,
|
||||
])
|
||||
->assertStatus(403);
|
||||
});
|
||||
|
||||
it('allows operator members to start verification for an existing onboarding session', function (): void {
|
||||
Queue::fake();
|
||||
|
||||
$workspace = Workspace::factory()->create();
|
||||
$user = User::factory()->create();
|
||||
|
||||
WorkspaceMembership::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'user_id' => (int) $user->getKey(),
|
||||
'role' => 'operator',
|
||||
]);
|
||||
|
||||
session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());
|
||||
|
||||
$tenant = Tenant::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'status' => Tenant::STATUS_ONBOARDING,
|
||||
]);
|
||||
|
||||
$connection = ProviderConnection::factory()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'entra_tenant_id' => (string) $tenant->tenant_id,
|
||||
]);
|
||||
|
||||
TenantOnboardingSession::query()->create([
|
||||
'workspace_id' => (int) $workspace->getKey(),
|
||||
'tenant_id' => (int) $tenant->getKey(),
|
||||
'entra_tenant_id' => (string) $tenant->tenant_id,
|
||||
'current_step' => 'connection',
|
||||
'state' => [
|
||||
'provider_connection_id' => (int) $connection->getKey(),
|
||||
],
|
||||
'started_by_user_id' => (int) $user->getKey(),
|
||||
'updated_by_user_id' => (int) $user->getKey(),
|
||||
]);
|
||||
|
||||
Livewire::actingAs($user)
|
||||
->test(ManagedTenantOnboardingWizard::class)
|
||||
->call('startVerification');
|
||||
|
||||
Queue::assertPushed(ProviderConnectionHealthCheckJob::class, 1);
|
||||
});
|
||||
});
|
||||
@ -10,7 +10,7 @@
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('redirects to tenant registration after switching to a workspace with no tenants', function (): void {
|
||||
it('redirects to onboarding after switching to a workspace with no tenants', function (): void {
|
||||
$user = User::factory()->create();
|
||||
|
||||
$workspace = Workspace::factory()->create();
|
||||
@ -24,7 +24,7 @@
|
||||
$this
|
||||
->actingAs($user)
|
||||
->post(route('admin.switch-workspace'), ['workspace_id' => (int) $workspace->getKey()])
|
||||
->assertRedirect(route('admin.workspace.managed-tenants.onboarding', ['workspace' => $workspace->slug ?? $workspace->getKey()]));
|
||||
->assertRedirect(route('admin.onboarding'));
|
||||
|
||||
expect(session(WorkspaceContext::SESSION_KEY))->toBe((int) $workspace->getKey());
|
||||
});
|
||||
|
||||
27
tests/Unit/GraphContractRegistryOnboardingProbesTest.php
Normal file
27
tests/Unit/GraphContractRegistryOnboardingProbesTest.php
Normal file
@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use App\Services\Graph\GraphContractRegistry;
|
||||
|
||||
it('provides contract registry paths for onboarding verification probes', function (): void {
|
||||
$registry = app(GraphContractRegistry::class);
|
||||
|
||||
$organizationPath = $registry->probePath('organization');
|
||||
|
||||
expect($organizationPath)->not->toBeNull();
|
||||
expect(ltrim((string) $organizationPath, '/'))->toBe('organization');
|
||||
|
||||
$appId = '00000000-0000-0000-0000-000000000000';
|
||||
$servicePrincipalByAppIdPath = $registry->probePath('service_principal_by_app_id', ['{appId}' => $appId]);
|
||||
|
||||
expect($servicePrincipalByAppIdPath)->not->toBeNull();
|
||||
expect((string) $servicePrincipalByAppIdPath)->toContain('servicePrincipals');
|
||||
expect((string) $servicePrincipalByAppIdPath)->toContain($appId);
|
||||
|
||||
$servicePrincipalId = '11111111-1111-1111-1111-111111111111';
|
||||
$assignmentsPath = $registry->probePath('service_principal_app_role_assignments', ['{servicePrincipalId}' => $servicePrincipalId]);
|
||||
|
||||
expect($assignmentsPath)->not->toBeNull();
|
||||
expect((string) $assignmentsPath)->toContain("servicePrincipals/{$servicePrincipalId}/appRoleAssignments");
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user