Security beyond the checklist in a Laravel app · Part 5 of 6

Security9 min read

Security misconfiguration and data integrity: headers, debug mode and a signed link

The headers the scanner flagged since part 1, set at the edge so error pages carry them too; version banners off; debug mode as the worst production mistake; cookies explained; and a signed download link whose signature nothing checked. Nine warnings to two.

By Abhishek Fouzdar

The first four parts fixed things in the code. This one fixes things about how the code is served, which is the OWASP category called Security Misconfiguration, and one thing about what the application trusts on the way back in, which is Software or Data Integrity Failures. It is also where the scanner finally earns its place in the series: the header warnings it has reported since part 1, nine of them, go to two, and the two that remain are there on purpose. NoteMini from part 4 gets a set of response headers, a quieter server, and a signed link that is actually checked.

1. The headers, and why the middleware was the wrong place

Here is the whole of the scanner's complaint, carried unchanged from part 1 because nothing in the four code parts touched it:

WARN  Content Security Policy (CSP) Header Not Set
WARN  Missing Anti-clickjacking Header
WARN  X-Content-Type-Options Header Missing
WARN  Permissions Policy Header Not Set
WARN  Cross-Origin-Resource-Policy Header Missing or Invalid
WARN  Server Leaks Version Information via "Server" HTTP Response Header Field
WARN  Server Leaks Information via "X-Powered-By" HTTP Response Header Field(s)
WARN  Cookie No HttpOnly Flag
WARN  Big Redirect Detected

These are not bugs in the sense the earlier parts were; the application works without them. They are the browser's safety features, each turned on by a header, and off by their absence. The important ones:

  • Content-Security-Policy tells the browser which sources of script, style and images to trust, and to refuse the rest. It is the second fence behind part 3's output escaping: even if a script tag reached a page, a policy of script-src 'self' refuses to run it. NoteMini uses no inline script, so the policy can be strict.
  • X-Frame-Options: DENY (and CSP's frame-ancestors 'none') stop another site from loading NoteMini in an invisible frame and tricking a user into clicking through it, which is clickjacking.
  • X-Content-Type-Options: nosniff stops the browser from guessing that a file is HTML or script when the server said it was something else, which is half of how a crafted upload becomes an executed page.
  • Referrer-Policy and Permissions-Policy limit what the browser tells other sites about where a user came from, and which device features a page may ask for.

The instinct is to set these in middleware, and the first version of the fix did:

class SecurityHeaders
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        $response->headers->set('Content-Security-Policy', "default-src 'self'; script-src 'self'; …");
        // …the rest
        return $response;
    }
}

It worked for every normal page, and the scanner's warnings dropped from nine to six. The six that stayed were the clue. A request for a path that matches no route, or a POST whose CSRF token is missing, does not return from the middleware with a response; it throws, and the framework renders the 404 or the 419 from its exception handler, which sits outside the middleware stack. So the error pages came back with no headers, and a 404 is a page a browser renders like any other. Middleware covers the responses the application returns; it does not cover the responses the framework renders when the application was never reached. Static files, served by nginx directly, were uncovered for the same reason: the request never entered PHP.

The place that covers all of them is the edge. nginx sees every response, the application's and the framework's and the static files', and add_header … always adds a header even to the 4xx and 5xx responses:

server {
    server_tokens off;

    add_header X-Content-Type-Options nosniff always;
    add_header X-Frame-Options DENY always;
    add_header Referrer-Policy strict-origin-when-cross-origin always;
    add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; form-action 'self'; frame-ancestors 'none'; base-uri 'self'" always;
    add_header Cross-Origin-Opener-Policy same-origin always;
    add_header Cross-Origin-Resource-Policy same-origin always;
    # …
}

server_tokens off is the other half of the section. By default nginx puts its version in the Server header and on its own error pages, and PHP puts its version in X-Powered-By; both are a free hint to anyone matching known versions to known vulnerabilities. server_tokens off drops the nginx version to the bare word nginx, and expose_php = Off in the PHP configuration removes X-Powered-By entirely. Neither closes a hole by itself; both remove a line from the attacker's reconnaissance, and cost nothing.

There is no new attack test here, because the instrument for this section is the scanner, and the number is the point. Where a test does fit, the edge makes it awkward: a feature test runs the application's kernel, not nginx, so it cannot see a header nginx adds. That is the honest trade. Headers at the edge cover every response and are verified by the scan; headers in middleware are unit-testable but miss the error pages. For a real deployment the edge wins, and the scan is how you check it.

2. Debug mode, and the page that tells everyone everything

Three times in this series the scanner reported Information Disclosure - Debug Error Messages, each time against a request that returned a 500: the share form in part 1, a race in the spider in part 2. Each of those 500s rendered Laravel's debug error page, and the debug error page is, by design, a confession. When APP_DEBUG is true, an unhandled exception produces a page with the stack trace, the exact file and line, the configuration values in scope, often the failing query with its bindings, and a view of the environment. In development that page is the best debugging tool Laravel has. In production it is the single most damaging misconfiguration a Laravel application can ship with, because one forced error hands an attacker the map.

There is no clever fix; there is a setting, and the discipline to get it right per environment. In production, APP_DEBUG=false, and an unhandled exception renders a plain error page with no detail. The development stack keeps APP_DEBUG=true, because that is what development is for, and the two must never be confused, which is why the value lives in the environment and not in a committed config file. The PHP configuration says the same thing from the other side: display_errors is On in the development image and must be Off in production, so that a fatal error below the framework does not print a PHP trace to the page.

This is also where the earlier 500s stop being someone else's problem. A 500 is not only a bug; with debug on it is a disclosure, and with debug off it is still a worse experience than the 404 or 409 the situation deserved. The share-form 500 from part 1 was a plain bug and was fixed. The ones that remain, a request that races a deletion and dies on a missing row, belong to the last category in the Top 10, handling the unexpected, and are part 6's subject. The rule this section leaves is narrow and absolute: APP_DEBUG=false in production, checked, because nothing else in the application matters if a forced error prints the keys.

3. The cookies, and what the browser is told to protect

Two of the scanner's warnings were about cookies, and they pull in opposite directions, which is why they are worth separating. Laravel's session cookie is already handled well: it is HttpOnly, so script cannot read it, which is what keeps an XSS from stealing a session; it is SameSite=Lax by default, so it is not sent on cross-site POSTs, which is part of what keeps CSRF from working; and it is encrypted. The one production setting the development stack cannot carry is Secure, which tells the browser never to send the cookie over plain HTTP. It is off here because the stack is HTTP, and it is SESSION_SECURE_COOKIE=true in production, where the session cookie travels only over TLS. The same TLS front end sets Strict-Transport-Security, which tells the browser to refuse HTTP for the site entirely from then on; it is not set on the HTTP development stack, because a browser ignores it over HTTP anyway.

The warning that stays, Cookie No HttpOnly Flag, is on a different cookie and is correct to stay. Laravel issues an XSRF-TOKEN cookie that is deliberately readable from JavaScript, so that a front end can read it and send it back as the X-XSRF-TOKEN header, which is how the framework's CSRF protection works for anything that is not a plain form post. A readable CSRF token is not a readable session: the token is useless without a session to go with it, and the session cookie it protects is the one with HttpOnly. This is the difference between a scanner finding and a vulnerability. The scanner reports every cookie without the flag, because it cannot know which cookies are secrets; a person reads the two it found, sees that the secret one has the flag and the deliberately-readable one does not, and marks it understood. A clean scan is not the goal; an explained scan is.

4. The signature that was never checked

The last piece is not about how the app is served but about what it trusts. NoteMini gets a feature to export a note as a text file through a link the user can send to themselves, good for an hour. Laravel has exactly the tool: a signed URL, which carries a signature over its parameters and expiry, computed with the application key:

$url = URL::temporarySignedRoute('notes.download', now()->addHour(), ['note' => $note]);

The link generator is correct. The route that receives the link is where it goes wrong:

Route::get('/d/{note}', [NoteExportController::class, 'download'])->name('notes.download');

The signature is in the URL and nothing checks it. The signed middleware, which recomputes the signature and refuses the request if it does not match, is not on the route, so the parameters the signature was meant to protect are free to change. The note id is one of those parameters, and the download has no other access control, because a signed URL is supposed to be the access control. So the link for one note becomes the link for any note by changing the id, and the signature that was meant to prevent exactly that rides along, ignored.

The test makes a valid link for one note and changes the id to a note in another team:

it('honours the signature on a download link and refuses a tampered one', function () {
    $alice = owner();
    $aliceNote = Note::factory()->for($alice->teams->first())->for($alice, 'author')->create(['title' => 'Mine']);
    $mallory = owner();
    $secret = Note::factory()->for($mallory->teams->first())->for($mallory, 'author')->create(['title' => 'Competitor research']);

    $valid = URL::temporarySignedRoute('notes.download', now()->addHour(), ['note' => $aliceNote]);
    $this->get($valid)->assertOk()->assertSee('Mine');

    $tampered = str_replace('/d/'.$aliceNote->id, '/d/'.$secret->id, $valid);
    $this->get($tampered)->assertForbidden();

    $this->get('/d/'.$secret->id)->assertForbidden();
});
  ⨯ it honours the signature on a download link and refuses a tampered one
  Expected response status code [403] but received 200.

The tampered link returned another team's note. The fix is the middleware whose whole job is to check the signature:

Route::get('/d/{note}', [NoteExportController::class, 'download'])->middleware('signed')->name('notes.download');

Now the signature is recomputed over the parameters as they arrive, and a changed id or a stretched expiry produces a signature that does not match, so the request is refused with a 403 before the controller runs. The general shape is the integrity-failures category in one line: data that left the server and came back, trusted without checking that it came back unchanged. A signed URL is the right tool and was reached for; the signing is only half of it, and the checking is the half that holds. The same mistake wears other clothes elsewhere, a value round-tripped through a hidden form field and trusted, a serialized object read back from a cookie, a webhook acted on without verifying its signature, and the fix is always the second half: verify what you signed.

The numbers

The scanner's warnings across the series, from a signed-in baseline scan at the end of each part:

After part WARN What changed
1 11 the starting state: headers, banners, cookies
2 11 access control is invisible to a passive scan
3 9 the share-form 500 was fixed, so its disclosure went
4 9 authentication is invisible to a passive scan too
5 2 headers at the edge, versions off, debug understood

The two that remain are the readable XSRF-TOKEN cookie, which is correct, and a "big redirect" on the form posts that flash their input back, which is Laravel working as designed. There are no failures and sixty-five of the scanner's rules pass. The feature suite is at thirty-seven and the attack suite at twenty-seven.

The shape of that table is the honest summary of what a passive scanner is for. It found the headers and the banners, which are real and which it is better at than a person, because it never forgets to check. It was blind to the access-control and authentication and injection bugs of parts 2, 3 and 4, which is why those parts leaned on tests. And it reported, every time, things that were correct, which a person had to read and clear. A scanner is a checklist that runs; this series is about the part that a checklist cannot do.

What went wrong

Removing the middleware broke the site. When the headers moved to the edge, the middleware class was deleted, but the line that registered it had been reformatted by the code styler into a shape the delete did not match, so the registration stayed, now pointing at a class that no longer existed. Every page returned 500. The lesson is the same one as part 2's missing alias, from the other direction: a reference to a class that is gone fails as loudly as a name with no definition, and the fix is to remove both ends, not one.

A clean scan was never the target. It would have been easy to chase the last two warnings to zero by stripping the XSRF-TOKEN cookie's purpose or suppressing the redirect, and both would have been worse than the warning. The goal the series settled on is an explained scan: every remaining line understood and written down, which is a stronger position than a zero that was reached by breaking something useful.

Part 6 is the last one, and it takes the category the 2025 list added, handling the unexpected, together with what the application records when something goes wrong and what it trusts in its supply chain: Supply chain, logging and the unexpected: composer audit, what to record, and failing closed.

New posts by email

Get new posts by email. Nothing else, no digests, unsubscribe in one click.

Comments

Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.