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

main
ts 550 lines 21.3 KB
Raw
1 import { fileURLToPath } from "node:url";
2 /**
3 * Wave 3 — Site→Router hostname binding.
4 *
5 * A router-attached site's `domain: { name, router }` declaration alone must
6 * be sufficient for the hostname to be fully provisioned: the site binds its
7 * concrete hostnames onto the Router's distribution (alias), managed
8 * certificate (SAN — replacement on change), and Route 53 record set.
9 *
10 * The ungated tests compile real compositions (no cloud calls — resource
11 * registration only) and assert on the binding rows the engine collects,
12 * which is exactly what the providers receive in `reconcile` and what the
13 * planner diffs (`diffBindings` plans an update whenever a row changes).
14 *
15 * The live suite is gated behind AWS_TEST_HOSTED_ZONE=<zone-name> because it
16 * needs a real Route 53 hosted zone (the shared testing account has none).
17 * Under the floci runner (ALCHEMY_TEST_DEV=1) the zone must exist in the
18 * emulator, and HTTP checks go through the distribution's local edge port.
19 */
20 import * as AWS from "@alchemy.run/aws";
21 import { Certificate, CertificateProvider } from "@alchemy.run/aws/ACM/Certificate";
22 import { describe, expect } from "@alchemy.run/test";
23 import * as Test from "@alchemy.run/test/Alchemy";
24 import * as acm from "@distilled.cloud/aws/acm";
25 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
26 import { Credentials } from "@distilled.cloud/aws/Credentials";
27 import type { RegionName } from "@distilled.cloud/aws/Region";
28 import * as route53 from "@distilled.cloud/aws/route-53";
29 import * as Stack from "alchemy/Stack";
30 import { Stage } from "alchemy/Stage";
31 import { inMemoryState } from "alchemy/State";
32 import * as Effect from "effect/Effect";
33 import * as FetchHttpClient from "effect/http/FetchHttpClient";
34 import * as Layer from "effect/Layer";
35 import * as Redacted from "effect/Redacted";
36 import * as Schedule from "effect/Schedule";
37
38 const { test } = Test.make({ providers: AWS.providers() });
39
40 // Anchor the fixture to the repo root regardless of the runner's cwd.
41 const fixtureDir = fileURLToPath(
42 new URL("../../../../../examples/aws-static-site/site", import.meta.url),
43 );
44
45 interface BindingRow {
46 sid: string;
47 data: any;
48 }
49
50 /**
51 * Compile a composition (registration only — no plan, no apply, no cloud
52 * calls) and return the binding rows the engine collected, keyed by target
53 * FQN. Mirrors the compile harness in test/binding-stability.test.ts.
54 */
55 const compileStack = (
56 build: Effect.Effect<any, any, any>,
57 ): Effect.Effect<
58 { bindings: Record<string, BindingRow[]>; resourceFqns: string[] },
59 never,
60 never
61 > =>
62 Effect.scoped(
63 (build as Effect.Effect<any, any, never>).pipe(
64 Stack.make({
65 name: "wave3-hostname-binding",
66 providers: Layer.empty,
67 state: inMemoryState(),
68 } as any),
69 Effect.map((compiled: any) => ({
70 bindings: compiled.bindings as Record<string, BindingRow[]>,
71 resourceFqns: Object.keys(compiled.resources) as string[],
72 })),
73 ),
74 ).pipe(Effect.provideService(Stage, "test")) as Effect.Effect<
75 { bindings: Record<string, BindingRow[]>; resourceFqns: string[] },
76 never,
77 never
78 >;
79
80 const siteRowsOf = (bindings: Record<string, BindingRow[]>) =>
81 Object.entries(bindings).flatMap(([fqn, rows]) =>
82 rows.filter((row) => row.sid.startsWith("AWS.Website.Site")).map((row) => ({ fqn, ...row })),
83 );
84
85 describe(
86 "AWS.Website Router hostname binding (composition)",
87 { tags: ["provider:aws", "provider:aws:website", "live"] },
88 () => {
89 test(
90 "attached site's domain declaration binds concrete hostnames onto the Router's distribution, certificate, and record set",
91 Effect.gen(function* () {
92 const compiled = yield* compileStack(
93 Effect.gen(function* () {
94 const router = yield* AWS.Website.Router("Router", {
95 domain: { name: "router.example.com", hostedZoneId: "Z1234567890ABC" },
96 });
97 yield* AWS.Website.StaticSite("DocsSite", {
98 path: fixtureDir,
99 domain: {
100 name: "docs.example.com",
101 // The wildcard alias is a host pattern — nothing concrete to
102 // register, so it must NOT appear in the bound hostnames.
103 aliases: ["*.preview.example.com", "assets.example.com"],
104 redirects: ["old.example.com"],
105 router,
106 path: "/docs",
107 },
108 });
109 return {};
110 }),
111 );
112
113 const expected = ["docs.example.com", "assets.example.com", "old.example.com"];
114
115 const distributionRow = (compiled.bindings["Router/Distribution"] ?? []).find(
116 (row) => row.sid === "AWS.Website.Site(DocsSite)",
117 );
118 expect(distributionRow?.data.aliases).toEqual(expected);
119
120 const certificateRow = (compiled.bindings["Router/Certificate"] ?? []).find(
121 (row) => row.sid === "AWS.Website.Site(DocsSite)",
122 );
123 expect(certificateRow?.data.subjectAlternativeNames).toEqual(expected);
124
125 const recordsRow = (compiled.bindings["Router/SiteAliasRecords"] ?? []).find(
126 (row) => row.sid === "AWS.Website.Site(DocsSite)",
127 );
128 expect(recordsRow?.data.names).toEqual(expected);
129
130 // The Router creates the record-set bind target alongside its own
131 // per-hostname alias records.
132 expect(compiled.resourceFqns).toContain("Router/SiteAliasRecords");
133 }),
134 );
135
136 test(
137 "removing the attached site removes its binding rows",
138 Effect.gen(function* () {
139 const compiled = yield* compileStack(
140 Effect.gen(function* () {
141 yield* AWS.Website.Router("Router", {
142 domain: { name: "router.example.com", hostedZoneId: "Z1234567890ABC" },
143 });
144 return {};
145 }),
146 );
147 expect(siteRowsOf(compiled.bindings)).toEqual([]);
148 }),
149 );
150
151 test(
152 "path-only and wildcard-only attachments bind nothing",
153 Effect.gen(function* () {
154 const compiled = yield* compileStack(
155 Effect.gen(function* () {
156 const router = yield* AWS.Website.Router("Router", {
157 domain: { name: "router.example.com", hostedZoneId: "Z1234567890ABC" },
158 });
159 yield* AWS.Website.StaticSite("PathOnlySite", {
160 path: fixtureDir,
161 domain: { router, path: "/path-only" },
162 });
163 yield* AWS.Website.StaticSite("WildcardSite", {
164 path: fixtureDir,
165 domain: { name: "*.example.com", router, path: "/wild" },
166 });
167 return {};
168 }),
169 );
170 expect(siteRowsOf(compiled.bindings)).toEqual([]);
171 }),
172 );
173
174 test(
175 "a Router without a domain exposes no bind targets (no certificate to cover aliases)",
176 Effect.gen(function* () {
177 const compiled = yield* compileStack(
178 Effect.gen(function* () {
179 const router = yield* AWS.Website.Router("Router", {});
180 yield* AWS.Website.StaticSite("DocsSite", {
181 path: fixtureDir,
182 domain: { name: "docs.example.com", router },
183 });
184 return { router };
185 }),
186 );
187 expect(siteRowsOf(compiled.bindings)).toEqual([]);
188 }),
189 );
190
191 test(
192 "a user-provided cert Router binds aliases and records but not the certificate",
193 Effect.gen(function* () {
194 const compiled = yield* compileStack(
195 Effect.gen(function* () {
196 const router = yield* AWS.Website.Router("Router", {
197 domain: {
198 name: "router.example.com",
199 hostedZoneId: "Z1234567890ABC",
200 cert: "arn:aws:acm:us-east-1:123456789012:certificate/abc",
201 },
202 });
203 yield* AWS.Website.StaticSite("DocsSite", {
204 path: fixtureDir,
205 domain: { name: "docs.example.com", router },
206 });
207 return {};
208 }),
209 );
210 const rows = siteRowsOf(compiled.bindings);
211 expect(rows.map((row) => row.fqn).sort()).toEqual([
212 "Router/Distribution",
213 "Router/SiteAliasRecords",
214 ]);
215 }),
216 );
217
218 test(
219 "cross-stack router refs fall back to KV host-matching only (no bindings, no error)",
220 Effect.gen(function* () {
221 const compiled = yield* compileStack(
222 Effect.gen(function* () {
223 // A hand-built structural slice, as a cross-stack consumer would
224 // assemble from another stack's outputs — carries no bindTargets.
225 const routerRef = {
226 kvStoreArn: "arn:aws:cloudfront::123456789012:key-value-store/9f6a",
227 kvNamespace: "9f6a",
228 distributionId: "E1234567890ABC",
229 distributionArn: "arn:aws:cloudfront::123456789012:distribution/E1234567890ABC",
230 url: "https://d111111abcdef8.cloudfront.net",
231 };
232 yield* AWS.Website.StaticSite("DocsSite", {
233 path: fixtureDir,
234 domain: { name: "docs.example.com", router: routerRef },
235 });
236 return {};
237 }),
238 );
239 expect(siteRowsOf(compiled.bindings)).toEqual([]);
240 // The KV route registration (host-matching) still happens.
241 expect(compiled.resourceFqns).toContain("DocsSite/RoutesUpdate");
242 }),
243 );
244
245 test(
246 // Plan-safety: ACM SANs are immutable, so a change in the BOUND SAN set
247 // must plan a certificate REPLACEMENT (create-first swap), not an
248 // in-place update. Prop/alias deltas on the Distribution ride the
249 // engine's default binding diff (any changed row plans an update).
250 "a bound SAN delta plans a certificate replacement",
251 Effect.gen(function* () {
252 const provider = yield* Certificate.Provider;
253 const olds = {
254 domainName: "router.example.com",
255 subjectAlternativeNames: [] as string[],
256 hostedZoneId: "Z1234567890ABC",
257 };
258 const base = {
259 id: "Certificate",
260 fqn: "Router/Certificate",
261 instanceId: "wave3instance",
262 olds,
263 news: olds,
264 output: undefined,
265 };
266
267 // Adding a bound hostname → replace.
268 const added = yield* provider.diff!({
269 ...base,
270 oldBindings: [],
271 newBindings: [
272 {
273 sid: "AWS.Website.Site(DocsSite)",
274 data: { subjectAlternativeNames: ["docs.example.com"] },
275 },
276 ],
277 });
278 expect(added?.action).toBe("replace");
279
280 // Removing it → replace.
281 const removed = yield* provider.diff!({
282 ...base,
283 oldBindings: [
284 {
285 sid: "AWS.Website.Site(DocsSite)",
286 data: { subjectAlternativeNames: ["docs.example.com"] },
287 },
288 ],
289 newBindings: [],
290 });
291 expect(removed?.action).toBe("replace");
292
293 // Identical bound SANs → no provider-forced action (engine noops).
294 const unchanged = yield* provider.diff!({
295 ...base,
296 oldBindings: [
297 {
298 sid: "AWS.Website.Site(DocsSite)",
299 data: { subjectAlternativeNames: ["docs.example.com"] },
300 },
301 ],
302 newBindings: [
303 {
304 sid: "AWS.Website.Site(DocsSite)",
305 data: { subjectAlternativeNames: ["docs.example.com"] },
306 },
307 ],
308 });
309 expect(unchanged).toBeUndefined();
310 }).pipe(Effect.provide(certificateProviderForDiff())),
311 { tags: ["provider:aws:acm"] },
312 );
313 },
314 );
315
316 /**
317 * The Certificate provider with dummy ambient services: `diff` is a pure
318 * SAN comparison (no network), but the provider layer and its lifecycle
319 * effects are typed against the AWS environment, so satisfy it with inert
320 * stand-ins. Composed as ONE layer so the test provides exactly once.
321 */
322 function certificateProviderForDiff() {
323 const ambient = Layer.mergeAll(
324 FetchHttpClient.layer,
325 Layer.succeed(Stack.Stack, {
326 name: "wave3-hostname-binding",
327 stage: "test",
328 resources: {},
329 bindings: {},
330 actions: {},
331 }),
332 Layer.succeed(Stage, "test"),
333 Layer.succeed(
334 Credentials,
335 Effect.succeed({
336 accessKeyId: Redacted.make("test"),
337 secretAccessKey: Redacted.make("test"),
338 sessionToken: undefined,
339 region: "us-east-1" as RegionName,
340 }),
341 ),
342 );
343 return Layer.mergeAll(CertificateProvider().pipe(Layer.provide(ambient)), ambient);
344 }
345
346 // ---------------------------------------------------------------------------
347 // Live verification — gated on AWS_TEST_HOSTED_ZONE=<zone-name> (e.g.
348 // "alchemy-test.example.com"). The shared testing account currently has NO
349 // hosted zone, so this cannot run there; it is implemented for an account
350 // that has one. The suite also folds in wave-2's deferred gated checks
351 // (cloudfrontUrl:false 301 and redirect 301), which need the same zone.
352 // ---------------------------------------------------------------------------
353
354 const testZone = process.env.AWS_TEST_HOSTED_ZONE;
355
356 // Under the floci runner the emulator serves each distribution's edge on a
357 // local plain-HTTP port (`distribution.url`, as in StaticSite.test.ts), and
358 // the test's hostnames resolve to nothing through system DNS. The edge port
359 // forwards the viewer's Host header untouched to the viewer-request function,
360 // so emulated requests hit that port and carry the hostname as `Host`.
361 const runEmulated = process.env.ALCHEMY_TEST_DEV === "1";
362
363 describe.skipIf(!testZone)(
364 "AWS.Website Router hostname binding (live)",
365 {
366 tags: [
367 "provider:aws",
368 "provider:aws:acm",
369 "provider:aws:cloudfront",
370 "provider:aws:route53",
371 "provider:aws:website",
372 "live",
373 ],
374 },
375 () => {
376 test.provider(
377 "attached site's declaration alone provisions alias + SAN + DNS and serves over HTTPS",
378 (stack) =>
379 Effect.gen(function* () {
380 yield* stack.destroy();
381
382 const zoneName = testZone!.replace(/\.$/, "");
383 const zone = yield* route53
384 .listHostedZonesByName({ DNSName: `${zoneName}.` })
385 .pipe(
386 Effect.map((response) =>
387 (response.HostedZones ?? []).find((candidate) => candidate.Name === `${zoneName}.`),
388 ),
389 );
390 if (!zone?.Id) {
391 return yield* Effect.die(
392 `AWS_TEST_HOSTED_ZONE=${zoneName} does not resolve to a hosted zone in this account`,
393 );
394 }
395 const hostedZoneId = zone.Id.replace(/^\/hostedzone\//, "");
396 const routerHost = `wave3-router.${zoneName}`;
397 const siteHost = `wave3-docs.${zoneName}`;
398 const redirectHost = `wave3-old.${zoneName}`;
399
400 const routerOnly = Effect.gen(function* () {
401 const router = yield* AWS.Website.Router("Router", {
402 domain: { name: routerHost, hostedZoneId },
403 // Wave-2 deferred gated check: default-domain requests 301 to
404 // the canonical domain.
405 cloudfrontUrl: false,
406 invalidation: { paths: "all", wait: true },
407 });
408 return { router };
409 });
410
411 const withSite = Effect.gen(function* () {
412 const { router } = yield* routerOnly;
413 const site = yield* AWS.Website.StaticSite("DocsSite", {
414 path: fixtureDir,
415 forceDestroy: true,
416 domain: {
417 name: siteHost,
418 // Wave-2 deferred gated check: redirect hostnames 301 with
419 // path + query preserved.
420 redirects: [redirectHost],
421 router,
422 },
423 });
424 return { router, site };
425 });
426
427 const deployed = yield* stack.deploy(withSite);
428 const distributionId = deployed.router.distribution.distributionId as string;
429
430 // Distribution aliases: the router's own hostname plus the site's
431 // bound hostnames (canonical + redirect).
432 const config = yield* cloudfront.getDistributionConfig({ Id: distributionId });
433 const aliases = config.DistributionConfig?.Aliases?.Items ?? [];
434 expect(aliases).toContain(routerHost);
435 expect(aliases).toContain(siteHost);
436 expect(aliases).toContain(redirectHost);
437
438 // Certificate: issued, SANs cover the bound hostnames.
439 const certificateArn = (deployed.router.certificate as any).certificateArn as string;
440 const certificate = yield* acm.describeCertificate({ CertificateArn: certificateArn });
441 expect(certificate.Certificate?.Status).toBe("ISSUED");
442 const sans = certificate.Certificate?.SubjectAlternativeNames ?? [];
443 expect(sans).toContain(siteHost);
444 expect(sans).toContain(redirectHost);
445
446 // Route 53: A-alias records exist for the bound hostnames.
447 const recordFor = (name: string) =>
448 route53
449 .listResourceRecordSets({
450 HostedZoneId: hostedZoneId,
451 StartRecordName: `${name}.`,
452 StartRecordType: "A",
453 MaxItems: 5,
454 })
455 .pipe(
456 Effect.map((response) =>
457 (response.ResourceRecordSets ?? []).find(
458 (recordSet) => recordSet.Name === `${name}.` && recordSet.Type === "A",
459 ),
460 ),
461 );
462 expect(yield* recordFor(siteHost)).toBeDefined();
463 expect(yield* recordFor(redirectHost)).toBeDefined();
464
465 // Manual-redirect fetch (the platform HttpClient follows redirects,
466 // which would hide the 301s under test). Retries ride out DNS/cert/
467 // edge propagation on freshly-created hostnames.
468 const edgeUrl = (deployed.router.distribution.url as string).replace(/\/+$/, "");
469 const fetchManual = (url: string) =>
470 Effect.tryPromise(async (signal) => {
471 const viewer = new URL(url);
472 const response = await fetch(
473 runEmulated ? `${edgeUrl}${viewer.pathname}${viewer.search}` : url,
474 {
475 signal,
476 redirect: "manual",
477 cache: "no-store",
478 headers: runEmulated
479 ? { "cache-control": "no-cache", host: viewer.host }
480 : { "cache-control": "no-cache" },
481 },
482 );
483 return {
484 status: response.status,
485 location: response.headers.get("location"),
486 };
487 });
488 const expectResponse = (
489 url: string,
490 check: (response: { status: number; location: string | null }) => boolean,
491 ) =>
492 fetchManual(url).pipe(
493 Effect.flatMap((response) =>
494 check(response)
495 ? Effect.succeed(response)
496 : Effect.fail(
497 new Error(
498 `unexpected response from ${url}: ${response.status} -> ${response.location}`,
499 ),
500 ),
501 ),
502 Effect.retry({ schedule: Schedule.exponential("2 seconds"), times: 12 }),
503 );
504
505 // HTTPS: the site serves on its own hostname (edge + DNS + TLS).
506 yield* expectResponse(`https://${siteHost}/`, (response) => response.status === 200);
507
508 // Redirect hostname 301s to the canonical site hostname, path and
509 // query preserved.
510 yield* expectResponse(
511 `https://${redirectHost}/some/path?q=1`,
512 (response) =>
513 response.status === 301 && response.location === `https://${siteHost}/some/path?q=1`,
514 );
515
516 // cloudfrontUrl:false — default-domain requests 301 to the
517 // canonical router domain.
518 const defaultDomain = deployed.router.distribution.domainName as string;
519 yield* expectResponse(
520 `https://${defaultDomain}/x?y=2`,
521 (response) =>
522 response.status === 301 && response.location === `https://${routerHost}/x?y=2`,
523 );
524
525 // Removal path: redeploy without the site — the bound hostnames must
526 // leave the distribution aliases, the certificate is replaced
527 // (create-first) with the shrunk SAN set, and the DNS records are
528 // garbage-collected from the record set.
529 const shrunk = yield* stack.deploy(routerOnly);
530 const shrunkConfig = yield* cloudfront.getDistributionConfig({
531 Id: shrunk.router.distribution.distributionId as string,
532 });
533 const shrunkAliases = shrunkConfig.DistributionConfig?.Aliases?.Items ?? [];
534 expect(shrunkAliases).toContain(routerHost);
535 expect(shrunkAliases).not.toContain(siteHost);
536 expect(shrunkAliases).not.toContain(redirectHost);
537 const shrunkCertificateArn = (shrunk.router.certificate as any).certificateArn as string;
538 expect(shrunkCertificateArn).not.toBe(certificateArn);
539 expect(yield* recordFor(siteHost)).toBeUndefined();
540 expect(yield* recordFor(redirectHost)).toBeUndefined();
541
542 yield* stack.destroy();
543 }),
544 // Two full CloudFront distribution deployments + two ACM issuances +
545 // disable→wait→delete on destroy. Same order of budget as the Router
546 // live lifecycle test (which needed 2400s), plus the cert swap.
547 { timeout: 3_000_000 },
548 );
549 },
550 );