سامانه صدور فاکتور و حسابداری
test(finora): detect implicit PUBLIC execute and cross-migration identity RPC grants
davoodmehraban89 committed
Nov 22, 2026 at 21:29 UTC
b2a9a6238eae5618840a17137bef8f91fe80a910
4 files changed
+108
-2
PROJECT_STATE.md
+6
@@ -713,3 +713,9 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
713
- Owner asked to continue. Existing [Draft PR237](https://github.com/davoodmehraban89/Factor-easy/pull/237) exact head `4c661721c911ac2c481657e6d4acb2b1ff06ac7c` has 3/3 triggered Quality/WP1/Security PASS, WP2 path-filtered. Instead of a new PR or financial implementation, inspect this specific QA guard for a security false-negative.
714
- **Confirmed against PostgreSQL CREATE FUNCTION documentation**: function EXECUTE is granted to `PUBLIC` by default, absent an effective REVOKE or configured alternate default privileges. Existing `findUnsafePublicJournalIdentityRpcs` only checks `GRANT EXECUTE` found in the same newly changed SQL migration file, so a dangerous public SECURITY DEFINER identity function *without explicit GRANT* can evade review. Separate later migration containing only GRANT can also evade the same-file matcher. This is a **QA tripwire deficiency**, not a runtime exploit demonstration.
715
- **Scoped change in existing PR237:** conservatively review dangerous newly created/changed public SECURITY DEFINER identity RPCs even without GRANT unless explicit effective PUBLIC REVOKE exists in the same SQL file, and review standalone public journal-identity GRANT statements in changed SQL migrations. Do not block ordinary safe private/canonical journal wrappers; add positive/negative Node fixtures and temporary-Git diff CLI tests. Maintain exact existing posted-history guard and use existing Quality/Security workflows, document regex limitations including ALTER DEFAULT PRIVILEGES, grants across roles or dynamic SQL. No SQL/migrations/Auth/grants/financial app code/schema/production/main/merge. Keep Issue216/229 OPEN and phases unchanged.
716
+
717
+
718
+### 2026-11-22 — FIN-QA-ID-RPC-DEFAULT-EXECUTE / implementation and verification plan
719
+- Corrected the existing `findUnsafePublicJournalIdentityRpcs` in [Draft PR237](https://github.com/davoodmehraban89/Factor-easy/pull/237): PostgreSQL `CREATE FUNCTION` grants EXECUTE to `PUBLIC` by default; a dangerous new public SECURITY DEFINER identity RPC lacking explicit GRANT must still trigger review unless the source has explicit REVOKE from PUBLIC and no renewed authenticated/anon/PUBLIC GRANT. Distinct migration with standalone GRANT for an existing `public.finora_journal_*identity` now triggers manual review, even without CREATE. Existing 5 PR219-shape alerts and posted-history migration safeguards remain.
720
+- Expanded existing Node suite by **four tests**: implicit PUBLIC exposure, explicit REVOKE/renewed GRANT, standalone later GRANT and actual temporary-Git base→head grant-only diff blocked by CLI. **Heuristic limitation:** cannot prove effective catalog ACLs across all historical grants, `ALTER DEFAULT PRIVILEGES`, dynamic SQL or actual JWT authorization; real database/JWT testing is still Codex-main's obligation.
721
+- Do not claim a result for the new SHA until exact-head Quality/Security/WP1 finish. WP2 only if actually triggered. No financial app runtime, migration SQL, grants/RLS/Auth, posted history, `main`, merge or deployment touched. Issue216 and Issue229 remain product P0 OPEN and estimated phase progress unchanged.
docs/EXECUTION_STATUS.md
+5
@@ -1,5 +1,10 @@
1
# وضعیت اجرای فینورا
2
3
+### ۲۲ نوامبر ۲۰۲۶ — اصلاح ضعف کنترل امنیتی PR237 در مجوزهای پیشفرض
4
+- کنترل قبلی فقط SQL دارای `GRANT EXECUTE` صریح را بررسی میکرد؛ اما PostgreSQL بهصورت پیشفرض برای تابع جدید به `PUBLIC` مجوز اجرای تابع میدهد. اکنون تابع عمومی `SECURITY DEFINER` با الگوی خطرناک حتی بدون GRANT صریح هم بازبینی میشود؛ `REVOKE` صریح از PUBLIC در همان منبع، بدون GRANT مجدد، این هشدار را برای همان تابع حذف میکند.
5
+- `GRANT` مستقلِ تابع هویت سند در migration جداگانه نیز هشدار میدهد؛ چهار آزمون جدید سناریوی مجوز پیشفرض، REVOKE/GRANT، GRANT مستقل و diff واقعی مخزن موقت را میپوشانند. **این الگوی متنی اثبات امنیت SQL یا اصلاح محصول نیست**؛ تاریخچهٔ ACL و JWT واقعی باید جداگانه بررسی شود. نتیجهٔ CI روی SHA جدید تا اتمام Workflowها نامعلوم است؛ Issue216/229 باز هستند.
6
+
7
+
8
### ۲۰۲۶-۱۱-۲۲ — FIN-QA-ID-RPC-TRIPWIRE؛ کنترل بازبینی خودکار PR219
9
- بر مبنای یافتهٔ ثبتشده در [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 شود.
10
- تستهای Node موجود با سه آزمون محدود تازه تکمیل شدند: الگوی SQL واقعی PR219 (۵ هشدار)، الگوی خصوصی سالم و کامنتشده (بدون هشدار)، و diff روی مخزن Git موقت که نسخه ناامن را در CI رد و نسخه تمیز را قبول میکند. بدون migration/RPC یا تغییر دادههای عملیاتی. تا بررسی گیت روی SHA نهایی، **ادعای PASS تازه ممنوع** است؛ PR236 با چهار گیت قبلی مستقل سبز میماند.
scripts/accounting-history-migration-guard.mjs
+22
-2
@@ -45,8 +45,15 @@ export function findUnsafePublicJournalIdentityRpcs(sql){
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;
48
+ // PostgreSQL grants EXECUTE to PUBLIC for new functions by default.
49
+ // An explicit GRANT is *not* needed to make a SECURITY DEFINER public RPC callable.
50
+ // An explicit REVOKE from PUBLIC suppresses this default only when no
51
+ // separate GRANT to authenticated/anon/PUBLIC restores access.
52
+ // ALTER DEFAULT PRIVILEGES / prior ACLs and SQL semantics require manual review.
53
+ const grant=new RegExp('\\bGRANT\\s+(?:EXECUTE|ALL(?:\\s+PRIVILEGES)?)\\s+ON\\s+FUNCTION\\s+public\\s*\\.\\s*'+name+'\\s*\\([^;]*\\)\\s+TO\\s+[^;]*\\b(?:authenticated|anon|PUBLIC)\\b[^;]*;','i');
54
+ const revokePublic=new RegExp('\\bREVOKE\\s+(?:EXECUTE|ALL(?:\\s+PRIVILEGES)?)\\s+ON\\s+FUNCTION\\s+public\\s*\\.\\s*'+name+'\\s*\\([^;]*\\)\\s+FROM\\s+[^;]*\\bPUBLIC\\b[^;]*;','i');
55
+ const exposedBySource=grant.test(source)||!revokePublic.test(source);
56
+ if(!/\bSECURITY\s+DEFINER\b/i.test(header)||!exposedBySource)continue;
57
const line=source.slice(0,match.index).split('\n').length;
58
const flag=reason=>findings.push({line,kind:'identity-rpc',reason:name+': '+reason});
59
if(/\bp_actor\s+uuid\b/i.test(header)&&/\bp_actor\b/i.test(body))
@@ -59,6 +66,19 @@ export function findUnsafePublicJournalIdentityRpcs(sql){
66
!/\bFROM\s+public\s*\.\s*records\b/i.test(body))
67
flag('public allocator lacks a direct persisted voucher/company/fiscal scope lookup');
68
}
69
+ // A later migration can re-expose an existing identity function by a
70
+ // standalone GRANT; this file contains no CREATE and cannot inspect the
71
+ // complete prior function/ACL history. Fail closed to require review.
72
+ const standaloneGrants=/\bGRANT\s+(?:EXECUTE|ALL(?:\s+PRIVILEGES)?)\s+ON\s+FUNCTION\s+public\s*\.\s*(finora_journal_[a-z_0-9]*identity)\s*\([^;]*?\)\s+TO\s+[^;]*\b(?:authenticated|anon|PUBLIC)\b[^;]*;/gi;
73
+ for(const grant of source.matchAll(standaloneGrants)){
74
+ const name=grant[1].toLowerCase();
75
+ if(starts.some(x=>x[1].toLowerCase()===name))continue;
76
+ findings.push({
77
+ line:source.slice(0,grant.index).split('\n').length,
78
+ kind:'identity-rpc',
79
+ reason:name+': standalone grant can re-expose a prior journal identity RPC; manual ACL and JWT review required'
80
+ });
81
+ }
82
return findings;
83
}
84
scripts/accounting-history-migration-guard.test.mjs
+75
@@ -176,3 +176,78 @@ test('PR migration base-to-head diff blocks exposed candidate RPCs; clean versio
176
assert.match(allowed.stdout,/FINORA_IDENTITY_RPC_MIGRATION_TRIPWIRE_PASS/);
177
}finally{rmSync(dir,{recursive:true,force:true});}
178
});
179
+
180
+
181
+test('PostgreSQL default PUBLIC EXECUTE: no explicit GRANT still flags exposed identity RPC shapes',()=>{
182
+ const implicit=exposedPr219IdentityFunctions.replace(/^GRANT EXECUTE ON FUNCTION.*\n/gm,'');
183
+ const findings=findUnsafePublicJournalIdentityRpcs(implicit);
184
+ assert.equal(findings.length,5);
185
+ assert.equal(findings.filter(x=>x.reason.includes('p_actor')).length,3);
186
+ assert.equal(findings.filter(x=>x.reason.includes('registry-only')).length,1);
187
+ assert.equal(findings.filter(x=>x.reason.includes('persisted voucher')).length,1);
188
+});
189
+
190
+test('explicit PUBLIC revoke suppresses implicit exposure; authenticated grant restores review requirement',()=>{
191
+ const implicit=exposedPr219IdentityFunctions.replace(/^GRANT EXECUTE ON FUNCTION.*\n/gm,'');
192
+ const revoke=[
193
+ 'REVOKE ALL ON FUNCTION public.finora_journal_allocate_identity(uuid,text,text,text,uuid) FROM PUBLIC,anon,authenticated;',
194
+ 'REVOKE ALL ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) FROM PUBLIC,anon,authenticated;',
195
+ 'REVOKE ALL ON FUNCTION public.finora_journal_delete_identity(uuid,text,uuid) FROM PUBLIC,anon,authenticated;'
196
+ ].join('\n');
197
+ assert.deepEqual(findUnsafePublicJournalIdentityRpcs(implicit+revoke),[]);
198
+ const restored=implicit+revoke+'\nGRANT EXECUTE ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) TO authenticated;';
199
+ const result=findUnsafePublicJournalIdentityRpcs(restored);
200
+ assert.equal(result.length,2);
201
+ assert.ok(result.every(x=>x.reason.includes('post_identity')));
202
+ // Revoking only authenticated/anon does not revoke PostgreSQL's PUBLIC default.
203
+ const noPublic='REVOKE ALL ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) FROM authenticated,anon;';
204
+ const justPost=implicit.slice(implicit.indexOf('CREATE OR REPLACE FUNCTION public.finora_journal_post_identity('),
205
+ implicit.indexOf('CREATE OR REPLACE FUNCTION public.finora_journal_delete_identity('));
206
+ assert.equal(findUnsafePublicJournalIdentityRpcs(justPost+noPublic).length,2);
207
+});
208
+
209
+test('separate later migration containing only GRANT is flagged with no CREATE in that file',()=>{
210
+ const standalone='GRANT EXECUTE ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) TO authenticated;';
211
+ const result=findUnsafePublicJournalIdentityRpcs(standalone);
212
+ assert.equal(result.length,1);
213
+ assert.match(result[0].reason,/standalone grant/);
214
+ assert.deepEqual(findUnsafePublicJournalIdentityRpcs('-- '+standalone),[]);
215
+ // A safe normal journal posting RPC is out of scope of the identity-state tripwire.
216
+ assert.deepEqual(findUnsafePublicJournalIdentityRpcs(
217
+ 'GRANT EXECUTE ON FUNCTION public.finora_journal_post(uuid,text,bigint) TO authenticated;'),[]);
218
+});
219
+
220
+test('base-to-head migration diff catches a standalone GRANT in a later migration',()=>{
221
+ const dir=mkdtempSync(join(tmpdir(),'finora-identity-cross-file-grant-'));
222
+ const git=args=>{
223
+ const r=spawnSync('git',args,{cwd:dir,encoding:'utf8',timeout:15000});
224
+ assert.equal(r.status,0,r.stderr||r.error?.message);
225
+ return r.stdout.trim();
226
+ };
227
+ const cli=fileURLToPath(new URL('./accounting-history-migration-guard.mjs',import.meta.url));
228
+ try{
229
+ mkdirSync(join(dir,'supabase','migrations'),{recursive:true});
230
+ git(['init','-q']);
231
+ git(['config','user.email','qa@example.invalid']);
232
+ git(['config','user.name','Finora QA']);
233
+ writeFileSync(join(dir,'supabase','migrations','000_private.sql'),
234
+ 'REVOKE ALL ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) FROM PUBLIC;');
235
+ git(['add','.']);git(['commit','-qm','historical hardened RPC']);
236
+ const base=git(['rev-parse','HEAD']);
237
+ const grantFile=join(dir,'supabase','migrations','001_reexpose.sql');
238
+ writeFileSync(grantFile,'GRANT EXECUTE ON FUNCTION public.finora_journal_post_identity(uuid,text,uuid) TO authenticated;');
239
+ git(['add','.']);git(['commit','-qm','later grant bypass']);
240
+ const report=auditMigrationDiff({base,cwd:dir});
241
+ assert.equal(report.inspected,1);
242
+ assert.equal(report.violations.length,1);
243
+ assert.match(report.violations[0].reason,/standalone grant/);
244
+ const blocked=spawnSync(process.execPath,[cli],{cwd:dir,encoding:'utf8',
245
+ env:{...process.env,FINORA_MIGRATION_BASE_SHA:base}});
246
+ assert.equal(blocked.status,1,blocked.stderr);
247
+ assert.match(blocked.stderr,/FINORA_IDENTITY_RPC_MIGRATION_BLOCKED/);
248
+ writeFileSync(grantFile,'SELECT 1;');
249
+ git(['add','.']);git(['commit','-qm','remove re-exposure']);
250
+ const clean=auditMigrationDiff({base,cwd:dir});
251
+ assert.deepEqual(clean.violations,[]);
252
+ }finally{rmSync(dir,{recursive:true,force:true});}
253
+});