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

main
ts 291 lines 9.7 KB
Raw
1 import * as organizations from "@distilled.cloud/aws/organizations";
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 type { Providers } from "../Providers.ts";
8 import { collectPages, retryOrganizations } from "./common.ts";
9
10 export class PolicyAttachmentUnexpectedResponse extends Data.TaggedError(
11 "PolicyAttachmentUnexpectedResponse",
12 )<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface PolicyAttachmentProps {
18 /**
19 * Policy to attach.
20 */
21 policyId: string;
22 /**
23 * Target root, OU, or account ID.
24 */
25 targetId: string;
26 }
27
28 export interface PolicyAttachment extends Resource<
29 "AWS.Organizations.PolicyAttachment",
30 PolicyAttachmentProps,
31 {
32 /**
33 * ID of the attached policy.
34 */
35 policyId: string;
36 /**
37 * ID of the root, OU, or account the policy is attached to.
38 */
39 targetId: string;
40 /**
41 * ARN of the attachment target.
42 */
43 targetArn: string | undefined;
44 /**
45 * Friendly name of the attachment target.
46 */
47 targetName: string | undefined;
48 /**
49 * Kind of the attachment target (`ROOT`, `ORGANIZATIONAL_UNIT`, or
50 * `ACCOUNT`).
51 */
52 targetType: organizations.TargetType | undefined;
53 },
54 never,
55 Providers
56 > {}
57
58 /**
59 * Attaches an Organizations {@link Policy} to a root, OU, or account.
60 *
61 * Existence-only resource: changing either `policyId` or `targetId` replaces
62 * the attachment. The policy's type must already be enabled on the root (see
63 * {@link RootPolicyType}).
64 * ### Attaching Policies
65 * **Example:** Attach an SCP to an Organizational Unit
66 * ```typescript
67 * const workloads = yield* OrganizationalUnit("Workloads", {
68 * parentId: root.rootId,
69 * name: "workloads",
70 * });
71 *
72 * const denyRegions = yield* Policy("DenyOtherRegions", {
73 * type: "SERVICE_CONTROL_POLICY",
74 * document: {
75 * Version: "2012-10-17",
76 * Statement: [
77 * {
78 * Effect: "Deny",
79 * NotAction: ["iam:*", "organizations:*", "sts:*"],
80 * Resource: "*",
81 * Condition: {
82 * StringNotEquals: { "aws:RequestedRegion": ["us-east-1", "us-west-2"] },
83 * },
84 * },
85 * ],
86 * },
87 * });
88 *
89 * yield* PolicyAttachment("DenyRegionsOnWorkloads", {
90 * policyId: denyRegions.policyId,
91 * targetId: workloads.ouId,
92 * });
93 * ```
94 *
95 * **Example:** Attach a Policy to a Member Account
96 * ```typescript
97 * yield* PolicyAttachment("DenyRegionsOnDev", {
98 * policyId: denyRegions.policyId,
99 * targetId: devAccount.accountId,
100 * });
101 * ```
102 *
103 * @resource
104 */
105 export const PolicyAttachment = Resource<PolicyAttachment>("AWS.Organizations.PolicyAttachment");
106
107 export const PolicyAttachmentProvider = () =>
108 Provider.effect(
109 PolicyAttachment,
110 Effect.gen(function* () {
111 return {
112 stables: ["policyId", "targetId"],
113 diff: Effect.fn(function* ({ olds, news }) {
114 if (!isResolved(news)) return;
115 if (olds?.policyId !== news.policyId || olds?.targetId !== news.targetId) {
116 return { action: "replace" } as const;
117 }
118 }),
119 read: Effect.fn(function* ({ olds, output }) {
120 const policyId = output?.policyId ?? olds?.policyId;
121 const targetId = output?.targetId ?? olds?.targetId;
122 if (policyId === undefined || targetId === undefined) {
123 // A `creating` row persisted before upstream Outputs resolved
124 // can't round-trip Output-valued ids — they deserialize as
125 // `undefined`. Report "not found" so the engine re-drives the
126 // create (reconcile observes before attaching).
127 return undefined;
128 }
129 return yield* readAttachment({ policyId, targetId });
130 }),
131 // Enumerate every (policy, target) attachment. There is no direct
132 // "list attachments" API, so we fan out: for each policy type, list the
133 // policies of that type, then list each policy's targets, emitting one
134 // Attributes per (policy, target) pair — the exact shape `read` returns.
135 // listPolicies/listTargetsForPolicy may only be called from the org
136 // management account or a delegated administrator; a member account or a
137 // standalone account that isn't part of an org rejects with the typed
138 // AccessDeniedException / AWSOrganizationsNotInUseException, which we
139 // degrade to [].
140 list: () =>
141 Effect.gen(function* () {
142 const perType = yield* Effect.forEach(
143 POLICY_TYPES,
144 (Filter) =>
145 Effect.gen(function* () {
146 const policies = yield* retryOrganizations(
147 collectPages(
148 (NextToken) => organizations.listPolicies({ Filter, NextToken }),
149 (page) => page.Policies,
150 ),
151 );
152 const policyIds = policies
153 .map((policy) => policy.Id)
154 .filter((id): id is string => id != null);
155 const perPolicy = yield* Effect.forEach(
156 policyIds,
157 (policyId) => listAttachmentsForPolicy(policyId),
158 { concurrency: 10 },
159 );
160 return perPolicy.flat();
161 }),
162 { concurrency: 10 },
163 );
164 return perType.flat();
165 }).pipe(
166 Effect.catchTags({
167 AccessDeniedException: () => Effect.succeed([] as PolicyAttachment["Attributes"][]),
168 AWSOrganizationsNotInUseException: () =>
169 Effect.succeed([] as PolicyAttachment["Attributes"][]),
170 }),
171 ),
172 reconcile: Effect.fn(function* ({ news, session }) {
173 // Observe — list current attachments to see whether ours is present.
174 // The attachment is identity-only; both `policyId` and `targetId`
175 // are stable, so `diff` handles any change as a replacement.
176 let state = yield* readAttachment(news);
177
178 // Ensure — attach if missing. `DuplicatePolicyAttachmentException`
179 // is treated as success (e.g. a peer reconciler attached
180 // concurrently, or our observation lost a race).
181 if (!state) {
182 yield* retryOrganizations(
183 organizations
184 .attachPolicy({
185 PolicyId: news.policyId,
186 TargetId: news.targetId,
187 })
188 .pipe(Effect.catchTag("DuplicatePolicyAttachmentException", () => Effect.void)),
189 );
190 state = yield* readAttachment(news);
191 if (!state) {
192 return yield* new PolicyAttachmentUnexpectedResponse({
193 message: `policy attachment '${news.policyId}' -> '${news.targetId}' not found after create`,
194 });
195 }
196 }
197
198 yield* session.note(`${state.policyId}:${state.targetId}`);
199 return state;
200 }),
201 delete: Effect.fn(function* ({ output }) {
202 yield* retryOrganizations(
203 organizations
204 .detachPolicy({
205 PolicyId: output.policyId,
206 TargetId: output.targetId,
207 })
208 .pipe(
209 Effect.catchTags({
210 PolicyNotAttachedException: () => Effect.void,
211 PolicyNotFoundException: () => Effect.void,
212 TargetNotFoundException: () => Effect.void,
213 }),
214 ),
215 );
216 }),
217 };
218 }),
219 );
220
221 // All policy types that can be attached to a root, OU, or account. `list()`
222 // fans out over each of these because listPolicies requires an explicit
223 // `Filter` and only returns policies of that single type.
224 const POLICY_TYPES = [
225 "SERVICE_CONTROL_POLICY",
226 "RESOURCE_CONTROL_POLICY",
227 "TAG_POLICY",
228 "BACKUP_POLICY",
229 "AISERVICES_OPT_OUT_POLICY",
230 "CHATBOT_POLICY",
231 "DECLARATIVE_POLICY_EC2",
232 "SECURITYHUB_POLICY",
233 "INSPECTOR_POLICY",
234 "UPGRADE_ROLLOUT_POLICY",
235 "BEDROCK_POLICY",
236 "S3_POLICY",
237 "NETWORK_SECURITY_DIRECTOR_POLICY",
238 ] as const satisfies readonly organizations.PolicyType[];
239
240 const listAttachmentsForPolicy = (policyId: string) =>
241 retryOrganizations(
242 collectPages(
243 (NextToken) => organizations.listTargetsForPolicy({ PolicyId: policyId, NextToken }),
244 (page) => page.Targets,
245 ),
246 ).pipe(
247 Effect.map((targets) =>
248 targets
249 .filter(
250 (
251 target,
252 ): target is organizations.PolicyTargetSummary & {
253 TargetId: string;
254 } => target.TargetId != null,
255 )
256 .map(
257 (target) =>
258 ({
259 policyId,
260 targetId: target.TargetId,
261 targetArn: target.Arn,
262 targetName: target.Name,
263 targetType: target.Type,
264 }) satisfies PolicyAttachment["Attributes"],
265 ),
266 ),
267 // The policy was deleted between enumeration and target read — skip it.
268 Effect.catchTag("PolicyNotFoundException", () =>
269 Effect.succeed([] as PolicyAttachment["Attributes"][]),
270 ),
271 );
272
273 const readAttachment = Effect.fn(function* ({ policyId, targetId }: PolicyAttachmentProps) {
274 const targets = yield* retryOrganizations(
275 collectPages(
276 (NextToken) => organizations.listTargetsForPolicy({ PolicyId: policyId, NextToken }),
277 (page) => page.Targets,
278 ),
279 );
280
281 const target = targets.find((candidate) => candidate.TargetId === targetId);
282 return target
283 ? ({
284 policyId,
285 targetId,
286 targetArn: target.Arn,
287 targetName: target.Name,
288 targetType: target.Type,
289 } satisfies PolicyAttachment["Attributes"])
290 : undefined;
291 });