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
| 1 | import * as AWS from "@alchemy.run/aws"; |
| 2 | import { Certificate, waitForRoute53Change } from "@alchemy.run/aws/ACM/Certificate"; |
| 3 | import { HostedZone } from "@alchemy.run/aws/Route53"; |
| 4 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 5 | import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment"; |
| 6 | import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup"; |
| 7 | import { expect } from "@alchemy.run/test"; |
| 8 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 9 | import * as acm from "@distilled.cloud/aws/acm"; |
| 10 | import { Region as AwsRegion } from "@distilled.cloud/aws/Region"; |
| 11 | import * as route53 from "@distilled.cloud/aws/route-53"; |
| 12 | import * as Output from "alchemy/Output"; |
| 13 | import * as Provider from "alchemy/Provider"; |
| 14 | import { isResourceState, State, type ResourceState } from "alchemy/State"; |
| 15 | import * as Data from "effect/Data"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import * as Layer from "effect/Layer"; |
| 18 | import * as Schedule from "effect/Schedule"; |
| 19 | |
| 20 | // ACM certificates for CloudFront are provider-pinned to us-east-1; every |
| 21 | // out-of-band ACM call in this file must target the same region. |
| 22 | const withUsEast1 = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 23 | effect.pipe(Effect.provideService(AwsRegion, Effect.succeed("us-east-1"))); |
| 24 | |
| 25 | const { test } = Test.make({ |
| 26 | providers: Layer.mergeAll(AWS.providers(), Cloudflare.providers()), |
| 27 | }); |
| 28 | |
| 29 | test.provider.skipIf(!!process.env.FAST)( |
| 30 | "polls Route53 validation changes returned with resource-path IDs", |
| 31 | (stack) => |
| 32 | Effect.gen(function* () { |
| 33 | yield* stack.destroy(); |
| 34 | |
| 35 | const zone = yield* stack.deploy( |
| 36 | HostedZone("CertificateValidationZone", { |
| 37 | name: "alchemy-certificate-change-id.alchemy.", |
| 38 | forceDestroy: true, |
| 39 | }), |
| 40 | ); |
| 41 | |
| 42 | const change = yield* route53.changeResourceRecordSets({ |
| 43 | HostedZoneId: zone.id.replace(/^\/hostedzone\//, ""), |
| 44 | ChangeBatch: { |
| 45 | Comment: "ACM Route53 change ID regression test", |
| 46 | Changes: [ |
| 47 | { |
| 48 | Action: "UPSERT", |
| 49 | ResourceRecordSet: { |
| 50 | Name: `_validation.${zone.name}`, |
| 51 | Type: "TXT", |
| 52 | TTL: 60, |
| 53 | ResourceRecords: [{ Value: '"alchemy"' }], |
| 54 | }, |
| 55 | }, |
| 56 | ], |
| 57 | }, |
| 58 | }); |
| 59 | |
| 60 | expect(change.ChangeInfo.Id).toMatch(/^\/change\//); |
| 61 | const completed = yield* waitForRoute53Change(change.ChangeInfo.Id); |
| 62 | expect(completed.Status).toBe("INSYNC"); |
| 63 | |
| 64 | yield* stack.destroy(); |
| 65 | }), |
| 66 | { |
| 67 | tags: ["provider:aws", "provider:aws:acm", "provider:aws:route53", "live"], |
| 68 | timeout: 180_000, |
| 69 | }, |
| 70 | ); |
| 71 | |
| 72 | // Canonical `list()` test (AWS account/region-scoped collection): request a |
| 73 | // real ACM certificate (no DNS validation, stays PENDING_VALIDATION), resolve |
| 74 | // the provider from context via the typed `findProvider` helper, call `list()`, |
| 75 | // and assert the deployed certificate ARN appears in the exhaustively-paginated |
| 76 | // result. A PENDING certificate is fully enumerable and deletable. |
| 77 | test.provider.skipIf(!!process.env.FAST)( |
| 78 | "list enumerates the deployed certificate", |
| 79 | (stack) => |
| 80 | Effect.gen(function* () { |
| 81 | yield* stack.destroy(); |
| 82 | |
| 83 | const cert = yield* stack.deploy( |
| 84 | Effect.gen(function* () { |
| 85 | return yield* Certificate("ListCertificate", { |
| 86 | domainName: "alchemy-acm-list-test.example.com", |
| 87 | }); |
| 88 | }), |
| 89 | ); |
| 90 | |
| 91 | expect(cert.certificateArn).toBeDefined(); |
| 92 | |
| 93 | const provider = yield* Provider.findProvider(Certificate); |
| 94 | // ACM `ListCertificates` is eventually consistent — a freshly requested |
| 95 | // certificate can take a few seconds to surface in the paginated |
| 96 | // listing. Poll until our ARN appears, bounded. |
| 97 | const all = yield* Effect.gen(function* () { |
| 98 | const result = yield* provider.list(); |
| 99 | if (!result.some((c) => c.certificateArn === cert.certificateArn)) { |
| 100 | return yield* Effect.fail(new CertificateNotListed()); |
| 101 | } |
| 102 | return result; |
| 103 | }).pipe( |
| 104 | Effect.retry({ |
| 105 | while: (e) => e._tag === "CertificateNotListed", |
| 106 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]), |
| 107 | }), |
| 108 | ); |
| 109 | |
| 110 | expect(all.some((c) => c.certificateArn === cert.certificateArn)).toBe(true); |
| 111 | |
| 112 | yield* stack.destroy(); |
| 113 | }), |
| 114 | { tags: ["provider:aws", "provider:aws:acm", "live"], timeout: 120_000 }, |
| 115 | ); |
| 116 | |
| 117 | class CertificateNotListed extends Data.TaggedError("CertificateNotListed") {} |
| 118 | |
| 119 | // Exportability is fixed at request time — ACM rejects |
| 120 | // `UpdateCertificateOptions` for the export option ("Export option for |
| 121 | // certificates cannot be updated"), so changing `export` must REPLACE the |
| 122 | // certificate with a freshly requested one. |
| 123 | test.provider.skipIf(!!process.env.FAST)( |
| 124 | "replaces the certificate when the export option changes", |
| 125 | (stack) => |
| 126 | Effect.gen(function* () { |
| 127 | yield* stack.destroy(); |
| 128 | |
| 129 | const domainName = "alchemy-acm-options-test.example.com"; |
| 130 | const deployWith = (exportOption: "ENABLED" | "DISABLED") => |
| 131 | stack.deploy( |
| 132 | Certificate("OptionsCertificate", { |
| 133 | domainName, |
| 134 | export: exportOption, |
| 135 | }), |
| 136 | ); |
| 137 | |
| 138 | const created = yield* deployWith("ENABLED"); |
| 139 | expect(created.certificateArn).toBeDefined(); |
| 140 | expect(created.export).toBe("ENABLED"); |
| 141 | |
| 142 | const updated = yield* deployWith("DISABLED"); |
| 143 | expect(updated.certificateArn).not.toEqual(created.certificateArn); |
| 144 | expect(updated.export).toBe("DISABLED"); |
| 145 | |
| 146 | yield* stack.destroy(); |
| 147 | }), |
| 148 | { tags: ["provider:aws", "provider:aws:acm", "live"], timeout: 180_000 }, |
| 149 | ); |
| 150 | |
| 151 | // Regression test for https://github.com/alchemy-run/alchemy/issues/736. |
| 152 | // |
| 153 | // A `creating` state row persisted before upstream Outputs resolve cannot |
| 154 | // round-trip Output-valued props (`domainName` from a HostedZone Output, |
| 155 | // `hostedZoneId`) — they deserialize as `undefined`. In the worst case the |
| 156 | // row's props are junk and the engine's deletion-planning branch (which every |
| 157 | // `destroy` and every deploy that drops the resource runs) calls |
| 158 | // `provider.read` with those junk `olds`. Before the fix, `read` dereferenced |
| 159 | // `olds!` unconditionally (`findManagedCertificate` reads |
| 160 | // `props.keyAlgorithm` / `props.domainName`), so planning crashed with a |
| 161 | // TypeError and wedged the stack — plan/deploy/destroy all build a plan, so |
| 162 | // there was no CLI escape hatch. |
| 163 | // |
| 164 | // Simulate exactly that row after a real deploy and assert the guarded `read` |
| 165 | // reports "not found" instead of crashing: destroy succeeds (skipping the |
| 166 | // physical delete, since no attr could be recovered), and a follow-up deploy |
| 167 | // of the same program converges on the SAME leaked certificate (found by |
| 168 | // domain + SAN + alchemy ownership tags) — no duplicate is requested. |
| 169 | test.provider.skipIf(!!process.env.FAST)( |
| 170 | "recovers a wedged creating-state certificate whose props were lost (#736)", |
| 171 | (stack) => |
| 172 | Effect.gen(function* () { |
| 173 | yield* stack.destroy(); |
| 174 | |
| 175 | const domainName = "alchemy-acm-recovery-736.example.com"; |
| 176 | const deployCertificate = () => |
| 177 | stack.deploy( |
| 178 | Certificate("RecoveryCertificate", { |
| 179 | domainName, |
| 180 | // List the primary domain explicitly: ACM's DescribeCertificate |
| 181 | // reports it in SubjectAlternativeNames, and recovery-by-search |
| 182 | // (`findManagedCertificate`) compares that list against the |
| 183 | // props' SAN list — aligning them is what lets the redeploy |
| 184 | // below converge on the leaked certificate. |
| 185 | subjectAlternativeNames: [domainName], |
| 186 | }), |
| 187 | ); |
| 188 | |
| 189 | const created = yield* deployCertificate(); |
| 190 | expect(created.certificateArn).toBeDefined(); |
| 191 | |
| 192 | // Safety net: reclaim the certificate on scope close even if the body |
| 193 | // fails mid-way (e.g. during the pre-fix crash verification). |
| 194 | yield* Effect.addFinalizer(() => |
| 195 | withUsEast1(acm.deleteCertificate({ CertificateArn: created.certificateArn })).pipe( |
| 196 | Effect.ignore, |
| 197 | ), |
| 198 | ); |
| 199 | |
| 200 | // `ListCertificates` is eventually consistent; the recovery redeploy |
| 201 | // below finds the certificate through it, so wait (bounded) until the |
| 202 | // fresh ARN is visible before wedging the state. |
| 203 | yield* Effect.gen(function* () { |
| 204 | const listed = yield* withUsEast1(acm.listCertificates({})); |
| 205 | if ( |
| 206 | !listed.CertificateSummaryList?.some( |
| 207 | (summary) => summary.CertificateArn === created.certificateArn, |
| 208 | ) |
| 209 | ) { |
| 210 | return yield* Effect.fail(new CertificateNotListed()); |
| 211 | } |
| 212 | }).pipe( |
| 213 | Effect.retry({ |
| 214 | while: (e) => e._tag === "CertificateNotListed", |
| 215 | schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(18)]), |
| 216 | }), |
| 217 | ); |
| 218 | |
| 219 | // Rewrite the certificate's persisted row into the wedged shape an |
| 220 | // interrupted deploy leaves behind: `creating`, no attributes, and the |
| 221 | // props lost in the Output round-trip. |
| 222 | const state = yield* yield* State; |
| 223 | const stage = stack.stage; |
| 224 | const fqns = yield* state.list({ stack: stack.name, stage }); |
| 225 | const rows = yield* Effect.forEach(fqns, (fqn) => |
| 226 | state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))), |
| 227 | ); |
| 228 | const wedged = rows.find( |
| 229 | (r): r is { fqn: string; row: ResourceState } => |
| 230 | isResourceState(r.row) && r.row.resourceType === "AWS.ACM.Certificate", |
| 231 | ); |
| 232 | if (!wedged) { |
| 233 | return yield* Effect.die(new Error("no AWS.ACM.Certificate state row found after deploy")); |
| 234 | } |
| 235 | yield* state.set({ |
| 236 | stack: stack.name, |
| 237 | stage, |
| 238 | fqn: wedged.fqn, |
| 239 | value: { |
| 240 | ...wedged.row, |
| 241 | status: "creating", |
| 242 | attr: undefined, |
| 243 | props: undefined as never, |
| 244 | }, |
| 245 | }); |
| 246 | |
| 247 | // Deletion planning reads the wedged row with `olds: undefined`. |
| 248 | // Before the fix this crashed with |
| 249 | // `TypeError: undefined is not an object (evaluating 'props.keyAlgorithm')`; |
| 250 | // after it, `read` reports "not found", the physical delete is skipped |
| 251 | // (no attr could be recovered) and the row is reaped. |
| 252 | yield* stack.destroy(); |
| 253 | |
| 254 | // The certificate itself leaked (the wedged row had no recoverable |
| 255 | // attr) — redeploying the same program must converge on it via |
| 256 | // domain + SAN + ownership tags instead of requesting a duplicate. |
| 257 | const recovered = yield* deployCertificate(); |
| 258 | expect(recovered.certificateArn).toEqual(created.certificateArn); |
| 259 | |
| 260 | yield* stack.destroy(); |
| 261 | }), |
| 262 | { tags: ["provider:aws", "provider:aws:acm", "live"], timeout: 240_000 }, |
| 263 | ); |
| 264 | |
| 265 | // ACM issues ONE validation record shared by a name and its wildcard. The |
| 266 | // provider must upsert it once: Route 53 rejects a change batch that touches |
| 267 | // the same record twice (`InvalidChangeBatch`). |
| 268 | // |
| 269 | // Issuance needs a publicly resolvable zone, so delegate a subdomain of the |
| 270 | // Cloudflare test zone to a fresh Route 53 zone. The delegation is deployed |
| 271 | // first so ACM never sees (and negatively caches) the undelegated name. |
| 272 | const cloudflareZoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us"; |
| 273 | // One delegated subdomain per test stage (`test_$USER` by default), so |
| 274 | // concurrent runs by different developers never share NS records. |
| 275 | const wildcardDomainFor = (stage: string) => |
| 276 | `acm-wildcard-${stage.toLowerCase().replace(/[^a-z0-9-]/g, "-")}.${cloudflareZoneName}`; |
| 277 | |
| 278 | const delegatedZone = (wildcardDomain: string) => |
| 279 | Effect.gen(function* () { |
| 280 | const { accountId } = yield* yield* CloudflareEnvironment; |
| 281 | const parent = yield* findZoneByName({ accountId, name: cloudflareZoneName }); |
| 282 | if (!parent) { |
| 283 | return yield* Effect.die(new Error(`Cloudflare zone ${cloudflareZoneName} not found`)); |
| 284 | } |
| 285 | const zone = yield* HostedZone("WildcardZone", { |
| 286 | name: wildcardDomain, |
| 287 | forceDestroy: true, |
| 288 | }); |
| 289 | // Route 53 always assigns four name servers to a public hosted zone. |
| 290 | yield* Effect.forEach([0, 1, 2, 3], (i) => |
| 291 | Cloudflare.DNS.Record(`WildcardZoneNs${i}`, { |
| 292 | zoneId: parent.id, |
| 293 | name: wildcardDomain, |
| 294 | type: "NS", |
| 295 | content: zone.nameServers.pipe(Output.map((nameServers) => nameServers[i]!)), |
| 296 | ttl: 60, |
| 297 | }), |
| 298 | ); |
| 299 | return zone; |
| 300 | }); |
| 301 | |
| 302 | test.provider.skipIf(!!process.env.FAST)( |
| 303 | "validates an apex + wildcard certificate through one shared record", |
| 304 | (stack) => |
| 305 | Effect.gen(function* () { |
| 306 | yield* stack.destroy(); |
| 307 | const wildcardDomain = wildcardDomainFor(stack.stage); |
| 308 | |
| 309 | yield* stack.deploy(delegatedZone(wildcardDomain)); |
| 310 | |
| 311 | const { zone, certificate } = yield* stack.deploy( |
| 312 | Effect.gen(function* () { |
| 313 | const zone = yield* delegatedZone(wildcardDomain); |
| 314 | const certificate = yield* Certificate("WildcardCertificate", { |
| 315 | domainName: wildcardDomain, |
| 316 | subjectAlternativeNames: [wildcardDomain, `*.${wildcardDomain}`], |
| 317 | hostedZoneId: zone.id, |
| 318 | }); |
| 319 | return { zone, certificate }; |
| 320 | }), |
| 321 | ); |
| 322 | |
| 323 | const issued = yield* withUsEast1( |
| 324 | acm.describeCertificate({ CertificateArn: certificate.certificateArn }), |
| 325 | ); |
| 326 | expect(issued.Certificate?.Status).toBe("ISSUED"); |
| 327 | |
| 328 | // Both names validated through the single record ACM shares between them. |
| 329 | const options = issued.Certificate?.DomainValidationOptions ?? []; |
| 330 | expect(options.map((option) => option.DomainName).sort()).toEqual([ |
| 331 | `*.${wildcardDomain}`, |
| 332 | wildcardDomain, |
| 333 | ]); |
| 334 | expect(new Set(options.map((option) => option.ResourceRecord?.Name)).size).toBe(1); |
| 335 | |
| 336 | const records = yield* route53.listResourceRecordSets({ |
| 337 | HostedZoneId: zone.id.replace(/^\/hostedzone\//, ""), |
| 338 | }); |
| 339 | expect( |
| 340 | (records.ResourceRecordSets ?? []).filter((record) => record.Type === "CNAME"), |
| 341 | ).toHaveLength(1); |
| 342 | |
| 343 | yield* stack.destroy(); |
| 344 | const deleted = yield* withUsEast1( |
| 345 | acm.describeCertificate({ CertificateArn: certificate.certificateArn }), |
| 346 | ).pipe(Effect.flip); |
| 347 | expect(deleted._tag).toBe("ResourceNotFoundException"); |
| 348 | }), |
| 349 | { |
| 350 | tags: [ |
| 351 | "provider:aws", |
| 352 | "provider:aws:acm", |
| 353 | "provider:aws:route53", |
| 354 | "provider:cloudflare", |
| 355 | "live", |
| 356 | ], |
| 357 | timeout: 900_000, |
| 358 | }, |
| 359 | ); |