The best way to control Claude Code, Codex and more from any computer or phone

main
ts 260 lines 9.72 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Schedule from "effect/Schedule";
10 import PaymentCryptographyTestFunctionLive, { PaymentCryptographyTestFunction } from "./handler.ts";
11 import { reapLeakedKeys } from "./reapKeys.ts";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "PaymentCryptoBindings");
16
17 // The whole suite deploys real Payment Cryptography keys (billed monthly),
18 // so it is gated behind AWS_TEST_PAYMENTCRYPTO=1 alongside the Key lifecycle.
19 const gated = !process.env.AWS_TEST_PAYMENTCRYPTO;
20
21 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]);
22
23 let baseUrl: string;
24
25 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
26 readonly status: number;
27 readonly body: string;
28 }> {}
29
30 // Retry transient 5xx from cold re-inits; genuine 4xx fails immediately.
31 const send = (request: HttpClientRequest.HttpClientRequest) =>
32 HttpClient.execute(request).pipe(
33 Effect.flatMap((response) =>
34 response.status >= 500
35 ? response.text.pipe(
36 Effect.flatMap((body) =>
37 Effect.fail(new TransientUpstream({ status: response.status, body })),
38 ),
39 )
40 : Effect.succeed(response),
41 ),
42 Effect.retry({
43 while: (e) => e._tag === "TransientUpstream",
44 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
45 }),
46 );
47
48 describe.skipIf(gated)(
49 "PaymentCryptography Bindings",
50 {
51 tags: [
52 "provider:aws",
53 "provider:aws:lambda",
54 "provider:aws:paymentcryptography",
55 "provider:aws:translate",
56 "live",
57 ],
58 },
59 () => {
60 beforeAll(
61 Effect.gen(function* () {
62 yield* sharedStack.destroy();
63 // Pre-clean: schedule deletion for any ACTIVE keys a previously
64 // crashed run leaked under this stack's tags (the scratch state is
65 // in-memory, so the destroy above cannot see them).
66 yield* Core.withProviders(
67 reapLeakedKeys([sharedStack.name]),
68 testOptions,
69 sharedStack.name,
70 );
71
72 const { functionUrl } = yield* sharedStack.deploy(
73 Effect.gen(function* () {
74 return yield* PaymentCryptographyTestFunction;
75 }).pipe(Effect.provide(PaymentCryptographyTestFunctionLive)),
76 );
77
78 expect(functionUrl).toBeTruthy();
79 baseUrl = functionUrl!.replace(/\/+$/, "");
80
81 yield* HttpClient.get(`${baseUrl}/health`).pipe(
82 Effect.flatMap((response) =>
83 response.status === 200
84 ? Effect.succeed(response)
85 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
86 ),
87 Effect.retry({ schedule: readinessPolicy }),
88 );
89 }).pipe(Effect.orDie),
90 { timeout: 240_000 },
91 );
92
93 // Destroy schedules key deletion (mandatory >=3 day window — keys cannot
94 // be hard-deleted, DELETE_PENDING is the terminal state a test can reach);
95 // the trailing reap catches any key the destroy missed so even a partial
96 // failure leaves nothing ACTIVE.
97 afterAll(
98 sharedStack
99 .destroy()
100 .pipe(
101 Effect.ensuring(
102 Core.withProviders(reapLeakedKeys([sharedStack.name]), testOptions, sharedStack.name),
103 ),
104 Effect.orDie,
105 ),
106 { timeout: 120_000 },
107 );
108
109 describe("EncryptData", () => {
110 test.provider("encrypts hex-encoded plaintext under the key", (_stack) =>
111 Effect.gen(function* () {
112 const response = (yield* send(
113 HttpClientRequest.bodyJsonUnsafe(
114 HttpClientRequest.post(`${baseUrl}/encrypt-decrypt`),
115 // "1234567890123456" — one full AES block, hex-encoded
116 { plainTextHex: "31323334353637383930313233343536" },
117 ),
118 ).pipe(Effect.flatMap((r) => r.json))) as {
119 keyArn: string;
120 cipherText: string;
121 plainText: string;
122 };
123
124 expect(response.keyArn).toContain(":key/");
125 expect(response.cipherText).toBeTruthy();
126 expect(response.cipherText).not.toBe("31323334353637383930313233343536");
127 }),
128 );
129 });
130
131 describe("DecryptData", () => {
132 test.provider("round-trips ciphertext back to the plaintext", (_stack) =>
133 Effect.gen(function* () {
134 const response = (yield* send(
135 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/encrypt-decrypt`), {
136 plainTextHex: "41414141414141414141414141414141",
137 }),
138 ).pipe(Effect.flatMap((r) => r.json))) as { plainText: string };
139
140 expect(response.plainText.toUpperCase()).toBe("41414141414141414141414141414141");
141 }),
142 );
143 });
144
145 describe("GenerateMac", () => {
146 test.provider("generates an HMAC over message data", (_stack) =>
147 Effect.gen(function* () {
148 const response = (yield* send(
149 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/mac`), {
150 messageDataHex: "31323334353637383930313233343536",
151 }),
152 ).pipe(Effect.flatMap((r) => r.json))) as { mac: string };
153
154 expect(response.mac).toBeTruthy();
155 expect(response.mac).toMatch(/^[0-9A-Fa-f]+$/);
156 }),
157 );
158 });
159
160 describe("VerifyMac", () => {
161 test.provider("verifies a generated MAC and rejects a tampered one", (_stack) =>
162 Effect.gen(function* () {
163 const response = (yield* send(
164 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/mac`), {
165 messageDataHex: "39393939393939393939393939393939",
166 }),
167 ).pipe(Effect.flatMap((r) => r.json))) as { verifiedKeyArn: string; tampered: string };
168
169 expect(response.verifiedKeyArn).toContain(":key/");
170 expect(response.tampered).toBe("verification-failed");
171 }),
172 );
173 });
174
175 describe("ReEncryptData", () => {
176 test.provider("translates DUKPT ciphertext to the working key and round-trips", (_stack) =>
177 Effect.gen(function* () {
178 const response = (yield* send(
179 HttpClientRequest.bodyJsonUnsafe(
180 HttpClientRequest.post(`${baseUrl}/re-encrypt`),
181 // "ABCDABCDABCDABCD" — one full AES block, hex-encoded
182 { plainTextHex: "41424344414243444142434441424344" },
183 ),
184 ).pipe(Effect.flatMap((r) => r.json))) as { outgoingKeyArn: string; plainText: string };
185
186 expect(response.outgoingKeyArn).toContain(":key/");
187 expect(response.plainText.toUpperCase()).toBe("41424344414243444142434441424344");
188 }),
189 );
190 });
191
192 describe("GenerateCardValidationData", () => {
193 test.provider("generates a CVV2 for a PAN + expiry", (_stack) =>
194 Effect.gen(function* () {
195 const response = (yield* send(
196 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/card`), {
197 pan: "9123456789012345",
198 expiry: "0130",
199 }),
200 ).pipe(Effect.flatMap((r) => r.json))) as { cvv2: string };
201
202 expect(response.cvv2).toMatch(/^\d{3}$/);
203 }),
204 );
205 });
206
207 describe("VerifyCardValidationData", () => {
208 test.provider("verifies the generated CVV2 and rejects a tampered one", (_stack) =>
209 Effect.gen(function* () {
210 const response = (yield* send(
211 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/card`), {
212 pan: "9123456789012345",
213 expiry: "0130",
214 }),
215 ).pipe(Effect.flatMap((r) => r.json))) as { verifiedKeyArn: string; tampered: string };
216
217 expect(response.verifiedKeyArn).toContain(":key/");
218 expect(response.tampered).toBe("verification-failed");
219 }),
220 );
221 });
222
223 describe("GeneratePinData / VerifyPinData / TranslatePinData", () => {
224 test.provider("issues a Visa PIN, verifies the PVV, and translates the PIN block", (_stack) =>
225 Effect.gen(function* () {
226 const response = (yield* send(
227 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/pin`), {
228 pan: "9123456789012345",
229 }),
230 ).pipe(Effect.flatMap((r) => r.json))) as {
231 pvv: string;
232 verificationKeyArn: string;
233 translatedKeyArn: string;
234 translatedPinBlock: string;
235 };
236
237 expect(response.pvv).toMatch(/^\d+$/);
238 expect(response.verificationKeyArn).toContain(":key/");
239 // The translated block comes back under the outgoing PEK.
240 expect(response.translatedKeyArn).toContain(":key/");
241 expect(response.translatedKeyArn).not.toBe(response.verificationKeyArn);
242 expect(response.translatedPinBlock).toMatch(/^[0-9A-Fa-f]+$/);
243 }),
244 );
245 });
246
247 describe("GetPublicKeyCertificate", () => {
248 test.provider("exports the public key certificate of the signing key pair", (_stack) =>
249 Effect.gen(function* () {
250 const response = (yield* send(HttpClientRequest.get(`${baseUrl}/public-key-cert`)).pipe(
251 Effect.flatMap((r) => r.json),
252 )) as { keyCertificate: string; keyCertificateChain: string };
253
254 expect(response.keyCertificate.length).toBeGreaterThan(0);
255 expect(response.keyCertificateChain.length).toBeGreaterThan(0);
256 }),
257 );
258 });
259 },
260 );