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

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

test(wp2): reproduce Issue229 approval bypass with restricted real JWT

davoodmehraban89 committed Nov 22, 2026 at 13:33 UTC f683d5f88dfb619ae4b9c2b2890ab78bfd30ff4d
1 file changed +149
scripts/wp2-source-approval-boundary-jwt-e2e.mjs new
+149
@@ -0,0 +1,149 @@
1 +import assert from 'node:assert/strict';
2 +import {spawnSync} from 'node:child_process';
3 +
4 +// Issue #229 — EXPECTED CONTRACT RED, never a product pass.
5 +// Real Auth JWT / PostgREST against the *disposable local* WP2 stack only.
6 +// psql/service-role are strictly fixture and read-back tools, never the posting caller.
7 +const api=String(process.env.API_URL||'').replace(/\/$/,'');
8 +const anon=process.env.ANON_KEY,service=process.env.SERVICE_ROLE_KEY,db=process.env.DB_URL;
9 +for(const [key,val] of Object.entries({API_URL:api,ANON_KEY:anon,SERVICE_ROLE_KEY:service,DB_URL:db})){
10 + assert.ok(val,'missing disposable WP2 setting '+key);
11 +}
12 +for(const [label,url] of [['API_URL',api],['DB_URL',db]]){
13 + const host=new URL(url).hostname.toLowerCase();
14 + assert.ok(['localhost','127.0.0.1','::1','[::1]'].includes(host),
15 + label+' MUST refer to localhost: refusing any nonlocal financial operation');
16 +}
17 +const suffix=Date.now()+'_'+crypto.randomUUID().slice(0,8);
18 +const q=value=>"'"+String(value).replaceAll("'","''")+"'";
19 +function sql(statement,scalar=false){
20 + const args=[db,'-X','-v','ON_ERROR_STOP=1'];
21 + if(scalar)args.push('-At');
22 + args.push('-c',statement);
23 + const result=spawnSync('psql',args,{encoding:'utf8'});
24 + assert.equal(result.status,0,'disposable fixture SQL failed; check local-stack logs');
25 + return (result.stdout||'').trim();
26 +}
27 +function rec(org,owner,collection,id,data){
28 + return '('+[q(org),q(owner),q(collection),q(id),q(JSON.stringify(data))+'::jsonb'].join(',')+')';
29 +}
30 +async function addUser(label){
31 + const email='finora-issue229-'+label+'-'+suffix+'@example.test';
32 + const password='QA-'+crypto.randomUUID()+'-Aa9!';
33 + const response=await fetch(api+'/auth/v1/admin/users',{
34 + method:'POST',
35 + headers:{apikey:service,Authorization:'Bearer '+service,'Content-Type':'application/json'},
36 + body:JSON.stringify({email,password,email_confirm:true,user_metadata:{username:'qa229'+label+Date.now()}})
37 + });
38 + const user=await response.json();
39 + assert.equal(response.status,200,'disposable Auth setup failed for '+label);
40 + assert.ok(user.id,'new Auth user missing ID');
41 + return {id:user.id,email,password};
42 +}
43 +async function login(user){
44 + const response=await fetch(api+'/auth/v1/token?grant_type=password',{
45 + method:'POST',headers:{apikey:anon,'Content-Type':'application/json'},
46 + body:JSON.stringify({email:user.email,password:user.password})
47 + });
48 + const body=await response.json();
49 + assert.equal(response.status,200,'Auth user login failed');
50 + assert.equal(body.user?.id,user.id,'JWT identity mismatch');
51 + assert.ok(body.access_token,'Auth access token missing');
52 + return body.access_token;
53 +}
54 +async function rpc(name,args,jwt){
55 + const response=await fetch(api+'/rest/v1/rpc/'+name,{
56 + method:'POST',headers:{apikey:anon,Authorization:'Bearer '+jwt,'Content-Type':'application/json'},
57 + body:JSON.stringify(args)
58 + });
59 + const raw=await response.text();
60 + let body;
61 + try{body=JSON.parse(raw)}catch{body=raw}
62 + return {status:response.status,body};
63 +}
64 +const owner=await addUser('owner'),seller=await addUser('seller');
65 +const org=crypto.randomUUID(),co='QA229_CO_'+suffix,fy='QA229_FY_'+suffix;
66 +const cash='QA229_CASH_'+suffix,revenue='QA229_REV_'+suffix;
67 +const sourceId='QA229_SALE_'+suffix,voucherId='QA229_JV_'+suffix;
68 +sql('INSERT INTO public.organizations(id,owner_user_id,name) VALUES ('+
69 + q(org)+','+q(owner.id)+','+q('QA229 disposable organization')+');');
70 +sql('UPDATE public.licenses SET organization_id='+q(org)+
71 + ",plan='lifetime',status='active',ends_at=date '2099-01-01',modules=array['full_suite']::text[] WHERE user_id="+q(owner.id)+';');
72 +sql('INSERT INTO public.organization_members(organization_id,user_id,status,is_owner) VALUES ('+
73 + q(org)+','+q(owner.id)+",'active',true),("+q(org)+','+q(seller.id)+",'active',false);");
74 +sql('INSERT INTO public.member_module_permissions(organization_id,member_id,module_key,capabilities,scope_type) '+
75 + 'SELECT '+q(org)+",id,'commerce',array['read','create']::text[],'organization' "+
76 + 'FROM public.organization_members WHERE organization_id='+q(org)+' AND user_id='+q(seller.id)+';');
77 +const records=[
78 + rec(org,owner.id,'companies',co,{name:'QA229 disposable company'}),
79 + rec(org,owner.id,'fiscalYears',fy,{companyId:co,startDate:'1405/01/01',endDate:'1405/12/29',status:'open'}),
80 + rec(org,owner.id,'accounts',cash,{companyId:co,systemRole:'cash_default',accountType:'asset',
81 + normalBalance:'debit',level:'detail',postingAllowed:true,active:true,code:'1101',name:'QA229 cash'}),
82 + rec(org,owner.id,'accounts',revenue,{companyId:co,systemRole:'revenue_default',accountType:'revenue',
83 + normalBalance:'credit',level:'detail',postingAllowed:true,active:true,code:'4101',name:'QA229 revenue'})
84 +];
85 +sql('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+records.join(',')+';');
86 +sql('INSERT INTO private.finora_phase1a_account_role_snapshots ('+
87 + 'organization_id,company_id,version,assignments,account_fields,approved,approved_by,reason) '+
88 + 'SELECT '+q(org)+','+q(co)+",1,jsonb_build_object('cash_default',"+q(cash)+
89 + ",'revenue_default',"+q(revenue)+"),jsonb_build_object('cash_default',"+
90 + 'private.finora_phase1a_account_fields(c.data),'+
91 + "'revenue_default',private.finora_phase1a_account_fields(r.data)),true,"+q(owner.id)+
92 + ",'Issue229 disposable snapshot' FROM public.records c JOIN public.records r ON "+
93 + 'r.organization_id=c.organization_id AND r.collection='+q('accounts')+
94 + ' AND r.id='+q(revenue)+' WHERE c.organization_id='+q(org)+
95 + ' AND c.collection='+q('accounts')+' AND c.id='+q(cash)+';');
96 +const data={companyId:co,date:'1405/01/01',kind:'formal',description:'QA229 restricted seller sale',
97 + reference:sourceId,accountingVersion:1,accountingStatus:'draft',documentStatus:'draft',
98 + paymentMethod:'cash',currencyCode:'IRR',items:[{prodId:'QA_PRODUCT',qty:1,price:125,lineTotal:125}],
99 + subtotal:125,discountType:'fixed',discountInput:0,discount:0,
100 + vatMode:'none',vatType:'percent',vatRate:0,vat:0,grandTotal:125};
101 +sql('INSERT INTO public.records(organization_id,owner_id,collection,id,data) VALUES '+
102 + rec(org,seller.id,'invoices',sourceId,data)+';');
103 +const noExtraRoles=sql('SELECT count(*) FROM public.organization_member_roles mr '+
104 + 'JOIN public.organization_members m ON m.id=mr.member_id WHERE m.organization_id='+
105 + q(org)+' AND m.user_id='+q(seller.id)+' AND mr.active;',true);
106 +assert.equal(noExtraRoles,'0','seller unexpectedly inherits an assigned reusable role');
107 +// Verify the REAL capability predicate with seller JWT subject as evaluated by auth.uid().
108 +// No application privilege is inferred merely from the synthetic grant row.
109 +const privilegeLog=sql('BEGIN; SELECT set_config('+q('request.jwt.claim.sub')+','+
110 + q(seller.id)+',true); SELECT '+
111 + "CASE WHEN private.has_org_capability("+q(org)+",'commerce','create') THEN 't' ELSE 'f' END || '|' || "+
112 + "CASE WHEN private.has_org_capability("+q(org)+",'accounting','approve') THEN 't' ELSE 'f' END; ROLLBACK;",true);
113 +assert.ok(privilegeLog.split(/\r?\n/).includes('t|f'),
114 + 'fixture does not have commerce:create without accounting:approve; NOT a product RED');
115 +const jwt=await login(seller);
116 +const args={p_organization_id:org,p_voucher_id:voucherId,
117 + p_source_collection:'invoices',p_source_id:sourceId,
118 + p_header:{companyId:co,fiscalYearId:fy,date:'1405/01/01',voucherType:'sale',
119 + sourceType:'sale',sourceId,sourceVersion:'1',description:'QA229 approval boundary'},
120 + p_lines:[]};
121 +const result=await rpc('finora_journal_autopost',args,jwt);
122 +// The existing code is known to bypass separate accounting approval.
123 +// A 403/42501 here is an UNEXPECTED PASS of the new authorization boundary;
124 +// review/update this expected-RED test to assert the complete fixed draft-first flow.
125 +if(result.status!==200){
126 + throw Error('Approval bypass NOT reproduced: JWT RPC status '+result.status+
127 + '; inspect whether product has been repaired or fixture/setup failed. Do NOT count as expected RED.');
128 +}
129 +assert.equal(result.body?.voucher?.status,'posted',
130 + 'existing code must have actually POSTED, otherwise no authorization-bypass evidence');
131 +assert.equal(result.body?.voucher?.id,voucherId,
132 + 'posted voucher identity mismatch; do not count a fake/partial response');
133 +const journal=sql("SELECT data->>'status' FROM public.records WHERE organization_id="+q(org)+
134 + " AND collection='journalVouchers' AND id="+q(voucherId)+';',true);
135 +const source=sql("SELECT data->>'documentStatus' || '|' || data->>'journalVoucherId' "+
136 + 'FROM public.records WHERE organization_id='+q(org)+" AND collection='invoices' AND id="+q(sourceId)+';',true);
137 +const lines=sql("SELECT count(*) || '|' || coalesce(sum((data->>'debit')::numeric),0) || '|' || "+
138 + "coalesce(sum((data->>'credit')::numeric),0) FROM public.records WHERE organization_id="+q(org)+
139 + " AND collection='journalLines' AND data->>'voucherId'="+q(voucherId)+';',true);
140 +const audit=sql('SELECT count(*) FROM private.finora_phase1a_journal_audit WHERE organization_id='+
141 + q(org)+' AND voucher_id='+q(voucherId)+' AND actor_id='+q(seller.id)+'::uuid;',true);
142 +const counter=sql('SELECT last_no FROM private.finora_phase1a_journal_counters WHERE organization_id='+
143 + q(org)+' AND fiscal_year_id='+q(fy)+';',true);
144 +assert.equal(journal,'posted','JWT returned posted but journal status is not persisted');
145 +assert.equal(source,'posted|'+voucherId,'source-to-posted linkage not persisted');
146 +assert.equal(lines,'2|125|125','unexpected ledger line count or imbalance');
147 +assert.ok(Number(audit)>=2,'Auth-user actor audit missing from persisted posting');
148 +assert.equal(counter,'1','unexpected posting counter state');
149 +console.log('FINORA_ISSUE229_APPROVAL_EXPECTED_RED: real non-owner commerce:create JWT without accounting:approve POSTED sale via legacy autopost; persisted source, voucher, balanced lines, actor audit and counter verified in disposable local Supabase. This is a CONFIRMED PRODUCT DEFECT, NOT a fix or authorization PASS.');