|
| 1 | +import type { EncryptionClient } from '@cipherstash/stack/encryption' |
| 2 | +import type { AnyV3Table } from '@cipherstash/stack/eql/v3' |
| 3 | +import { encryptedTable, types } from '@cipherstash/stack/eql/v3' |
| 4 | +import { describe, expect, it, vi } from 'vitest' |
| 5 | +import type { EncryptionFactory, Introspector } from '../src/create' |
| 6 | +import { makeEncryptedSupabase } from '../src/create' |
| 7 | +import type { IntrospectionData } from '../src/introspect' |
| 8 | +import { |
| 9 | + createMockEncryptionClient, |
| 10 | + createMockSupabase, |
| 11 | + failingOperation, |
| 12 | + fakeEnvelope, |
| 13 | + isFakeEnvelope, |
| 14 | +} from './helpers/supabase-mock' |
| 15 | + |
| 16 | +/** |
| 17 | + * Tables with NO encrypted columns ("plaintext tables"). |
| 18 | + * |
| 19 | + * The adapter registers every table it knows about with its query builder, but |
| 20 | + * `Encryption({ schemas })` only receives tables that carry at least one |
| 21 | + * encrypted column — it rejects an empty schema list, and a plaintext table has |
| 22 | + * nothing for it to do. Both real engines refuse a model operation on a table |
| 23 | + * they were not initialized with: the native client resolves |
| 24 | + * `decryptModel`/`bulkDecryptModels` to a "not initialized with" failure, and |
| 25 | + * the WASM client throws from `requireTable` for decrypts AND encrypts. So any |
| 26 | + * read of a plaintext table — or a mutation with `.select()` — used to fail |
| 27 | + * with `Failed to decrypt model: [eql/v3]: decryptModel received a table this |
| 28 | + * client was not initialized with`. |
| 29 | + * |
| 30 | + * The shared `createMockEncryptionClient` ignores the table argument, which is |
| 31 | + * why the existing suites never saw it. The factory below enforces the |
| 32 | + * registration contract the real engines enforce, so these tests fail the way |
| 33 | + * production did. |
| 34 | + */ |
| 35 | + |
| 36 | +/** |
| 37 | + * An `Encryption` stand-in that, like both real engines, only serves the tables |
| 38 | + * it was initialized with. Records what it was given so a test can assert the |
| 39 | + * plaintext table really was left out. |
| 40 | + */ |
| 41 | +function registryEnforcingFactory() { |
| 42 | + const registered: string[] = [] |
| 43 | + const calls: string[] = [] |
| 44 | + |
| 45 | + const factory: EncryptionFactory = async ({ schemas }) => { |
| 46 | + registered.push(...schemas.map((t) => t.tableName)) |
| 47 | + const inner = createMockEncryptionClient() as unknown as Record< |
| 48 | + string, |
| 49 | + (...args: unknown[]) => unknown |
| 50 | + > |
| 51 | + const guarded = |
| 52 | + (method: string) => |
| 53 | + (input: unknown, table: AnyV3Table | undefined, ...rest: unknown[]) => { |
| 54 | + calls.push(`${method}:${table?.tableName ?? '<none>'}`) |
| 55 | + if (table && !registered.includes(table.tableName)) { |
| 56 | + return failingOperation({ |
| 57 | + type: /decrypt/i.test(method) |
| 58 | + ? 'DecryptionError' |
| 59 | + : 'EncryptionError', |
| 60 | + message: `[eql/v3]: table "${table.tableName}" is not one this client was initialized with`, |
| 61 | + }) |
| 62 | + } |
| 63 | + return inner[method](input, table, ...rest) |
| 64 | + } |
| 65 | + return { |
| 66 | + ...inner, |
| 67 | + encryptModel: guarded('encryptModel'), |
| 68 | + bulkEncryptModels: guarded('bulkEncryptModels'), |
| 69 | + decryptModel: guarded('decryptModel'), |
| 70 | + bulkDecryptModels: guarded('bulkDecryptModels'), |
| 71 | + } as unknown as EncryptionClient |
| 72 | + } |
| 73 | + |
| 74 | + return { factory, registered, calls } |
| 75 | +} |
| 76 | + |
| 77 | +const introspection: IntrospectionData = { |
| 78 | + tables: [ |
| 79 | + { |
| 80 | + tableName: 'users', |
| 81 | + columns: [ |
| 82 | + { columnName: 'id', domainName: null }, |
| 83 | + { columnName: 'email', domainName: 'eql_v3_text_search' }, |
| 84 | + ], |
| 85 | + }, |
| 86 | + { |
| 87 | + tableName: 'audit_log', |
| 88 | + columns: [ |
| 89 | + { columnName: 'id', domainName: null }, |
| 90 | + { columnName: 'action', domainName: null }, |
| 91 | + ], |
| 92 | + }, |
| 93 | + ], |
| 94 | + unmodelled: new Map(), |
| 95 | + eqlVersion: '3.0.4', |
| 96 | +} |
| 97 | + |
| 98 | +const introspector: Introspector = { |
| 99 | + introspect: async () => introspection, |
| 100 | + eqlRequiresQueryDomains: () => false, |
| 101 | +} |
| 102 | + |
| 103 | +const auditRows = [ |
| 104 | + { id: 1, action: 'login' }, |
| 105 | + { id: 2, action: 'logout' }, |
| 106 | +] |
| 107 | + |
| 108 | +async function introspectedClient(resultData: unknown) { |
| 109 | + const encryption = registryEnforcingFactory() |
| 110 | + const supabase = createMockSupabase(resultData) |
| 111 | + const es = await makeEncryptedSupabase(encryption.factory, introspector)( |
| 112 | + supabase.client as never, |
| 113 | + { databaseUrl: 'postgres://x' }, |
| 114 | + ) |
| 115 | + return { es, encryption, supabase } |
| 116 | +} |
| 117 | + |
| 118 | +const users = encryptedTable('users', { email: types.TextSearch('email') }) |
| 119 | +const auditLog = encryptedTable('audit_log', {}) |
| 120 | + |
| 121 | +async function declaredClient(resultData: unknown) { |
| 122 | + const encryption = registryEnforcingFactory() |
| 123 | + const supabase = createMockSupabase(resultData) |
| 124 | + const es = await makeEncryptedSupabase(encryption.factory, null)( |
| 125 | + supabase.client as never, |
| 126 | + { schemas: { users, audit_log: auditLog } }, |
| 127 | + ) |
| 128 | + return { es, encryption, supabase } |
| 129 | +} |
| 130 | + |
| 131 | +describe.each([ |
| 132 | + ['introspection mode', introspectedClient], |
| 133 | + ['declared mode', declaredClient], |
| 134 | +] as const)('plaintext table — %s', (_mode, build) => { |
| 135 | + it('leaves the plaintext table out of Encryption({ schemas })', async () => { |
| 136 | + const { encryption } = await build([]) |
| 137 | + expect(encryption.registered).toEqual(['users']) |
| 138 | + }) |
| 139 | + |
| 140 | + it.each([ |
| 141 | + ['', false], |
| 142 | + [' with throwOnError', true], |
| 143 | + ])('reads every row of a plaintext table%s', async (_label, throwOnError) => { |
| 144 | + const { es, encryption } = await build(auditRows) |
| 145 | + const query = es.from('audit_log').select('id, action') |
| 146 | + const { data, error } = await (throwOnError ? query.throwOnError() : query) |
| 147 | + |
| 148 | + expect(error).toBeNull() |
| 149 | + expect(data).toEqual(auditRows) |
| 150 | + // Nothing to decrypt, so the encryption client is not consulted at all. |
| 151 | + expect(encryption.calls).toEqual([]) |
| 152 | + }) |
| 153 | + |
| 154 | + it('reads a single row of a plaintext table', async () => { |
| 155 | + const { es } = await build(auditRows[0]) |
| 156 | + const { data, error } = await es |
| 157 | + .from('audit_log') |
| 158 | + .select('id, action') |
| 159 | + .eq('id', 1) |
| 160 | + .single() |
| 161 | + |
| 162 | + expect(error).toBeNull() |
| 163 | + expect(data).toEqual(auditRows[0]) |
| 164 | + }) |
| 165 | + |
| 166 | + it.each([ |
| 167 | + ['one row', auditRows[0]], |
| 168 | + ['several rows', auditRows], |
| 169 | + ])('inserts %s and returns them via .select()', async (_label, rows) => { |
| 170 | + const { es, encryption, supabase } = await build([rows].flat()) |
| 171 | + const { data, error } = await es |
| 172 | + .from('audit_log') |
| 173 | + .insert(rows) |
| 174 | + .select('id, action') |
| 175 | + |
| 176 | + expect(error).toBeNull() |
| 177 | + expect(data).toEqual([rows].flat()) |
| 178 | + // The rows went to PostgREST exactly as written — no encrypt step ran. |
| 179 | + expect(supabase.callsFor('insert')[0].args[0]).toEqual(rows) |
| 180 | + expect(encryption.calls).toEqual([]) |
| 181 | + }) |
| 182 | + |
| 183 | + it('still encrypts and decrypts the encrypted table on the same instance', async () => { |
| 184 | + const { es, encryption, supabase } = await build([ |
| 185 | + { id: 1, email: fakeEnvelope('a@example.com', 'email') }, |
| 186 | + ]) |
| 187 | + const { data, error } = await es |
| 188 | + .from('users') |
| 189 | + .insert({ id: 1, email: 'a@example.com' }) |
| 190 | + .select('id, email') |
| 191 | + |
| 192 | + expect(error).toBeNull() |
| 193 | + expect(data).toEqual([{ id: 1, email: 'a@example.com' }]) |
| 194 | + const sent = supabase.callsFor('insert')[0].args[0] as Record< |
| 195 | + string, |
| 196 | + unknown |
| 197 | + > |
| 198 | + expect(isFakeEnvelope(sent.email)).toBe(true) |
| 199 | + expect(encryption.calls).toEqual([ |
| 200 | + 'encryptModel:users', |
| 201 | + 'bulkDecryptModels:users', |
| 202 | + ]) |
| 203 | + }) |
| 204 | +}) |
| 205 | + |
| 206 | +/** |
| 207 | + * Passing a plaintext table's rows through must not become a way to hand the |
| 208 | + * caller ciphertext typed as data. A row from a table with no encrypted columns |
| 209 | + * can still carry an EQL payload — from an embedded relation to an encrypted |
| 210 | + * table (`select('id, users(email)')`), or from a declared-mode table declared |
| 211 | + * with `{}` whose real columns are `eql_v3_*` domains. Before the passthrough |
| 212 | + * those reads failed; they must still fail, and say why, rather than succeed |
| 213 | + * with an envelope where the caller expects a value. |
| 214 | + */ |
| 215 | +describe('plaintext table rows that carry ciphertext', () => { |
| 216 | + const envelope = { |
| 217 | + v: 3, |
| 218 | + i: { t: 'users', c: 'email' }, |
| 219 | + c: 'mBbKmsMMkbKBSN', |
| 220 | + hm: 'hm', |
| 221 | + } |
| 222 | + |
| 223 | + it.each([ |
| 224 | + [ |
| 225 | + 'an embedded relation', |
| 226 | + [{ id: 1, users: { email: envelope } }], |
| 227 | + '[0].users', |
| 228 | + ], |
| 229 | + [ |
| 230 | + 'an embedded to-many relation', |
| 231 | + [{ id: 1, users: [{ email: 'x' }, { email: envelope }] }], |
| 232 | + '[0].users', |
| 233 | + ], |
| 234 | + [ |
| 235 | + 'an undeclared encrypted column', |
| 236 | + [{ id: 1, action: envelope }], |
| 237 | + '[0].action', |
| 238 | + ], |
| 239 | + ])('refuses %s', async (_case, rows, path) => { |
| 240 | + const { es } = await declaredClient(rows) |
| 241 | + const { data, error } = await es |
| 242 | + .from('audit_log') |
| 243 | + .select('id, users(email)') |
| 244 | + |
| 245 | + expect(data).toBeNull() |
| 246 | + expect(error?.message).toContain( |
| 247 | + 'table "audit_log" has no encrypted columns', |
| 248 | + ) |
| 249 | + expect(error?.message).toContain(`"${path}"`) |
| 250 | + // Never the ciphertext itself. |
| 251 | + expect(error?.message).not.toContain(envelope.c) |
| 252 | + expect(error?.encryptionError?.type).toBe('DecryptionError') |
| 253 | + }) |
| 254 | + |
| 255 | + it('never names a key inside a jsonb document', async () => { |
| 256 | + const { logger } = await import('@cipherstash/stack/adapter-kit') |
| 257 | + const logged = vi.spyOn(logger, 'error').mockImplementation(() => {}) |
| 258 | + try { |
| 259 | + const rows = [{ id: 1, meta: { 'ssn-078-05-1120': envelope } }] |
| 260 | + const { es } = await introspectedClient(rows) |
| 261 | + const { error } = await es.from('audit_log').select('id, meta') |
| 262 | + |
| 263 | + expect(error?.message).toContain('"[0].meta"') |
| 264 | + expect(error?.message).not.toContain('ssn-078-05-1120') |
| 265 | + // The message reaches the logger too, so the log must not carry it either. |
| 266 | + expect(logged).toHaveBeenCalled() |
| 267 | + for (const args of logged.mock.calls) { |
| 268 | + expect(args.join(' ')).toContain('"[0].meta"') |
| 269 | + expect(args.join(' ')).not.toContain('ssn-078-05-1120') |
| 270 | + } |
| 271 | + } finally { |
| 272 | + logged.mockRestore() |
| 273 | + } |
| 274 | + }) |
| 275 | + |
| 276 | + it('refuses a single row the same way', async () => { |
| 277 | + const { es } = await introspectedClient({ id: 1, action: envelope }) |
| 278 | + const { data, error } = await es |
| 279 | + .from('audit_log') |
| 280 | + .select('id, action') |
| 281 | + .single() |
| 282 | + |
| 283 | + expect(data).toBeNull() |
| 284 | + expect(error?.message).toContain('"action"') |
| 285 | + }) |
| 286 | + |
| 287 | + it.each([ |
| 288 | + ['without the envelope keys', { v: 3, note: 'not ciphertext' }], |
| 289 | + ['with v, i and c but no table/column identifier', { v: 1, i: {}, c: 'x' }], |
| 290 | + ['with a null identifier', { v: 1, i: null, c: 'x' }], |
| 291 | + ])('leaves a plaintext jsonb value %s alone', async (_label, meta) => { |
| 292 | + const rows = [{ id: 1, meta }] |
| 293 | + const { es } = await introspectedClient(rows) |
| 294 | + const { data, error } = await es.from('audit_log').select('id, meta') |
| 295 | + |
| 296 | + expect(error).toBeNull() |
| 297 | + expect(data).toEqual(rows) |
| 298 | + }) |
| 299 | +}) |
0 commit comments