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

main
ts 508 lines 18.5 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 { 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 { AccountID } from "../Environment.ts";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import type { IamAction } from "./actions.generated.ts";
14 import {
15 oldestNondefaultPolicyVersion,
16 parsePolicyDocument,
17 policyArnFromParts,
18 stringifyPolicyDocument,
19 toTagRecord,
20 } from "./common.ts";
21
22 export class PolicyConflict extends Data.TaggedError("PolicyConflict")<{
23 readonly message: string;
24 readonly cause?: unknown;
25 }> {}
26
27 export type { IamAction } from "./actions.generated.ts";
28 export { stringifyPolicyDocument } from "./common.ts";
29
30 export interface PolicyDocument {
31 Version: "2012-10-17";
32 Statement: PolicyStatement[];
33 }
34
35 export interface PolicyStatement {
36 Effect: "Allow" | "Deny";
37 Sid?: string;
38 Action?: IamAction[] | string[];
39 Resource?: string | string[];
40 Condition?: Record<string, Record<string, string | string[]>>;
41 Principal?: string | Record<string, string | string[]>;
42 NotPrincipal?: string | Record<string, string | string[]>;
43 NotAction?: string[];
44 NotResource?: string[];
45 }
46
47 /**
48 * A single statement in a Service Control Policy (SCP) or Resource Control
49 * Policy (RCP) — the restricted IAM dialect accepted by AWS Organizations.
50 *
51 * SCP statements never carry a `Principal`/`NotPrincipal` (they apply to the
52 * accounts the policy is attached to), and Allow statements are further
53 * restricted by Organizations at write time (`Resource` must be `"*"`, no
54 * `Condition`, no `NotAction`). This interface narrows {@link PolicyStatement}
55 * to the SCP-legal field set; the Allow-statement value restrictions are
56 * enforced by the Organizations API.
57 */
58 export interface ServiceControlPolicyStatement {
59 Sid?: string;
60 Effect: "Allow" | "Deny";
61 Action?: IamAction[] | string[];
62 NotAction?: string[];
63 Resource?: string | string[];
64 NotResource?: string[];
65 Condition?: Record<string, Record<string, string | string[]>>;
66 }
67
68 /**
69 * A Service Control Policy document — the SCP-legal subset of
70 * {@link PolicyDocument} used by AWS Organizations policies
71 * (`SERVICE_CONTROL_POLICY` / `RESOURCE_CONTROL_POLICY`).
72 */
73 export interface ServiceControlPolicyDocument {
74 Version: "2012-10-17";
75 Statement: ServiceControlPolicyStatement[];
76 }
77
78 /**
79 * Canonicalize an IAM policy document for drift comparison.
80 *
81 * Accepts either the raw JSON string a cloud API returned (IAM returns
82 * URL-encoded documents; both encoded and plain strings are handled) or an
83 * in-memory document object, and produces a deterministic string — object keys
84 * sorted recursively, arrays kept in order, no whitespace — so two equivalent
85 * documents compare equal regardless of key ordering or encoding.
86 *
87 * Single-element arrays are collapsed to their element: the IAM policy
88 * grammar treats `["x"]` and `"x"` as equivalent in every list-valued
89 * position (`Action`, `Resource`, principal values, condition values, even
90 * `Statement` itself), and several AWS services (e.g. Secrets Manager)
91 * store the scalar form — without collapsing, a typed document that uses
92 * arrays would spuriously diff against the stored policy on every deploy.
93 *
94 * Unparseable strings are returned unchanged so a diff still fires (and shows
95 * the offending value) instead of throwing inside a provider.
96 */
97 export const normalizePolicyDocument = (json: string | object): string => {
98 const stable = (value: unknown): unknown =>
99 Array.isArray(value)
100 ? value.length === 1
101 ? stable(value[0])
102 : value.map(stable)
103 : value !== null && typeof value === "object"
104 ? Object.fromEntries(
105 Object.entries(value as Record<string, unknown>)
106 .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
107 .map(([k, v]) => [k, stable(v)]),
108 )
109 : value;
110 if (typeof json === "string") {
111 try {
112 return JSON.stringify(stable(JSON.parse(json)));
113 } catch {
114 try {
115 return JSON.stringify(stable(JSON.parse(decodeURIComponent(json))));
116 } catch {
117 return json;
118 }
119 }
120 }
121 return JSON.stringify(stable(json));
122 };
123
124 export type PolicyName = string;
125 export type PolicyArn = `arn:aws:iam::${AccountID}:policy/${string}`;
126
127 export interface PolicyProps {
128 /**
129 * Name of the managed policy. If omitted, a deterministic name is generated.
130 */
131 policyName?: string;
132 /**
133 * Optional IAM path prefix for the policy.
134 * @default "/"
135 */
136 path?: string;
137 /**
138 * The JSON IAM policy document.
139 */
140 policyDocument: PolicyDocument;
141 /**
142 * Optional description for the policy.
143 */
144 description?: string;
145 /**
146 * User-defined tags to apply to the managed policy.
147 */
148 tags?: Record<string, string>;
149 }
150
151 export interface Policy extends Resource<
152 "AWS.IAM.Policy",
153 PolicyProps,
154 {
155 /** The ARN of the policy. */
156 policyArn: PolicyArn;
157 /** The name of the policy. */
158 policyName: PolicyName;
159 /** The stable unique ID of the policy. */
160 policyId: string | undefined;
161 /** The IAM path of the policy. */
162 path: string | undefined;
163 /** The version currently set as the default (e.g. `v2`). */
164 defaultVersionId: string | undefined;
165 /** How many IAM identities the policy is attached to. */
166 attachmentCount: number | undefined;
167 /** How many IAM identities use the policy as a permissions boundary. */
168 permissionsBoundaryUsageCount: number | undefined;
169 /** Whether the policy can be attached to IAM identities. */
170 isAttachable: boolean | undefined;
171 /** The description of the policy. */
172 description: string | undefined;
173 /** The policy document of the default version. */
174 policyDocument: PolicyDocument;
175 /** The tags applied to the policy. */
176 tags: Record<string, string>;
177 },
178 never,
179 Providers
180 > {}
181
182 /**
183 * A customer-managed IAM policy.
184 *
185 * `Policy` owns the lifecycle of the policy metadata and its default version,
186 * rotating versions on updates while keeping the current document attached to a
187 * stable policy ARN.
188 * ### Creating Policies
189 * **Example:** Managed Policy
190 * ```typescript
191 * const policy = yield* Policy("AppPolicy", {
192 * policyDocument: {
193 * Version: "2012-10-17",
194 * Statement: [{
195 * Effect: "Allow",
196 * Action: ["s3:GetObject"],
197 * Resource: ["arn:aws:s3:::my-bucket/*"],
198 * }],
199 * },
200 * });
201 * ```
202 *
203 * @resource
204 */
205 export const Policy = Resource<Policy>("AWS.IAM.Policy");
206
207 export const PolicyProvider = () =>
208 Provider.effect(
209 Policy,
210 Effect.gen(function* () {
211 const toPolicyName = (id: string, props: PolicyProps) =>
212 props.policyName
213 ? Effect.succeed(props.policyName)
214 : createPhysicalName({ id, maxLength: 128 });
215
216 const toPolicyArn = Effect.fn(function* (id: string, props: PolicyProps) {
217 const { accountId } = yield* AWSEnvironment.current;
218 const policyName = yield* toPolicyName(id, props);
219 return policyArnFromParts({
220 accountId,
221 path: props.path,
222 policyName,
223 }) as PolicyArn;
224 });
225
226 const readPolicy = Effect.fn(function* (policyArn: string) {
227 const response = yield* iam
228 .getPolicy({ PolicyArn: policyArn })
229 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
230 return response?.Policy;
231 });
232
233 const readPolicyDocument = Effect.fn(function* ({
234 policyArn,
235 versionId,
236 }: {
237 policyArn: string;
238 versionId: string | undefined;
239 }) {
240 if (!versionId) {
241 return undefined;
242 }
243 const response = yield* iam
244 .getPolicyVersion({
245 PolicyArn: policyArn,
246 VersionId: versionId,
247 })
248 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
249 return parsePolicyDocument(response?.PolicyVersion?.Document);
250 });
251
252 const prunePolicyVersions = Effect.fn(function* (policyArn: string) {
253 const versions = yield* iam.listPolicyVersions({
254 PolicyArn: policyArn,
255 });
256 if ((versions.Versions?.length ?? 0) < 5) {
257 return;
258 }
259 const removable = oldestNondefaultPolicyVersion(versions.Versions);
260 if (!removable?.VersionId) {
261 return;
262 }
263 yield* iam.deletePolicyVersion({
264 PolicyArn: policyArn,
265 VersionId: removable.VersionId,
266 });
267 });
268
269 return {
270 stables: ["policyArn", "policyName", "policyId"],
271 list: () =>
272 Effect.gen(function* () {
273 // IAM is global; enumerate only customer-managed ("Local")
274 // policies, paginating exhaustively.
275 const policies = yield* iam.listPolicies.pages({ Scope: "Local" }).pipe(
276 Stream.runCollect,
277 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Policies ?? [])),
278 );
279 const rows = yield* Effect.forEach(
280 policies,
281 (policy) =>
282 Effect.gen(function* () {
283 if (!policy.Arn || !policy.PolicyName) {
284 return undefined;
285 }
286 const tags = yield* iam.listPolicyTags({
287 PolicyArn: policy.Arn,
288 });
289 const policyDocument = yield* readPolicyDocument({
290 policyArn: policy.Arn,
291 versionId: policy.DefaultVersionId,
292 });
293 if (!policyDocument) {
294 return undefined;
295 }
296 return {
297 policyArn: policy.Arn as PolicyArn,
298 policyName: policy.PolicyName,
299 policyId: policy.PolicyId,
300 path: policy.Path,
301 defaultVersionId: policy.DefaultVersionId,
302 attachmentCount: policy.AttachmentCount,
303 permissionsBoundaryUsageCount: policy.PermissionsBoundaryUsageCount,
304 isAttachable: policy.IsAttachable,
305 description: policy.Description,
306 policyDocument,
307 tags: toTagRecord(tags.Tags),
308 };
309 }).pipe(
310 // A peer test may delete a policy between `listPolicies` and
311 // hydrating its tags/version — skip the vanished entry rather
312 // than failing the whole enumeration.
313 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
314 ),
315 { concurrency: 10 },
316 );
317 return rows.filter((row): row is NonNullable<typeof row> => row !== undefined);
318 }),
319 diff: Effect.fn(function* ({ id, olds, news }) {
320 if (!isResolved(news)) return;
321 if (
322 (yield* toPolicyName(id, olds ?? ({} as PolicyProps))) !==
323 (yield* toPolicyName(id, news))
324 ) {
325 return { action: "replace" } as const;
326 }
327 if ((olds?.path ?? "/") !== (news.path ?? "/")) {
328 return { action: "replace" } as const;
329 }
330 if ((olds?.description ?? undefined) !== (news.description ?? undefined)) {
331 return { action: "replace" } as const;
332 }
333 }),
334 read: Effect.fn(function* ({ id, olds, output }) {
335 const policyArn =
336 output?.policyArn ?? (yield* toPolicyArn(id, olds ?? ({} as PolicyProps)));
337 const policy = yield* readPolicy(policyArn);
338 if (!policy?.Arn || !policy.PolicyName) {
339 return undefined;
340 }
341
342 const tags = yield* iam.listPolicyTags({
343 PolicyArn: policy.Arn,
344 });
345 const policyDocument = yield* readPolicyDocument({
346 policyArn: policy.Arn,
347 versionId: policy.DefaultVersionId,
348 });
349
350 if (!policyDocument) {
351 return undefined;
352 }
353
354 return {
355 policyArn: policy.Arn as PolicyArn,
356 policyName: policy.PolicyName,
357 policyId: policy.PolicyId,
358 path: policy.Path,
359 defaultVersionId: policy.DefaultVersionId,
360 attachmentCount: policy.AttachmentCount,
361 permissionsBoundaryUsageCount: policy.PermissionsBoundaryUsageCount,
362 isAttachable: policy.IsAttachable,
363 description: policy.Description,
364 policyDocument,
365 tags: toTagRecord(tags.Tags),
366 };
367 }),
368 reconcile: Effect.fn(function* ({ id, news, output, session }) {
369 const policyName = output?.policyName ?? (yield* toPolicyName(id, news));
370 const policyArn = output?.policyArn ?? (yield* toPolicyArn(id, news));
371 const desiredTags = {
372 ...(yield* createInternalTags(id)),
373 ...news.tags,
374 };
375
376 // Observe — fetch the policy metadata, current default-version
377 // document, and tags. Each piece feeds an independent sync step.
378 let observed = yield* readPolicy(policyArn);
379
380 // Ensure — create the managed policy when it is missing. We
381 // pass the desired document as the initial version so first
382 // create lands fully configured. On race, adopt by reading
383 // existing.
384 if (!observed?.Arn) {
385 const created = yield* iam
386 .createPolicy({
387 PolicyName: policyName,
388 Path: news.path,
389 PolicyDocument: stringifyPolicyDocument(news.policyDocument),
390 Description: news.description,
391 Tags: createTagsList(desiredTags),
392 })
393 .pipe(
394 Effect.catchTag("EntityAlreadyExistsException", () =>
395 Effect.gen(function* () {
396 const existing = yield* readPolicy(policyArn);
397 if (!existing?.Arn) {
398 return yield* new PolicyConflict({
399 message: `Policy '${policyName}' already exists but could not be described`,
400 });
401 }
402 const existingTags = yield* iam.listPolicyTags({
403 PolicyArn: existing.Arn,
404 });
405 if (!hasTags(desiredTags, existingTags.Tags)) {
406 return yield* new PolicyConflict({
407 message: `Policy '${policyName}' already exists and is not managed by alchemy`,
408 });
409 }
410 return { Policy: existing };
411 }),
412 ),
413 );
414 observed = created.Policy;
415 }
416
417 // Sync default-version document — IAM managed policies are
418 // immutable per version, so any document change requires
419 // creating a new default version (and pruning the oldest non-
420 // default if we're at the 5-version cap).
421 const observedDocument = yield* readPolicyDocument({
422 policyArn,
423 versionId: observed?.DefaultVersionId,
424 });
425 if (JSON.stringify(observedDocument ?? null) !== JSON.stringify(news.policyDocument)) {
426 yield* prunePolicyVersions(policyArn);
427 const createdVersion = yield* iam.createPolicyVersion({
428 PolicyArn: policyArn,
429 PolicyDocument: stringifyPolicyDocument(news.policyDocument),
430 SetAsDefault: true,
431 });
432 if (createdVersion.PolicyVersion?.VersionId) {
433 yield* iam.setDefaultPolicyVersion({
434 PolicyArn: policyArn,
435 VersionId: createdVersion.PolicyVersion.VersionId,
436 });
437 }
438 }
439
440 // Sync tags against the cloud's actual tags so adoption /
441 // out-of-band tag changes converge.
442 const observedTagsResp = yield* iam.listPolicyTags({
443 PolicyArn: policyArn,
444 });
445 const observedTags = toTagRecord(observedTagsResp.Tags);
446 const { removed, upsert } = diffTags(observedTags, desiredTags);
447 if (upsert.length > 0) {
448 yield* iam.tagPolicy({
449 PolicyArn: policyArn,
450 Tags: upsert,
451 });
452 }
453 if (removed.length > 0) {
454 yield* iam.untagPolicy({
455 PolicyArn: policyArn,
456 TagKeys: removed,
457 });
458 }
459
460 // Re-read for fresh metadata and the now-current document.
461 const fresh = yield* readPolicy(policyArn);
462 const freshDocument =
463 (yield* readPolicyDocument({
464 policyArn,
465 versionId: fresh?.DefaultVersionId,
466 })) ?? news.policyDocument;
467
468 yield* session.note(policyArn);
469 return {
470 policyArn,
471 policyName,
472 policyId: fresh?.PolicyId ?? observed?.PolicyId,
473 path: fresh?.Path ?? observed?.Path ?? news.path ?? "/",
474 defaultVersionId: fresh?.DefaultVersionId ?? observed?.DefaultVersionId,
475 attachmentCount: fresh?.AttachmentCount ?? observed?.AttachmentCount,
476 permissionsBoundaryUsageCount:
477 fresh?.PermissionsBoundaryUsageCount ?? observed?.PermissionsBoundaryUsageCount,
478 isAttachable: fresh?.IsAttachable ?? observed?.IsAttachable,
479 description: fresh?.Description ?? observed?.Description ?? news.description,
480 policyDocument: freshDocument,
481 tags: desiredTags,
482 };
483 }),
484 delete: Effect.fn(function* ({ output }) {
485 const versions = yield* iam
486 .listPolicyVersions({
487 PolicyArn: output.policyArn,
488 })
489 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
490 for (const version of versions?.Versions ?? []) {
491 if (!version.IsDefaultVersion && version.VersionId) {
492 yield* iam
493 .deletePolicyVersion({
494 PolicyArn: output.policyArn,
495 VersionId: version.VersionId,
496 })
497 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
498 }
499 }
500 yield* iam
501 .deletePolicy({
502 PolicyArn: output.policyArn,
503 })
504 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
505 }),
506 };
507 }),
508 );