fix: register AuthScopeContextListener for Sanctum bearer-token flow

Live HTTP smoke test on the post-architectural-fixes branch surfaced
that captured Sentry events carried only route-scope tags (app,
route_name, http.method) — auth-scope tags (user_id, actor_type,
actor_scope) were absent on every request.

Root cause: Sanctum's Guard fires Laravel\Sanctum\Events\TokenAuthenticated
(vendor/laravel/sanctum/src/Guard.php:77) on bearer-token resolution,
NOT Illuminate\Auth\Events\Authenticated. The Authenticated event only
fires from SessionGuard
(vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php:833),
which Crewli does not use — CookieBearerToken middleware injects the
httpOnly cookie as Authorization: Bearer, then auth:sanctum invokes
Sanctum's Guard. So the listener never ran on Crewli's HTTP path.

Offline tests in AuthScopeContextListenerTest passed because they
dispatch event(new Authenticated(...)) directly, bypassing the Guard
layer. Sanctum::actingAs() in tests has the same blind spot — it
short-circuits the Guard via guard('sanctum')->setUser() and fires
neither event.

Fix:
- New handleTokenAuthenticated(TokenAuthenticated $event) method on
  AuthScopeContextListener extracts the user via $event->token->tokenable
  and delegates to a private bindForUser() shared with handle().
- AppServiceProvider registers the listener for both Authenticated
  (covers SessionGuard / login flow / future authenticators) and
  TokenAuthenticated (covers Crewli's bearer-token Sanctum flow).

Regression coverage: AuthScopeBindingHttpFlowTest exercises the real
Sanctum Guard via $user->createToken() + Authorization: Bearer header.
Three cases:
  - super_admin on a user-scope route: actor_scope=user, all auth tags
    present.
  - super_admin on an admin.* route: actor_scope=platform, no
    organisation_id (correct platform-mode behaviour).
  - org_admin on a route with {organisation} param: actor_scope=
    organisation, organisation_id valid ULID.

Test count 1541 to 1544. Larastan clean. Pint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-06 13:58:42 +02:00
parent 0379016c7e
commit adab3be781
3 changed files with 193 additions and 15 deletions

View File

@@ -0,0 +1,145 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Observability;
use App\Models\Organisation;
use App\Models\User;
use Database\Seeders\RoleSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use RuntimeException;
use Sentry\ClientBuilder;
use Sentry\Event as SentryEvent;
use Sentry\EventHint;
use Sentry\SentrySdk;
use Sentry\State\Hub;
use Symfony\Component\Uid\Ulid;
use Tests\TestCase;
/**
* Verifies that AuthScopeContextListener auth-scope tags actually bind on
* a live HTTP request flow not just when the Authenticated event is
* dispatched directly from a test.
*
* Reproduces the bug surfaced after the WS-7 PR-2 architectural-fixes
* deployment: offline tests passed because they called
* `event(new Authenticated(...))` directly, but Crewli's bearer-token
* Sanctum flow only fires `Laravel\Sanctum\Events\TokenAuthenticated`
* (vendor/laravel/sanctum/src/Guard.php:77), never `Authenticated`. Live
* captured events therefore carried no user_id / actor_type / actor_scope
* tags. The fix listens to both events.
*
* To exercise the real Sanctum Guard, this test creates a personal-access
* token via $user->createToken() and passes Authorization: Bearer in the
* request Sanctum::actingAs() short-circuits the Guard layer and would
* NOT detect the regression.
*/
final class AuthScopeBindingHttpFlowTest extends TestCase
{
use RefreshDatabase;
/**
* Captured events from the recording before_send hook.
*
* @var list<array{event: SentryEvent, hint: ?EventHint}>
*/
private static array $captured = [];
protected function setUp(): void
{
parent::setUp();
$this->seed(RoleSeeder::class);
self::$captured = [];
$clientBuilder = ClientBuilder::create([
'dsn' => 'https://test@localhost/1',
'environment' => 'testing',
'release' => 'crewli-api@test',
'send_default_pii' => false,
'traces_sample_rate' => 0.0,
'profiles_sample_rate' => 0.0,
'before_send' => static function (SentryEvent $event, ?EventHint $hint = null): ?SentryEvent {
self::$captured[] = ['event' => $event, 'hint' => $hint];
return null;
},
]);
SentrySdk::setCurrentHub(new Hub($clientBuilder->getClient()));
}
/**
* @return array<string, string>
*/
private function authHeader(User $user): array
{
$token = $user->createToken('regression-test')->plainTextToken;
return ['Authorization' => 'Bearer '.$token];
}
public function test_authenticated_http_request_captures_auth_scope_tags_on_thrown_exception(): void
{
$user = User::factory()->create();
$user->assignRole('super_admin');
Route::middleware(['auth:sanctum', \App\Http\Middleware\BindSentryRouteContext::class])->group(function (): void {
Route::get('_obs_authflow_throw', static fn () => throw new RuntimeException('regression-test'))
->name('test.obs.authflow_throw');
});
$response = $this->withHeaders($this->authHeader($user))->getJson('/_obs_authflow_throw');
$response->assertStatus(500);
$this->assertCount(1, self::$captured, 'Sentry event must be captured for thrown RuntimeException');
$tags = self::$captured[0]['event']->getTags();
$this->assertSame($user->id, $tags['user_id'] ?? null, 'user_id tag missing on live HTTP flow');
$this->assertSame('super_admin', $tags['actor_type'] ?? null, 'actor_type tag missing on live HTTP flow');
$this->assertArrayHasKey('actor_scope', $tags, 'actor_scope tag missing on live HTTP flow');
}
public function test_authenticated_http_request_to_admin_route_tags_actor_scope_platform(): void
{
$user = User::factory()->create();
$user->assignRole('super_admin');
Route::middleware(['auth:sanctum', \App\Http\Middleware\BindSentryRouteContext::class])
->name('admin.')
->group(function (): void {
Route::get('_obs_admin_throw', static fn () => throw new RuntimeException('regression-test'))
->name('platform_throw');
});
$this->withHeaders($this->authHeader($user))->getJson('/_obs_admin_throw');
$tags = self::$captured[0]['event']->getTags();
$this->assertSame('platform', $tags['actor_scope'] ?? null,
'super_admin on admin.* route must tag actor_scope=platform');
$this->assertArrayNotHasKey('organisation_id', $tags,
'organisation_id MUST be absent on platform-scoped events');
}
public function test_authenticated_http_request_to_organisation_route_tags_organisation_scope(): void
{
$org = Organisation::factory()->create();
$user = User::factory()->create();
$org->users()->attach($user, ['role' => 'org_admin']);
$user->assignRole('org_admin');
Route::middleware(['auth:sanctum', \App\Http\Middleware\BindSentryRouteContext::class])->group(function (): void {
Route::get('_obs_org_throw/{organisation}', static fn () => throw new RuntimeException('regression-test'))
->name('test.obs.org_throw');
});
$this->withHeaders($this->authHeader($user))->getJson('/_obs_org_throw/'.$org->id);
$tags = self::$captured[0]['event']->getTags();
$this->assertSame('organisation', $tags['actor_scope'] ?? null);
$this->assertSame($org->id, $tags['organisation_id'] ?? null);
$this->assertTrue(Ulid::isValid($tags['organisation_id']));
}
}