سامانه صدور فاکتور و حسابداری
test(wp3): create balanced tenant fixture with genuine owner JWT and verify foreign denials
davoodmehraban89 committed
Nov 24, 2026 at 10:14 UTC
eaa873c3c22d43d5c5a8e1c8e98ec46ff3c9abae
1 file changed
+46
-11
scripts/wp3-financial-tenant-e2e.mjs
+46
-11
@@ -2,6 +2,12 @@ import assert from 'node:assert/strict';
2
3
const api=process.env.API_URL,anon=process.env.ANON_KEY,service=process.env.SERVICE_ROLE_KEY,db=process.env.DB_URL;
4
for(const [k,v] of Object.entries({API_URL:api,ANON_KEY:anon,SERVICE_ROLE_KEY:service,DB_URL:db})) if(!v) throw new Error(`Missing ${k}`);
5
+// This integration fixture must never target hosted Supabase.
6
+for (const [value,protocols,port] of [[api,['http:'], '54321'],[db,['postgres:','postgresql:'],'54322']]) {
7
+ const u=new URL(value);
8
+ assert.ok(protocols.includes(u.protocol) && ['127.0.0.1','localhost','[::1]'].includes(u.hostname) && u.port===port,
9
+ 'WP3 refuses non-disposable local API/DB target');
10
+}
11
const suffix=`wp3-${Date.now()}`, users=[];
12
const q=s=>`'${String(s).replaceAll("'","''")}'`;
13
async function adminUser(email,password){
@@ -42,15 +48,40 @@ try{
48
`);
49
const [jwtA,jwtB]=await Promise.all([token(emailA,passA),token(emailB,passB)]);
50
const voucherId=`wp3-voucher-${suffix}`,companyId=`wp3-company-${suffix}`,fyId=`wp3-fy-${suffix}`;
45
- const data={companyId,fiscalYearId:fyId,date:'1405/01/01',description:'WP3 isolated financial fixture',status:'draft',sourceType:'manual'};
51
+ const debitId=`wp3-debit-${suffix}`,creditId=`wp3-credit-${suffix}`;
52
+ const header={companyId,fiscalYearId:fyId,date:'1405/01/01',description:'WP3 isolated financial fixture',sourceType:'manual'};
53
+ const data={...header,status:'draft'};
54
+ const lines=[{accountId:debitId,debit:100,credit:0},{accountId:creditId,debit:0,credit:100}];
55
psql(`
56
insert into public.records(organization_id,owner_id,collection,id,data) values
57
(${q(orgA)},${q(userA)},'companies',${q(companyId)},'{"name":"WP3 fixture company"}'::jsonb),
58
(${q(orgA)},${q(userA)},'fiscalYears',${q(fyId)},'{"companyId":"${companyId}","startDate":"1405/01/01","endDate":"1405/12/29","status":"open"}'::jsonb),
50
- (${q(orgA)},${q(userA)},'journalVouchers',${q(voucherId)},${q(JSON.stringify(data))}::jsonb);
59
+ (${q(orgA)},${q(userA)},'accounts',${q(debitId)},${q(JSON.stringify({companyId,code:'WP3D',name:'WP3 debit',postingAllowed:true,active:true}))}::jsonb),
60
+ (${q(orgA)},${q(userA)},'accounts',${q(creditId)},${q(JSON.stringify({companyId,code:'WP3C',name:'WP3 credit',postingAllowed:true,active:true}))}::jsonb);
61
`);
52
- const own=await rest(`records?select=id,organization_id,data,version&collection=eq.journalVouchers&id=eq.${encodeURIComponent(voucherId)}`,jwtA);
53
- assert.equal(own.status,200);const ownRows=await own.json();assert.equal(ownRows.length,1,'tenant A must read its seeded voucher');
62
+ // Do not seed a journal through unauthed SQL: lifecycle allocation requires
63
+ // the real authenticated actor, even on a disposable DB.
64
+ const created=await rpc('finora_journal_create_draft',{p_organization_id:orgA,p_voucher_id:voucherId,p_header:header,p_lines:lines},jwtA);
65
+ assert.equal(created.status,200,`WP3 authorized create draft: HTTP ${created.status}: ${created.body}`);
66
+ const ownPath=`records?select=id,organization_id,owner_id,data,version&organization_id=eq.${orgA}&collection=eq.journalVouchers&id=eq.${encodeURIComponent(voucherId)}`;
67
+ const linesPath=`records?select=id,organization_id,owner_id,data,version&organization_id=eq.${orgA}&collection=eq.journalLines&data->>voucherId=eq.${encodeURIComponent(voucherId)}&order=id.asc`;
68
+ async function snapshot(path,t){const r=await rest(path,t);assert.equal(r.status,200,'WP3 snapshot HTTP status');return r.json();}
69
+ const ownRows=await snapshot(ownPath,jwtA);
70
+ assert.equal(ownRows.length,1,'tenant A must read the authenticated draft');
71
+ const own=ownRows[0];
72
+ assert.equal(own.id,voucherId);assert.equal(own.organization_id,orgA);assert.equal(own.owner_id,userA);
73
+ for(const [k,v] of Object.entries(data)) assert.equal(own.data[k],v,`draft ${k}`);
74
+ assert.equal(own.data.createdBy,userA,'draft must record authenticated creator');
75
+ const version=Number(own.version);assert.ok(Number.isSafeInteger(version)&&version>0,'persisted positive version required');
76
+ const ownLines=await snapshot(linesPath,jwtA);assert.equal(ownLines.length,2);
77
+ for(const expected of lines){
78
+ const matches=ownLines.filter(row=>row.data.accountId===expected.accountId);
79
+ assert.equal(matches.length,1,'each expected account appears exactly once');
80
+ const row=matches[0];assert.equal(row.organization_id,orgA);assert.equal(row.owner_id,userA);
81
+ assert.equal(row.data.voucherId,voucherId);assert.equal(row.data.companyId,companyId);
82
+ assert.equal(row.data.debit,expected.debit);assert.equal(row.data.credit,expected.credit);
83
+ }
84
+ console.log('WP3_AUTHENTICATED_DRAFT_FIXTURE_PASS: signed owner JWT created balanced draft and owner readback confirmed voucher, actor, version and two lines');
85
const foreign=await rest(`records?select=id,organization_id,data&collection=eq.journalVouchers&id=eq.${encodeURIComponent(voucherId)}`,jwtB);
86
assert.equal(foreign.status,200);assert.equal((await foreign.json()).length,0,'tenant B read another tenant journal voucher');
87
const insertForeign=await rest('records?select=id',jwtB,{method:'POST',headers:{'Content-Type':'application/json',Prefer:'return=representation'},body:JSON.stringify({organization_id:orgA,owner_id:userB,collection:'journalVouchers',id:`wp3-injected-${suffix}`,data})});
@@ -63,14 +94,18 @@ try{
94
assert.equal((await deleteForeign.json().catch(()=>[])).length,0,'cross-tenant delete returned deleted rows');
95
const after=await rest(`records?select=id,data&collection=eq.journalVouchers&id=eq.${encodeURIComponent(voucherId)}`,jwtA);
96
assert.equal(after.status,200);const afterRows=await after.json();assert.equal(afterRows.length,1);assert.equal(afterRows[0].data.description,data.description,'tenant B changed or deleted tenant A voucher');
66
- const orgArgs={p_organization_id:orgA,p_voucher_id:`wp3-rpc-${suffix}`,p_header:{companyId,fiscalYearId:fyId,date:'1405/01/01',description:'forbidden',sourceType:'manual'},p_lines:[]};
97
+ const orgArgs={p_organization_id:orgA,p_voucher_id:`wp3-rpc-${suffix}`,p_header:{...header,description:'forbidden'},p_lines:lines};
98
expectDenied(await rpc('finora_journal_create_draft',orgArgs,jwtB),'create draft RPC');
68
- expectDenied(await rpc('finora_journal_update_draft',{p_organization_id:orgA,p_voucher_id:voucherId,p_expected_version:1,p_header:{description:'tamper'},p_lines:[]},jwtB),'update draft RPC');
69
- expectDenied(await rpc('finora_journal_delete_draft',{p_organization_id:orgA,p_voucher_id:voucherId,p_expected_version:1},jwtB),'delete draft RPC');
70
- expectDenied(await rpc('finora_journal_post',{p_organization_id:orgA,p_voucher_id:voucherId,p_expected_version:1},jwtB),'post RPC');
71
- expectDenied(await rpc('finora_journal_reverse',{p_organization_id:orgA,p_original_id:voucherId,p_reversal_id:`wp3-reversal-${suffix}`,p_date:'1405/01/02',p_reason:'unauthorized cross-tenant reversal',p_expected_version:1,p_allocations:null},jwtB),'reverse RPC');
72
- const finalA=await rest(`records?select=id,data&collection=eq.journalVouchers&id=eq.${encodeURIComponent(voucherId)}`,jwtA);
73
- assert.equal((await finalA.json()).length,1,'source voucher missing after forbidden RPC attempts');
99
+ expectDenied(await rpc('finora_journal_update_draft',{p_organization_id:orgA,p_voucher_id:voucherId,p_expected_version:version,p_header:{description:'tamper'},p_lines:lines},jwtB),'update draft RPC');
100
+ expectDenied(await rpc('finora_journal_delete_draft',{p_organization_id:orgA,p_voucher_id:voucherId,p_expected_version:version},jwtB),'delete draft RPC');
101
+ expectDenied(await rpc('finora_journal_post',{p_organization_id:orgA,p_voucher_id:voucherId,p_expected_version:version},jwtB),'post RPC');
102
+ expectDenied(await rpc('finora_journal_reverse',{p_organization_id:orgA,p_original_id:voucherId,p_reversal_id:`wp3-reversal-${suffix}`,p_date:'1405/01/02',p_reason:'unauthorized cross-tenant reversal',p_expected_version:version,p_allocations:null},jwtB),'reverse RPC');
103
+ assert.deepEqual(await snapshot(ownPath,jwtA),ownRows,'foreign operations changed original voucher');
104
+ assert.deepEqual(await snapshot(linesPath,jwtA),ownLines,'foreign operations changed original lines');
105
+ for (const id of [`wp3-injected-${suffix}`,orgArgs.p_voucher_id,`wp3-reversal-${suffix}`]){
106
+ const rows=await snapshot(`records?select=id&organization_id=eq.${orgA}&collection=eq.journalVouchers&id=eq.${encodeURIComponent(id)}`,jwtA);
107
+ assert.equal(rows.length,0,'foreign attempt created a voucher');
108
+ }
109
console.log('WP3_FINANCIAL_TENANT_ISOLATION_PASS: cross-tenant journal read/insert/update/delete and create/update/delete/post/reverse RPC attempts denied; tenant A fixture unchanged.');
110
}finally{
111
console.log(`WP3 disposable fixtures: ${users.length} auth users; entire local Supabase stack is destroyed by workflow teardown.`);