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

Security11 min read

Broken access control: the id in the URL, the field in the form, the route that forgot

Four ordinary features, added the way features are added: a JSON endpoint that skipped the policy, a profile form fed the whole request, a delete on GET, an admin route outside its group. Each with the test that went red, the fix, and two route-level invariants.

By Abhishek Fouzdar

Broken access control has been first on the OWASP Top 10 since 2021, and it is first because it is less a bug class than a habit: every new endpoint is a new place to forget who is allowed. This part adds four ordinary features to NoteMini from part 1, the way such features are added, and for each one shows the code as it was written, why the check is not there, the test that goes red, and the fix at the layer that holds. A JSON endpoint, a profile form, a one-click delete and a CSV export. Four red tests, four green, and two route-level invariants that keep the last two mistakes from coming back.

1. The id in the URL

The mobile client needs JSON. It signs in through the web form inside a web view and sends the session cookie, so the new endpoint goes behind auth and reads a note by id:

Route::middleware('auth')->prefix('api')->group(function () {
    Route::get('/notes', [Api\NoteController::class, 'index']);
    Route::get('/notes/{id}', [Api\NoteController::class, 'show']);
});
public function index(): JsonResponse
{
    return response()->json(Note::latest('updated_at')->limit(50)->get(['id', 'title', 'updated_at']));
}

public function show(int $id): JsonResponse
{
    $note = Note::with('author:id,name')->findOrFail($id);

    return response()->json(['id' => $note->id, 'title' => $note->title, 'body' => $note->body, /* … */]);
}

The web controller for the same note calls $this->authorize('view', $note) on its first line. Nobody copied that line, because the new controller was not copied from the old one. It was written fresh, for a different client, in a different directory, by someone whose task was "return the note as JSON", and the task was done when the JSON came back. This is how most access control bugs arrive: not as a missing policy, but as a new path to the data that the policy was never asked about.

Why the code lets it through: auth establishes that someone is signed in, and that is all it establishes. findOrFail confirms that a row with this id exists. Between those two facts there is no step that connects the person to the row, so the only input the endpoint acts on is a number the client typed, and the note's team, author and policy are never consulted. The list endpoint is the same gap in a different shape: Note::latest() is every note in the table, and limit(50) is the only thing standing between one team and another's.

The test, written as a member of another team:

it('refuses a note to a member of another team over the JSON endpoint too', function () {
    $alice = owner();
    $note = Note::factory()->for($alice->teams->first())->for($alice, 'author')->create(['title' => 'Q4 pricing']);
    $mallory = owner();

    $this->getJson("/api/notes/{$note->id}")->assertUnauthorized();
    $this->actingAs($mallory)->getJson("/api/notes/{$note->id}")->assertForbidden();
    $this->actingAs($mallory)->getJson('/api/notes')->assertOk()->assertDontSee('Q4 pricing');
});
  ⨯ it refuses a note to a member of another team over the JSON endpoint too
  Expected response status code [403] but received 200.

The fix lets the framework do the two things it already knows how to do. Route model binding turns {note} into a model and answers 404 when there is none; the policy, the same one the web routes use, decides whether this user may see it; and the list is scoped the way the web list is, through the current team that the team middleware already resolved:

Route::middleware(['auth', 'team'])->prefix('api')->group(function () {
    Route::get('/notes', [Api\NoteController::class, 'index']);
    Route::get('/notes/{note}', [Api\NoteController::class, 'show']);
});
public function index(Request $request): JsonResponse
{
    $team = $request->attributes->get('team');

    return response()->json($team->notes()->latest('updated_at')->limit(50)->get(['id', 'title', 'updated_at']));
}

public function show(Note $note): JsonResponse
{
    $this->authorize('view', $note);
    // …
}

Two rules fall out of this. An int $id parameter on a controller method is a smell: it means the method is about to look something up itself, and a lookup the controller does itself is a lookup nobody authorised. And findOrFail is not an access control, however much it reads like one; existence and permission are different questions, and the policy is where the second one is answered. The guest line in the test is there because JSON routes are where authentication gets dropped as often as authorisation: the auth middleware answers a JSON request with a 401 rather than a redirect to the sign-in page, and the test pins that behaviour so a later "make the API public for the marketing site" does not pass unnoticed.

2. The field in the form

The profile page lets people change their name and email. The controller validates both and saves:

$request->validate([
    'name' => ['required', 'string', 'max:100'],
    'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($request->user())],
]);

$request->user()->update($request->all());

On its own that last line is survivable, because User::$fillable is ['name', 'email', 'password'] and update() discards everything else. The weakness arrives on the model, from the other direction. Part 1's admin controller grants admin with forceFill(['is_admin' => …]), and forceFill reads like a hack, so at some point someone made it unnecessary:

protected $fillable = ['name', 'email', 'password', 'is_admin'];

Two reasonable changes, in two files, probably by two people, and the profile form is now an admin form. Why: update($request->all()) hands the model every field the request carried, not every field the form showed, and the model's list is the only thing deciding which of those land. A field that is on the list, whatever form it came from, is written. Mass assignment is not a bug in $fillable; it is the combination of an unfiltered input array with a list that was edited for a different reason.

The test posts two fields the form does not have:

it('does not let a user grant themselves admin, or change their password, through the profile form', function () {
    $mallory = owner();

    $this->actingAs($mallory)->put('/profile', [
        'name' => 'Mallory', 'email' => $mallory->email,
        'is_admin' => 1, 'password' => 'a password she chose',
    ])->assertRedirect();

    $mallory->refresh();
    expect($mallory->is_admin)->toBeFalse()
        ->and(Hash::check('a password she chose', $mallory->password))->toBeFalse();
});
  ⨯ it does not let a user grant themselves admin, or change their password, through the profile form
  Failed asserting that true is false.

The second half of the test matters as much as the first. password was on the fillable list all along, legitimately, for registration. The profile form never asked for it, but $request->all() passed it through and the hashed cast stored it. A field the form does not show is still a field the request can carry, and a change of password without the old password is an account takeover waiting for a session to be borrowed.

Three fences, in the order of how much each is worth:

$data = $request->validate([
    'name' => ['required', 'string', 'max:100'],
    'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($request->user())],
]);

$request->user()->update($data);

The array validate() returns contains the validated keys and nothing else. Whatever the request carried, the model sees name and email. This is the fence that holds, and it holds regardless of what any model's list says, which matters because $fillable is one shared, global, easily edited array and the validation rules sit in the method that uses them. $request->all() has no place in a call to update() or create(). $request->validated(), $request->safe()->only([…]) and the return value of validate() are the three spellings of the fix.

The second fence is the model's list, back to ['name', 'email', 'password'], with is_admin set only by forceFill in the admin controller, on its own route, behind its own gate, from its own validated boolean. forceFill is not a hack. It is the method whose name says the caller has decided, and a reader who meets it knows to look for the gate above it.

The third is a setting, in AppServiceProvider::boot():

Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction());

With it, filling an attribute the model does not allow throws MassAssignmentException outside production instead of dropping the attribute on the floor. Silence is the problem here: a form that posts a field the model ignores is a non-event, and non-events do not fail tests. With the setting on, the day someone adds a field to the list, or passes all() somewhere new, a feature test that posts an extra field fails in CI rather than in a breach.

A one-click delete in the notes list, so nobody has to open a note to remove it:

Route::get('/notes/{note}/delete', [NoteController::class, 'destroy'])->name('notes.quick-delete');
@can('delete', $note) <a href="{{ route('notes.quick-delete', $note) }}">delete</a> @endcan

The controller still authorises, the policy still says only the author or an owner may delete, and the link only renders for people who may. Every access check is in place and the feature is still wrong, because of what a GET request is.

A browser sends GET requests on behalf of whatever page it is showing. An image tag, a stylesheet link, a prefetch hint, a redirect: each one is a GET to a URL the page chose, carrying the cookies the browser holds for that site, with no click and no confirmation. Laravel's CSRF protection exists for exactly this and it is on by default, but it protects POST, PUT, PATCH and DELETE, because those are the methods the HTTP specification reserves for changes. A route that changes state on GET has opted out of the protection by choosing the one method it does not cover. The author of the note is signed in, the policy says yes, and the request came from a page the author never meant to act on.

The test is the shortest in the suite:

it('does not change anything on a GET request, however the link was reached', function () {
    $alice = owner();
    $note = Note::factory()->for($alice->teams->first())->for($alice, 'author')->create();

    $this->actingAs($alice)->get("/notes/{$note->id}/delete");

    expect(Note::whereKey($note->id)->exists())->toBeTrue();
});
  ⨯ it does not change anything on a GET request, however the link was reached
  Failed asserting that false is true.

The fix is to make the one-click delete a form. It looks the same in the list, it is one click, and it is a DELETE request with a token the page issued:

@can('delete', $note)
    <form method="post" action="{{ route('notes.destroy', $note) }}" class="inline">
        @csrf @method('delete')
        <button class="quiet" type="submit">delete</button>
    </form>
@endcan

The GET route is gone. The rule is older than Laravel and the framework's middleware encodes it: GET reads, everything else needs a token. Because this rule is about routes rather than code, it can be checked at the route table, and the last section does that.

4. The route that forgot

The admin wants the user list as CSV. The export method goes in the admin controller next to the list, the method is correct, and the route is added at the bottom of routes/web.php, after the admin group, because that is where the cursor was:

Route::middleware(['auth', 'can:admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/users', [Admin\UserController::class, 'index'])->name('users.index');
    Route::patch('/users/{user}', [Admin\UserController::class, 'update'])->name('users.update');
});

// …forty lines later

Route::get('/admin/export', [Admin\UserController::class, 'export'])->middleware('auth')->name('admin.export');

It has auth. It lives under /admin. It is in the admin controller. Everything about it says admin except the one thing that decides, which is the middleware list, and that says "anyone signed in". The admin link in the navigation is wrapped in @can('admin'), so no non-admin ever sees the link, which is OWASP's third scenario for this category word for word: an access control that exists in the view and nowhere else.

it('refuses every admin route to a user who is not an admin', function () {
    $mallory = owner();

    $this->actingAs($mallory)->get('/admin/users/export')->assertForbidden();
});
  ⨯ it refuses every admin route to a user who is not an admin
  Expected response status code [403] but received 200.

The fix is one move, into the group, where the gate applies to everything by construction:

Route::middleware(['auth', 'can:admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/users', [Admin\UserController::class, 'index'])->name('users.index');
    Route::get('/users/export', [Admin\UserController::class, 'export'])->name('users.export');
    Route::patch('/users/{user}', [Admin\UserController::class, 'update'])->name('users.update');
});

That fixes this route. It does nothing about the next one, and the next one will be added the same way, so the test that stays is not about /admin/users/export. It is about the route table:

it('puts every route under /admin behind the admin gate', function () {
    $unguarded = collect(Route::getRoutes()->getRoutes())
        ->filter(fn ($route) => str_starts_with($route->uri(), 'admin'))
        ->reject(fn ($route) => in_array('can:admin', $route->gatherMiddleware(), true))
        ->map(fn ($route) => implode('|', $route->methods()).' /'.$route->uri())
        ->values()
        ->all();

    expect($unguarded)->toBe([]);
});

And the same idea for section 3:

it('never answers a GET with a change', function () {
    $changing = collect(Route::getRoutes()->getRoutes())
        ->filter(fn ($route) => in_array('GET', $route->methods(), true))
        ->filter(fn ($route) => preg_match('/@(store|update|destroy|switch|invite|remove)$/', $route->getActionName()) === 1)
        ->map(fn ($route) => 'GET /'.$route->uri().' → '.$route->getActionName())
        ->values()
        ->all();

    expect($changing)->toBe([]);
});

Both run in a few milliseconds, both fail with the offending route in the message, and both encode a rule that was previously in someone's head: everything under /admin is gated, and GET never changes anything. The convention they depend on, that the admin routes share a prefix and that changing methods have conventional names, is cheap to keep and is itself a kind of access control: a structure the test can read.

The results

The attack suite after this part:

  ✓ it refuses a note to a member of another team
  ✓ it keeps another team's notes out of the list and the search
  ✓ it refuses an attachment to a member of another team, even by guessing its id
  ✓ it refuses the admin area to a signed-in user who is not an admin
  ✓ it does not let a user make themselves an admin through any form
  ✓ it does not open a shared note to a wrong, expired or revoked token
  ✓ it refuses a team page, an invite and a removal to a non-member
  ✓ it refuses a note to a member of another team over the JSON endpoint too
  ✓ it renders a note body that carries script as text, not as script
  ✓ it treats a search term and a sort column as data, not as SQL
  ✓ it stores an upload where the web server cannot execute or serve it
  ✓ it refuses to clip an address that resolves to a private network
  ✓ it does not let a user grant themselves admin, or change their password, through the profile form
  ✓ it does not change anything on a GET request, however the link was reached
  ✓ it refuses every admin route to a user who is not an admin
  ✓ it puts every route under /admin behind the admin gate
  ✓ it never answers a GET with a change

  Tests:    17 passed (63 assertions)

Seventeen, from eleven; the feature suite is at twenty-eight. The ZAP baseline, signed in, spidered 112 URLs and reported the same eleven warnings as part 1, which is expected: a baseline scan is passive, and none of this part's four mistakes shows in a response header. Access control is the category a scanner is worst at, because the scanner has one account and the bug needs two. The tests have two.

One alert did change. Information Disclosure - Debug Error Messages x 1 is still there, on a different request: POST /notes/9/share answered 500, this time with a foreign key failure from the share link insert. The spider runs several threads, one of which had submitted the delete form for note 9 while another was still on its page; the share request found the note by binding, then inserted a row pointing at an id that no longer existed. That is a race the application should answer with a 404 or a 409, not a 500, and it goes on the list for part 6, which is about what an application does when the world changes under it.

What went wrong

The guest request was not a guest. The first version of the JSON test made the signed-out request last, and it got a 403 instead of a 401. actingAs() sets the user on the guard for the rest of the test, not for one request, so the "guest" was still Mallory. The guest request now comes first, and the general rule is that any test mixing identities should start with the one that has none.

The route invariant caught its own author. "Never answers a GET with a change" matched on method names, and the first list of names included export, which is a GET and a read. The test failed on the route it was written next to. The list is now the six names that change something, and the failure message prints the route, which is how a test like this earns its keep: when it fails in a year, it says which route and which method, and the reader decides whether the route or the list is wrong.

The scanner raced itself. The 500 above is not a NoteMini bug the tests could have found, because the test client runs one request at a time. The spider's threads found it in seconds. A scanner is also a load test with no manners, and the errors it leaves in the log are worth reading for that reason alone.

Part 3 moves from who may ask to what they send: the search box, the sort menu, the Markdown body, the upload and anything that reaches a shell: Injection and output: the search, the sort, the Markdown body, the upload and the shell.

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.