@davoodmehraban89 / Factor-easy / commits / c362503
Fork 0

سامانه صدور فاکتور و حسابداری

fix(finance): scope journal guard audit writes to tenant members

davoodmehraban89 committed Nov 15, 2026 at 13:05 UTC c3625039b34ab9425dd91c11cf9090bc94fdbe4f
5 files changed +84 -2
PROJECT_STATE.md
+6 -1
@@ -320,4 +320,9 @@ Owner requests layer-by-layer click/functional testing of all controls and compa
320 ### 2026-11-15 — WP1 first CI failure and baseline prerequisite repair
321 - Exact PR206 head `e4e0e29b7bfcb207d007b4cac801be1ec1101dfe` ran the new disposable workflow. PostgreSQL 17 image setup passed; the baseline RED step failed before WP1 SQL execution. Captured artifact `wp1-baseline-red.zip` shows `public.handle_new_user()` references `profiles.phone`, but current main source migrations did not include historical `20261007165208_phone_identity_profile.sql`.
322 - Root cause is a missing historical migration archive in current main, not a financial regression. The WP1 disposable harness already includes `20261007165208` in its selected migration allowlist, so port that one archived prerequisite from WP0 PR194; do not import unrelated PR194 changes. It is documented as already applied to Production and recovered read-only from migration history; repository archive addition is not a Production reapply.
323 -- No WP1 financial test stage ran on this first attempt. Next exact-head workflow must rerun after adding the archive. Do not mark WP1 green until all workflow steps pass.
\ No newline at end of file
323 +- No WP1 financial test stage ran on this first attempt. Next exact-head workflow must rerun after adding the archive. Do not mark WP1 green until all workflow steps pass.
324 +
325 +### 2026-11-15 — Independent SQL review: guard audit tenant scope
326 +- Review found `private.finora_phase1a_log_guard(uuid,text,text,text)` is SECURITY DEFINER and EXECUTE-granted to authenticated, but previously trusted caller-supplied `p_org` without checking active membership. A tenant A member could forge guard_violation audit entries in tenant B. This is an audit-integrity / cross-tenant contamination risk, not direct financial-row write access.
327 +- Added candidate migration `20261115130000_wp1_guard_audit_tenant_scope.sql`, conservative DOWN, and `wp1_guard_audit_tenant_scope.sql` regression. It requires active membership for `auth.uid()` before audit insertion and bounds input. Trigger logging for same-tenant operations remains permitted.
328 +- Patch has not yet passed CI. It is candidate-only; do not merge or deploy until the full exact-head WP1 workflow passes and SQL/ACL review is repeated.
\ No newline at end of file
docs/audits/WP1_DB_ONLY_INTEGRATION_CANDIDATE_2026-11-15_FA.md
+9 -1
@@ -46,4 +46,12 @@ Root cause: the current main source tree does not contain the historical migrati
46
47 Repair: port only this single historical prerequisite migration from WP0 into this candidate. This is a source-history/schema-parity repair, not a WP1 financial migration and not an instruction to reapply it in Production. The harness already selects this exact migration timestamp; no test was weakened and no synthetic schema shortcut was introduced.
48
49 -The next exact-head CI run must prove the baseline stage progresses past auth-user bootstrap. The remaining WP1 SQL stages are still unverified until the workflow completes.
\ No newline at end of file
49 +The next exact-head CI run must prove the baseline stage progresses past auth-user bootstrap. The remaining WP1 SQL stages are still unverified until the workflow completes.
50 +
51 +## Independent SQL review finding — guard audit tenant boundary
52 +
53 +The read-through of the staged SQL found that `private.finora_phase1a_log_guard(uuid,text,text,text)` was `SECURITY DEFINER` and executable by `authenticated`, but accepted a caller-supplied organization ID without verifying active membership. The trigger needs authenticated execution to record audit-mode violations, so simply revoking the grant would break the `SECURITY INVOKER` trigger path. However, as written, a member of organization A could directly invoke the function with organization B and append a forged `guard_violation` row to B audit history.
54 +
55 +An additive candidate migration `20261115130000_wp1_guard_audit_tenant_scope.sql` now checks that `auth.uid()` is an active member of the supplied organization before writing and bounds audit input. A synthetic SQL regression `wp1_guard_audit_tenant_scope.sql` verifies that cross-tenant injection is denied while same-tenant trigger logging remains available. A conservative DOWN restores the prior logger body; it does not remove audit history.
56 +
57 +This is a code-review-driven patch, not yet validated. It is included in the disposable WP1 suite and must pass the next exact-head CI run. It does not change the audit/shadow default, enable enforcement, or authorize Production.
\ No newline at end of file
supabase/migrations/20261115130000_wp1_guard_audit_tenant_scope.sql new
+23
@@ -0,0 +1,23 @@
1 +-- WP1 security correction: guard audit logging must stay within the caller tenant.
2 +-- Additive and disposable-proof only; does not change guard mode or enable enforcement.
3 +CREATE OR REPLACE FUNCTION private.finora_phase1a_log_guard(
4 + p_org uuid,p_voucher text,p_message text,p_state text)
5 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path=''
6 +AS $fn$
7 +DECLARE v_actor uuid:=auth.uid();
8 +BEGIN
9 + IF v_actor IS NULL OR p_org IS NULL OR NOT EXISTS(
10 + SELECT 1 FROM public.organization_members
11 + WHERE organization_id=p_org AND user_id=v_actor AND status='active') THEN
12 + RAISE EXCEPTION 'FINORA_GUARD_AUDIT_SCOPE_FORBIDDEN' USING ERRCODE='42501';
13 + END IF;
14 + IF coalesce(length(p_message),0)>2000 OR coalesce(p_state,'') !~ '^[0-9A-Z]{5}$' THEN
15 + RAISE EXCEPTION 'FINORA_GUARD_AUDIT_INPUT_INVALID' USING ERRCODE='22023';
16 + END IF;
17 + PERFORM private.finora_phase1a_audit_event(
18 + p_org,p_voucher,v_actor,'guard_violation',coalesce(p_message,''),
19 + jsonb_build_object('sqlstate',p_state));
20 +END $fn$;
21 +-- EXECUTE remains available to authenticated because SECURITY INVOKER trigger
22 +-- functions call this SECURITY DEFINER writer. Tenant membership is now checked
23 +-- inside the writer; anon/public access remains revoked by the prior migration.
supabase/rollback/20261115130000_wp1_guard_audit_tenant_scope.sql new
+7
@@ -0,0 +1,7 @@
1 +-- Conservative DOWN: restore the previous WP1/Phase 1A logger body.
2 +-- This does not remove audit history or other WP1 objects.
3 +CREATE OR REPLACE FUNCTION private.finora_phase1a_log_guard(p_org uuid,p_voucher text,p_message text,p_state text)
4 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $a$
5 +BEGIN
6 + PERFORM private.finora_phase1a_audit_event(p_org,p_voucher,auth.uid(),'guard_violation',p_message,jsonb_build_object('sqlstate',p_state));
7 +END $a$;
supabase/tests/wp1_guard_audit_tenant_scope.sql new
+39
@@ -0,0 +1,39 @@
1 +-- Cross-tenant guard-audit injection must fail; own-tenant audit stays usable.
2 +\set ON_ERROR_STOP on
3 +BEGIN;
4 +INSERT INTO auth.users(id,email,email_confirmed_at,raw_user_meta_data) VALUES
5 + ('fa000000-0000-4000-8000-000000000001','wp1-audit-a@example.invalid',now(),'{}'),
6 + ('fa000000-0000-4000-8000-000000000002','wp1-audit-b@example.invalid',now(),'{}');
7 +SELECT set_config('wp1.audit_org_a',(SELECT id::text FROM public.organizations WHERE owner_user_id='fa000000-0000-4000-8000-000000000001'),true);
8 +SELECT set_config('wp1.audit_org_b',(SELECT id::text FROM public.organizations WHERE owner_user_id='fa000000-0000-4000-8000-000000000002'),true);
9 +SELECT set_config('request.jwt.claim.sub','fa000000-0000-4000-8000-000000000001',true);
10 +SET LOCAL ROLE authenticated;
11 +DO $test$
12 +BEGIN
13 + BEGIN
14 + PERFORM private.finora_phase1a_log_guard(current_setting('wp1.audit_org_b')::uuid,
15 + 'WP1_CROSS_ORG_SPOOF','forged cross-tenant audit event','23514');
16 + RAISE EXCEPTION 'WP1_CROSS_TENANT_AUDIT_INJECTION_ACCEPTED';
17 + EXCEPTION WHEN insufficient_privilege THEN
18 + IF SQLERRM<>'FINORA_GUARD_AUDIT_SCOPE_FORBIDDEN' THEN RAISE; END IF;
19 + END;
20 + PERFORM private.finora_phase1a_log_guard(current_setting('wp1.audit_org_a')::uuid,
21 + 'WP1_OWN_ORG_AUDIT','synthetic same-tenant audit event','23514');
22 +END $test$;
23 +RESET ROLE;
24 +DO $verify$
25 +BEGIN
26 + IF NOT EXISTS(SELECT 1 FROM private.finora_phase1a_journal_audit
27 + WHERE organization_id=current_setting('wp1.audit_org_a')::uuid
28 + AND voucher_id='WP1_OWN_ORG_AUDIT' AND actor_id='fa000000-0000-4000-8000-000000000001'
29 + AND action='guard_violation' AND reason='synthetic same-tenant audit event') THEN
30 + RAISE EXCEPTION 'WP1_OWN_TENANT_AUDIT_NOT_WRITTEN';
31 + END IF;
32 + IF EXISTS(SELECT 1 FROM private.finora_phase1a_journal_audit
33 + WHERE organization_id=current_setting('wp1.audit_org_b')::uuid
34 + AND voucher_id='WP1_CROSS_ORG_SPOOF') THEN
35 + RAISE EXCEPTION 'WP1_CROSS_TENANT_AUDIT_ROW_WRITTEN';
36 + END IF;
37 + RAISE NOTICE 'WP1_GUARD_AUDIT_SCOPE_PASS: cross-tenant spoof denied, own-tenant trigger logging retained';
38 +END $verify$;
39 +ROLLBACK;