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 { isResolved } from "alchemy/Diff"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { createInternalTags, createTagsList, diffTags, hasTags } from "alchemy/Tags"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import type { Providers } from "../Providers.ts"; |
| 11 | import { parsePolicyDocument, stringifyPolicyDocument, toTagRecord } from "./common.ts"; |
| 12 | import type { PolicyDocument } from "./Policy.ts"; |
| 13 | |
| 14 | export class UserConflict extends Data.TaggedError("UserConflict")<{ |
| 15 | readonly message: string; |
| 16 | readonly cause?: unknown; |
| 17 | }> {} |
| 18 | |
| 19 | export interface UserProps { |
| 20 | /** |
| 21 | * User name. If omitted, a deterministic name is generated. |
| 22 | */ |
| 23 | userName?: string; |
| 24 | /** |
| 25 | * Optional IAM path prefix. |
| 26 | * @default "/" |
| 27 | */ |
| 28 | path?: string; |
| 29 | /** |
| 30 | * Optional permissions boundary policy ARN. |
| 31 | */ |
| 32 | permissionsBoundary?: string; |
| 33 | /** |
| 34 | * Managed policy ARNs attached to the user. |
| 35 | */ |
| 36 | managedPolicyArns?: string[]; |
| 37 | /** |
| 38 | * Inline policies embedded in the user. |
| 39 | */ |
| 40 | inlinePolicies?: Record<string, PolicyDocument>; |
| 41 | /** |
| 42 | * User-defined tags to apply to the user. |
| 43 | */ |
| 44 | tags?: Record<string, string>; |
| 45 | } |
| 46 | |
| 47 | export interface User extends Resource< |
| 48 | "AWS.IAM.User", |
| 49 | UserProps, |
| 50 | { |
| 51 | /** The ARN of the user. */ |
| 52 | userArn: string; |
| 53 | /** The name of the user. */ |
| 54 | userName: string; |
| 55 | /** The stable unique ID of the user. */ |
| 56 | userId: string | undefined; |
| 57 | /** The IAM path of the user. */ |
| 58 | path: string | undefined; |
| 59 | /** The managed policy ARN used as the permissions boundary, if any. */ |
| 60 | permissionsBoundary: string | undefined; |
| 61 | /** Managed policy ARNs attached to the user. */ |
| 62 | managedPolicyArns: string[]; |
| 63 | /** Inline policies embedded in the user, keyed by policy name. */ |
| 64 | inlinePolicies: Record<string, PolicyDocument>; |
| 65 | /** The tags applied to the user. */ |
| 66 | tags: Record<string, string>; |
| 67 | }, |
| 68 | never, |
| 69 | Providers |
| 70 | > {} |
| 71 | |
| 72 | /** |
| 73 | * An IAM user with optional inline policies, managed policies, and tags. |
| 74 | * |
| 75 | * `User` manages a long-lived IAM identity together with its attached managed |
| 76 | * policies, inline policies, permissions boundary, and tags. |
| 77 | * ### Creating IAM Users |
| 78 | * **Example:** User with Managed Policies |
| 79 | * ```typescript |
| 80 | * const user = yield* User("AppUser", { |
| 81 | * userName: "app-user", |
| 82 | * managedPolicyArns: [ |
| 83 | * "arn:aws:iam::aws:policy/ReadOnlyAccess", |
| 84 | * ], |
| 85 | * }); |
| 86 | * ``` |
| 87 | * |
| 88 | * @resource |
| 89 | */ |
| 90 | export const User = Resource<User>("AWS.IAM.User"); |
| 91 | |
| 92 | export const UserProvider = () => |
| 93 | Provider.effect( |
| 94 | User, |
| 95 | Effect.gen(function* () { |
| 96 | const toName = (id: string, props: UserProps) => |
| 97 | props.userName ? Effect.succeed(props.userName) : createPhysicalName({ id, maxLength: 64 }); |
| 98 | |
| 99 | const readManagedPolicies = Effect.fn(function* (userName: string) { |
| 100 | const attached = yield* iam.listAttachedUserPolicies.items({ UserName: userName }).pipe( |
| 101 | Stream.runCollect, |
| 102 | Effect.map((chunk) => Array.from(chunk)), |
| 103 | ); |
| 104 | return attached |
| 105 | .map((policy) => policy.PolicyArn) |
| 106 | .filter((policyArn): policyArn is string => typeof policyArn === "string"); |
| 107 | }); |
| 108 | |
| 109 | const readInlinePolicies = Effect.fn(function* (userName: string) { |
| 110 | const policyNames = yield* iam.listUserPolicies.items({ UserName: userName }).pipe( |
| 111 | Stream.runCollect, |
| 112 | Effect.map((chunk) => Array.from(chunk)), |
| 113 | ); |
| 114 | const entries = yield* Effect.forEach(policyNames, (policyName) => |
| 115 | iam |
| 116 | .getUserPolicy({ |
| 117 | UserName: userName, |
| 118 | PolicyName: policyName, |
| 119 | }) |
| 120 | .pipe( |
| 121 | Effect.map( |
| 122 | (response) => [policyName, parsePolicyDocument(response.PolicyDocument)] as const, |
| 123 | ), |
| 124 | Effect.catchTag("NoSuchEntityException", () => |
| 125 | Effect.succeed([policyName, undefined] as const), |
| 126 | ), |
| 127 | ), |
| 128 | ); |
| 129 | return Object.fromEntries( |
| 130 | entries.filter((entry): entry is [string, PolicyDocument] => entry[1] !== undefined), |
| 131 | ); |
| 132 | }); |
| 133 | |
| 134 | const readTags = Effect.fn(function* (userName: string) { |
| 135 | const listed = yield* iam.listUserTags({ |
| 136 | UserName: userName, |
| 137 | }); |
| 138 | return toTagRecord(listed.Tags); |
| 139 | }); |
| 140 | |
| 141 | const syncManagedPolicies = Effect.fn(function* ({ |
| 142 | userName, |
| 143 | olds, |
| 144 | news, |
| 145 | }: { |
| 146 | userName: string; |
| 147 | olds: string[]; |
| 148 | news: string[]; |
| 149 | }) { |
| 150 | const oldSet = new Set(olds); |
| 151 | const newSet = new Set(news); |
| 152 | for (const policyArn of news) { |
| 153 | if (!oldSet.has(policyArn)) { |
| 154 | yield* iam.attachUserPolicy({ |
| 155 | UserName: userName, |
| 156 | PolicyArn: policyArn, |
| 157 | }); |
| 158 | } |
| 159 | } |
| 160 | for (const policyArn of olds) { |
| 161 | if (!newSet.has(policyArn)) { |
| 162 | yield* iam |
| 163 | .detachUserPolicy({ |
| 164 | UserName: userName, |
| 165 | PolicyArn: policyArn, |
| 166 | }) |
| 167 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 168 | } |
| 169 | } |
| 170 | }); |
| 171 | |
| 172 | const syncInlinePolicies = Effect.fn(function* ({ |
| 173 | userName, |
| 174 | olds, |
| 175 | news, |
| 176 | }: { |
| 177 | userName: string; |
| 178 | olds: Record<string, PolicyDocument>; |
| 179 | news: Record<string, PolicyDocument>; |
| 180 | }) { |
| 181 | for (const [policyName, document] of Object.entries(news)) { |
| 182 | if (JSON.stringify(olds[policyName] ?? null) !== JSON.stringify(document)) { |
| 183 | yield* iam.putUserPolicy({ |
| 184 | UserName: userName, |
| 185 | PolicyName: policyName, |
| 186 | PolicyDocument: stringifyPolicyDocument(document), |
| 187 | }); |
| 188 | } |
| 189 | } |
| 190 | for (const policyName of Object.keys(olds)) { |
| 191 | if (!(policyName in news)) { |
| 192 | yield* iam |
| 193 | .deleteUserPolicy({ |
| 194 | UserName: userName, |
| 195 | PolicyName: policyName, |
| 196 | }) |
| 197 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 198 | } |
| 199 | } |
| 200 | }); |
| 201 | |
| 202 | return { |
| 203 | stables: ["userArn", "userName", "userId"], |
| 204 | list: () => |
| 205 | Effect.gen(function* () { |
| 206 | // IAM is global; `listUsers` enumerates every user in the |
| 207 | // account. Paginate exhaustively, then hydrate each user's |
| 208 | // managed/inline policies and tags (the list summary omits |
| 209 | // them) to produce the same Attributes shape `read` returns. |
| 210 | const users = yield* iam.listUsers.pages({}).pipe( |
| 211 | Stream.runCollect, |
| 212 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Users ?? [])), |
| 213 | ); |
| 214 | |
| 215 | const hydrated = yield* Effect.forEach( |
| 216 | users, |
| 217 | (user) => |
| 218 | Effect.gen(function* () { |
| 219 | const [managedPolicyArns, inlinePolicies, tags] = yield* Effect.all([ |
| 220 | readManagedPolicies(user.UserName), |
| 221 | readInlinePolicies(user.UserName), |
| 222 | readTags(user.UserName), |
| 223 | ]); |
| 224 | return { |
| 225 | userArn: user.Arn, |
| 226 | userName: user.UserName, |
| 227 | userId: user.UserId, |
| 228 | path: user.Path, |
| 229 | permissionsBoundary: user.PermissionsBoundary?.PermissionsBoundaryArn, |
| 230 | managedPolicyArns, |
| 231 | inlinePolicies, |
| 232 | tags, |
| 233 | }; |
| 234 | }).pipe( |
| 235 | // A user may be deleted concurrently mid-hydration. |
| 236 | Effect.catchTag("NoSuchEntityException", () => Effect.undefined), |
| 237 | ), |
| 238 | { concurrency: 10 }, |
| 239 | ); |
| 240 | |
| 241 | return hydrated.filter( |
| 242 | (attrs): attrs is NonNullable<typeof attrs> => attrs !== undefined, |
| 243 | ); |
| 244 | }), |
| 245 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 246 | if (!isResolved(news)) return; |
| 247 | if ((yield* toName(id, olds ?? ({} as UserProps))) !== (yield* toName(id, news))) { |
| 248 | return { action: "replace" } as const; |
| 249 | } |
| 250 | if ((olds?.path ?? "/") !== (news.path ?? "/")) { |
| 251 | return { action: "replace" } as const; |
| 252 | } |
| 253 | }), |
| 254 | read: Effect.fn(function* ({ id, olds, output }) { |
| 255 | const userName = output?.userName ?? (yield* toName(id, olds ?? ({} as UserProps))); |
| 256 | const response = yield* iam |
| 257 | .getUser({ |
| 258 | UserName: userName, |
| 259 | }) |
| 260 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 261 | if (!response?.User?.Arn) { |
| 262 | return undefined; |
| 263 | } |
| 264 | const [managedPolicyArns, inlinePolicies, tags] = yield* Effect.all([ |
| 265 | readManagedPolicies(userName), |
| 266 | readInlinePolicies(userName), |
| 267 | readTags(userName), |
| 268 | ]); |
| 269 | return { |
| 270 | userArn: response.User.Arn, |
| 271 | userName: response.User.UserName, |
| 272 | userId: response.User.UserId, |
| 273 | path: response.User.Path, |
| 274 | permissionsBoundary: response.User.PermissionsBoundary?.PermissionsBoundaryArn, |
| 275 | managedPolicyArns, |
| 276 | inlinePolicies, |
| 277 | tags, |
| 278 | }; |
| 279 | }), |
| 280 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 281 | const userName = output?.userName ?? (yield* toName(id, news)); |
| 282 | const desiredTags = { |
| 283 | ...(yield* createInternalTags(id)), |
| 284 | ...news.tags, |
| 285 | }; |
| 286 | |
| 287 | // Observe — read the live user (or absence). |
| 288 | const observedResponse = yield* iam |
| 289 | .getUser({ UserName: userName }) |
| 290 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined)); |
| 291 | let observedUser = observedResponse?.User; |
| 292 | |
| 293 | // Ensure — create the user when missing. On race, verify |
| 294 | // ownership tags before adopting. |
| 295 | if (!observedUser?.Arn) { |
| 296 | const created = yield* iam |
| 297 | .createUser({ |
| 298 | UserName: userName, |
| 299 | Path: news.path, |
| 300 | PermissionsBoundary: news.permissionsBoundary, |
| 301 | Tags: createTagsList(desiredTags), |
| 302 | }) |
| 303 | .pipe( |
| 304 | Effect.catchTag("EntityAlreadyExistsException", () => |
| 305 | iam.getUser({ UserName: userName }).pipe( |
| 306 | Effect.filterOrFail( |
| 307 | (existing) => hasTags(desiredTags, existing.User?.Tags), |
| 308 | () => |
| 309 | new UserConflict({ |
| 310 | message: `User '${userName}' already exists and is not managed by alchemy`, |
| 311 | }), |
| 312 | ), |
| 313 | ), |
| 314 | ), |
| 315 | ); |
| 316 | observedUser = created.User; |
| 317 | } |
| 318 | |
| 319 | // Sync permissions boundary against observed. |
| 320 | const observedBoundary = observedUser?.PermissionsBoundary?.PermissionsBoundaryArn; |
| 321 | if (news.permissionsBoundary !== observedBoundary) { |
| 322 | if (news.permissionsBoundary) { |
| 323 | yield* iam.putUserPermissionsBoundary({ |
| 324 | UserName: userName, |
| 325 | PermissionsBoundary: news.permissionsBoundary, |
| 326 | }); |
| 327 | } else if (observedBoundary) { |
| 328 | yield* iam |
| 329 | .deleteUserPermissionsBoundary({ |
| 330 | UserName: userName, |
| 331 | }) |
| 332 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | // Sync managed and inline policies — observe live state and |
| 337 | // apply only the delta. |
| 338 | const [observedManagedPolicies, observedInlinePolicies] = yield* Effect.all([ |
| 339 | readManagedPolicies(userName), |
| 340 | readInlinePolicies(userName), |
| 341 | ]); |
| 342 | yield* syncManagedPolicies({ |
| 343 | userName, |
| 344 | olds: observedManagedPolicies, |
| 345 | news: news.managedPolicyArns ?? [], |
| 346 | }); |
| 347 | yield* syncInlinePolicies({ |
| 348 | userName, |
| 349 | olds: observedInlinePolicies, |
| 350 | news: news.inlinePolicies ?? {}, |
| 351 | }); |
| 352 | |
| 353 | // Sync tags against the cloud's actual tags. |
| 354 | const observedTags = yield* readTags(userName); |
| 355 | const { removed, upsert } = diffTags(observedTags, desiredTags); |
| 356 | if (upsert.length > 0) { |
| 357 | yield* iam.tagUser({ |
| 358 | UserName: userName, |
| 359 | Tags: upsert, |
| 360 | }); |
| 361 | } |
| 362 | if (removed.length > 0) { |
| 363 | yield* iam.untagUser({ |
| 364 | UserName: userName, |
| 365 | TagKeys: removed, |
| 366 | }); |
| 367 | } |
| 368 | |
| 369 | // Re-read for fresh attributes after all mutations. |
| 370 | const user = yield* iam.getUser({ UserName: userName }); |
| 371 | const userArn = user.User?.Arn ?? observedUser?.Arn ?? userName; |
| 372 | |
| 373 | yield* session.note(userArn); |
| 374 | return { |
| 375 | userArn, |
| 376 | userName: user.User?.UserName ?? userName, |
| 377 | userId: user.User?.UserId ?? observedUser?.UserId, |
| 378 | path: user.User?.Path ?? observedUser?.Path ?? news.path ?? "/", |
| 379 | permissionsBoundary: |
| 380 | user.User?.PermissionsBoundary?.PermissionsBoundaryArn ?? news.permissionsBoundary, |
| 381 | managedPolicyArns: news.managedPolicyArns ?? [], |
| 382 | inlinePolicies: news.inlinePolicies ?? {}, |
| 383 | tags: desiredTags, |
| 384 | }; |
| 385 | }), |
| 386 | delete: Effect.fn(function* ({ output }) { |
| 387 | yield* iam |
| 388 | .deleteUserPermissionsBoundary({ |
| 389 | UserName: output.userName, |
| 390 | }) |
| 391 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 392 | |
| 393 | yield* iam.listUserPolicies.items({ UserName: output.userName }).pipe( |
| 394 | Stream.mapEffect((policyName) => |
| 395 | iam |
| 396 | .deleteUserPolicy({ |
| 397 | UserName: output.userName, |
| 398 | PolicyName: policyName, |
| 399 | }) |
| 400 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)), |
| 401 | ), |
| 402 | Stream.runDrain, |
| 403 | // The user itself may already be gone. |
| 404 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 405 | ); |
| 406 | |
| 407 | yield* iam.listAttachedUserPolicies.items({ UserName: output.userName }).pipe( |
| 408 | Stream.mapEffect((policy) => |
| 409 | policy.PolicyArn |
| 410 | ? iam |
| 411 | .detachUserPolicy({ |
| 412 | UserName: output.userName, |
| 413 | PolicyArn: policy.PolicyArn, |
| 414 | }) |
| 415 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)) |
| 416 | : Effect.void, |
| 417 | ), |
| 418 | Stream.runDrain, |
| 419 | // The user itself may already be gone. |
| 420 | Effect.catchTag("NoSuchEntityException", () => Effect.void), |
| 421 | ); |
| 422 | |
| 423 | yield* iam |
| 424 | .deleteUser({ |
| 425 | UserName: output.userName, |
| 426 | }) |
| 427 | .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)); |
| 428 | }), |
| 429 | }; |
| 430 | }), |
| 431 | ); |