Pattern Playbook

Course › Day 4 · Hosts and guests › Scene 19 of 49 · 20 min

A host saw another host’s bookings

IDOR, queries that start from the account, policies with 404s, scoped exists rules, no mass assignment

On this page
  1. The incident
  2. The broken code
  3. The fix, part 1: one current account per request
  4. The fix, part 2: lists start from the account
  5. The fix, part 3: single records go through a policy
  6. The fix, part 4: input is scoped too
  7. Laravel inside: scoped route bindings
  8. Tests
  9. Remember

#securityMonday 09:00

Email from a hostHi, I opened one of my bookings and changed the 812 in the address to 813. I can now see a booking for a property that isn’t mine: the guest’s name, email and what they paid. I stopped there. You might want to look at this.

Sara · tech leadThat’s an IDOR. Every account’s data is one number away from every other account. Nobody touches anything else until this is closed.

The broken code

Nordic Stays is multi-tenant: many host companies (accounts, from the foundation) share one database. Three new endpoints were added to the booking controller in a hurry: index, show and move.

app/Http/Controllers/BookingController.php (before)the bug
<?php

namespace App\Http\Controllers;

use App\Bookings\CreateBooking;
use App\Http\Requests\StoreBookingRequest;
use App\Http\Resources\BookingResource;
use App\Models\Booking;
use App\Models\Property;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class BookingController extends Controller
{
    public function store(StoreBookingRequest $request, Property $property, CreateBooking $createBooking): BookingResource
    {
        $booking = $createBooking->handle(
            $property,
            $request->stay(),
            $request->safe()->only(['guest_name', 'guest_email', 'guests']),
        );

        return new BookingResource($booking);
    }

    public function index(): AnonymousResourceCollection
    {
        return BookingResource::collection(Booking::latest()->paginate());       // every account's bookings
    }

    public function show(Booking $booking): BookingResource
    {
        return new BookingResource($booking);                                     // any id works: the IDOR
    }

    public function move(Request $request, Booking $booking): BookingResource
    {
        $request->validate(['property_id' => 'required|exists:properties,id']);  // exists in ANY account
        $booking->update($request->all());                                        // and every other column too

        return new BookingResource($booking);
    }
}

IDOR (insecure direct object reference) means: the app checks that you’re logged in, but not that the thing you asked for is yours. Ids are sequential, so trying 813, 814, 815 is all it takes.

exists:properties,id checks that the property exists, not that it belongs to you, so a booking can be moved into another account. And $request->all() passes whatever the request contains to the model: a crafted request could change status or total_cents. (The $fillable list from the foundation limits that damage; validated input is what stops it.)

How the fix works, in one picture

Before

/bookings/813Booking::find(813)another host’s booking

The lookup found any booking by its number.

After

/bookings/813$account->bookings()404another account’s ids don’t exist

Every query starts from the current account; anything else is a 404.

The fix, part 1: one current account per request

A user can belong to several accounts (memberships) and works in one at a time (current_account_id). A middleware resolves that account once per request and refuses the request if the user isn’t actually a member, for example after being removed (scene 20).

app/Http/Middleware/SetCurrentAccount.phpnew file
<?php

namespace App\Http\Middleware;

use App\Models\Account;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SetCurrentAccount
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        $account = $user?->current_account_id ? Account::find($user->current_account_id) : null;

        if ($account === null || $user->roleIn($account->id) === null) {
            abort(403, 'Choose an account you are a member of.');
        }

        app()->instance(Account::class, $account);              // anything that asks for "Account" gets this one

        return $next($request);
    }
}

The routes in part 3 run it right after auth:sanctum. Under Octane, where the app stays in memory between requests, register Account with $this->app->scoped() so it is forgotten after each request (scene 45).

The fix, part 2: lists start from the account

The rule that prevents most leaks is about where a query starts. Booking::query() starts from every booking in the database. $account->bookings() starts from this account’s bookings, so forgetting a where can only ever show too little.

The account gets one relation that reaches its bookings through its properties:

app/Models/Account.phpchanged since scene 13: +7
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsToMany;use Illuminate\Database\Eloquent\Relations\HasMany;use Illuminate\Database\Eloquent\Relations\HasManyThrough; class Account extends Model{
18 unchanged lines use HasFactory; protected $fillable = ['name']; public function users(): BelongsToMany { return $this->belongsToMany(User::class, 'memberships') ->using(Membership::class) ->withPivot('role') ->withTimestamps(); } public function properties(): HasMany { return $this->hasMany(Property::class); } public function channelConnections(): HasMany
{ return $this->hasMany(ChannelConnection::class); } /** Bookings of all this account's properties: bookings → properties.account_id */ public function bookings(): HasManyThrough { return $this->hasManyThrough(Booking::class, Property::class); }}

The whole controller after this scene; index() starts from the account, show() and move() rely on the policies and the request below:

app/Http/Controllers/BookingController.php (after)changed since the version above: +14 −11
<?php namespace App\Http\Controllers; use App\Bookings\CreateBooking;use App\Http\Requests\MoveBookingRequest;use App\Http\Requests\StoreBookingRequest;use App\Http\Resources\BookingResource;use App\Models\Account;use App\Models\Booking;use App\Models\Property;use Illuminate\Http\Request;use Illuminate\Http\Resources\Json\AnonymousResourceCollection; class BookingController extends Controller
9 unchanged lines{ public function store(StoreBookingRequest $request, Property $property, CreateBooking $createBooking): BookingResource { $booking = $createBooking->handle( $property, $request->stay(), $request->safe()->only(['guest_name', 'guest_email', 'guests']), );
return new BookingResource($booking); } public function index(): AnonymousResourceCollection { return BookingResource::collection(Booking::latest()->paginate()); // every account's bookings public function index(Account $account): AnonymousResourceCollection { return BookingResource::collection( $account->bookings()->latest('bookings.id')->cursorPaginate(50), // the account is injected by the middleware ); } public function show(Booking $booking): BookingResource { return new BookingResource($booking); // any id works: the IDOR } public function move(Request $request, Booking $booking): BookingResource { $request->validate(['property_id' => 'required|exists:properties,id']); // exists in ANY account $booking->update($request->all()); // and every other column too return new BookingResource($booking); // the route's policy has checked it } public function move(MoveBookingRequest $request, Booking $booking): BookingResource { $booking->property_id = $request->validated('property_id'); // one field, by name, after validation $booking->save(); // (Day 5 adds the availability check) return new BookingResource($booking); }}

There is no $request->all() left anywhere in the app, and a Larastan rule or a simple CI grep keeps it that way (scene 47).

The fix, part 3: single records go through a policy

A record found by its id in the URL gets the same check every time: is the user a member of the account that owns it? The policy is the one place that answers. can() on the route runs it before the controller, so a controller can’t forget.

app/Policies/BookingPolicy.phpnew file
<?php

namespace App\Policies;

use App\Enums\MembershipRole;
use App\Models\Booking;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class BookingPolicy
{
    public function view(User $user, Booking $booking): Response
    {
        return $this->member($user, $booking) ? Response::allow() : Response::denyAsNotFound();   // 404, not 403
    }

    public function update(User $user, Booking $booking): Response
    {
        if (! $this->member($user, $booking)) {
            return Response::denyAsNotFound();
        }

        return in_array($user->roleIn($booking->property->account_id), [MembershipRole::Owner, MembershipRole::CoHost], true)
            ? Response::allow()
            : Response::deny('Only owners and co-hosts can change bookings.');     // a member may know it exists
    }

    private function member(User $user, Booking $booking): bool
    {
        return $user->roleIn($booking->property->account_id) !== null;
    }
}

Routes: every id is checked

For another account’s booking the policy answers 404, not 403: a 403 would confirm that booking 813 exists. Response::denyAsNotFound() does exactly that. A member without the right role gets a 403, because they may know the booking exists. Property routes keep the plain 403 from scene 3: a listing is public (guests find it in search), so its id is no secret; a booking’s is.

Every host route now lives in one group: logged in, inside the current account, and every booking id checked. The cancel, payment and mark-paid routes from earlier scenes move into it too.

routes/api.phpchanged since scene 14: +21 −24
7 unchanged lines<?php use App\Http\Controllers\BookingController;use App\Http\Controllers\BookingPaymentController;use App\Http\Controllers\CancelBookingController;use App\Http\Controllers\ChannelWebhookController;use App\Http\Controllers\CustomOfferController;
use App\Http\Controllers\MarkBookingPaidController;use App\Http\Controllers\QuoteController;use App\Http\Controllers\StripeWebhookController;use App\Http\Middleware\SetCurrentAccount;use Illuminate\Support\Facades\Route; // Laravel serves this file under /api: the full URL is /api/v1/properties/{property}/bookings.Route::get('/v1/properties/{property}/quote', QuoteController::class); // public: guests aren't logged in Route::post('/v1/properties/{property}/bookings', [BookingController::class, 'store']) ->middleware('auth:sanctum') ->can('createBooking', 'property'); Route::post('/v1/properties/{property}/offers', CustomOfferController::class) // a host prices an offer for one guest ->middleware('auth:sanctum') ->can('createBooking', 'property'); Route::post('/v1/bookings/{booking}/payment', BookingPaymentController::class) ->middleware('auth:sanctum'); Route::post('/v1/bookings/{booking}/cancel', CancelBookingController::class) ->middleware('auth:sanctum'); // who may: scenes 19 and 20 Route::post('/v1/bookings/{booking}/mark-paid', MarkBookingPaidController::class) ->middleware('auth:sanctum'); // who may: scenes 19 and 20 // Stripe calls this, not a browser. API routes have no CSRF check, which Stripe couldn't pass.// Laravel serves this file under /api. // Public: guests aren't logged in when they look at prices.Route::get('/v1/properties/{property}/quote', QuoteController::class); // Everything a host does: logged in, inside one current account, every id checked by a policy.Route::middleware(['auth:sanctum', SetCurrentAccount::class])->prefix('v1')->group(function (): void { Route::post('/properties/{property}/bookings', [BookingController::class, 'store'])->can('createBooking', 'property'); Route::post('/properties/{property}/offers', CustomOfferController::class)->can('createBooking', 'property'); // a host prices an offer for one guest Route::get('/bookings', [BookingController::class, 'index']); Route::get('/bookings/{booking}', [BookingController::class, 'show'])->can('view', 'booking'); Route::patch('/bookings/{booking}/property', [BookingController::class, 'move'])->can('update', 'booking'); Route::post('/bookings/{booking}/payment', BookingPaymentController::class)->can('update', 'booking'); Route::post('/bookings/{booking}/cancel', CancelBookingController::class)->can('update', 'booking'); Route::post('/bookings/{booking}/mark-paid', MarkBookingPaidController::class)->can('update', 'booking');}); // Called by Stripe and by the channels, not by a browser. API routes have no CSRF check, which they couldn't pass.Route::post('/webhooks/stripe', StripeWebhookController::class); // {channel} is bound to the Channel enum: /webhooks/channels/vrbo is a 404.Route::post('/webhooks/channels/{channel}', ChannelWebhookController::class);Route::post('/webhooks/channels/{channel}', ChannelWebhookController::class); // {channel} is the Channel enum: vrbo is a 404

The fix, part 4: input is scoped too

Ids that arrive in the body need the same care as ids in the URL. The exists rule gets a where for the account, and only validated fields reach the model.

app/Http/Requests/MoveBookingRequest.phpnew file
<?php

namespace App\Http\Requests;

use App\Models\Account;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class MoveBookingRequest extends FormRequest
{
    /** @return array<string, list<mixed>> */
    public function rules(Account $account): array                          // the current account, injected like in a controller
    {
        return [
            'property_id' => [
                'required',
                'integer',
                Rule::exists('properties', 'id')->where('account_id', $account->id),   // yours, not just existing
            ],
        ];
    }
}

Laravel inside: scoped route bindings

For nested routes like /properties/{property}/bookings/{booking}, Laravel can find the child through the parent instead of by its id alone. With ->scopeBindings(), booking 813 is looked up as $property->bookings()->where("id", 813), so a booking of another property is a 404 before any policy runs.

Illuminate/Database/Eloquent/Model.php (simplified)
public function resolveChildRouteBinding($childType, $value, $field)
{
    $relationship = $this->{Str::plural(Str::camel($childType))}();     // {booking} under {property} → $property->bookings()

    $field = $field ?: $relationship->getRelated()->getRouteKeyName();

    return $relationship->where($field, $value)->first();               // null → 404
}

A global scope (where account_id = current added to every query of a model) is the other common tool. It’s safe in web requests, but queued jobs and commands have no current account, so it either has to throw there or be switched off, and code that switches it off is where the next leak hides. Nordic Stays keeps the scoping visible instead: queries start from the account, and policies guard records.

TestsEvery endpoint, tried as the wrong account

One dataset lists every route that takes an id. Each new endpoint is added to it, so "can another account reach this?" is answered by the suite, not by a reviewer’s memory.

tests/Feature/TenancyTest.phpnew file
<?php

use App\Models\Booking;
use App\Models\Property;
use App\Models\User;

beforeEach(function () {
    $this->theirs = Booking::factory()->create();                             // another account's booking
    $this->ourProperty = Property::factory()->create();
    $this->us = hostOf($this->ourProperty);
});

it('hides another account’s booking on every endpoint', function (string $method, string $uri, array $body) {
    $this->actingAs($this->us)
        ->json($method, str_replace('{booking}', (string) $this->theirs->id, $uri), $body)
        ->assertNotFound();                                                    // not 403: don't confirm it exists
})->with([
    'show' => ['GET', '/api/v1/bookings/{booking}', []],
    'move' => ['PATCH', '/api/v1/bookings/{booking}/property', ['property_id' => 1]],
    'pay' => ['POST', '/api/v1/bookings/{booking}/payment', []],
    'cancel' => ['POST', '/api/v1/bookings/{booking}/cancel', []],
    'mark paid' => ['POST', '/api/v1/bookings/{booking}/mark-paid', []],
]);

it('lists only our own bookings', function () {
    $ours = Booking::factory()->for($this->ourProperty)->create();

    $this->actingAs($this->us)->getJson('/api/v1/bookings')
        ->assertOk()
        ->assertJsonCount(1, 'data')
        ->assertJsonPath('data.0.id', $ours->id);
});

it('refuses to move our booking into another account’s property', function () {
    $ours = Booking::factory()->for($this->ourProperty)->create();

    $this->actingAs($this->us)
        ->patchJson("/api/v1/bookings/{$ours->id}/property", ['property_id' => $this->theirs->property_id])
        ->assertUnprocessable()
        ->assertJsonValidationErrors('property_id');
});

it('refuses a user whose current account is not theirs', function () {
    $stranger = User::factory()->create(['current_account_id' => $this->ourProperty->account_id]);   // not a member

    $this->actingAs($stranger)->getJson('/api/v1/bookings')->assertForbidden();
});

Remember

  • Every query starts from the current account: $account->bookings(), never Booking::find($id).
  • Another account’s id answers 404, exactly like an id that doesn’t exist.

Accounts are sealed off from each other. Tuesday: inside one account, the cleaner opens a booking and sees how much the guest paid.