All notes

One payment, two months: hardening Kashier subscriptions in a multi-tenant SaaS

· 5 min read

The webhook and the browser redirect arrived in the same second and both extended the plan. Here are the seven holes I closed in Tabaliy's billing, and the one Postgres function that now does all of it.

Tabaliy is a multi-tenant inventory SaaS for Egyptian shops: warehouses, batches, expiry dates and barcode scanning. Shops pay a monthly or yearly subscription through Kashier, an Egyptian payment gateway. The customer pays on Kashier's hosted page, and Kashier tells us about it in two ways:

  1. A browser redirect back to our site with a signed query string.
  2. A server-to-server webhook with a signed JSON body.

The first version handled both in two Supabase Edge Functions, and each one did the obvious thing: read the payment row, and if it is still pending, mark it paid and extend the shop's plan. It worked in every test. Then I audited it like an attacker would, and found that "it works" and "it is safe to take money with" are two different bars.

1. Both callbacks arrive in the same second

The redirect and the webhook routinely land within a second of each other. Both functions read the row, both saw pending, and both extended the billing period. One payment, two months.

The fix was to move the decision out of the edge functions and into one Postgres function, finalize_kashier_payment(), which runs in a single transaction and locks the payment row first (select ... for update). It only activates on the transition pending | failed → success. Whichever callback loses the race waits on the lock, then sees success and returns already_processed.

2. Never trust the amount in the callback

The paid amount in a callback came from outside. The one figure that never left our control is the price we stored when we created the checkout session, from our own pricing table on the server. The function compares the two, and any amount or currency mismatch moves the payment to a review status. It never activates.

Plan, billing cycle and tenant also come from the stored row, never from the order ID string the callback sends back.

3. Unknown order IDs never activate anything

If no payment row exists for an order ID, then our server never issued that checkout. The function does not activate a plan for it. It records a review row when it can identify the tenant, and the call is logged.

4. Check the signature on a fixed set of fields

Kashier signs the webhook with HMAC-SHA256. The tempting bug is to build the signed string from whatever fields the payload contains. Then a forged payload simply leaves out the fields it cannot control. The verifier signs a fixed list of fields taken from Kashier's documentation:

const EXPECTED_SIGNATURE_KEYS = ["merchantOrderId", "amount", "currency", "status", "transactionId"];

The comparison is constant-time. A plain !== returns at the first wrong character, which tells an attacker how much of a forged signature was right.

Read the signed set carefully. The event field is not in it, and only data.status is. An early version treated event: "refund" as a refund, so anyone holding a genuine signed SUCCESS payload could relabel it as a refund and expire a paying shop. Now only the signed status (REFUNDED or VOIDED) decides a refund.

5. Fail closed on test mode

An unset or misspelled KASHIER_MODE used to fall back to test without a word. In production that creates sandbox checkouts whose callbacks then activate real plans. Now the mode must be exactly live or test, or the function refuses to run. The mode is also stored on the payment row, and a callback whose mode does not match the session we issued goes to review.

6. Pin the redirect URL

The page Kashier sends the payer back to used to come from the request body. Anyone with a login could create a genuine checkout on our merchant account that sent the payer to their own site afterwards. That is a real payment page with our branding, handing the customer to an attacker. The redirect is now checked against an allowlist of our own origins.

The same audit found that any team member, a read-only viewer included, could start a checkout. Billing is now limited to the owner and to members with billing permission.

7. Refunds have to take the time back

Before the audit, any webhook after success was ignored, so a refunded shop kept its paid period. refund_kashier_payment() now marks the payment refunded and, if that payment is still the one that set the shop's current period, expires the subscription. If a later payment has already moved the period, it leaves the shop alone and flags the refund for manual review.

I chose "expire" over "pull the end date back one period" on purpose. It is simpler, and it can never leave paid time in place after a refund. The trade-off is written down in the migration, and the previous end date is saved so an operator can restore it by hand.

The bonus bug: upgrades that stacked

The activation function used to add the new period on top of the current end date. That is right for a renewal. On a plan change it let a shop buy one year of the cheap plan, then one month of the top plan, and get thirteen months of the top plan. Now a renewal of the same plan extends from the later of now and the current end date, and a plan change starts from now.

What I took from it

  • Put the money decision in the database. Edge functions are stateless and run in parallel. A row lock in one transaction is the simplest way to make two callbacks agree.
  • Trust only what you stored. Price, plan, tenant and mode come from your row, never from the callback.
  • Know exactly which fields are signed. Anything outside the signature is user input.
  • Fail closed. A missing secret or mode should stop the function, not quietly pick a default.
  • Unclear cases go to review. A review status and a human beat an automatic guess with someone's money.

None of these were in the happy-path tests. I found them by asking, for every line, "what if someone sends this on purpose?" That question is the most useful part of payment work.