@davoodmehraban89 / Factor-easy-2 Mirror · read-only / commits / 251e669
Fork 0

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

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

Synced Dec 4, 14:15 UTC

test(finora): verify company-scoped inventory RLS with real restricted member JWT

davoodmehraban89 committed Nov 23, 2026 at 16:32 UTC 251e66948ebbc2b5d39d54508476df5bfed66c03
1 file changed +52 -16
scripts/wp2-stock-tenant-jwt-e2e.mjs
+52 -16
@@ -2,8 +2,8 @@ import assert from 'node:assert/strict';
2 import {spawnSync} from 'node:child_process';
3
4 // Issue223: real Auth-issued JWT / PostgREST against disposable local WP2 ONLY.
5 -// This proves organization RLS and posted source immutability, NOT the active-
6 -// company read model, stock posting approval, valuation, or live-host security.
5 +// Proves organization/company row scopes and posted-source immutability;
6 +// NOT the active-company UI read model, stock approval, valuation, or live-host security.
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,value] of Object.entries({API_URL:api,ANON_KEY:anon,SERVICE_ROLE_KEY:service,DB_URL:db}))
@@ -88,14 +88,14 @@ async function attemptOwnPostedMutation(collection,id,jwt,oldData){
88 }
89 const users=[];
90 try{
91 - const [a,b]=await Promise.all([createUser('a'),createUser('b')]);
92 - users.push(a,b);
93 - const orgA=crypto.randomUUID(),orgB=crypto.randomUUID();
91 + const [a,b,c]=await Promise.all([createUser('a'),createUser('b'),createUser('c')]);
92 + users.push(a,b,c);
93 + const orgA=crypto.randomUUID(),orgB=crypto.randomUUID(),memberA=crypto.randomUUID();
94 const ca1='QA223_CO_A1_'+suffix,ca2='QA223_CO_A2_'+suffix,cb='QA223_CO_B_'+suffix;
95 const whA1='QA223_WH_A1_'+suffix,whA2='QA223_WH_A2_'+suffix,whB='QA223_WH_B_'+suffix;
96 const product='QA223_PRODUCT_'+suffix;
97 const movementA1='QA223_MOV_A1_'+suffix,movementA2='QA223_MOV_A2_'+suffix;
98 - const movementB='QA223_MOV_B_'+suffix,countA='QA223_COUNT_A_'+suffix,countB='QA223_COUNT_B_'+suffix;
98 + const movementB='QA223_MOV_B_'+suffix,countA='QA223_COUNT_A_'+suffix,countA2='QA223_COUNT_A2_'+suffix,countB='QA223_COUNT_B_'+suffix;
99 const movementData=(uid,companyId,warehouseId,qty)=>({
100 ownerUserId:uid,companyId,warehouseId,productId:product,qty,unitCost:50,
101 kind:'adjustment_in',status:'posted',date:'1405/07/21',
@@ -108,15 +108,21 @@ try{
108 });
109 const mvA1=movementData(a.id,ca1,whA1,5),mvA2=movementData(a.id,ca2,whA2,3);
110 const mvB=movementData(b.id,cb,whB,7);
111 - const coA=countData(a.id,ca1,whA1,5),coB=countData(b.id,cb,whB,7);
111 + const coA=countData(a.id,ca1,whA1,5),coA2=countData(a.id,ca2,whA2,3),coB=countData(b.id,cb,whB,7);
112 sql('insert into public.organizations(id,owner_user_id,name) values '+
113 '('+quote(orgA)+','+quote(a.id)+','+quote('QA223 org A')+'),'+
114 '('+quote(orgB)+','+quote(b.id)+','+quote('QA223 org B')+');'+
115 - 'update public.licenses set organization_id='+quote(orgA)+',max_companies=2 where user_id='+quote(a.id)+';'+
115 + 'update public.licenses set organization_id='+quote(orgA)+',max_companies=2,max_users=2 where user_id='+quote(a.id)+';'+
116 'update public.licenses set organization_id='+quote(orgB)+' where user_id='+quote(b.id)+';'+
117 'insert into public.organization_members(organization_id,user_id,status,is_owner) values '+
118 '('+quote(orgA)+','+quote(a.id)+','+quote('active')+',true),'+
119 '('+quote(orgB)+','+quote(b.id)+','+quote('active')+',true);');
120 + // A real non-owner member receives only inventory:read for company A1.
121 + // The disposable organization license permits exactly owner A + member C.
122 + sql('insert into public.organization_members(id,organization_id,user_id,status,is_owner) values ('+
123 + quote(memberA)+','+quote(orgA)+','+quote(c.id)+','+quote('active')+',false);');
124 + sql('insert into public.member_module_permissions(organization_id,member_id,module_key,capabilities,scope_type,scope_id,confidentiality_level) values ('+
125 + quote(orgA)+','+quote(memberA)+','+quote('inventory')+",array['read']::text[],"+quote('company')+','+quote(ca1)+',0);");
126 // The disposable fixture needs A's two companies: default license capacity is 1.
127 // Raise only A's local test license to 2, without bypassing its DB trigger.
128 const seed=[
@@ -132,14 +138,15 @@ try{
138 [orgA,a.id,'stockMovements',movementA2,mvA2],
139 [orgB,b.id,'stockMovements',movementB,mvB],
140 [orgA,a.id,'inventoryCounts',countA,coA],
141 + [orgA,a.id,'inventoryCounts',countA2,coA2],
142 [orgB,b.id,'inventoryCounts',countB,coB]
143 ];
144 sql('insert into public.records(organization_id,owner_id,collection,id,data) values '+
145 seed.map(row=>record(...row)).join(',')+';');
139 - const [jwtA,jwtB]=await Promise.all([login(a),login(b)]);
140 - for(const [collection,aid,bid,oldData] of [
141 - ['stockMovements',movementA1,movementB,mvA1],
142 - ['inventoryCounts',countA,countB,coA]
146 + const [jwtA,jwtB,jwtC]=await Promise.all([login(a),login(b),login(c)]);
147 + for(const [collection,aid,a2id,bid,oldData,oldData2] of [
148 + ['stockMovements',movementA1,movementA2,movementB,mvA1,mvA2],
149 + ['inventoryCounts',countA,countA2,countB,coA,coA2]
150 ]){
151 const own=await rows(collection,aid,jwtA);
152 assert.equal(own.length,1,'A JWT cannot see own '+collection);
@@ -150,6 +157,13 @@ try{
157 'B JWT cannot see own '+collection);
158 assert.deepEqual(await rows(collection,bid,jwtA),[],
159 'FINORA_ISSUE223_CROSS_ORG_READ_BYPASS: A JWT read B '+collection);
160 + const scopedA1=await rows(collection,aid,jwtC);
161 + assert.equal(scopedA1.length,1,'company-scoped C cannot read A1 '+collection);
162 + assert.deepEqual(scopedA1[0].data,oldData,'C read unexpected A1 '+collection+' data');
163 + assert.deepEqual(await rows(collection,a2id,jwtC),[],
164 + 'FINORA_ISSUE223_COMPANY_SCOPE_BYPASS: C read same-org company A2 '+collection);
165 + assert.deepEqual(await rows(collection,bid,jwtC),[],
166 + 'FINORA_ISSUE223_COMPANY_SCOPE_CROSS_ORG_BYPASS: C read foreign org '+collection);
167 const injected=await rest('records?select=id',jwtB,{
168 method:'POST',headers:{'Content-Type':'application/json',Prefer:'return=representation'},
169 body:JSON.stringify({organization_id:orgA,owner_id:b.id,collection,
@@ -159,18 +173,34 @@ try{
173 'FINORA_ISSUE223_FOREIGN_INSERT_ALLOWED: '+collection+' HTTP '+injected.status);
174 await attemptForeignPatch(collection,aid,orgA,jwtB);
175 await attemptForeignDelete(collection,aid,orgA,jwtB);
176 + await attemptForeignPatch(collection,aid,orgA,jwtC);
177 + await attemptForeignDelete(collection,aid,orgA,jwtC);
178 + await attemptForeignPatch(collection,a2id,orgA,jwtC);
179 + await attemptForeignDelete(collection,a2id,orgA,jwtC);
180 assert.deepEqual((await rows(collection,aid,jwtA))[0].data,oldData,
181 'foreign JWT changed or removed posted '+collection);
182 await attemptOwnPostedMutation(collection,aid,jwtA,oldData);
183 assert.deepEqual((await rows(collection,aid,jwtA))[0].data,oldData,
184 'FINORA_ISSUE223_POSTED_IMMUTABILITY_BYPASS: '+collection);
185 }
168 - // Current SQL tenant boundary is organization, not active-company. This is
169 - // EXPECTED for the legitimate same-owner A1/A2 accountant; client selection
170 - // and company-specific posting authorization are separate acceptance gates.
186 + const readOnlyCreateId='QA223_READONLY_CREATE_'+suffix;
187 + const readOnlyCreate=await rest('records?select=id',jwtC,{
188 + method:'POST',headers:{'Content-Type':'application/json',Prefer:'return=representation'},
189 + body:JSON.stringify({organization_id:orgA,owner_id:c.id,collection:'stockMovements',
190 + id:readOnlyCreateId,data:movementData(c.id,ca1,whA1,1)})
191 + });
192 + assert.ok([401,403].includes(readOnlyCreate.status),
193 + 'FINORA_ISSUE223_READONLY_CREATE_ALLOWED: inventory:read member HTTP '+readOnlyCreate.status);
194 + assert.deepEqual(await rows('stockMovements',readOnlyCreateId,jwtA),[],
195 + 'read-only inventory member created a stock movement');
196 + // Owners have organization-wide scope and legitimately see A1/A2. A delegated
197 + // member with company scope A1 sees A1 only; neither result is the UI selector.
198 + // Client active-company Kardex filtering remains a separate product acceptance gate.
199 const sameOrg=await rows('stockMovements',movementA2,jwtA);
200 assert.equal(sameOrg.length,1,'authorized same-org owner must see company A2');
201 assert.equal(sameOrg[0].data.companyId,ca2);
202 + assert.equal((await rows('inventoryCounts',countA2,jwtA)).length,1,
203 + 'organization owner must see company A2 inventory count');
204 assert.deepEqual(await rows('stockMovements',movementA2,jwtB),[],
205 'foreign organization can see A2 stock movement');
206 const crossOrg=await rest('records?select=id,data&collection=eq.stockMovements',jwtA);
@@ -178,9 +208,15 @@ try{
208 const orgRows=await crossOrg.json();
209 assert.deepEqual(orgRows.map(x=>x.id).sort(),[movementA1,movementA2].sort(),
210 'A JWT stock records must include authorized A1/A2 and exclude B');
211 + const scopedRows=await rest('records?select=id&collection=eq.stockMovements',jwtC);
212 + assert.equal(scopedRows.status,200);
213 + assert.deepEqual((await scopedRows.json()).map(x=>x.id),[movementA1],
214 + 'company-scoped inventory:read JWT must return only A1 rows');
215 console.log('WP2_PHASE5_STOCK_JWT_ISOLATION_PASS: Auth-issued JWT A/B read, forbidden cross-org insert/update/delete, readback unchanged for posted stockMovements/inventoryCounts; same-org A1/A2 visible by design.');
216 console.log('WP2_PHASE5_POSTED_IMMUTABILITY_PASS: posted stockMovements and inventoryCounts reject same-owner JWT data PATCH and DELETE; original rows intact.');
183 - console.log('WP2_PHASE5_ACTIVE_COMPANY_NOT_RLS_SCOPE: database JWT protects organizations; PR242 active-company Kardex/browser errors remain separate product P0.');
217 + console.log('WP2_PHASE5_COMPANY_SCOPE_JWT_PASS: real Auth-issued non-owner C with inventory:read scoped to company A1 reads A1 stock/count rows and cannot read same-org A2 or foreign-org B.');
218 + console.log('WP2_PHASE5_READ_ONLY_MEMBER_CAPABILITY_PASS: scoped inventory:read member cannot create, patch or delete stock/count records; source readback unchanged.');
219 + console.log('WP2_PHASE5_ACTIVE_COMPANY_NOT_RLS_SCOPE: owner A legitimately sees A1/A2; delegated company-scoped C sees A1 only. PR242 active-company Kardex/UI filter remains a separate product P0.');
220 }finally{
221 console.log('WP2_PHASE5_QA_DISPOSABLE: '+users.length+' temporary Auth fixture users; disposable local Supabase workflow handles teardown.');
222 }