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 { AWSEnvironment } from "@alchemy.run/aws/Environment"; |
| 3 | import { Role } from "@alchemy.run/aws/IAM"; |
| 4 | import { expect } from "@alchemy.run/test"; |
| 5 | import * as Test from "@alchemy.run/test/Alchemy"; |
| 6 | import type { ResolvedCredentials } from "@distilled.cloud/aws/Credentials"; |
| 7 | import * as IAM from "@distilled.cloud/aws/iam"; |
| 8 | import * as STS from "@distilled.cloud/aws/sts"; |
| 9 | import { adopt } from "alchemy/AdoptPolicy"; |
| 10 | import * as Drift from "alchemy/Drift"; |
| 11 | import * as Provider from "alchemy/Provider"; |
| 12 | import { State } from "alchemy/State"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as Layer from "effect/Layer"; |
| 15 | import * as Redacted from "effect/Redacted"; |
| 16 | import * as Schedule from "effect/Schedule"; |
| 17 | |
| 18 | const { test } = Test.make({ providers: AWS.providers() }); |
| 19 | |
| 20 | const assumeRolePolicy = { |
| 21 | Version: "2012-10-17" as const, |
| 22 | Statement: [ |
| 23 | { |
| 24 | Effect: "Allow" as const, |
| 25 | Principal: { Service: "lambda.amazonaws.com" }, |
| 26 | Action: ["sts:AssumeRole"], |
| 27 | }, |
| 28 | ], |
| 29 | }; |
| 30 | |
| 31 | test.provider( |
| 32 | "create, update, and delete role", |
| 33 | (stack) => |
| 34 | Effect.gen(function* () { |
| 35 | yield* stack.destroy(); |
| 36 | |
| 37 | const role = yield* stack.deploy( |
| 38 | Effect.gen(function* () { |
| 39 | return yield* Role("IamRole", { |
| 40 | assumeRolePolicyDocument: assumeRolePolicy, |
| 41 | maxSessionDuration: "2 hours", |
| 42 | managedPolicyArns: ["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"], |
| 43 | inlinePolicies: { |
| 44 | AllowLogs: { |
| 45 | Version: "2012-10-17", |
| 46 | Statement: [{ Effect: "Allow", Action: ["logs:CreateLogGroup"], Resource: "*" }], |
| 47 | }, |
| 48 | }, |
| 49 | tags: { env: "test" }, |
| 50 | }); |
| 51 | }), |
| 52 | ); |
| 53 | |
| 54 | const created = yield* IAM.getRole({ RoleName: role.roleName }); |
| 55 | expect(created.Role.RoleName).toBe(role.roleName); |
| 56 | // Duration.Input prop converts to whole wire seconds. |
| 57 | expect(created.Role.MaxSessionDuration).toBe(7200); |
| 58 | |
| 59 | // #1968: IAM stores `["sts:AssumeRole"]` as `"sts:AssumeRole"`; an |
| 60 | // equivalent document is not drift. |
| 61 | const clean = yield* Drift.detect({ name: stack.name, stage: stack.stage }).pipe( |
| 62 | Effect.provide(stack.state), |
| 63 | ); |
| 64 | expect(clean.resources.IamRole?.action).toBe("unchanged"); |
| 65 | |
| 66 | yield* stack.deploy( |
| 67 | Effect.gen(function* () { |
| 68 | return yield* Role("IamRole", { |
| 69 | assumeRolePolicyDocument: assumeRolePolicy, |
| 70 | maxSessionDuration: "1 hour", |
| 71 | managedPolicyArns: [], |
| 72 | inlinePolicies: { |
| 73 | AllowLogs: { |
| 74 | Version: "2012-10-17", |
| 75 | Statement: [{ Effect: "Allow", Action: ["logs:CreateLogStream"], Resource: "*" }], |
| 76 | }, |
| 77 | }, |
| 78 | tags: { env: "prod" }, |
| 79 | }); |
| 80 | }), |
| 81 | ); |
| 82 | |
| 83 | const updatedTags = yield* IAM.listRoleTags({ RoleName: role.roleName }); |
| 84 | expect( |
| 85 | Object.fromEntries((updatedTags.Tags ?? []).map((tag) => [tag.Key, tag.Value])), |
| 86 | ).toMatchObject({ env: "prod" }); |
| 87 | |
| 88 | // The reconcile sync path applies the changed Duration prop. |
| 89 | const updated = yield* IAM.getRole({ RoleName: role.roleName }); |
| 90 | expect(updated.Role.MaxSessionDuration).toBe(3600); |
| 91 | |
| 92 | yield* stack.destroy(); |
| 93 | |
| 94 | const deleted = yield* IAM.getRole({ RoleName: role.roleName }).pipe(Effect.option); |
| 95 | expect(deleted._tag).toBe("None"); |
| 96 | }), |
| 97 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 98 | ); |
| 99 | |
| 100 | test.provider( |
| 101 | "does not rewrite an inline policy IAM stores in an equivalent form", |
| 102 | (stack) => |
| 103 | Effect.gen(function* () { |
| 104 | yield* stack.destroy(); |
| 105 | |
| 106 | const deployRole = (tags: Record<string, string>) => |
| 107 | stack.deploy( |
| 108 | Effect.gen(function* () { |
| 109 | return yield* Role("EquivalentInlineRole", { |
| 110 | assumeRolePolicyDocument: assumeRolePolicy, |
| 111 | inlinePolicies: { |
| 112 | AllowLogs: { |
| 113 | Version: "2012-10-17", |
| 114 | Statement: [{ Effect: "Allow", Action: ["logs:CreateLogGroup"], Resource: "*" }], |
| 115 | }, |
| 116 | }, |
| 117 | tags, |
| 118 | }); |
| 119 | }), |
| 120 | ); |
| 121 | |
| 122 | const role = yield* deployRole({ env: "test" }); |
| 123 | |
| 124 | // Store an equivalent document in a different form: reordered keys and |
| 125 | // a single-item list as a scalar. |
| 126 | const equivalent = JSON.stringify({ |
| 127 | Version: "2012-10-17", |
| 128 | Statement: [{ Resource: "*", Action: "logs:CreateLogGroup", Effect: "Allow" }], |
| 129 | }); |
| 130 | yield* IAM.putRolePolicy({ |
| 131 | RoleName: role.roleName, |
| 132 | PolicyName: "AllowLogs", |
| 133 | PolicyDocument: equivalent, |
| 134 | }); |
| 135 | |
| 136 | // A tags-only change runs reconcile, which must leave the policy alone. |
| 137 | yield* deployRole({ env: "prod" }); |
| 138 | |
| 139 | const observed = yield* IAM.getRolePolicy({ |
| 140 | RoleName: role.roleName, |
| 141 | PolicyName: "AllowLogs", |
| 142 | }); |
| 143 | expect(JSON.parse(decodeURIComponent(observed.PolicyDocument))).toEqual( |
| 144 | JSON.parse(equivalent), |
| 145 | ); |
| 146 | |
| 147 | yield* stack.destroy(); |
| 148 | }), |
| 149 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 150 | ); |
| 151 | |
| 152 | // Credentials the next deploy runs as; unset means the testing profile. |
| 153 | let deployAs: ResolvedCredentials | undefined; |
| 154 | |
| 155 | const deployAsEnvironment = Layer.effect( |
| 156 | AWSEnvironment, |
| 157 | Effect.gen(function* () { |
| 158 | const profile = yield* AWSEnvironment; |
| 159 | return Effect.map(profile, (environment) => ({ |
| 160 | ...environment, |
| 161 | credentials: Effect.suspend(() => |
| 162 | deployAs ? Effect.succeed(deployAs) : environment.credentials, |
| 163 | ), |
| 164 | })); |
| 165 | }), |
| 166 | ).pipe(Layer.provide(AWS.providers())); |
| 167 | |
| 168 | const deployAsRole = Test.make({ |
| 169 | providers: AWS.providers().pipe(Layer.provide(deployAsEnvironment)), |
| 170 | }); |
| 171 | |
| 172 | deployAsRole.test.provider( |
| 173 | "a role denied rewriting its own policies can deploy a change to itself", |
| 174 | (stack) => |
| 175 | Effect.gen(function* () { |
| 176 | yield* stack.destroy(); |
| 177 | |
| 178 | const { accountId, region } = yield* AWSEnvironment.current; |
| 179 | const deployRole = (tags: Record<string, string>) => |
| 180 | stack.deploy( |
| 181 | Effect.gen(function* () { |
| 182 | return yield* Role("SelfDeployingRole", { |
| 183 | assumeRolePolicyDocument: { |
| 184 | Version: "2012-10-17", |
| 185 | Statement: [ |
| 186 | { |
| 187 | Effect: "Allow", |
| 188 | Principal: { AWS: `arn:aws:iam::${accountId}:root` }, |
| 189 | Action: ["sts:AssumeRole"], |
| 190 | }, |
| 191 | ], |
| 192 | }, |
| 193 | inlinePolicies: { |
| 194 | Deploy: { |
| 195 | Version: "2012-10-17", |
| 196 | Statement: [ |
| 197 | { Effect: "Allow", Action: ["*"], Resource: "*" }, |
| 198 | { |
| 199 | Effect: "Deny", |
| 200 | Action: ["iam:UpdateAssumeRolePolicy", "iam:PutRolePolicy"], |
| 201 | Resource: "*", |
| 202 | }, |
| 203 | ], |
| 204 | }, |
| 205 | }, |
| 206 | tags, |
| 207 | }); |
| 208 | }), |
| 209 | ); |
| 210 | |
| 211 | const role = yield* deployRole({ env: "test" }); |
| 212 | |
| 213 | // A freshly created role's trust policy takes a few seconds to apply. |
| 214 | const assumed = yield* STS.assumeRole({ |
| 215 | RoleArn: role.roleArn, |
| 216 | RoleSessionName: "alchemy-self-deploy", |
| 217 | }).pipe( |
| 218 | Effect.retry({ |
| 219 | while: (error) => error._tag === "AccessDeniedException", |
| 220 | schedule: Schedule.exponential("1 second"), |
| 221 | times: 8, |
| 222 | }), |
| 223 | ); |
| 224 | deployAs = { |
| 225 | accessKeyId: Redacted.make(assumed.Credentials!.AccessKeyId), |
| 226 | secretAccessKey: Redacted.isRedacted(assumed.Credentials!.SecretAccessKey) |
| 227 | ? assumed.Credentials!.SecretAccessKey |
| 228 | : Redacted.make(assumed.Credentials!.SecretAccessKey), |
| 229 | sessionToken: Redacted.make(assumed.Credentials!.SessionToken), |
| 230 | region, |
| 231 | expiration: assumed.Credentials!.Expiration?.getTime(), |
| 232 | }; |
| 233 | |
| 234 | // As the role itself, change only its tags. Reconcile must not call |
| 235 | // UpdateAssumeRolePolicy or PutRolePolicy for unchanged documents |
| 236 | // that IAM returns in its own form. |
| 237 | yield* deployRole({ env: "prod" }).pipe( |
| 238 | Effect.ensuring(Effect.sync(() => (deployAs = undefined))), |
| 239 | ); |
| 240 | |
| 241 | const tags = yield* IAM.listRoleTags({ RoleName: role.roleName }); |
| 242 | expect( |
| 243 | Object.fromEntries((tags.Tags ?? []).map((tag) => [tag.Key, tag.Value])), |
| 244 | ).toMatchObject({ env: "prod" }); |
| 245 | |
| 246 | yield* stack.destroy(); |
| 247 | }).pipe(Effect.ensuring(Effect.sync(() => (deployAs = undefined)))), |
| 248 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 249 | ); |
| 250 | |
| 251 | test.provider( |
| 252 | "folds binding-supplied policy statements into an inline policy", |
| 253 | (stack) => |
| 254 | Effect.gen(function* () { |
| 255 | yield* stack.destroy(); |
| 256 | |
| 257 | // Phase 1: a consumer binds policy statements to the role; the provider |
| 258 | // folds them into the synthesized `alchemy-bindings` inline policy. |
| 259 | const role = yield* stack.deploy( |
| 260 | Effect.gen(function* () { |
| 261 | const role = yield* Role("BoundRole", { assumeRolePolicyDocument: assumeRolePolicy }); |
| 262 | yield* role.bind`Allow(test, s3:GetObject)`({ |
| 263 | policyStatements: [ |
| 264 | { |
| 265 | Effect: "Allow", |
| 266 | Action: ["s3:GetObject"], |
| 267 | Resource: ["arn:aws:s3:::example-bucket/*"], |
| 268 | }, |
| 269 | ], |
| 270 | }); |
| 271 | return role; |
| 272 | }), |
| 273 | ); |
| 274 | |
| 275 | const bound = yield* IAM.getRolePolicy({ |
| 276 | RoleName: role.roleName, |
| 277 | PolicyName: "alchemy-bindings", |
| 278 | }); |
| 279 | const boundDoc = JSON.parse(decodeURIComponent(bound.PolicyDocument)) as { |
| 280 | Statement: Array<{ Action: string[]; Resource: string[] }>; |
| 281 | }; |
| 282 | expect(boundDoc.Statement).toEqual( |
| 283 | expect.arrayContaining([ |
| 284 | expect.objectContaining({ |
| 285 | Action: ["s3:GetObject"], |
| 286 | Resource: ["arn:aws:s3:::example-bucket/*"], |
| 287 | }), |
| 288 | ]), |
| 289 | ); |
| 290 | |
| 291 | // Phase 2: re-deploy without the binding; the inline policy is removed. |
| 292 | yield* stack.deploy( |
| 293 | Effect.gen(function* () { |
| 294 | return yield* Role("BoundRole", { assumeRolePolicyDocument: assumeRolePolicy }); |
| 295 | }), |
| 296 | ); |
| 297 | |
| 298 | const afterUnbind = yield* IAM.getRolePolicy({ |
| 299 | RoleName: role.roleName, |
| 300 | PolicyName: "alchemy-bindings", |
| 301 | }).pipe(Effect.option); |
| 302 | expect(afterUnbind._tag).toBe("None"); |
| 303 | |
| 304 | yield* stack.destroy(); |
| 305 | }), |
| 306 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 307 | ); |
| 308 | |
| 309 | test.provider( |
| 310 | "bindings can supply the role's trust policy", |
| 311 | (stack) => |
| 312 | Effect.gen(function* () { |
| 313 | yield* stack.destroy(); |
| 314 | |
| 315 | // A bare role with no `assumeRolePolicyDocument`; the binding supplies the |
| 316 | // trust statement instead. |
| 317 | const role = yield* stack.deploy( |
| 318 | Effect.gen(function* () { |
| 319 | const role = yield* Role("TrustBoundRole", {}); |
| 320 | yield* role.bind`Trust(test, lambda)`({ |
| 321 | assumeRolePolicyStatements: [ |
| 322 | { |
| 323 | Effect: "Allow", |
| 324 | Principal: { Service: "lambda.amazonaws.com" }, |
| 325 | Action: ["sts:AssumeRole"], |
| 326 | }, |
| 327 | ], |
| 328 | }); |
| 329 | return role; |
| 330 | }), |
| 331 | ); |
| 332 | |
| 333 | const live = yield* IAM.getRole({ RoleName: role.roleName }); |
| 334 | const trust = JSON.parse(decodeURIComponent(live.Role.AssumeRolePolicyDocument!)) as { |
| 335 | Statement: Array<{ Principal?: { Service?: string } }>; |
| 336 | }; |
| 337 | expect(trust.Statement).toEqual( |
| 338 | expect.arrayContaining([ |
| 339 | expect.objectContaining({ Principal: { Service: "lambda.amazonaws.com" } }), |
| 340 | ]), |
| 341 | ); |
| 342 | |
| 343 | yield* stack.destroy(); |
| 344 | }), |
| 345 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 346 | ); |
| 347 | |
| 348 | test.provider( |
| 349 | "list enumerates the deployed role", |
| 350 | (stack) => |
| 351 | Effect.gen(function* () { |
| 352 | yield* stack.destroy(); |
| 353 | |
| 354 | const role = yield* stack.deploy( |
| 355 | Effect.gen(function* () { |
| 356 | return yield* Role("ListRole", { |
| 357 | assumeRolePolicyDocument: assumeRolePolicy, |
| 358 | tags: { env: "test" }, |
| 359 | }); |
| 360 | }), |
| 361 | ); |
| 362 | |
| 363 | const provider = yield* Provider.findProvider(Role); |
| 364 | const all = yield* provider.list(); |
| 365 | |
| 366 | const found = all.find((r) => r.roleName === role.roleName); |
| 367 | expect(found).toBeDefined(); |
| 368 | expect(found?.roleArn).toBe(role.roleArn); |
| 369 | |
| 370 | yield* stack.destroy(); |
| 371 | |
| 372 | const deleted = yield* IAM.getRole({ RoleName: role.roleName }).pipe(Effect.option); |
| 373 | expect(deleted._tag).toBe("None"); |
| 374 | }), |
| 375 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 376 | ); |
| 377 | |
| 378 | // Engine-level adoption tests for IAM Role. Note: the user must supply an |
| 379 | // explicit `roleName` for adoption to work across a state-store wipe — |
| 380 | // without one, `createPhysicalName` derives a fresh name from a per-deploy |
| 381 | // random `instanceId`, so the cold-start `read` lookup would never find |
| 382 | // the original role. |
| 383 | // |
| 384 | // These tests wipe the state store mid-test, so the framework's automatic |
| 385 | // scratch-stack teardown cannot always see the role. Each test therefore |
| 386 | // uses a DETERMINISTIC role name, pre-cleans any leftover from a previously |
| 387 | // killed run, and guarantees an idempotent out-of-band delete via |
| 388 | // `Effect.ensuring` so a pass (or interruption) never orphans the role. |
| 389 | const deleteRoleIfExists = (roleName: string) => |
| 390 | IAM.deleteRole({ RoleName: roleName }).pipe( |
| 391 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 392 | Effect.asVoid, |
| 393 | // Any non-not-found failure is a real cleanup bug — surface it loudly. |
| 394 | Effect.orDie, |
| 395 | ); |
| 396 | |
| 397 | test.provider( |
| 398 | "owned role (matching alchemy tags) is silently adopted without --adopt", |
| 399 | (stack) => |
| 400 | Effect.gen(function* () { |
| 401 | yield* stack.destroy(); |
| 402 | |
| 403 | const roleName = "alchemy-test-role-adopt"; |
| 404 | |
| 405 | // Reclaim a leftover from a previously killed run. |
| 406 | yield* deleteRoleIfExists(roleName); |
| 407 | |
| 408 | const initial = yield* stack.deploy( |
| 409 | Effect.gen(function* () { |
| 410 | return yield* Role("AdoptableRole", { |
| 411 | roleName, |
| 412 | assumeRolePolicyDocument: assumeRolePolicy, |
| 413 | }); |
| 414 | }), |
| 415 | ); |
| 416 | |
| 417 | // Wipe state — the role stays in IAM. |
| 418 | yield* Effect.gen(function* () { |
| 419 | const state = yield* yield* State; |
| 420 | yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "AdoptableRole" }); |
| 421 | }).pipe(Effect.provide(stack.state)); |
| 422 | |
| 423 | const adopted = yield* stack.deploy( |
| 424 | Effect.gen(function* () { |
| 425 | return yield* Role("AdoptableRole", { |
| 426 | roleName, |
| 427 | assumeRolePolicyDocument: assumeRolePolicy, |
| 428 | }); |
| 429 | }), |
| 430 | ); |
| 431 | |
| 432 | expect(adopted.roleArn).toEqual(initial.roleArn); |
| 433 | expect(adopted.roleName).toEqual(roleName); |
| 434 | |
| 435 | yield* stack.destroy(); |
| 436 | |
| 437 | const deleted = yield* IAM.getRole({ RoleName: roleName }).pipe(Effect.option); |
| 438 | expect(deleted._tag).toBe("None"); |
| 439 | }).pipe(Effect.ensuring(deleteRoleIfExists("alchemy-test-role-adopt"))), |
| 440 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 441 | ); |
| 442 | |
| 443 | test.provider( |
| 444 | "foreign-tagged role requires adopt(true) to take over", |
| 445 | (stack) => |
| 446 | Effect.gen(function* () { |
| 447 | yield* stack.destroy(); |
| 448 | |
| 449 | // Use a deterministic shared physical name for both deploys. |
| 450 | const sharedRoleName = "alchemy-test-role-takeover"; |
| 451 | |
| 452 | // Reclaim a leftover from a previously killed run. |
| 453 | yield* deleteRoleIfExists(sharedRoleName); |
| 454 | |
| 455 | const original = yield* stack.deploy( |
| 456 | Effect.gen(function* () { |
| 457 | return yield* Role("Original", { |
| 458 | roleName: sharedRoleName, |
| 459 | assumeRolePolicyDocument: assumeRolePolicy, |
| 460 | }); |
| 461 | }), |
| 462 | ); |
| 463 | |
| 464 | yield* Effect.gen(function* () { |
| 465 | const state = yield* yield* State; |
| 466 | yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "Original" }); |
| 467 | }).pipe(Effect.provide(stack.state)); |
| 468 | |
| 469 | const takenOver = yield* stack |
| 470 | .deploy( |
| 471 | Effect.gen(function* () { |
| 472 | return yield* Role("Different", { |
| 473 | roleName: sharedRoleName, |
| 474 | assumeRolePolicyDocument: assumeRolePolicy, |
| 475 | }); |
| 476 | }), |
| 477 | ) |
| 478 | .pipe(adopt(true)); |
| 479 | |
| 480 | expect(takenOver.roleArn).toEqual(original.roleArn); |
| 481 | |
| 482 | // After adoption, tags should now identify this stack/stage/id. |
| 483 | const tagsResp = yield* IAM.listRoleTags({ RoleName: sharedRoleName }); |
| 484 | const tagMap = Object.fromEntries((tagsResp.Tags ?? []).map((t) => [t.Key, t.Value])); |
| 485 | expect(tagMap["alchemy::id"]).toEqual("Different"); |
| 486 | |
| 487 | yield* stack.destroy(); |
| 488 | |
| 489 | const deleted = yield* IAM.getRole({ RoleName: sharedRoleName }).pipe(Effect.option); |
| 490 | expect(deleted._tag).toBe("None"); |
| 491 | }).pipe(Effect.ensuring(deleteRoleIfExists("alchemy-test-role-takeover"))), |
| 492 | { tags: ["provider:aws", "provider:aws:iam", "live"] }, |
| 493 | ); |