@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 298 lines 11.9 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { ConditionalForwarder, Directory, EventTopic } from "@alchemy.run/aws/DirectoryService";
3 import { Topic } from "@alchemy.run/aws/SNS";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as ds from "@distilled.cloud/aws/directory-service";
7 import * as EC2 from "@distilled.cloud/aws/ec2";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import * as Schedule from "effect/Schedule";
11 import { getDefaultVpc } from "../DefaultVpc.ts";
12
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 // Ungated typed-error probes: prove the distilled error union carries the
16 // not-found tag this provider's read/delete paths depend on. Runs in every
17 // CI pass at near-zero cost, unlike the gated lifecycle below.
18 test.provider(
19 "describeDirectories on a nonexistent directory fails with EntityDoesNotExistException",
20 () =>
21 Effect.gen(function* () {
22 const error = yield* Effect.flip(ds.describeDirectories({ DirectoryIds: ["d-1234567890"] }));
23 expect(error._tag).toBe("EntityDoesNotExistException");
24 }),
25 { tags: ["provider:aws", "provider:aws:directoryservice", "live"] },
26 );
27
28 test.provider(
29 "describeConditionalForwarders on a nonexistent directory fails with EntityDoesNotExistException",
30 () =>
31 Effect.gen(function* () {
32 const error = yield* Effect.flip(
33 ds.describeConditionalForwarders({
34 DirectoryId: "d-1234567890",
35 RemoteDomainNames: ["partner.alchemy-test.internal"],
36 }),
37 );
38 expect(error._tag).toBe("EntityDoesNotExistException");
39 }),
40 { tags: ["provider:aws", "provider:aws:directoryservice", "live"] },
41 );
42
43 test.provider(
44 "describeEventTopics on a nonexistent directory fails with EntityDoesNotExistException",
45 () =>
46 Effect.gen(function* () {
47 const error = yield* Effect.flip(ds.describeEventTopics({ DirectoryId: "d-1234567890" }));
48 expect(error._tag).toBe("EntityDoesNotExistException");
49 }),
50 { tags: ["provider:aws", "provider:aws:directoryservice", "live"] },
51 );
52
53 test.provider(
54 "registerEventTopic on a nonexistent directory fails with EntityDoesNotExistException",
55 () =>
56 Effect.gen(function* () {
57 const error = yield* Effect.flip(
58 ds.registerEventTopic({
59 DirectoryId: "d-1234567890",
60 TopicName: "alchemy-directory-service-missing",
61 }),
62 );
63 expect(error._tag).toBe("EntityDoesNotExistException");
64 }),
65 { tags: ["provider:aws", "provider:aws:directoryservice", "live"] },
66 );
67
68 // Resolve the default VPC and two default-for-AZ subnets in DIFFERENT AZs —
69 // Directory Service launches one domain controller per subnet and requires
70 // exactly two subnets in distinct Availability Zones.
71 const defaultNetwork = Effect.gen(function* () {
72 const vpc = yield* getDefaultVpc;
73 const subnets = yield* EC2.describeSubnets({
74 Filters: [
75 { Name: "vpc-id", Values: [vpc.vpcId] },
76 { Name: "default-for-az", Values: ["true"] },
77 ],
78 });
79 const byAz = new Map<string, string>();
80 for (const subnet of subnets.Subnets ?? []) {
81 if (
82 subnet.SubnetId !== undefined &&
83 subnet.AvailabilityZone !== undefined &&
84 // Not every AZ supports every service — stick to the region's first
85 // three AZs (suffix a/b/c).
86 /[abc]$/.test(subnet.AvailabilityZone) &&
87 !byAz.has(subnet.AvailabilityZone)
88 ) {
89 byAz.set(subnet.AvailabilityZone, subnet.SubnetId);
90 }
91 }
92 const subnetIds = [...byAz.entries()]
93 .sort((l, r) => l[0].localeCompare(r[0]))
94 .map(([, id]) => id)
95 .slice(0, 2);
96 if (subnetIds.length < 2) {
97 return yield* Effect.die(new Error("default VPC is missing subnets in two distinct AZs"));
98 }
99 return { vpcId: vpc.vpcId, subnetIds };
100 });
101
102 // Deletion is verified as INITIATED (stage `Deleting`, irreversible) or
103 // fully gone. Full disappearance takes several more minutes server-side.
104 const assertDirectoryDeleting = (directoryId: string) =>
105 Effect.gen(function* () {
106 const stage = yield* ds.describeDirectories({ DirectoryIds: [directoryId] }).pipe(
107 Effect.map((r) => r.DirectoryDescriptions?.[0]?.Stage ?? ("gone" as const)),
108 Effect.catchTag("EntityDoesNotExistException", () => Effect.succeed("gone" as const)),
109 );
110 if (stage !== "gone" && stage !== "Deleting" && stage !== "Deleted") {
111 return yield* Effect.fail(
112 new Error(`directory '${directoryId}' still exists (stage: ${stage})`),
113 );
114 }
115 }).pipe(
116 Effect.retry({
117 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(18)]),
118 }),
119 );
120
121 // Simple AD is closed to new customers: CreateDirectory fails with "Simple
122 // AD is no longer open to new customers. For capabilities similar to Simple
123 // AD, explore AWS Managed Microsoft AD." (wire ClientException, typed as
124 // SimpleADClosedToNewCustomers). See
125 // https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_simple_ad.html
126 // This ungated probe pins the typed rejection; it targets a nonexistent VPC
127 // so it can never create a billable directory even if Simple AD reopens (it
128 // would then fail with a different tag — re-enable the lifecycle below).
129 test.provider(
130 "createDirectory (Simple AD) is rejected with a typed SimpleADClosedToNewCustomers",
131 () =>
132 Effect.gen(function* () {
133 const error = yield* Effect.flip(
134 ds.createDirectory({
135 Name: "closed-probe.alchemy-test.internal",
136 Password: "AlchemyTest123!",
137 Size: "Small",
138 VpcSettings: {
139 VpcId: "vpc-00000000000000000",
140 SubnetIds: ["subnet-00000000000000000", "subnet-00000000000000001"],
141 },
142 }),
143 );
144 expect(error._tag).toBe("SimpleADClosedToNewCustomers");
145 }),
146 { tags: ["provider:aws", "provider:aws:directoryservice", "live"] },
147 );
148
149 // A Simple AD directory takes ~10 minutes to provision (Microsoft AD takes
150 // 20-40) and bills hourly while it exists. Because Simple AD is closed to new
151 // customers (see the probe above), the full lifecycle is gated behind
152 // AWS_TEST_DIRECTORY=1 AND AWS_TEST_DIRECTORY_SIMPLE_AD=1 (for an account
153 // that is still an existing Simple AD customer) and always destroys what it
154 // created.
155 test.provider.skipIf(!process.env.AWS_TEST_DIRECTORY || !process.env.AWS_TEST_DIRECTORY_SIMPLE_AD)(
156 "create Simple AD directory, verify, update tags, destroy",
157 (stack) =>
158 Effect.gen(function* () {
159 yield* stack.destroy();
160
161 const network = yield* defaultNetwork;
162 const props = {
163 name: "corp.alchemy-test.internal",
164 password: Redacted.make("AlchemyTest123!"),
165 size: "Small" as const,
166 description: "alchemy directory-service test",
167 vpcId: network.vpcId,
168 subnetIds: network.subnetIds,
169 };
170
171 const buildStack = (tags: Record<string, string>) =>
172 Effect.gen(function* () {
173 const directory = yield* Directory("Corp", { ...props, tags });
174 // Directory Service's native event mechanism: publish status
175 // changes to an SNS topic.
176 const topic = yield* Topic("Status", {});
177 const eventTopic = yield* EventTopic("StatusTopic", {
178 directoryId: directory.directoryId,
179 topicName: topic.topicName,
180 });
181 return { directory, eventTopic };
182 });
183
184 const { directory, eventTopic } = yield* stack.deploy(
185 buildStack({ fixture: "directory-service" }),
186 );
187
188 expect(directory.directoryId).toMatch(/^d-/);
189 expect(directory.directoryName).toBe("corp.alchemy-test.internal");
190 expect(directory.type).toBe("SimpleAD");
191 expect(directory.stage).toBe("Active");
192 expect(directory.size).toBe("Small");
193 expect(directory.dnsIpAddrs.length).toBe(2);
194 expect(directory.vpcId).toBe(network.vpcId);
195 expect([...directory.subnetIds].sort()).toEqual([...network.subnetIds].sort());
196 expect(directory.tags.fixture).toBe("directory-service");
197 expect(directory.tags["alchemy::id"]).toBeDefined();
198
199 // Out-of-band verification via distilled.
200 const described = yield* ds.describeDirectories({
201 DirectoryIds: [directory.directoryId],
202 });
203 const observed = described.DirectoryDescriptions?.[0];
204 expect(observed?.Stage).toBe("Active");
205 expect(observed?.Type).toBe("SimpleAD");
206 expect(observed?.Name).toBe("corp.alchemy-test.internal");
207
208 // The EventTopic association registered the directory as a publisher
209 // to the SNS topic — verify out-of-band via distilled.
210 expect(eventTopic.directoryId).toBe(directory.directoryId);
211 expect(eventTopic.topicArn).toBeDefined();
212 expect(eventTopic.status).toBe("Registered");
213 const topics = yield* ds.describeEventTopics({
214 DirectoryId: directory.directoryId,
215 });
216 expect(topics.EventTopics?.map((topic) => topic.TopicName)).toContain(eventTopic.topicName);
217
218 // Tags mutate in place — a second deploy must keep the SAME directory
219 // id (no replacement) and converge the tag set.
220 const { directory: updated } = yield* stack.deploy(
221 buildStack({ fixture: "directory-service", wave: "2" }),
222 );
223 expect(updated.directoryId).toBe(directory.directoryId);
224 expect(updated.tags.wave).toBe("2");
225
226 // Destroy immediately — directories bill while they exist — and
227 // verify deletion was initiated out-of-band.
228 yield* stack.destroy();
229 yield* assertDirectoryDeleting(directory.directoryId);
230 }),
231 // directory create (~10 min) + tag-sync deploy + delete initiation.
232 {
233 tags: [
234 "provider:aws",
235 "provider:aws:directoryservice",
236 "provider:aws:ec2",
237 "provider:aws:sns",
238 "live",
239 ],
240 timeout: 2_400_000,
241 },
242 );
243
244 // Conditional forwarders require an AWS Managed Microsoft AD directory
245 // (Simple AD does not support them), which takes 20-40 minutes to provision.
246 // Gated separately behind AWS_TEST_DIRECTORY_MSAD=1.
247 test.provider.skipIf(!process.env.AWS_TEST_DIRECTORY_MSAD)(
248 "create Microsoft AD directory with conditional forwarder, update DNS, destroy",
249 (stack) =>
250 Effect.gen(function* () {
251 yield* stack.destroy();
252
253 const network = yield* defaultNetwork;
254 const directoryProps = {
255 type: "MicrosoftAD" as const,
256 name: "msad.alchemy-test.internal",
257 password: Redacted.make("AlchemyTest123!"),
258 edition: "Standard" as const,
259 vpcId: network.vpcId,
260 subnetIds: network.subnetIds,
261 };
262 const build = (dnsIpAddrs: string[]) =>
263 Effect.gen(function* () {
264 const directory = yield* Directory("MsAd", directoryProps);
265 const forwarder = yield* ConditionalForwarder("Partner", {
266 directoryId: directory.directoryId,
267 remoteDomainName: "partner.alchemy-test.internal",
268 dnsIpAddrs,
269 });
270 return { directory, forwarder };
271 });
272
273 const { directory, forwarder } = yield* stack.deploy(build(["10.200.0.2"]));
274 expect(directory.type).toBe("MicrosoftAD");
275 expect(directory.stage).toBe("Active");
276 expect(forwarder.remoteDomainName).toBe("partner.alchemy-test.internal");
277 expect(forwarder.dnsIpAddrs).toEqual(["10.200.0.2"]);
278
279 // Out-of-band verification via distilled.
280 const observed = yield* ds.describeConditionalForwarders({
281 DirectoryId: directory.directoryId,
282 RemoteDomainNames: ["partner.alchemy-test.internal"],
283 });
284 expect(observed.ConditionalForwarders?.[0]?.DnsIpAddrs).toEqual(["10.200.0.2"]);
285
286 // DNS addresses mutate in place — same directory, same forwarder.
287 const { forwarder: updated } = yield* stack.deploy(build(["10.200.0.2", "10.200.1.2"]));
288 expect([...updated.dnsIpAddrs].sort()).toEqual(["10.200.0.2", "10.200.1.2"]);
289
290 yield* stack.destroy();
291 yield* assertDirectoryDeleting(directory.directoryId);
292 }),
293 // Microsoft AD create (20-40 min) + forwarder sync + delete initiation.
294 {
295 tags: ["provider:aws", "provider:aws:directoryservice", "provider:aws:ec2", "live"],
296 timeout: 3_600_000,
297 },
298 );