|
| 1 | +/** |
| 2 | + * v3 bulk-encrypt middleware — the plain-JSONB twin of the v2 |
| 3 | + * `../middleware/bulk-encrypt.ts`. Same `beforeExecute` lifecycle and |
| 4 | + * batching contract, with two deliberate differences: |
| 5 | + * |
| 6 | + * - **Jurisdiction**: params are matched against the closed v3 |
| 7 | + * codec-id set ({@link CIPHERSTASH_V3_CODEC_ID_SET}), never the v2 |
| 8 | + * set — the two middlewares partition the param space by codec id, |
| 9 | + * so a plan whose params carry v2 codec ids is invisible here. |
| 10 | + * - **Wire**: the param slot is replaced with the plain JSONB text of |
| 11 | + * the EQL payload ({@link v3ToDriver} — v3 columns are PG domains |
| 12 | + * over `jsonb`), never the v2 `eql_v2_encrypted` composite literal. |
| 13 | + * This module MUST NOT import `encodeEqlV2EncryptedWire`. |
| 14 | + * |
| 15 | + * The `(table, column)` routing-key stamping is NOT forked: the AST walk |
| 16 | + * is version-neutral (it touches only the shared envelope base) and is |
| 17 | + * reused from the v2 module via the exported |
| 18 | + * {@link stampRoutingKeysFromAst}. |
| 19 | + * |
| 20 | + * Everything else — one `sdk.bulkEncrypt` per `(table, column)` group, |
| 21 | + * `setHandleCiphertext` stamping with plaintext retention, `ctx.signal` |
| 22 | + * forwarding by identity plus the pre-flight abort check and the abort |
| 23 | + * race, and the ciphertext-count diagnostic — mirrors the v2 middleware; |
| 24 | + * see its module doc for the full lifecycle rationale. |
| 25 | + */ |
| 26 | + |
| 27 | +import type { |
| 28 | + ParamRefHandle, |
| 29 | + SqlParamRefMutator, |
| 30 | +} from '@prisma-next/sql-relational-core/middleware' |
| 31 | +import type { SqlMiddleware } from '@prisma-next/sql-runtime' |
| 32 | +import { ifDefined } from '@prisma-next/utils/defined' |
| 33 | +import { |
| 34 | + checkCipherstashAborted, |
| 35 | + raceCipherstashAbort, |
| 36 | +} from '../execution/abort' |
| 37 | +import { |
| 38 | + EncryptedEnvelopeBase, |
| 39 | + setHandleCiphertext, |
| 40 | +} from '../execution/envelope-base' |
| 41 | +import { markBulkEncryptMiddlewareRegistered } from '../execution/middleware-registry' |
| 42 | +import { type BulkEncryptTarget, groupByRoutingKey } from '../execution/routing' |
| 43 | +import type { CipherstashSdk } from '../execution/sdk' |
| 44 | +import { CIPHERSTASH_V3_CODEC_ID_SET } from '../extension-metadata/constants-v3' |
| 45 | +// Version-neutral AST routing-key stamping — reused, not the v2 encode path. |
| 46 | +import { stampRoutingKeysFromAst } from '../middleware/bulk-encrypt' |
| 47 | +import { v3ToDriver } from './wire-v3' |
| 48 | + |
| 49 | +/** |
| 50 | + * Construct the v3 bulk-encrypt middleware. The returned middleware is |
| 51 | + * stateless aside from the captured `sdk` reference; one instance per |
| 52 | + * (v3) runtime extension is the expected pattern. |
| 53 | + */ |
| 54 | +export function bulkEncryptMiddlewareV3(sdk: CipherstashSdk): SqlMiddleware { |
| 55 | + // Mark this sdk as wired up so the codec's `encode` can distinguish |
| 56 | + // "happy path: middleware will run later and fill in the ciphertext" |
| 57 | + // from "misconfig: this sdk has no middleware registered". See |
| 58 | + // `../execution/middleware-registry.ts`. |
| 59 | + markBulkEncryptMiddlewareRegistered(sdk) |
| 60 | + return { |
| 61 | + name: 'cipherstash.bulk-encrypt-v3', |
| 62 | + familyId: 'sql', |
| 63 | + async beforeExecute(plan, ctx, params) { |
| 64 | + if (!params) { |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + stampRoutingKeysFromAst(plan.ast) |
| 69 | + |
| 70 | + const targets = collectV3Targets(params) |
| 71 | + if (targets.length === 0) { |
| 72 | + return |
| 73 | + } |
| 74 | + |
| 75 | + const groups = groupByRoutingKey(targets) |
| 76 | + for (const [groupKey, group] of groups) { |
| 77 | + const first = group[0] |
| 78 | + if (!first) continue |
| 79 | + const routingKey = first.routingKey |
| 80 | + |
| 81 | + checkCipherstashAborted(ctx.signal, 'bulk-encrypt') |
| 82 | + const ciphertexts = await raceCipherstashAbort( |
| 83 | + sdk.bulkEncrypt({ |
| 84 | + routingKey, |
| 85 | + values: group.map((t) => t.plaintext), |
| 86 | + ...ifDefined('signal', ctx.signal), |
| 87 | + }), |
| 88 | + ctx.signal, |
| 89 | + 'bulk-encrypt', |
| 90 | + ) |
| 91 | + |
| 92 | + if (ciphertexts.length !== group.length) { |
| 93 | + throw new Error( |
| 94 | + `cipherstash v3 bulk-encrypt: SDK returned ${ciphertexts.length} ciphertexts ` + |
| 95 | + `for routing key ${groupKey} but ${group.length} were requested.`, |
| 96 | + ) |
| 97 | + } |
| 98 | + |
| 99 | + // Replace each ParamRef's value with the plain JSONB text the |
| 100 | + // pg driver can serialise directly (the envelope instance |
| 101 | + // itself would fail at the driver boundary). The envelope's |
| 102 | + // ciphertext slot is also stamped via `setHandleCiphertext` |
| 103 | + // and its plaintext slot retained, so follow-on reuse of the |
| 104 | + // same envelope skips the re-encrypt round-trip. |
| 105 | + params.replaceValues( |
| 106 | + group.map((t, i) => { |
| 107 | + const ciphertext = ciphertexts[i] |
| 108 | + setHandleCiphertext(t.envelope, ciphertext) |
| 109 | + return { |
| 110 | + ref: t.ref, |
| 111 | + newValue: v3ToDriver(ciphertext), |
| 112 | + } |
| 113 | + }), |
| 114 | + ) |
| 115 | + } |
| 116 | + }, |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +function collectV3Targets( |
| 121 | + params: SqlParamRefMutator, |
| 122 | +): BulkEncryptTarget<ParamRefHandle<string | undefined>>[] { |
| 123 | + const targets: BulkEncryptTarget<ParamRefHandle<string | undefined>>[] = [] |
| 124 | + for (const entry of params.entries()) { |
| 125 | + if ( |
| 126 | + entry.codecId === undefined || |
| 127 | + !CIPHERSTASH_V3_CODEC_ID_SET.has(entry.codecId) |
| 128 | + ) |
| 129 | + continue |
| 130 | + const value = entry.value |
| 131 | + if (!(value instanceof EncryptedEnvelopeBase)) continue |
| 132 | + const handle = value.expose() |
| 133 | + if (handle.plaintext === undefined) { |
| 134 | + throw new Error( |
| 135 | + 'cipherstash v3 bulk-encrypt: encountered an envelope with no plaintext on the write path. ' + |
| 136 | + 'Use the relevant `Encrypted*.from(plaintext)` factory to construct write-side envelopes.', |
| 137 | + ) |
| 138 | + } |
| 139 | + if (handle.table === undefined || handle.column === undefined) { |
| 140 | + throw new Error( |
| 141 | + 'cipherstash v3 bulk-encrypt: envelope reached the bulk-encrypt phase without a (table, column) ' + |
| 142 | + "routing context. The middleware's AST walk only handles `InsertAst` and `UpdateAst`; " + |
| 143 | + 'cipherstash envelopes embedded in other plan shapes (e.g. raw SQL) must stamp routing ' + |
| 144 | + 'context explicitly via `setHandleRoutingKey` before execute.', |
| 145 | + ) |
| 146 | + } |
| 147 | + targets.push({ |
| 148 | + ref: entry.ref, |
| 149 | + plaintext: handle.plaintext, |
| 150 | + envelope: value, |
| 151 | + routingKey: { table: handle.table, column: handle.column }, |
| 152 | + }) |
| 153 | + } |
| 154 | + return targets |
| 155 | +} |
0 commit comments