Skip to content

Commit 3bd2e76

Browse files
authored
Merge pull request #1554 from cipherstash/claude/project-thread-uthgtw
fix(stack,supabase,prisma): keep plaintext search terms out of errors and logs
2 parents 8b2aefe + b29eaa1 commit 3bd2e76

14 files changed

Lines changed: 493 additions & 15 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@cipherstash/stack': patch
3+
'@cipherstash/stack-supabase': patch
4+
'@cipherstash/stack-prisma': patch
5+
'stash': patch
6+
---
7+
8+
Two validation errors no longer quote the caller's search term: a free-text search term that is too short, and a `like`/`ilike` pattern with wildcards the encrypted search cannot honour. Each now reports the term's length instead.
9+
10+
The Supabase and DynamoDB adapters' error logs now record a failure's kind instead of its full message, which could quote a plaintext value. The kind is the error class plus any known encryption error type, FFI error code or auth code it carries; anything else is left out. The DynamoDB `options.logger` hook now receives a copy of the error whose message is that description, with the same `code`. The full message is still returned to the caller and passed to `errorHandler`. `@cipherstash/stack/adapter-kit` exports the shared `describeFailure` and `likeWildcardError` helpers that produce these messages.

‎languages/typescript/packages/stack-prisma/src/v3/operators-v3.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575

7676
import {
7777
jsonPathOf,
78+
likeWildcardError,
7879
matchNeedleError,
7980
parseSelectorSegments,
8081
unsupportedLeafReason,
@@ -537,7 +538,7 @@ function normalizeMatchNeedle(
537538
throw operatorError(
538539
ctx,
539540
method,
540-
`cipherstash ${method}: pattern ${JSON.stringify(value)} on column "${ctx.columnName ?? 'unknown'}" has wildcards fuzzy free-text matching cannot honor (an interior "%" or any "_"). Pass a literal search term.`,
541+
`cipherstash ${method} on column "${ctx.columnName ?? 'unknown'}": ${likeWildcardError(value)} Pass a literal search term.`,
541542
)
542543
}
543544
const match = ctx.meta.indexes.match

‎languages/typescript/packages/stack-prisma/test/v3/operator-lowering-v3-text-search.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,22 @@ describe('cipherstash v3 operator lowering — eqlMatch needle guards', () => {
124124
}
125125
})
126126

127+
// The pattern is the caller's plaintext search term. The error is thrown to
128+
// the caller, who commonly logs it, so it reports the term's length only.
129+
it('never echoes the rejected pattern in the wildcard error', () => {
130+
for (const needle of ['Qzx%wvy', 'Qzx_wvy']) {
131+
let message = ''
132+
try {
133+
lowerMatch(needle)
134+
} catch (err) {
135+
message = (err as Error).message
136+
}
137+
expect(message, needle).toMatch(/cannot honor/)
138+
expect(message, needle).not.toContain('Qzx')
139+
expect(message, needle).not.toContain('wvy')
140+
}
141+
})
142+
127143
it('rejects a needle that is empty after stripping with the matchNeedleError reason', () => {
128144
expect(() => lowerMatch('%%')).toThrow(EncryptionOperatorError)
129145
expect(() => lowerMatch('%%')).toThrow(
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { logger } from '@cipherstash/stack/adapter-kit'
2+
import { encryptedTable, types } from '@cipherstash/stack/eql/v3'
3+
import { afterEach, describe, expect, it, vi } from 'vitest'
4+
import { EncryptedQueryBuilderImpl } from '../src/query-builder'
5+
import {
6+
createMockEncryptionClient,
7+
createMockSupabase,
8+
} from './helpers/supabase-mock'
9+
10+
// A search term on an encrypted column is plaintext the caller chose to
11+
// protect. The library promises never to log plaintext, and its own error
12+
// messages are routinely logged by callers, so neither may carry the term.
13+
// These tests use distinctive sentinels so a substring check cannot pass by
14+
// accident against an ordinary English word in the message.
15+
16+
const users = encryptedTable('users', {
17+
email: types.TextSearch('email'),
18+
nickname: types.TextEq('nickname'),
19+
})
20+
const COLUMNS = ['id', 'email', 'nickname']
21+
22+
function builder(encryptionClient = createMockEncryptionClient()) {
23+
const supabase = createMockSupabase([])
24+
return new EncryptedQueryBuilderImpl(
25+
'users',
26+
users,
27+
encryptionClient,
28+
supabase.client,
29+
COLUMNS,
30+
)
31+
}
32+
33+
/** Every string the logger was handed, across all levels. */
34+
function logged(spies: ReturnType<typeof vi.spyOn>[]): string {
35+
return spies
36+
.flatMap((spy) => spy.mock.calls.flat())
37+
.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg)))
38+
.join('\n')
39+
}
40+
41+
function spyLogger() {
42+
return (['error', 'warn', 'info', 'debug'] as const).map((level) =>
43+
vi.spyOn(logger, level).mockImplementation(() => {}),
44+
)
45+
}
46+
47+
afterEach(() => {
48+
vi.restoreAllMocks()
49+
})
50+
51+
describe('plaintext search terms stay out of errors and logs', () => {
52+
it('a too-short matches() needle is neither logged nor echoed in the error', async () => {
53+
const spies = spyLogger()
54+
55+
const { error } = await builder().select('id').matches('email', 'Qz')
56+
57+
expect(error?.message).toMatch(/at least 3 characters/)
58+
expect(error?.message).not.toContain('Qz')
59+
expect(logged(spies)).not.toContain('Qz')
60+
})
61+
62+
it('a like() pattern with unsupported wildcards is not echoed in the error', () => {
63+
for (const pattern of ['Qzx%wvy', 'Qzx_wvy']) {
64+
let message = ''
65+
try {
66+
builder().select('id').like('email', pattern)
67+
} catch (err) {
68+
message = (err as Error).message
69+
}
70+
expect(message, pattern).toMatch(/cannot honor/)
71+
expect(message, pattern).not.toContain('Qzx')
72+
expect(message, pattern).not.toContain('wvy')
73+
}
74+
})
75+
76+
// The catch around query execution sees errors from every layer (encryption,
77+
// PostgREST, the network), and any of them may quote a value. It reports the
78+
// failure's kind; the message itself goes back to the caller, not to the log.
79+
it('a failed query logs the failure kind, not the error message', async () => {
80+
const encryption = createMockEncryptionClient()
81+
vi.spyOn(
82+
encryption as unknown as { bulkEncrypt: (...a: unknown[]) => unknown },
83+
'bulkEncrypt',
84+
).mockImplementation(() => {
85+
throw new TypeError('value "Qzx-secret-wvy" could not be encoded')
86+
})
87+
const spies = spyLogger()
88+
89+
const { error } = await builder(encryption)
90+
.select('id')
91+
.in('nickname', ['Qzx-secret-wvy', 'other'])
92+
93+
expect(error?.message).toContain('Qzx-secret-wvy')
94+
const output = logged(spies)
95+
expect(output).toMatch(/failed on table "users"/)
96+
expect(output).toContain('TypeError')
97+
expect(output).not.toContain('Qzx')
98+
})
99+
})

‎languages/typescript/packages/stack-supabase/__tests__/supabase-plaintext-table.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,11 @@ describe('plaintext table rows that carry ciphertext', () => {
262262

263263
expect(error?.message).toContain('"[0].meta"')
264264
expect(error?.message).not.toContain('ssn-078-05-1120')
265-
// The message reaches the logger too, so the log must not carry it either.
265+
// The log names the failure's kind, never the message (CIP-5161), so it
266+
// carries neither the key nor the row path.
266267
expect(logged).toHaveBeenCalled()
267268
for (const args of logged.mock.calls) {
268-
expect(args.join(' ')).toContain('"[0].meta"')
269+
expect(args.join(' ')).toContain('DecryptionError')
269270
expect(args.join(' ')).not.toContain('ssn-078-05-1120')
270271
}
271272
} finally {

‎languages/typescript/packages/stack-supabase/src/query-builder.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { AuditConfig } from '@cipherstash/stack/adapter-kit'
22
import {
3+
describeFailure,
4+
likeWildcardError,
35
logger,
46
parseSelectorSegments,
57
reconstructSelectorDocument,
@@ -597,8 +599,12 @@ export class EncryptedQueryBuilderImpl<
597599
} satisfies DecryptContext)
598600
} catch (err) {
599601
const message = err instanceof Error ? err.message : String(err)
602+
// Log the failure's kind, never its message: this catch sees errors from
603+
// every layer (query-term validation, encryption, PostgREST), and their
604+
// messages may quote a plaintext value. The full message still reaches
605+
// the caller in the returned `error`.
600606
logger.error(
601-
`Supabase encrypted query failed on table "${this.tableName}": ${message}`,
607+
`Supabase encrypted query failed on table "${this.tableName}" (${describeFailure(err)}).`,
602608
)
603609

604610
// A failure inside any of the encrypt/decrypt steps above is thrown as an
@@ -893,7 +899,7 @@ export class EncryptedQueryBuilderImpl<
893899
const { needle, hasUnsupportedWildcard } = parseLikeNeedle(pattern)
894900
if (hasUnsupportedWildcard) {
895901
throw new Error(
896-
`[supabase v3]: "${op}" pattern "${pattern}" on encrypted column "${column}" has wildcards fuzzy free-text matching cannot honor (an unescaped internal "%" or any unescaped "_"). Use matches("${column}", term) with a literal search term.`,
902+
`[supabase v3]: "${op}" on encrypted column "${column}": ${likeWildcardError(pattern)} Escape a literal "%" or "_" as "\\%" or "\\_", or use matches("${column}", term) with a literal search term.`,
897903
)
898904
}
899905
const key = `${op}:${column}`
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import { PROTECT_ERROR_CODES } from '@cipherstash/protect-ffi'
2+
import { describe, expect, it } from 'vitest'
3+
import {
4+
describeFailure,
5+
FFI_ERROR_CODES,
6+
} from '@/utils/logger/describe-failure'
7+
8+
// `describeFailure` is what adapters log in place of an error's message, which
9+
// may quote a plaintext value (CIP-5161). Everything it returns must come from
10+
// a fixed allowlist, never from the error, however identifier-like the error's
11+
// fields look.
12+
describe('describeFailure', () => {
13+
it('names an Error by its class, never its message', () => {
14+
expect(describeFailure(new TypeError('value "Qzx" is bad'))).toBe(
15+
'TypeError',
16+
)
17+
})
18+
19+
it('appends known type, code and authCode identifiers', () => {
20+
const err = Object.assign(new Error('boom Qzx'), {
21+
type: 'EncryptionError',
22+
code: 'UNKNOWN_COLUMN',
23+
authCode: 'USAGE_LIMIT_EXCEEDED',
24+
})
25+
expect(describeFailure(err)).toBe(
26+
'Error: EncryptionError: UNKNOWN_COLUMN: USAGE_LIMIT_EXCEEDED',
27+
)
28+
})
29+
30+
it('reads identifiers from a nested encryptionError', () => {
31+
const err = Object.assign(new Error('Qzx'), {
32+
name: 'EncryptionFailedError',
33+
encryptionError: {
34+
type: 'EncryptionError',
35+
message: 'Qzx',
36+
authCode: 'USAGE_LIMIT_EXCEEDED',
37+
},
38+
})
39+
expect(describeFailure(err)).toBe(
40+
'EncryptionFailedError: EncryptionError: USAGE_LIMIT_EXCEEDED',
41+
)
42+
})
43+
44+
// An identifier-shaped field can still hold caller data, so the shape is not
45+
// the test: only known values pass.
46+
it('drops identifier-shaped values that are not known codes', () => {
47+
const err = Object.assign(new Error('invalid value'), {
48+
code: 'Qzx-secret-wvy',
49+
type: 'alice.smith',
50+
authCode: '123-45-6789',
51+
})
52+
expect(describeFailure(err)).toBe('Error')
53+
expect(describeFailure({ code: 'Qzx_secret', message: 'x' })).toBe('object')
54+
expect(describeFailure({ code: 42883 })).toBe('object')
55+
})
56+
57+
it('reports an unknown error class as Error', () => {
58+
const renamed = new Error('x')
59+
renamed.name = 'QzxSecret'
60+
expect(describeFailure(renamed)).toBe('Error')
61+
})
62+
63+
it('describes a non-object by its type', () => {
64+
expect(describeFailure('Qzx')).toBe('string')
65+
expect(describeFailure(null)).toBe('null')
66+
expect(describeFailure(undefined)).toBe('undefined')
67+
})
68+
69+
// Called from inside a catch: if describing the failure threw, Supabase would
70+
// reject instead of returning `{ error }`, and DynamoDB would skip its
71+
// errorHandler.
72+
it('returns a fixed description when reading the error throws', () => {
73+
const err = new Error('x')
74+
Object.defineProperty(err, 'type', {
75+
get() {
76+
throw new Error('getter Qzx')
77+
},
78+
})
79+
expect(describeFailure(err)).toBe('unknown failure')
80+
81+
const { proxy, revoke } = Proxy.revocable({}, {})
82+
revoke()
83+
expect(describeFailure(proxy)).toBe('unknown failure')
84+
})
85+
86+
it('allowlists exactly the FFI error codes protect-ffi declares', () => {
87+
expect([...FFI_ERROR_CODES].sort()).toEqual([...PROTECT_ERROR_CODES].sort())
88+
})
89+
})

‎languages/typescript/packages/stack/__tests__/dynamodb/resolve-decrypt.test.ts‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,55 @@ describe('handleError', () => {
446446
expect(rethrow('ECONNRESET').code).toBe('DYNAMODB_ENCRYPTION_ERROR')
447447
})
448448

449+
// The message may quote a plaintext value (CIP-5161). It is returned to the
450+
// caller on the error, but the library's own log names only the failure kind.
451+
it('logs the failure kind and code, never the message', () => {
452+
const failure = Object.assign(
453+
new Error('value "Qzx-secret-wvy" rejected'),
454+
{
455+
code: 'UNKNOWN_COLUMN',
456+
},
457+
)
458+
459+
const error = handleError(failure, 'encryptModel')
460+
461+
expect(error.message).toContain('Qzx-secret-wvy')
462+
const logged = errorLog.mock.calls.flat().join('\n')
463+
expect(logged).toContain('encryptModel')
464+
expect(logged).toContain('UNKNOWN_COLUMN')
465+
expect(logged).not.toContain('Qzx')
466+
})
467+
468+
// `options.logger` is a log sink the caller wires to `console` or a log
469+
// service, so it gets the same log-safe description as the shared logger.
470+
// The full message stays on the returned error and on `errorHandler`'s.
471+
it('hands the configured logger a log-safe error, and errorHandler the full one', () => {
472+
const failure = Object.assign(
473+
new Error('value "Qzx-secret-wvy" rejected'),
474+
{
475+
code: 'UNKNOWN_COLUMN',
476+
},
477+
)
478+
const logged: unknown[] = []
479+
const handled: Error[] = []
480+
481+
const error = handleError(failure, 'encryptModel', {
482+
logger: { error: (message, err) => logged.push(message, err) },
483+
errorHandler: (err) => handled.push(err),
484+
})
485+
486+
expect(error.message).toContain('Qzx-secret-wvy')
487+
expect(handled[0]?.message).toContain('Qzx-secret-wvy')
488+
const [message, loggedError] = logged as [string, Error & { code: string }]
489+
expect(message).toContain('encryptModel')
490+
expect(loggedError).toBeInstanceOf(Error)
491+
expect(loggedError.code).toBe('UNKNOWN_COLUMN')
492+
expect(
493+
[message, loggedError.message, String(loggedError.stack)].join('\n'),
494+
).not.toContain('Qzx')
495+
expect(loggedError.message).toContain('UNKNOWN_COLUMN')
496+
})
497+
449498
it('extracts the message from an Error, a plain object, or anything else', () => {
450499
expect(
451500
handleError(new Error('from an Error'), 'decryptModel').message,
@@ -463,7 +512,7 @@ describe('handleError', () => {
463512
expect(handleError(null, 'decryptModel').message).toBe('null')
464513
})
465514

466-
it('hands the constructed error to both the errorHandler and the caller logger', () => {
515+
it('hands the constructed error to the errorHandler and a log-safe copy to the caller logger', () => {
467516
const seen: unknown[] = []
468517
const callerLog = { error: vi.fn() }
469518

@@ -478,7 +527,16 @@ describe('handleError', () => {
478527
// classified one.
479528
expect(seen).toHaveLength(1)
480529
expect(seen[0]).toBe(error)
481-
expect(callerLog.error).toHaveBeenCalledWith('Error in decryptModel', error)
530+
// The logger gets a copy with the same code but a log-safe message
531+
// (CIP-5161), not the caller's error.
532+
expect(callerLog.error).toHaveBeenCalledWith(
533+
'Error in decryptModel',
534+
expect.objectContaining({
535+
code: error.code,
536+
message: expect.stringContaining('DynamoDB error in decryptModel'),
537+
}),
538+
)
539+
expect(callerLog.error.mock.calls[0][1]).not.toBe(error)
482540
expect(errorLog).toHaveBeenCalledWith(
483541
expect.stringContaining('DynamoDB error in decryptModel'),
484542
)

0 commit comments

Comments
 (0)