The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ssoAdmin from "@distilled.cloud/aws/sso-admin"; |
| 2 | import { isResolved } from "alchemy/Diff"; |
| 3 | import * as Provider from "alchemy/Provider"; |
| 4 | import { Resource } from "alchemy/Resource"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import * as Stream from "effect/Stream"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { listInstances, resolveInstance, retryIdentityCenter } from "./common.ts"; |
| 11 | |
| 12 | export class AccountAssignmentUnexpectedResponse extends Data.TaggedError( |
| 13 | "AccountAssignmentUnexpectedResponse", |
| 14 | )<{ |
| 15 | readonly message: string; |
| 16 | readonly cause?: unknown; |
| 17 | }> {} |
| 18 | |
| 19 | export class AccountAssignmentOperationFailed extends Data.TaggedError( |
| 20 | "AccountAssignmentOperationFailed", |
| 21 | )<{ |
| 22 | readonly message: string; |
| 23 | readonly cause?: unknown; |
| 24 | }> {} |
| 25 | |
| 26 | export interface AccountAssignmentProps { |
| 27 | /** |
| 28 | * Explicit Identity Center instance ARN. |
| 29 | * If omitted, Alchemy adopts the only visible instance. |
| 30 | */ |
| 31 | instanceArn?: string; |
| 32 | /** |
| 33 | * Permission set ARN to assign. |
| 34 | */ |
| 35 | permissionSetArn: string; |
| 36 | /** |
| 37 | * Principal ID from the IAM Identity Center identity store. |
| 38 | */ |
| 39 | principalId: string; |
| 40 | /** |
| 41 | * Principal type. |
| 42 | */ |
| 43 | principalType: "USER" | "GROUP"; |
| 44 | /** |
| 45 | * Target AWS account ID. |
| 46 | */ |
| 47 | targetId: string; |
| 48 | } |
| 49 | |
| 50 | export interface AccountAssignment extends Resource< |
| 51 | "AWS.IdentityCenter.AccountAssignment", |
| 52 | AccountAssignmentProps, |
| 53 | { |
| 54 | /** The Identity Center instance the assignment lives in. */ |
| 55 | instanceArn: string; |
| 56 | /** The permission set provisioned to the target. */ |
| 57 | permissionSetArn: string; |
| 58 | /** The user or group ID that was assigned. */ |
| 59 | principalId: string; |
| 60 | /** Whether the principal is a `USER` or `GROUP`. */ |
| 61 | principalType: "USER" | "GROUP"; |
| 62 | /** The AWS account ID the assignment targets. */ |
| 63 | targetId: string; |
| 64 | /** The target type (`AWS_ACCOUNT`). */ |
| 65 | targetType: "AWS_ACCOUNT"; |
| 66 | }, |
| 67 | never, |
| 68 | Providers |
| 69 | > {} |
| 70 | |
| 71 | /** |
| 72 | * Assigns an IAM Identity Center permission set to a user or group in an AWS |
| 73 | * account. |
| 74 | * ### Creating Assignments |
| 75 | * **Example:** Assign A Group To A Workload Account |
| 76 | * ```typescript |
| 77 | * const assignment = yield* AccountAssignment("ProdAdminAssignment", { |
| 78 | * permissionSetArn: admin.permissionSetArn, |
| 79 | * principalType: "GROUP", |
| 80 | * principalId: engineers.groupId, |
| 81 | * targetId: prod.accountId, |
| 82 | * }); |
| 83 | * ``` |
| 84 | * |
| 85 | * @resource |
| 86 | */ |
| 87 | export const AccountAssignment = Resource<AccountAssignment>( |
| 88 | "AWS.IdentityCenter.AccountAssignment", |
| 89 | ); |
| 90 | |
| 91 | export const AccountAssignmentProvider = () => |
| 92 | Provider.effect( |
| 93 | AccountAssignment, |
| 94 | Effect.gen(function* () { |
| 95 | return { |
| 96 | stables: [ |
| 97 | "instanceArn", |
| 98 | "permissionSetArn", |
| 99 | "principalId", |
| 100 | "principalType", |
| 101 | "targetId", |
| 102 | "targetType", |
| 103 | ], |
| 104 | diff: Effect.fn(function* ({ olds, news }) { |
| 105 | if (!isResolved(news)) return; |
| 106 | if ( |
| 107 | olds?.instanceArn !== news.instanceArn || |
| 108 | olds?.permissionSetArn !== news.permissionSetArn || |
| 109 | olds?.principalId !== news.principalId || |
| 110 | olds?.principalType !== news.principalType || |
| 111 | olds?.targetId !== news.targetId |
| 112 | ) { |
| 113 | return { action: "replace" } as const; |
| 114 | } |
| 115 | }), |
| 116 | // Enumerate every account assignment in the account/region. Assignments |
| 117 | // are keyed by (instance, permissionSet, account, principal) with no |
| 118 | // top-level list API, so fan out: list instances -> permission sets per |
| 119 | // instance -> accounts provisioned to each permission set -> account |
| 120 | // assignments per (account, permissionSet). Each `listAccountAssignments` |
| 121 | // item already carries every field of the `read`-shaped Attributes, so |
| 122 | // no per-item hydration is needed. All pagination is exhausted; missing |
| 123 | // parents (deleted concurrently) are skipped via the typed |
| 124 | // `ResourceNotFoundException` tag. Bounded concurrency keeps the fan-out |
| 125 | // from exploding. |
| 126 | list: () => |
| 127 | Effect.gen(function* () { |
| 128 | const instances = yield* listInstances(); |
| 129 | |
| 130 | const perInstance = yield* Effect.forEach( |
| 131 | instances, |
| 132 | (instance) => { |
| 133 | const instanceArn = instance.InstanceArn; |
| 134 | if (!instanceArn) { |
| 135 | return Effect.succeed([] as AccountAssignment["Attributes"][]); |
| 136 | } |
| 137 | return listAssignmentsForInstance(instanceArn); |
| 138 | }, |
| 139 | { concurrency: 5 }, |
| 140 | ); |
| 141 | |
| 142 | return perInstance.flat(); |
| 143 | }), |
| 144 | read: Effect.fn(function* ({ olds, output }) { |
| 145 | if (output?.instanceArn) { |
| 146 | return yield* readAssignment({ |
| 147 | instanceArn: output.instanceArn, |
| 148 | permissionSetArn: output.permissionSetArn, |
| 149 | principalId: output.principalId, |
| 150 | principalType: output.principalType, |
| 151 | targetId: output.targetId, |
| 152 | }); |
| 153 | } |
| 154 | |
| 155 | if (!olds) { |
| 156 | return undefined; |
| 157 | } |
| 158 | |
| 159 | return yield* readAssignment(olds); |
| 160 | }), |
| 161 | reconcile: Effect.fn(function* ({ news, output, session }) { |
| 162 | // Observe — look up the assignment between (principal, |
| 163 | // permissionSet, target). All identifying fields are stable; |
| 164 | // diff() forces a replace on any change, so this reconcile is |
| 165 | // existence-only. |
| 166 | const existing = yield* readAssignment({ |
| 167 | ...news, |
| 168 | instanceArn: output?.instanceArn ?? news.instanceArn, |
| 169 | }); |
| 170 | if (existing) { |
| 171 | yield* session.note( |
| 172 | `${existing.targetId}:${existing.permissionSetArn}:${existing.principalId}`, |
| 173 | ); |
| 174 | return existing; |
| 175 | } |
| 176 | |
| 177 | // Ensure — create the assignment if missing. |
| 178 | const instance = yield* resolveInstance(news.instanceArn); |
| 179 | const response = yield* retryIdentityCenter( |
| 180 | ssoAdmin.createAccountAssignment({ |
| 181 | InstanceArn: instance.InstanceArn!, |
| 182 | PermissionSetArn: news.permissionSetArn, |
| 183 | PrincipalId: news.principalId, |
| 184 | PrincipalType: news.principalType, |
| 185 | TargetId: news.targetId, |
| 186 | TargetType: "AWS_ACCOUNT", |
| 187 | }), |
| 188 | ); |
| 189 | |
| 190 | const requestId = response.AccountAssignmentCreationStatus?.RequestId ?? undefined; |
| 191 | if (requestId) { |
| 192 | yield* waitForAssignmentCreation(instance.InstanceArn!, requestId); |
| 193 | } |
| 194 | |
| 195 | const created = yield* readAssignment({ |
| 196 | ...news, |
| 197 | instanceArn: instance.InstanceArn, |
| 198 | }); |
| 199 | if (!created) { |
| 200 | return yield* new AccountAssignmentUnexpectedResponse({ |
| 201 | message: "account assignment not found after create", |
| 202 | }); |
| 203 | } |
| 204 | |
| 205 | yield* session.note( |
| 206 | `${created.targetId}:${created.permissionSetArn}:${created.principalId}`, |
| 207 | ); |
| 208 | return created; |
| 209 | }), |
| 210 | delete: Effect.fn(function* ({ output }) { |
| 211 | if (!(yield* readAssignment(output))) { |
| 212 | return; |
| 213 | } |
| 214 | |
| 215 | const response = yield* retryIdentityCenter( |
| 216 | ssoAdmin |
| 217 | .deleteAccountAssignment({ |
| 218 | InstanceArn: output.instanceArn, |
| 219 | PermissionSetArn: output.permissionSetArn, |
| 220 | PrincipalId: output.principalId, |
| 221 | PrincipalType: output.principalType, |
| 222 | TargetId: output.targetId, |
| 223 | TargetType: "AWS_ACCOUNT", |
| 224 | }) |
| 225 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)), |
| 226 | ); |
| 227 | |
| 228 | const requestId = response?.AccountAssignmentDeletionStatus?.RequestId ?? undefined; |
| 229 | if (requestId) { |
| 230 | yield* waitForAssignmentDeletion(output.instanceArn, requestId); |
| 231 | } |
| 232 | }), |
| 233 | }; |
| 234 | }), |
| 235 | ); |
| 236 | |
| 237 | const listAssignmentsForInstance = Effect.fn(function* (instanceArn: string) { |
| 238 | const permissionSetArns = yield* retryIdentityCenter( |
| 239 | ssoAdmin.listPermissionSets.items({ InstanceArn: instanceArn, MaxResults: 100 }).pipe( |
| 240 | Stream.runCollect, |
| 241 | Effect.map((items) => Array.from(items) as string[]), |
| 242 | ), |
| 243 | ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([]))); |
| 244 | |
| 245 | const perPermissionSet = yield* Effect.forEach( |
| 246 | permissionSetArns, |
| 247 | (permissionSetArn) => listAssignmentsForPermissionSet(instanceArn, permissionSetArn), |
| 248 | { concurrency: 10 }, |
| 249 | ); |
| 250 | |
| 251 | return perPermissionSet.flat(); |
| 252 | }); |
| 253 | |
| 254 | const listAssignmentsForPermissionSet = Effect.fn(function* ( |
| 255 | instanceArn: string, |
| 256 | permissionSetArn: string, |
| 257 | ) { |
| 258 | const accountIds = yield* retryIdentityCenter( |
| 259 | ssoAdmin.listAccountsForProvisionedPermissionSet |
| 260 | .items({ |
| 261 | InstanceArn: instanceArn, |
| 262 | PermissionSetArn: permissionSetArn, |
| 263 | MaxResults: 100, |
| 264 | }) |
| 265 | .pipe( |
| 266 | Stream.runCollect, |
| 267 | Effect.map((items) => Array.from(items) as string[]), |
| 268 | ), |
| 269 | ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([]))); |
| 270 | |
| 271 | const perAccount = yield* Effect.forEach( |
| 272 | accountIds, |
| 273 | (accountId) => |
| 274 | ssoAdmin.listAccountAssignments |
| 275 | .items({ |
| 276 | InstanceArn: instanceArn, |
| 277 | AccountId: accountId, |
| 278 | PermissionSetArn: permissionSetArn, |
| 279 | MaxResults: 100, |
| 280 | }) |
| 281 | .pipe( |
| 282 | Stream.runCollect, |
| 283 | Effect.map((items) => Array.from(items) as ssoAdmin.AccountAssignment[]), |
| 284 | retryIdentityCenter, |
| 285 | Effect.map((assignments) => |
| 286 | assignments.flatMap((assignment): AccountAssignment["Attributes"][] => { |
| 287 | if ( |
| 288 | !assignment.AccountId || |
| 289 | !assignment.PermissionSetArn || |
| 290 | !assignment.PrincipalId || |
| 291 | (assignment.PrincipalType !== "USER" && assignment.PrincipalType !== "GROUP") |
| 292 | ) { |
| 293 | return []; |
| 294 | } |
| 295 | return [ |
| 296 | { |
| 297 | instanceArn, |
| 298 | permissionSetArn: assignment.PermissionSetArn, |
| 299 | principalId: assignment.PrincipalId, |
| 300 | principalType: assignment.PrincipalType as "USER" | "GROUP", |
| 301 | targetId: assignment.AccountId, |
| 302 | targetType: "AWS_ACCOUNT", |
| 303 | }, |
| 304 | ]; |
| 305 | }), |
| 306 | ), |
| 307 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([])), |
| 308 | ), |
| 309 | { concurrency: 10 }, |
| 310 | ); |
| 311 | |
| 312 | return perAccount.flat(); |
| 313 | }); |
| 314 | |
| 315 | const readAssignment = Effect.fn(function* ({ |
| 316 | instanceArn, |
| 317 | permissionSetArn, |
| 318 | principalId, |
| 319 | principalType, |
| 320 | targetId, |
| 321 | }: AccountAssignmentProps) { |
| 322 | // A `creating` row can serialize without resolved Outputs (`targetId` |
| 323 | // from `account.accountId`, etc.). Distilled `ListAccountAssignments` |
| 324 | // then fails with `ParseError: Expected string at ["AccountId"]`. |
| 325 | if (!targetId || !permissionSetArn || !principalId) { |
| 326 | return undefined; |
| 327 | } |
| 328 | |
| 329 | const instance = yield* resolveInstance(instanceArn); |
| 330 | const assignments = yield* ssoAdmin.listAccountAssignments |
| 331 | .items({ |
| 332 | InstanceArn: instance.InstanceArn!, |
| 333 | AccountId: targetId, |
| 334 | PermissionSetArn: permissionSetArn, |
| 335 | MaxResults: 100, |
| 336 | }) |
| 337 | .pipe( |
| 338 | Stream.runCollect, |
| 339 | Effect.map((items) => Array.from(items) as ssoAdmin.AccountAssignment[]), |
| 340 | ); |
| 341 | |
| 342 | const match = assignments.find( |
| 343 | (assignment) => |
| 344 | assignment.PrincipalId === principalId && assignment.PrincipalType === principalType, |
| 345 | ); |
| 346 | |
| 347 | if (!match) { |
| 348 | return undefined; |
| 349 | } |
| 350 | const result: AccountAssignment["Attributes"] = { |
| 351 | instanceArn: instance.InstanceArn!, |
| 352 | permissionSetArn, |
| 353 | principalId, |
| 354 | principalType, |
| 355 | targetId, |
| 356 | targetType: "AWS_ACCOUNT", |
| 357 | }; |
| 358 | return result; |
| 359 | }); |
| 360 | |
| 361 | const waitForAssignmentCreation = (instanceArn: string, requestId: string) => |
| 362 | Effect.gen(function* () { |
| 363 | const response = yield* retryIdentityCenter( |
| 364 | ssoAdmin.describeAccountAssignmentCreationStatus({ |
| 365 | InstanceArn: instanceArn, |
| 366 | AccountAssignmentCreationRequestId: requestId, |
| 367 | }), |
| 368 | ); |
| 369 | const status = response.AccountAssignmentCreationStatus; |
| 370 | |
| 371 | if (!status?.Status || status.Status === "IN_PROGRESS") { |
| 372 | return yield* Effect.fail({ |
| 373 | _tag: "AssignmentCreationInProgress" as const, |
| 374 | }); |
| 375 | } |
| 376 | |
| 377 | if (status.Status === "FAILED") { |
| 378 | return yield* new AccountAssignmentOperationFailed({ |
| 379 | message: `account assignment creation failed: ${status.FailureReason ?? "unknown failure"}`, |
| 380 | }); |
| 381 | } |
| 382 | |
| 383 | return status; |
| 384 | }).pipe( |
| 385 | Effect.retry({ |
| 386 | while: (error: any) => error?._tag === "AssignmentCreationInProgress", |
| 387 | schedule: Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(120)]), |
| 388 | }), |
| 389 | ); |
| 390 | |
| 391 | const waitForAssignmentDeletion = (instanceArn: string, requestId: string) => |
| 392 | Effect.gen(function* () { |
| 393 | const response = yield* retryIdentityCenter( |
| 394 | ssoAdmin.describeAccountAssignmentDeletionStatus({ |
| 395 | InstanceArn: instanceArn, |
| 396 | AccountAssignmentDeletionRequestId: requestId, |
| 397 | }), |
| 398 | ); |
| 399 | const status = response.AccountAssignmentDeletionStatus; |
| 400 | |
| 401 | if (!status?.Status || status.Status === "IN_PROGRESS") { |
| 402 | return yield* Effect.fail({ |
| 403 | _tag: "AssignmentDeletionInProgress" as const, |
| 404 | }); |
| 405 | } |
| 406 | |
| 407 | if (status.Status === "FAILED") { |
| 408 | return yield* new AccountAssignmentOperationFailed({ |
| 409 | message: `account assignment deletion failed: ${status.FailureReason ?? "unknown failure"}`, |
| 410 | }); |
| 411 | } |
| 412 | |
| 413 | return status; |
| 414 | }).pipe( |
| 415 | Effect.retry({ |
| 416 | while: (error: any) => error?._tag === "AssignmentDeletionInProgress", |
| 417 | schedule: Schedule.max([Schedule.spaced("2 seconds"), Schedule.recurs(120)]), |
| 418 | }), |
| 419 | ); |