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

main
ts 297 lines 11.3 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Schedule from "effect/Schedule";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 export class IamTestFunction extends Lambda.Function<Lambda.Function>()("IamTestFunction") {}
14
15 /**
16 * A permissive-but-harmless custom policy used by the simulator and
17 * context-key routes. The `aws:username` condition guarantees
18 * GetContextKeysForCustomPolicy returns a non-empty key list.
19 */
20 const CUSTOM_POLICY = JSON.stringify({
21 Version: "2012-10-17",
22 Statement: [
23 {
24 Effect: "Allow",
25 Action: ["s3:ListAllMyBuckets"],
26 Resource: "*",
27 Condition: { StringLike: { "aws:username": "*" } },
28 },
29 ],
30 });
31
32 export default IamTestFunction.make(
33 {
34 main,
35 functionUrl: true,
36 // Credential-report + access-advisor routes poll (bounded) for report
37 // generation; the AWS default 3s Lambda timeout is far too tight.
38 timeout: Duration.seconds(30),
39 },
40 Effect.gen(function* () {
41 // The IAM entity the principal-scoped routes interrogate. The inline
42 // policy grants s3:ListAllMyBuckets so the access-advisor job lists the
43 // s3 namespace and the principal simulation evaluates to "allowed".
44 const user = yield* IAM.User("BindingsUser", {
45 inlinePolicies: {
46 AllowListBuckets: {
47 Version: "2012-10-17",
48 Statement: [
49 {
50 Effect: "Allow",
51 Action: ["s3:ListAllMyBuckets"],
52 Resource: ["*"],
53 },
54 ],
55 },
56 },
57 tags: { fixture: "iam-bindings" },
58 });
59
60 const accessKey = yield* IAM.AccessKey("BindingsUserKey", {
61 userName: user.userName,
62 });
63
64 // Output accessors: yielding at init returns an *accessor* effect that
65 // must be yielded again inside the runtime route to get the value.
66 const userArn = yield* user.userArn;
67 const userName = yield* user.userName;
68
69 // --- account-audit bindings ---
70 const getAccountSummary = yield* IAM.GetAccountSummary();
71 const getAccountAuthorizationDetails = yield* IAM.GetAccountAuthorizationDetails();
72
73 // --- credential report ---
74 const generateCredentialReport = yield* IAM.GenerateCredentialReport();
75 const getCredentialReport = yield* IAM.GetCredentialReport();
76
77 // --- access advisor ---
78 const generateServiceLastAccessedDetails = yield* IAM.GenerateServiceLastAccessedDetails();
79 const getServiceLastAccessedDetails = yield* IAM.GetServiceLastAccessedDetails();
80 const getServiceLastAccessedDetailsWithEntities =
81 yield* IAM.GetServiceLastAccessedDetailsWithEntities();
82 const listPoliciesGrantingServiceAccess = yield* IAM.ListPoliciesGrantingServiceAccess();
83
84 // --- policy simulation ---
85 const simulateCustomPolicy = yield* IAM.SimulateCustomPolicy();
86 const simulatePrincipalPolicy = yield* IAM.SimulatePrincipalPolicy();
87 const getContextKeysForCustomPolicy = yield* IAM.GetContextKeysForCustomPolicy();
88 const getContextKeysForPrincipalPolicy = yield* IAM.GetContextKeysForPrincipalPolicy();
89
90 // --- access-key hygiene (scoped to the fixture's canonical AccessKey) ---
91 const getAccessKeyLastUsed = yield* IAM.GetAccessKeyLastUsed(accessKey);
92
93 const bound = {
94 getAccountSummary,
95 getAccountAuthorizationDetails,
96 generateCredentialReport,
97 getCredentialReport,
98 generateServiceLastAccessedDetails,
99 getServiceLastAccessedDetails,
100 getServiceLastAccessedDetailsWithEntities,
101 listPoliciesGrantingServiceAccess,
102 simulateCustomPolicy,
103 simulatePrincipalPolicy,
104 getContextKeysForCustomPolicy,
105 getContextKeysForPrincipalPolicy,
106 getAccessKeyLastUsed,
107 };
108
109 return {
110 fetch: Effect.gen(function* () {
111 const request = yield* HttpServerRequest;
112 const url = new URL(request.originalUrl);
113 const pathname = url.pathname;
114
115 if (request.method === "GET" && pathname === "/bindings") {
116 return yield* HttpServerResponse.json({
117 bound: Object.keys(bound),
118 });
119 }
120
121 if (request.method === "GET" && pathname === "/account-summary") {
122 const { SummaryMap } = yield* getAccountSummary();
123 return yield* HttpServerResponse.json({
124 keys: Object.keys(SummaryMap ?? {}).length,
125 users: SummaryMap?.Users ?? null,
126 });
127 }
128
129 if (request.method === "GET" && pathname === "/authorization-details") {
130 const { UserDetailList } = yield* getAccountAuthorizationDetails({
131 Filter: ["User"],
132 MaxItems: 100,
133 });
134 return yield* HttpServerResponse.json({
135 users: (UserDetailList ?? []).length,
136 });
137 }
138
139 if (request.method === "GET" && pathname === "/credential-report") {
140 // Kick off generation (idempotent — returns STARTED/INPROGRESS/
141 // COMPLETE), then poll the report with a bounded retry on the two
142 // typed not-ready tags. A genuine IAM gap surfaces as
143 // AccessDeniedException and 500s the route instead.
144 yield* generateCredentialReport();
145 const result = yield* getCredentialReport().pipe(
146 Effect.retry({
147 while: (e): boolean =>
148 e._tag === "CredentialReportNotPresentException" ||
149 e._tag === "CredentialReportNotReadyException",
150 schedule: Schedule.spaced("2 seconds"),
151 times: 8,
152 }),
153 Effect.map((r) => ({
154 tag: "Ok",
155 bytes: r.Content?.length ?? 0,
156 format: r.ReportFormat ?? null,
157 })),
158 Effect.catchTag(
159 ["CredentialReportNotPresentException", "CredentialReportNotReadyException"],
160 (e) => Effect.succeed({ tag: e._tag, bytes: 0, format: null }),
161 ),
162 );
163 return yield* HttpServerResponse.json(result);
164 }
165
166 if (request.method === "GET" && pathname === "/service-last-accessed") {
167 // Access-advisor round trip against the fixture user: generate the
168 // job, briefly poll until it leaves IN_PROGRESS, then drill into
169 // the s3 namespace (guaranteed present — the user's inline policy
170 // allows s3). Keep this well below the Lambda timeout: under
171 // parallel test load the IAM calls themselves can be slow, and the
172 // caller already accepts IN_PROGRESS as a valid asynchronous state.
173 const { JobId } = yield* generateServiceLastAccessedDetails({
174 Arn: yield* userArn,
175 });
176 const details = yield* getServiceLastAccessedDetails({
177 JobId: JobId!,
178 }).pipe(
179 Effect.repeat({
180 schedule: Schedule.spaced("1 second"),
181 until: (r): boolean => r.JobStatus !== "IN_PROGRESS",
182 times: 3,
183 }),
184 );
185 if (details.JobStatus !== "COMPLETED") {
186 return yield* HttpServerResponse.json({
187 status: details.JobStatus,
188 services: 0,
189 entities: null,
190 });
191 }
192 const withEntities = yield* getServiceLastAccessedDetailsWithEntities({
193 JobId: JobId!,
194 ServiceNamespace: "s3",
195 });
196 return yield* HttpServerResponse.json({
197 status: details.JobStatus,
198 services: (details.ServicesLastAccessed ?? []).length,
199 entities: (withEntities.EntityDetailsList ?? []).length,
200 });
201 }
202
203 if (request.method === "GET" && pathname === "/policies-granting-access") {
204 const { PoliciesGrantingServiceAccess } = yield* listPoliciesGrantingServiceAccess({
205 Arn: yield* userArn,
206 ServiceNamespaces: ["s3"],
207 });
208 const s3 = (PoliciesGrantingServiceAccess ?? []).find(
209 (entry) => entry.ServiceNamespace === "s3",
210 );
211 return yield* HttpServerResponse.json({
212 policies: (s3?.Policies ?? []).length,
213 });
214 }
215
216 if (request.method === "GET" && pathname === "/simulate-custom") {
217 const { EvaluationResults } = yield* simulateCustomPolicy({
218 PolicyInputList: [CUSTOM_POLICY],
219 ActionNames: ["s3:ListAllMyBuckets"],
220 ContextEntries: [
221 {
222 ContextKeyName: "aws:username",
223 ContextKeyType: "string",
224 ContextKeyValues: ["alchemy-test"],
225 },
226 ],
227 });
228 return yield* HttpServerResponse.json({
229 decision: EvaluationResults?.[0]?.EvalDecision ?? null,
230 });
231 }
232
233 if (request.method === "GET" && pathname === "/simulate-principal") {
234 const { EvaluationResults } = yield* simulatePrincipalPolicy({
235 PolicySourceArn: yield* userArn,
236 ActionNames: ["s3:ListAllMyBuckets"],
237 });
238 return yield* HttpServerResponse.json({
239 decision: EvaluationResults?.[0]?.EvalDecision ?? null,
240 });
241 }
242
243 if (request.method === "GET" && pathname === "/context-keys-custom") {
244 const { ContextKeyNames } = yield* getContextKeysForCustomPolicy({
245 PolicyInputList: [CUSTOM_POLICY],
246 });
247 return yield* HttpServerResponse.json({
248 contextKeys: ContextKeyNames ?? [],
249 });
250 }
251
252 if (request.method === "GET" && pathname === "/context-keys-principal") {
253 const { ContextKeyNames } = yield* getContextKeysForPrincipalPolicy({
254 PolicySourceArn: yield* userArn,
255 });
256 return yield* HttpServerResponse.json({
257 contextKeys: ContextKeyNames ?? [],
258 });
259 }
260
261 if (request.method === "GET" && pathname === "/access-key-last-used") {
262 // The binding injects the fixture key's AccessKeyId; a fresh key
263 // has no last-used data but the owning user name is always echoed.
264 const { UserName, AccessKeyLastUsed } = yield* getAccessKeyLastUsed();
265 return yield* HttpServerResponse.json({
266 userName: UserName ?? null,
267 expectedUserName: yield* userName,
268 lastUsedService: AccessKeyLastUsed?.ServiceName ?? null,
269 });
270 }
271
272 return yield* HttpServerResponse.json(
273 { error: "Not found", method: request.method, pathname },
274 { status: 404 },
275 );
276 }).pipe(Effect.orDie),
277 };
278 }).pipe(
279 Effect.provide(
280 Layer.mergeAll(
281 IAM.GetAccountSummaryHttp,
282 IAM.GetAccountAuthorizationDetailsHttp,
283 IAM.GenerateCredentialReportHttp,
284 IAM.GetCredentialReportHttp,
285 IAM.GenerateServiceLastAccessedDetailsHttp,
286 IAM.GetServiceLastAccessedDetailsHttp,
287 IAM.GetServiceLastAccessedDetailsWithEntitiesHttp,
288 IAM.ListPoliciesGrantingServiceAccessHttp,
289 IAM.SimulateCustomPolicyHttp,
290 IAM.SimulatePrincipalPolicyHttp,
291 IAM.GetContextKeysForCustomPolicyHttp,
292 IAM.GetContextKeysForPrincipalPolicyHttp,
293 IAM.GetAccessKeyLastUsedHttp,
294 ),
295 ),
296 ),
297 );