The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * KMS binding tests (Encrypt / Decrypt / GenerateDataKey* / ReEncrypt / |
| 3 | * Sign / Verify / GenerateMac / VerifyMac / GetPublicKey / |
| 4 | * DeriveSharedSecret / DescribeKey / GenerateRandom). |
| 5 | * |
| 6 | * COST + CLEANUP NOTE — the shared test keys: |
| 7 | * KMS keys cost $1/mo while enabled and have a 7-day minimum pending-deletion |
| 8 | * window (pending-deletion keys are NOT billed), so this suite neither keeps |
| 9 | * permanently-enabled keys nor creates brand-new keys per run. The `Key` |
| 10 | * resource has no user-assignable identity (only a cloud-generated keyId), so |
| 11 | * it can't be adopted across runs from the scratch stack's in-memory state. |
| 12 | * Instead FOUR standing keys (symmetric encryption, HMAC, ECDSA signing, and |
| 13 | * ECDH key agreement — each crypto operation requires its matching KeyUsage) |
| 14 | * are acquired/released out-of-band via distilled KMS around the whole suite: |
| 15 | * |
| 16 | * - During the run each key is addressed by its deterministic alias (see the |
| 17 | * `STANDING_*_ALIAS` constants in `handler.ts`). |
| 18 | * - `beforeAll` (`ensureStandingKeys`) reclaims the previous run's keys — via |
| 19 | * the alias if an interrupted run left it behind, otherwise by each key's |
| 20 | * unique description — cancelling scheduled deletion and re-creating the |
| 21 | * alias. Only on the first-ever run (or >7 days after the last run) does |
| 22 | * it `createKey`. |
| 23 | * - `afterAll` (`releaseStandingKeys`) deletes the aliases and schedules the |
| 24 | * keys for deletion (7-day window, idempotent) so a passing run leaves no |
| 25 | * aliases and no enabled/billed keys behind — PendingDeletion is KMS's |
| 26 | * terminal "deleted" state; keys pending deletion are not billed and |
| 27 | * cannot be removed any faster. |
| 28 | * - The Lambda fixture binds the crypto operations by alias name — the |
| 29 | * bindings accept `Key | AliasName`, and the alias form scopes IAM with the |
| 30 | * `kms:RequestAlias` condition so the keys never need to live in the stack. |
| 31 | * |
| 32 | * The fixture stack (Lambda only) is destroyed normally. |
| 33 | */ |
| 34 | import * as AWS from "@alchemy.run/aws"; |
| 35 | import { describe, expect } from "@alchemy.run/test"; |
| 36 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 37 | import * as Core from "@alchemy.run/test/Core"; |
| 38 | import * as kms from "@distilled.cloud/aws/kms"; |
| 39 | import * as Data from "effect/Data"; |
| 40 | import * as Effect from "effect/Effect"; |
| 41 | import * as HttpClient from "effect/http/HttpClient"; |
| 42 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 43 | import * as Schedule from "effect/Schedule"; |
| 44 | import * as Stream from "effect/Stream"; |
| 45 | import KMSTestFunctionLive, { |
| 46 | KMSTestFunction, |
| 47 | STANDING_AGREEMENT_KEY_ALIAS, |
| 48 | STANDING_HMAC_KEY_ALIAS, |
| 49 | STANDING_KEY_ALIAS, |
| 50 | STANDING_SIGNING_KEY_ALIAS, |
| 51 | } from "./handler"; |
| 52 | |
| 53 | const testOptions = { providers: AWS.providers() }; |
| 54 | const { test, beforeAll, afterAll } = Test.make(testOptions); |
| 55 | const sharedStack = Core.scratchStack(testOptions, "KMSBindings"); |
| 56 | |
| 57 | // Lambda function URL cold-start (DNS, IAM propagation, init) can take well |
| 58 | // over 60s on a fresh deploy under parallel-suite load. |
| 59 | const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]); |
| 60 | |
| 61 | let baseUrl: string; |
| 62 | let standingKeyId: string; |
| 63 | |
| 64 | class TransientUpstream extends Data.TaggedError("TransientUpstream")<{ |
| 65 | readonly status: number; |
| 66 | readonly body: string; |
| 67 | }> {} |
| 68 | |
| 69 | class CryptoNotAuthorized extends Data.TaggedError("CryptoNotAuthorized") {} |
| 70 | |
| 71 | class StandingKeyNotReady extends Data.TaggedError("StandingKeyNotReady")<{ |
| 72 | readonly actualState: kms.KeyState | undefined; |
| 73 | readonly expectedState: kms.KeyState; |
| 74 | readonly keyId: string; |
| 75 | }> {} |
| 76 | |
| 77 | // Cold re-inits under parallel load surface as transient 5xx from the fixture |
| 78 | // — retry those; a genuine 4xx/assertion failure is returned immediately. |
| 79 | const send = (request: HttpClientRequest.HttpClientRequest) => |
| 80 | HttpClient.execute(request).pipe( |
| 81 | Effect.flatMap((response) => |
| 82 | response.status >= 500 |
| 83 | ? response.text.pipe( |
| 84 | Effect.flatMap((body) => |
| 85 | Effect.fail(new TransientUpstream({ status: response.status, body })), |
| 86 | ), |
| 87 | ) |
| 88 | : Effect.succeed(response), |
| 89 | ), |
| 90 | Effect.retry({ |
| 91 | while: (e) => e._tag === "TransientUpstream", |
| 92 | schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]), |
| 93 | }), |
| 94 | ); |
| 95 | |
| 96 | const postJson = (path: string, body: object) => |
| 97 | send(HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}${path}`), body)).pipe( |
| 98 | Effect.flatMap((response) => response.json), |
| 99 | ); |
| 100 | |
| 101 | const getJson = (path: string) => |
| 102 | send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe( |
| 103 | Effect.flatMap((response) => response.json), |
| 104 | ); |
| 105 | |
| 106 | const toBase64 = (value: string) => |
| 107 | Effect.sync(() => Buffer.from(value, "utf8").toString("base64")); |
| 108 | |
| 109 | const fromBase64 = (value: string) => |
| 110 | Effect.sync(() => Buffer.from(value, "base64").toString("utf8")); |
| 111 | |
| 112 | interface StandingKeySpec { |
| 113 | readonly alias: `alias/${string}`; |
| 114 | /** |
| 115 | * Unique marker for the key. The alias is deleted at teardown, so this |
| 116 | * description is what identifies the previous run's (pending-deletion) |
| 117 | * key for reclaim. |
| 118 | */ |
| 119 | readonly description: string; |
| 120 | readonly keySpec?: kms.KeySpec; |
| 121 | readonly keyUsage?: kms.KeyUsageType; |
| 122 | } |
| 123 | |
| 124 | const RECLAIM_NOTE = |
| 125 | "scheduled for deletion after each run, reclaimed by description (see test/AWS/KMS/Bindings.test.ts)"; |
| 126 | |
| 127 | const STANDING_KEYS: readonly StandingKeySpec[] = [ |
| 128 | { |
| 129 | alias: STANDING_KEY_ALIAS, |
| 130 | // Keep this exact text stable — it reclaims keys minted by earlier runs. |
| 131 | description: `Shared key for alchemy AWS.KMS binding tests — ${RECLAIM_NOTE}`, |
| 132 | }, |
| 133 | { |
| 134 | alias: STANDING_HMAC_KEY_ALIAS, |
| 135 | description: `Shared HMAC key for alchemy AWS.KMS binding tests — ${RECLAIM_NOTE}`, |
| 136 | keySpec: "HMAC_256", |
| 137 | keyUsage: "GENERATE_VERIFY_MAC", |
| 138 | }, |
| 139 | { |
| 140 | alias: STANDING_SIGNING_KEY_ALIAS, |
| 141 | description: `Shared ECDSA signing key for alchemy AWS.KMS binding tests — ${RECLAIM_NOTE}`, |
| 142 | keySpec: "ECC_NIST_P256", |
| 143 | keyUsage: "SIGN_VERIFY", |
| 144 | }, |
| 145 | { |
| 146 | alias: STANDING_AGREEMENT_KEY_ALIAS, |
| 147 | description: `Shared ECDH key-agreement key for alchemy AWS.KMS binding tests — ${RECLAIM_NOTE}`, |
| 148 | keySpec: "ECC_NIST_P256", |
| 149 | keyUsage: "KEY_AGREEMENT", |
| 150 | }, |
| 151 | ]; |
| 152 | |
| 153 | /** |
| 154 | * One scan of the account's customer keys, hydrated with metadata. Used to |
| 155 | * reclaim previous runs' pending-deletion keys by their unique descriptions |
| 156 | * once the aliases are gone. |
| 157 | */ |
| 158 | const scanKeyMetadatas = Effect.gen(function* () { |
| 159 | const keys = yield* kms.listKeys.pages({}).pipe( |
| 160 | Stream.runCollect, |
| 161 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Keys ?? [])), |
| 162 | ); |
| 163 | return yield* Effect.all( |
| 164 | keys.map((key) => |
| 165 | kms.describeKey({ KeyId: key.KeyId! }).pipe( |
| 166 | Effect.map((response) => response.KeyMetadata), |
| 167 | Effect.catchTag("NotFoundException", () => Effect.succeed(undefined)), |
| 168 | ), |
| 169 | ), |
| 170 | { concurrency: 5 }, |
| 171 | ); |
| 172 | }); |
| 173 | |
| 174 | /** |
| 175 | * Wait for KMS's eventually-consistent state transition to become visible. |
| 176 | * Ten seconds is ample in practice and keeps a broken transition bounded. |
| 177 | */ |
| 178 | const waitForKeyState = Effect.fn(function* (keyId: string, expectedState: kms.KeyState) { |
| 179 | return yield* kms.describeKey({ KeyId: keyId }).pipe( |
| 180 | Effect.flatMap((response) => { |
| 181 | const actualState = response.KeyMetadata?.KeyState; |
| 182 | return actualState === expectedState |
| 183 | ? Effect.succeed(response.KeyMetadata!) |
| 184 | : Effect.fail(new StandingKeyNotReady({ actualState, expectedState, keyId })); |
| 185 | }), |
| 186 | Effect.retry({ |
| 187 | while: (error) => error._tag === "StandingKeyNotReady", |
| 188 | schedule: Schedule.max([Schedule.fixed("250 millis"), Schedule.recurs(40)]), |
| 189 | }), |
| 190 | ); |
| 191 | }); |
| 192 | |
| 193 | /** Converge an existing (possibly pending-deletion/disabled) key to enabled. */ |
| 194 | const reviveKey = Effect.fn(function* (metadata: kms.KeyMetadata) { |
| 195 | const keyId = metadata.KeyId!; |
| 196 | if (metadata.KeyState === "PendingDeletion") { |
| 197 | yield* kms.cancelKeyDeletion({ KeyId: keyId }); |
| 198 | // CancelKeyDeletion leaves the key disabled, but that transition is not |
| 199 | // immediately visible. Enabling or aliasing it too early is rejected as |
| 200 | // KMSInvalidStateException (the c64 sweep's 17-test setup cascade). |
| 201 | yield* waitForKeyState(keyId, "Disabled"); |
| 202 | yield* kms.enableKey({ KeyId: keyId }); |
| 203 | } else if (metadata.Enabled === false) { |
| 204 | yield* kms.enableKey({ KeyId: keyId }); |
| 205 | } |
| 206 | return yield* waitForKeyState(keyId, "Enabled"); |
| 207 | }); |
| 208 | |
| 209 | /** |
| 210 | * Acquire one standing key: reclaim the previous run's key (cancelling its |
| 211 | * scheduled deletion and re-creating the alias), or create it on the |
| 212 | * first-ever run. `scan` is the lazily-computed account key scan, shared |
| 213 | * across the four keys. |
| 214 | */ |
| 215 | const ensureStandingKey = Effect.fn(function* ( |
| 216 | spec: StandingKeySpec, |
| 217 | scanned: { metadatas?: readonly (kms.KeyMetadata | undefined)[] }, |
| 218 | ) { |
| 219 | const existing = yield* kms.describeKey({ KeyId: spec.alias }).pipe( |
| 220 | Effect.map((response) => response.KeyMetadata), |
| 221 | Effect.catchTag("NotFoundException", () => Effect.succeed(undefined)), |
| 222 | ); |
| 223 | |
| 224 | if (existing?.KeyId) { |
| 225 | // The alias survived (a previous run was interrupted before release, or |
| 226 | // external interference disabled the key) — converge to enabled. |
| 227 | yield* reviveKey(existing); |
| 228 | return existing.KeyId; |
| 229 | } |
| 230 | |
| 231 | // Alias absent — the normal case after a clean release. Reclaim the |
| 232 | // previous run's pending-deletion key by its unique description before |
| 233 | // resorting to creating a new one. |
| 234 | if (scanned.metadatas === undefined) { |
| 235 | scanned.metadatas = yield* scanKeyMetadatas; |
| 236 | } |
| 237 | const reclaimed = scanned.metadatas?.find( |
| 238 | (metadata) => metadata?.Description === spec.description, |
| 239 | ); |
| 240 | const keyId = reclaimed?.KeyId |
| 241 | ? yield* reviveKey(reclaimed).pipe(Effect.map(() => reclaimed.KeyId!)) |
| 242 | : yield* kms |
| 243 | .createKey({ |
| 244 | Description: spec.description, |
| 245 | KeySpec: spec.keySpec, |
| 246 | KeyUsage: spec.keyUsage, |
| 247 | Tags: [{ TagKey: "alchemy:standing-fixture", TagValue: "kms-bindings" }], |
| 248 | }) |
| 249 | .pipe( |
| 250 | Effect.flatMap((created) => |
| 251 | created.KeyMetadata?.KeyId |
| 252 | ? Effect.succeed(created.KeyMetadata.KeyId) |
| 253 | : Effect.die(new Error("createKey returned no key ID")), |
| 254 | ), |
| 255 | ); |
| 256 | |
| 257 | yield* kms.createAlias({ AliasName: spec.alias, TargetKeyId: keyId }).pipe( |
| 258 | // DescribeKey reaches Enabled before CreateAlias's internal view of the |
| 259 | // key always converges. Retry only that exact transient state error. |
| 260 | Effect.retry({ |
| 261 | while: (error) => error._tag === "KMSInvalidStateException", |
| 262 | schedule: Schedule.max([Schedule.fixed("250 millis"), Schedule.recurs(40)]), |
| 263 | }), |
| 264 | Effect.catchTag("AlreadyExistsException", () => |
| 265 | // Lost a create race with a parallel run: the alias already points at |
| 266 | // another key. Schedule ours for deletion so it doesn't become an |
| 267 | // orphan, and fall through to the alias's actual target. |
| 268 | kms.scheduleKeyDeletion({ KeyId: keyId, PendingWindowInDays: 7 }).pipe(Effect.ignore), |
| 269 | ), |
| 270 | ); |
| 271 | // CreateAlias is eventually consistent: the immediate read-back can 404 |
| 272 | // under load. Retry the alias lookup for a bounded window. |
| 273 | const described = yield* kms.describeKey({ KeyId: spec.alias }).pipe( |
| 274 | Effect.retry({ |
| 275 | while: (error) => error._tag === "NotFoundException", |
| 276 | schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(8)]), |
| 277 | }), |
| 278 | ); |
| 279 | return described.KeyMetadata!.KeyId; |
| 280 | }); |
| 281 | |
| 282 | /** Acquire all four standing keys; returns the symmetric key's id. */ |
| 283 | const ensureStandingKeys = Effect.gen(function* () { |
| 284 | const scanned: { metadatas?: readonly (kms.KeyMetadata | undefined)[] } = {}; |
| 285 | let symmetricKeyId = ""; |
| 286 | for (const spec of STANDING_KEYS) { |
| 287 | const keyId = yield* ensureStandingKey(spec, scanned); |
| 288 | if (spec.alias === STANDING_KEY_ALIAS) { |
| 289 | symmetricKeyId = keyId; |
| 290 | } |
| 291 | } |
| 292 | return symmetricKeyId; |
| 293 | }); |
| 294 | |
| 295 | /** |
| 296 | * Release the shared test keys: delete each alias and schedule its key for |
| 297 | * deletion (7-day minimum window — KMS keys cannot be hard-deleted) so a |
| 298 | * passing run leaves no aliases and no enabled/billed keys behind. |
| 299 | * Idempotent — tolerates aliases/keys already gone or keys already pending |
| 300 | * deletion (a concurrent run's release, or a re-run after partial teardown). |
| 301 | */ |
| 302 | const releaseStandingKeys = Effect.gen(function* () { |
| 303 | const scanned: { metadatas?: readonly (kms.KeyMetadata | undefined)[] } = {}; |
| 304 | for (const spec of STANDING_KEYS) { |
| 305 | const viaAlias = yield* kms.describeKey({ KeyId: spec.alias }).pipe( |
| 306 | Effect.map((response) => response.KeyMetadata), |
| 307 | Effect.catchTag("NotFoundException", () => Effect.succeed(undefined)), |
| 308 | ); |
| 309 | |
| 310 | yield* kms |
| 311 | .deleteAlias({ AliasName: spec.alias }) |
| 312 | .pipe(Effect.catchTag("NotFoundException", () => Effect.void)); |
| 313 | |
| 314 | // If the alias was already gone (interrupted earlier release), fall back |
| 315 | // to the description lookup so an enabled key never survives teardown. |
| 316 | if (viaAlias === undefined && scanned.metadatas === undefined) { |
| 317 | scanned.metadatas = yield* scanKeyMetadatas; |
| 318 | } |
| 319 | const target = |
| 320 | viaAlias ?? scanned.metadatas?.find((metadata) => metadata?.Description === spec.description); |
| 321 | if (target?.KeyId && target.KeyState !== "PendingDeletion") { |
| 322 | yield* kms.scheduleKeyDeletion({ KeyId: target.KeyId, PendingWindowInDays: 7 }).pipe( |
| 323 | // Already pending deletion (raced with another run) or already gone. |
| 324 | Effect.catchTag(["KMSInvalidStateException", "NotFoundException"], () => Effect.void), |
| 325 | ); |
| 326 | } |
| 327 | } |
| 328 | }); |
| 329 | |
| 330 | describe( |
| 331 | "KMS Bindings", |
| 332 | { tags: ["provider:aws", "provider:aws:kms", "provider:aws:lambda", "live"] }, |
| 333 | () => { |
| 334 | beforeAll( |
| 335 | Effect.gen(function* () { |
| 336 | yield* Effect.logInfo("KMS test setup: ensuring standing keys"); |
| 337 | // `beforeAll` doesn't run inside `test.provider`'s environment, so |
| 338 | // provide the AWS providers (Credentials/Region) explicitly for the |
| 339 | // out-of-band distilled calls. |
| 340 | standingKeyId = yield* Core.withProviders(ensureStandingKeys, testOptions, "KMSBindings"); |
| 341 | yield* Effect.logInfo( |
| 342 | `KMS test setup: standing key ${standingKeyId} (${STANDING_KEY_ALIAS})`, |
| 343 | ); |
| 344 | |
| 345 | yield* Effect.logInfo("KMS test setup: destroying previous resources"); |
| 346 | yield* sharedStack.destroy(); |
| 347 | |
| 348 | yield* Effect.logInfo("KMS test setup: deploying fixture"); |
| 349 | const { functionUrl } = yield* sharedStack.deploy( |
| 350 | Effect.gen(function* () { |
| 351 | return yield* KMSTestFunction; |
| 352 | }).pipe(Effect.provide(KMSTestFunctionLive)), |
| 353 | ); |
| 354 | |
| 355 | expect(functionUrl).toBeTruthy(); |
| 356 | baseUrl = functionUrl!.replace(/\/+$/, ""); |
| 357 | |
| 358 | yield* Effect.logInfo(`KMS test setup: probing readiness at ${baseUrl}/ready`); |
| 359 | yield* HttpClient.get(`${baseUrl}/ready`).pipe( |
| 360 | Effect.flatMap((response) => |
| 361 | response.status === 200 |
| 362 | ? Effect.succeed(response) |
| 363 | : Effect.fail(new Error(`Function not ready: ${response.status}`)), |
| 364 | ), |
| 365 | Effect.retry({ schedule: readinessPolicy }), |
| 366 | ); |
| 367 | |
| 368 | // The fresh Lambda role's IAM policy propagates eventually — /ready |
| 369 | // exercises no KMS permission, so also probe a full encrypt/decrypt |
| 370 | // round-trip plus one operation per standing key (bounded) before |
| 371 | // letting the tests run. Without this the first calls occasionally |
| 372 | // land before the role policy is authorized. |
| 373 | yield* Effect.logInfo("KMS test setup: probing crypto authorization"); |
| 374 | yield* Effect.gen(function* () { |
| 375 | const probePlaintext = yield* toBase64("kms-iam-propagation-probe"); |
| 376 | const encrypted = (yield* postJson("/encrypt", { plaintextBase64: probePlaintext })) as { |
| 377 | ciphertextBase64?: string; |
| 378 | }; |
| 379 | if (!encrypted.ciphertextBase64) { |
| 380 | return yield* Effect.fail(new CryptoNotAuthorized()); |
| 381 | } |
| 382 | const decrypted = (yield* postJson("/decrypt", { |
| 383 | ciphertextBase64: encrypted.ciphertextBase64, |
| 384 | })) as { ok: boolean }; |
| 385 | if (!decrypted.ok) { |
| 386 | return yield* Effect.fail(new CryptoNotAuthorized()); |
| 387 | } |
| 388 | const mac = (yield* postJson("/mac", { messageBase64: probePlaintext })) as { |
| 389 | macBase64?: string; |
| 390 | }; |
| 391 | if (!mac.macBase64) { |
| 392 | return yield* Effect.fail(new CryptoNotAuthorized()); |
| 393 | } |
| 394 | const signed = (yield* postJson("/sign", { messageBase64: probePlaintext })) as { |
| 395 | signatureBase64?: string; |
| 396 | }; |
| 397 | if (!signed.signatureBase64) { |
| 398 | return yield* Effect.fail(new CryptoNotAuthorized()); |
| 399 | } |
| 400 | }).pipe( |
| 401 | Effect.retry({ |
| 402 | while: (error) => error._tag === "CryptoNotAuthorized", |
| 403 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]), |
| 404 | }), |
| 405 | ); |
| 406 | }), |
| 407 | { timeout: 240_000 }, |
| 408 | ); |
| 409 | |
| 410 | // Release the out-of-band keys even if the stack destroy fails — a passing |
| 411 | // (or failing) run must never leave enabled KMS keys behind. |
| 412 | afterAll( |
| 413 | sharedStack |
| 414 | .destroy() |
| 415 | .pipe( |
| 416 | Effect.ensuring( |
| 417 | Core.withProviders(releaseStandingKeys, testOptions, "KMSBindings").pipe(Effect.orDie), |
| 418 | ), |
| 419 | ), |
| 420 | { timeout: 120_000 }, |
| 421 | ); |
| 422 | |
| 423 | describe("Encrypt", () => { |
| 424 | test.provider("encrypts a payload under the standing key", (_stack) => |
| 425 | Effect.gen(function* () { |
| 426 | const plaintextBase64 = yield* toBase64("alchemy kms encrypt"); |
| 427 | const response = (yield* postJson("/encrypt", { plaintextBase64 })) as { |
| 428 | keyId?: string; |
| 429 | ciphertextBase64?: string; |
| 430 | }; |
| 431 | |
| 432 | expect(response.ciphertextBase64).toBeTruthy(); |
| 433 | expect(response.ciphertextBase64).not.toEqual(plaintextBase64); |
| 434 | // KMS resolves the alias and reports the backing key ARN. |
| 435 | expect(response.keyId).toContain(standingKeyId); |
| 436 | }), |
| 437 | ); |
| 438 | }); |
| 439 | |
| 440 | describe("Decrypt", () => { |
| 441 | test.provider("round-trips plaintext through encrypt/decrypt", (_stack) => |
| 442 | Effect.gen(function* () { |
| 443 | const message = "alchemy kms round-trip: attack at dawn"; |
| 444 | const encrypted = (yield* postJson("/encrypt", { |
| 445 | plaintextBase64: yield* toBase64(message), |
| 446 | context: { tenant: "alchemy-test" }, |
| 447 | })) as { ciphertextBase64: string }; |
| 448 | |
| 449 | const decrypted = (yield* postJson("/decrypt", { |
| 450 | ciphertextBase64: encrypted.ciphertextBase64, |
| 451 | context: { tenant: "alchemy-test" }, |
| 452 | })) as { ok: boolean; keyId?: string; plaintextBase64?: string }; |
| 453 | |
| 454 | expect(decrypted.ok).toBe(true); |
| 455 | expect(yield* fromBase64(decrypted.plaintextBase64!)).toEqual(message); |
| 456 | expect(decrypted.keyId).toContain(standingKeyId); |
| 457 | }), |
| 458 | ); |
| 459 | |
| 460 | test.provider("fails with a typed InvalidCiphertextException on context mismatch", (_stack) => |
| 461 | Effect.gen(function* () { |
| 462 | const encrypted = (yield* postJson("/encrypt", { |
| 463 | plaintextBase64: yield* toBase64("context-bound secret"), |
| 464 | context: { tenant: "alpha" }, |
| 465 | })) as { ciphertextBase64: string }; |
| 466 | |
| 467 | const decrypted = (yield* postJson("/decrypt", { |
| 468 | ciphertextBase64: encrypted.ciphertextBase64, |
| 469 | context: { tenant: "beta" }, |
| 470 | })) as { ok: boolean; error?: string }; |
| 471 | |
| 472 | expect(decrypted.ok).toBe(false); |
| 473 | expect(decrypted.error).toEqual("InvalidCiphertextException"); |
| 474 | }), |
| 475 | ); |
| 476 | }); |
| 477 | |
| 478 | describe("GenerateDataKey", () => { |
| 479 | test.provider("returns a plaintext data key whose ciphertext blob decrypts back", (_stack) => |
| 480 | Effect.gen(function* () { |
| 481 | const generated = (yield* postJson("/generate-data-key", {})) as { |
| 482 | keyId?: string; |
| 483 | plaintextBase64?: string; |
| 484 | ciphertextBase64?: string; |
| 485 | }; |
| 486 | |
| 487 | expect(generated.plaintextBase64).toBeTruthy(); |
| 488 | expect(generated.ciphertextBase64).toBeTruthy(); |
| 489 | expect(generated.keyId).toContain(standingKeyId); |
| 490 | // AES_256 data key = 32 bytes. |
| 491 | const dataKey = yield* Effect.sync(() => |
| 492 | Buffer.from(generated.plaintextBase64!, "base64"), |
| 493 | ); |
| 494 | expect(dataKey.length).toBe(32); |
| 495 | |
| 496 | // The encrypted copy must decrypt (via the Decrypt binding) back to |
| 497 | // the exact plaintext data key. |
| 498 | const decrypted = (yield* postJson("/decrypt", { |
| 499 | ciphertextBase64: generated.ciphertextBase64, |
| 500 | })) as { ok: boolean; plaintextBase64?: string }; |
| 501 | |
| 502 | expect(decrypted.ok).toBe(true); |
| 503 | expect(decrypted.plaintextBase64).toEqual(generated.plaintextBase64); |
| 504 | }), |
| 505 | ); |
| 506 | }); |
| 507 | |
| 508 | describe("GenerateDataKeyWithoutPlaintext", () => { |
| 509 | test.provider("returns only a ciphertext blob that decrypts to a 32-byte key", (_stack) => |
| 510 | Effect.gen(function* () { |
| 511 | const generated = (yield* postJson("/generate-data-key-without-plaintext", {})) as { |
| 512 | keyId?: string; |
| 513 | ciphertextBase64?: string; |
| 514 | }; |
| 515 | |
| 516 | expect(generated.ciphertextBase64).toBeTruthy(); |
| 517 | expect(generated.keyId).toContain(standingKeyId); |
| 518 | |
| 519 | const decrypted = (yield* postJson("/decrypt", { |
| 520 | ciphertextBase64: generated.ciphertextBase64, |
| 521 | })) as { ok: boolean; plaintextBase64?: string }; |
| 522 | |
| 523 | expect(decrypted.ok).toBe(true); |
| 524 | const dataKey = yield* Effect.sync(() => |
| 525 | Buffer.from(decrypted.plaintextBase64!, "base64"), |
| 526 | ); |
| 527 | expect(dataKey.length).toBe(32); |
| 528 | }), |
| 529 | ); |
| 530 | }); |
| 531 | |
| 532 | describe("GenerateDataKeyPair", () => { |
| 533 | test.provider( |
| 534 | "returns a key pair whose private blob decrypts back to the plaintext", |
| 535 | (_stack) => |
| 536 | Effect.gen(function* () { |
| 537 | const generated = (yield* postJson("/generate-data-key-pair", {})) as { |
| 538 | keyId?: string; |
| 539 | keyPairSpec?: string; |
| 540 | publicKeyBase64?: string; |
| 541 | privateKeyPlaintextBase64?: string; |
| 542 | privateKeyCiphertextBase64?: string; |
| 543 | }; |
| 544 | |
| 545 | expect(generated.keyPairSpec).toEqual("ECC_NIST_P256"); |
| 546 | expect(generated.publicKeyBase64).toBeTruthy(); |
| 547 | expect(generated.privateKeyPlaintextBase64).toBeTruthy(); |
| 548 | expect(generated.privateKeyCiphertextBase64).toBeTruthy(); |
| 549 | |
| 550 | const decrypted = (yield* postJson("/decrypt", { |
| 551 | ciphertextBase64: generated.privateKeyCiphertextBase64, |
| 552 | })) as { ok: boolean; plaintextBase64?: string }; |
| 553 | |
| 554 | expect(decrypted.ok).toBe(true); |
| 555 | expect(decrypted.plaintextBase64).toEqual(generated.privateKeyPlaintextBase64); |
| 556 | }), |
| 557 | ); |
| 558 | }); |
| 559 | |
| 560 | describe("GenerateDataKeyPairWithoutPlaintext", () => { |
| 561 | test.provider("returns a public key and an encrypted private key only", (_stack) => |
| 562 | Effect.gen(function* () { |
| 563 | const generated = (yield* postJson("/generate-data-key-pair-without-plaintext", {})) as { |
| 564 | publicKeyBase64?: string; |
| 565 | privateKeyCiphertextBase64?: string; |
| 566 | }; |
| 567 | |
| 568 | expect(generated.publicKeyBase64).toBeTruthy(); |
| 569 | expect(generated.privateKeyCiphertextBase64).toBeTruthy(); |
| 570 | |
| 571 | const decrypted = (yield* postJson("/decrypt", { |
| 572 | ciphertextBase64: generated.privateKeyCiphertextBase64, |
| 573 | })) as { ok: boolean; plaintextBase64?: string }; |
| 574 | expect(decrypted.ok).toBe(true); |
| 575 | expect(decrypted.plaintextBase64).toBeTruthy(); |
| 576 | }), |
| 577 | ); |
| 578 | }); |
| 579 | |
| 580 | describe("ReEncrypt", () => { |
| 581 | test.provider("rotates the encryption context without exposing the plaintext", (_stack) => |
| 582 | Effect.gen(function* () { |
| 583 | const message = "re-encrypt me in place"; |
| 584 | const encrypted = (yield* postJson("/encrypt", { |
| 585 | plaintextBase64: yield* toBase64(message), |
| 586 | context: { tenant: "alpha" }, |
| 587 | })) as { ciphertextBase64: string }; |
| 588 | |
| 589 | const reEncrypted = (yield* postJson("/re-encrypt", { |
| 590 | ciphertextBase64: encrypted.ciphertextBase64, |
| 591 | sourceContext: { tenant: "alpha" }, |
| 592 | destinationContext: { tenant: "beta" }, |
| 593 | })) as { keyId?: string; sourceKeyId?: string; ciphertextBase64?: string }; |
| 594 | |
| 595 | expect(reEncrypted.ciphertextBase64).toBeTruthy(); |
| 596 | expect(reEncrypted.ciphertextBase64).not.toEqual(encrypted.ciphertextBase64); |
| 597 | expect(reEncrypted.keyId).toContain(standingKeyId); |
| 598 | |
| 599 | const decrypted = (yield* postJson("/decrypt", { |
| 600 | ciphertextBase64: reEncrypted.ciphertextBase64, |
| 601 | context: { tenant: "beta" }, |
| 602 | })) as { ok: boolean; plaintextBase64?: string }; |
| 603 | |
| 604 | expect(decrypted.ok).toBe(true); |
| 605 | expect(yield* fromBase64(decrypted.plaintextBase64!)).toEqual(message); |
| 606 | }), |
| 607 | ); |
| 608 | }); |
| 609 | |
| 610 | describe("DescribeKey", () => { |
| 611 | test.provider("describes the bound key through the alias", (_stack) => |
| 612 | Effect.gen(function* () { |
| 613 | const described = (yield* getJson("/describe-key")) as { |
| 614 | keyId?: string; |
| 615 | keySpec?: string; |
| 616 | keyState?: string; |
| 617 | }; |
| 618 | expect(described.keyId).toEqual(standingKeyId); |
| 619 | expect(described.keySpec).toEqual("SYMMETRIC_DEFAULT"); |
| 620 | expect(described.keyState).toEqual("Enabled"); |
| 621 | }), |
| 622 | ); |
| 623 | }); |
| 624 | |
| 625 | describe("GenerateMac / VerifyMac", () => { |
| 626 | test.provider("computes an HMAC that verifies", (_stack) => |
| 627 | Effect.gen(function* () { |
| 628 | const messageBase64 = yield* toBase64("hmac-protected payload"); |
| 629 | const mac = (yield* postJson("/mac", { messageBase64 })) as { macBase64?: string }; |
| 630 | expect(mac.macBase64).toBeTruthy(); |
| 631 | |
| 632 | const verified = (yield* postJson("/verify-mac", { |
| 633 | messageBase64, |
| 634 | macBase64: mac.macBase64, |
| 635 | })) as { ok: boolean; macValid?: boolean }; |
| 636 | |
| 637 | expect(verified.ok).toBe(true); |
| 638 | expect(verified.macValid).toBe(true); |
| 639 | }), |
| 640 | ); |
| 641 | |
| 642 | test.provider("rejects a tampered message with a typed KMSInvalidMacException", (_stack) => |
| 643 | Effect.gen(function* () { |
| 644 | const mac = (yield* postJson("/mac", { |
| 645 | messageBase64: yield* toBase64("original message"), |
| 646 | })) as { macBase64?: string }; |
| 647 | |
| 648 | const verified = (yield* postJson("/verify-mac", { |
| 649 | messageBase64: yield* toBase64("tampered message"), |
| 650 | macBase64: mac.macBase64, |
| 651 | })) as { ok: boolean; error?: string }; |
| 652 | |
| 653 | expect(verified.ok).toBe(false); |
| 654 | expect(verified.error).toEqual("KMSInvalidMacException"); |
| 655 | }), |
| 656 | ); |
| 657 | }); |
| 658 | |
| 659 | describe("Sign / Verify", () => { |
| 660 | test.provider("signs a message that verifies inside KMS", (_stack) => |
| 661 | Effect.gen(function* () { |
| 662 | const messageBase64 = yield* toBase64("release-manifest-v1"); |
| 663 | const signed = (yield* postJson("/sign", { messageBase64 })) as { |
| 664 | signatureBase64?: string; |
| 665 | }; |
| 666 | expect(signed.signatureBase64).toBeTruthy(); |
| 667 | |
| 668 | const verified = (yield* postJson("/verify", { |
| 669 | messageBase64, |
| 670 | signatureBase64: signed.signatureBase64, |
| 671 | })) as { ok: boolean; signatureValid?: boolean }; |
| 672 | |
| 673 | expect(verified.ok).toBe(true); |
| 674 | expect(verified.signatureValid).toBe(true); |
| 675 | }), |
| 676 | ); |
| 677 | |
| 678 | test.provider( |
| 679 | "rejects a tampered message with a typed KMSInvalidSignatureException", |
| 680 | (_stack) => |
| 681 | Effect.gen(function* () { |
| 682 | const signed = (yield* postJson("/sign", { |
| 683 | messageBase64: yield* toBase64("original manifest"), |
| 684 | })) as { signatureBase64?: string }; |
| 685 | |
| 686 | const verified = (yield* postJson("/verify", { |
| 687 | messageBase64: yield* toBase64("forged manifest"), |
| 688 | signatureBase64: signed.signatureBase64, |
| 689 | })) as { ok: boolean; error?: string }; |
| 690 | |
| 691 | expect(verified.ok).toBe(false); |
| 692 | expect(verified.error).toEqual("KMSInvalidSignatureException"); |
| 693 | }), |
| 694 | ); |
| 695 | }); |
| 696 | |
| 697 | describe("GetPublicKey", () => { |
| 698 | test.provider("downloads the signing key's DER-encoded public key", (_stack) => |
| 699 | Effect.gen(function* () { |
| 700 | const response = (yield* getJson("/public-key")) as { |
| 701 | keyUsage?: string; |
| 702 | publicKeyBase64?: string; |
| 703 | signingAlgorithms?: string[]; |
| 704 | }; |
| 705 | expect(response.keyUsage).toEqual("SIGN_VERIFY"); |
| 706 | expect(response.publicKeyBase64).toBeTruthy(); |
| 707 | expect(response.signingAlgorithms).toContain("ECDSA_SHA_256"); |
| 708 | }), |
| 709 | ); |
| 710 | }); |
| 711 | |
| 712 | describe("DeriveSharedSecret", () => { |
| 713 | test.provider("KMS-side ECDH matches a locally computed shared secret", (_stack) => |
| 714 | Effect.gen(function* () { |
| 715 | const response = (yield* postJson("/derive-shared-secret", {})) as { |
| 716 | byteLength?: number; |
| 717 | match?: boolean; |
| 718 | }; |
| 719 | // P-256 ECDH shared secret = 32 bytes. |
| 720 | expect(response.byteLength).toBe(32); |
| 721 | expect(response.match).toBe(true); |
| 722 | }), |
| 723 | ); |
| 724 | }); |
| 725 | |
| 726 | describe("GenerateRandom", () => { |
| 727 | test.provider("returns distinct 32-byte random payloads", (_stack) => |
| 728 | Effect.gen(function* () { |
| 729 | const first = (yield* postJson("/random", {})) as { randomBase64?: string }; |
| 730 | const second = (yield* postJson("/random", {})) as { randomBase64?: string }; |
| 731 | expect(first.randomBase64).toBeTruthy(); |
| 732 | expect(second.randomBase64).toBeTruthy(); |
| 733 | const bytes = yield* Effect.sync(() => Buffer.from(first.randomBase64!, "base64")); |
| 734 | expect(bytes.length).toBe(32); |
| 735 | expect(first.randomBase64).not.toEqual(second.randomBase64); |
| 736 | }), |
| 737 | ); |
| 738 | }); |
| 739 | |
| 740 | describe("least privilege", () => { |
| 741 | test.provider( |
| 742 | "the role only receives the bound actions (kms:GetKeyRotationStatus is denied)", |
| 743 | (_stack) => |
| 744 | Effect.gen(function* () { |
| 745 | const response = (yield* getJson("/unauthorized")) as { ok: boolean; error?: string }; |
| 746 | |
| 747 | expect(response.ok).toBe(false); |
| 748 | expect(response.error).toEqual("AccessDeniedException"); |
| 749 | }), |
| 750 | ); |
| 751 | }); |
| 752 | }, |
| 753 | ); |