|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * The analytics → `security` admission bridge, and the three resolutions it |
| 5 | + * must tell apart. |
| 6 | + * |
| 7 | + * The object-level gate at the analytics door is only as good as the answer the |
| 8 | + * bridge brings back, and the bridge has three outcomes that are easy to |
| 9 | + * collapse into one: |
| 10 | + * |
| 11 | + * - the `security` service is ABSENT — this deployment has no object-level |
| 12 | + * gate anywhere, `GET /data/<object>` included, because that gate IS the |
| 13 | + * absent middleware. The two doors agree, which is the equivalence property |
| 14 | + * the card asks for, so the query is ADMITTED and the state is reported at |
| 15 | + * init; |
| 16 | + * - resolving the service THREW — a security service exists on this |
| 17 | + * deployment and could not be reached; |
| 18 | + * - the service resolved but exposes NEITHER `canReadObject` NOR `explain` — |
| 19 | + * it exists and cannot answer. |
| 20 | + * |
| 21 | + * The last two are wired-but-broken providers. `/data`'s middleware does not |
| 22 | + * fall open in either state, so admitting here would reopen exactly the |
| 23 | + * divergence between the two doors that this gate closes — and would do it |
| 24 | + * silently, which is worse than the original defect: the original at least had |
| 25 | + * a shape a reader could find in the code. Both DENY, and both say why at |
| 26 | + * `error`. |
| 27 | + * |
| 28 | + * ⛔ The absent case is not a bug to be tightened away. It is the negative |
| 29 | + * control that keeps the two deny cases honest: a bridge that denied on absence |
| 30 | + * too would refuse every analytics query on every deployment that ships no |
| 31 | + * `plugin-security`, which is a strictly different (and wrong) answer from the |
| 32 | + * one `/data` gives on that same deployment. |
| 33 | + */ |
| 34 | + |
| 35 | +import { describe, it, expect, vi } from 'vitest'; |
| 36 | +import { DatasetSchema } from '@objectstack/spec/ui'; |
| 37 | +import type { ExecutionContext } from '@objectstack/spec/kernel'; |
| 38 | +import { AnalyticsServicePlugin } from '../plugin.js'; |
| 39 | +import type { AnalyticsService } from '../analytics-service.js'; |
| 40 | + |
| 41 | +/** The reported probe's shape: one object, one count measure, no dimensions. */ |
| 42 | +const probe = DatasetSchema.parse({ |
| 43 | + name: 'probe_member', |
| 44 | + label: 'probe', |
| 45 | + object: 'employer_member', |
| 46 | + dimensions: [], |
| 47 | + measures: [{ name: 'cnt', label: 'Count', aggregate: 'count' }], |
| 48 | +}); |
| 49 | + |
| 50 | +const CALLER = { userId: 'u_seeker', tenantId: 'org_a' } as ExecutionContext; |
| 51 | + |
| 52 | +/** The SQL posture — the reported path, where nothing else stands in the way. */ |
| 53 | +const nativeSql = () => ({ nativeSql: true, objectqlAggregate: false, inMemory: false }); |
| 54 | + |
| 55 | +/** |
| 56 | + * Engine double. Every read it serves is recorded, so a denial can be asserted |
| 57 | + * as "the database was never reached" rather than only as a thrown envelope — |
| 58 | + * a gate that refuses AFTER running the statement has not refused anything. |
| 59 | + */ |
| 60 | +function fakeEngine() { |
| 61 | + const reads: string[] = []; |
| 62 | + return { |
| 63 | + reads, |
| 64 | + engine: { |
| 65 | + execute: async (sql: unknown, options?: { object?: string }) => { |
| 66 | + reads.push(`execute:${options?.object ?? String(sql)}`); |
| 67 | + return { rows: [{ cnt: 24 }] }; |
| 68 | + }, |
| 69 | + aggregate: async (object: string) => { |
| 70 | + reads.push(`aggregate:${object}`); |
| 71 | + return [{ cnt: 24 }]; |
| 72 | + }, |
| 73 | + getObject: (name: string) => |
| 74 | + name === 'employer_member' ? { fields: { id: { type: 'text' } } } : undefined, |
| 75 | + resolveEffectiveDatasource: () => undefined, |
| 76 | + }, |
| 77 | + }; |
| 78 | +} |
| 79 | + |
| 80 | +/** |
| 81 | + * Minimal `PluginContext`. `security` is supplied as a THUNK so a fixture can |
| 82 | + * make the lookup itself throw — the corner that is otherwise unreachable from |
| 83 | + * a plain service map. |
| 84 | + */ |
| 85 | +function fakePluginContext(opts: { |
| 86 | + data: unknown; |
| 87 | + security?: () => unknown; |
| 88 | +}) { |
| 89 | + const registered: Record<string, unknown> = {}; |
| 90 | + const warn = vi.fn(); |
| 91 | + const error = vi.fn(); |
| 92 | + return { |
| 93 | + registered, |
| 94 | + warn, |
| 95 | + error, |
| 96 | + ctx: { |
| 97 | + getService: (name: string) => { |
| 98 | + if (name === 'security') return opts.security ? opts.security() : undefined; |
| 99 | + if (name === 'data') return opts.data; |
| 100 | + return registered[name]; |
| 101 | + }, |
| 102 | + registerService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 103 | + replaceService: (name: string, svc: unknown) => { registered[name] = svc; }, |
| 104 | + logger: { info() {}, warn, error, debug() {} }, |
| 105 | + }, |
| 106 | + }; |
| 107 | +} |
| 108 | + |
| 109 | +async function bootAnalytics(security?: () => unknown) { |
| 110 | + const { engine, reads } = fakeEngine(); |
| 111 | + const { ctx, registered, error } = fakePluginContext({ data: engine, security }); |
| 112 | + await new AnalyticsServicePlugin({ queryCapabilities: nativeSql }).init(ctx as never); |
| 113 | + return { service: registered.analytics as AnalyticsService, reads, error }; |
| 114 | +} |
| 115 | + |
| 116 | +const runProbe = (service: AnalyticsService) => |
| 117 | + service.queryDataset(probe as never, { measures: ['cnt'] } as never, CALLER); |
| 118 | + |
| 119 | +describe('analytics admission bridge — resolving the "security" service', () => { |
| 120 | + // ── The two corners that used to admit silently ──────────────────────────── |
| 121 | + |
| 122 | + it('DENIES when resolving the "security" service THROWS', async () => { |
| 123 | + const boom = () => { throw new Error('security service is initialising'); }; |
| 124 | + const { service, reads, error } = await bootAnalytics(boom); |
| 125 | + |
| 126 | + await expect(runProbe(service)).rejects.toMatchObject({ |
| 127 | + code: 'PERMISSION_DENIED', |
| 128 | + status: 403, |
| 129 | + }); |
| 130 | + // The refusal has to happen BEFORE the statement runs, or it is not a gate. |
| 131 | + expect(reads).toEqual([]); |
| 132 | + // And it has to be findable. A security refusal nobody can see is |
| 133 | + // indistinguishable from a gate that never ran. |
| 134 | + expect(error.mock.calls.map((c) => String(c[0])).join('\n')).toMatch( |
| 135 | + /read admission could not be resolved .* denying the query \(fail-closed\).*threw/s, |
| 136 | + ); |
| 137 | + }); |
| 138 | + |
| 139 | + it('DENIES when the "security" service exposes neither canReadObject nor explain', async () => { |
| 140 | + // A registered object that is not the contract it claims to be — |
| 141 | + // `explain` is NON-optional on `ISecurityService`, so a conforming |
| 142 | + // provider never lands here. |
| 143 | + const { service, reads, error } = await bootAnalytics(() => ({ getReadFilter: () => undefined })); |
| 144 | + |
| 145 | + await expect(runProbe(service)).rejects.toMatchObject({ |
| 146 | + code: 'PERMISSION_DENIED', |
| 147 | + status: 403, |
| 148 | + }); |
| 149 | + expect(reads).toEqual([]); |
| 150 | + expect(error.mock.calls.map((c) => String(c[0])).join('\n')).toMatch( |
| 151 | + /read admission could not be resolved .* neither canReadObject\(\) nor explain\(\)/s, |
| 152 | + ); |
| 153 | + }); |
| 154 | + |
| 155 | + // ── The negative control: absence is a different state and still ADMITS ──── |
| 156 | + |
| 157 | + it('ADMITS when NO "security" service is registered at all', async () => { |
| 158 | + // ⛔ Not a corner to tighten. On this deployment `/data` has no |
| 159 | + // object-level gate either, so the two doors still agree — which is the |
| 160 | + // property being defended. Tightening this to a denial would refuse every |
| 161 | + // analytics query on every deployment shipping no `plugin-security`. |
| 162 | + const { service, reads } = await bootAnalytics(undefined); |
| 163 | + |
| 164 | + const result = await runProbe(service); |
| 165 | + expect(result.rows).toEqual([{ cnt: 24 }]); |
| 166 | + expect(reads).toHaveLength(1); |
| 167 | + }); |
| 168 | + |
| 169 | + // ── The two working spellings, so the deny cases cannot pass by refusing all ─ |
| 170 | + |
| 171 | + it('asks canReadObject when the service has it, and serves an ADMITTED caller', async () => { |
| 172 | + const canReadObject = vi.fn(() => true); |
| 173 | + const { service, reads } = await bootAnalytics(() => ({ canReadObject })); |
| 174 | + |
| 175 | + const result = await runProbe(service); |
| 176 | + expect(result.rows).toEqual([{ cnt: 24 }]); |
| 177 | + expect(canReadObject).toHaveBeenCalledWith('employer_member', CALLER); |
| 178 | + expect(reads).toHaveLength(1); |
| 179 | + }); |
| 180 | + |
| 181 | + it('refuses through canReadObject when that service answers false', async () => { |
| 182 | + const { service, reads } = await bootAnalytics(() => ({ canReadObject: () => false })); |
| 183 | + |
| 184 | + await expect(runProbe(service)).rejects.toMatchObject({ |
| 185 | + code: 'PERMISSION_DENIED', |
| 186 | + status: 403, |
| 187 | + }); |
| 188 | + expect(reads).toEqual([]); |
| 189 | + }); |
| 190 | + |
| 191 | + it('falls back to explain for a service that predates canReadObject — both verdicts', async () => { |
| 192 | + const admitted = await bootAnalytics(() => ({ |
| 193 | + explain: async () => ({ allowed: true }), |
| 194 | + })); |
| 195 | + expect((await runProbe(admitted.service)).rows).toEqual([{ cnt: 24 }]); |
| 196 | + |
| 197 | + const refused = await bootAnalytics(() => ({ |
| 198 | + explain: async () => ({ allowed: false }), |
| 199 | + })); |
| 200 | + await expect(runProbe(refused.service)).rejects.toMatchObject({ |
| 201 | + code: 'PERMISSION_DENIED', |
| 202 | + status: 403, |
| 203 | + }); |
| 204 | + expect(refused.reads).toEqual([]); |
| 205 | + }); |
| 206 | +}); |
0 commit comments