|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [ADR-0123 D1 / D2 / D4] A walled session with NO active organization, at the |
| 5 | + * three install-local doors that seed or purge sample data. |
| 6 | + * |
| 7 | + * ## What was measured before this file |
| 8 | + * |
| 9 | + * On a posture-only (walled) boot, a signed-in admin whose session carried no |
| 10 | + * `activeOrganizationId`, though their user held a `sys_member` row: |
| 11 | + * |
| 12 | + * POST …/install-local -> 200, seeded {mode: "skipped", reason: "multi-tenant-no-active-org"} |
| 13 | + * POST …/install-local/:id/reseed-sample-data -> 400 RESEED_SKIPPED "Reseed did not run: multi-tenant-no-active-org" |
| 14 | + * POST …/install-local/:id/purge-sample-data -> 400 RESEED_SKIPPED |
| 15 | + * |
| 16 | + * and the resolver's "first membership" fallback read an object no package |
| 17 | + * defines, so it threw and was swallowed. ADR-0123 already rules on this state: |
| 18 | + * D1 makes it legal and named, so no subsystem guesses an organization for it; |
| 19 | + * D2 refuses a tenant-scoped write loudly, with the catalog's |
| 20 | + * `PERMISSION_DENIED` / 403; D4 says the refusal names the missing active |
| 21 | + * organization. |
| 22 | + * |
| 23 | + * ## What this file pins |
| 24 | + * |
| 25 | + * 1. walled, no active organization, the user a member of TWO organizations: |
| 26 | + * the install registers the package and reports `seeded {mode: "refused"}` |
| 27 | + * with the sentence in `reason`; the reseed and the purge answer the 403 |
| 28 | + * envelope; no seed run starts and no organization is guessed; |
| 29 | + * 2. walled, an active organization: all three doors act in it, as before; |
| 30 | + * 3. unwalled (`single`): the active-organization read is never consulted. |
| 31 | + * |
| 32 | + * The membership rows are served by the store on purpose: a resolver that |
| 33 | + * guessed from them (under either object name the platform has spelled) would |
| 34 | + * seed into one of the two organizations, and case 1 would go red. |
| 35 | + */ |
| 36 | + |
| 37 | +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; |
| 38 | +import { mkdtempSync, rmSync } from 'node:fs'; |
| 39 | +import { join } from 'node:path'; |
| 40 | +import { tmpdir } from 'node:os'; |
| 41 | + |
| 42 | +let loadCalls: any[] = []; |
| 43 | + |
| 44 | +vi.mock('@objectstack/runtime', () => ({ |
| 45 | + SeedLoaderService: class { |
| 46 | + async load(request: any) { |
| 47 | + loadCalls.push(request); |
| 48 | + return { summary: { totalInserted: 2, totalUpdated: 0, totalSkipped: 0 }, errors: [] }; |
| 49 | + } |
| 50 | + async buildDependencyGraph(objects: string[]) { |
| 51 | + return { insertOrder: objects, nodes: objects.map((object) => ({ object, dependsOn: [], references: [] })) }; |
| 52 | + } |
| 53 | + }, |
| 54 | + recordSeedOutcome: vi.fn(), |
| 55 | +})); |
| 56 | +// Only the seed-request parse is stubbed; every other export stays the real one, |
| 57 | +// because `@objectstack/core` reads `@objectstack/spec/data` values at module load. |
| 58 | +vi.mock('@objectstack/spec/data', async (importOriginal) => ({ |
| 59 | + ...(await importOriginal<typeof import('@objectstack/spec/data')>()), |
| 60 | + SeedLoaderRequestSchema: { parse: (x: any) => x }, |
| 61 | +})); |
| 62 | + |
| 63 | +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; |
| 64 | +import { INSTALLER_USER_ID, withInstallerGrants } from './install-local-principal.fixtures.js'; |
| 65 | +import { LocalManifestSource } from './local-manifest-source.js'; |
| 66 | + |
| 67 | +type Handler = (c: any) => Promise<any>; |
| 68 | + |
| 69 | +const BASE = '/api/v1/marketplace/install-local'; |
| 70 | +const MANIFEST = { |
| 71 | + id: 'app.test.noorg', |
| 72 | + version: '1.0.0', |
| 73 | + objects: [{ name: 'noorg_x', fields: { name: { type: 'text' } } }], |
| 74 | + data: [{ object: 'noorg_x', externalId: 'name', records: [{ name: 'a' }, { name: 'b' }] }], |
| 75 | +}; |
| 76 | + |
| 77 | +/** The installer is a member of two organizations; the store says so under both spellings. */ |
| 78 | +const MEMBERSHIPS = [ |
| 79 | + { id: 'mem_a', organization_id: 'org_a', user_id: INSTALLER_USER_ID, role: 'owner' }, |
| 80 | + { id: 'mem_b', organization_id: 'org_b', user_id: INSTALLER_USER_ID, role: 'owner' }, |
| 81 | +]; |
| 82 | + |
| 83 | +function makeC(body: unknown, manifestId?: string) { |
| 84 | + return { |
| 85 | + req: { |
| 86 | + url: `http://localhost:3000${BASE}`, |
| 87 | + raw: new Request('http://localhost:3000/x'), |
| 88 | + json: async () => body, |
| 89 | + param: (k: string) => (k === 'manifestId' ? manifestId : undefined), |
| 90 | + header: () => undefined, |
| 91 | + }, |
| 92 | + json: vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })), |
| 93 | + }; |
| 94 | +} |
| 95 | + |
| 96 | +let dir: string; |
| 97 | +beforeEach(() => { |
| 98 | + dir = mkdtempSync(join(tmpdir(), 'mil-noorg-')); |
| 99 | + loadCalls = []; |
| 100 | +}); |
| 101 | +afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); }); |
| 102 | + |
| 103 | +/** |
| 104 | + * Boot the real plugin. `posture` is the `tenancy` service's posture in force; |
| 105 | + * `activeOrg` what the session's `activeOrganizationId` says (absent: none). |
| 106 | + */ |
| 107 | +async function boot(opts: { posture: 'single' | 'isolated'; activeOrg?: string }) { |
| 108 | + const routes = new Map<string, Handler>(); |
| 109 | + const rawApp = { |
| 110 | + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), |
| 111 | + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), |
| 112 | + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), |
| 113 | + }; |
| 114 | + const reads: Array<{ object: string; query: any }> = []; |
| 115 | + const granted = withInstallerGrants({ |
| 116 | + syncSchemas: async () => undefined, |
| 117 | + find: async (object: string, query?: any) => { reads.push({ object, query }); return []; }, |
| 118 | + }); |
| 119 | + const objectql = { |
| 120 | + ...granted, |
| 121 | + find: async (object: string, query?: any) => { |
| 122 | + if (object === 'sys_member' || object === 'sys_organization_member') { |
| 123 | + reads.push({ object, query }); |
| 124 | + return MEMBERSHIPS.map((m) => ({ ...m })); |
| 125 | + } |
| 126 | + return granted.find(object, query); |
| 127 | + }, |
| 128 | + }; |
| 129 | + const register = vi.fn(); |
| 130 | + const services: Record<string, unknown> = { |
| 131 | + manifest: { register }, |
| 132 | + auth: { |
| 133 | + api: { |
| 134 | + getSession: async () => ({ |
| 135 | + user: { id: INSTALLER_USER_ID }, |
| 136 | + session: opts.activeOrg ? { activeOrganizationId: opts.activeOrg } : {}, |
| 137 | + }), |
| 138 | + }, |
| 139 | + }, |
| 140 | + objectql, |
| 141 | + metadata: {}, |
| 142 | + tenancy: { posture: opts.posture }, |
| 143 | + }; |
| 144 | + const hooks = new Map<string, any>(); |
| 145 | + const ctx = { |
| 146 | + hook: (e: string, h: any) => hooks.set(e, h), |
| 147 | + getService: (name: string) => { |
| 148 | + if (name === 'http-server') return { getRawApp: () => rawApp }; |
| 149 | + const svc = services[name]; |
| 150 | + if (svc === undefined) throw new Error(`no ${name}`); |
| 151 | + return svc; |
| 152 | + }, |
| 153 | + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, |
| 154 | + }; |
| 155 | + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); |
| 156 | + const resolveActiveOrgId = vi.spyOn(plugin as any, 'resolveActiveOrgId'); |
| 157 | + await plugin.start(ctx as any); |
| 158 | + await hooks.get('kernel:ready')?.(); |
| 159 | + return { |
| 160 | + register, |
| 161 | + reads, |
| 162 | + resolveActiveOrgId, |
| 163 | + install: () => routes.get(`POST ${BASE}`)!(makeC({ manifest: MANIFEST })), |
| 164 | + reseed: () => routes.get(`POST ${BASE}/:manifestId/reseed-sample-data`)!(makeC({}, MANIFEST.id)), |
| 165 | + purge: () => routes.get(`POST ${BASE}/:manifestId/purge-sample-data`)!(makeC({}, MANIFEST.id)), |
| 166 | + }; |
| 167 | +} |
| 168 | + |
| 169 | +const ledgerEntry = () => new LocalManifestSource(dir).read(MANIFEST.id).entry; |
| 170 | + |
| 171 | +describe('walled, no active organization — refused at every sample-data door, and no organization is guessed', () => { |
| 172 | + it('install: the package registers, and `seeded` reports the refusal instead of seeding', async () => { |
| 173 | + const m = await boot({ posture: 'isolated' }); |
| 174 | + const res = await m.install(); |
| 175 | + |
| 176 | + expect(res.status).toBe(200); |
| 177 | + expect(res.payload.success).toBe(true); |
| 178 | + expect(m.register).toHaveBeenCalled(); |
| 179 | + expect(ledgerEntry()?.manifestId).toBe(MANIFEST.id); |
| 180 | + expect(Object.keys(res.payload.data.seeded).sort()).toEqual(['mode', 'reason']); |
| 181 | + expect(res.payload.data.seeded.mode).toBe('refused'); |
| 182 | + expect(res.payload.data.seeded.reason).toContain('this session has no active organization'); |
| 183 | + expect(loadCalls).toHaveLength(0); |
| 184 | + expect(ledgerEntry()?.withSampleData).not.toBe(true); |
| 185 | + }); |
| 186 | + |
| 187 | + it('reseed: 403 PERMISSION_DENIED naming the missing active organization, and no seed run', async () => { |
| 188 | + const m = await boot({ posture: 'isolated' }); |
| 189 | + await m.install(); |
| 190 | + const res = await m.reseed(); |
| 191 | + |
| 192 | + expect(res.status).toBe(403); |
| 193 | + expect(res.payload.success).toBe(false); |
| 194 | + expect(res.payload.error.code).toBe('PERMISSION_DENIED'); |
| 195 | + expect(res.payload.error.message).toContain('this session has no active organization'); |
| 196 | + expect(loadCalls).toHaveLength(0); |
| 197 | + expect(ledgerEntry()?.withSampleData).not.toBe(true); |
| 198 | + }); |
| 199 | + |
| 200 | + it('purge: 403 PERMISSION_DENIED naming the missing active organization, and no seed object is read', async () => { |
| 201 | + const m = await boot({ posture: 'isolated' }); |
| 202 | + await m.install(); |
| 203 | + const res = await m.purge(); |
| 204 | + |
| 205 | + expect(res.status).toBe(403); |
| 206 | + expect(res.payload.success).toBe(false); |
| 207 | + expect(res.payload.error.code).toBe('PERMISSION_DENIED'); |
| 208 | + expect(res.payload.error.message).toContain('this session has no active organization'); |
| 209 | + expect(m.reads.filter((r) => r.object === 'noorg_x')).toEqual([]); |
| 210 | + expect(ledgerEntry()?.sampleDataPurged).toBeUndefined(); |
| 211 | + }); |
| 212 | +}); |
| 213 | + |
| 214 | +describe('walled, an active organization — all three doors act in it, as before', () => { |
| 215 | + it('install seeds inline into the active organization', async () => { |
| 216 | + const m = await boot({ posture: 'isolated', activeOrg: 'org_b' }); |
| 217 | + const res = await m.install(); |
| 218 | + |
| 219 | + expect(res.status).toBe(200); |
| 220 | + expect(res.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 2 }); |
| 221 | + expect(loadCalls).toHaveLength(1); |
| 222 | + expect(loadCalls[0].config.organizationId).toBe('org_b'); |
| 223 | + }); |
| 224 | + |
| 225 | + it('reseed seeds into the active organization', async () => { |
| 226 | + const m = await boot({ posture: 'isolated', activeOrg: 'org_b' }); |
| 227 | + await m.install(); |
| 228 | + const res = await m.reseed(); |
| 229 | + |
| 230 | + expect(res.status).toBe(200); |
| 231 | + expect(res.payload.data).toMatchObject({ inserted: 2, withSampleData: true }); |
| 232 | + expect(loadCalls).toHaveLength(2); |
| 233 | + expect(loadCalls[1].config.organizationId).toBe('org_b'); |
| 234 | + }); |
| 235 | + |
| 236 | + it('purge reads the seed object in the active organization only', async () => { |
| 237 | + const m = await boot({ posture: 'isolated', activeOrg: 'org_b' }); |
| 238 | + await m.install(); |
| 239 | + const res = await m.purge(); |
| 240 | + |
| 241 | + expect(res.status).toBe(200); |
| 242 | + expect(res.payload.success).toBe(true); |
| 243 | + const seedReads = m.reads.filter((r) => r.object === 'noorg_x'); |
| 244 | + expect(seedReads).toHaveLength(1); |
| 245 | + expect(seedReads[0].query.where).toEqual({ organization_id: 'org_b' }); |
| 246 | + }); |
| 247 | +}); |
| 248 | + |
| 249 | +describe('unwalled (`single`) — the active-organization read is never consulted', () => { |
| 250 | + it('install, reseed and purge act table-wide with no organization, and never ask for one', async () => { |
| 251 | + const m = await boot({ posture: 'single' }); |
| 252 | + |
| 253 | + const install = await m.install(); |
| 254 | + expect(install.status).toBe(200); |
| 255 | + expect(install.payload.data.seeded).toMatchObject({ mode: 'inline', inserted: 2 }); |
| 256 | + const reseed = await m.reseed(); |
| 257 | + expect(reseed.status).toBe(200); |
| 258 | + const purge = await m.purge(); |
| 259 | + expect(purge.status).toBe(200); |
| 260 | + |
| 261 | + expect(loadCalls).toHaveLength(2); |
| 262 | + for (const call of loadCalls) expect(call.config.organizationId).toBeUndefined(); |
| 263 | + const seedReads = m.reads.filter((r) => r.object === 'noorg_x'); |
| 264 | + expect(seedReads).toHaveLength(1); |
| 265 | + expect(seedReads[0].query.where).toBeUndefined(); |
| 266 | + expect(m.resolveActiveOrgId).not.toHaveBeenCalled(); |
| 267 | + }); |
| 268 | +}); |
0 commit comments