SKIP TO CONTENT
Carlos Barahona sigil CARLOS BARAHONA
← JOURNAL

SUBDIVY · 8 MIN

The database is the rulebook

My family’s rentals ran on a spreadsheet. One row per unit, one column per month, and a cell turned green when the rent came in. It worked as a record and did nothing else. It couldn’t remind a tenant three days before the due date, couldn’t number a receipt, and couldn’t tell anyone that the 31st doesn’t exist in February. Subdivy is that spreadsheet moved to the phone, with the parts a spreadsheet can’t do: units, tenants, due dates, payments, PDF receipts and WhatsApp reminders. It’s in a pilot with a few landlords now.

The interesting decision isn’t in the app. It’s where the rules live.

The phone holds the key

Subdivy is an Expo app that talks to Supabase directly. There’s no backend of mine in between, which means the project URL and the publishable key ship inside every build. Anyone who installs the app has both, and anyone who signs up has a valid session to go with them.

So the threat model starts from there: assume a signed-in user from some other account is calling the Data API by hand, with whatever payload they like. Under that assumption, nothing in src/ is a security boundary. Hiding a button is UX. Checking account.plan === 'admin' in a screen is UX. The real boundaries are four layers in the database, and each one answers a different question:

  1. Grants: which tables and columns the authenticated role can touch at all.
  2. Row-level security: which rows.
  3. Triggers and security definer functions: which business rules hold.
  4. Edge functions: anything that needs a secret, like the WhatsApp token.

I designed it this way from the first migration rather than after an incident. With a client that talks straight to Postgres, the database is the only place a rule can’t be skipped.

Grants decide the columns

Row-level security is the layer people reach for first, but it only filters rows. It can’t stop a user from updating a column on a row they legitimately own. An account row belongs to its landlord, and it also holds their plan and their receipt counter. A policy that lets them edit their business name would let them edit those too.

Column-level grants close that gap:

grant select on public.accounts to authenticated;
grant update (business_name, currency, remind_before, remind_days_before,
              remind_late, notify_late, notify_soon)
  on public.accounts to authenticated;

plan, role, receipt_seq and owner_user aren’t in the list, so no policy can ever hand them out. Payments get the same treatment, only more so:

grant select on public.payments to authenticated;
grant update (proof_path, receipt_path, receipt_sent_at) on public.payments to authenticated;

There’s no insert grant on payments at all. The client can attach a proof photo or a receipt PDF to an existing payment, and that’s it.

Row-level security decides the rows

Every table scopes back to one question: which account does the caller own? A helper in a private schema answers it, and private isn’t exposed through the API:

create policy "tenants: account all" on public.tenants for all to authenticated
  using (account_id = (select private.my_account_id()))
  with check (account_id = (select private.my_account_id()));

The (select ...) wrapper matters. Without it, Postgres can call the function once per row; with it, once per query.

The subtle part is with check. A lease belongs to a unit and names a tenant, and both are foreign keys the client supplies. Checking only that the unit is mine leaves a hole: I could create a lease in my own account that points at someone else’s tenant, and every join through it would leak their name and WhatsApp number. So the lease policy checks both ends:

with check (
  unit_id in (
    select u.id from public.units u join public.properties p on p.id = u.property_id
    where p.account_id = (select private.my_account_id()))
  and tenant_id in (select id from public.tenants where account_id = (select private.my_account_id()))
);

Every foreign key the client can set gets the same treatment. That’s the rule that’s easiest to forget, because the row being inserted looks perfectly scoped.

Receipts go through one door

A receipt number is something a tenant keeps and an owner might dispute, so it can’t skip or repeat. That rules out computing it in the app, where two phones recording payments at the same moment would both read the same “last number”.

Instead, payments are created only through an RPC:

create or replace function public.create_payment(
  p_lease_id uuid, p_period date, p_amount numeric,
  p_paid_on date, p_method public.pay_method
)
returns public.payments
language plpgsql
security definer
set search_path = ''
as $$
-- ...
begin
  select p.account_id into v_account
  from public.leases l
  join public.units u on u.id = l.unit_id
  join public.properties p on p.id = u.property_id
  join public.accounts a on a.id = p.account_id
  where l.id = p_lease_id and a.owner_user = (select auth.uid());

  if v_account is null then
    raise exception 'lease_not_found' using errcode = '42501';
  end if;

  update public.accounts set receipt_seq = receipt_seq + 1
  where id = v_account
  returning receipt_seq into v_seq;
  -- insert the payment with receipt_no 'R-<year>-<seq>' ...

Three things make it safe. security definer lets it write the counter the client can’t, so the first thing it does is prove ownership itself, because RLS no longer does it. set search_path = '', with every name schema-qualified, stops a caller from shadowing public.accounts with a table of their own. And update ... returning takes a row lock on the account, so two payments in the same account line up behind each other and get consecutive numbers.

The table adds the last guard: unique (lease_id, period). A month can be marked paid once. Tap “paid” twice on a bad connection and the second call fails instead of producing a second receipt.

Rules that depend on the calendar

Some rules aren’t about who you are but about when. A property administrator manages units for owners on a commission, and a commission change mid-month would make that month’s statement wrong. So a trigger enforces it:

v_this_month date := date_trunc('month', now() at time zone 'America/Panama')::date;
-- ...
if exists (select 1 from public.management_agreements where owner_id = new.owner_id) then
  if new.effective_from < (v_this_month + interval '1 month')::date then
    raise exception 'agreement_change_must_start_next_month';
  end if;

Agreements are append-only. There’s no update or delete policy, so a change is a new row, and the history of who earned what percentage, from when, is never rewritten.

Note the time zone. Supabase runs in UTC, and Panamá is five hours behind, so “this month” in plain now() turns over at 7 p.m. on the last day. Every date the app reasons about goes through America/Panama first.

The same thinking drives rent status. Paid, due soon, late and vacant are never stored. A view derives them for the current month, clamping each lease’s pay day to the length of the month, so a lease due on the 31st falls due on the 28th in February. The view is security_invoker, so it runs with the caller’s policies instead of bypassing them.

Errors are part of the contract

A trigger that raises agreement_change_must_start_next_month is only half a feature. The other half is a landlord reading something they understand. The app keeps one table that maps database error codes to short Spanish copy:

{ match: /agreement_change_must_start_next_month/i,
  text: 'El cambio de comisión solo puede aplicar desde el próximo mes.' },
{ match: /duplicate key.*payments|payments_lease_id_period_key/i,
  text: 'Este mes ya está marcado como pagado.' },

That’s the price of this design. Every rule exists twice: once where it’s enforced, and once where it’s explained. The app still validates forms so people get fast feedback, but those checks are courtesy. If the app and the database ever disagree, the database wins, and the worst case is a confusing message rather than a broken invariant.

What it costs

Migrations here are applied by hand in the Supabase SQL editor, and nothing with an AI agent attached has database access. A schema mistake is never “fixed” by editing an old migration; it’s a new one, reviewed and applied on purpose. That’s slower than letting tools push schema changes, and for a database holding tenants’ names, phone numbers and income, I think slow is correct.

The broader lesson is the one the spreadsheet was teaching all along. A green cell was a record anyone could change. A receipt has to be a fact. The only way to make it one, when the client is a phone you don’t control, is to let the database refuse.