The shape of the problem
The platform already separated companies from each other. What it had no concept of was a party above a company: a reseller with their own API credentials who creates companies, pays for them, and must never see anyone else's.
The dangerous part is that the existing isolation looks like it already covers this. Every query is scoped by company, so nothing leaks between companies. But "which companies may this caller act on?" had no answer in the schema at all, because until now the answer was always "the one they belong to". An enterprise caller belongs to none of them and controls many.
Ownership has to exist in the data, not in the code
The fix that holds is a column: a company records the enterprise client that owns it, added in migration 0110. Every enterprise-scoped read and write filters on it. The alternative, checking a list of permitted companies in each handler, fails the first time someone writes a new handler and forgets.
Two decisions in that commit are worth more than the column itself.
Refuse rather than create an ownerless company. A token can say the caller is an enterprise user without carrying a client id, in which case the code looks the client up. If there is still no client, company creation fails with a message to contact support. The tempting alternative is to create the company and leave the owner null, which produces a row that no enterprise query matches and no one can reach.
The backfill is not allowed to guess. Existing enterprise companies predated the column, so they needed an owner assigned. When a company could plausibly belong to more than one active client, the script stops instead of picking. Its argument parsing fails closed too: an unknown flag, an empty value or a malformed uuid is an error rather than something silently ignored, because a dropped --company would widen the update from one row to every ownerless row.
The billing owner nobody can see
A reseller's customer should not be asked to pay. Invoices, payment prompts and onboarding notifications belong to the reseller, while the company carries on using the product.
So an enterprise company can carry a hidden billing owner: a user who receives the billing side and does not appear in the company's own member list. Hidden is the hard half. A member list, a staff count, a notification fan-out and a CRM lead sync all enumerate users, and each one had to learn to leave this user out, which is why that change touches the campaign service and the lead sync rather than only the company module.
Taking money for someone else
Payment was where the two tenancies met most awkwardly. An enterprise token pays as the company's billing owner, so the charge lands on the reseller while the credits land on the customer's wallet.
Two properties had to hold before that could go live.
The browser is not a trustworthy reporter
After a checkout, the customer's browser tells the server the payment succeeded. Taking that at face value means anyone can mint credits by calling the endpoint. Razorpay signs the result, so the server recomputes it: HMAC-SHA256 over orderId|paymentId with the key secret, hex encoded, compared against what the browser sent.
const expected = Buffer.from(
crypto.createHmac('sha256', keySecret).update(`${orderId}|${paymentId}`).digest('hex')
)
const given = Buffer.from(signature)
if (given.length !== expected.length) return false
return crypto.timingSafeEqual(given, expected)
The length check is not defensive clutter. timingSafeEqual throws when the two buffers differ in length, so without it a wrong-length signature produces a 500 instead of a clean rejection, and an attacker learns the difference between malformed and merely wrong. Comparison is constant time for the same reason: a plain === leaks how much of the signature was correct through how long it took to say no.
One payment, one grant
A customer who refreshes the confirmation page, or a retry on a slow network, sends the same successful payment twice. Checking whether it has been granted and then granting it loses the race: both requests can read "not yet" before either writes.
So completion runs in one transaction that locks the intent row first, and a payment already marked successful returns without granting anything.
await db.transaction(async (tx) => {
const [intent] = await tx.select({ status: paymentIntents.status })
.where(eq(paymentIntents.id, intentId))
.limit(1)
.for('update') // the second request waits here
if (intent.status === 'success') return // and then finds the work done
...
})
This is idempotency, not exactly-once delivery, and the distinction matters: the request can still arrive any number of times. What is guaranteed is that the credits are granted once, because the second caller blocks on the lock and then observes the first caller's committed result.
The authorization holes this surfaced
Reviewing the branch meant reading the existing enterprise endpoints properly, and three of them were wrong in ways that predated this work:
- The guard validated the company id from the query string, then the header, and stopped. A request naming a company in its path was never checked against it, so sending your own company id in a header let you read or update someone else's company. The fix checks every company a request names, in the query, the header, the path and the body.
- Any enterprise client could read, and deactivate, another enterprise client. Those routes are now self-only, and creation is refused outright on the tenant controller.
- Any active member, including an agent, could turn their company into an enterprise account, which locked every normal user out of it with "Enterprise token required". That endpoint now always refuses.
These shipped as their own hotfix first, ahead of the feature, and the guard change went out in report mode: it logs what it would have refused instead of refusing. An authorization change that is wrong about a legitimate request does not look like a bug, it looks like the product being down for whoever hit it. The logs are what decide when it is safe to enforce.
How it was checked
143 tests across 20 new spec files, and the ones that matter are the negative cases: an enterprise client reaching a company it does not own, a second completion of the same payment, a signature that is the right shape and the wrong value, a hidden billing owner appearing in a member list it should be absent from.
Verifying the guard on production needed no customer data. A token signed with the service's own secret for invented ids returns 404 Company not found on the old code and 403 You can only access your own company on the new, which distinguishes the two deployments without reading a real row.
What I took from it
- A new tenancy boundary is a schema change. Expressed in handlers it is a convention, and the first handler written by someone who has not read this page will not follow it.
- Ship authorization changes in report mode. The cost of being too strict is an outage for a real customer, and the logs answer in a day what review cannot answer at all.
- Migrations that assign ownership should refuse ambiguity. "Pick the most likely owner" is the one behaviour whose failure mode is a privacy incident.
- Building the second tenant is what finds the holes in the first. None of the three authorization bugs were introduced here; they were simply never load-bearing until someone outside the company could call them.