The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as rolesanywhere from "@distilled.cloud/aws/rolesanywhere"; |
| 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 } from "alchemy/Resource"; |
| 7 | import { createInternalTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import { toWireSeconds } from "alchemy/Util/Duration"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import type * as Duration from "effect/Duration"; |
| 11 | import * as Effect from "effect/Effect"; |
| 12 | import * as Stream from "effect/Stream"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | import { readRolesAnywhereTags, syncRolesAnywhereTags, toWireTags } from "./internal.ts"; |
| 15 | |
| 16 | /** |
| 17 | * Raised when the RolesAnywhere API acknowledges a profile write but returns |
| 18 | * no profile detail and the profile cannot be found by name afterwards. |
| 19 | */ |
| 20 | export class ProfileMissing extends Data.TaggedError("ProfileMissing")<{ |
| 21 | readonly resourceName: string; |
| 22 | }> {} |
| 23 | |
| 24 | /** |
| 25 | * A single rule extracting a value from the certificate field, e.g. |
| 26 | * `{ specifier: "CN" }` to map the common name. |
| 27 | */ |
| 28 | export interface ProfileMappingRule { |
| 29 | /** |
| 30 | * The specifier within the certificate field to map, e.g. `CN` or `OU` |
| 31 | * for `x509Subject`. |
| 32 | */ |
| 33 | specifier: string; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * A mapping from a certificate field to the session tags IAM Roles Anywhere |
| 38 | * attaches to the vended session. |
| 39 | */ |
| 40 | export interface ProfileAttributeMapping { |
| 41 | /** |
| 42 | * The certificate field to map: `x509Subject`, `x509Issuer` or `x509SAN`. |
| 43 | */ |
| 44 | certificateField: string; |
| 45 | /** |
| 46 | * The rules extracting specifiers from the certificate field. |
| 47 | */ |
| 48 | mappingRules: ProfileMappingRule[]; |
| 49 | } |
| 50 | |
| 51 | export interface ProfileProps { |
| 52 | /** |
| 53 | * Name of the profile. If omitted, a unique name is generated from the app, |
| 54 | * stage and logical ID. The name is updatable in place. |
| 55 | */ |
| 56 | profileName?: string; |
| 57 | /** |
| 58 | * IAM role ARNs that IAM Roles Anywhere is trusted to assume on behalf of |
| 59 | * authenticated workloads. Each role's trust policy must trust |
| 60 | * `rolesanywhere.amazonaws.com`. |
| 61 | */ |
| 62 | roleArns: string[]; |
| 63 | /** |
| 64 | * An inline IAM session policy (JSON) applied to the vended session, |
| 65 | * further restricting the assumed role's effective permissions. |
| 66 | */ |
| 67 | sessionPolicy?: string; |
| 68 | /** |
| 69 | * Managed policy ARNs that apply to the vended session as a permissions |
| 70 | * intersection. |
| 71 | */ |
| 72 | managedPolicyArns?: string[]; |
| 73 | /** |
| 74 | * How long vended session credentials are valid for, e.g. `"1 hour"` or |
| 75 | * `Duration.minutes(15)` (a bare number is milliseconds). Rounded to whole |
| 76 | * seconds on the wire (900-43200 seconds). |
| 77 | * @default "1 hour" |
| 78 | */ |
| 79 | duration?: Duration.Input; |
| 80 | /** |
| 81 | * Whether temporary credential requests must include instance properties. |
| 82 | * Immutable after creation — changing it replaces the profile. |
| 83 | * @default false |
| 84 | */ |
| 85 | requireInstanceProperties?: boolean; |
| 86 | /** |
| 87 | * Whether the vended session can carry a caller-specified role session |
| 88 | * name. |
| 89 | * @default false |
| 90 | */ |
| 91 | acceptRoleSessionName?: boolean; |
| 92 | /** |
| 93 | * Mappings from certificate fields (`x509Subject`, `x509Issuer`, |
| 94 | * `x509SAN`) to the session tags attached to the vended session. Fields |
| 95 | * omitted here keep their AWS default mapping; a field previously managed |
| 96 | * by this resource and later removed has its custom mapping deleted. |
| 97 | */ |
| 98 | attributeMappings?: ProfileAttributeMapping[]; |
| 99 | /** |
| 100 | * Whether the profile is enabled. When disabled, temporary credential |
| 101 | * requests with this profile fail. |
| 102 | * @default true |
| 103 | */ |
| 104 | enabled?: boolean; |
| 105 | /** |
| 106 | * User-defined tags for the profile. |
| 107 | */ |
| 108 | tags?: Record<string, string>; |
| 109 | } |
| 110 | |
| 111 | export interface Profile extends Resource< |
| 112 | "AWS.RolesAnywhere.Profile", |
| 113 | ProfileProps, |
| 114 | { |
| 115 | /** |
| 116 | * Unique ID of the profile. |
| 117 | */ |
| 118 | profileId: string; |
| 119 | /** |
| 120 | * ARN of the profile. |
| 121 | */ |
| 122 | profileArn: string; |
| 123 | /** |
| 124 | * Name of the profile. |
| 125 | */ |
| 126 | profileName: string; |
| 127 | /** |
| 128 | * IAM role ARNs the profile can vend sessions for. |
| 129 | */ |
| 130 | roleArns: string[]; |
| 131 | /** |
| 132 | * Whether the profile is enabled. |
| 133 | */ |
| 134 | enabled: boolean; |
| 135 | }, |
| 136 | never, |
| 137 | Providers |
| 138 | > {} |
| 139 | |
| 140 | /** |
| 141 | * An IAM Roles Anywhere profile — the list of IAM roles that the Roles |
| 142 | * Anywhere service is trusted to assume for authenticated certificate |
| 143 | * identities, optionally intersected with managed policies and an inline |
| 144 | * session policy. |
| 145 | * ### Creating a Profile |
| 146 | * **Example:** Basic Profile |
| 147 | * ```typescript |
| 148 | * const role = yield* IAM.Role("WorkloadRole", { |
| 149 | * assumeRolePolicyDocument: { |
| 150 | * Version: "2012-10-17", |
| 151 | * Statement: [ |
| 152 | * { |
| 153 | * Effect: "Allow", |
| 154 | * Principal: { Service: "rolesanywhere.amazonaws.com" }, |
| 155 | * Action: ["sts:AssumeRole", "sts:TagSession", "sts:SetSourceIdentity"], |
| 156 | * }, |
| 157 | * ], |
| 158 | * }, |
| 159 | * }); |
| 160 | * const profile = yield* RolesAnywhere.Profile("Profile", { |
| 161 | * roleArns: [role.roleArn], |
| 162 | * }); |
| 163 | * ``` |
| 164 | * |
| 165 | * ### Restricting the Session |
| 166 | * **Example:** Session Policy and Duration |
| 167 | * ```typescript |
| 168 | * const profile = yield* RolesAnywhere.Profile("Profile", { |
| 169 | * roleArns: [role.roleArn], |
| 170 | * duration: "15 minutes", |
| 171 | * sessionPolicy: JSON.stringify({ |
| 172 | * Version: "2012-10-17", |
| 173 | * Statement: [ |
| 174 | * { Effect: "Allow", Action: "s3:GetObject", Resource: "*" }, |
| 175 | * ], |
| 176 | * }), |
| 177 | * }); |
| 178 | * ``` |
| 179 | * |
| 180 | * ### Mapping Certificate Attributes |
| 181 | * **Example:** Session Tags from the Certificate Subject |
| 182 | * ```typescript |
| 183 | * const profile = yield* RolesAnywhere.Profile("Profile", { |
| 184 | * roleArns: [role.roleArn], |
| 185 | * attributeMappings: [ |
| 186 | * { |
| 187 | * certificateField: "x509Subject", |
| 188 | * mappingRules: [{ specifier: "CN" }], |
| 189 | * }, |
| 190 | * ], |
| 191 | * }); |
| 192 | * ``` |
| 193 | * |
| 194 | * @resource |
| 195 | */ |
| 196 | export const Profile = Resource<Profile>("AWS.RolesAnywhere.Profile"); |
| 197 | |
| 198 | const toAttrs = (detail: rolesanywhere.ProfileDetail) => ({ |
| 199 | profileId: detail.profileId!, |
| 200 | profileArn: detail.profileArn!, |
| 201 | profileName: detail.name!, |
| 202 | roleArns: [...(detail.roleArns ?? [])], |
| 203 | enabled: detail.enabled ?? false, |
| 204 | }); |
| 205 | |
| 206 | const sameMembers = ( |
| 207 | left: ReadonlyArray<string> | undefined, |
| 208 | right: ReadonlyArray<string> | undefined, |
| 209 | ) => { |
| 210 | const l = [...(left ?? [])].sort(); |
| 211 | const r = [...(right ?? [])].sort(); |
| 212 | return l.length === r.length && l.every((v, i) => v === r[i]); |
| 213 | }; |
| 214 | |
| 215 | export const ProfileProvider = () => |
| 216 | Provider.effect( |
| 217 | Profile, |
| 218 | Effect.gen(function* () { |
| 219 | const createName = Effect.fn(function* (id: string, props: Partial<ProfileProps>) { |
| 220 | return props.profileName ?? (yield* createPhysicalName({ id, maxLength: 255 })); |
| 221 | }); |
| 222 | |
| 223 | /** Find a profile by its user-facing name across all pages. */ |
| 224 | const findByName = (name: string) => |
| 225 | rolesanywhere.listProfiles.items({}).pipe( |
| 226 | Stream.filter((detail) => detail.name === name), |
| 227 | Stream.runHead, |
| 228 | Effect.map((head) => (head._tag === "Some" ? head.value : undefined)), |
| 229 | ); |
| 230 | |
| 231 | const getById = (profileId: string) => |
| 232 | rolesanywhere.getProfile({ profileId }).pipe( |
| 233 | Effect.map((r) => r.profile), |
| 234 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 235 | ); |
| 236 | |
| 237 | return { |
| 238 | stables: ["profileId", "profileArn"], |
| 239 | |
| 240 | diff: Effect.fn(function* ({ olds, news }) { |
| 241 | if (!isResolved(news)) return undefined; |
| 242 | // requireInstanceProperties has no member on updateProfile — it is |
| 243 | // immutable after create, so a change forces a replacement. |
| 244 | if ( |
| 245 | (olds?.requireInstanceProperties ?? false) !== (news.requireInstanceProperties ?? false) |
| 246 | ) { |
| 247 | return { action: "replace" } as const; |
| 248 | } |
| 249 | }), |
| 250 | |
| 251 | read: Effect.fn(function* ({ id, olds, output }) { |
| 252 | const found = output?.profileId |
| 253 | ? yield* getById(output.profileId) |
| 254 | : yield* findByName(yield* createName(id, olds ?? {})); |
| 255 | if (found === undefined) return undefined; |
| 256 | const attrs = toAttrs(found); |
| 257 | const tags = yield* readRolesAnywhereTags(attrs.profileArn); |
| 258 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 259 | }), |
| 260 | |
| 261 | reconcile: Effect.fn(function* ({ id, news, olds, output, session }) { |
| 262 | const name = output?.profileName ?? (yield* createName(id, news)); |
| 263 | const internalTags = yield* createInternalTags(id); |
| 264 | const desiredTags = { ...internalTags, ...news.tags }; |
| 265 | const desiredEnabled = news.enabled ?? true; |
| 266 | const desiredDurationSeconds = toWireSeconds(news.duration); |
| 267 | |
| 268 | // 1. Observe — cloud state is authoritative; output caches the id. |
| 269 | let live = output?.profileId ? yield* getById(output.profileId) : yield* findByName(name); |
| 270 | |
| 271 | // 2. Ensure — create if missing. |
| 272 | if (live === undefined) { |
| 273 | const created = yield* rolesanywhere.createProfile({ |
| 274 | name, |
| 275 | roleArns: news.roleArns, |
| 276 | sessionPolicy: news.sessionPolicy, |
| 277 | managedPolicyArns: news.managedPolicyArns, |
| 278 | durationSeconds: desiredDurationSeconds, |
| 279 | requireInstanceProperties: news.requireInstanceProperties, |
| 280 | acceptRoleSessionName: news.acceptRoleSessionName, |
| 281 | enabled: desiredEnabled, |
| 282 | tags: toWireTags(desiredTags), |
| 283 | }); |
| 284 | live = created.profile ?? (yield* findByName(name)); |
| 285 | if (live === undefined) { |
| 286 | return yield* new ProfileMissing({ resourceName: name }); |
| 287 | } |
| 288 | } else { |
| 289 | // 3. Sync — converge the mutable aspects (name, roleArns, |
| 290 | // sessionPolicy, managedPolicyArns, duration, |
| 291 | // acceptRoleSessionName) by diffing observed against desired. |
| 292 | const desiredName = news.profileName ?? live.name!; |
| 293 | const drift = |
| 294 | live.name !== desiredName || |
| 295 | !sameMembers(live.roleArns, news.roleArns) || |
| 296 | !sameMembers(live.managedPolicyArns, news.managedPolicyArns) || |
| 297 | (news.sessionPolicy !== undefined && live.sessionPolicy !== news.sessionPolicy) || |
| 298 | (desiredDurationSeconds !== undefined && |
| 299 | live.durationSeconds !== desiredDurationSeconds) || |
| 300 | (news.acceptRoleSessionName !== undefined && |
| 301 | (live.acceptRoleSessionName ?? false) !== news.acceptRoleSessionName); |
| 302 | if (drift) { |
| 303 | const updated = yield* rolesanywhere.updateProfile({ |
| 304 | profileId: live.profileId!, |
| 305 | name: desiredName, |
| 306 | roleArns: news.roleArns, |
| 307 | sessionPolicy: news.sessionPolicy, |
| 308 | managedPolicyArns: news.managedPolicyArns, |
| 309 | durationSeconds: desiredDurationSeconds, |
| 310 | acceptRoleSessionName: news.acceptRoleSessionName, |
| 311 | }); |
| 312 | live = updated.profile ?? live; |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | // Explicitly annotated so control-flow analysis inside the sync |
| 317 | // loops below (which reassign from API responses that themselves |
| 318 | // take `profile.profileId` as input) never cycles back into an |
| 319 | // inferred `ProfileDetail | undefined`. |
| 320 | let profile: rolesanywhere.ProfileDetail = live; |
| 321 | |
| 322 | // 3a. Sync attribute mappings — diff the OBSERVED mappings against |
| 323 | // the desired set. A fresh profile carries AWS default mappings |
| 324 | // that must not be touched unless the user manages that field, so |
| 325 | // deletions are driven by the fields previously declared in `olds` |
| 326 | // rather than full replacement of observed state. |
| 327 | const desiredMappings = news.attributeMappings ?? []; |
| 328 | const observedMappings = new Map( |
| 329 | (profile.attributeMappings ?? []).map((m) => [ |
| 330 | m.certificateField, |
| 331 | (m.mappingRules ?? []).map((r) => r.specifier), |
| 332 | ]), |
| 333 | ); |
| 334 | for (const mapping of desiredMappings) { |
| 335 | const observedSpecifiers = observedMappings.get(mapping.certificateField); |
| 336 | const desiredSpecifiers = mapping.mappingRules.map((r) => r.specifier); |
| 337 | if ( |
| 338 | observedSpecifiers === undefined || |
| 339 | !sameMembers(observedSpecifiers, desiredSpecifiers) |
| 340 | ) { |
| 341 | const mapped = yield* rolesanywhere.putAttributeMapping({ |
| 342 | profileId: profile.profileId!, |
| 343 | certificateField: mapping.certificateField, |
| 344 | mappingRules: mapping.mappingRules.map((r) => ({ |
| 345 | specifier: r.specifier, |
| 346 | })), |
| 347 | }); |
| 348 | profile = mapped.profile; |
| 349 | } |
| 350 | } |
| 351 | const desiredFields = new Set(desiredMappings.map((m) => m.certificateField)); |
| 352 | for (const previous of olds?.attributeMappings ?? []) { |
| 353 | if ( |
| 354 | !desiredFields.has(previous.certificateField) && |
| 355 | observedMappings.has(previous.certificateField) |
| 356 | ) { |
| 357 | const cleaned = yield* rolesanywhere |
| 358 | .deleteAttributeMapping({ |
| 359 | profileId: profile.profileId!, |
| 360 | certificateField: previous.certificateField, |
| 361 | }) |
| 362 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)); |
| 363 | profile = cleaned?.profile ?? profile; |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | if ((profile.enabled ?? false) !== desiredEnabled) { |
| 368 | // The enable/disable response can echo the pre-toggle state — the |
| 369 | // successful call itself is authoritative for the flag. |
| 370 | yield* desiredEnabled |
| 371 | ? rolesanywhere.enableProfile({ profileId: profile.profileId! }) |
| 372 | : rolesanywhere.disableProfile({ profileId: profile.profileId! }); |
| 373 | profile = { ...profile, enabled: desiredEnabled }; |
| 374 | } |
| 375 | |
| 376 | // 3b. Sync tags against observed cloud tags. |
| 377 | yield* syncRolesAnywhereTags(profile.profileArn!, desiredTags); |
| 378 | |
| 379 | yield* session.note(profile.profileId!); |
| 380 | return toAttrs(profile); |
| 381 | }), |
| 382 | |
| 383 | delete: Effect.fn(function* ({ output }) { |
| 384 | yield* rolesanywhere |
| 385 | .deleteProfile({ profileId: output.profileId }) |
| 386 | .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)); |
| 387 | }), |
| 388 | |
| 389 | list: () => |
| 390 | rolesanywhere.listProfiles.items({}).pipe( |
| 391 | Stream.map(toAttrs), |
| 392 | Stream.runCollect, |
| 393 | Effect.map((chunk) => Array.from(chunk)), |
| 394 | ), |
| 395 | }; |
| 396 | }), |
| 397 | ); |