@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 361 lines 12.4 KB
Raw
1 import * as auditmanager from "@distilled.cloud/aws/auditmanager";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags, type Tags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as EffectStream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { toTagRecord, unredact } from "./internal.ts";
12
13 export class ControlUnexpectedResponse extends Data.TaggedError("ControlUnexpectedResponse")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 /**
19 * The keyword used to search evidence for a control mapping source.
20 */
21 export interface ControlSourceKeyword {
22 /**
23 * How the keyword is entered (`SELECT_FROM_LIST`, `UPLOAD_FILE`, or
24 * `INPUT_TEXT`).
25 */
26 keywordInputType?: auditmanager.KeywordInputType;
27 /**
28 * The value of the keyword — e.g. a CloudTrail event name, a Config rule
29 * name, or a Security Hub control name.
30 */
31 keywordValue?: string;
32 }
33
34 /**
35 * A data source Audit Manager collects evidence from for a custom control.
36 */
37 export interface ControlMappingSourceProps {
38 /**
39 * Name of the evidence source.
40 */
41 sourceName: string;
42 /**
43 * A description of the source.
44 */
45 sourceDescription?: string;
46 /**
47 * How the source collects evidence: `System_Controls_Mapping` (automated)
48 * or `Procedural_Controls_Mapping` (manual).
49 */
50 sourceSetUpOption?: auditmanager.SourceSetUpOption;
51 /**
52 * The evidence collection method (`AWS_Cloudtrail`, `AWS_Config`,
53 * `AWS_Security_Hub`, `AWS_API_Call`, or `MANUAL`).
54 */
55 sourceType?: auditmanager.SourceType;
56 /**
57 * The keyword that scopes what evidence the source collects.
58 */
59 sourceKeyword?: ControlSourceKeyword;
60 /**
61 * How often automated evidence is collected (`DAILY`, `WEEKLY`, or
62 * `MONTHLY`).
63 */
64 sourceFrequency?: auditmanager.SourceFrequency;
65 /**
66 * Instructions shown to users when evidence collection fails.
67 */
68 troubleshootingText?: string;
69 }
70
71 export interface ControlProps {
72 /**
73 * Name of the custom control.
74 * @default ${app}-${stage}-${id}
75 */
76 name?: string;
77 /**
78 * A description of the control's purpose.
79 */
80 description?: string;
81 /**
82 * Steps for testing the control.
83 */
84 testingInformation?: string;
85 /**
86 * Title of the recommended action plan when the control isn't met.
87 */
88 actionPlanTitle?: string;
89 /**
90 * Recommended actions when the control isn't met.
91 */
92 actionPlanInstructions?: string;
93 /**
94 * The data sources Audit Manager collects evidence from for this control.
95 */
96 controlMappingSources: ControlMappingSourceProps[];
97 /**
98 * Tags to associate with the control.
99 */
100 tags?: Record<string, string>;
101 }
102
103 export interface Control extends Resource<
104 "AWS.AuditManager.Control",
105 ControlProps,
106 {
107 /**
108 * Service-assigned unique identifier of the control.
109 */
110 controlId: string;
111 /**
112 * ARN of the control.
113 */
114 arn: string;
115 /**
116 * The control's name.
117 */
118 name: string;
119 /**
120 * The control's type — always `Custom` for controls Alchemy creates.
121 */
122 type: auditmanager.ControlType | undefined;
123 /**
124 * Lifecycle state of the control (`ACTIVE` or `END_OF_SUPPORT`).
125 */
126 state: auditmanager.ControlState | undefined;
127 /**
128 * Current tags reported for the control.
129 */
130 tags: Record<string, string>;
131 },
132 never,
133 Providers
134 > {}
135
136 /**
137 * A custom control in AWS Audit Manager — a compliance requirement paired
138 * with the data sources (CloudTrail, Config, Security Hub, API calls, or
139 * manual evidence) Audit Manager collects evidence from to demonstrate it.
140 *
141 * :::note
142 * Audit Manager must be registered in the account (`RegisterAccount`)
143 * before controls can be created.
144 * :::
145 * ### Creating Controls
146 * **Example:** Manual-Evidence Control
147 * ```typescript
148 * import * as AWS from "@alchemy.run/aws";
149 *
150 * const control = yield* AWS.AuditManager.Control("AccessReview", {
151 * description: "Quarterly review of privileged access",
152 * controlMappingSources: [{
153 * sourceName: "access-review-records",
154 * sourceSetUpOption: "Procedural_Controls_Mapping",
155 * sourceType: "MANUAL",
156 * }],
157 * });
158 * ```
159 *
160 * **Example:** CloudTrail-Backed Control
161 * ```typescript
162 * const control = yield* AWS.AuditManager.Control("RootLoginMonitor", {
163 * description: "Detects console logins by the root user",
164 * controlMappingSources: [{
165 * sourceName: "root-console-logins",
166 * sourceSetUpOption: "System_Controls_Mapping",
167 * sourceType: "AWS_Cloudtrail",
168 * sourceKeyword: {
169 * keywordInputType: "SELECT_FROM_LIST",
170 * keywordValue: "ConsoleLogin",
171 * },
172 * sourceFrequency: "DAILY",
173 * }],
174 * });
175 * ```
176 *
177 * @resource
178 */
179 export const Control = Resource<Control>("AWS.AuditManager.Control");
180
181 const createControlName = (id: string, props: { name?: string | undefined }) =>
182 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 100 });
183
184 const toAttributes = (control: auditmanager.Control): Control["Attributes"] => ({
185 controlId: control.id ?? "",
186 arn: control.arn ?? "",
187 name: control.name ?? "",
188 type: control.type,
189 state: control.state,
190 tags: toTagRecord(control.tags),
191 });
192
193 const readControlById = Effect.fn(function* (controlId: string) {
194 const response = yield* auditmanager
195 .getControl({ controlId })
196 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
197 return response?.control;
198 });
199
200 const findControlByName = Effect.fn(function* (name: string) {
201 const pages = yield* auditmanager.listControls
202 .pages({ controlType: "Custom" })
203 .pipe(EffectStream.runCollect);
204 const match = Array.from(pages)
205 .flatMap((page) => page.controlMetadataList ?? [])
206 .find((control) => control.name === name);
207 if (!match?.id) return undefined;
208 return yield* readControlById(match.id);
209 });
210
211 /**
212 * Projection used for drift detection between desired and observed mapping
213 * sources — server-assigned fields (sourceId) are excluded.
214 */
215 const projectSource = (source: {
216 sourceName?: string | undefined;
217 sourceDescription?: string | undefined;
218 sourceSetUpOption?: auditmanager.SourceSetUpOption | undefined;
219 sourceType?: auditmanager.SourceType | undefined;
220 sourceKeyword?: ControlSourceKeyword | undefined;
221 sourceFrequency?: auditmanager.SourceFrequency | undefined;
222 troubleshootingText?: string | undefined;
223 }) => ({
224 sourceName: source.sourceName ?? "",
225 sourceDescription: source.sourceDescription ?? "",
226 sourceSetUpOption: source.sourceSetUpOption ?? "",
227 sourceType: source.sourceType ?? "",
228 keywordInputType: source.sourceKeyword?.keywordInputType ?? "",
229 keywordValue: source.sourceKeyword?.keywordValue ?? "",
230 sourceFrequency: source.sourceFrequency ?? "",
231 troubleshootingText: source.troubleshootingText ?? "",
232 });
233
234 export const ControlProvider = () =>
235 Provider.effect(
236 Control,
237 Effect.gen(function* () {
238 return {
239 stables: ["controlId", "arn"],
240 list: () =>
241 Effect.gen(function* () {
242 const pages = yield* auditmanager.listControls
243 .pages({ controlType: "Custom" })
244 .pipe(EffectStream.runCollect);
245 const ids = Array.from(pages)
246 .flatMap((page) => page.controlMetadataList ?? [])
247 .flatMap((control) => (control.id ? [control.id] : []));
248 const hydrated = yield* Effect.forEach(ids, (controlId) => readControlById(controlId), {
249 concurrency: 5,
250 });
251 return hydrated.flatMap((control) =>
252 control === undefined ? [] : [toAttributes(control)],
253 );
254 }),
255 read: Effect.fn(function* ({ id, olds, output }) {
256 const control = output?.controlId
257 ? yield* readControlById(output.controlId)
258 : yield* findControlByName(yield* createControlName(id, olds ?? {}));
259 if (!control) return undefined;
260 const attrs = toAttributes(control);
261 return (yield* hasAlchemyTags(id, attrs.tags as Tags)) ? attrs : Unowned(attrs);
262 }),
263 reconcile: Effect.fn(function* ({ id, news, output, session }) {
264 const name = yield* createControlName(id, news);
265 const internalTags = yield* createInternalTags(id);
266 const desiredTags = { ...internalTags, ...news.tags };
267
268 // Observe — prefer the cached id; fall back to a name lookup so a
269 // create whose state failed to persist is adopted, not duplicated.
270 let control = output?.controlId
271 ? yield* readControlById(output.controlId)
272 : yield* findControlByName(name);
273
274 // Ensure — create if missing.
275 if (control === undefined) {
276 const created = yield* auditmanager.createControl({
277 name,
278 description: news.description,
279 testingInformation: news.testingInformation,
280 actionPlanTitle: news.actionPlanTitle,
281 actionPlanInstructions: news.actionPlanInstructions,
282 controlMappingSources: news.controlMappingSources,
283 tags: desiredTags,
284 });
285 control = created.control;
286 if (!control?.id) {
287 return yield* new ControlUnexpectedResponse({
288 message: `CreateControl for '${name}' returned no control`,
289 });
290 }
291 yield* session.note(`Created control ${name} (${control.id})`);
292 }
293
294 // Sync — diff observed against desired; UpdateControl on drift.
295 const observedSources = (control.controlMappingSources ?? []).map((source) =>
296 projectSource({
297 ...source,
298 troubleshootingText: unredact(source.troubleshootingText),
299 }),
300 );
301 const desiredSources = news.controlMappingSources.map(projectSource);
302 const drifted =
303 (control.name ?? "") !== name ||
304 (unredact(control.description) ?? "") !== (news.description ?? "") ||
305 (unredact(control.testingInformation) ?? "") !== (news.testingInformation ?? "") ||
306 (unredact(control.actionPlanTitle) ?? "") !== (news.actionPlanTitle ?? "") ||
307 (unredact(control.actionPlanInstructions) ?? "") !==
308 (news.actionPlanInstructions ?? "") ||
309 JSON.stringify(observedSources) !== JSON.stringify(desiredSources);
310 if (drifted) {
311 // Reuse the server-assigned sourceId for sources whose name is
312 // unchanged so AWS updates them in place instead of replacing.
313 const observedByName = new Map(
314 (control.controlMappingSources ?? []).map((source) => [
315 source.sourceName,
316 source.sourceId,
317 ]),
318 );
319 const updated = yield* auditmanager.updateControl({
320 controlId: control.id ?? "",
321 name,
322 description: news.description,
323 testingInformation: news.testingInformation,
324 actionPlanTitle: news.actionPlanTitle,
325 actionPlanInstructions: news.actionPlanInstructions,
326 controlMappingSources: news.controlMappingSources.map((source) => ({
327 ...source,
328 sourceId: observedByName.get(source.sourceName),
329 })),
330 });
331 control = updated.control ?? control;
332 yield* session.note(`Updated control ${name}`);
333 }
334
335 // Sync tags — diff against observed cloud tags.
336 const attrs = toAttributes(control);
337 const { removed, upsert } = diffTags(attrs.tags, desiredTags);
338 if (removed.length > 0) {
339 yield* auditmanager.untagResource({
340 resourceArn: attrs.arn,
341 tagKeys: removed,
342 });
343 }
344 if (upsert.length > 0) {
345 yield* auditmanager.tagResource({
346 resourceArn: attrs.arn,
347 tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])),
348 });
349 }
350
351 yield* session.note(attrs.arn);
352 return { ...attrs, tags: desiredTags };
353 }),
354 delete: Effect.fn(function* ({ output }) {
355 yield* auditmanager
356 .deleteControl({ controlId: output.controlId })
357 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
358 }),
359 };
360 }),
361 );