Four levels of agents in one admin console: a permission model that holds
Every multi-level distribution business starts with the same three roles and ends up with six, and the permission code that was fine at three becomes a source of incidents at six. The usual cause is not a missing role —
Every multi-level distribution business starts with the same three roles and ends up
with six, and the permission code that was fine at three becomes a source of incidents
at six. The usual cause is not a missing role — it is that permission is checked in the
controller, and the controller is not the only door into the data.
The mistake: checking the role, not the relation
// this is how the bug gets shipped
if (req.user.role !== "admin") return res.status(403).end();
const orders = await db.order.findMany({ where: { id: req.params.id } });
An admin from branch A reads branch B's order. The role check passed. The relation was
never checked. In a multi-level system every object has an owner chain, and permission
is a property of the path between the requester and the object, not of the requester
alone.
Fix one: make the scope part of the query
Never fetch by primary key and then authorise. Authorise by adding the scope to the
query, so an unauthorised object is indistinguishable from a missing one:
const scope = await scopeFor(req.user); // { agentIds: [...], selfId }
const order = await db.order.findFirst({
where: {
id: req.params.id,
OR: [
{ agentId: { in: scope.agentIds } },
{ agentId: scope.selfId },
],
},
});
if (!order) return res.status(404).end();
Two benefits: the query cannot return data the caller may not see, and the response
does not leak existence. The scopeFor function walks the agent tree once per request
and caches it for the lifetime of that request.
Fix two: precompute the subtree
Walking parent links at request time is fine at four levels and terrible at four
thousand agents. Store a materialised path or a closure table and refresh it on
re-parenting:
-- closure table: one row per ancestor/descendant pair
CREATE TABLE agent_tree (
ancestor_id BIGINT NOT NULL,
descendant_id BIGINT NOT NULL,
depth INT NOT NULL,
PRIMARY KEY (ancestor_id, descendant_id)
);
CREATE INDEX agent_tree_desc ON agent_tree (descendant_id, depth);
-- everyone under agent 42, including itself
SELECT descendant_id FROM agent_tree WHERE ancestor_id = 42;
Re-parenting is then a bounded delete/insert inside one transaction. The read path
becomes a single indexed lookup, which is what you want when the commission dashboard
is the most-loaded page in the product.
Fix three: separate "can see" from "can act"
Reporting and mutation have different rules and mixing them is how agents end up able
to edit their own upline's commission rate. Two functions, two call sites:
-
readScope(user)— the subtree plus self, used by lists and detail views. -
writeScope(user)— the subtree strictly below self, used by every mutation, and empty for leaf agents.
The second being empty for leaves is not a bug; it is the whole point. A leaf agent has
no one below them, so any write targeting an object outside themselves is a 403 by
construction, without a single role string in the code.
Fix four: audit rows carry the actor, not just the action
When a dispute arrives — and it will — the question is "who changed this rate and when",
not "what changed". Write an append-only audit row in the same transaction as the
mutation, with actor id, target id, before/after values, and the request id. Without the
transaction boundary, you get audit rows for changes that rolled back, which is worse
than no audit at all.
What this costs
About two days of schema and query work, and a rule that no handler may call the ORM
without a scope argument — enforced with a lint rule, because code review does not scale
to a team under deadline.
The fuller write-up, including the commission settlement side and how it interacts with
the wallet ledger, is at
keston.dev.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.