Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 78
0.00% covered (danger)
0.00%
0 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
CoverageController
0.00% covered (danger)
0.00%
0 / 78
0.00% covered (danger)
0.00%
0 / 7
1806
0.00% covered (danger)
0.00%
0 / 1
 grant
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
2
 show
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
56
 nonceIsValid
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 cookieIsValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 makeGrantCookie
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
2
 serveFile
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
156
 mimeFor
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
240
1<?php
2
3namespace App\Http\Controllers;
4
5use Illuminate\Http\Request;
6use Illuminate\Http\Response;
7use Illuminate\Support\Facades\Cache;
8use Illuminate\Support\Str;
9use Symfony\Component\HttpFoundation\BinaryFileResponse;
10use Symfony\Component\HttpFoundation\Cookie;
11use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
12
13/**
14 * FIRE-1271: serve the PHPUnit coverage HTML report from
15 * storage/coverage/html/ behind the admin gate.
16 *
17 * The report is regenerated on every prod deploy by the runTest route
18 * (routes/api.php) which runs `php artisan test --coverage-html
19 * storage/coverage/html`. No CI change needed.
20 *
21 * Auth flow (two hops, because the report loads sub-assets — CSS/JS/images
22 * via relative URLs from a new browser tab that can't carry a bearer):
23 *
24 *   1. FE calls `GET /api/coverage-grant` with the admin bearer token
25 *      (route protected by auth.token + require.admin). Response is a JSON
26 *      body containing a one-shot `?t=<nonce>` URL. The nonce is stored in
27 *      the cache with a 1-hour TTL.
28 *
29 *   2. FE opens the returned URL in a new tab. The backend validates the
30 *      nonce, sets an HttpOnly cookie scoped to `/api/coverage`, and 302s
31 *      to the canonical index. Every subsequent asset request in that tab
32 *      carries the cookie, so CSS/JS/images all authenticate transparently.
33 *
34 * Replaces the previous public `coverage.*` subdomain iframe embed that
35 * had zero auth.
36 */
37class CoverageController extends Controller
38{
39    private const COOKIE_NAME = 'coverage_grant';
40
41    private const CACHE_PREFIX = 'coverage_grant:';
42
43    /**
44     * Nonce TTL (also the cookie lifetime). One hour is enough for a
45     * browsing session — the admin re-clicks the link if they need
46     * longer. Short TTL keeps the blast radius small if a nonce leaks.
47     */
48    private const GRANT_TTL_MINUTES = 60;
49
50    /**
51     * FIRE-1271 · Step 1: admin bearer → one-shot nonce URL.
52     *
53     * Called by the FE with the admin bearer token; this route sits under
54     * the auth.token + require.admin middleware group in routes/api.php.
55     * Returns a JSON payload with `open_url` — a single-use URL the FE
56     * opens in a new tab to bootstrap the cookie session.
57     */
58    public function grant(Request $request): SymfonyResponse
59    {
60        $nonce = Str::random(64);
61        $userId = optional($request->user())->id;
62
63        Cache::put(
64            self::CACHE_PREFIX.$nonce,
65            ['user_id' => $userId, 'issued_at' => now()->timestamp],
66            now()->addMinutes(self::GRANT_TTL_MINUTES),
67        );
68
69        // Build the open_url from the request itself so we never rely on
70        // APP_URL being aligned with the actual origin. Prod uses
71        // https://fireservicetitan.com:8081, dev uses http://127.0.0.1:8000,
72        // and either way the FE receives a URL that matches the origin it
73        // just called.
74        $base = rtrim($request->getSchemeAndHttpHost(), '/');
75        $openUrl = $base.'/api/coverage?t='.$nonce;
76
77        return response()->json([
78            'open_url' => $openUrl,
79            'expires_in_minutes' => self::GRANT_TTL_MINUTES,
80        ]);
81    }
82
83    /**
84     * FIRE-1271 · Step 2 + serve.
85     *
86     * Two entry points collapse into one method because the coverage
87     * subtree needs to serve arbitrary paths (index.html, dashboard.html,
88     * per-file HTML, _css/*, _js/*, _icons/*, etc). We decide auth once
89     * per request:
90     *
91     *   - If `?t=<nonce>` is present, treat this as the bootstrap: validate
92     *     the nonce in cache, mint the cookie, redirect to the same path
93     *     without the query string so nobody bookmarks the nonce.
94     *
95     *   - Else read the cookie and validate against the cache.
96     *
97     * Either way, once auth is established, we run the path-traversal
98     * defence and stream the file.
99     */
100    public function show(Request $request, ?string $path = null): SymfonyResponse
101    {
102        $nonce = $request->query('t');
103
104        if ($nonce !== null && $nonce !== '') {
105            if (! $this->nonceIsValid($nonce)) {
106                return response('Coverage session expired. Reload the report from Titan.', 403);
107            }
108
109            // Strip the nonce from the URL by redirecting to the target
110            // path without ?t=. Attach the cookie on that response —
111            // browsers apply it before following the redirect, so the next
112            // hop is authenticated automatically.
113            //
114            // Default to index.html (not "/") because the report loads its
115            // sub-assets via relative URLs like `_css/style.css`. If the
116            // browser lands on `/api/coverage` (no trailing slash, no
117            // filename) the relative path resolves against `/api/`, which
118            // 404s. Landing on `/api/coverage/index.html` resolves
119            // sub-assets against `/api/coverage/`, which is correct.
120            //
121            // Relative Location keeps the origin the client hit — url()
122            // would prepend APP_URL which may not match in dev.
123            $redirectTarget = '/api/coverage/'.($path !== null && $path !== '' ? $path : 'index.html');
124
125            return redirect($redirectTarget)
126                ->withCookie($this->makeGrantCookie($nonce));
127        }
128
129        if (! $this->cookieIsValid($request)) {
130            return response('Not authorised. Open the coverage report from Titan.', 403);
131        }
132
133        return $this->serveFile($path);
134    }
135
136    private function nonceIsValid(string $nonce): bool
137    {
138        // Cheap sanity check first so we don't hit the cache with obviously
139        // malformed input.
140        if (strlen($nonce) < 32 || ! ctype_alnum($nonce)) {
141            return false;
142        }
143
144        return Cache::has(self::CACHE_PREFIX.$nonce);
145    }
146
147    private function cookieIsValid(Request $request): bool
148    {
149        $cookie = $request->cookie(self::COOKIE_NAME);
150        if (! is_string($cookie) || $cookie === '') {
151            return false;
152        }
153
154        return $this->nonceIsValid($cookie);
155    }
156
157    private function makeGrantCookie(string $nonce): Cookie
158    {
159        // HttpOnly + SameSite=Lax so the cookie rides top-level navigations
160        // (the new tab we redirected into) but not third-party embeds.
161        // Path-scoped to /api/coverage so no other endpoint ever sees it.
162        // Secure=true in prod (HTTPS); left off in local so dev works over
163        // plain HTTP.
164        return new Cookie(
165            self::COOKIE_NAME,
166            $nonce,
167            now()->addMinutes(self::GRANT_TTL_MINUTES)->timestamp,
168            '/api/coverage',
169            null,
170            secure: app()->environment('production'),
171            httpOnly: true,
172            raw: false,
173            sameSite: Cookie::SAMESITE_LAX,
174        );
175    }
176
177    private function serveFile(?string $path): SymfonyResponse
178    {
179        $root = storage_path('coverage/html');
180        $realRoot = realpath($root);
181
182        if ($realRoot === false) {
183            return response('Coverage report not generated yet.', 404);
184        }
185
186        $requested = $path === null || $path === '' ? 'index.html' : $path;
187
188        // Reject obvious traversal shapes before touching the filesystem.
189        // Explicit checks (not one big regex) keep the failure modes easy
190        // to read in logs.
191        if (str_contains($requested, "\0")) {
192            return response('Invalid path.', 400);
193        }
194        if (str_contains($requested, '..')) {
195            return response('Invalid path.', 400);
196        }
197        if (str_starts_with($requested, '/') || str_starts_with($requested, '\\')) {
198            return response('Invalid path.', 400);
199        }
200
201        $target = $realRoot.DIRECTORY_SEPARATOR.$requested;
202        $realTarget = realpath($target);
203
204        if ($realTarget === false || ! is_file($realTarget)) {
205            return response('File not found.', 404);
206        }
207
208        // Final containment check — a realpath that resolved outside the
209        // coverage root means a symlink or path oddity slipped through
210        // the simple string checks above.
211        if (! str_starts_with($realTarget, $realRoot.DIRECTORY_SEPARATOR) && $realTarget !== $realRoot) {
212            return response('Invalid path.', 400);
213        }
214
215        $response = new BinaryFileResponse($realTarget);
216        $response->headers->set('Content-Type', $this->mimeFor($realTarget));
217        // No caching — coverage changes on every deploy and we want admins
218        // to see the latest without a hard refresh.
219        $response->headers->set('Cache-Control', 'no-store, must-revalidate');
220
221        return $response;
222    }
223
224    /**
225     * Best-effort mime lookup. `mime_content_type` returns text/plain for
226     * .css / .js / .html because it sniffs content — override those
227     * explicitly so browsers render the report with the correct styling
228     * and behaviour.
229     */
230    private function mimeFor(string $file): string
231    {
232        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
233
234        return match ($ext) {
235            'html', 'htm' => 'text/html; charset=UTF-8',
236            'css' => 'text/css; charset=UTF-8',
237            'js' => 'application/javascript; charset=UTF-8',
238            'json' => 'application/json',
239            'svg' => 'image/svg+xml',
240            'png' => 'image/png',
241            'jpg', 'jpeg' => 'image/jpeg',
242            'gif' => 'image/gif',
243            'woff' => 'font/woff',
244            'woff2' => 'font/woff2',
245            'ttf' => 'font/ttf',
246            'xml' => 'application/xml; charset=UTF-8',
247            default => mime_content_type($file) ?: 'application/octet-stream',
248        };
249    }
250}