The best way to control Claude Code, Codex and more from any computer or phone

main
ts 350 lines 14.2 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
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
11 export class ServiceLinkedRoleUnexpectedResponse extends Data.TaggedError(
12 "ServiceLinkedRoleUnexpectedResponse",
13 )<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 /**
19 * Deleting a service-linked role is asynchronous: `deleteServiceLinkedRole`
20 * returns a deletion task that can end in `FAILED` (usually because the
21 * linked service still has resources using the role). The failure reason —
22 * including the offending resource ARNs, when the service reports them —
23 * is surfaced on this error.
24 */
25 export class ServiceLinkedRoleDeletionFailed extends Data.TaggedError(
26 "ServiceLinkedRoleDeletionFailed",
27 )<{
28 readonly roleName: string;
29 readonly status: string;
30 readonly reason: string | undefined;
31 }> {
32 override get message() {
33 return `IAM service-linked role ${this.roleName} deletion ${this.status}${this.reason ? `: ${this.reason}` : ""}`;
34 }
35 }
36
37 export interface ServiceLinkedRoleProps {
38 /**
39 * The service principal the role is linked to, e.g.
40 * `autoscaling.amazonaws.com` or `elasticbeanstalk.amazonaws.com`.
41 * The linked service owns the role's name, trust policy, and permissions.
42 */
43 awsServiceName: string;
44 /**
45 * Optional suffix appended to the AWS-generated role name
46 * (`AWSServiceRoleFor<Service>_<customSuffix>`). Only some services allow
47 * suffixes; services that don't reject the create with `InvalidInputException`.
48 * Use a suffix to create multiple service-linked roles for the same service.
49 */
50 customSuffix?: string;
51 /**
52 * Optional description for the role. The description is the only aspect of
53 * a service-linked role IAM allows editing after creation.
54 */
55 description?: string;
56 }
57
58 export interface ServiceLinkedRole extends Resource<
59 "AWS.IAM.ServiceLinkedRole",
60 ServiceLinkedRoleProps,
61 {
62 /** The name of the service-linked role. */
63 roleName: string;
64 /** The ARN of the service-linked role. */
65 roleArn: string;
66 /** The stable unique ID of the role. */
67 roleId: string | undefined;
68 /** The IAM path of the role. */
69 path: string | undefined;
70 /** The AWS service principal the role is linked to. */
71 awsServiceName: string;
72 /** The custom suffix appended to the role name, if any. */
73 customSuffix: string | undefined;
74 /** The description of the role. */
75 description: string | undefined;
76 },
77 never,
78 Providers
79 > {}
80
81 /**
82 * An IAM role linked to (and managed by) a specific AWS service.
83 *
84 * The linked service controls the role's trust and permissions policies; the
85 * only mutable aspect is the description. Deletion is asynchronous — the
86 * provider submits a deletion task and waits (bounded) for it to complete,
87 * failing with {@link ServiceLinkedRoleDeletionFailed} when the linked service
88 * still has resources using the role.
89 *
90 * Some services auto-create their service-linked role on first use; deploying
91 * this resource over an existing role adopts it (the create API reports the
92 * collision and the provider converges on the existing role).
93 * ### Creating Service-Linked Roles
94 * **Example:** Auto Scaling Service-Linked Role
95 * ```typescript
96 * const role = yield* ServiceLinkedRole("AutoScalingRole", {
97 * awsServiceName: "autoscaling.amazonaws.com",
98 * });
99 * ```
100 *
101 * **Example:** Suffixed Role for a Dedicated Workload
102 * ```typescript
103 * const role = yield* ServiceLinkedRole("WorkloadRole", {
104 * awsServiceName: "autoscaling.amazonaws.com",
105 * customSuffix: "analytics",
106 * description: "Auto Scaling role scoped to the analytics workload",
107 * });
108 * ```
109 *
110 * @resource
111 */
112 export const ServiceLinkedRole = Resource<ServiceLinkedRole>("AWS.IAM.ServiceLinkedRole");
113
114 /**
115 * Derive the custom suffix back out of an `AWSServiceRoleFor..._suffix`
116 * role name. Base (unsuffixed) service-linked role names never contain an
117 * underscore, so everything after the first `_` is the suffix.
118 */
119 const suffixFromRoleName = (roleName: string): string | undefined => {
120 const index = roleName.indexOf("_");
121 return index === -1 ? undefined : roleName.slice(index + 1);
122 };
123
124 const toAttributes = (role: iam.Role, awsServiceName: string): ServiceLinkedRole["Attributes"] => ({
125 roleName: role.RoleName,
126 roleArn: role.Arn,
127 roleId: role.RoleId,
128 path: role.Path,
129 awsServiceName,
130 customSuffix: suffixFromRoleName(role.RoleName),
131 description: role.Description,
132 });
133
134 export const ServiceLinkedRoleProvider = () =>
135 Provider.effect(
136 ServiceLinkedRole,
137 Effect.gen(function* () {
138 // Service-linked roles live under a deterministic path
139 // (`/aws-service-role/{service}/`), so we can always find ours by
140 // listing that path and matching the (optional) custom suffix — the
141 // role NAME itself is generated by AWS and not derivable up front.
142 const findRole = Effect.fn(function* (props: {
143 awsServiceName: string;
144 customSuffix?: string;
145 }) {
146 const roles = yield* iam.listRoles
147 .pages({ PathPrefix: `/aws-service-role/${props.awsServiceName}/` })
148 .pipe(
149 Stream.runCollect,
150 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Roles ?? [])),
151 );
152 return roles.find((role) =>
153 props.customSuffix
154 ? role.RoleName.endsWith(`_${props.customSuffix}`)
155 : !role.RoleName.includes("_"),
156 );
157 });
158
159 const getRole = Effect.fn(function* (roleName: string) {
160 const response = yield* iam
161 .getRole({ RoleName: roleName })
162 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
163 return response?.Role;
164 });
165
166 const submitDeletion = Effect.fn(function* (roleName: string) {
167 return yield* iam.deleteServiceLinkedRole({ RoleName: roleName }).pipe(
168 Effect.retry({
169 while: (error) =>
170 error._tag === "LimitExceededException" || error._tag === "ServiceFailureException",
171 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
172 }),
173 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
174 );
175 });
176
177 // Deletion is asynchronous. Poll both task status and the role itself on
178 // a bounded budget (30 × 2s = 60s); observable role absence, not merely
179 // task success/absence, is terminal. IAM can transiently mark a deletion
180 // task FAILED even though immediately resubmitting it succeeds. Treat a
181 // failed or expired task as a request to re-observe and resubmit within
182 // the same budget. If a dependency really remains, every task continues
183 // to fail and the final typed error retains the resource in state.
184 const deleteAndWait = Effect.fn(function* (roleName: string) {
185 let deletionTaskId: string | undefined;
186 let lastStatus = "NOT_SUBMITTED";
187 let lastReason: string | undefined;
188 for (let attempt = 0; attempt < 30; attempt++) {
189 // The role's observable absence is the terminal condition. A newly
190 // submitted deletion task can briefly return NoSuchEntity before
191 // its status record propagates, so task absence alone is not proof.
192 const role = yield* getRole(roleName);
193 if (!role) {
194 return;
195 }
196
197 if (deletionTaskId === undefined) {
198 const submitted = yield* submitDeletion(roleName);
199 deletionTaskId = submitted?.DeletionTaskId;
200 lastStatus = deletionTaskId ? "SUBMITTED" : "NOT_FOUND";
201 }
202
203 if (deletionTaskId !== undefined) {
204 const status = yield* iam
205 .getServiceLinkedRoleDeletionStatus({
206 DeletionTaskId: deletionTaskId,
207 })
208 .pipe(
209 // Both the task record and IAM itself are eventually
210 // consistent. Keep polling the role on transient status-read
211 // failures; never translate them into successful deletion.
212 Effect.catchTags({
213 NoSuchEntityException: () => Effect.succeed("TASK_NOT_FOUND" as const),
214 ServiceFailureException: () => Effect.undefined,
215 }),
216 );
217 if (status === "TASK_NOT_FOUND") {
218 lastStatus = status;
219 deletionTaskId = undefined;
220 } else if (status !== undefined) {
221 lastStatus = status.Status;
222 if (status.Status === "FAILED") {
223 const usage = (status.Reason?.RoleUsageList ?? [])
224 .flatMap((entry) => entry.Resources ?? [])
225 .join(", ");
226 lastReason = [status.Reason?.Reason, usage].filter((part) => part).join(" — ");
227 // AWS documents that a new request must be submitted after a
228 // failed deletion task. The next bounded iteration does so.
229 deletionTaskId = undefined;
230 }
231 }
232 }
233 yield* Effect.sleep("2 seconds");
234 }
235 return yield* new ServiceLinkedRoleDeletionFailed({
236 roleName,
237 status: "TIMED_OUT",
238 reason:
239 lastReason ??
240 `deletion task ${deletionTaskId ?? "not returned"} was ${lastStatus}, but role remained observable after 60s`,
241 });
242 });
243
244 return {
245 stables: ["roleName", "roleArn", "roleId", "path", "awsServiceName", "customSuffix"],
246 list: () =>
247 Effect.gen(function* () {
248 // IAM is global; every service-linked role lives under the
249 // `/aws-service-role/` path, with the linked service name as
250 // the next path segment.
251 const roles = yield* iam.listRoles.pages({ PathPrefix: "/aws-service-role/" }).pipe(
252 Stream.runCollect,
253 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Roles ?? [])),
254 );
255 return roles.flatMap((role) => {
256 const awsServiceName = role.Path.split("/")[2];
257 return awsServiceName ? [toAttributes(role, awsServiceName)] : [];
258 });
259 }),
260 diff: Effect.fn(function* ({ olds, news }) {
261 if (!isResolved(news)) return;
262 // The linked service and suffix are baked into the AWS-generated
263 // role name — changing either requires a new role.
264 if (olds.awsServiceName !== news.awsServiceName) {
265 return { action: "replace" } as const;
266 }
267 if ((olds.customSuffix ?? undefined) !== (news.customSuffix ?? undefined)) {
268 return { action: "replace" } as const;
269 }
270 }),
271 read: Effect.fn(function* ({ olds, output }) {
272 // Service-linked roles cannot carry user tags (IAM rejects
273 // modifications beyond the description), so there is no Alchemy
274 // ownership brand — the role is an account singleton per
275 // (service, suffix) and is reported as-is.
276 const role = output?.roleName
277 ? yield* getRole(output.roleName)
278 : olds?.awsServiceName !== undefined
279 ? yield* findRole(olds)
280 : undefined;
281 if (!role) {
282 return undefined;
283 }
284 const awsServiceName =
285 olds?.awsServiceName ?? output?.awsServiceName ?? role.Path.split("/")[2] ?? "";
286 return toAttributes(role, awsServiceName);
287 }),
288 reconcile: Effect.fn(function* ({ news, output, session }) {
289 // Observe — prefer the cached role name; fall back to searching
290 // the service's deterministic path.
291 let observed = output?.roleName ? yield* getRole(output.roleName) : undefined;
292 if (!observed) {
293 observed = yield* findRole(news);
294 }
295
296 // Ensure — create when missing. AWS reports an existing role
297 // (auto-created by the service, or a concurrent reconcile) as
298 // `InvalidInputException`; re-observe and adopt it. If nothing
299 // is found the input really was invalid — rethrow.
300 if (!observed) {
301 const created = yield* iam
302 .createServiceLinkedRole({
303 AWSServiceName: news.awsServiceName,
304 CustomSuffix: news.customSuffix,
305 Description: news.description,
306 })
307 .pipe(
308 Effect.catchTag("InvalidInputException", (error) =>
309 findRole(news).pipe(
310 Effect.flatMap((existing) =>
311 existing ? Effect.succeed({ Role: existing }) : Effect.fail(error),
312 ),
313 ),
314 ),
315 );
316 observed = created.Role;
317 }
318 if (!observed) {
319 return yield* new ServiceLinkedRoleUnexpectedResponse({
320 message: `Service-linked role for '${news.awsServiceName}' was created but could not be described`,
321 });
322 }
323
324 // Sync description — the only aspect IAM lets us edit on a
325 // service-linked role. Only converge when the user declared one;
326 // an omitted prop leaves the service's default description alone.
327 if (news.description !== undefined && observed.Description !== news.description) {
328 yield* iam
329 .updateRole({
330 RoleName: observed.RoleName,
331 Description: news.description,
332 })
333 .pipe(
334 // A few linked services lock the role entirely — treat the
335 // description as service-managed rather than failing.
336 Effect.catchTag("UnmodifiableEntityException", () => Effect.void),
337 );
338 }
339
340 // Return fresh attributes.
341 const fresh = (yield* getRole(observed.RoleName)) ?? observed;
342 yield* session.note(fresh.Arn);
343 return toAttributes(fresh, news.awsServiceName);
344 }),
345 delete: Effect.fn(function* ({ output }) {
346 yield* deleteAndWait(output.roleName);
347 }),
348 };
349 }),
350 );