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

main
ts 229 lines 9.18 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 eventbridge from "@distilled.cloud/aws/eventbridge";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import * as Schedule from "effect/Schedule";
11 import SignerTestFunctionLive, { SignerTestFunction } from "./handler";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = Test.make(testOptions);
15 const sharedStack = Core.scratchStack(testOptions, "SignerBindings");
16
17 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
18 // over 60s on a fresh deploy.
19 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
20
21 let baseUrl: string;
22 let functionArn: string;
23
24 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
25 readonly status: number;
26 readonly body: string;
27 readonly url: string;
28 }> {}
29
30 // The shared Lambda fixture occasionally answers a transient 5xx under load
31 // (cold re-init, IAM propagation on the freshly attached policy that the
32 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
33 // 4xx/assertion failure surfaces immediately.
34 const send = (request: HttpClientRequest.HttpClientRequest) =>
35 HttpClient.execute(request).pipe(
36 Effect.flatMap((response) =>
37 response.status >= 500
38 ? response.text.pipe(
39 Effect.flatMap((body) =>
40 Effect.fail(
41 new TransientUpstream({ status: response.status, body, url: request.url }),
42 ),
43 ),
44 )
45 : Effect.succeed(response),
46 ),
47 Effect.retry({
48 while: (e) => e._tag === "TransientUpstream",
49 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
50 }),
51 );
52
53 const getJson = (path: string) =>
54 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
55
56 const postJson = (path: string) =>
57 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
58
59 describe.sequential(
60 "Signer Bindings",
61 {
62 tags: ["provider:aws", "provider:aws:lambda", "provider:aws:s3", "provider:aws:signer", "live"],
63 },
64 () => {
65 beforeAll(
66 Effect.gen(function* () {
67 yield* Effect.logInfo("Signer test setup: destroying previous resources");
68 yield* sharedStack.destroy();
69
70 yield* Effect.logInfo("Signer test setup: deploying fixture");
71 const attrs = yield* sharedStack.deploy(
72 Effect.gen(function* () {
73 return yield* SignerTestFunction;
74 }).pipe(Effect.provide(SignerTestFunctionLive)),
75 );
76
77 expect(attrs.functionUrl).toBeTruthy();
78 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
79 functionArn = attrs.functionArn;
80
81 const readinessUrl = `${baseUrl}/bindings`;
82 yield* Effect.logInfo(`Signer test setup: probing readiness at ${readinessUrl}`);
83 yield* HttpClient.get(readinessUrl).pipe(
84 Effect.flatMap((response) =>
85 response.status === 200
86 ? Effect.succeed(response)
87 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
88 ),
89 Effect.tapError((error) =>
90 Effect.logWarning(`Signer test setup: fixture not ready yet (${String(error)})`),
91 ),
92 Effect.retry({ schedule: readinessPolicy }),
93 );
94 }),
95 { timeout: 300_000 },
96 );
97
98 afterAll(process.env.NO_DESTROY ? Effect.void : sharedStack.destroy(), { timeout: 180_000 });
99
100 describe("binding registration", () => {
101 test.provider("all nine capabilities initialize in the runtime", (_stack) =>
102 Effect.gen(function* () {
103 const response = (yield* getJson("/bindings")) as { bound: string[] };
104 expect(response.bound).toHaveLength(9);
105 expect(response.bound).toContain("startSigningJob");
106 expect(response.bound).toContain("signPayload");
107 expect(response.bound).toContain("revokeSigningProfile");
108 expect(response.bound).toContain("getRevocationStatus");
109 }),
110 );
111 });
112
113 describe("ListSigningPlatforms / GetSigningPlatform", () => {
114 test.provider("reads the AWS-managed platform catalog", (_stack) =>
115 Effect.gen(function* () {
116 const platforms = (yield* getJson("/platforms")) as { ids: string[] };
117 expect(platforms.ids.length).toBeGreaterThan(0);
118 expect(platforms.ids).toContain("AWSLambda-SHA384-ECDSA");
119
120 const platform = (yield* getJson("/platform?id=AWSLambda-SHA384-ECDSA")) as {
121 platformId: string;
122 revocationSupported: boolean;
123 };
124 expect(platform.platformId).toBe("AWSLambda-SHA384-ECDSA");
125 }),
126 );
127 });
128
129 describe("StartSigningJob / DescribeSigningJob / ListSigningJobs / RevokeSignature / GetRevocationStatus", () => {
130 test.provider(
131 "signs a zip end-to-end, observes the job, revokes its signature",
132 (_stack) =>
133 Effect.gen(function* () {
134 // Start: freshly-propagated IAM on the source/destination buckets
135 // can transiently reject the S3 access — re-poll bounded.
136 const started = (yield* postJson("/start").pipe(
137 Effect.repeat({
138 schedule: Schedule.spaced("5 seconds"),
139 until: (r): boolean => (r as { ok: boolean }).ok === true,
140 times: 10,
141 }),
142 )) as { ok: boolean; jobId?: string; tag?: string; message?: string };
143 if (!started.ok) {
144 throw new Error(`StartSigningJob failed: ${started.tag}: ${started.message}`);
145 }
146 const jobId = started.jobId!;
147 const query = `?id=${encodeURIComponent(jobId)}`;
148
149 // Describe: poll (bounded) until the async signing job lands. A
150 // just-started job can 404 briefly ("Pending") before it appears.
151 const job = (yield* getJson(`/job${query}`).pipe(
152 Effect.repeat({
153 schedule: Schedule.spaced("3 seconds"),
154 until: (r): boolean => {
155 const status = (r as { status: string }).status;
156 return status !== "InProgress" && status !== "Pending";
157 },
158 times: 20,
159 }),
160 )) as { status: string; signedKey?: string };
161 expect(job.status).toBe("Succeeded");
162 expect(job.signedKey).toContain("signed/");
163
164 // List: the job is enumerated account-wide.
165 const jobs = (yield* getJson("/jobs")) as { jobIds: string[] };
166 expect(jobs.jobIds).toContain(jobId);
167
168 // Revocation status check: derived ARNs round-trip through the
169 // data endpoint; Signer may reject the empty certificate-hash list
170 // with a typed ValidationException — either proves binding + IAM.
171 const revocation = (yield* getJson(`/revocation${query}`)) as {
172 ok: boolean;
173 revokedEntities?: string[];
174 tag?: string;
175 };
176 if (revocation.ok) {
177 expect(revocation.revokedEntities).toEqual([]);
178 } else {
179 expect(["ValidationException", "BadRequestException"]).toContain(revocation.tag);
180 }
181
182 // Revoke: the Lambda platform supports revocation, so revoking the
183 // completed job's signature must land.
184 const revoked = (yield* postJson(`/revoke-job${query}`)) as {
185 revoked: boolean;
186 tag?: string;
187 };
188 expect(revoked.revoked).toBe(true);
189 }),
190 { timeout: 240_000 },
191 );
192 });
193
194 describe("SignPayload", () => {
195 test.provider("synchronously signs a Notation payload with the bound profile", (_stack) =>
196 Effect.gen(function* () {
197 const signed = (yield* postJson("/sign")) as {
198 ok: boolean;
199 jobId?: string;
200 hasSignature?: boolean;
201 tag?: string;
202 };
203 if (signed.ok) {
204 expect(signed.hasSignature).toBe(true);
205 expect(signed.jobId).toBeTruthy();
206 } else {
207 // A typed rejection of the payload still proves the binding and
208 // IAM round-trip; an AccessDeniedException would not.
209 expect(["ValidationException", "BadRequestException"]).toContain(signed.tag);
210 }
211 }),
212 );
213 });
214
215 describe("consumeSigningJobEvents", { tags: ["provider:aws:eventbridge"] }, () => {
216 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
217 Effect.gen(function* () {
218 // Out-of-band via distilled: the fixture's consumeSigningJobEvents
219 // must have materialized as a rule on the default bus with the
220 // Lambda as target.
221 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
222 TargetArn: functionArn,
223 });
224 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
225 }),
226 );
227 });
228 },
229 );