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 { 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 autoscaling from "@distilled.cloud/aws/auto-scaling"; |
| 6 | import * as eventbridge from "@distilled.cloud/aws/eventbridge"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as HttpClient from "effect/http/HttpClient"; |
| 9 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import AsgBindingsFunctionLive, { |
| 12 | AsgBindingsFunction, |
| 13 | bindingsAsgName, |
| 14 | } from "./fixtures/bindings-handler.ts"; |
| 15 | |
| 16 | const testOptions = { providers: AWS.providers() }; |
| 17 | const { test, beforeAll, afterAll } = Test.make(testOptions); |
| 18 | const sharedStack = Core.scratchStack(testOptions, "AutoScalingBindings"); |
| 19 | |
| 20 | const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]); |
| 21 | |
| 22 | let baseUrl: string; |
| 23 | |
| 24 | interface RouteResult { |
| 25 | ok: boolean; |
| 26 | tag: string; |
| 27 | name?: string; |
| 28 | maxSize?: number; |
| 29 | count?: number; |
| 30 | } |
| 31 | |
| 32 | // Call a fixture route, repeating (bounded) while the response still shows an |
| 33 | // authorization failure — a freshly attached IAM policy is eventually |
| 34 | // consistent and the first invocations after deploy can see AccessDenied. |
| 35 | // Routes whose EXPECTED outcome is a scoped denial pass |
| 36 | // `retryDenied: false` (they run after routes that already proved the |
| 37 | // policy propagated). |
| 38 | const callRoute = (method: "GET" | "POST", path: string, options: { retryDenied?: boolean } = {}) => |
| 39 | Effect.gen(function* () { |
| 40 | const request = |
| 41 | method === "GET" |
| 42 | ? HttpClientRequest.get(`${baseUrl}${path}`) |
| 43 | : HttpClientRequest.post(`${baseUrl}${path}`); |
| 44 | return yield* HttpClient.execute(request).pipe( |
| 45 | Effect.flatMap((response) => |
| 46 | response.status === 200 |
| 47 | ? response.json |
| 48 | : Effect.fail(new Error(`Route ${path} not ready: ${response.status}`)), |
| 49 | ), |
| 50 | // `json` is the untyped `Json` union; RouteResult's optional props |
| 51 | // (`string | undefined`) aren't Json-assignable, so the intentional |
| 52 | // two-step conversion is required (same pattern as the /refresh route). |
| 53 | Effect.map((json) => json as unknown as RouteResult), |
| 54 | Effect.repeat({ |
| 55 | until: (body): boolean => |
| 56 | options.retryDenied === false || |
| 57 | (body.tag !== "AccessDenied" && body.tag !== "AccessDeniedException"), |
| 58 | schedule: Schedule.spaced("3 seconds"), |
| 59 | times: 10, |
| 60 | }), |
| 61 | ); |
| 62 | }); |
| 63 | |
| 64 | // Deploys a Lambda bound to a zero-sized ASG with every AutoScaling runtime |
| 65 | // binding plus the instance-events EventBridge subscription. Read bindings are |
| 66 | // asserted on live data; instance-scoped write bindings are probed with a |
| 67 | // well-formed non-existent instance id — AWS answers with a typed |
| 68 | // `ValidationError` (never AccessDenied), proving the binding's IAM grant. |
| 69 | describe( |
| 70 | "AutoScaling runtime bindings", |
| 71 | { |
| 72 | tags: [ |
| 73 | "provider:aws", |
| 74 | "provider:aws:autoscaling", |
| 75 | "provider:aws:ec2", |
| 76 | "provider:aws:lambda", |
| 77 | "live", |
| 78 | ], |
| 79 | }, |
| 80 | () => { |
| 81 | beforeAll( |
| 82 | Effect.gen(function* () { |
| 83 | yield* sharedStack.destroy(); |
| 84 | |
| 85 | const { fn } = yield* sharedStack.deploy( |
| 86 | Effect.gen(function* () { |
| 87 | const fn = yield* AsgBindingsFunction; |
| 88 | return { fn }; |
| 89 | }).pipe(Effect.provide(AsgBindingsFunctionLive)), |
| 90 | ); |
| 91 | |
| 92 | expect(fn.functionUrl).toBeTruthy(); |
| 93 | baseUrl = fn.functionUrl!.replace(/\/+$/, ""); |
| 94 | |
| 95 | yield* HttpClient.get(`${baseUrl}/health`).pipe( |
| 96 | Effect.flatMap((response) => |
| 97 | response.status === 200 |
| 98 | ? Effect.succeed(response) |
| 99 | : Effect.fail(new Error(`Function not ready: ${response.status}`)), |
| 100 | ), |
| 101 | Effect.retry({ schedule: readinessPolicy }), |
| 102 | ); |
| 103 | }), |
| 104 | { timeout: 300_000 }, |
| 105 | ); |
| 106 | |
| 107 | afterAll( |
| 108 | Effect.gen(function* () { |
| 109 | yield* sharedStack.destroy(); |
| 110 | // Assert the fixture ASG is fully gone — the suite must leave nothing. |
| 111 | // The hook context has no AWS providers of its own, so provide them |
| 112 | // explicitly for the out-of-band distilled call. |
| 113 | const remaining = yield* Core.withProviders( |
| 114 | autoscaling |
| 115 | .describeAutoScalingGroups({ AutoScalingGroupNames: [bindingsAsgName] } as any) |
| 116 | .pipe( |
| 117 | Effect.map((r) => (r.AutoScalingGroups ?? []).length), |
| 118 | Effect.repeat({ |
| 119 | until: (count) => count === 0, |
| 120 | schedule: Schedule.spaced("3 seconds"), |
| 121 | times: 10, |
| 122 | }), |
| 123 | ), |
| 124 | testOptions, |
| 125 | sharedStack.name, |
| 126 | ); |
| 127 | expect(remaining).toBe(0); |
| 128 | }), |
| 129 | { timeout: 180_000 }, |
| 130 | ); |
| 131 | |
| 132 | test.provider( |
| 133 | "DescribeAutoScalingGroup returns the bound group's live state", |
| 134 | (_stack) => |
| 135 | Effect.gen(function* () { |
| 136 | const body = yield* callRoute("GET", "/describe"); |
| 137 | expect(body.ok).toBe(true); |
| 138 | expect(body.name).toEqual(bindingsAsgName); |
| 139 | expect(body.maxSize).toEqual(0); |
| 140 | }), |
| 141 | { timeout: 60_000 }, |
| 142 | ); |
| 143 | |
| 144 | test.provider( |
| 145 | "DescribeScalingActivities lists the group's activities", |
| 146 | (_stack) => |
| 147 | Effect.gen(function* () { |
| 148 | const body = yield* callRoute("GET", "/activities"); |
| 149 | expect(body.ok).toBe(true); |
| 150 | expect(body.count).toBeGreaterThanOrEqual(0); |
| 151 | }), |
| 152 | { timeout: 60_000 }, |
| 153 | ); |
| 154 | |
| 155 | test.provider( |
| 156 | "SetDesiredCapacity succeeds against the bound group", |
| 157 | (_stack) => |
| 158 | Effect.gen(function* () { |
| 159 | const body = yield* callRoute("POST", "/set-desired"); |
| 160 | expect(body.ok).toBe(true); |
| 161 | }), |
| 162 | { timeout: 60_000 }, |
| 163 | ); |
| 164 | |
| 165 | test.provider( |
| 166 | "ExecutePolicy is IAM-wired (typed ValidationError for a bogus policy)", |
| 167 | (_stack) => |
| 168 | Effect.gen(function* () { |
| 169 | const body = yield* callRoute("POST", "/execute-policy"); |
| 170 | expect(body.tag).toEqual("ValidationError"); |
| 171 | }), |
| 172 | { timeout: 60_000 }, |
| 173 | ); |
| 174 | |
| 175 | // SetInstanceHealth / TerminateInstanceInAutoScalingGroup carry no group |
| 176 | // name in the request — EC2 Auto Scaling resolves the instance's owning |
| 177 | // group for resource-level authorization. The bogus instance resolves to |
| 178 | // nothing, so the (correct, least-privilege) group-scoped grant denies — |
| 179 | // a typed AccessDeniedException, proving the binding client signed and |
| 180 | // dispatched the operation with the attached policy (a missing policy |
| 181 | // would deny identically for REAL instances too; the other seven bindings |
| 182 | // prove grant attachment works end-to-end via the same scaffold). With a |
| 183 | // real in-group instance the same grant authorizes. |
| 184 | test.provider( |
| 185 | "SetInstanceHealth dispatches a signed request (scoped denial for a bogus instance)", |
| 186 | (_stack) => |
| 187 | Effect.gen(function* () { |
| 188 | const body = yield* callRoute("POST", "/set-health", { retryDenied: false }); |
| 189 | expect(body.tag).toEqual("AccessDeniedException"); |
| 190 | }), |
| 191 | { timeout: 60_000 }, |
| 192 | ); |
| 193 | |
| 194 | test.provider( |
| 195 | "SetInstanceProtection is IAM-wired (typed ValidationError for a bogus instance)", |
| 196 | (_stack) => |
| 197 | Effect.gen(function* () { |
| 198 | const body = yield* callRoute("POST", "/set-protection"); |
| 199 | expect(body.tag).toEqual("ValidationError"); |
| 200 | }), |
| 201 | { timeout: 60_000 }, |
| 202 | ); |
| 203 | |
| 204 | test.provider( |
| 205 | "TerminateInstanceInAutoScalingGroup dispatches a signed request (scoped denial)", |
| 206 | (_stack) => |
| 207 | Effect.gen(function* () { |
| 208 | const body = yield* callRoute("POST", "/terminate", { retryDenied: false }); |
| 209 | expect(body.tag).toEqual("AccessDeniedException"); |
| 210 | }), |
| 211 | { timeout: 60_000 }, |
| 212 | ); |
| 213 | |
| 214 | test.provider( |
| 215 | "Standby enter/exit are IAM-wired (typed ValidationError)", |
| 216 | (_stack) => |
| 217 | Effect.gen(function* () { |
| 218 | const enter = yield* callRoute("POST", "/standby-enter"); |
| 219 | expect(enter.tag).toEqual("ValidationError"); |
| 220 | const exit = yield* callRoute("POST", "/standby-exit"); |
| 221 | expect(exit.tag).toEqual("ValidationError"); |
| 222 | }), |
| 223 | { timeout: 60_000 }, |
| 224 | ); |
| 225 | |
| 226 | test.provider( |
| 227 | "InstanceRefresh start/describe/cancel round-trip on the zero-instance fleet", |
| 228 | (_stack) => |
| 229 | Effect.gen(function* () { |
| 230 | const body = (yield* callRoute("POST", "/refresh")) as unknown as { |
| 231 | startTag: string; |
| 232 | describeOk: boolean; |
| 233 | describeCount?: number; |
| 234 | cancelTag: string; |
| 235 | }; |
| 236 | // A refresh on the empty fleet completes (or is already in progress |
| 237 | // from a previous run) — never an authorization failure. |
| 238 | expect(["Success", "InstanceRefreshInProgressFault"]).toContain(body.startTag); |
| 239 | expect(body.describeOk).toBe(true); |
| 240 | expect(body.describeCount).toBeGreaterThanOrEqual(1); |
| 241 | expect(body.cancelTag).toEqual("Success"); |
| 242 | }), |
| 243 | { timeout: 60_000 }, |
| 244 | ); |
| 245 | |
| 246 | test.provider( |
| 247 | "consumeInstanceEvents created the EventBridge rule for instance events", |
| 248 | (_stack) => |
| 249 | Effect.gen(function* () { |
| 250 | // The rule's physical name is `{stack}-{logicalId}` truncated to fit |
| 251 | // the instance-id suffix (e.g. `AutoScalingBindings-BindingsGroup- |
| 252 | // Instan3unhktjkefuey4…`), so the full logical id may not survive. |
| 253 | // Filter server-side on the stable stack+logical prefix and pick the |
| 254 | // autoscaling-pattern rule. |
| 255 | let rule: eventbridge.Rule | undefined; |
| 256 | let nextToken: string | undefined; |
| 257 | for (let page = 0; page < 10 && !rule; page++) { |
| 258 | const result = yield* eventbridge.listRules({ |
| 259 | NamePrefix: "AutoScalingBindings-BindingsGroup-", |
| 260 | NextToken: nextToken, |
| 261 | Limit: 100, |
| 262 | }); |
| 263 | rule = (result.Rules ?? []).find((candidate) => |
| 264 | candidate.EventPattern?.includes("aws.autoscaling"), |
| 265 | ); |
| 266 | nextToken = result.NextToken; |
| 267 | if (!nextToken) break; |
| 268 | } |
| 269 | expect(rule).toBeDefined(); |
| 270 | expect(rule?.EventPattern).toContain("aws.autoscaling"); |
| 271 | expect(rule?.EventPattern).toContain("EC2 Instance Launch Successful"); |
| 272 | }), |
| 273 | { tags: ["provider:aws:eventbridge"], timeout: 60_000 }, |
| 274 | ); |
| 275 | }, |
| 276 | ); |