@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 04:45 UTC

main
ts 305 lines 12 KB
Raw
1 import * as controltower from "@distilled.cloud/aws/controltower";
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 { createInternalTags, 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 * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { canonicalParameters, observeControlTowerTags, syncControlTowerTags } from "./internal.ts";
13
14 export interface EnabledControlProps {
15 /**
16 * The identifier (ARN) of the control to enable, e.g.
17 * `arn:aws:controltower:us-west-2::control/AWS-GR_ENCRYPTED_VOLUMES` or a
18 * Control Catalog ARN. Changing the control replaces the enablement.
19 */
20 controlIdentifier: string;
21 /**
22 * The ARN of the organizational unit the control is enabled on.
23 * Changing the target replaces the enablement.
24 */
25 targetIdentifier: string;
26 /**
27 * Parameters for configurable controls, as `{ key, value }` pairs.
28 * Updated in place via `UpdateEnabledControl`.
29 */
30 parameters?: { key: string; value: any }[];
31 /**
32 * Tags to apply to the enabled control. Merged with internal Alchemy
33 * tags.
34 */
35 tags?: Record<string, string>;
36 }
37
38 export interface EnabledControl extends Resource<
39 "AWS.ControlTower.EnabledControl",
40 EnabledControlProps,
41 {
42 /**
43 * The ARN of the enabled control.
44 */
45 enabledControlArn: string;
46 /**
47 * The identifier of the enabled control.
48 */
49 controlIdentifier: string;
50 /**
51 * The ARN of the organizational unit the control is enabled on.
52 */
53 targetIdentifier: string;
54 },
55 never,
56 Providers
57 > {}
58
59 /**
60 * An AWS Control Tower control (guardrail) enabled on an organizational
61 * unit. Enabling a control starts an asynchronous operation that deploys
62 * governance resources (SCPs, Config rules, or hooks) to the OU and the
63 * accounts it contains.
64 *
65 * Requires an AWS Control Tower landing zone and can only be managed from
66 * the Organizations management account.
67 * ### Enabling Controls
68 * **Example:** Enable a preventive guardrail on an OU
69 * ```typescript
70 * import * as ControlTower from "@alchemy.run/aws/ControlTower";
71 *
72 * const encryptedVolumes = yield* ControlTower.EnabledControl("EncryptedVolumes", {
73 * controlIdentifier:
74 * "arn:aws:controltower:us-west-2::control/AWS-GR_ENCRYPTED_VOLUMES",
75 * targetIdentifier: "arn:aws:organizations::111122223333:ou/o-example/ou-example",
76 * });
77 * ```
78 *
79 * **Example:** Enable a configurable control with parameters
80 * ```typescript
81 * const regionDeny = yield* ControlTower.EnabledControl("RegionDeny", {
82 * controlIdentifier:
83 * "arn:aws:controlcatalog:::control/50utmyu7yqmhr8fpnpo8bnaj1",
84 * targetIdentifier: ouArn,
85 * parameters: [
86 * { key: "AllowedRegions", value: ["us-east-1", "us-west-2"] },
87 * ],
88 * });
89 * ```
90 *
91 * @resource
92 */
93 export const EnabledControl = Resource<EnabledControl>("AWS.ControlTower.EnabledControl");
94
95 /**
96 * An asynchronous control operation (ENABLE_CONTROL / DISABLE_CONTROL /
97 * UPDATE_ENABLED_CONTROL) converged to the terminal `FAILED` status.
98 */
99 export class ControlOperationFailed extends Data.TaggedError("ControlOperationFailed")<{
100 readonly operationIdentifier: string;
101 readonly status: string;
102 readonly statusMessage: string | undefined;
103 }> {}
104
105 /**
106 * `EnableControl` succeeded but the enabled control's ARN could not be
107 * resolved from either the operation output or `ListEnabledControls`.
108 */
109 export class EnabledControlArnUnavailable extends Data.TaggedError("EnabledControlArnUnavailable")<{
110 readonly controlIdentifier: string;
111 readonly targetIdentifier: string;
112 }> {}
113
114 /**
115 * Internal signal that a control operation is still `IN_PROGRESS`,
116 * consumed by {@link waitForControlOperation}'s bounded schedule.
117 */
118 class ControlOperationPending extends Data.TaggedError("ControlOperationPending")<{
119 readonly operationIdentifier: string;
120 readonly status: string | undefined;
121 }> {}
122
123 // Explicitly-typed retry wrappers — an inline `Effect.retry` in provider
124 // lifecycle code leaks `Retry.Return`'s conditional type into declaration
125 // emit and widens the provider layer to `unknown` for every consumer of
126 // `AWS.providers()`.
127 const retryWhileControlOperationPending = <A, E extends { readonly _tag: string }, R>(
128 self: Effect.Effect<A, E, R>,
129 ): Effect.Effect<A, E, R> =>
130 Effect.retry(self, {
131 while: (e) => e._tag === "ControlOperationPending",
132 // Control operations deploy SCPs/Config rules across an OU's accounts
133 // and typically take a few minutes; poll every 10s up to ~15 minutes.
134 schedule: Schedule.max([Schedule.spaced("10 seconds"), Schedule.recurs(90)]),
135 });
136
137 // Control Tower serializes control operations per OU — a concurrent
138 // operation surfaces as a typed ConflictException. Retry through it on a
139 // bounded schedule.
140 const retryWhileControlConflict = <A, E extends { readonly _tag: string }, R>(
141 self: Effect.Effect<A, E, R>,
142 ): Effect.Effect<A, E, R> =>
143 Effect.retry(self, {
144 while: (e) => e._tag === "ConflictException",
145 schedule: Schedule.max([Schedule.spaced("15 seconds"), Schedule.recurs(40)]),
146 });
147
148 const waitForControlOperation = (operationIdentifier: string) =>
149 retryWhileControlOperationPending(
150 Effect.gen(function* () {
151 const { controlOperation } = yield* controltower.getControlOperation({
152 operationIdentifier,
153 });
154 if (controlOperation.status === "SUCCEEDED") {
155 return;
156 }
157 if (controlOperation.status === "FAILED") {
158 return yield* new ControlOperationFailed({
159 operationIdentifier,
160 status: controlOperation.status,
161 statusMessage: controlOperation.statusMessage,
162 });
163 }
164 return yield* new ControlOperationPending({
165 operationIdentifier,
166 status: controlOperation.status,
167 });
168 }),
169 );
170
171 const readEnabledControl = (enabledControlArn: string) =>
172 controltower.getEnabledControl({ enabledControlIdentifier: enabledControlArn }).pipe(
173 Effect.map((r) => r.enabledControlDetails),
174 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
175 );
176
177 // Find an enabled control by (controlIdentifier, targetIdentifier) —
178 // covers the create-race and lost-output cases where we don't have the
179 // ARN cached.
180 const findEnabledControlArn = (controlIdentifier: string, targetIdentifier: string) =>
181 controltower.listEnabledControls.pages({ targetIdentifier }).pipe(
182 Stream.runCollect,
183 Effect.map(
184 (chunk) =>
185 Array.from(chunk)
186 .flatMap((page) => page.enabledControls)
187 .find((summary) => summary.controlIdentifier === controlIdentifier)?.arn,
188 ),
189 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
190 );
191
192 export const EnabledControlProvider = () =>
193 Provider.effect(
194 EnabledControl,
195 Effect.gen(function* () {
196 return EnabledControl.Provider.of({
197 stables: ["enabledControlArn", "controlIdentifier", "targetIdentifier"],
198 // Enumeration requires a target OU — there is no org-wide listing
199 // that returns the full attribute shape without the management
200 // account's OU tree, so nuke discovery is not supported.
201 list: () => Effect.succeed([]),
202 read: Effect.fn(function* ({ id, olds, output }) {
203 const arn =
204 output?.enabledControlArn ??
205 (olds !== undefined
206 ? yield* findEnabledControlArn(olds.controlIdentifier, olds.targetIdentifier)
207 : undefined);
208 if (arn === undefined) return undefined;
209 const details = yield* readEnabledControl(arn);
210 if (details === undefined) return undefined;
211 const attrs = {
212 enabledControlArn: arn,
213 controlIdentifier: details.controlIdentifier ?? olds?.controlIdentifier ?? "",
214 targetIdentifier: details.targetIdentifier ?? olds?.targetIdentifier ?? "",
215 };
216 const tags = yield* observeControlTowerTags(arn);
217 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
218 }),
219 diff: Effect.fn(function* ({ news, olds }) {
220 if (!isResolved(news)) return undefined;
221 if (
222 news.controlIdentifier !== olds.controlIdentifier ||
223 news.targetIdentifier !== olds.targetIdentifier
224 ) {
225 return { action: "replace" } as const;
226 }
227 }),
228 reconcile: Effect.fn(function* ({ id, news, output, session }) {
229 // 1. Observe — cloud state is authoritative; output is only an
230 // ARN cache.
231 let arn = output?.enabledControlArn;
232 let details = arn === undefined ? undefined : yield* readEnabledControl(arn);
233 if (details === undefined) {
234 arn = yield* findEnabledControlArn(news.controlIdentifier, news.targetIdentifier);
235 details = arn === undefined ? undefined : yield* readEnabledControl(arn);
236 }
237
238 // 2. Ensure — enable if missing and wait for the asynchronous
239 // operation to converge.
240 if (details === undefined) {
241 const internalTags = yield* createInternalTags(id);
242 const enabled = yield* retryWhileControlConflict(
243 controltower.enableControl({
244 controlIdentifier: news.controlIdentifier,
245 targetIdentifier: news.targetIdentifier,
246 parameters: news.parameters,
247 tags: { ...news.tags, ...internalTags },
248 }),
249 );
250 yield* session.note(`control operation ${enabled.operationIdentifier}`);
251 yield* waitForControlOperation(enabled.operationIdentifier);
252 arn =
253 enabled.arn ??
254 (yield* findEnabledControlArn(news.controlIdentifier, news.targetIdentifier));
255 if (arn === undefined) {
256 return yield* new EnabledControlArnUnavailable({
257 controlIdentifier: news.controlIdentifier,
258 targetIdentifier: news.targetIdentifier,
259 });
260 }
261 details = yield* readEnabledControl(arn);
262 } else if (news.parameters !== undefined) {
263 // 3. Sync — parameters are the only in-place-mutable aspect.
264 // Diff observed parameter summaries against desired; skip
265 // the API on a no-op. Parameters cannot be cleared (the
266 // update API requires them), so an absent `parameters` prop
267 // leaves observed parameters alone.
268 const observed = canonicalParameters(details.parameters);
269 const desired = canonicalParameters(news.parameters);
270 if (observed !== desired) {
271 const updated = yield* retryWhileControlConflict(
272 controltower.updateEnabledControl({
273 enabledControlIdentifier: arn!,
274 parameters: news.parameters,
275 }),
276 );
277 yield* session.note(`control operation ${updated.operationIdentifier}`);
278 yield* waitForControlOperation(updated.operationIdentifier);
279 }
280 }
281
282 // 3b. Sync tags against observed cloud tags.
283 yield* syncControlTowerTags(arn!, id, news.tags);
284
285 // 4. Return fresh attributes.
286 return {
287 enabledControlArn: arn!,
288 controlIdentifier: news.controlIdentifier,
289 targetIdentifier: news.targetIdentifier,
290 };
291 }),
292 delete: Effect.fn(function* ({ output, session }) {
293 const result = yield* retryWhileControlConflict(
294 controltower.disableControl({
295 enabledControlIdentifier: output.enabledControlArn,
296 }),
297 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
298 if (result !== undefined) {
299 yield* session.note(`control operation ${result.operationIdentifier}`);
300 yield* waitForControlOperation(result.operationIdentifier);
301 }
302 }),
303 });
304 }),
305 );