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

main
ts 257 lines 10.4 KB
Raw
1 import crypto from "node:crypto";
2 import * as ACMPCA from "@alchemy.run/aws/ACMPCA";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import * as S3 from "@alchemy.run/aws/S3";
5 import * as Cause from "effect/Cause";
6 import * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import { HttpServerRequest } from "effect/http/HttpServerRequest";
9 import * as HttpServerResponse from "effect/http/HttpServerResponse";
10 import * as Layer from "effect/Layer";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import path from "pathe";
14
15 const main = path.resolve(import.meta.dirname, "handler.ts");
16
17 /**
18 * Deterministic bucket for audit reports (S3 names are global, but the
19 * testing account is fixed). The bucket policy must grant Amazon Web
20 * Services Private CA write access for CreateCertificateAuthorityAuditReport
21 * to succeed.
22 */
23 export const AUDIT_BUCKET_NAME = "alchemy-test-acmpca-audit-reports";
24
25 /**
26 * A static leaf CSR (checked in — fixtures are never generated at test
27 * time). The private key was discarded; the tests only need a valid CSR
28 * for the CA to sign.
29 */
30 export const LEAF_CSR = `-----BEGIN CERTIFICATE REQUEST-----
31 MIICgTCCAWkCAQAwPDEjMCEGA1UEAwwabGVhZi5hbGNoZW15LXRlc3QuaW50ZXJu
32 YWwxFTATBgNVBAoMDEFsY2hlbXkgVGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEP
33 ADCCAQoCggEBALGadvvgETlb8XMOiqRBUz/L+C3Ilc2d43TRYROvMXKnbzewzyA2
34 EyBhXYUvWvewXH6chrC8GqcgbHGLs4GyHfLE3qO6TAF8mBzdvZo8J0aKGBMZLASA
35 yq/JwwSawzGuQp818h/Qs85nxqEk8oxOQPMK3e6N7z81JC/nWEV/c9bQa5HGPiGF
36 0sMbNik5wPaMxxmt6Njx3P9DwbJWjcDaoslpY44iQrtWON3kiGVIFSE7jPX5B/Na
37 i3RZJofI/UhMZkS5sHrAboNuZ8p03AS7O+zCkLTvvD948N4FPIWUP0khZocaR+k1
38 xWgv/lFU0OBy3+SGifqb9QwcM5aD8ExN1UsCAwEAAaAAMA0GCSqGSIb3DQEBCwUA
39 A4IBAQAIk42ecyyxlCHTA6xarCx74SgptR3VyCvgFj4qErEJA/ST3l26Emx5uuAC
40 59hfZq42szQ/6VZwJTq71ThwUFPP+x3LpXRJnuHAOP2ORZ0x4LJwHlPiEZR2GFnZ
41 CWuYpynAYgAKUh0ubeFzyp/odXwemlbaFc52JuxA9gUPVuThsiFqIWH780cfA9NM
42 VIhBWsnInHBw0ffVQDbxcIRqP9qxwOIH9SHGKPXz1F5CfvSII9Z5QqeMuZwdXu7k
43 Sy1wRo1UPY6ot0Kstqs8TJVA6R220wEk5iUEg/d3Ft1W0T17I60Gx5P6LgxjTJbp
44 WDtemfBJScvPotEJ+xTh9kn81whi
45 -----END CERTIFICATE REQUEST-----`;
46
47 export class ACMPCATestFunction extends Lambda.Function<Lambda.Function>()("ACMPCATestFunction") {}
48
49 export default ACMPCATestFunction.make(
50 {
51 main,
52 functionUrl: true,
53 timeout: Duration.seconds(60),
54 },
55 Effect.gen(function* () {
56 const ca = yield* ACMPCA.CertificateAuthority("BindingsCA", {
57 subject: { commonName: "bindings.alchemy-test.internal" },
58 usageMode: "SHORT_LIVED_CERTIFICATE",
59 permanentDeletionTime: "7 days",
60 tags: { fixture: "acmpca-bindings" },
61 });
62
63 yield* S3.Bucket("AuditReports", {
64 bucketName: AUDIT_BUCKET_NAME,
65 forceDestroy: true,
66 policy: [
67 {
68 Effect: "Allow",
69 Principal: { Service: "acm-pca.amazonaws.com" },
70 Action: ["s3:PutObject", "s3:GetBucketAcl", "s3:GetBucketLocation"],
71 Resource: [`arn:aws:s3:::${AUDIT_BUCKET_NAME}`, `arn:aws:s3:::${AUDIT_BUCKET_NAME}/*`],
72 },
73 ],
74 });
75
76 const CaArn = yield* ca.certificateAuthorityArn;
77
78 // Deploy-time: creates the EventBridge rule (default bus, source
79 // aws.acm-pca) targeting this Function. Runtime firing rides on the
80 // certificates the suite issues/revokes; the test verifies the rule
81 // deploys.
82 yield* ACMPCA.consumeCertificateAuthorityEvents(
83 { kinds: ["issuance", "revocation"] },
84 (events) =>
85 Stream.runForEach(events, (event) =>
86 Effect.log(`acm-pca event: ${event["detail-type"]} -> ${event.resources.join(",")}`),
87 ),
88 );
89 const getCsr = yield* ACMPCA.GetCertificateAuthorityCsr(ca);
90 const getCaCertificate = yield* ACMPCA.GetCertificateAuthorityCertificate(ca);
91 const issueCertificate = yield* ACMPCA.IssueCertificate(ca);
92 const getCertificate = yield* ACMPCA.GetCertificate(ca);
93 const importCaCertificate = yield* ACMPCA.ImportCertificateAuthorityCertificate(ca);
94 const revokeCertificate = yield* ACMPCA.RevokeCertificate(ca);
95 const createAuditReport = yield* ACMPCA.CreateCertificateAuthorityAuditReport(ca);
96 const describeAuditReport = yield* ACMPCA.DescribeCertificateAuthorityAuditReport(ca);
97
98 // ACM PCA activation is eventually consistent: for a few seconds after
99 // ImportCertificateAuthorityCertificate flips the CA to ACTIVE, other
100 // API nodes still answer with a typed InvalidStateException. Retry that
101 // tag on a bounded schedule (~30s worst case).
102 const retryInvalidState = <A, E extends { readonly _tag: string }, R>(
103 self: Effect.Effect<A, E, R>,
104 ): Effect.Effect<A, E, R> =>
105 Effect.retry(self, {
106 while: (e): boolean => e._tag === "InvalidStateException",
107 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
108 });
109
110 // Issuance is asynchronous — poll GetCertificate while the typed
111 // in-progress tag (or a stale post-activation state read) is observed
112 // (bounded, ~30s worst case).
113 const waitForCertificate = (CertificateArn: string) =>
114 getCertificate({ CertificateArn }).pipe(
115 Effect.retry({
116 while: (e): boolean =>
117 e._tag === "RequestInProgressException" || e._tag === "InvalidStateException",
118 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
119 }),
120 );
121
122 return {
123 fetch: Effect.gen(function* () {
124 const request = yield* HttpServerRequest;
125 const url = new URL(request.originalUrl);
126 const pathname = url.pathname;
127
128 if (request.method === "GET" && pathname === "/csr") {
129 const { Csr } = yield* getCsr();
130 return yield* HttpServerResponse.json({
131 csr: Csr,
132 caArn: yield* CaArn,
133 });
134 }
135
136 if (request.method === "GET" && pathname === "/ca-certificate") {
137 const result = yield* retryInvalidState(getCaCertificate());
138 return yield* HttpServerResponse.json({
139 certificate: result.Certificate,
140 certificateChain: result.CertificateChain,
141 });
142 }
143
144 // Full activation flow: fetch the CA's CSR, self-sign it with the
145 // root template, then install the signed certificate. Exercises
146 // GetCertificateAuthorityCsr + IssueCertificate + GetCertificate +
147 // ImportCertificateAuthorityCertificate in one route.
148 if (request.method === "POST" && pathname === "/activate") {
149 const { Csr } = yield* getCsr();
150 const issued = yield* retryInvalidState(
151 issueCertificate({
152 Csr: yield* Effect.sync(() => new TextEncoder().encode(Csr!)),
153 SigningAlgorithm: "SHA256WITHRSA",
154 TemplateArn: "arn:aws:acm-pca:::template/RootCACertificate/V1",
155 Validity: { Type: "YEARS", Value: 10 },
156 }),
157 );
158 const certificate = yield* waitForCertificate(issued.CertificateArn!);
159 yield* retryInvalidState(
160 importCaCertificate({
161 Certificate: yield* Effect.sync(() =>
162 new TextEncoder().encode(certificate.Certificate!),
163 ),
164 }),
165 );
166 return yield* HttpServerResponse.json({
167 certificateArn: issued.CertificateArn,
168 });
169 }
170
171 // Issue a short-lived end-entity certificate from the checked-in
172 // leaf CSR and return its PEM.
173 if (request.method === "POST" && pathname === "/issue") {
174 const issued = yield* retryInvalidState(
175 issueCertificate({
176 Csr: yield* Effect.sync(() => new TextEncoder().encode(LEAF_CSR)),
177 SigningAlgorithm: "SHA256WITHRSA",
178 Validity: { Type: "DAYS", Value: 5 },
179 }),
180 );
181 const certificate = yield* waitForCertificate(issued.CertificateArn!);
182 return yield* HttpServerResponse.json({
183 certificateArn: issued.CertificateArn,
184 certificate: certificate.Certificate,
185 });
186 }
187
188 if (request.method === "POST" && pathname === "/revoke") {
189 const body = (yield* request.json) as unknown as {
190 certificateArn: string;
191 };
192 const certificate = yield* waitForCertificate(body.certificateArn);
193 const serial = yield* Effect.sync(
194 () => new crypto.X509Certificate(certificate.Certificate!).serialNumber,
195 );
196 yield* retryInvalidState(
197 revokeCertificate({
198 CertificateSerial: serial,
199 RevocationReason: "CESSATION_OF_OPERATION",
200 }),
201 );
202 return yield* HttpServerResponse.json({ revoked: true, serial });
203 }
204
205 // Generate an audit report into the fixture bucket and poll it out
206 // of the CREATING state (reports land asynchronously in S3).
207 if (request.method === "POST" && pathname === "/audit") {
208 const report = yield* retryInvalidState(
209 createAuditReport({
210 S3BucketName: AUDIT_BUCKET_NAME,
211 AuditReportResponseFormat: "JSON",
212 }),
213 );
214 const status = yield* describeAuditReport({
215 AuditReportId: report.AuditReportId!,
216 }).pipe(
217 Effect.repeat({
218 schedule: Schedule.spaced("2 seconds"),
219 until: (r): boolean => r.AuditReportStatus !== "CREATING",
220 times: 10,
221 }),
222 );
223 return yield* HttpServerResponse.json({
224 auditReportId: report.AuditReportId,
225 s3Key: report.S3Key,
226 status: status.AuditReportStatus,
227 });
228 }
229
230 return yield* HttpServerResponse.json(
231 { error: "Not found", method: request.method, pathname },
232 { status: 404 },
233 );
234 }).pipe(
235 // Surface the failure to the test instead of a generic Lambda 500 —
236 // the suite's `send` helper includes non-200 bodies in its error.
237 Effect.catchCause((cause) =>
238 HttpServerResponse.json({ error: Cause.pretty(cause) }, { status: 500 }),
239 ),
240 ),
241 };
242 }).pipe(
243 Effect.provide(
244 Layer.mergeAll(
245 Lambda.EventSource,
246 ACMPCA.GetCertificateAuthorityCsrHttp,
247 ACMPCA.GetCertificateAuthorityCertificateHttp,
248 ACMPCA.IssueCertificateHttp,
249 ACMPCA.GetCertificateHttp,
250 ACMPCA.ImportCertificateAuthorityCertificateHttp,
251 ACMPCA.RevokeCertificateHttp,
252 ACMPCA.CreateCertificateAuthorityAuditReportHttp,
253 ACMPCA.DescribeCertificateAuthorityAuditReportHttp,
254 ),
255 ),
256 ),
257 );