stage 2 of oauth removal, switch to sanctum pat tokens completed, docs updated

This commit is contained in:
Codex Agent
2025-11-07 07:46:53 +01:00
parent 776da57ca9
commit 67affd3317
41 changed files with 124 additions and 2148 deletions

View File

@@ -1,26 +0,0 @@
<?php
namespace Tests\Feature\Api\Tenant;
use Tests\TestCase;
class TenantTokenGuardTest extends TestCase
{
public function test_missing_token_returns_structured_error(): void
{
$response = $this->getJson('/api/v1/tenant/events');
$response->assertStatus(401);
$response->assertJson([
'error' => [
'code' => 'token_missing',
'title' => 'Token Missing',
'message' => 'Authentication token not provided.',
],
]);
$error = $response->json('error');
$this->assertIsArray($error);
$this->assertArrayNotHasKey('meta', $error);
}
}

View File

@@ -120,7 +120,7 @@ class LoginTest extends TestCase
'email_verified_at' => now(),
]);
$intended = 'http://localhost/api/v1/oauth/authorize?client_id=tenant-admin-app&response_type=code';
$intended = 'http://localhost/event-admin/dashboard?from=intended-test';
$returnTarget = '/event-admin/dashboard';
$encodedReturn = rtrim(strtr(base64_encode($returnTarget), '+/', '-_'), '=');

View File

@@ -56,7 +56,7 @@ class TenantAdminGoogleControllerTest extends TestCase
Socialite::shouldReceive('driver')->once()->with('google')->andReturn($driver);
$driver->shouldReceive('user')->once()->andReturn($socialiteUser);
$targetUrl = 'http://localhost:8000/api/v1/oauth/authorize?foo=bar';
$targetUrl = 'http://localhost:8000/event-admin/dashboard?foo=bar';
$encodedReturn = rtrim(strtr(base64_encode($targetUrl), '+/', '-_'), '=');
$this->withSession([

View File

@@ -27,6 +27,8 @@ class TenantProfileApiTest extends TestCase
'password' => Hash::make('secret-password'),
'email' => 'tenant@example.com',
'name' => 'Max Mustermann',
'first_name' => 'Max',
'last_name' => 'Mustermann',
]);
$login = $this->postJson('/api/v1/tenant-auth/login', [
@@ -57,6 +59,34 @@ class TenantProfileApiTest extends TestCase
$data = $me->json();
$this->assertEquals('Max Mustermann', data_get($data, 'user.name'));
$this->assertContains('tenant-admin', $data['abilities']);
$legacy = $this
->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/tenant/me');
$legacy->assertOk();
$legacy->assertJsonFragment([
'id' => $tenant->id,
'tenant_id' => $tenant->id,
'name' => 'Test Tenant GmbH',
'event_credits_balance' => 12,
'fullName' => 'Max Mustermann',
]);
$legacy->assertJsonStructure([
'id',
'tenant_id',
'name',
'slug',
'email',
'fullName',
'event_credits_balance',
'active_reseller_package_id',
'remaining_events',
'package_expires_at',
'features',
'scopes',
]);
$this->assertContains('tenant-admin', $legacy->json('scopes'));
}
public function test_me_requires_valid_token(): void

View File

@@ -1,204 +0,0 @@
<?php
namespace Tests\Feature\OAuth;
use App\Models\OAuthClient;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;
class AuthorizeTest extends TestCase
{
use RefreshDatabase;
public function test_authorize_redirects_guests_to_login(): void
{
$tenant = Tenant::factory()->create();
$client = $this->createClientForTenant($tenant);
$query = $this->buildAuthorizeQuery($client);
$fullUrl = url('/api/v1/oauth/authorize?'.http_build_query($query));
$response = $this->get('/api/v1/oauth/authorize?'.http_build_query($query));
$response->assertRedirect();
$location = $response->headers->get('Location');
$this->assertNotNull($location);
$this->assertStringStartsWith(route('tenant.admin.login'), $location);
$parsed = parse_url($location);
$actualQuery = [];
parse_str($parsed['query'] ?? '', $actualQuery);
$this->assertSame('login_required', $actualQuery['error'] ?? null);
$this->assertSame('Please sign in to continue.', $actualQuery['error_description'] ?? null);
$this->assertReturnToMatches($query, $actualQuery['return_to'] ?? null);
$this->assertIntendedUrlMatches($query);
}
public function test_authorize_returns_json_payload_for_ajax_guests(): void
{
$tenant = Tenant::factory()->create();
$client = $this->createClientForTenant($tenant);
$query = $this->buildAuthorizeQuery($client);
$response = $this->withHeaders(['Accept' => 'application/json'])
->get('/api/v1/oauth/authorize?'.http_build_query($query));
$response->assertStatus(401)
->assertJson([
'error' => 'login_required',
'error_description' => 'Please sign in to continue.',
]);
$this->assertIntendedUrlMatches($query);
}
public function test_authorize_rejects_when_user_cannot_access_client_tenant(): void
{
$homeTenant = Tenant::factory()->create();
$otherTenant = Tenant::factory()->create();
$user = User::factory()->create([
'tenant_id' => $homeTenant->id,
'role' => 'tenant_admin',
]);
$client = $this->createClientForTenant($otherTenant);
$this->actingAs($user);
$query = $this->buildAuthorizeQuery($client);
$response = $this->get('/api/v1/oauth/authorize?'.http_build_query($query));
$response->assertRedirect();
$location = $response->headers->get('Location');
$this->assertNotNull($location);
$parsed = parse_url($location);
$actualQuery = [];
parse_str($parsed['query'] ?? '', $actualQuery);
$this->assertSame('tenant_mismatch', $actualQuery['error'] ?? null);
$this->assertReturnToMatches($query, $actualQuery['return_to'] ?? null);
}
public function test_authorize_redirects_with_error_when_client_unknown(): void
{
$tenant = Tenant::factory()->create();
$this->actingAs(User::factory()->create([
'tenant_id' => $tenant->id,
'role' => 'tenant_admin',
]));
$query = $this->buildAuthorizeQuery(new OAuthClient([
'client_id' => 'missing-client',
'redirect_uris' => ['http://localhost/callback'],
'scopes' => ['tenant:read', 'tenant:write'],
]));
$response = $this->get('/api/v1/oauth/authorize?'.http_build_query($query));
$response->assertRedirect();
$location = $response->headers->get('Location');
$this->assertNotNull($location);
$parsed = parse_url($location);
$actualQuery = [];
parse_str($parsed['query'] ?? '', $actualQuery);
$this->assertSame('invalid_client', $actualQuery['error'] ?? null);
$this->assertReturnToMatches($query, $actualQuery['return_to'] ?? null);
}
public function test_authorize_returns_json_error_for_tenant_mismatch_when_requested(): void
{
$homeTenant = Tenant::factory()->create();
$otherTenant = Tenant::factory()->create();
$user = User::factory()->create([
'tenant_id' => $homeTenant->id,
'role' => 'tenant_admin',
]);
$client = $this->createClientForTenant($otherTenant);
$this->actingAs($user);
$query = $this->buildAuthorizeQuery($client);
$response = $this->withHeaders(['Accept' => 'application/json'])
->get('/api/v1/oauth/authorize?'.http_build_query($query));
$response->assertStatus(403)
->assertJson([
'error' => 'tenant_mismatch',
]);
}
private function createClientForTenant(Tenant $tenant): 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' => ['tenant:read', 'tenant:write'],
'is_active' => true,
]);
}
private function buildAuthorizeQuery(OAuthClient $client): array
{
return [
'client_id' => $client->client_id,
'redirect_uri' => 'http://localhost/callback',
'response_type' => 'code',
'scope' => 'tenant:read tenant:write',
'state' => Str::random(10),
'code_challenge' => rtrim(strtr(base64_encode(hash('sha256', Str::random(32), true)), '+/', '-_'), '='),
'code_challenge_method' => 'S256',
];
}
private function assertIntendedUrlMatches(array $expectedQuery): void
{
$intended = session('url.intended');
$this->assertNotNull($intended, 'Expected intended URL to be recorded in session.');
$parts = parse_url($intended);
$this->assertSame('/api/v1/oauth/authorize', $parts['path'] ?? null);
$actualQuery = [];
parse_str($parts['query'] ?? '', $actualQuery);
$this->assertEqualsCanonicalizing($expectedQuery, $actualQuery);
}
private function decodeReturnTo(?string $value): ?string
{
if ($value === null) {
return null;
}
$padded = str_pad($value, strlen($value) + ((4 - (strlen($value) % 4)) % 4), '=');
$normalized = strtr($padded, '-_', '+/');
return base64_decode($normalized) ?: null;
}
private function assertReturnToMatches(array $expectedQuery, ?string $encoded): void
{
$decoded = $this->decodeReturnTo($encoded);
$this->assertNotNull($decoded, 'Failed to decode return_to parameter.');
$parts = parse_url($decoded);
$this->assertSame('/api/v1/oauth/authorize', $parts['path'] ?? null);
$actualQuery = [];
parse_str($parts['query'] ?? '', $actualQuery);
$this->assertEqualsCanonicalizing($expectedQuery, $actualQuery);
}
}

View File

@@ -1,284 +0,0 @@
<?php
namespace Tests\Feature;
use App\Models\OAuthClient;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Tests\TestCase;
class OAuthFlowTest extends TestCase
{
use RefreshDatabase;
private const PUBLIC_KEY = <<<KEY
-----BEGI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();
config()->set('oauth.keys.current_kid', 'test-kid');
config()->set('oauth.keys.storage_path', storage_path('app/oauth-keys-tests'));
$paths = $this->keyPaths('test-kid');
File::ensureDirectoryExists($paths['directory']);
File::put($paths['public'], self::PUBLIC_KEY);
File::put($paths['private'], self::PRIVATE_KEY);
File::chmod($paths['private'], 0600);
File::chmod($paths['public'], 0644);
}
protected function tearDown(): void
{
File::deleteDirectory(storage_path('app/oauth-keys-tests'));
parent::tearDown();
}
public function test_authorization_code_flow_and_refresh(): void
{
$tenant = Tenant::factory()->create([
'slug' => 'test-tenant',
]);
OAuthClient::create([
'id' => (string) Str::uuid(),
'client_id' => 'tenant-admin-app',
'tenant_id' => $tenant->id,
'redirect_uris' => ['http://localhost/callback'],
'scopes' => ['tenant:read', 'tenant:write'],
'is_active' => true,
]);
$codeVerifier = 'unit-test-code-verifier-1234567890';
$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' => 'tenant-admin-app',
'redirect_uri' => 'http://localhost/callback',
'response_type' => 'code',
'scope' => 'tenant:read tenant:write',
'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');
$this->assertEquals($state, $query['state'] ?? null);
$tokenResponse = $this->post('/api/v1/oauth/token', [
'grant_type' => 'authorization_code',
'code' => $authorizationCode,
'client_id' => 'tenant-admin-app',
'redirect_uri' => 'http://localhost/callback',
'code_verifier' => $codeVerifier,
]);
$tokenResponse->assertOk();
$tokenData = $tokenResponse->json();
$this->assertArrayHasKey('access_token', $tokenData);
$this->assertArrayHasKey('refresh_token', $tokenData);
$this->assertSame('Bearer', $tokenData['token_type']);
$meResponse = $this->get('/api/v1/tenant/me', [
'Authorization' => 'Bearer ' . $tokenData['access_token'],
]);
$meResponse->assertOk();
$meResponse->assertJsonFragment([
'tenant_id' => $tenant->id,
'name' => $tenant->name,
]);
$refreshResponse = $this->post('/api/v1/oauth/token', [
'grant_type' => 'refresh_token',
'refresh_token' => $tokenData['refresh_token'],
'client_id' => 'tenant-admin-app',
]);
$refreshResponse->assertOk();
$refreshData = $refreshResponse->json();
$this->assertArrayHasKey('access_token', $refreshData);
$this->assertArrayHasKey('refresh_token', $refreshData);
$this->assertNotEquals($refreshData['access_token'], $tokenData['access_token']);
$this->withServerVariables(['REMOTE_ADDR' => '198.51.100.10'])
->post('/api/v1/oauth/token', [
'grant_type' => 'refresh_token',
'refresh_token' => $refreshData['refresh_token'],
'client_id' => 'tenant-admin-app',
])
->assertStatus(403)
->assertJson([
'error' => 'Refresh token cannot be used from this IP address',
]);
}
public function test_refresh_token_ip_binding_can_be_disabled(): void
{
config()->set('oauth.refresh_tokens.enforce_ip_binding', false);
$tenant = Tenant::factory()->create([
'slug' => 'ip-free',
]);
OAuthClient::create([
'id' => (string) Str::uuid(),
'client_id' => 'tenant-admin-app',
'tenant_id' => $tenant->id,
'redirect_uris' => ['http://localhost/callback'],
'scopes' => ['tenant:read'],
'is_active' => true,
]);
$codeVerifier = 'unit-test-code-verifier-abcdef';
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
$codeResponse = $this->get('/api/v1/oauth/authorize?' . http_build_query([
'client_id' => 'tenant-admin-app',
'redirect_uri' => 'http://localhost/callback',
'response_type' => 'code',
'scope' => 'tenant:read',
'state' => 'state',
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256',
]));
$location = $codeResponse->headers->get('Location');
parse_str(parse_url($location, PHP_URL_QUERY) ?? '', $query);
$code = $query['code'];
$tokenResponse = $this->post('/api/v1/oauth/token', [
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => 'tenant-admin-app',
'redirect_uri' => 'http://localhost/callback',
'code_verifier' => $codeVerifier,
]);
$token = $tokenResponse->json('refresh_token');
$this->withServerVariables(['REMOTE_ADDR' => '203.0.113.33'])
->post('/api/v1/oauth/token', [
'grant_type' => 'refresh_token',
'refresh_token' => $token,
'client_id' => 'tenant-admin-app',
])
->assertOk();
}
public function test_refresh_token_allows_same_subnet_when_enabled(): void
{
config()->set('oauth.refresh_tokens.allow_subnet_match', true);
$tenant = Tenant::factory()->create([
'slug' => 'subnet-tenant',
]);
OAuthClient::create([
'id' => (string) Str::uuid(),
'client_id' => 'tenant-admin-app',
'tenant_id' => $tenant->id,
'redirect_uris' => ['http://localhost/callback'],
'scopes' => ['tenant:read'],
'is_active' => true,
]);
$codeVerifier = 'unit-test-code-verifier-subnet';
$codeChallenge = rtrim(strtr(base64_encode(hash('sha256', $codeVerifier, true)), '+/', '-_'), '=');
$codeResponse = $this->get('/api/v1/oauth/authorize?' . http_build_query([
'client_id' => 'tenant-admin-app',
'redirect_uri' => 'http://localhost/callback',
'response_type' => 'code',
'scope' => 'tenant:read',
'state' => 'state',
'code_challenge' => $codeChallenge,
'code_challenge_method' => 'S256',
]));
$location = $codeResponse->headers->get('Location');
parse_str(parse_url($location, PHP_URL_QUERY) ?? '', $query);
$code = $query['code'];
$tokenResponse = $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.24'])->post('/api/v1/oauth/token', [
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => 'tenant-admin-app',
'redirect_uri' => 'http://localhost/callback',
'code_verifier' => $codeVerifier,
]);
$token = $tokenResponse->json('refresh_token');
$this->withServerVariables(['REMOTE_ADDR' => '198.51.100.55'])
->post('/api/v1/oauth/token', [
'grant_type' => 'refresh_token',
'refresh_token' => $token,
'client_id' => 'tenant-admin-app',
])
->assertOk();
}
private function keyPaths(string $kid): array
{
$base = storage_path('app/oauth-keys-tests');
return [
'directory' => $base . DIRECTORY_SEPARATOR . $kid,
'public' => $base . DIRECTORY_SEPARATOR . $kid . DIRECTORY_SEPARATOR . 'public.key',
'private' => $base . DIRECTORY_SEPARATOR . $kid . DIRECTORY_SEPARATOR . 'private.key',
];
}
}

View File

@@ -2,10 +2,10 @@
namespace Tests\Feature\Tenant;
use App\Models\OAuthClient;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Tests\TestCase;
@@ -17,12 +17,8 @@ abstract class TenantTestCase extends TestCase
protected User $tenantUser;
protected OAuthClient $oauthClient;
protected string $token;
protected ?string $refreshToken = null;
protected function setUp(): void
{
parent::setUp();
@@ -44,7 +40,7 @@ abstract class TenantTestCase extends TestCase
$this->app->instance('tenant', $this->tenant);
}
protected function initialiseTenantContext(array $scopes = ['tenant:read', 'tenant:write']): void
protected function initialiseTenantContext(): void
{
$this->tenant = Tenant::factory()->create([
'name' => 'Test Tenant',
@@ -55,68 +51,18 @@ abstract class TenantTestCase extends TestCase
'name' => 'Test User',
'email' => 'test-'.Str::random(6).'@example.com',
'tenant_id' => $this->tenant->id,
'role' => 'admin',
'role' => 'tenant_admin',
'password' => Hash::make('password'),
]);
$this->oauthClient = $this->createTenantClient($this->tenant, $scopes);
[$this->token, $this->refreshToken] = $this->issueTokens($this->oauthClient, $scopes);
$login = $this->postJson('/api/v1/tenant-auth/login', [
'login' => $this->tenantUser->email,
'password' => 'password',
]);
$login->assertOk();
$this->token = (string) $login->json('token');
$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
{
$this->actingAs($this->tenantUser);
$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'),
];
}
}

View File

@@ -2,10 +2,10 @@
namespace Tests\Feature;
use App\Models\OAuthClient;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Tests\TestCase;
class TenantCreditsTest extends TestCase
@@ -19,16 +19,21 @@ class TenantCreditsTest extends TestCase
'event_credits_balance' => 0,
]);
$client = OAuthClient::create([
'id' => (string) Str::uuid(),
'client_id' => 'tenant-admin-app',
$user = User::factory()->create([
'tenant_id' => $tenant->id,
'redirect_uris' => ['http://localhost/callback'],
'scopes' => ['tenant:read', 'tenant:write'],
'is_active' => true,
'role' => 'tenant_admin',
'email' => 'tenant-admin@example.com',
'password' => Hash::make('password'),
]);
[$accessToken] = $this->obtainTokens($client);
$login = $this->postJson('/api/v1/tenant-auth/login', [
'login' => $user->email,
'password' => 'password',
]);
$login->assertOk();
$accessToken = $login->json('token');
$headers = [
'Authorization' => 'Bearer '.$accessToken,
@@ -77,46 +82,5 @@ class TenantCreditsTest extends TestCase
$syncResponse->assertOk()
->assertJsonStructure(['balance', 'subscription_active', 'server_time']);
}
private function obtainTokens(OAuthClient $client): array
{
$codeVerifier = 'tenant-credits-code-verifier-1234567890';
$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' => 'tenant:read tenant:write',
'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'),
];
}
}

View File

@@ -1,76 +0,0 @@
import { test, expect } from '@playwright/test';
test('OAuth Flow for tenant-admin-app', async ({ page }) => {
const code_challenge = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
const code_verifier = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM';
const redirect_uri = 'http://localhost:8000/auth/callback';
const state = 'teststate';
const scope = 'tenant:read tenant:write tenant:admin';
const authorizeUrl = `/api/v1/oauth/authorize?response_type=code&client_id=tenant-admin-app&redirect_uri=${encodeURIComponent(redirect_uri)}&scope=${encodeURIComponent(scope)}&code_challenge=${code_challenge}&code_challenge_method=S256&state=${state}`;
// Navigate to authorize - should immediately redirect to callback
await page.goto(authorizeUrl);
await page.waitForLoadState('networkidle');
// Log response if no redirect
const currentUrl = page.url();
if (currentUrl.includes('/authorize')) {
const response = await page.content();
console.log('No redirect, response:', response.substring(0, 500)); // First 500 chars
}
// Wait for redirect to callback and parse params
await expect(page).toHaveURL(new RegExp(`${redirect_uri}\\?.*`));
const urlObj = new URL(currentUrl);
const code = urlObj.searchParams.get('code') || '';
const receivedState = urlObj.searchParams.get('state') || '';
expect(receivedState).toBe(state);
expect(code).not.toBeNull();
console.log('Authorization code:', code);
// Token exchange via fetch
const tokenParams = {
code: code!,
redirect_uri,
code_verifier
};
const tokenResponse = await page.evaluate(async (params) => {
const response = await fetch('/api/v1/oauth/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: 'tenant-admin-app',
code: params.code,
redirect_uri: params.redirect_uri,
code_verifier: params.code_verifier,
}).toString(),
});
return await response.json();
}, tokenParams);
console.log('Token response:', tokenResponse);
expect(tokenResponse.access_token).toBeTruthy();
const accessToken = tokenResponse.access_token;
// Call /tenant/me with token
const meResponse = await page.evaluate(async (token) => {
const response = await fetch('/api/v1/tenant/me', {
headers: {
'Authorization': `Bearer ${token}`,
'Accept': 'application/json',
},
});
return await response.json();
}, accessToken);
console.log('/tenant/me response:', meResponse);
expect(meResponse).toHaveProperty('id');
expect(meResponse.email).toBe('demo@example.com');
});

View File

@@ -1,6 +1,5 @@
import 'dotenv/config';
import { test as base, expect, Page, APIRequestContext } from '@playwright/test';
import { randomBytes, createHash } from 'node:crypto';
export type TenantCredentials = {
email: string;
@@ -44,16 +43,13 @@ export const test = base.extend<TenantAdminFixtures>({
export const expectFixture = expect;
const clientId = process.env.VITE_OAUTH_CLIENT_ID ?? 'tenant-admin-app';
const redirectUri = new URL('/event-admin/auth/callback', process.env.PLAYWRIGHT_BASE_URL ?? 'http://localhost:8000').toString();
const scopes = (process.env.VITE_OAUTH_SCOPES as string | undefined) ?? 'tenant:read tenant:write';
async function performTenantSignIn(page: Page, _credentials: TenantCredentials) {
const tokens = await exchangeTokens(page.request);
async function performTenantSignIn(page: Page, credentials: TenantCredentials) {
const token = await exchangeToken(page.request, credentials);
await page.addInitScript(({ stored }) => {
localStorage.setItem('tenant_oauth_tokens.v1', JSON.stringify(stored));
}, { stored: tokens });
localStorage.setItem('tenant_admin.token.v1', JSON.stringify(stored));
sessionStorage.setItem('tenant_admin.token.session.v1', JSON.stringify(stored));
}, { stored: token });
await page.goto('/event-admin');
await page.waitForLoadState('domcontentloaded');
@@ -61,78 +57,27 @@ async function performTenantSignIn(page: Page, _credentials: TenantCredentials)
type StoredTokenPayload = {
accessToken: string;
refreshToken: string;
expiresAt: number;
scope?: string;
clientId?: string;
abilities: string[];
issuedAt: number;
};
async function exchangeTokens(request: APIRequestContext): Promise<StoredTokenPayload> {
const verifier = generateCodeVerifier();
const challenge = generateCodeChallenge(verifier);
const state = randomBytes(12).toString('hex');
const params = new URLSearchParams({
response_type: 'code',
client_id: clientId,
redirect_uri: redirectUri,
scope: scopes,
state,
code_challenge: challenge,
code_challenge_method: 'S256',
});
const authResponse = await request.get(`/api/v1/oauth/authorize?${params.toString()}`, {
maxRedirects: 0,
headers: {
'x-playwright-test': 'tenant-admin',
async function exchangeToken(request: APIRequestContext, credentials: TenantCredentials): Promise<StoredTokenPayload> {
const response = await request.post('/api/v1/tenant-auth/login', {
data: {
login: credentials.email,
password: credentials.password,
},
});
if (authResponse.status() >= 400) {
throw new Error(`OAuth authorize failed: ${authResponse.status()} ${await authResponse.text()}`);
if (!response.ok()) {
throw new Error(`Tenant PAT login failed: ${response.status()} ${await response.text()}`);
}
const location = authResponse.headers()['location'];
if (!location) {
throw new Error('OAuth authorize did not return redirect location');
}
const code = new URL(location).searchParams.get('code');
if (!code) {
throw new Error('OAuth authorize response missing code');
}
const tokenResponse = await request.post('/api/v1/oauth/token', {
form: {
grant_type: 'authorization_code',
code,
client_id: clientId,
redirect_uri: redirectUri,
code_verifier: verifier,
},
});
if (!tokenResponse.ok()) {
throw new Error(`OAuth token exchange failed: ${tokenResponse.status()} ${await tokenResponse.text()}`);
}
const body = await tokenResponse.json();
const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : 3600;
const body = await response.json();
return {
accessToken: body.access_token,
refreshToken: body.refresh_token,
expiresAt: Date.now() + Math.max(expiresIn - 30, 0) * 1000,
scope: body.scope,
clientId,
accessToken: body.token,
abilities: Array.isArray(body.abilities) ? body.abilities : [],
issuedAt: Date.now(),
};
}
function generateCodeVerifier(): string {
return randomBytes(32).toString('base64url');
}
function generateCodeChallenge(verifier: string): string {
return createHash('sha256').update(verifier).digest('base64url');
}