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

main
ts 206 lines 8.31 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as iam from "@distilled.cloud/aws/iam";
6 import * as licensemanager from "@distilled.cloud/aws/license-manager";
7 import * as sts from "@distilled.cloud/aws/sts";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as HttpClient from "effect/http/HttpClient";
11 import * as HttpClientRequest from "effect/http/HttpClientRequest";
12 import * as Schedule from "effect/Schedule";
13 import LicenseManagerSellerFunctionLive, { LicenseManagerSellerFunction } from "./seller-handler";
14
15 const testOptions = { providers: AWS.providers() };
16 const { test, beforeAll, afterAll } = Test.make(testOptions);
17 const sharedStack = Core.scratchStack(testOptions, "LicenseManagerSeller");
18
19 // The deterministic license name the fixture issues (and sweeps) — used for
20 // the out-of-band zero-orphan verification below.
21 const FIXTURE_LICENSE_NAME = "alchemy-lm-seller-e2e";
22
23 // License Manager requires one-time account onboarding (see
24 // LicenseConfiguration.test.ts): create the service-linked role
25 // idempotently, then probe with a bounded typed retry through IAM
26 // propagation. Raw distilled calls need the AWS layer, so this runs inside
27 // `test.provider` bodies (beforeAll provides no cloud credentials).
28 const ensureOnboarded = Effect.gen(function* () {
29 yield* iam
30 .createServiceLinkedRole({ AWSServiceName: "license-manager.amazonaws.com" })
31 .pipe(Effect.catchTag("InvalidInputException", () => Effect.void));
32 yield* licensemanager.listLicenseConfigurations({ MaxResults: 1 }).pipe(
33 Effect.retry({
34 while: (e) => e._tag === "AccessDeniedException",
35 schedule: Schedule.exponential("1 second"),
36 times: 8,
37 }),
38 );
39 });
40
41 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
42 // over 60s on a fresh deploy.
43 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
44
45 let baseUrl: string;
46
47 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
48 readonly status: number;
49 readonly body: string;
50 }> {}
51
52 // The Lambda fixture occasionally answers a transient 5xx (cold re-init,
53 // IAM propagation on the freshly attached policy that the handler's
54 // `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine 4xx or
55 // assertion failure surfaces immediately.
56 const send = (request: HttpClientRequest.HttpClientRequest) =>
57 HttpClient.execute(request).pipe(
58 Effect.flatMap((response) =>
59 response.status >= 500
60 ? response.text.pipe(
61 Effect.flatMap((body) =>
62 Effect.fail(new TransientUpstream({ status: response.status, body })),
63 ),
64 )
65 : Effect.succeed(response),
66 ),
67 Effect.retry({
68 while: (e) => e._tag === "TransientUpstream",
69 schedule: Schedule.max([Schedule.exponential("2 seconds"), Schedule.recurs(4)]),
70 }),
71 );
72
73 const getJson = (path: string) =>
74 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
75
76 const postJson = (path: string) =>
77 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
78
79 describe.sequential(
80 "LicenseManager Seller Lifecycle",
81 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:licensemanager", "live"] },
82 () => {
83 beforeAll(
84 Effect.gen(function* () {
85 yield* Effect.logInfo("LicenseManager seller setup: destroying previous resources");
86 yield* sharedStack.destroy();
87
88 yield* Effect.logInfo("LicenseManager seller setup: deploying fixture");
89 const { functionUrl } = yield* sharedStack.deploy(
90 Effect.gen(function* () {
91 return yield* LicenseManagerSellerFunction;
92 }).pipe(Effect.provide(LicenseManagerSellerFunctionLive)),
93 );
94
95 expect(functionUrl).toBeTruthy();
96 baseUrl = functionUrl!.replace(/\/+$/, "");
97
98 const readinessUrl = `${baseUrl}/bindings`;
99 yield* Effect.logInfo(`LicenseManager seller setup: probing readiness at ${readinessUrl}`);
100 yield* HttpClient.get(readinessUrl).pipe(
101 Effect.flatMap((response) =>
102 response.status === 200
103 ? Effect.succeed(response)
104 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
105 ),
106 Effect.tapError((error) =>
107 Effect.logWarning(
108 `LicenseManager seller setup: fixture not ready yet (${String(error)})`,
109 ),
110 ),
111 Effect.retry({ schedule: readinessPolicy }),
112 );
113 }),
114 { timeout: 240_000 },
115 );
116
117 afterAll(sharedStack.destroy(), { timeout: 120_000 });
118
119 describe("binding registration", () => {
120 test.provider("all 9 seller-plane capabilities initialize in the runtime", (_stack) =>
121 Effect.gen(function* () {
122 const response = (yield* getJson("/bindings")) as { bound: string[] };
123 expect(response.bound).toHaveLength(9);
124 }),
125 );
126 });
127
128 describe("seller data plane", { tags: ["provider:aws:iam"] }, () => {
129 test.provider(
130 "issue -> version -> token mint/exchange -> checkout/extend/checkin -> grant -> delete",
131 (_stack) =>
132 Effect.gen(function* () {
133 yield* ensureOnboarded;
134 const { Account } = yield* sts.getCallerIdentity({});
135 const response = (yield* postJson(`/lifecycle?account=${Account}`)) as {
136 licenseArn: string;
137 licenseStatus: string | null;
138 bumpedVersion: string | null;
139 tokenListed: number;
140 accessToken: string;
141 checkedOut: boolean;
142 extended: boolean;
143 grant: string;
144 deletionStatus: string | null;
145 };
146
147 // CreateLicense issued a real license that reached AVAILABLE.
148 expect(response.licenseArn).toContain(":license:");
149 expect(response.licenseStatus).toBe("AVAILABLE");
150 // CreateLicenseVersion published version 2.
151 expect(response.bumpedVersion).toBe("2");
152 // CreateToken + ListTokens round-tripped the token metadata.
153 expect(response.tokenListed).toBe(1);
154 // GetAccessToken exchanged the (Redacted) refresh token — or
155 // surfaced one of its typed rejections; both prove the grant.
156 expect([
157 "Ok",
158 "AuthorizationException",
159 "ValidationException",
160 "AccessDeniedException",
161 "InvalidParameterValueException",
162 ]).toContain(response.accessToken);
163 // CheckoutLicense / ExtendLicenseConsumption ran for real.
164 expect(response.checkedOut).toBe(true);
165 expect(response.extended).toBe(true);
166 // CreateGrant + DeleteGrant — a self-account grant may be rejected
167 // with a typed validation error; both outcomes prove the wiring.
168 expect([
169 "CreatedAndDeleted",
170 "InvalidParameterValueException",
171 "ValidationException",
172 "AuthorizationException",
173 "ResourceLimitExceededException",
174 ]).toContain(response.grant);
175 // DeleteLicense retired it.
176 expect(["PENDING_DELETE", "DELETED"]).toContain(response.deletionStatus);
177
178 // Out-of-band zero-orphan verification via distilled: no fixture
179 // license remains AVAILABLE.
180 const { Licenses } = yield* licensemanager.listLicenses({});
181 const leftovers = (Licenses ?? []).filter(
182 (l): boolean => l.LicenseName === FIXTURE_LICENSE_NAME && l.Status === "AVAILABLE",
183 );
184 expect(leftovers).toHaveLength(0);
185 }),
186 { timeout: 120_000 },
187 );
188 });
189
190 describe("CreateGrantVersion", () => {
191 test.provider(
192 "surfaces a typed rejection for a nonexistent grant ARN (proving the grant)",
193 (_stack) =>
194 Effect.gen(function* () {
195 const response = (yield* getJson("/grant-version-invalid")) as { tag: string };
196 expect([
197 "InvalidParameterValueException",
198 "ValidationException",
199 "AuthorizationException",
200 ]).toContain(response.tag);
201 }),
202 { timeout: 60_000 },
203 );
204 });
205 },
206 );