Skip to content

Commit 650f0b8

Browse files
authored
Merge pull request #1544 from cipherstash/claude/project-thread-qzt4qf
fix(stack-supabase): read tables that have no encrypted columns
2 parents 208b117 + 2e6188f commit 650f0b8

14 files changed

Lines changed: 648 additions & 78 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@cipherstash/stack": patch
3+
---
4+
5+
`@cipherstash/stack/adapter-kit` now exports `isEncryptedPayload`, the check
6+
model decryption uses to find an encrypted value in a row. The Supabase adapter
7+
uses it to refuse a row it would otherwise return undecrypted.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"stash": patch
3+
---
4+
5+
The `stash-supabase` skill now says that tables with no encrypted columns are
6+
read and written through the same `es.from()`, and that an embedded relation to
7+
an encrypted table is refused rather than decrypted.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
"@cipherstash/stack-supabase": patch
3+
---
4+
5+
Reading a table that has no encrypted columns no longer fails. Such a table is
6+
not registered with the encryption client, and the adapter still asked the
7+
client to decrypt its rows, so every `select()` on it, and every insert, update
8+
or upsert followed by `.select()`, returned "decryptModel received a table this
9+
client was not initialized with" (or threw, with `throwOnError`). On the
10+
`wasm-inline` entry, writes to such a table failed the same way. The adapter now
11+
passes the rows of a table with no encrypted columns straight through, in both
12+
introspection and declared mode, without calling the encryption client.
13+
14+
A row from such a table that still holds an encrypted value, from an embedded
15+
relation to an encrypted table or from an undeclared `eql_v3_*` column in
16+
declared mode, is refused with an error naming the column, rather than returned
17+
as ciphertext.

‎languages/typescript/packages/stack-supabase/__tests__/helpers/supabase-mock.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,19 @@ export function operation<T>(data: T) {
7373
return op
7474
}
7575

76+
/** A chainable operation resolving to `{ failure }`, like a real failed one. */
77+
export function failingOperation(failure: { type: string; message: string }) {
78+
const op = {
79+
withLockContext: () => op,
80+
audit: () => op,
81+
then: (
82+
onfulfilled?: ((value: { failure: typeof failure }) => unknown) | null,
83+
onrejected?: ((reason: unknown) => unknown) | null,
84+
) => Promise.resolve({ failure }).then(onfulfilled, onrejected),
85+
}
86+
return op
87+
}
88+
7689
type SchemaLike = {
7790
build(): { columns: Record<string, unknown> }
7891
buildColumnKeyMap?(): Record<string, string>

‎languages/typescript/packages/stack-supabase/__tests__/supabase-encryption-error.test.ts‎

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { EncryptedQueryBuilderImpl } from '../src/query-builder'
66
import {
77
createMockEncryptionClient,
88
createMockSupabase,
9+
failingOperation,
910
fakeEnvelope,
1011
operation,
1112
} from './helpers/supabase-mock'
@@ -25,19 +26,6 @@ const usersV3 = encryptedTable('users', {
2526
email: types.TextEq('email'),
2627
})
2728

28-
/** A chainable op that resolves to `{ failure }`, like a real failed operation. */
29-
function failingOperation(failure: { type: string; message: string }) {
30-
const op = {
31-
withLockContext: () => op,
32-
audit: () => op,
33-
then: (
34-
onfulfilled?: ((value: { failure: typeof failure }) => unknown) | null,
35-
onrejected?: ((reason: unknown) => unknown) | null,
36-
) => Promise.resolve({ failure }).then(onfulfilled, onrejected),
37-
}
38-
return op
39-
}
40-
4129
describe('EncryptedSupabaseError.encryptionError (#626)', () => {
4230
it('threads the EncryptionError through on an encryption failure', async () => {
4331
const failure = {
Lines changed: 299 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,299 @@
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

Comments
 (0)