@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 343 lines 13.2 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as EC2 from "@alchemy.run/aws/EC2";
3 import * as Endpoint from "@alchemy.run/aws/Endpoint";
4 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
5 import * as Region from "@alchemy.run/aws/Region";
6 import { Bucket } from "@alchemy.run/aws/S3";
7 import { Queue } from "@alchemy.run/aws/SQS";
8 import { expect } from "@alchemy.run/test";
9 import * as Test from "@alchemy.run/test/Alchemy";
10 import * as Core from "@alchemy.run/test/Core";
11 import { Credentials } from "@distilled.cloud/aws/Credentials";
12 import * as ec2 from "@distilled.cloud/aws/ec2";
13 import type { RegionName } from "@distilled.cloud/aws/Region";
14 import * as Alchemy from "alchemy";
15 /**
16 * Credential-free `alchemy dev` for AWS.
17 *
18 * THE RULING: local emulation is invisible plumbing — `alchemy dev`
19 * with zero AWS credentials must work, landing every emulatable resource in
20 * the local floci emulator, while `Alchemy.remote()` resources demand real
21 * credentials up front with a typed, actionable error.
22 *
23 * ## How zero-credentials is arranged
24 *
25 * This file exercises the real resolution path with nothing configured:
26 *
27 * 1. `Test.make({ profile: <name that exists nowhere on disk> })` — the
28 * harness's `withProfileOverride` makes `ALCHEMY_PROFILE` resolve to a
29 * profile that has no AWS (or any) section, so the real on-disk
30 * `~/.alchemy` config (e.g. the `testing` SSO profile set by
31 * `--profile testing`) is never consulted.
32 * 2. Ambient AWS_* env credentials are neutralized via the ConfigProvider
33 * seam: a masking provider is `Layer.provide`d onto `AWS.providers()`,
34 * so `AWSEnvironment.Default`'s env-var probe (`{ method: "env" }`)
35 * finds nothing even when the shell exports AWS keys. All other config
36 * (ALCHEMY_PROFILE, etc.) falls through to the harness provider.
37 *
38 * With neither a profile nor env creds, `AWSEnvironment.Default` in dev mode
39 * falls back to the local emulator environment (dummy creds, account
40 * 000000000000, endpoint localhost:4566, `ensureFloci`) instead of failing.
41 *
42 * Requires Docker (floci runs as the shared `alchemy-floci` container);
43 * emulator-touching tests are skipped when the daemon is unavailable.
44 */
45 import { CredentialsRequired } from "alchemy/Auth/Demand";
46 import { ProfileStore, type ProfileStoreService } from "alchemy/Auth/Profile";
47 import * as ConfigProvider from "effect/ConfigProvider";
48 import * as Effect from "effect/Effect";
49 import * as HttpBody from "effect/http/HttpBody";
50 import * as HttpClient from "effect/http/HttpClient";
51 import * as HttpClientRequest from "effect/http/HttpClientRequest";
52 import * as Layer from "effect/Layer";
53 import * as Redacted from "effect/Redacted";
54 import * as Result from "effect/Result";
55
56 const FLOCI_ENDPOINT = "http://localhost:4566";
57
58 /**
59 * A profile name that exists in no `~/.alchemy` config. `getProfile`
60 * returns `undefined` for it, which is exactly the "user never
61 * configured a profile" starting state.
62 */
63 const NO_CREDS_PROFILE = "credfree-dev-test-does-not-exist";
64
65 /**
66 * Config keys that could leak ambient AWS credentials (or redirect the
67 * emulator endpoint / region) from the developer's shell or .env files
68 * into the environment resolution under test.
69 */
70 const MASKED_AWS_KEYS = new Set([
71 "AWS_ACCESS_KEY_ID",
72 "AWS_SECRET_ACCESS_KEY",
73 "AWS_SESSION_TOKEN",
74 "AWS_ACCOUNT_ID",
75 "AWS_ENDPOINT_URL",
76 "AWS_PROFILE",
77 "AWS_REGION",
78 "AWS_DEFAULT_REGION",
79 ]);
80
81 /**
82 * ConfigProvider that hides the AWS_* credential keys and delegates every
83 * other lookup to the ambient provider (so ALCHEMY_PROFILE overrides and
84 * .env config still work). Provided onto `AWS.providers()` so the
85 * environment resolution captured at layer build sees a shell with no AWS
86 * credentials, regardless of what the real shell exports.
87 */
88 const maskAwsEnv = Layer.effect(
89 ConfigProvider.ConfigProvider,
90 Effect.gen(function* () {
91 const base = yield* ConfigProvider.ConfigProvider;
92 return ConfigProvider.make((path) =>
93 path.length === 1 && typeof path[0] === "string" && MASKED_AWS_KEYS.has(path[0])
94 ? Effect.succeed(undefined)
95 : base.load(path),
96 );
97 }),
98 );
99
100 const providers = AWS.providers().pipe(Layer.provide(maskAwsEnv));
101
102 // `dev: true` runs the same topology as the real `alchemy dev` command
103 // (including the RPC sidecar default for RPC-backed providers).
104 const testOptions = { providers, profile: NO_CREDS_PROFILE };
105 const { test, deploy, destroy } = Test.make({ ...testOptions, dev: true });
106
107 /**
108 * Raw (non-distilled) call against the emulator gateway — out-of-band proof
109 * that a resource exists IN THE EMULATOR, not the real cloud.
110 */
111 const rawAwsJson = Effect.fn(function* (options: {
112 service: string;
113 region: string;
114 target: string;
115 body: Record<string, unknown>;
116 }) {
117 const client = yield* HttpClient.HttpClient;
118 return yield* client.execute(
119 HttpClientRequest.post(`${FLOCI_ENDPOINT}/`).pipe(
120 HttpClientRequest.setHeaders({
121 "content-type": "application/x-amz-json-1.0",
122 "x-amz-target": options.target,
123 "x-amz-date": "20260101T000000Z",
124 authorization: `AWS4-HMAC-SHA256 Credential=test/20260101/${options.region}/${options.service}/aws4_request, SignedHeaders=host;x-amz-date, Signature=dummy`,
125 }),
126 HttpClientRequest.setBody(
127 HttpBody.text(JSON.stringify(options.body), "application/x-amz-json-1.0"),
128 ),
129 ),
130 );
131 });
132
133 /**
134 * The DX ruling, end to end: a dev deploy with NO configured profile and NO
135 * env credentials must succeed, transparently landing the resources in the
136 * local emulator. Forcing `AWSEnvironment.current` inside the stack program
137 * additionally pins the credential fallback itself: resolution yields the
138 * synthesized local environment (dummy account, emulator endpoint) instead
139 * of prompting or dying.
140 */
141 test.provider(
142 "dev deploy with zero AWS credentials lands in the local emulator",
143 (stack) =>
144 Effect.gen(function* () {
145 yield* stack.destroy();
146
147 const outputs = yield* stack.deploy(
148 Effect.gen(function* () {
149 const bucket = yield* Bucket("CredFreeBucket");
150 const queue = yield* Queue("CredFreeQueue");
151 // Force the ambient AWS environment: with no profile and no env
152 // creds, dev mode must synthesize the local emulator environment
153 // rather than prompting for credentials or failing.
154 const env = yield* AWSEnvironment.current;
155 return {
156 bucket,
157 queue,
158 accountId: env.accountId,
159 region: env.region,
160 endpoint: env.endpoint,
161 };
162 }),
163 );
164
165 // The synthesized environment IS the `{ method: "local" }` one.
166 expect(outputs.accountId).toBe("000000000000");
167 expect(outputs.region).toBe("us-east-1");
168 expect(outputs.endpoint).toBe(FLOCI_ENDPOINT);
169
170 // Emulator identities: the dummy-account ARNs prove no real AWS
171 // account was involved.
172 expect(outputs.bucket.bucketArn).toContain(outputs.bucket.bucketName);
173 expect(outputs.queue.queueArn).toContain(":000000000000:");
174 expect(outputs.queue.queueUrl).toContain(outputs.queue.queueName);
175
176 // Out-of-band: the queue exists in the emulator gateway.
177 const listQueues = yield* rawAwsJson({
178 service: "sqs",
179 region: "us-east-1",
180 target: "AmazonSQS.ListQueues",
181 body: {},
182 });
183 expect(listQueues.status).toBe(200);
184 const queues = (yield* listQueues.json) as { QueueUrls?: string[] };
185 expect(queues.QueueUrls?.some((url) => url.endsWith(`/${outputs.queue.queueName}`))).toBe(
186 true,
187 );
188
189 // Destroy must be equally credential-free (rows are stamped local).
190 yield* stack.destroy();
191
192 const after = yield* rawAwsJson({
193 service: "sqs",
194 region: "us-east-1",
195 target: "AmazonSQS.ListQueues",
196 body: {},
197 });
198 const queuesAfter = (yield* after.json) as { QueueUrls?: string[] };
199 expect(
200 queuesAfter.QueueUrls?.some((url) => url.endsWith(`/${outputs.queue.queueName}`)) ?? false,
201 ).toBe(false);
202 }),
203 { tags: ["provider:aws", "provider:aws:s3", "provider:aws:sqs", "local"], timeout: 240_000 },
204 );
205
206 /** Floci-scoped context for the raw distilled calls the test makes itself. */
207 const flociContext = Layer.mergeAll(
208 Endpoint.of(FLOCI_ENDPOINT),
209 Region.of("us-east-1"),
210 Layer.succeed(
211 Credentials,
212 Effect.succeed({
213 accessKeyId: Redacted.make("test"),
214 secretAccessKey: Redacted.make("test"),
215 sessionToken: undefined,
216 region: "us-east-1" as RegionName,
217 }),
218 ),
219 );
220
221 /**
222 * `AWS.EC2.Network` reads availability zones while it is declared, so
223 * evaluating this program needs a reachable EC2 API.
224 */
225 const NetworkStack = Alchemy.Stack(
226 "CredFreeNetwork",
227 { providers, state: Alchemy.localState() },
228 Effect.gen(function* () {
229 const network = yield* EC2.Network("Network", { cidrBlock: "10.0.0.0/16" });
230 return { vpcId: network.vpcId };
231 }),
232 );
233
234 /**
235 * `alchemy destroy` (live mode, no `--dev`) of a stage `alchemy dev` created
236 * must not evaluate the program against the real cloud (#1976). With zero
237 * credentials, evaluating `EC2.Network` live fails; destroy plans from state
238 * alone and deletes every row through the local provider its mode records.
239 */
240 test(
241 "destroy of a dev stage needs no AWS credentials",
242 Effect.gen(function* () {
243 yield* destroy(NetworkStack);
244 const { vpcId } = yield* deploy(NetworkStack);
245 expect(vpcId).toMatch(/^vpc-/);
246
247 // The same call `alchemy destroy --stage <dev stage>` makes: live mode.
248 yield* Core.destroy(testOptions, NetworkStack);
249
250 const vpcs = yield* ec2
251 .describeVpcs({ Filters: [{ Name: "vpc-id", Values: [vpcId] }] })
252 .pipe(Effect.provide(flociContext));
253 expect(vpcs.Vpcs ?? []).toEqual([]);
254 }),
255 { tags: ["provider:aws", "provider:aws:ec2", "local"], timeout: 240_000 },
256 );
257
258 /**
259 * Profile service with nothing configured. Mutation and configuration methods
260 * are tripwires: the credential-demand path must fail with the typed
261 * `CredentialsRequired` — it never starts a configure flow (logins belong to
262 * `alchemy profile edit` exclusively).
263 */
264 const unexpectedProfileMutation = Effect.die(
265 new Error("the credential-free path must not mutate profiles"),
266 );
267 const noCredsProfile: ProfileStoreService = {
268 readManifest: unexpectedProfileMutation,
269 getProfile: () => Effect.succeed(undefined),
270 ensureProfile: () => unexpectedProfileMutation,
271 createProfile: () => unexpectedProfileMutation,
272 renameProfile: () => unexpectedProfileMutation,
273 current: Effect.succeed({ name: NO_CREDS_PROFILE, source: "configuration" }),
274 setProviderConfig: () => unexpectedProfileMutation,
275 deleteProviderConfig: () => unexpectedProfileMutation,
276 deleteProfile: () => Effect.succeed(false),
277 loadProviderConfig: () => unexpectedProfileMutation,
278 };
279
280 /**
281 * The test runner exports CI=true, but the CI contract for the
282 * credential-demand seam is "use env-var credentials" — a different behavior
283 * than the one under test. Mask CI and AWS credentials at the demand seam
284 * as well as provider construction, so fake-profile wrappers and .env files
285 * cannot turn the missing-credentials assertion into an environment login.
286 */
287 const maskCredentialDemand = Layer.effect(
288 ConfigProvider.ConfigProvider,
289 Effect.gen(function* () {
290 const base = yield* ConfigProvider.ConfigProvider;
291 return ConfigProvider.make((path) =>
292 path.length === 1 &&
293 typeof path[0] === "string" &&
294 (path[0] === "CI" || MASKED_AWS_KEYS.has(path[0]))
295 ? Effect.succeed(undefined)
296 : base.load(path),
297 );
298 }),
299 );
300
301 /**
302 * The other half of the ruling: a resource pinned to the real cloud via
303 * `Alchemy.remote()` must NOT silently fall back to the emulator. With no
304 * credentials configured, the dev deploy fails up front — before apply —
305 * with the typed `CredentialsRequired` error naming the demanding resource
306 * and pointing at `alchemy profile edit`.
307 */
308 test.provider(
309 "remote() without credentials fails with a typed CredentialsRequired error",
310 (stack) =>
311 Effect.gen(function* () {
312 const result = yield* Effect.result(
313 stack
314 .deploy(
315 Effect.gen(function* () {
316 const bucket = yield* Bucket("RemoteBucket").pipe(Alchemy.remote());
317 return { bucket };
318 }),
319 )
320 .pipe(
321 // No saved profile, CI mode, or ambient AWS credentials.
322 Effect.provideService(ProfileStore, noCredsProfile),
323 Effect.provide(maskCredentialDemand),
324 ),
325 );
326
327 expect(Result.isFailure(result)).toBe(true);
328 if (Result.isFailure(result)) {
329 const error = result.failure as CredentialsRequired;
330 expect(error._tag).toBe("CredentialsRequired");
331 expect(error.provider).toBe("AWS");
332 expect(error.reason).toBe("remote");
333 expect(error.resources.some((fqn) => fqn.includes("RemoteBucket"))).toBe(true);
334 expect(error.message).toContain("AWS credentials are required");
335 expect(error.message).toContain("RemoteBucket");
336 expect(error.message).toContain(
337 `alchemy profile edit --profile ${NO_CREDS_PROFILE} --add AWS`,
338 );
339 expect(error.message).toContain("Alchemy.remote()");
340 }
341 }),
342 { tags: ["provider:aws", "provider:aws:s3", "local"], timeout: 60_000 },
343 );