initialiseTenantContext(); } protected function authenticatedRequest(string $method, string $uri, array $data = [], array $headers = []) { $headers = array_merge([ 'Authorization' => 'Bearer '.$this->token, ], $headers); return $this->withHeaders($headers)->json($method, $uri, $data); } protected function mockTenantContext(): void { $this->app->instance('tenant', $this->tenant); } protected function initialiseTenantContext(array $scopes = ['tenant:read', 'tenant:write']): void { $this->tenant = Tenant::factory()->create([ 'name' => 'Test Tenant', 'slug' => 'test-tenant-'.Str::random(6), ]); $this->tenantUser = User::factory()->create([ 'name' => 'Test User', 'email' => 'test-'.Str::random(6).'@example.com', 'tenant_id' => $this->tenant->id, 'role' => 'admin', ]); $this->oauthClient = $this->createTenantClient($this->tenant, $scopes); [$this->token, $this->refreshToken] = $this->issueTokens($this->oauthClient, $scopes); $this->app->instance('tenant', $this->tenant); } protected function createTenantClient(Tenant $tenant, array $scopes): OAuthClient { return OAuthClient::create([ 'id' => (string) Str::uuid(), 'client_id' => 'tenant-admin-app-'.$tenant->id, 'tenant_id' => $tenant->id, 'client_secret' => null, 'redirect_uris' => ['http://localhost/callback'], 'scopes' => $scopes, 'is_active' => true, ]); } protected function issueTokens(OAuthClient $client, array $scopes = ['tenant:read', 'tenant:write']): array { $codeVerifier = 'tenant-code-verifier-'.Str::random(32); $codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '='); $state = Str::random(10); $response = $this->get('/api/v1/oauth/authorize?'.http_build_query([ 'client_id' => $client->client_id, 'redirect_uri' => 'http://localhost/callback', 'response_type' => 'code', 'scope' => implode(' ', $scopes), 'state' => $state, 'code_challenge' => $codeChallenge, 'code_challenge_method' => 'S256', ])); $response->assertRedirect(); $location = $response->headers->get('Location'); $this->assertNotNull($location); $query = []; parse_str(parse_url($location, PHP_URL_QUERY) ?? '', $query); $authorizationCode = $query['code'] ?? null; $this->assertNotNull($authorizationCode, 'Authorization code should be present'); $tokenResponse = $this->post('/api/v1/oauth/token', [ 'grant_type' => 'authorization_code', 'code' => $authorizationCode, 'client_id' => $client->client_id, 'redirect_uri' => 'http://localhost/callback', 'code_verifier' => $codeVerifier, ]); $tokenResponse->assertOk(); return [ $tokenResponse->json('access_token'), $tokenResponse->json('refresh_token'), ]; } }