The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as iam from "@distilled.cloud/aws/iam"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource, type ResourceBinding } from "alchemy/Resource"; |
| 7 | import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import { toWireSeconds } from "alchemy/Util/Duration"; |
| 9 | import type * as Duration from "effect/Duration"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import type { AccountID } from "../Environment.ts"; |
| 14 | import { AWSEnvironment } from "../Environment.ts"; |
| 15 | import type { Providers } from "../Providers.ts"; |
| 16 | import { parsePolicyDocument, stringifyPolicyDocument, toTagRecord } from "./common.ts"; |
| 17 | import { normalizePolicyDocument, type PolicyDocument, type PolicyStatement } from "./Policy.ts"; |
| 18 | |
| 19 | export type RoleName = string; |
| 20 | export type RoleArn = `arn:aws:iam::${AccountID}:role/${RoleName}`; |
| 21 | |
| 22 | /** |
| 23 | * IAM misuses `MalformedPolicyDocument` for an eventual-consistency case: a |
| 24 | * trust policy whose `Principal` names a *freshly created* user/role is |
| 25 | * rejected with "Invalid principal in policy" until that principal finishes |
| 26 | * propagating through IAM (typically a few seconds). That specific message is |
| 27 | * retryable; a genuinely malformed document (bad syntax/fields) is not and |
| 28 | * fails fast because its message never matches. |
| 29 | */ |
| 30 | const invalidPrincipalRetry = { |
| 31 | while: (e: { _tag: string; message?: string }) => |
| 32 | e._tag === "MalformedPolicyDocumentException" && |
| 33 | (e.message?.includes("Invalid principal") ?? false), |
| 34 | schedule: Schedule.exponential("2 seconds"), |
| 35 | times: 5, |
| 36 | } as const; |
| 37 | |
| 38 | export interface RoleProps { |
| 39 | /** |
| 40 | * Name of the role. If omitted, a unique name will be generated. |
| 41 | */ |
| 42 | roleName?: string; |
| 43 | /** |
| 44 | * Optional IAM path prefix for the role. |
| 45 | * @default "/" |
| 46 | */ |
| 47 | path?: string; |
| 48 | /** |
| 49 | * IAM trust policy for the role. Optional when a binding contributes the |
| 50 | * trust statements (see the `assumeRolePolicyStatements` binding field) — at |
| 51 | * least one of the two must supply a statement. |
| 52 | */ |
| 53 | assumeRolePolicyDocument?: PolicyDocument; |
| 54 | /** |
| 55 | * Managed policy ARNs to attach to the role. |
| 56 | */ |
| 57 | managedPolicyArns?: string[]; |
| 58 | /** |
| 59 | * Inline policies keyed by policy name. |
| 60 | */ |
| 61 | inlinePolicies?: Record<string, PolicyDocument>; |
| 62 | /** |
| 63 | * Optional description for the role. |
| 64 | */ |
| 65 | description?: string; |
| 66 | /** |
| 67 | * Maximum session duration, e.g. `"4 hours"` or `Duration.hours(4)`. |
| 68 | * Sent to IAM as whole seconds (a bare number is milliseconds). |
| 69 | */ |
| 70 | maxSessionDuration?: Duration.Input; |
| 71 | /** |
| 72 | * Optional managed policy ARN used as the permissions boundary. |
| 73 | */ |
| 74 | permissionsBoundary?: string; |
| 75 | /** |
| 76 | * User-defined tags to apply to the role. |
| 77 | */ |
| 78 | tags?: Record<string, string>; |
| 79 | } |
| 80 | |
| 81 | export interface Role extends Resource< |
| 82 | "AWS.IAM.Role", |
| 83 | RoleProps, |
| 84 | { |
| 85 | /** The ARN of the role. */ |
| 86 | roleArn: RoleArn; |
| 87 | /** The name of the role. */ |
| 88 | roleName: RoleName; |
| 89 | /** The stable unique ID of the role. */ |
| 90 | roleId: string | undefined; |
| 91 | /** The IAM path of the role. */ |
| 92 | path: string | undefined; |
| 93 | /** The trust policy in effect for the role. */ |
| 94 | assumeRolePolicyDocument: PolicyDocument; |
| 95 | /** Managed policy ARNs attached to the role. */ |
| 96 | managedPolicyArns: string[]; |
| 97 | /** Inline policies embedded in the role, keyed by policy name. */ |
| 98 | inlinePolicies: Record<string, PolicyDocument>; |
| 99 | /** The description of the role. */ |
| 100 | description: string | undefined; |
| 101 | /** The maximum session duration, in seconds. */ |
| 102 | maxSessionDuration: number | undefined; |
| 103 | /** The managed policy ARN used as the permissions boundary, if any. */ |
| 104 | permissionsBoundary: string | undefined; |
| 105 | /** The tags applied to the role. */ |
| 106 | tags: Record<string, string>; |
| 107 | }, |
| 108 | { |
| 109 | /** |
| 110 | * IAM policy statements contributed by bindings (e.g. a consumer granting |
| 111 | * this role access to a resource). They are folded into a managed inline |
| 112 | * policy named `alchemy-bindings` on the role. |
| 113 | */ |
| 114 | policyStatements?: PolicyStatement[]; |
| 115 | /** |
| 116 | * Trust-policy (assume-role) statements contributed by bindings — e.g. a |
| 117 | * consumer declaring which service principal may assume this role. They are |
| 118 | * merged into the role's `assumeRolePolicyDocument`. |
| 119 | */ |
| 120 | assumeRolePolicyStatements?: PolicyStatement[]; |
| 121 | }, |
| 122 | Providers |
| 123 | > {} |
| 124 | |
| 125 | /** |
| 126 | * Name of the inline policy the role provider synthesizes from binding-supplied |
| 127 | * {@link PolicyStatement}s. |
| 128 | */ |
| 129 | const BINDINGS_POLICY_NAME = "alchemy-bindings"; |
| 130 | |
| 131 | /** |
| 132 | * Merge the user's inline policies with a synthetic `alchemy-bindings` policy |
| 133 | * built from binding-supplied statements (deduped by JSON identity, sorted for |
| 134 | * a stable document). |
| 135 | */ |
| 136 | const mergeBoundInlinePolicies = ( |
| 137 | inlinePolicies: Record<string, PolicyDocument> | undefined, |
| 138 | bindings: ResourceBinding<Role["Binding"]>[], |
| 139 | ): Record<string, PolicyDocument> => { |
| 140 | const statements = bindings |
| 141 | .filter((binding) => (binding as { action?: string }).action !== "delete") |
| 142 | .flatMap((binding) => binding.data?.policyStatements ?? []); |
| 143 | if (statements.length === 0) return inlinePolicies ?? {}; |
| 144 | const deduped = Array.from(new Map(statements.map((s) => [JSON.stringify(s), s])).values()).sort( |
| 145 | (a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)), |
| 146 | ); |
| 147 | return { |
| 148 | ...inlinePolicies, |
| 149 | [BINDINGS_POLICY_NAME]: { Version: "2012-10-17", Statement: deduped }, |
| 150 | }; |
| 151 | }; |
| 152 | |
| 153 | /** |
| 154 | * Merge the user's trust policy with binding-supplied assume-role statements |
| 155 | * (deduped by JSON identity, sorted for a stable document). |
| 156 | */ |
| 157 | const mergeBoundAssumeRolePolicy = ( |
| 158 | doc: PolicyDocument | undefined, |
| 159 | bindings: ResourceBinding<Role["Binding"]>[], |
| 160 | ): PolicyDocument => { |
| 161 | const bound = bindings |
| 162 | .filter((binding) => (binding as { action?: string }).action !== "delete") |
| 163 | .flatMap((binding) => binding.data?.assumeRolePolicyStatements ?? []); |
| 164 | const statements = [...(doc?.Statement ?? []), ...bound]; |
| 165 | const deduped = Array.from(new Map(statements.map((s) => [JSON.stringify(s), s])).values()).sort( |
| 166 | (a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)), |
| 167 | ); |
| 168 | return { Version: "2012-10-17", Statement: deduped }; |
| 169 | }; |
| 170 | |
| 171 | /** |
| 172 | * An IAM role for AWS services and runtimes. |
| 173 | * ### Creating Roles |
| 174 | * **Example:** ECS Task Role |
| 175 | * ```typescript |
| 176 | * const role = yield* Role("TaskRole", { |
| 177 | * assumeRolePolicyDocument: { |
| 178 | * Version: "2012-10-17", |
| 179 | * Statement: [{ |
| 180 | * Effect: "Allow", |
| 181 | * Principal: { Service: "ecs-tasks.amazonaws.com" }, |
| 182 | * Action: ["sts:AssumeRole"], |
| 183 | * }], |
| 184 | * }, |
| 185 | * }); |
| 186 | * ``` |
| 187 | * |
| 188 | * ### Granting Permissions |
| 189 | * **Example:** Attach a Customer-Managed Policy |
| 190 | * ```typescript |
| 191 | * const policy = yield* Policy("AppPolicy", { |
| 192 | * policyDocument: { |
| 193 | * Version: "2012-10-17", |
| 194 | * Statement: [{ |
| 195 | * Effect: "Allow", |
| 196 | * Action: ["s3:GetObject"], |
| 197 | * Resource: ["arn:aws:s3:::my-bucket/*"], |
| 198 | * }], |
| 199 | * }, |
| 200 | * }); |
| 201 | * |
| 202 | * const role = yield* Role("AppRole", { |
| 203 | * assumeRolePolicyDocument: { |
| 204 | * Version: "2012-10-17", |
| 205 | * Statement: [{ |
| 206 | * Effect: "Allow", |
| 207 | * Principal: { Service: "lambda.amazonaws.com" }, |
| 208 | * Action: ["sts:AssumeRole"], |
| 209 | * }], |
| 210 | * }, |
| 211 | * managedPolicyArns: [policy.policyArn], |
| 212 | * inlinePolicies: { |
| 213 | * Logs: { |
| 214 | * Version: "2012-10-17", |
| 215 | * Statement: [{ |
| 216 | * Effect: "Allow", |
| 217 | * Action: ["logs:CreateLogStream", "logs:PutLogEvents"], |
| 218 | * Resource: ["*"], |
| 219 | * }], |
| 220 | * }, |
| 221 | * }, |
| 222 | * }); |
| 223 | * ``` |
| 224 | * |
| 225 | * @resource |
| 226 | */ |
| 227 | export const Role = Resource<Role>("AWS.IAM.Role"); |
| 228 | |
| 229 | // The persisted document when it means the same as the observed one, else |
| 230 | // the observed one. |
| 231 | const samePolicyDocument = ( |
| 232 | persisted: PolicyDocument | undefined, |
| 233 | observed: PolicyDocument, |
| 234 | ): PolicyDocument => |
| 235 | persisted !== undefined && |
| 236 | normalizePolicyDocument(persisted) === normalizePolicyDocument(observed) |
| 237 | ? persisted |
| 238 | : observed; |
| 239 | |
| 240 | // The persisted list when it holds the same members as the observed one. |
| 241 | const sameSet = (persisted: string[] | undefined, observed: string[]): string[] => |
| 242 | persisted !== undefined && |
| 243 | persisted.length === observed.length && |
| 244 | observed.every((value) => persisted.includes(value)) |
| 245 | ? persisted |
| 246 | : observed; |
| 247 | |
| 248 | export const RoleProvider = () => |
| 249 | Provider.effect( |
| 250 | Role, |
| 251 | Effect.gen(function* () { |
| 252 | const toRoleName = (id: string, props: { roleName?: string } = {}) => |
| 253 | props.roleName ? Effect.succeed(props.roleName) : createPhysicalName({ id, maxLength: 64 }); |
| 254 | |
| 255 | const readInlinePolicies = Effect.fn(function* (roleName: string) { |
| 256 | const policyNames = yield* iam.listRolePolicies.items({ RoleName: roleName }).pipe( |
| 257 | Stream.runCollect, |
| 258 | Effect.map((chunk) => Array.from(chunk)), |
| 259 | ); |
| 260 | const entries = yield* Effect.forEach(policyNames, (policyName) => |
| 261 | iam |
| 262 | .getRolePolicy({ |
| 263 | RoleName: roleName, |
| 264 | PolicyName: policyName, |
| 265 | }) |
| 266 | .pipe( |
| 267 | Effect.map( |
| 268 | (response) => [policyName, parsePolicyDocument(response.PolicyDocument)] as const, |
| 269 | ), |
| 270 | Effect.catchTag("NoSuchEntityException", () => |
| 271 | Effect.succeed([policyName, undefined] as const), |
| 272 | ), |
| 273 | ), |
| 274 | ); |
| 275 | return Object.fromEntries( |
| 276 | entries.filter((entry): entry is [string, PolicyDocument] => entry[1] !== undefined), |
| 277 | ); |
| 278 | }); |
| 279 | |
| 280 | const readManagedPolicies = Effect.fn(function* (roleName: string) { |
| 281 | const attached = yield* iam.listAttachedRolePolicies.items({ RoleName: roleName }).pipe( |
| 282 | Stream.runCollect, |
| 283 | Effect.map((chunk) => Array.from(chunk)), |
| 284 | ); |
| 285 | return attached |
| 286 | .map((policy) => policy.PolicyArn) |
| 287 | .filter((policyArn): policyArn is string => typeof policyArn === "string"); |
| 288 | }); |
| 289 | |
| 290 | const readTags = Effect.fn(function* (roleName: string) { |
| 291 | const listed = yield* iam.listRoleTags({ |
| 292 | RoleName: roleName, |
| 293 | }); |
| 294 | return toTagRecord(listed.Tags); |
| 295 | }); |
| 296 | |
| 297 | const syncManagedPolicies = Effect.fn(function* ({ |
| 298 | roleName, |
| 299 | olds, |
| 300 | news, |
| 301 | }: { |
| 302 | roleName: string; |
| 303 | olds: string[]; |
| 304 | news: string[]; |
| 305 | }) { |
| 306 | const oldSet = new Set(olds); |
| 307 | const newSet = new Set(news); |
| 308 | |
| 309 | for (const policyArn of news) { |
| 310 | if (!oldSet.has(policyArn)) { |
| 311 | yield* iam.attachRolePolicy({ |
| 312 | RoleName: roleName, |
| 313 | PolicyArn: policyArn, |
| 314 | }); |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | for (const policyArn of olds) { |
| 319 | if (!newSet.has(policyArn)) { |
| 320 | yield* iam |
| 321 | .detachRolePolicy({ |
| 322 | RoleName: roleName, |
| 323 | PolicyArn: policyArn, |
| 324 | }) |
| 325 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 326 | } |
| 327 | } |
| 328 | }); |
| 329 | |
| 330 | const syncInlinePolicies = Effect.fn(function* ({ |
| 331 | roleName, |
| 332 | olds, |
| 333 | news, |
| 334 | }: { |
| 335 | roleName: string; |
| 336 | olds: Record<string, PolicyDocument>; |
| 337 | news: Record<string, PolicyDocument>; |
| 338 | }) { |
| 339 | for (const [policyName, document] of Object.entries(news)) { |
| 340 | const observed = olds[policyName]; |
| 341 | if ( |
| 342 | observed === undefined || |
| 343 | normalizePolicyDocument(observed) !== normalizePolicyDocument(document) |
| 344 | ) { |
| 345 | yield* iam.putRolePolicy({ |
| 346 | RoleName: roleName, |
| 347 | PolicyName: policyName, |
| 348 | PolicyDocument: stringifyPolicyDocument(document), |
| 349 | }); |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | for (const policyName of Object.keys(olds)) { |
| 354 | if (!(policyName in news)) { |
| 355 | yield* iam |
| 356 | .deleteRolePolicy({ |
| 357 | RoleName: roleName, |
| 358 | PolicyName: policyName, |
| 359 | }) |
| 360 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 361 | } |
| 362 | } |
| 363 | }); |
| 364 | |
| 365 | return { |
| 366 | stables: ["roleArn", "roleName"], |
| 367 | list: () => |
| 368 | Effect.gen(function* () { |
| 369 | // IAM is global; `listRoles` enumerates every role in the |
| 370 | // account. Paginate exhaustively, then hydrate each role's |
| 371 | // managed/inline policies and tags (the list summary omits |
| 372 | // them) to produce the same Attributes shape `read` returns. |
| 373 | const roles = yield* iam.listRoles.pages({}).pipe( |
| 374 | Stream.runCollect, |
| 375 | Effect.map((chunk) => |
| 376 | Array.from(chunk) |
| 377 | .flatMap((page) => page.Roles ?? []) |
| 378 | // Service-linked roles are owned by AWS and cannot be |
| 379 | // modified or deleted by us (UnmodifiableEntityException). |
| 380 | .filter((role) => !role.Path?.startsWith("/aws-service-role/")), |
| 381 | ), |
| 382 | ); |
| 383 | |
| 384 | const hydrated = yield* Effect.forEach( |
| 385 | roles, |
| 386 | (role) => |
| 387 | Effect.gen(function* () { |
| 388 | const assumeRolePolicyDocument = parsePolicyDocument( |
| 389 | role.AssumeRolePolicyDocument, |
| 390 | ); |
| 391 | if (!assumeRolePolicyDocument) { |
| 392 | return undefined; |
| 393 | } |
| 394 | const [managedPolicyArns, inlinePolicies, tags] = yield* Effect.all([ |
| 395 | readManagedPolicies(role.RoleName), |
| 396 | readInlinePolicies(role.RoleName), |
| 397 | readTags(role.RoleName), |
| 398 | ]); |
| 399 | return { |
| 400 | roleArn: role.Arn as RoleArn, |
| 401 | roleName: role.RoleName, |
| 402 | roleId: role.RoleId, |
| 403 | path: role.Path, |
| 404 | assumeRolePolicyDocument, |
| 405 | managedPolicyArns, |
| 406 | inlinePolicies, |
| 407 | description: role.Description, |
| 408 | maxSessionDuration: role.MaxSessionDuration, |
| 409 | permissionsBoundary: role.PermissionsBoundary?.PermissionsBoundaryArn, |
| 410 | tags, |
| 411 | }; |
| 412 | }).pipe( |
| 413 | // A role may be deleted concurrently mid-hydration. |
| 414 | Effect.catchTag("NoSuchEntityException", () => Effect.undefined), |
| 415 | ), |
| 416 | { concurrency: 8 }, |
| 417 | ); |
| 418 | |
| 419 | return hydrated.filter( |
| 420 | (attrs): attrs is NonNullable<typeof attrs> => attrs !== undefined, |
| 421 | ); |
| 422 | }), |
| 423 | diff: Effect.fn(function* ({ id, olds, news = {} }) { |
| 424 | if (!isResolved(news)) return; |
| 425 | if ((yield* toRoleName(id, olds ?? {})) !== (yield* toRoleName(id, news ?? {}))) { |
| 426 | return { action: "replace" } as const; |
| 427 | } |
| 428 | if ((olds?.path ?? "/") !== (news?.path ?? "/")) { |
| 429 | return { action: "replace" } as const; |
| 430 | } |
| 431 | }), |
| 432 | read: Effect.fn(function* ({ id, olds, output }) { |
| 433 | const roleName = output?.roleName ?? (yield* toRoleName(id, olds ?? {})); |
| 434 | const role = yield* iam |
| 435 | .getRole({ |
| 436 | RoleName: roleName, |
| 437 | }) |
| 438 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 439 | if (!role?.Role) { |
| 440 | return undefined; |
| 441 | } |
| 442 | |
| 443 | const [managedPolicyArns, inlinePolicies, tags] = yield* Effect.all([ |
| 444 | readManagedPolicies(roleName), |
| 445 | readInlinePolicies(roleName), |
| 446 | readTags(roleName), |
| 447 | ]); |
| 448 | |
| 449 | const observedAssumeRolePolicy = |
| 450 | parsePolicyDocument(role.Role.AssumeRolePolicyDocument) ?? |
| 451 | output?.assumeRolePolicyDocument; |
| 452 | if (!observedAssumeRolePolicy) { |
| 453 | return undefined; |
| 454 | } |
| 455 | |
| 456 | // IAM stores documents in its own form (single-item arrays become |
| 457 | // scalars, keys reorder) and lists managed policies in its own |
| 458 | // order. Keep the persisted value wherever it is equivalent to what |
| 459 | // IAM returns, so an untouched role does not read as drifted. |
| 460 | const attrs = { |
| 461 | roleArn: role.Role.Arn as RoleArn, |
| 462 | roleName: role.Role.RoleName, |
| 463 | roleId: role.Role.RoleId, |
| 464 | path: role.Role.Path, |
| 465 | assumeRolePolicyDocument: samePolicyDocument( |
| 466 | output?.assumeRolePolicyDocument, |
| 467 | observedAssumeRolePolicy, |
| 468 | ), |
| 469 | managedPolicyArns: sameSet(output?.managedPolicyArns, managedPolicyArns), |
| 470 | inlinePolicies: Object.fromEntries( |
| 471 | Object.entries(inlinePolicies).map(([name, document]) => [ |
| 472 | name, |
| 473 | samePolicyDocument(output?.inlinePolicies?.[name], document), |
| 474 | ]), |
| 475 | ), |
| 476 | description: role.Role.Description, |
| 477 | maxSessionDuration: role.Role.MaxSessionDuration, |
| 478 | permissionsBoundary: role.Role.PermissionsBoundary?.PermissionsBoundaryArn, |
| 479 | tags, |
| 480 | }; |
| 481 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 482 | }), |
| 483 | reconcile: Effect.fn(function* ({ id, news = {}, output, session, bindings }) { |
| 484 | const roleName = output?.roleName ?? (yield* toRoleName(id, news)); |
| 485 | // Fold binding-supplied policy statements into the inline policies. |
| 486 | const inlinePolicies = mergeBoundInlinePolicies(news.inlinePolicies, bindings); |
| 487 | // Merge binding-supplied trust statements into the trust policy. |
| 488 | const assumeRolePolicyDocument = mergeBoundAssumeRolePolicy( |
| 489 | news.assumeRolePolicyDocument, |
| 490 | bindings, |
| 491 | ); |
| 492 | if (assumeRolePolicyDocument.Statement.length === 0) { |
| 493 | return yield* Effect.die( |
| 494 | "Role requires a trust policy: set `assumeRolePolicyDocument` or bind `assumeRolePolicyStatements`.", |
| 495 | ); |
| 496 | } |
| 497 | const desiredTags = { |
| 498 | ...(yield* createInternalTags(id)), |
| 499 | ...news.tags, |
| 500 | }; |
| 501 | const desiredMaxSessionDuration = toWireSeconds(news.maxSessionDuration); |
| 502 | |
| 503 | // Observe — read the role from IAM. Absence is signalled by |
| 504 | // `NoSuchEntityException`; ownership has already been verified |
| 505 | // upstream so adopting a `Unowned` role is the engine's call. |
| 506 | let observedRole = yield* iam |
| 507 | .getRole({ RoleName: roleName }) |
| 508 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 509 | |
| 510 | // Ensure — create the role when missing. A peer reconciler may |
| 511 | // have created it concurrently; tolerate that race by reading |
| 512 | // the existing role. |
| 513 | if (!observedRole?.Role) { |
| 514 | observedRole = yield* iam |
| 515 | .createRole({ |
| 516 | Path: news.path, |
| 517 | RoleName: roleName, |
| 518 | AssumeRolePolicyDocument: stringifyPolicyDocument(assumeRolePolicyDocument), |
| 519 | Description: news.description, |
| 520 | MaxSessionDuration: desiredMaxSessionDuration, |
| 521 | PermissionsBoundary: news.permissionsBoundary, |
| 522 | Tags: createTagsList(desiredTags), |
| 523 | }) |
| 524 | .pipe( |
| 525 | Effect.retry(invalidPrincipalRetry), |
| 526 | Effect.catchTag("EntityAlreadyExistsException", () => |
| 527 | iam.getRole({ RoleName: roleName }), |
| 528 | ), |
| 529 | ); |
| 530 | } |
| 531 | |
| 532 | const observedAssumePolicy = parsePolicyDocument( |
| 533 | observedRole.Role?.AssumeRolePolicyDocument, |
| 534 | ); |
| 535 | const observedDescription = observedRole.Role?.Description; |
| 536 | const observedMaxSessionDuration = observedRole.Role?.MaxSessionDuration; |
| 537 | const observedPermissionsBoundary = |
| 538 | observedRole.Role?.PermissionsBoundary?.PermissionsBoundaryArn; |
| 539 | |
| 540 | // Sync assume-role policy — only call updateAssumeRolePolicy |
| 541 | // when the document actually differs. IAM returns the stored |
| 542 | // document in its own form (reordered keys, single-item lists as |
| 543 | // scalars), so compare normalized documents, not raw JSON text. |
| 544 | if ( |
| 545 | observedAssumePolicy === undefined || |
| 546 | normalizePolicyDocument(observedAssumePolicy) !== |
| 547 | normalizePolicyDocument(assumeRolePolicyDocument) |
| 548 | ) { |
| 549 | yield* iam |
| 550 | .updateAssumeRolePolicy({ |
| 551 | RoleName: roleName, |
| 552 | PolicyDocument: stringifyPolicyDocument(assumeRolePolicyDocument), |
| 553 | }) |
| 554 | .pipe(Effect.retry(invalidPrincipalRetry)); |
| 555 | } |
| 556 | |
| 557 | // Sync description / maxSessionDuration via updateRole. |
| 558 | if ( |
| 559 | observedDescription !== news.description || |
| 560 | observedMaxSessionDuration !== desiredMaxSessionDuration |
| 561 | ) { |
| 562 | yield* iam.updateRole({ |
| 563 | RoleName: roleName, |
| 564 | Description: news.description, |
| 565 | MaxSessionDuration: desiredMaxSessionDuration, |
| 566 | }); |
| 567 | } |
| 568 | |
| 569 | // Sync permissions boundary — put when desired, delete when |
| 570 | // cleared, no-op when unchanged. |
| 571 | if (news.permissionsBoundary !== observedPermissionsBoundary) { |
| 572 | if (news.permissionsBoundary) { |
| 573 | yield* iam.putRolePermissionsBoundary({ |
| 574 | RoleName: roleName, |
| 575 | PermissionsBoundary: news.permissionsBoundary, |
| 576 | }); |
| 577 | } else if (observedPermissionsBoundary) { |
| 578 | yield* iam |
| 579 | .deleteRolePermissionsBoundary({ |
| 580 | RoleName: roleName, |
| 581 | }) |
| 582 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | // Sync managed and inline policies — observe the live state |
| 587 | // and apply only the delta. This is robust to manual edits in |
| 588 | // the AWS console and to adoption. |
| 589 | const [observedManagedPolicies, observedInlinePolicies] = yield* Effect.all([ |
| 590 | readManagedPolicies(roleName), |
| 591 | readInlinePolicies(roleName), |
| 592 | ]); |
| 593 | yield* syncManagedPolicies({ |
| 594 | roleName, |
| 595 | olds: observedManagedPolicies, |
| 596 | news: news.managedPolicyArns ?? [], |
| 597 | }); |
| 598 | yield* syncInlinePolicies({ |
| 599 | roleName, |
| 600 | olds: observedInlinePolicies, |
| 601 | news: inlinePolicies, |
| 602 | }); |
| 603 | |
| 604 | // Sync tags against the cloud's actual tags so adoption / |
| 605 | // out-of-band tag changes converge. |
| 606 | const observedTags = yield* readTags(roleName); |
| 607 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 608 | if (upsert.length > 0) { |
| 609 | yield* iam.tagRole({ |
| 610 | RoleName: roleName, |
| 611 | Tags: upsert, |
| 612 | }); |
| 613 | } |
| 614 | if (removed.length > 0) { |
| 615 | yield* iam.untagRole({ |
| 616 | RoleName: roleName, |
| 617 | TagKeys: removed, |
| 618 | }); |
| 619 | } |
| 620 | |
| 621 | // Re-read for fresh attributes after all mutations. |
| 622 | const liveRole = yield* iam.getRole({ RoleName: roleName }); |
| 623 | const roleArn = (liveRole.Role?.Arn ?? |
| 624 | observedRole.Role?.Arn ?? |
| 625 | `arn:aws:iam::${(yield* AWSEnvironment.current).accountId}:role/${roleName}`) as RoleArn; |
| 626 | |
| 627 | yield* session.note(roleArn); |
| 628 | return { |
| 629 | roleArn, |
| 630 | roleName: liveRole.Role?.RoleName ?? roleName, |
| 631 | roleId: liveRole.Role?.RoleId ?? observedRole.Role?.RoleId, |
| 632 | path: liveRole.Role?.Path ?? observedRole.Role?.Path ?? news.path ?? "/", |
| 633 | assumeRolePolicyDocument, |
| 634 | managedPolicyArns: news.managedPolicyArns ?? [], |
| 635 | inlinePolicies, |
| 636 | description: liveRole.Role?.Description ?? news.description, |
| 637 | maxSessionDuration: liveRole.Role?.MaxSessionDuration ?? desiredMaxSessionDuration, |
| 638 | permissionsBoundary: |
| 639 | liveRole.Role?.PermissionsBoundary?.PermissionsBoundaryArn ?? |
| 640 | news.permissionsBoundary, |
| 641 | tags: desiredTags, |
| 642 | }; |
| 643 | }), |
| 644 | delete: Effect.fn(function* ({ output }) { |
| 645 | yield* iam |
| 646 | .deleteRolePermissionsBoundary({ |
| 647 | RoleName: output.roleName, |
| 648 | }) |
| 649 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 650 | |
| 651 | yield* iam.listRolePolicies.items({ RoleName: output.roleName }).pipe( |
| 652 | Stream.mapEffect((policyName) => |
| 653 | iam |
| 654 | .deleteRolePolicy({ |
| 655 | RoleName: output.roleName, |
| 656 | PolicyName: policyName, |
| 657 | }) |
| 658 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)), |
| 659 | ), |
| 660 | Stream.runDrain, |
| 661 | // The role itself may already be gone. |
| 662 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 663 | ); |
| 664 | |
| 665 | yield* iam.listAttachedRolePolicies.items({ RoleName: output.roleName }).pipe( |
| 666 | Stream.mapEffect((policy) => |
| 667 | iam |
| 668 | .detachRolePolicy({ |
| 669 | RoleName: output.roleName, |
| 670 | PolicyArn: policy.PolicyArn!, |
| 671 | }) |
| 672 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)), |
| 673 | ), |
| 674 | Stream.runDrain, |
| 675 | // The role itself may already be gone. |
| 676 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 677 | ); |
| 678 | |
| 679 | yield* iam |
| 680 | .deleteRole({ |
| 681 | RoleName: output.roleName, |
| 682 | }) |
| 683 | .pipe( |
| 684 | Effect.retry({ |
| 685 | while: (error) => |
| 686 | error._tag === "ConcurrentModificationException" || |
| 687 | error._tag === "DeleteConflictException" || |
| 688 | error._tag === "LimitExceededException" || |
| 689 | error._tag === "ServiceFailureException", |
| 690 | schedule: Schedule.max([Schedule.exponential("250 millis"), Schedule.recurs(8)]), |
| 691 | }), |
| 692 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 693 | ); |
| 694 | |
| 695 | // IAM deletion is eventually consistent. Do not let the engine |
| 696 | // discard state until the role is actually absent, otherwise a |
| 697 | // following clean run (or nuke) can still discover the old role. |
| 698 | for (let attempt = 0; attempt < 30; attempt++) { |
| 699 | const remaining = yield* iam |
| 700 | .getRole({ RoleName: output.roleName }) |
| 701 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 702 | if (remaining === undefined) return; |
| 703 | yield* Effect.sleep("1 second"); |
| 704 | } |
| 705 | return yield* Effect.die( |
| 706 | new Error(`IAM role ${output.roleName} remained observable 30 seconds after delete`), |
| 707 | ); |
| 708 | }), |
| 709 | }; |
| 710 | }), |
| 711 | ); |