سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 20:45 UTC
security(stage3): deny JWT modifications to sources linked to posted or reversed vouchers
davoodmehraban89 committed
Oct 23, 2026 at 14:48 UTC
aadb3458bc5288618f9d3d64daa6959e442fb489
1 file changed
+54
supabase/migrations/20261016104500_stage3_posted_source_immutable.sql
new
+54
@@ -0,0 +1,54 @@
1
+-- Stage 3 security gate: source documents referenced by an already posted
2
+-- or reversed voucher cannot be altered through user-facing REST, versioned
3
+-- sync, or ordinary SQL UPDATE/DELETE. Test-only pending release approval.
4
+-- Directly addresses RED local JWT evidence: HTTP 200 mutation after autopost.
5
+-- All checks are tenant-scoped and based on the persisted journal linkage,
6
+-- not on potentially stale/missing client-owned accountingStatus flags.
7
+CREATE OR REPLACE FUNCTION private.finora_stage3_guard_posted_source()
8
+RETURNS trigger
9
+LANGUAGE plpgsql
10
+SECURITY DEFINER
11
+SET search_path = ''
12
+AS $guard$
13
+DECLARE
14
+ v_kind text;
15
+BEGIN
16
+ IF TG_OP NOT IN ('UPDATE','DELETE') THEN
17
+ RETURN NEW;
18
+ END IF;
19
+ IF OLD.collection NOT IN ('invoices','purchases') THEN
20
+ RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
21
+ END IF;
22
+
23
+ -- Ordinary authenticated JWT clients must never mutate a committed source.
24
+ -- auth.uid() remains the original JWT actor inside this SECURITY DEFINER
25
+ -- trigger. Trusted migrations/admin repairs with no user JWT are not
26
+ -- automatically blocked; those need independent operational approval.
27
+ IF auth.uid() IS NULL
28
+ OR private.finora_phase1a_mode(OLD.organization_id) <> 'enforce' THEN
29
+ RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
30
+ END IF;
31
+
32
+ v_kind := CASE OLD.collection WHEN 'invoices' THEN 'sale' ELSE 'purchase' END;
33
+ IF EXISTS (
34
+ SELECT 1 FROM public.records v
35
+ WHERE v.organization_id = OLD.organization_id
36
+ AND v.collection = 'journalVouchers'
37
+ AND v.data->>'sourceType' = v_kind
38
+ AND v.data->>'sourceId' = OLD.id
39
+ AND v.data->>'status' IN ('posted','reversed')
40
+ ) THEN
41
+ RAISE EXCEPTION 'FINORA_POSTED_SOURCE_IMMUTABLE'
42
+ USING ERRCODE = '23514';
43
+ END IF;
44
+ RETURN CASE WHEN TG_OP = 'DELETE' THEN OLD ELSE NEW END;
45
+END
46
+$guard$;
47
+
48
+DROP TRIGGER IF EXISTS trg_finora_stage3_posted_source_immutable ON public.records;
49
+CREATE TRIGGER trg_finora_stage3_posted_source_immutable
50
+BEFORE UPDATE OR DELETE ON public.records
51
+FOR EACH ROW EXECUTE FUNCTION private.finora_stage3_guard_posted_source();
52
+
53
+REVOKE ALL ON FUNCTION private.finora_stage3_guard_posted_source()
54
+FROM PUBLIC, anon, authenticated;