@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 4c66172
Fork 0

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

Mirrored from https://github.com/davoodmehraban89/Factor-easy.git

Synced Dec 4, 06:45 UTC

test(finora): block exposed public identity-RPC audit and journal-state bypass

davoodmehraban89 committed Nov 22, 2026 at 21:01 UTC 4c661721c911ac2c481657e6d4acb2b1ff06ac7c
4 files changed +145 -5
PROJECT_STATE.md
+7 -1
@@ -700,4 +700,10 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
700 - **New owner continuation scope:** strengthen the **existing** `scripts/accounting-history-migration-guard.mjs` and its existing test file, not build a new SQL/RPC implementation or a second financial lifecycle. Existing QA [PR236](https://github.com/davoodmehraban89/Factor-easy/pull/236) head `19a0e1dba4040266f811bad056ad1e5ed7daa1c9` already has four exact-SHA green gates and remains Draft. Start isolated QA-only child branch `qa/finora-identity-rpc-security-tripwire-20261122` from that exact SHA; base to PR236, never main.
701 - **Evidence-triggering defect candidate:** static review of nonmerged [PR219](https://github.com/davoodmehraban89/Factor-easy/pull/219) at `ab14e46abec4b8ef1f36c4f219d9a9ba6d99bc6d` identified three independently reviewable hazards: (1) `SECURITY DEFINER` public identity RPCs directly GRANTed to authenticated with caller-controlled `p_actor` written to financial audit; (2) directly callable registry-only posted-state transition bypassing actual balanced/versioned fiscal journal posting; (3) publicly callable reservation of ATF to a voucher not verified against persisted org/company/fiscal draft. Existing [PR219 review](https://github.com/davoodmehraban89/Factor-easy/pull/219#issuecomment-7082845441) and [Issue216 handoff](https://github.com/davoodmehraban89/Factor-easy/issues/216#issuecomment-7082849834) are **source-only findings**, not proof of deployed exposure.
702 - **Proposed bounded QA task:** add conservative, comment-stripping migration-diff heuristics that flag these *newly added/changed* public identity-RPC shapes and tests covering a PR219-shaped sample, safe private helper, legitimate ordinary journal posting, existing historic posted→draft tripwire, git base-to-head and fail-closed CLI. Reuse the **existing Security workflow invocation**; no workflow or migration changes expected. Avoid false claim of full SQL semantic proof. Explicitly label manual review required. If a test indicates accidental false positive on current code or fixture, correct the heuristic rather than masking the failure.
703 -- **Safety/acceptance:** no production DB access, SQL DDL/DML, server RPC code, auth/grants, historical data, `main`, merge or deployment. Validate actual new PR HEAD's Quality, WP1, WP2 and Security separately (Security tripwire on 0 changed migrations still must show PASS). Existing Issue216/229 product blockers stay OPEN and percentages unchanged.
\ No newline at end of file
703 +- **Safety/acceptance:** no production DB access, SQL DDL/DML, server RPC code, auth/grants, historical data, `main`, merge or deployment. Validate actual new PR HEAD's Quality, WP1, WP2 and Security separately (Security tripwire on 0 changed migrations still must show PASS). Existing Issue216/229 product blockers stay OPEN and percentages unchanged.
704 +
705 +
706 +### 2026-11-22 — FIN-QA-ID-RPC-TRIPWIRE / code and acceptance checkpoint
707 +- Reused the pre-existing `scripts/accounting-history-migration-guard.mjs` and `scripts/accounting-history-migration-guard.test.mjs`, without changing the workflow or a migration. Added `findUnsafePublicJournalIdentityRpcs` for **newly added/modified** public SECURITY DEFINER journal identity functions *granted to authenticated*: caller-controlled audit actor; direct registry-only post state; and identity allocation missing a direct persisted voucher lookup. The guard strips SQL comments, provides filename/line plus specific `FINORA_IDENTITY_RPC_MIGRATION_BLOCKED` CLI marker, and leaves existing posted→draft historical safeguard intact.
708 +- Reproduced source shape against actual [PR219 SHA `ab14e46...`](https://github.com/davoodmehraban89/Factor-easy/pull/219): five static warnings at definition lines **53 (two), 106 (two), 133 (one)**. Added unit fixtures reflecting the source shape, safe private/canonical wrapper, comments and disposable temporary-Git base-to-head diff with fail/allow CLI cases. This is conservative **review tripwire** only: SQL parser completeness, actual Auth JWT and atomicity must still be independently verified by Codex-main.
709 +- **Post-implementation verification pending until exact commit SHA Quality/WP1/WP2/Security run.** No server runtime, SQL migration, Auth/RLS/grants, main, merge, deployment or hosted database used. Issue216/229 remain product P0 OPEN; phase estimates unchanged.
docs/EXECUTION_STATUS.md
+5
@@ -1,5 +1,10 @@
1 # وضعیت اجرای فینورا
2
3 +### ۲۰۲۶-۱۱-۲۲ — FIN-QA-ID-RPC-TRIPWIRE؛ کنترل بازبینی خودکار PR219
4 +- بر مبنای یافتهٔ ثبت‌شده در [PR219](https://github.com/davoodmehraban89/Factor-easy/pull/219#issuecomment-7082845441)، همان کنترل موجود `scripts/accounting-history-migration-guard.mjs` تقویت شد تا در migration **جدید/تغییریافته**، تابع عمومی `SECURITY DEFINER` با مجوز `authenticated` و پارامتر قابل جعل `p_actor`، تغییر مستقل رجیستری به `posted` و رزرو عطف بدون بررسی صریح سند موجود را برای **بازبینی الزامی** مسدود کند. این کنترل تحلیل معنایی کامل SQL نیست و نمی‌تواند جایگزین آزمون JWT/DB شود.
5 +- تست‌های Node موجود با سه آزمون محدود تازه تکمیل شدند: الگوی SQL واقعی PR219 (۵ هشدار)، الگوی خصوصی سالم و کامنت‌شده (بدون هشدار)، و diff روی مخزن Git موقت که نسخه ناامن را در CI رد و نسخه تمیز را قبول می‌کند. بدون migration/RPC یا تغییر داده‌های عملیاتی. تا بررسی گیت روی SHA نهایی، **ادعای PASS تازه ممنوع** است؛ PR236 با چهار گیت قبلی مستقل سبز می‌ماند.
6 +
7 +
8 ### ۲۰۲۶-۱۱-۲۲ — اصلاح صحت QA برای Issue216؛ جلوگیری از پنهان‌شدن رفع نقص
9 - آزمایش مستقل در Node 22 نشان داد `test.todo` حتی اگر assertion موفق شود، به‌عنوان TODO و exit=0 شمرده می‌شود؛ بنابراین **صرف وجود دو TODO شکست موردانتظار، آیندهٔ اصلاح محصول را تضمین نمی‌کند**. به [PR236](https://github.com/davoodmehraban89/Factor-easy/pull/236) دو تست عادی با عنوان صریح «QA fingerprint» اضافه شد: در صورت ثابت‌شدن شناسه، آن‌ها CI را **شکست می‌دهند** تا TODO مربوط حذف و assertion مطلوب `assert.equal` به PASS عادی تبدیل شود.
10 - این کنترل **وجود نقص فعلی را برای مدیریت xfail** پایش می‌کند، نه این‌که نقص محصول را تأیید یا مجاز کند. آخرین اجرای کامل قبلی `1d5adf7da159e997f3541eba0dc80263bceace0f` با Quality/WP2/Security موفق ثبت شده، اما اصلاح QA در commit جدید نیازمند بررسی گیت‌های همان SHA تازه است؛ WP1 قبلی نیز هنوز باید بررسی شود. تغییر محصول/SQL/مجوز یا merge انجام نشده است.
scripts/accounting-history-migration-guard.mjs
+34 -3
@@ -32,6 +32,36 @@ export function findPostedToDraftRewrites(sql) {
32 return results;
33 }
34
35 +
36 +// Conservative, diff-only review heuristic for exposed journal-identity RPCs.
37 +// This intentionally checks new/modified migration SQL only. SQL semantics,
38 +// real JWT permissions and journal transactional atomicity still require review.
39 +export function findUnsafePublicJournalIdentityRpcs(sql){
40 + const source=withoutComments(sql),findings=[];
41 + const starts=[...source.matchAll(/\bCREATE\s+(?:OR\s+REPLACE\s+)?FUNCTION\s+public\s*\.\s*(finora_journal_[a-z_0-9]*identity)\s*\(/gi)];
42 + for(let i=0;i<starts.length;i++){
43 + const match=starts[i],name=match[1].toLowerCase();
44 + const segment=source.slice(match.index,starts[i+1]?.index??source.length);
45 + const definition=/\bAS\s+(\$[a-z_0-9]*\$)([\s\S]*?)\1\s*;/i.exec(segment);
46 + if(!definition)continue;
47 + const header=segment.slice(0,definition.index),body=definition[2];
48 + const grant=new RegExp('\\bGRANT\\s+EXECUTE\\s+ON\\s+FUNCTION\\s+public\\s*\\.\\s*'+name+'\\s*\\([^;]*\\)\\s+TO\\s+[^;]*\\b(?:authenticated|PUBLIC)\\b[^;]*;','i');
49 + if(!grant.test(source)||!/\bSECURITY\s+DEFINER\b/i.test(header))continue;
50 + const line=source.slice(0,match.index).split('\n').length;
51 + const flag=reason=>findings.push({line,kind:'identity-rpc',reason:name+': '+reason});
52 + if(/\bp_actor\s+uuid\b/i.test(header)&&/\bp_actor\b/i.test(body))
53 + flag('caller-supplied p_actor reaches privileged identity RPC; derive audit actor from auth.uid()');
54 + if(/_post_identity$/.test(name)&&
55 + /\bUPDATE\s+public\s*\.\s*finora_journal_document_registry\s+SET\s+state\s*=\s*'posted'/i.test(body))
56 + flag('direct registry-only posted state can bypass canonical journal posting checks');
57 + if(/_allocate_identity$/.test(name)&&
58 + /\bINSERT\s+INTO\s+public\s*\.\s*finora_journal_document_registry\b/i.test(body)&&
59 + !/\bFROM\s+public\s*\.\s*records\b/i.test(body))
60 + flag('public allocator lacks a direct persisted voucher/company/fiscal scope lookup');
61 + }
62 + return findings;
63 +}
64 +
65 function git(args,cwd=process.cwd()){
66 const r=spawnSync('git',args,{cwd,encoding:'utf8',timeout:30000,maxBuffer:8*1024*1024});
67 if(r.error||r.status!==0)throw Error('Git migration diff unavailable: '+(r.stderr||r.error?.message||'git exit '+r.status).trim());
@@ -49,7 +79,7 @@ export function auditMigrationDiff({base='HEAD^',head='HEAD',cwd=process.cwd()}=
79 throw Error('Unexpected migration path from Git diff');
80 const sql=git(['show',head+':'+path],cwd);
81 inspected++;
52 - for(const finding of findPostedToDraftRewrites(sql))violations.push({file:path,...finding});
82 + for(const finding of [...findPostedToDraftRewrites(sql),...findUnsafePublicJournalIdentityRpcs(sql)])violations.push({file:path,...finding});
83 }
84 return {inspected,violations};
85 }
@@ -61,11 +91,12 @@ if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
91 const report=auditMigrationDiff({base});
92 if(report.violations.length){
93 for(const v of report.violations)
64 - console.error('FINORA_POSTED_HISTORY_DOWNGRADE_BLOCKED '+v.file+':'+v.line+' '+v.reason);
65 - console.error('STOP MERGE: preserve historical posted/reversed records and reversal links; use owner-approved non-destructive migration and isolated historic parity tests.');
94 + console.error((v.kind==='identity-rpc'?'FINORA_IDENTITY_RPC_MIGRATION_BLOCKED':'FINORA_POSTED_HISTORY_DOWNGRADE_BLOCKED')+' '+v.file+':'+v.line+' '+v.reason);
95 + console.error('STOP MERGE: preserve posted history and forbid exposed identity-RPC state/audit bypass; require owner-reviewed journal atomicity, real JWT negatives and migration parity.');
96 process.exitCode=1;
97 }else{
98 console.log('FINORA_POSTED_HISTORY_MIGRATION_TRIPWIRE_PASS: '+report.inspected+' changed migration file(s) scanned; heuristic only, SQL review required.');
99 + console.log('FINORA_IDENTITY_RPC_MIGRATION_TRIPWIRE_PASS: '+report.inspected+' changed migration file(s) scanned; heuristic only, real JWT/DB review required.');
100 }
101 }catch(error){console.error('FINORA_MIGRATION_GUARD_UNVERIFIED: '+error.message);process.exitCode=1;}
102 }
scripts/accounting-history-migration-guard.test.mjs
+99 -1
@@ -5,7 +5,7 @@ import {tmpdir} from 'node:os';
5 import {join} from 'node:path';
6 import {fileURLToPath} from 'node:url';
7 import {spawnSync} from 'node:child_process';
8 -import {findPostedToDraftRewrites,auditMigrationDiff} from './accounting-history-migration-guard.mjs';
8 +import {findPostedToDraftRewrites,findUnsafePublicJournalIdentityRpcs,auditMigrationDiff} from './accounting-history-migration-guard.mjs';
9
10 const dangerous219=String.raw`
11 DO $$
@@ -78,3 +78,101 @@ test('only scans added/modified SQL migrations in base-to-head commit diff; bloc
78 assert.match(accepted.stdout,/FINORA_POSTED_HISTORY_MIGRATION_TRIPWIRE_PASS/);
79 }finally{rmSync(dir,{recursive:true,force:true});}
80 });
81 +
82 +
83 +// Exact shapes adapted from the unmerged PR219 candidate. These text fixtures
84 +// are never migrated or executed: they exercise the SECURITY workflow guard.
85 +const exposedPr219IdentityFunctions=String.raw`
86 +CREATE OR REPLACE FUNCTION public.finora_journal_allocate_identity(
87 + p_org uuid,p_company text,p_fy text,p_voucher text,p_actor uuid DEFAULT auth.uid()
88 +) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $identity$
89 +BEGIN
90 + INSERT INTO public.finora_journal_document_registry(organization_id,company_id,voucher_id,created_by)
91 + VALUES(p_org,p_company,p_voucher,p_actor);
92 + RETURN '{}'::jsonb;
93 +END $identity$;
94 +CREATE OR REPLACE FUNCTION public.finora_journal_post_identity(
95 + p_org uuid,p_voucher text,p_actor uuid DEFAULT auth.uid()
96 +) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $identity$
97 +BEGIN
98 + UPDATE public.finora_journal_document_registry
99 + SET state='posted',posted_by=p_actor WHERE organization_id=p_org AND voucher_id=p_voucher;
100 + RETURN '{}'::jsonb;
101 +END $identity$;
102 +CREATE OR REPLACE FUNCTION public.finora_journal_delete_identity(
103 + p_org uuid,p_voucher text,p_actor uuid DEFAULT auth.uid()
104 +) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $identity$
105 +BEGIN
106 + UPDATE public.finora_journal_document_registry
107 + SET state='deleted',deleted_by=p_actor WHERE organization_id=p_org AND voucher_id=p_voucher;
108 + RETURN '{}'::jsonb;
109 +END $identity$;
110 +GRANT EXECUTE ON FUNCTION public.finora_journal_allocate_identity(uuid,text,text,text,uuid) TO authenticated;
111 +GRANT EXECUTE ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) TO authenticated;
112 +GRANT EXECUTE ON FUNCTION public.finora_journal_delete_identity(uuid,text,uuid) TO authenticated;
113 +`;
114 +
115 +test('PR219-shaped public identity RPCs trigger actor, registry-post and phantom-allocation review',()=>{
116 + const issues=findUnsafePublicJournalIdentityRpcs(exposedPr219IdentityFunctions);
117 + assert.equal(issues.length,5);
118 + assert.equal(issues.filter(x=>x.reason.includes('p_actor')).length,3);
119 + assert.equal(issues.filter(x=>x.reason.includes('registry-only posted')).length,1);
120 + assert.equal(issues.filter(x=>x.reason.includes('persisted voucher')).length,1);
121 + assert.ok(issues.every(x=>x.kind==='identity-rpc'&&Number.isInteger(x.line)));
122 +});
123 +
124 +test('safe private identity implementation and public canonical post wrapper do not trigger heuristic',()=>{
125 + const safe=String.raw`
126 +CREATE OR REPLACE FUNCTION private.finora_journal_allocate_identity(p_org uuid)
127 +RETURNS void LANGUAGE plpgsql SECURITY DEFINER AS $$
128 +BEGIN UPDATE public.finora_journal_document_registry SET state='posted'; END $$;
129 +CREATE OR REPLACE FUNCTION public.finora_journal_post_identity(p_org uuid,p_voucher text)
130 +RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER AS $$
131 +BEGIN RETURN public.finora_journal_post(p_org,p_voucher,1); END $$;
132 +GRANT EXECUTE ON FUNCTION public.finora_journal_post_identity(uuid,text) TO authenticated;
133 +`;
134 + assert.deepEqual(findUnsafePublicJournalIdentityRpcs(safe),[]);
135 + assert.deepEqual(findUnsafePublicJournalIdentityRpcs(
136 + exposedPr219IdentityFunctions.split('\n').map(s=>'-- '+s).join('\n')),[]);
137 +});
138 +
139 +test('PR migration base-to-head diff blocks exposed candidate RPCs; clean version passes',()=>{
140 + const dir=mkdtempSync(join(tmpdir(),'finora-identity-tripwire-'));
141 + const run=args=>{
142 + const r=spawnSync('git',args,{cwd:dir,encoding:'utf8',timeout:15000});
143 + assert.equal(r.status,0,r.stderr||r.error?.message);
144 + return r.stdout.trim();
145 + };
146 + const cli=fileURLToPath(new URL('./accounting-history-migration-guard.mjs',import.meta.url));
147 + try{
148 + mkdirSync(join(dir,'supabase','migrations'),{recursive:true});
149 + run(['init','-q']);
150 + run(['config','user.email','qa@example.invalid']);
151 + run(['config','user.name','Finora QA']);
152 + writeFileSync(join(dir,'supabase','migrations','000_baseline.sql'),'SELECT 1;');
153 + run(['add','.']);run(['commit','-qm','baseline']);
154 + const base=run(['rev-parse','HEAD']);
155 + writeFileSync(join(dir,'supabase','migrations','001_public_identity.sql'),exposedPr219IdentityFunctions);
156 + run(['add','.']);run(['commit','-qm','unsafe identity RPC']);
157 + let report=auditMigrationDiff({base,cwd:dir});
158 + assert.equal(report.inspected,1);
159 + assert.equal(report.violations.length,5);
160 + assert.ok(report.violations.every(x=>x.file==='supabase/migrations/001_public_identity.sql'));
161 + const blocked=spawnSync(process.execPath,[cli],{cwd:dir,encoding:'utf8',
162 + env:{...process.env,FINORA_MIGRATION_BASE_SHA:base}});
163 + assert.equal(blocked.status,1);
164 + assert.match(blocked.stderr,/FINORA_IDENTITY_RPC_MIGRATION_BLOCKED/);
165 + // A private trusted internal helper and normal public journal post wrapper
166 + // do not require publicly callable identity-state transitions.
167 + writeFileSync(join(dir,'supabase','migrations','001_public_identity.sql'),
168 + "CREATE FUNCTION private.safe_identity() RETURNS void LANGUAGE sql AS $$ SELECT 1 $$;");
169 + run(['add','.']);run(['commit','-qm','remove exposed identity helper']);
170 + report=auditMigrationDiff({base,cwd:dir});
171 + assert.equal(report.inspected,1);
172 + assert.deepEqual(report.violations,[]);
173 + const allowed=spawnSync(process.execPath,[cli],{cwd:dir,encoding:'utf8',
174 + env:{...process.env,FINORA_MIGRATION_BASE_SHA:base}});
175 + assert.equal(allowed.status,0,allowed.stderr);
176 + assert.match(allowed.stdout,/FINORA_IDENTITY_RPC_MIGRATION_TRIPWIRE_PASS/);
177 + }finally{rmSync(dir,{recursive:true,force:true});}
178 +});