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

main
ts 367 lines 12.9 KB
Raw
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 * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import { parsePolicyDocument, stringifyPolicyDocument } from "./common.ts";
10 import type { PolicyDocument } from "./Policy.ts";
11
12 export interface GroupProps {
13 /**
14 * Group name. If omitted, a deterministic name is generated.
15 */
16 groupName?: string;
17 /**
18 * Optional IAM path prefix.
19 * @default "/"
20 */
21 path?: string;
22 /**
23 * Managed policy ARNs attached to the group.
24 */
25 managedPolicyArns?: string[];
26 /**
27 * Inline policies embedded in the group.
28 */
29 inlinePolicies?: Record<string, PolicyDocument>;
30 }
31
32 export interface Group extends Resource<
33 "AWS.IAM.Group",
34 GroupProps,
35 {
36 /** The ARN of the group. */
37 groupArn: string;
38 /** The name of the group. */
39 groupName: string;
40 /** The stable unique ID of the group. */
41 groupId: string | undefined;
42 /** The IAM path of the group. */
43 path: string | undefined;
44 /** Managed policy ARNs attached to the group. */
45 managedPolicyArns: string[];
46 /** Inline policies embedded in the group, keyed by policy name. */
47 inlinePolicies: Record<string, PolicyDocument>;
48 },
49 never,
50 Providers
51 > {}
52
53 /**
54 * An IAM group that can own managed and inline policies.
55 *
56 * `Group` manages a shared authorization container for IAM users, including
57 * attached managed policies and embedded inline policies.
58 * ### Creating IAM Groups
59 * **Example:** Group with an Inline Policy
60 * ```typescript
61 * const group = yield* Group("SupportGroup", {
62 * groupName: "support",
63 * inlinePolicies: {
64 * SupportReadOnly: {
65 * Version: "2012-10-17",
66 * Statement: [{
67 * Effect: "Allow",
68 * Action: ["cloudwatch:Get*", "cloudwatch:List*"],
69 * Resource: ["*"],
70 * }],
71 * },
72 * },
73 * });
74 * ```
75 *
76 * @resource
77 */
78 export const Group = Resource<Group>("AWS.IAM.Group");
79
80 export const GroupProvider = () =>
81 Provider.effect(
82 Group,
83 Effect.gen(function* () {
84 const toName = (id: string, props: GroupProps) =>
85 props.groupName
86 ? Effect.succeed(props.groupName)
87 : createPhysicalName({ id, maxLength: 128 });
88
89 const readInlinePolicies = Effect.fn(function* (groupName: string) {
90 const policyNames = yield* iam.listGroupPolicies.items({ GroupName: groupName }).pipe(
91 Stream.runCollect,
92 Effect.map((chunk) => Array.from(chunk)),
93 );
94 const entries = yield* Effect.forEach(policyNames, (policyName) =>
95 iam
96 .getGroupPolicy({
97 GroupName: groupName,
98 PolicyName: policyName,
99 })
100 .pipe(
101 Effect.map(
102 (response) => [policyName, parsePolicyDocument(response.PolicyDocument)] as const,
103 ),
104 Effect.catchTag("NoSuchEntityException", () =>
105 Effect.succeed([policyName, undefined] as const),
106 ),
107 ),
108 );
109 return Object.fromEntries(
110 entries.filter((entry): entry is [string, PolicyDocument] => entry[1] !== undefined),
111 );
112 });
113
114 const readManagedPolicies = Effect.fn(function* (groupName: string) {
115 const attached = yield* iam.listAttachedGroupPolicies.items({ GroupName: groupName }).pipe(
116 Stream.runCollect,
117 Effect.map((chunk) => Array.from(chunk)),
118 );
119 return attached
120 .map((policy) => policy.PolicyArn)
121 .filter((policyArn): policyArn is string => typeof policyArn === "string");
122 });
123
124 const syncManagedPolicies = Effect.fn(function* ({
125 groupName,
126 olds,
127 news,
128 }: {
129 groupName: string;
130 olds: string[];
131 news: string[];
132 }) {
133 const oldSet = new Set(olds);
134 const newSet = new Set(news);
135 for (const policyArn of news) {
136 if (!oldSet.has(policyArn)) {
137 yield* iam.attachGroupPolicy({
138 GroupName: groupName,
139 PolicyArn: policyArn,
140 });
141 }
142 }
143 for (const policyArn of olds) {
144 if (!newSet.has(policyArn)) {
145 yield* iam
146 .detachGroupPolicy({
147 GroupName: groupName,
148 PolicyArn: policyArn,
149 })
150 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
151 }
152 }
153 });
154
155 const syncInlinePolicies = Effect.fn(function* ({
156 groupName,
157 olds,
158 news,
159 }: {
160 groupName: string;
161 olds: Record<string, PolicyDocument>;
162 news: Record<string, PolicyDocument>;
163 }) {
164 for (const [policyName, document] of Object.entries(news)) {
165 if (JSON.stringify(olds[policyName] ?? null) !== JSON.stringify(document)) {
166 yield* iam.putGroupPolicy({
167 GroupName: groupName,
168 PolicyName: policyName,
169 PolicyDocument: stringifyPolicyDocument(document),
170 });
171 }
172 }
173 for (const policyName of Object.keys(olds)) {
174 if (!(policyName in news)) {
175 yield* iam
176 .deleteGroupPolicy({
177 GroupName: groupName,
178 PolicyName: policyName,
179 })
180 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
181 }
182 }
183 });
184
185 return {
186 stables: ["groupArn", "groupName", "groupId"],
187 // IAM is global (no region). Enumerate every group via the paginated
188 // `listGroups`, then hydrate each into the full `read` Attributes shape
189 // by reading its attached managed policies and embedded inline policies.
190 list: () =>
191 Effect.gen(function* () {
192 const groups = yield* iam.listGroups.pages({}).pipe(
193 Stream.runCollect,
194 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Groups ?? [])),
195 );
196 const hydrated = yield* Effect.forEach(
197 groups,
198 (group) =>
199 Effect.gen(function* () {
200 const [managedPolicyArns, inlinePolicies] = yield* Effect.all([
201 readManagedPolicies(group.GroupName),
202 readInlinePolicies(group.GroupName),
203 ]);
204 return {
205 groupArn: group.Arn,
206 groupName: group.GroupName,
207 groupId: group.GroupId,
208 path: group.Path,
209 managedPolicyArns,
210 inlinePolicies,
211 };
212 }).pipe(
213 // A group can be deleted between `listGroups` and this
214 // per-group hydration (e.g. a sibling test tearing its group
215 // down) — `NoSuchEntityException` here just means it's gone,
216 // so drop it rather than failing the whole enumeration.
217 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
218 ),
219 { concurrency: 10 },
220 );
221 return hydrated.filter((g) => g !== undefined);
222 }),
223 diff: Effect.fn(function* ({ id, olds, news }) {
224 if (!isResolved(news)) return;
225 if ((yield* toName(id, olds ?? ({} as GroupProps))) !== (yield* toName(id, news))) {
226 return { action: "replace" } as const;
227 }
228 if ((olds?.path ?? "/") !== (news.path ?? "/")) {
229 return { action: "replace" } as const;
230 }
231 }),
232 read: Effect.fn(function* ({ id, olds, output }) {
233 const groupName = output?.groupName ?? (yield* toName(id, olds ?? ({} as GroupProps)));
234 const response = yield* iam
235 .getGroup({
236 GroupName: groupName,
237 })
238 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
239 if (!response?.Group?.Arn) {
240 return undefined;
241 }
242 const [managedPolicyArns, inlinePolicies] = yield* Effect.all([
243 readManagedPolicies(groupName),
244 readInlinePolicies(groupName),
245 ]);
246 return {
247 groupArn: response.Group.Arn,
248 groupName: response.Group.GroupName,
249 groupId: response.Group.GroupId,
250 path: response.Group.Path,
251 managedPolicyArns,
252 inlinePolicies,
253 };
254 }),
255 reconcile: Effect.fn(function* ({ id, news, output, session }) {
256 const groupName = output?.groupName ?? (yield* toName(id, news));
257
258 // Observe — fetch the live group. `getGroup` returns
259 // `NoSuchEntityException` when the group has not been created or
260 // was deleted out-of-band, in which case we fall through to the
261 // ensure step below.
262 let observed = yield* iam
263 .getGroup({ GroupName: groupName })
264 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
265
266 // Ensure — create the group when it is missing. A concurrent
267 // peer reconciler may win the race, so tolerate
268 // `EntityAlreadyExistsException` and reload.
269 if (!observed?.Group?.Arn) {
270 observed = yield* iam
271 .createGroup({
272 GroupName: groupName,
273 Path: news.path,
274 })
275 .pipe(
276 Effect.catchTag("EntityAlreadyExistsException", () =>
277 iam.getGroup({ GroupName: groupName }),
278 ),
279 Effect.map((response) => ({
280 Group: response.Group,
281 Users: [],
282 IsTruncated: false,
283 })),
284 );
285 }
286
287 // Sync — for each mutable aspect, diff observed against desired
288 // and apply only the delta. We trust the cloud as the source of
289 // truth instead of relying on `olds`.
290 const [observedManagedPolicies, observedInlinePolicies] = yield* Effect.all([
291 readManagedPolicies(groupName),
292 readInlinePolicies(groupName),
293 ]);
294
295 yield* syncManagedPolicies({
296 groupName,
297 olds: observedManagedPolicies,
298 news: news.managedPolicyArns ?? [],
299 });
300 yield* syncInlinePolicies({
301 groupName,
302 olds: observedInlinePolicies,
303 news: news.inlinePolicies ?? {},
304 });
305
306 const groupArn = observed.Group?.Arn ?? groupName;
307 yield* session.note(groupArn);
308 return {
309 groupArn,
310 groupName,
311 groupId: observed.Group?.GroupId,
312 path: observed.Group?.Path ?? news.path ?? "/",
313 managedPolicyArns: news.managedPolicyArns ?? [],
314 inlinePolicies: news.inlinePolicies ?? {},
315 };
316 }),
317 delete: Effect.fn(function* ({ output }) {
318 yield* iam.getGroup.items({ GroupName: output.groupName }).pipe(
319 Stream.mapEffect((user) =>
320 user.UserName
321 ? iam
322 .removeUserFromGroup({
323 GroupName: output.groupName,
324 UserName: user.UserName,
325 })
326 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void))
327 : Effect.void,
328 ),
329 Stream.runDrain,
330 // The group itself may already be gone.
331 Effect.catchTag("NoSuchEntityException", () => Effect.void),
332 );
333 yield* iam.listGroupPolicies.items({ GroupName: output.groupName }).pipe(
334 Stream.mapEffect((policyName) =>
335 iam
336 .deleteGroupPolicy({
337 GroupName: output.groupName,
338 PolicyName: policyName,
339 })
340 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void)),
341 ),
342 Stream.runDrain,
343 Effect.catchTag("NoSuchEntityException", () => Effect.void),
344 );
345 yield* iam.listAttachedGroupPolicies.items({ GroupName: output.groupName }).pipe(
346 Stream.mapEffect((policy) =>
347 policy.PolicyArn
348 ? iam
349 .detachGroupPolicy({
350 GroupName: output.groupName,
351 PolicyArn: policy.PolicyArn,
352 })
353 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void))
354 : Effect.void,
355 ),
356 Stream.runDrain,
357 Effect.catchTag("NoSuchEntityException", () => Effect.void),
358 );
359 yield* iam
360 .deleteGroup({
361 GroupName: output.groupName,
362 })
363 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
364 }),
365 };
366 }),
367 );