The export route checked permissions, the queued job did not, and a manager got every team's data
Our CSV export endpoint verified the user's role, then handed the filters to a queued job that ran with no user at all. A small change to the filter format let one team manager export the whole company's shipments. How we found it and moved authorization to the data layer.
A customer's operations director emailed our support team with an awkward question. One of their team managers, responsible for the northern region only, had exported a shipments CSV for a quarterly review. The file contained shipments for all five regions, including customer names and delivery addresses the manager was not supposed to see.
Our platform has team-scoped roles. A team manager can see and export shipments for their own teams. An account admin can see everything in the account. Opening the manager's shipment list in the browser showed only northern shipments, as expected. The export did not match the screen.
Following the request
The export endpoint and the job it dispatches, simplified:
// ShipmentExportController
public function store(ExportShipmentsRequest $request)
{
$this->authorize('export', Shipment::class); // is this user allowed to export at all?
ExportShipmentsJob::dispatch(
accountId: $request->user()->account_id,
filters: $request->validated('filters'),
notifyUserId: $request->user()->id,
);
return response()->json(['status' => 'queued'], 202);
}
// ExportShipmentsJob::handle()
public function handle(ShipmentRepository $shipments, CsvWriter $csv): void
{
$query = Shipment::query()->where('account_id', $this->accountId);
if (! empty($this->filters['team_ids'])) {
$query->whereIn('team_id', $this->filters['team_ids']);
}
// date, status filters...
$csv->write($query->cursor(), $this->path());
User::find($this->notifyUserId)->notify(new ExportReady($this->path()));
}
The policy check answered one question: can this user export shipments? A team manager can. It did not
answer the question that mattered: which shipments? That was decided by team_ids in the filters,
sent by the client.
The web frontend always filled team_ids with the manager's teams. Two weeks earlier, the frontend team
had changed the export dialog so that "All my teams" sent no team_ids at all, letting the backend apply
the default. The backend had no default. No team_ids meant no team filter, which meant every shipment in
the account.
Confirming the scope
We searched the job logs for exports by users without the account admin role and with an empty
team_ids:
export_id | user_role | team_ids | rows | created_at
----------+--------------+----------+---------+--------------------
E-77120 | team_manager | (none) | 48,291 | 2026-10-27 10:02
E-77341 | team_manager | (none) | 12,004 | 2026-10-29 15:40
E-77502 | team_manager | (none) | 48,877 | 2026-11-02 09:15
Three exports by two managers in two different customer accounts, all since the frontend change. Account
boundaries held in every case, because account_id came from the server. Team boundaries did not.
Two different authorization questions
Authorization usually has two parts:
- Function-level: may this user perform this kind of action? ("Can team managers export?")
- Object-level: on which records? ("Only shipments in their teams.")
Our route handled the first. The second was left to the client, by trusting the team_ids filter.
OWASP lists this pattern under Broken Access Control, the top category in the OWASP Top 10, and the API
Security Top 10 calls the object-level part out separately as Broken Object Level Authorization.
Why the job made it easy to miss
The listing endpoint did not have this bug. Its controller applied a scope based on the logged-in user:
$query = Shipment::visibleTo($request->user());
The export job could not do that, because a queued job has no request and no authenticated user.
auth()->user() inside handle() returns null. The developer who wrote the job passed the account ID
and the filters, which seemed enough, and the scope that protected the listing never ran.
This is a common shape: authorization implemented in the HTTP layer (middleware, controller, form request) and business logic moved into jobs, commands, scheduled tasks or event listeners that sit outside that layer. Each move is reasonable on its own, and each one is a chance to lose the check.
Environment
| Item | Value |
|---|---|
| Framework | Laravel 11, PHP 8.3 |
| Queue | Redis, Horizon |
| Roles | account admin, team manager, team member |
| Exposure | 3 exports, 2 accounts, other teams' shipment data within the same account |
1. Make the job act as a user, and scope with the same code as the UI
The job now receives the user ID and builds its query from the same scope the listing uses. Filters can only narrow that scope, never widen it:
final class ExportShipmentsJob implements ShouldQueue
{
public function __construct(
public readonly int $userId,
public readonly array $filters,
) {}
public function handle(CsvWriter $csv): void
{
$user = User::findOrFail($this->userId);
if ($user->cannot('export', Shipment::class)) {
return; // role changed since dispatch: do nothing, log below
}
$query = Shipment::visibleTo($user); // same scope as the listing page
if (! empty($this->filters['team_ids'])) {
$query->whereIn('team_id', $this->filters['team_ids']); // narrows only
}
$csv->write($query->cursor(), $this->path());
$user->notify(new ExportReady($this->path()));
}
}
The scope itself lives on the model, in one place:
public function scopeVisibleTo(Builder $query, User $user): Builder
{
$query->where('account_id', $user->account_id);
if ($user->role !== UserRole::AccountAdmin) {
$query->whereIn('team_id', $user->teams()->select('teams.id'));
}
return $query;
}
Because whereIn with the client's team_ids is applied on top of visibleTo, a manager who sends
another team's ID gets an empty intersection, not that team's data.
Re-checking the policy inside handle() matters too. Jobs can sit in a queue for minutes or hours. If a
user is demoted or removed in between, the job should not run with permissions they no longer have.
2. Do not trust anything in the payload that grants access
We reviewed every job in the codebase with one question: does any constructor argument decide which
records are visible? We found two more: a report job taking account_id from an internal API call, and an
invoice PDF job that took a list of invoice IDs. Both now take a user (or a system actor with an explicit,
logged reason) and resolve visibility themselves.
3. Fail closed on missing filters
The frontend change was the trigger, so we also made the backend default explicit. An empty team_ids now
means "all teams the user can see", which visibleTo already provides. The dangerous case, no filter
meaning no restriction, cannot happen any more because restriction never depended on the filter.
1. Policy tests per role, through the job. We test the job directly, with real database rows for several teams:
public function test_team_manager_export_contains_only_own_teams(): void
{
[$north, $south] = Team::factory()->count(2)->for($account = Account::factory()->create())->create();
Shipment::factory()->for($north)->count(3)->create();
Shipment::factory()->for($south)->count(4)->create();
$manager = User::factory()->teamManager()->for($account)->hasAttached($north)->create();
(new ExportShipmentsJob($manager->id, filters: []))->handle(app(CsvWriter::class));
$this->assertCsvRowCount(3);
$this->assertCsvOnlyContainsTeam($north);
}
public function test_team_manager_cannot_widen_scope_with_filters(): void
{
// same setup...
(new ExportShipmentsJob($manager->id, filters: ['team_ids' => [$south->id]]))
->handle(app(CsvWriter::class));
$this->assertCsvRowCount(0);
}
On the old job, the first test exported 7 rows and the second exported 4. Both pass on the new code.
2. A matrix test. For each role (account admin, team manager, team member, removed user) and each
data-exporting job, a data-provider test asserts the exact set of visible record IDs. Adding a new job
without adding it to the matrix fails a test that lists all classes implementing our ExportsData
interface.
3. Audit. Every export now records the user ID, the effective team IDs after scoping, and the row count. A weekly query alerts if any non-admin export includes a team the user did not belong to at the time. It has stayed empty since the fix.
4. Security response. We informed both affected customers with the list of exports and files, deleted the generated files from storage, invalidated their download links, and confirmed from access logs that each file had been downloaded only by the user who requested it.
Takeaways
- Checking that a user may perform an action is not the same as checking which records they may act on.
- Never let a client-supplied filter decide visibility. Filters narrow a server-side scope.
- Jobs, commands and listeners run outside your HTTP authorization layer. Pass the actor and re-check.
- Put the visibility rule in one scope and use it everywhere: listing, export, search, API.
References: OWASP Top 10, Broken Access Control, OWASP API Security, Broken Object Level Authorization, Laravel authorization and policies, Laravel queues.
Add a label
Embed this post
<iframe src="https://hibug.me/authorization-missing-in-background-export" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I build and maintain public and partner APIs, currently for a logistics platform with web, mobile and third-party clients all calling the same endpoints. Before that I worked on identity: login, sessions, OAuth integrations and the long tail of edge cases they create. The bugs I care about sit at the contract between client and server. A PUT that wiped fields the client never sent, a cache that served one user's page to another, a field removal that broke app versions still in the wild, a refresh flow that logged people out when two tabs raced. None of these show up in a happy-path demo. My posts walk through how each one surfaced, what the HTTP or auth spec actually says, the fix we shipped and the tests we added so the next change to the API does not repeat it.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.