The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
| 1 | import * as organizations from "@distilled.cloud/aws/organizations"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { hasAlchemyTags } from "alchemy/Tags"; |
| 7 | import * as Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import type { ServiceControlPolicyDocument } from "../IAM/Policy.ts"; |
| 11 | import { normalizePolicyDocument, stringifyPolicyDocument } from "../IAM/Policy.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { |
| 14 | collectPages, |
| 15 | createName, |
| 16 | readResourceTags, |
| 17 | retryOrganizations, |
| 18 | updateResourceTags, |
| 19 | } from "./common.ts"; |
| 20 | |
| 21 | export class OrganizationsPolicyUnexpectedResponse extends Data.TaggedError( |
| 22 | "OrganizationsPolicyUnexpectedResponse", |
| 23 | )<{ |
| 24 | readonly message: string; |
| 25 | readonly cause?: unknown; |
| 26 | }> {} |
| 27 | |
| 28 | export type PolicyId = string; |
| 29 | export type PolicyArn = string; |
| 30 | |
| 31 | export interface PolicyProps { |
| 32 | /** |
| 33 | * Policy name. If omitted, Alchemy generates one. |
| 34 | */ |
| 35 | name?: string; |
| 36 | /** |
| 37 | * Policy description. |
| 38 | * @default "" |
| 39 | */ |
| 40 | description?: string; |
| 41 | /** |
| 42 | * Organizations policy type. |
| 43 | */ |
| 44 | type: organizations.PolicyType; |
| 45 | /** |
| 46 | * Policy content. For `SERVICE_CONTROL_POLICY` / `RESOURCE_CONTROL_POLICY` |
| 47 | * pass a typed {@link ServiceControlPolicyDocument} (the SCP-legal IAM |
| 48 | * dialect — no `Principal`/`NotPrincipal`). Other policy types (tag, |
| 49 | * backup, AI-services opt-out, ...) use their own JSON grammars — pass |
| 50 | * them as a raw JSON `string`. The string form also serves as the |
| 51 | * escape hatch for adopted or hand-authored documents. |
| 52 | */ |
| 53 | document: ServiceControlPolicyDocument | string; |
| 54 | /** |
| 55 | * Optional tags applied to the policy. |
| 56 | */ |
| 57 | tags?: Record<string, string>; |
| 58 | } |
| 59 | |
| 60 | export interface Policy extends Resource< |
| 61 | "AWS.Organizations.Policy", |
| 62 | PolicyProps, |
| 63 | { |
| 64 | /** |
| 65 | * ID of the policy (e.g. `p-examplepolicyid`). |
| 66 | */ |
| 67 | policyId: PolicyId; |
| 68 | /** |
| 69 | * ARN of the policy. |
| 70 | */ |
| 71 | policyArn: PolicyArn; |
| 72 | /** |
| 73 | * Policy name. |
| 74 | */ |
| 75 | name: string; |
| 76 | /** |
| 77 | * Policy description. |
| 78 | */ |
| 79 | description: string | undefined; |
| 80 | /** |
| 81 | * Organizations policy type. |
| 82 | */ |
| 83 | type: organizations.PolicyType | undefined; |
| 84 | /** |
| 85 | * Whether the policy is an AWS-managed policy (e.g. `FullAWSAccess`). |
| 86 | */ |
| 87 | awsManaged: boolean | undefined; |
| 88 | /** |
| 89 | * Parsed policy document as currently stored by AWS Organizations. |
| 90 | */ |
| 91 | document: ServiceControlPolicyDocument; |
| 92 | /** |
| 93 | * Tags on the policy. |
| 94 | */ |
| 95 | tags: Record<string, string>; |
| 96 | }, |
| 97 | never, |
| 98 | Providers |
| 99 | > {} |
| 100 | |
| 101 | /** |
| 102 | * An AWS Organizations policy such as an SCP or tag policy. |
| 103 | * |
| 104 | * Attach it to a root, OU, or account with {@link PolicyAttachment}. Changing |
| 105 | * `type` or `name` replaces the policy; document and description changes |
| 106 | * update in place. |
| 107 | * ### Creating Policies |
| 108 | * **Example:** Service Control Policy (Typed Document) |
| 109 | * ```typescript |
| 110 | * const denyLeaveOrg = yield* Policy("DenyLeaveOrg", { |
| 111 | * type: "SERVICE_CONTROL_POLICY", |
| 112 | * description: "Prevent member accounts from leaving the organization", |
| 113 | * document: { |
| 114 | * Version: "2012-10-17", |
| 115 | * Statement: [ |
| 116 | * { |
| 117 | * Effect: "Deny", |
| 118 | * Action: ["organizations:LeaveOrganization"], |
| 119 | * Resource: "*", |
| 120 | * }, |
| 121 | * ], |
| 122 | * }, |
| 123 | * }); |
| 124 | * ``` |
| 125 | * |
| 126 | * **Example:** Tag Policy (Raw JSON) |
| 127 | * ```typescript |
| 128 | * const tagPolicy = yield* Policy("RequireEnvTag", { |
| 129 | * type: "TAG_POLICY", |
| 130 | * document: JSON.stringify({ |
| 131 | * tags: { |
| 132 | * environment: { |
| 133 | * tag_key: { "@@assign": "environment" }, |
| 134 | * tag_value: { "@@assign": ["dev", "staging", "prod"] }, |
| 135 | * }, |
| 136 | * }, |
| 137 | * }), |
| 138 | * }); |
| 139 | * ``` |
| 140 | * |
| 141 | * ### Attaching Policies |
| 142 | * **Example:** Attach an SCP to the Organization Root |
| 143 | * ```typescript |
| 144 | * const root = yield* Root("Root", {}); |
| 145 | * |
| 146 | * const scpEnabled = yield* RootPolicyType("ScpEnabled", { |
| 147 | * rootId: root.rootId, |
| 148 | * policyType: "SERVICE_CONTROL_POLICY", |
| 149 | * }); |
| 150 | * |
| 151 | * yield* PolicyAttachment("DenyLeaveOrgOnRoot", { |
| 152 | * policyId: denyLeaveOrg.policyId, |
| 153 | * targetId: scpEnabled.rootId, |
| 154 | * }); |
| 155 | * ``` |
| 156 | * |
| 157 | * @resource |
| 158 | */ |
| 159 | export const Policy = Resource<Policy>("AWS.Organizations.Policy"); |
| 160 | |
| 161 | export const PolicyProvider = () => |
| 162 | Provider.effect( |
| 163 | Policy, |
| 164 | Effect.gen(function* () { |
| 165 | return { |
| 166 | stables: ["policyId", "policyArn"], |
| 167 | diff: Effect.fn(function* ({ id, olds, news }) { |
| 168 | if (!isResolved(news)) return; |
| 169 | if (olds?.type !== news.type) { |
| 170 | return { action: "replace" } as const; |
| 171 | } |
| 172 | |
| 173 | const oldName = yield* toName(id, olds ?? {}); |
| 174 | const newName = yield* toName(id, news); |
| 175 | if (oldName !== newName) { |
| 176 | return { action: "replace" } as const; |
| 177 | } |
| 178 | }), |
| 179 | read: Effect.fn(function* ({ id, olds, output }) { |
| 180 | const state = output?.policyId |
| 181 | ? yield* readPolicyById(output.policyId) |
| 182 | : olds |
| 183 | ? yield* readPolicyByName({ |
| 184 | type: olds.type, |
| 185 | name: yield* toName(id, olds), |
| 186 | }) |
| 187 | : undefined; |
| 188 | if (!state) return undefined; |
| 189 | return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state); |
| 190 | }), |
| 191 | // `listPolicies` REQUIRES a `Filter` (one policy type per call), so we |
| 192 | // fan out across every policy-type filter and hydrate each summary via |
| 193 | // `describePolicy` into the exact `read` shape. Degrades to `[]` when |
| 194 | // the account isn't an org management/delegated-admin account |
| 195 | // (`AWSOrganizationsNotInUseException`/`AccessDeniedException`) and skips |
| 196 | // disabled policy types per-filter. |
| 197 | list: () => |
| 198 | Effect.gen(function* () { |
| 199 | const summaries = yield* Effect.forEach( |
| 200 | POLICY_TYPE_FILTERS, |
| 201 | (type) => |
| 202 | retryOrganizations( |
| 203 | collectPages( |
| 204 | (NextToken) => organizations.listPolicies({ Filter: type, NextToken }), |
| 205 | (page) => page.Policies, |
| 206 | ), |
| 207 | ).pipe( |
| 208 | // Not an org management/delegated account → nothing to list. |
| 209 | Effect.catchTag( |
| 210 | ["AWSOrganizationsNotInUseException", "AccessDeniedException"], |
| 211 | () => Effect.succeed([] as organizations.PolicySummary[]), |
| 212 | ), |
| 213 | ), |
| 214 | { concurrency: 10 }, |
| 215 | ); |
| 216 | |
| 217 | const ids = summaries |
| 218 | .flat() |
| 219 | .map((summary) => summary.Id) |
| 220 | .filter((policyId): policyId is string => policyId != null); |
| 221 | |
| 222 | const hydrated = yield* Effect.forEach(ids, (policyId) => readPolicyById(policyId), { |
| 223 | concurrency: 10, |
| 224 | }); |
| 225 | |
| 226 | return hydrated.filter( |
| 227 | (policy): policy is Policy["Attributes"] => policy !== undefined, |
| 228 | ); |
| 229 | }), |
| 230 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 231 | const name = yield* toName(id, news); |
| 232 | const desiredDescription = news.description ?? ""; |
| 233 | const desiredContent = |
| 234 | typeof news.document === "string" |
| 235 | ? news.document |
| 236 | : stringifyPolicyDocument(news.document); |
| 237 | |
| 238 | // Observe — locate the policy by ID if known, else by type+name. |
| 239 | // Both `name` (after generation) and `type` are stable, so `diff` |
| 240 | // handles renames as a replacement; here we just look up. |
| 241 | let state = output?.policyId |
| 242 | ? yield* readPolicyById(output.policyId) |
| 243 | : yield* readPolicyByName({ |
| 244 | type: news.type, |
| 245 | name, |
| 246 | }); |
| 247 | |
| 248 | // Ensure — create the policy if missing. Tolerate |
| 249 | // `DuplicatePolicyException` as adoption (a peer reconciler beat |
| 250 | // us, or our observation lost a race). |
| 251 | if (!state) { |
| 252 | yield* retryOrganizations( |
| 253 | organizations |
| 254 | .createPolicy({ |
| 255 | Name: name, |
| 256 | Description: desiredDescription, |
| 257 | Type: news.type, |
| 258 | Content: desiredContent, |
| 259 | }) |
| 260 | .pipe(Effect.catchTag("DuplicatePolicyException", () => Effect.void)), |
| 261 | ); |
| 262 | state = yield* readPolicyByName({ |
| 263 | type: news.type, |
| 264 | name, |
| 265 | }); |
| 266 | if (!state) { |
| 267 | return yield* new OrganizationsPolicyUnexpectedResponse({ |
| 268 | message: `policy '${name}' not found after create`, |
| 269 | }); |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | // Sync description + content — diff observed cloud state against |
| 274 | // desired. Documents are compared in canonical form |
| 275 | // (`normalizePolicyDocument`: sorted keys, no whitespace) so an |
| 276 | // unchanged re-deploy — regardless of key order or string-vs-typed |
| 277 | // authoring — skips the `updatePolicy` call entirely. |
| 278 | // `updatePolicy` requires `Name`; we keep the existing policy name |
| 279 | // (rename triggers replacement at the diff level). |
| 280 | const observedDescription = state.description ?? ""; |
| 281 | if ( |
| 282 | observedDescription !== desiredDescription || |
| 283 | normalizePolicyDocument(state.document) !== normalizePolicyDocument(desiredContent) |
| 284 | ) { |
| 285 | yield* retryOrganizations( |
| 286 | organizations.updatePolicy({ |
| 287 | PolicyId: state.policyId, |
| 288 | Name: state.name, |
| 289 | Description: desiredDescription, |
| 290 | Content: desiredContent, |
| 291 | }), |
| 292 | ); |
| 293 | } |
| 294 | |
| 295 | // Sync tags — diff observed cloud tags against desired. Using |
| 296 | // `state.tags` (fetched fresh) keeps the reconciler convergent on |
| 297 | // adoption and drift. |
| 298 | const tags = yield* updateResourceTags({ |
| 299 | id, |
| 300 | resourceId: state.policyId, |
| 301 | olds: state.tags, |
| 302 | news: news.tags, |
| 303 | }); |
| 304 | |
| 305 | const updated = yield* readPolicyById(state.policyId); |
| 306 | if (!updated) { |
| 307 | return yield* new OrganizationsPolicyUnexpectedResponse({ |
| 308 | message: `policy '${state.policyId}' not found after reconcile`, |
| 309 | }); |
| 310 | } |
| 311 | |
| 312 | yield* session.note(updated.policyArn); |
| 313 | return { |
| 314 | ...updated, |
| 315 | tags, |
| 316 | }; |
| 317 | }), |
| 318 | delete: Effect.fn(function* ({ output }) { |
| 319 | yield* retryOrganizations( |
| 320 | organizations.deletePolicy({ PolicyId: output.policyId }).pipe( |
| 321 | // Detaching a policy (the attachment's delete) propagates |
| 322 | // asynchronously — deletePolicy issued right after the detach |
| 323 | // can still observe the policy as attached. Retry through the |
| 324 | // typed dependency-violation tag, bounded. |
| 325 | Effect.retry({ |
| 326 | while: (error) => error._tag === "PolicyInUseException", |
| 327 | schedule: Schedule.spaced("3 seconds"), |
| 328 | times: 8, |
| 329 | }), |
| 330 | Effect.catchTag("PolicyNotFoundException", () => Effect.void), |
| 331 | ), |
| 332 | ); |
| 333 | }), |
| 334 | }; |
| 335 | }), |
| 336 | ); |
| 337 | |
| 338 | // The documented `ListPolicies` `Filter` values. `listPolicies` requires a |
| 339 | // single policy type per call, so `list()` fans out across all of them. |
| 340 | const POLICY_TYPE_FILTERS = [ |
| 341 | "SERVICE_CONTROL_POLICY", |
| 342 | "RESOURCE_CONTROL_POLICY", |
| 343 | "DECLARATIVE_POLICY_EC2", |
| 344 | "BACKUP_POLICY", |
| 345 | "TAG_POLICY", |
| 346 | "CHATBOT_POLICY", |
| 347 | "AISERVICES_OPT_OUT_POLICY", |
| 348 | "SECURITYHUB_POLICY", |
| 349 | ] as const satisfies readonly organizations.PolicyType[]; |
| 350 | |
| 351 | const toName = (id: string, props: { name?: string } = {}) => createName(id, props.name, 128); |
| 352 | |
| 353 | const readPolicyById = Effect.fn(function* (policyId: string) { |
| 354 | const described = yield* retryOrganizations( |
| 355 | organizations.describePolicy({ PolicyId: policyId }).pipe( |
| 356 | Effect.map((response) => response.Policy), |
| 357 | Effect.catchTag("PolicyNotFoundException", () => Effect.undefined), |
| 358 | ), |
| 359 | ); |
| 360 | |
| 361 | const summary = described?.PolicySummary; |
| 362 | if (!summary?.Id || !summary.Arn || !summary.Name) { |
| 363 | return undefined; |
| 364 | } |
| 365 | |
| 366 | const tags = yield* readResourceTags(summary.Id).pipe( |
| 367 | Effect.catchTag("TargetNotFoundException", () => Effect.succeed({})), |
| 368 | ); |
| 369 | |
| 370 | return { |
| 371 | policyId: summary.Id, |
| 372 | policyArn: summary.Arn, |
| 373 | name: summary.Name, |
| 374 | description: summary.Description, |
| 375 | type: summary.Type, |
| 376 | awsManaged: summary.AwsManaged, |
| 377 | document: JSON.parse(described?.Content ?? "{}") as ServiceControlPolicyDocument, |
| 378 | tags, |
| 379 | } satisfies Policy["Attributes"]; |
| 380 | }); |
| 381 | |
| 382 | const readPolicyByName = Effect.fn(function* ({ |
| 383 | type, |
| 384 | name, |
| 385 | }: { |
| 386 | type: organizations.PolicyType; |
| 387 | name: string; |
| 388 | }) { |
| 389 | const policies = yield* retryOrganizations( |
| 390 | collectPages( |
| 391 | (NextToken) => organizations.listPolicies({ Filter: type, NextToken }), |
| 392 | (page) => page.Policies, |
| 393 | ), |
| 394 | ); |
| 395 | |
| 396 | const match = policies.find((policy) => policy.Name === name); |
| 397 | return match?.Id ? yield* readPolicyById(match.Id) : undefined; |
| 398 | }); |