سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 08:00 UTC
test(finora): real-JWT approval bypass probe for posted inventory insert
davoodmehraban89 committed
Nov 23, 2026 at 18:27 UTC
c6921e83c9f7fb883d88f0039290a890451f6c1d
1 file changed
+130
scripts/wp2-phase5-posted-insert-approval-jwt-e2e.mjs
new
+130
@@ -0,0 +1,130 @@
1
+import assert from 'node:assert/strict';
2
+import {spawnSync} from 'node:child_process';
3
+
4
+// Issue238 / Phase5 source-status authorization hypothesis.
5
+// This is ONLY a disposable Supabase stack / real Auth JWT test, never Production.
6
+// An expected-product-RED marker reports a real persisted bypass, NOT a fix.
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 [k,v] of Object.entries({API_URL:api,ANON_KEY:anon,SERVICE_ROLE_KEY:service,DB_URL:db}))
10
+ assert.ok(v,'missing disposable local WP2 environment '+k);
11
+for(const [label,url] of [['API_URL',api],['DB_URL',db]]){
12
+ const host=new URL(url).hostname.toLowerCase();
13
+ assert.ok(['localhost','127.0.0.1','::1','[::1]'].includes(host),
14
+ 'FINORA_PHASE5_NONLOCAL_BLOCK: refusing '+label+' endpoint');
15
+}
16
+const suffix=Date.now()+'-'+crypto.randomUUID().slice(0,8);
17
+const q=x=>"'"+String(x).replaceAll("'","''")+"'";
18
+function sql(statement){
19
+ const result=spawnSync('psql',[db,'-X','-v','ON_ERROR_STOP=1','-c',statement],{encoding:'utf8'});
20
+ assert.equal(result.status,0,'local fixture SQL failed: '+(result.stderr||result.stdout).slice(-850));
21
+}
22
+async function createUser(label){
23
+ const email='finora-phase5-post-'+label+'-'+suffix+'@example.test';
24
+ const password='QA-'+crypto.randomUUID()+'-Aa9!';
25
+ const response=await fetch(api+'/auth/v1/admin/users',{
26
+ method:'POST',headers:{apikey:service,Authorization:'Bearer '+service,'Content-Type':'application/json'},
27
+ body:JSON.stringify({email,password,email_confirm:true,user_metadata:{username:'q5p'+label+Date.now()}})
28
+ });
29
+ const body=await response.json();
30
+ assert.equal(response.status,200,'local Auth user fixture failed: '+label);
31
+ assert.ok(body.id,'missing actual Auth user ID');
32
+ return {id:body.id,email,password};
33
+}
34
+async function jwt(user){
35
+ const response=await fetch(api+'/auth/v1/token?grant_type=password',{
36
+ method:'POST',headers:{apikey:anon,'Content-Type':'application/json'},
37
+ body:JSON.stringify({email:user.email,password:user.password})
38
+ });
39
+ const body=await response.json();
40
+ assert.equal(response.status,200,'real Auth JWT login failed');
41
+ assert.equal(body.user?.id,user.id,'JWT user identity mismatch');
42
+ assert.ok(body.access_token,'Auth JWT missing');
43
+ return body.access_token;
44
+}
45
+async function rest(path,token,init={}){
46
+ return fetch(api+'/rest/v1/'+path,{
47
+ ...init,headers:{apikey:anon,Authorization:'Bearer '+token,...(init.headers||{})}
48
+ });
49
+}
50
+function rec(org,owner,collection,id,data){
51
+ return '('+[q(org),q(owner),q(collection),q(id),q(JSON.stringify(data))+'::jsonb'].join(',')+')';
52
+}
53
+async function getOwnerRow(org,collection,id,token){
54
+ const r=await rest('records?select=organization_id,collection,id,data&organization_id=eq.'+
55
+ encodeURIComponent(org)+'&collection=eq.'+encodeURIComponent(collection)+
56
+ '&id=eq.'+encodeURIComponent(id),token);
57
+ assert.equal(r.status,200,'genuine owner readback HTTP must be 200');
58
+ return r.json();
59
+}
60
+let usersCreated=0;
61
+try{
62
+ const [owner,creator]=await Promise.all([createUser('owner'),createUser('creator')]);
63
+ usersCreated=2;
64
+ const org=crypto.randomUUID(),member=crypto.randomUUID();
65
+ const company='QA5_COMPANY_'+suffix,warehouse='QA5_WAREHOUSE_'+suffix,product='QA5_PRODUCT_'+suffix;
66
+ // The fixture retains the real max_users seat trigger and company quota.
67
+ sql('insert into public.organizations(id,owner_user_id,name) values ('+
68
+ q(org)+','+q(owner.id)+','+q('QA5 approved test organization')+');'+
69
+ 'update public.licenses set organization_id='+q(org)+',max_users=2 where user_id='+q(owner.id)+';'+
70
+ 'insert into public.organization_members(organization_id,user_id,status,is_owner) values ('+
71
+ q(org)+','+q(owner.id)+','+q('active')+',true);'+
72
+ 'insert into public.organization_members(id,organization_id,user_id,status,is_owner) values ('+
73
+ q(member)+','+q(org)+','+q(creator.id)+','+q('active')+',false);'+
74
+ 'insert into public.member_module_permissions(organization_id,member_id,module_key,capabilities,scope_type,scope_id,confidentiality_level) values ('+
75
+ q(org)+','+q(member)+','+q('inventory')+",array['create']::text[],"+
76
+ q('company')+','+q(company)+',0);');
77
+ sql('insert into public.records(organization_id,owner_id,collection,id,data) values '+
78
+ [
79
+ rec(org,owner.id,'companies',company,{name:'QA5 local company'}),
80
+ rec(org,owner.id,'warehouses',warehouse,{companyId:company,code:'QA5W',name:'Local warehouse'}),
81
+ rec(org,owner.id,'products',product,{companyId:company,code:'QA5P',name:'Local product'})
82
+ ].join(',')+';');
83
+ const [ownerJwt,creatorJwt]=await Promise.all([jwt(owner),jwt(creator)]);
84
+ const cases=[
85
+ {collection:'stockMovements',id:'QA5_POSTED_MOV_'+suffix,data:{
86
+ ownerUserId:creator.id,companyId:company,warehouseId:warehouse,
87
+ productId:product,kind:'adjustment_in',qty:5,unitCost:50,
88
+ date:'1405/08/01',status:'posted',postedAt:'2026-11-23T00:00:00.000Z'
89
+ }},
90
+ {collection:'inventoryCounts',id:'QA5_POSTED_COUNT_'+suffix,data:{
91
+ ownerUserId:creator.id,companyId:company,warehouseId:warehouse,
92
+ productId:product,expectedQty:5,actualQty:8,diff:3,
93
+ date:'1405/08/01',status:'posted',postedAt:'2026-11-23T00:00:00.000Z'
94
+ }}
95
+ ];
96
+ const observations=[];
97
+ for(const item of cases){
98
+ assert.equal((await getOwnerRow(org,item.collection,item.id,ownerJwt)).length,0,
99
+ 'posted source ID must be absent before user attempt');
100
+ // IMPORTANT: the *caller* is real non-owner user with inventory:create ONLY,
101
+ // and no inventory:approve. Service-role and psql do not perform the attempt.
102
+ const response=await rest('records',creatorJwt,{
103
+ method:'POST',headers:{'Content-Type':'application/json',Prefer:'return=minimal'},
104
+ body:JSON.stringify({organization_id:org,owner_id:creator.id,
105
+ collection:item.collection,id:item.id,data:item.data})
106
+ });
107
+ const after=await getOwnerRow(org,item.collection,item.id,ownerJwt);
108
+ const fixed=[401,403].includes(response.status)&&after.length===0;
109
+ const broken=[201,204].includes(response.status)&&after.length===1
110
+ &&after[0].organization_id===org&&after[0].collection===item.collection
111
+ &&after[0].id===item.id&&JSON.stringify(after[0].data)===JSON.stringify(item.data);
112
+ assert.ok(fixed||broken,
113
+ 'FINORA_PHASE5_POSTED_INSERT_THIRD_STATE: '+item.collection+
114
+ ' direct POST HTTP '+response.status+' owner readback '+JSON.stringify(after));
115
+ observations.push({collection:item.collection,status:response.status,
116
+ result:fixed?'properly_denied':'posted_without_approval'});
117
+ }
118
+ const allDenied=observations.every(x=>x.result==='properly_denied');
119
+ const allBroken=observations.every(x=>x.result==='posted_without_approval');
120
+ assert.ok(allDenied||allBroken,
121
+ 'FINORA_PHASE5_POSTED_INSERT_PARTIAL_THIRD_STATE: '+JSON.stringify(observations));
122
+ if(allBroken){
123
+ console.log('FINORA_PHASE5_POSTED_INSERT_WITHOUT_APPROVE_EXPECTED_RED: real Auth JWT member with inventory:create (company scoped) and no inventory:approve directly created POSTED stockMovements AND inventoryCounts through PostgREST. Owner readback confirms both exact persisted posted records; PRODUCT SECURITY/LIFECYCLE DEFECT, NOT A FIX.');
124
+ }else{
125
+ console.log('FINORA_PHASE5_POSTED_INSERT_APPROVAL_PASS: non-owner inventory:create without inventory:approve denied direct posted source INSERT for both stockMovements and inventoryCounts, no persisted rows.');
126
+ }
127
+ console.log('FINORA_PHASE5_POSTED_INSERT_JWT_EVIDENCE: '+JSON.stringify(observations));
128
+}finally{
129
+ console.log('FINORA_PHASE5_POSTED_INSERT_DISPOSABLE: '+usersCreated+' temporary Auth users; local WP2 teardown owns this database.');
130
+}