Note 03 / Supabase / Security / Postgres
When the client writes the date: guarding a Supabase streak table with a BEFORE trigger
Row-level security only checks who owns a row, not what they put in it. How a daily check-in table let users pick their own streak and day, and how a BEFORE trigger recomputed both on the server without breaking users in UTC+7.
- By
- Trần Thế Anh, Software Engineer
- Published
- Work done
- 7 October 2026, Yuuki (Supabase Postgres)
- Stack
- Supabase Postgres, row-level security, plpgsql triggers
- Reading
- 7 min, 1,370 words
A row-level security policy that says user_id = auth.uid() answers one question: whose row is this. It says nothing about which columns the owner may change, or to what. For a table the client upserts directly, like a streak counter, that gap is a payout machine if a trigger elsewhere turns the row into currency.
This note is about one such table, user_streaks, in the Yuuki app, and the BEFORE trigger that now sits in front of it. The previous note in this series covers the reward functions around it.
The setup
Each user has one row: current_streak, best_streak, last_checkin (a date) and a few other columns. The app writes the row itself after a check-in with a plain upsert. An AFTER trigger on the table grants in-app currency, with the amount picked from a seven-day cycle by current_streak. The trigger runs in the same transaction as the write, which was a deliberate earlier fix so a grant cannot be lost between two requests.
RLS on the table checked only user_id. So the authenticated role could UPDATE every column of its own row.
What a user could do
Reading the live definitions on 7 October 2026 showed the attack plainly:
- Update your row:
last_checkinto a different day,current_streakto 7. - The AFTER trigger sees a changed
last_checkinand grants the amount for position 7 of the cycle, the highest. - Repeat with another day. Each invented day is a separate dedup key, so each one pays.
There was a second consumer of the same row. A function that unlocks special milestone tasks reads best_streak. Setting best_streak to 100 opened the special streak milestones with no check-ins behind it.
First idea, and why it was rejected
Revoke UPDATE on the table from the client roles and make check-in an RPC only. It is the clean design. It was rejected for a practical reason: apps already in the stores write the row directly and then call the reward RPC, and one older build calls it even when the write failed. If the write is blocked, those users get streakSaved = false and never see a reward. The server had to accept the write and correct it, not refuse it.
The guard
A BEFORE INSERT OR UPDATE trigger, _user_streaks_guard, rewrites the incoming row. It only applies to requests whose JWT role is anon or authenticated. Server-side writers (the service role, the CMS, migrations) pass through unchanged.
create or replace function public._user_streaks_guard()
returns trigger language plpgsql security definer
set search_path to 'public'
as $$
declare v_floor date; v_exp int;
begin
if coalesce(auth.role(), '') not in ('anon', 'authenticated') then
return NEW;
end if;
if TG_OP = 'UPDATE' then
NEW.user_id := OLD.user_id;
if NEW.last_checkin is not distinct from OLD.last_checkin then
NEW.current_streak := OLD.current_streak;
NEW.best_streak := OLD.best_streak;
return NEW;
end if;
v_floor := OLD.last_checkin; -- plus the last day already paid, see below
if NEW.last_checkin is null
or not public._is_client_day(NEW.last_checkin)
or (v_floor is not null and NEW.last_checkin < v_floor) then
raise exception using errcode = 'check_violation',
message = 'checkin_day_rejected';
end if;
v_exp := case when OLD.last_checkin is not null
and NEW.last_checkin = OLD.last_checkin + 1
then coalesce(OLD.current_streak, 0) + 1
else 1 end;
NEW.current_streak := v_exp;
NEW.best_streak := greatest(coalesce(OLD.best_streak, 0), NEW.current_streak);
end if;
return NEW;
end $$;
That snippet is a trimmed illustration of the production function, not a paste. The real one also handled INSERT, the 100-day cap it had at the time and the ledger check. The shape of the rule is what matters:
- Streaks are computed, not accepted. The new streak comes from the old row: the next calendar day gives old plus one, the same day keeps the old value, anything else resets to 1. Whatever the client sent is overwritten.
- The day must be plausible. It has to pass
_is_client_day, and it cannot move backwards past the previous check-in or past the latest day already paid in the ledger. The ledger check closes a trick where a user deletes the row and recreates it with an older date to be paid again. user_idcannot change.- A refusal is an error, not a silent fix.
check_violationmakes the app’s write fail, so the app shows 0 reward, which is the truth.
Why plus or minus one day, not “today”
The obvious plausibility test is last_checkin = current_date in UTC. It breaks real users. Time zones run from UTC-12 to UTC+14, so the date on a phone is always one of three UTC dates: yesterday, today or tomorrow. A person in Vietnam (UTC+7) checking in at 01:00 local time is on the previous UTC day. With a strict equality test that person is refused every morning.
create or replace function public._is_client_day(p_day date)
returns boolean language sql stable
as $$
select p_day is not null
and p_day between (now() at time zone 'utc')::date - 1
and (now() at time zone 'utc')::date + 1;
$$;
The cost is a stated trade-off, not a hidden one. Each day still pays once (the dedup key contains the day), and the day must be inside the window when it arrives, so total payout over a lifetime is bounded by the days that have actually passed, plus one. But a payout the client queued and retries after more than a day is refused for good. The reply code for that is no_amount, which the client classifies as permanent so it stops retrying. If the amount had already been paid, the retry is a duplicate and counts as success anyway.
One compromise: the cap mismatch (as of 7 October 2026)
The app has two client builds and they cap streaks differently. The React Native build stops counting at 30. The Flutter build stops at 100. A server that recomputes the streak would disagree with the React Native client for anyone above 30, and that client would then display a different number from the one stored.
The guard allows exactly one exception to “ignore what the client sent”. If the client sends 30 and the real streak is above 30, the 30 is kept. It gives nothing away: position 2 of the seven-day cycle (the cycle repeats every seven days) is no higher than the average payout of a true long streak, and a client cannot pick any number other than the one cap it already used.
That compromise was temporary. A follow-up migration dated 24 October 2026 dropped both caps and took the date away from the client entirely: a check_in() function with no parameters works out “today” from a time zone pinned to the account, and the React Native build now calls it instead of writing the row itself.
Upserts and INSERT triggers
Upsert is INSERT ... ON CONFLICT DO UPDATE, and Postgres runs the BEFORE INSERT trigger on the proposed row even when the statement ends up updating. A guard that overwrote NEW.current_streak in the insert branch would wipe the client’s proposed value before the update branch could look at it. The fix is a short check at the top of the INSERT branch: if a row already exists for that user, return NEW untouched and let the UPDATE branch decide. Only a genuinely new row gets forced to a streak of 1.
Verification
The holes were read from live function definitions on 7 October 2026, and the SQL file documents what each branch is for. I did not re-run the fix while writing this article, so these are checks to run, not results:
- As an authenticated user, update
last_checkinto a date three days ago. Expected:checkin_day_rejected. - Update
current_streakto 7 while settinglast_checkinto the true next day. Expected: the stored value is the server’s old-plus-one, not 7. - Update
best_streakto 100 with no date change. Expected: the old value comes back. - Check in from a UTC+7 account at 01:00 local time. Expected: accepted, because the date is within the window.
The thing to take from this is narrow. When a table is client-writable and a trigger turns it into value, the policy that only checks ownership is not the security boundary. The trigger is, and it has to decide each column on purpose.