سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 4, 01:45 UTC
test: add real Supabase Auth tenant isolation e2e
davoodmehraban89 committed
Nov 17, 2026 at 08:57 UTC
7b579b539956008d4301255a62f216a77ab32224
1 file changed
+97
scripts/wp2-auth-tenant-e2e.mjs
new
+97
@@ -0,0 +1,97 @@
1
+import assert from 'node:assert/strict';
2
+import { spawnSync } from 'node:child_process';
3
+
4
+const api = process.env.API_URL;
5
+const anon = process.env.ANON_KEY;
6
+const service = process.env.SERVICE_ROLE_KEY;
7
+const db = process.env.DB_URL;
8
+for (const [name, value] of Object.entries({ API_URL: api, ANON_KEY: anon, SERVICE_ROLE_KEY: service, DB_URL: db })) {
9
+ if (!value) throw new Error(`Missing Supabase local environment value: ${name}`);
10
+}
11
+const suffix = `wp2-${Date.now()}`;
12
+const users = [];
13
+async function adminCreate(email) {
14
+ const response = await fetch(`${api}/auth/v1/admin/users`, {
15
+ method: 'POST',
16
+ headers: { apikey: service, Authorization: `Bearer ${service}`, 'Content-Type': 'application/json' },
17
+ body: JSON.stringify({ email, password: `T3st-${crypto.randomUUID()}-Aa9!`, email_confirm: true, user_metadata: { username: email.split('@')[0] } })
18
+ });
19
+ const body = await response.json();
20
+ assert.equal(response.status, 200, `admin create user failed: ${JSON.stringify(body)}`);
21
+ return body.id;
22
+}
23
+async function signIn(email, password) {
24
+ const response = await fetch(`${api}/auth/v1/token?grant_type=password`, {
25
+ method: 'POST', headers: { apikey: anon, 'Content-Type': 'application/json' },
26
+ body: JSON.stringify({ email, password })
27
+ });
28
+ const body = await response.json();
29
+ assert.equal(response.status, 200, `password sign-in failed: ${JSON.stringify(body)}`);
30
+ assert.ok(body.access_token && body.user?.id);
31
+ return body.access_token;
32
+}
33
+function sql(statement) {
34
+ const result = spawnSync('psql', [db, '-v', 'ON_ERROR_STOP=1', '-c', statement], { encoding: 'utf8' });
35
+ if (result.status !== 0) throw new Error(`psql failed: ${result.stderr || result.stdout}`);
36
+}
37
+async function rest(path, token, init = {}) {
38
+ return fetch(`${api}/rest/v1/${path}`, {
39
+ ...init,
40
+ headers: { apikey: anon, Authorization: `Bearer ${token}`, ...(init.headers || {}) }
41
+ });
42
+}
43
+try {
44
+ const emails = [`owner-a-${suffix}@example.test`, `owner-b-${suffix}@example.test`];
45
+ const passwords = [`T3st-A-${crypto.randomUUID()}-Aa9!`, `T3st-B-${crypto.randomUUID()}-Aa9!`];
46
+ for (let i = 0; i < 2; i++) {
47
+ const response = await fetch(`${api}/auth/v1/admin/users`, {
48
+ method: 'POST', headers: { apikey: service, Authorization: `Bearer ${service}`, 'Content-Type': 'application/json' },
49
+ body: JSON.stringify({ email: emails[i], password: passwords[i], email_confirm: true, user_metadata: { username: `w2${i}${Date.now()}` } })
50
+ });
51
+ const body = await response.json();
52
+ assert.equal(response.status, 200, `user provisioning failed: ${JSON.stringify(body)}`);
53
+ users.push(body.id);
54
+ }
55
+ const orgA = crypto.randomUUID(), orgB = crypto.randomUUID();
56
+ const q = (s) => `'${s.replaceAll("'", "''")}'`;
57
+ sql(`
58
+ insert into public.organizations(id,owner_user_id,name) values
59
+ (${q(orgA)},${q(users[0])},'WP2 tenant A ${suffix}'),
60
+ (${q(orgB)},${q(users[1])},'WP2 tenant B ${suffix}');
61
+ update public.licenses set organization_id=${q(orgA)} where user_id=${q(users[0])};
62
+ update public.licenses set organization_id=${q(orgB)} where user_id=${q(users[1])};
63
+ insert into public.organization_members(organization_id,user_id,status,is_owner)
64
+ values (${q(orgA)},${q(users[0])},'active',true),(${q(orgB)},${q(users[1])},'active',true);
65
+ `);
66
+ const tokens = [];
67
+ for (let i = 0; i < 2; i++) {
68
+ const response = await fetch(`${api}/auth/v1/token?grant_type=password`, {
69
+ method: 'POST', headers: { apikey: anon, 'Content-Type': 'application/json' },
70
+ body: JSON.stringify({ email: emails[i], password: passwords[i] })
71
+ });
72
+ const body = await response.json();
73
+ assert.equal(response.status, 200, `real Auth sign-in failed: ${JSON.stringify(body)}`);
74
+ assert.equal(body.user.id, users[i]);
75
+ tokens.push(body.access_token);
76
+ }
77
+ const visibleA = await rest('organizations?select=id,name&order=name', tokens[0]);
78
+ const visibleB = await rest('organizations?select=id,name&order=name', tokens[1]);
79
+ assert.equal(visibleA.status, 200); assert.equal(visibleB.status, 200);
80
+ const rowsA = await visibleA.json(), rowsB = await visibleB.json();
81
+ assert.ok(rowsA.some(x => x.id === orgA));
82
+ assert.ok(!rowsA.some(x => x.id === orgB), 'tenant A JWT leaked tenant B organization');
83
+ assert.ok(rowsB.some(x => x.id === orgB));
84
+ assert.ok(!rowsB.some(x => x.id === orgA), 'tenant B JWT leaked tenant A organization');
85
+ const membersA = await rest('organization_members?select=organization_id,user_id', tokens[0]);
86
+ const membersB = await rest('organization_members?select=organization_id,user_id', tokens[1]);
87
+ assert.equal(membersA.status, 200); assert.equal(membersB.status, 200);
88
+ const mA = await membersA.json(), mB = await membersB.json();
89
+ assert.ok(mA.every(x => x.organization_id === orgA), 'tenant A can read foreign membership');
90
+ assert.ok(mB.every(x => x.organization_id === orgB), 'tenant B can read foreign membership');
91
+ console.log('WP2_AUTH_TENANT_E2E_PASS: two Auth-issued JWTs; organization and membership RLS isolation verified through PostgREST.');
92
+} finally {
93
+ if (users.length) {
94
+ const ids = users.map(x => `'${x}'`).join(',');
95
+ sql(`delete from public.organizations where owner_user_id in (${ids}); delete from auth.users where id in (${ids});`);
96
+ }
97
+}