@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 288 lines 9.66 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 FrameworkUnexpectedResponse extends Data.TaggedError("FrameworkUnexpectedResponse")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 /**
19 * A control referenced by a framework control set.
20 */
21 export interface FrameworkControl {
22 /**
23 * The unique identifier of the control (standard or custom).
24 */
25 id: string;
26 }
27
28 /**
29 * A grouping of related controls within a framework.
30 */
31 export interface FrameworkControlSet {
32 /**
33 * Name of the control set.
34 */
35 name: string;
36 /**
37 * The controls in the set, referenced by control id.
38 */
39 controls?: FrameworkControl[];
40 }
41
42 export interface FrameworkProps {
43 /**
44 * Name of the custom framework.
45 * @default ${app}-${stage}-${id}
46 */
47 name?: string;
48 /**
49 * A description of the framework.
50 */
51 description?: string;
52 /**
53 * The compliance standard the framework relates to (e.g. `CIS`, `HIPAA`).
54 */
55 complianceType?: string;
56 /**
57 * The control sets that make up the framework. At least one set with at
58 * least one control is required.
59 */
60 controlSets: FrameworkControlSet[];
61 /**
62 * Tags to associate with the framework.
63 */
64 tags?: Record<string, string>;
65 }
66
67 export interface Framework extends Resource<
68 "AWS.AuditManager.Framework",
69 FrameworkProps,
70 {
71 /**
72 * Service-assigned unique identifier of the framework.
73 */
74 frameworkId: string;
75 /**
76 * ARN of the framework.
77 */
78 arn: string;
79 /**
80 * The framework's name.
81 */
82 name: string;
83 /**
84 * The framework's type — always `Custom` for frameworks Alchemy creates.
85 */
86 type: auditmanager.FrameworkType | undefined;
87 /**
88 * Current tags reported for the framework.
89 */
90 tags: Record<string, string>;
91 },
92 never,
93 Providers
94 > {}
95
96 /**
97 * A custom assessment framework in AWS Audit Manager — a named collection
98 * of control sets that assessments are created from.
99 *
100 * :::note
101 * Audit Manager must be registered in the account (`RegisterAccount`)
102 * before frameworks can be created.
103 * :::
104 * ### Creating Frameworks
105 * **Example:** Framework from a Custom Control
106 * ```typescript
107 * import * as AWS from "@alchemy.run/aws";
108 *
109 * const control = yield* AWS.AuditManager.Control("AccessReview", {
110 * controlMappingSources: [{
111 * sourceName: "access-review-records",
112 * sourceSetUpOption: "Procedural_Controls_Mapping",
113 * sourceType: "MANUAL",
114 * }],
115 * });
116 *
117 * const framework = yield* AWS.AuditManager.Framework("Compliance", {
118 * description: "Internal compliance framework",
119 * controlSets: [{
120 * name: "Access Management",
121 * controls: [{ id: control.controlId }],
122 * }],
123 * });
124 * ```
125 *
126 * @resource
127 */
128 export const Framework = Resource<Framework>("AWS.AuditManager.Framework");
129
130 const createFrameworkName = (id: string, props: { name?: string | undefined }) =>
131 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 100 });
132
133 const toAttributes = (framework: auditmanager.Framework): Framework["Attributes"] => ({
134 frameworkId: framework.id ?? "",
135 arn: framework.arn ?? "",
136 name: framework.name ?? "",
137 type: framework.type,
138 tags: toTagRecord(framework.tags),
139 });
140
141 const readFrameworkById = Effect.fn(function* (frameworkId: string) {
142 const response = yield* auditmanager
143 .getAssessmentFramework({ frameworkId })
144 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
145 return response?.framework;
146 });
147
148 const findFrameworkByName = Effect.fn(function* (name: string) {
149 const pages = yield* auditmanager.listAssessmentFrameworks
150 .pages({ frameworkType: "Custom" })
151 .pipe(EffectStream.runCollect);
152 const match = Array.from(pages)
153 .flatMap((page) => page.frameworkMetadataList ?? [])
154 .find((framework) => framework.name === name);
155 if (!match?.id) return undefined;
156 return yield* readFrameworkById(match.id);
157 });
158
159 /**
160 * Projection used for drift detection — control set names with their sorted
161 * control ids.
162 */
163 const projectControlSets = (
164 controlSets: {
165 name?: string | undefined;
166 controls?: { id?: string | undefined }[] | undefined;
167 }[],
168 ) =>
169 controlSets.map((set) => ({
170 name: set.name ?? "",
171 controls: (set.controls ?? []).flatMap((control) => (control.id ? [control.id] : [])).sort(),
172 }));
173
174 export const FrameworkProvider = () =>
175 Provider.effect(
176 Framework,
177 Effect.gen(function* () {
178 return {
179 stables: ["frameworkId", "arn"],
180 list: () =>
181 Effect.gen(function* () {
182 const pages = yield* auditmanager.listAssessmentFrameworks
183 .pages({ frameworkType: "Custom" })
184 .pipe(EffectStream.runCollect);
185 const ids = Array.from(pages)
186 .flatMap((page) => page.frameworkMetadataList ?? [])
187 .flatMap((framework) => (framework.id ? [framework.id] : []));
188 const hydrated = yield* Effect.forEach(
189 ids,
190 (frameworkId) => readFrameworkById(frameworkId),
191 { concurrency: 5 },
192 );
193 return hydrated.flatMap((framework) =>
194 framework === undefined ? [] : [toAttributes(framework)],
195 );
196 }),
197 read: Effect.fn(function* ({ id, olds, output }) {
198 const framework = output?.frameworkId
199 ? yield* readFrameworkById(output.frameworkId)
200 : yield* findFrameworkByName(yield* createFrameworkName(id, olds ?? {}));
201 if (!framework) return undefined;
202 const attrs = toAttributes(framework);
203 return (yield* hasAlchemyTags(id, attrs.tags as Tags)) ? attrs : Unowned(attrs);
204 }),
205 reconcile: Effect.fn(function* ({ id, news, output, session }) {
206 const name = yield* createFrameworkName(id, news);
207 const internalTags = yield* createInternalTags(id);
208 const desiredTags = { ...internalTags, ...news.tags };
209
210 // Observe — prefer the cached id; fall back to a name lookup so a
211 // create whose state failed to persist is adopted, not duplicated.
212 let framework = output?.frameworkId
213 ? yield* readFrameworkById(output.frameworkId)
214 : yield* findFrameworkByName(name);
215
216 // Ensure — create if missing.
217 if (framework === undefined) {
218 const created = yield* auditmanager.createAssessmentFramework({
219 name,
220 description: news.description,
221 complianceType: news.complianceType,
222 controlSets: news.controlSets,
223 tags: desiredTags,
224 });
225 framework = created.framework;
226 if (!framework?.id) {
227 return yield* new FrameworkUnexpectedResponse({
228 message: `CreateAssessmentFramework for '${name}' returned no framework`,
229 });
230 }
231 yield* session.note(`Created framework ${name} (${framework.id})`);
232 }
233
234 // Sync — diff observed against desired; update on drift.
235 const drifted =
236 (framework.name ?? "") !== name ||
237 (framework.description ?? "") !== (news.description ?? "") ||
238 (unredact(framework.complianceType) ?? "") !== (news.complianceType ?? "") ||
239 JSON.stringify(projectControlSets(framework.controlSets ?? [])) !==
240 JSON.stringify(projectControlSets(news.controlSets));
241 if (drifted) {
242 // Reuse the server-assigned control set id for sets whose name is
243 // unchanged so AWS updates them in place instead of replacing.
244 const observedByName = new Map(
245 (framework.controlSets ?? []).map((set) => [set.name, set.id]),
246 );
247 const updated = yield* auditmanager.updateAssessmentFramework({
248 frameworkId: framework.id ?? "",
249 name,
250 description: news.description,
251 complianceType: news.complianceType,
252 controlSets: news.controlSets.map((set) => ({
253 id: observedByName.get(set.name),
254 name: set.name,
255 controls: set.controls ?? [],
256 })),
257 });
258 framework = updated.framework ?? framework;
259 yield* session.note(`Updated framework ${name}`);
260 }
261
262 // Sync tags — diff against observed cloud tags.
263 const attrs = toAttributes(framework);
264 const { removed, upsert } = diffTags(attrs.tags, desiredTags);
265 if (removed.length > 0) {
266 yield* auditmanager.untagResource({
267 resourceArn: attrs.arn,
268 tagKeys: removed,
269 });
270 }
271 if (upsert.length > 0) {
272 yield* auditmanager.tagResource({
273 resourceArn: attrs.arn,
274 tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])),
275 });
276 }
277
278 yield* session.note(attrs.arn);
279 return { ...attrs, tags: desiredTags };
280 }),
281 delete: Effect.fn(function* ({ output }) {
282 yield* auditmanager
283 .deleteAssessmentFramework({ frameworkId: output.frameworkId })
284 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
285 }),
286 };
287 }),
288 );