Core Pest Footgun: One Request Per Test¶
BaseAuthController authenticates in its constructor, so a second request as a different account inside one Pest
feature test silently resolves the first account.
Required access¶
None. This is test-authoring advice for the core repository; no AWS, secrets or VPN are involved.
Symptom¶
A feature test makes two portal (or admin) requests as two different accounts. The second request 404s on a domain lookup that should succeed, or acts as the wrong account. The domain exists and the token is valid, so the 404 looks phantom.
Mechanism¶
App\Http\Controllers\Auth\BaseAuthController::__construct()(app/Http/Controllers/Auth/BaseAuthController.php, line 24) reads$_COOKIE['chtoken']and sets$this->token,$this->userand$this->account. Auth happens in the constructor, not in middleware.- Laravel memoizes the resolved controller instance on the
Routeobject. - Within one test there is a single app instance and a single router, so the
Routeoutlives each request. The constructor, and therefore the auth, runs once per app instance, not once per request. - A second request as another account reuses the controller built for the first, so
$this->accountis still the first account and the domain lookup 404s.
Production is unaffected
Production serves one request per app instance, so the constructor runs for every request. Only tests that issue several requests in one app instance see this.
This applies to every BaseAuthController subclass (portal and admin controllers), not just one route group.
Rule¶
Make one request per test whenever the accounts differ. Split edge cases into separate tests instead of looping over accounts inside one:
test('rescan refuses when the domain has a status-2 scan', function () {
$domain = Domain::factory()->create();
User::factory()->create(['account_id' => $domain->account_id]);
$response = requestAsPortalOwner($domain, '/domain/'.$domain->id.'/rescan');
$response->assertRedirect('/domain/'.$domain->id.'/scan?error=2');
});
Requesting twice as the same account in one test is fine.
Re-creating the app between requests
In principle a fresh app instance (for example $this->refreshApplication()) also resets the memoized controller. Nothing in core's tests does this today and it has not been verified here, so prefer splitting tests.
Reference¶
tests/Feature/ScanDispatchGuardsTest.php documents the pitfall next to the edge-case tests (around line 250):
"BaseAuthController authenticates in its constructor, and Laravel memoizes the controller instance on the Route, which
outlives a single test request ... Splitting keeps each test to one request." Its requestAsPortalOwner() helper shows
how to set the chtoken / chtoken_id superglobals the constructor reads (the cookie must be 128 characters: access
token plus 64 filler).