@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 368 lines 13.9 KB
Raw
1 /**
2 * ACM certificate validation through DNS adapters, live.
3 *
4 * - `Certificate({ dnsValidation: "external" })` → the adapter's retained
5 * validation records → `AWS.ACM.CertificateValidation`, published in
6 * Cloudflare and in a Route 53 zone delegated from the Cloudflare test
7 * zone.
8 * - The Route 53 default: `Certificate({ hostedZoneId })` validates inline.
9 *
10 * Skipped under --fast: ACM issuance takes minutes.
11 */
12 import * as AWS from "@alchemy.run/aws";
13 import * as Cloudflare from "@alchemy.run/cloudflare";
14 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
15 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
16 import { describe, expect } from "@alchemy.run/test";
17 import * as Test from "@alchemy.run/test/Alchemy";
18 import { withProviders } from "@alchemy.run/test/Core";
19 import * as acm from "@distilled.cloud/aws/acm";
20 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
21 import * as route53 from "@distilled.cloud/aws/route-53";
22 import * as dns from "@distilled.cloud/cloudflare/dns";
23 import * as Alchemy from "alchemy";
24 import * as DNS from "alchemy/DNS";
25 import * as Output from "alchemy/Output";
26 import * as Duration from "effect/Duration";
27 import * as Effect from "effect/Effect";
28 import * as Layer from "effect/Layer";
29 import * as Schedule from "effect/Schedule";
30 import * as Stream from "effect/Stream";
31
32 const providers = Layer.mergeAll(AWS.providers(), Cloudflare.providers());
33
34 const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
35 providers,
36 });
37
38 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
39 /** Validated through the Cloudflare zone. */
40 const CF_DOMAIN = `acm-dns-cf.${zoneName}`;
41 /** Route 53 zone delegated from the Cloudflare zone. */
42 const R53_ZONE = `acm-dns-r53.${zoneName}`;
43 /** Validated inline by the Route 53 default path. */
44 const INLINE_DOMAIN = `inline.${R53_ZONE}`;
45
46 const skipSlow = !!process.env.FAST;
47
48 const tags = [
49 "provider:aws",
50 "provider:aws:acm",
51 "provider:aws:route53",
52 "provider:cloudflare",
53 "provider:cloudflare:dns",
54 "live",
55 ];
56
57 const normalize = (name: string) => name.replace(/\.$/, "").toLowerCase();
58
59 // Certificates default to us-east-1 (CloudFront's region).
60 const withUsEast1 = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
61 effect.pipe(Effect.provideService(AwsRegion, Effect.succeed("us-east-1")));
62
63 const describeCertificate = (certificateArn: string) =>
64 withUsEast1(
65 acm
66 .describeCertificate({ CertificateArn: certificateArn })
67 .pipe(Effect.map((response) => response.Certificate)),
68 );
69
70 const waitForCertificateGone = (certificateArn: string) =>
71 withUsEast1(
72 acm.describeCertificate({ CertificateArn: certificateArn }).pipe(
73 Effect.as("present" as const),
74 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed("gone" as const)),
75 Effect.repeat({
76 schedule: Schedule.spaced("2 seconds"),
77 until: (status) => status === "gone",
78 times: 10,
79 }),
80 ),
81 );
82
83 /** Distinct validation CNAMEs ACM asks for (one per name, deduped). */
84 const distinctValidationRecords = (options: acm.DomainValidation[] | undefined) => [
85 ...new Map(
86 (options ?? []).flatMap((option) =>
87 option.ResourceRecord ? [[normalize(option.ResourceRecord.Name), option.ResourceRecord]] : [],
88 ),
89 ).values(),
90 ];
91
92 const lookupParentZoneId = Effect.gen(function* () {
93 const { accountId } = yield* yield* CloudflareEnvironment;
94 const zone = yield* findZoneByName({ accountId, name: zoneName });
95 if (!zone) {
96 return yield* Effect.die(new Error(`zone "${zoneName}" not found`));
97 }
98 return zone.id;
99 });
100
101 const cloudflareRecords = (zoneId: string, name: string, type: "CNAME" | "NS") =>
102 dns.listRecords.items({ zoneId, name: { exact: name }, type }).pipe(
103 Stream.runCollect,
104 Effect.map((chunk) =>
105 Array.from(chunk).filter((record) => normalize(record.name) === name && record.type === type),
106 ),
107 );
108
109 /** Route 53 CNAME record sets at `name`. */
110 const route53Cnames = (hostedZoneId: string, name: string) =>
111 route53
112 .listResourceRecordSets({
113 HostedZoneId: hostedZoneId,
114 StartRecordName: `${name}.`,
115 StartRecordType: "CNAME",
116 MaxItems: 1,
117 })
118 .pipe(
119 Effect.map((response) =>
120 (response.ResourceRecordSets ?? []).filter(
121 (set) => normalize(set.Name) === name && set.Type === "CNAME",
122 ),
123 ),
124 );
125
126 /**
127 * Exactly one validation CNAME per distinct name exists in Route 53,
128 * pointing at ACM's value.
129 */
130 const expectRoute53ValidationRecords = (
131 hostedZoneId: string,
132 options: acm.DomainValidation[] | undefined,
133 ) =>
134 Effect.forEach(distinctValidationRecords(options), (record) =>
135 Effect.gen(function* () {
136 const sets = yield* route53Cnames(hostedZoneId, normalize(record.Name));
137 expect(sets).toHaveLength(1);
138 expect((sets[0]!.ResourceRecords ?? []).map((r) => normalize(r.Value))).toEqual([
139 normalize(record.Value),
140 ]);
141 }),
142 );
143
144 describe.skipIf(skipSlow)("ACM validation through Cloudflare DNS (live)", { tags }, () => {
145 test.provider(
146 "an external-validated wildcard + apex certificate publishes one CNAME in Cloudflare and reaches ISSUED",
147 (stack) =>
148 Effect.gen(function* () {
149 yield* stack.destroy();
150 const zoneId = yield* lookupParentZoneId;
151
152 const [elapsed, deployed] = yield* stack
153 .deploy(
154 Effect.gen(function* () {
155 const cert = yield* AWS.ACM.Certificate("Cert", {
156 domainName: CF_DOMAIN,
157 subjectAlternativeNames: [`*.${CF_DOMAIN}`],
158 dnsValidation: "external",
159 });
160 const adapter = yield* DNS.resolve(Cloudflare.DNS.Adapter({ zone: zoneName }));
161 yield* adapter.records("CertValidation", {
162 records: Output.map(cert.domainValidationOptions, AWS.ACM.validationRecordsOf),
163 retain: true,
164 });
165 const issued = yield* AWS.ACM.CertificateValidation("CertIssued", {
166 certificateArn: cert.certificateArn,
167 });
168 return {
169 certificateArn: issued.certificateArn,
170 status: issued.status,
171 };
172 }),
173 )
174 .pipe(Effect.timed);
175 yield* Effect.logInfo(`ACM via Cloudflare DNS: issued in ${Duration.format(elapsed)}`);
176 expect(deployed.status).toBe("ISSUED");
177
178 const described = yield* describeCertificate(deployed.certificateArn);
179 expect(described?.Status).toBe("ISSUED");
180 // Apex + wildcard: two validations sharing one CNAME name.
181 expect(described?.DomainValidationOptions).toHaveLength(2);
182 const records = distinctValidationRecords(described?.DomainValidationOptions);
183 expect(records).toHaveLength(1);
184 expect(AWS.ACM.validationRecordsOf(described?.DomainValidationOptions)).toHaveLength(1);
185
186 // Exactly one DNS-only CNAME per distinct name in Cloudflare.
187 for (const record of records) {
188 const cnames = yield* cloudflareRecords(zoneId, normalize(record.Name), "CNAME");
189 expect(cnames).toHaveLength(1);
190 expect(normalize(cnames[0]!.content ?? "")).toBe(normalize(record.Value));
191 expect(cnames[0]!.proxied).toBe(false);
192 }
193
194 yield* stack.destroy();
195
196 expect(yield* waitForCertificateGone(deployed.certificateArn)).toBe("gone");
197
198 // The validation CNAMEs are retained (ACM reuses one per name
199 // across certificates). Remove this test's copies.
200 for (const record of records) {
201 const retained = yield* cloudflareRecords(zoneId, normalize(record.Name), "CNAME");
202 expect(retained).toHaveLength(1);
203 yield* Effect.forEach(retained, (r) => dns.deleteRecord({ zoneId, dnsRecordId: r.id }), {
204 discard: true,
205 });
206 }
207 }),
208 { timeout: 900_000 },
209 );
210 });
211
212 describe.skipIf(skipSlow)(
213 "ACM validation through a delegated Route 53 zone (live)",
214 { tags },
215 () => {
216 const parentZoneId = beforeAll(
217 withProviders(lookupParentZoneId, { providers }, "AcmDnsR53Delegation"),
218 );
219
220 // A Route 53 zone the internet resolves: delegated from the Cloudflare
221 // test zone with one NS record per Route 53 nameserver.
222 const Delegation = Alchemy.Stack(
223 "AcmDnsR53Delegation",
224 { providers, state: Alchemy.localState() },
225 Effect.gen(function* () {
226 const zoneId = yield* parentZoneId;
227 const zone = yield* AWS.Route53.HostedZone("Zone", {
228 name: R53_ZONE,
229 // Removes the retained validation CNAMEs with the zone.
230 forceDestroy: true,
231 });
232 // Route 53 always assigns four nameservers.
233 yield* Effect.forEach([0, 1, 2, 3], (index) =>
234 Cloudflare.DNS.Record(`Delegation${index}`, {
235 zoneId,
236 name: R53_ZONE,
237 type: "NS",
238 content: Output.map(zone.nameServers, (nameServers) => nameServers[index]!),
239 }),
240 );
241 return { hostedZoneId: zone.id, nameServers: zone.nameServers };
242 }),
243 );
244
245 const delegated = beforeAll(deploy(Delegation), { timeout: 300_000 });
246
247 afterAll.skipIf(!!process.env.NO_DESTROY)(
248 Effect.gen(function* () {
249 const zone = yield* delegated;
250 const zoneId = yield* parentZoneId;
251 yield* destroy(Delegation);
252 if (zone === undefined || zoneId === undefined) return;
253 yield* withProviders(
254 Effect.gen(function* () {
255 const status = yield* route53.getHostedZone({ Id: zone.hostedZoneId }).pipe(
256 Effect.as("present" as const),
257 Effect.catchTag("NoSuchHostedZone", () => Effect.succeed("gone" as const)),
258 Effect.repeat({
259 schedule: Schedule.spaced("2 seconds"),
260 until: (s) => s === "gone",
261 times: 10,
262 }),
263 );
264 expect(status).toBe("gone");
265 expect(yield* cloudflareRecords(zoneId, R53_ZONE, "NS")).toHaveLength(0);
266 }),
267 { providers },
268 "AcmDnsR53Delegation",
269 );
270 }),
271 { timeout: 300_000 },
272 );
273
274 test.provider(
275 "an external-validated certificate publishes its CNAME through the Route 53 adapter and reaches ISSUED",
276 (stack) =>
277 Effect.gen(function* () {
278 yield* stack.destroy();
279 const { hostedZoneId, nameServers } = yield* delegated;
280 const zoneId = yield* parentZoneId;
281
282 // The delegation is live in Cloudflare.
283 const ns = yield* cloudflareRecords(zoneId, R53_ZONE, "NS");
284 expect(ns.map((r) => normalize(r.content ?? "")).sort()).toEqual(
285 nameServers.map(normalize).sort(),
286 );
287
288 const [elapsed, deployed] = yield* stack
289 .deploy(
290 Effect.gen(function* () {
291 const cert = yield* AWS.ACM.Certificate("Cert", {
292 domainName: R53_ZONE,
293 subjectAlternativeNames: [`*.${R53_ZONE}`],
294 dnsValidation: "external",
295 });
296 const adapter = yield* DNS.resolve(AWS.Route53.Adapter({ hostedZoneId }));
297 yield* adapter.records("CertValidation", {
298 records: Output.map(cert.domainValidationOptions, AWS.ACM.validationRecordsOf),
299 retain: true,
300 });
301 const issued = yield* AWS.ACM.CertificateValidation("CertIssued", {
302 certificateArn: cert.certificateArn,
303 });
304 return {
305 certificateArn: issued.certificateArn,
306 status: issued.status,
307 };
308 }),
309 )
310 .pipe(Effect.timed);
311 yield* Effect.logInfo(`ACM via Route 53 adapter: issued in ${Duration.format(elapsed)}`);
312 expect(deployed.status).toBe("ISSUED");
313
314 const described = yield* describeCertificate(deployed.certificateArn);
315 expect(described?.Status).toBe("ISSUED");
316 expect(described?.DomainValidationOptions).toHaveLength(2);
317 expect(distinctValidationRecords(described?.DomainValidationOptions)).toHaveLength(1);
318 yield* expectRoute53ValidationRecords(hostedZoneId, described?.DomainValidationOptions);
319
320 yield* stack.destroy();
321
322 expect(yield* waitForCertificateGone(deployed.certificateArn)).toBe("gone");
323 // Retained: the zone's `forceDestroy` removes them with the zone.
324 yield* expectRoute53ValidationRecords(hostedZoneId, described?.DomainValidationOptions);
325 }),
326 { timeout: 900_000 },
327 );
328
329 test.provider(
330 "the Route 53 default validates inline and reaches ISSUED",
331 (stack) =>
332 Effect.gen(function* () {
333 yield* stack.destroy();
334 const { hostedZoneId } = yield* delegated;
335
336 const [elapsed, deployed] = yield* stack
337 .deploy(
338 Effect.gen(function* () {
339 const cert = yield* AWS.ACM.Certificate("Cert", {
340 domainName: INLINE_DOMAIN,
341 hostedZoneId,
342 });
343 return {
344 certificateArn: cert.certificateArn,
345 status: cert.status,
346 hostedZoneId: cert.hostedZoneId,
347 };
348 }),
349 )
350 .pipe(Effect.timed);
351 yield* Effect.logInfo(
352 `ACM inline Route 53 validation: issued in ${Duration.format(elapsed)}`,
353 );
354 expect(deployed.status).toBe("ISSUED");
355 expect(deployed.hostedZoneId).toBe(hostedZoneId);
356
357 const described = yield* describeCertificate(deployed.certificateArn);
358 expect(described?.Status).toBe("ISSUED");
359 yield* expectRoute53ValidationRecords(hostedZoneId, described?.DomainValidationOptions);
360
361 yield* stack.destroy();
362
363 expect(yield* waitForCertificateGone(deployed.certificateArn)).toBe("gone");
364 }),
365 { timeout: 900_000 },
366 );
367 },
368 );