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

main
ts 239 lines 8.49 KB
Raw
1 import * as inspector2 from "@distilled.cloud/aws/inspector2";
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, tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10
11 /** CIS Benchmark hardening level the scan checks against. */
12 export type CisSecurityLevel = "LEVEL_1" | "LEVEL_2";
13
14 export interface CisScanConfigurationProps {
15 /**
16 * Name of the CIS scan configuration. If omitted, a unique name is
17 * generated. Updatable in place — identity is the configuration's ARN.
18 */
19 scanName?: string;
20
21 /**
22 * The CIS Benchmark level the scan checks target instances against:
23 * `LEVEL_1` (essential hardening) or `LEVEL_2` (defense in depth).
24 * Updatable in place.
25 */
26 securityLevel: CisSecurityLevel;
27
28 /**
29 * When the scan runs: `{ oneTime: {} }`, or a `daily` / `weekly` /
30 * `monthly` schedule with a start time, e.g.
31 * `{ daily: { startTime: { timeOfDay: "02:00", timezone: "UTC" } } }`.
32 * Updatable in place.
33 */
34 schedule: inspector2.Schedule;
35
36 /**
37 * The accounts (`["SELF"]` for the current account) and EC2 instance
38 * resource tags the scan targets. Updatable in place.
39 */
40 targets: {
41 /** Account ids to scan; `["SELF"]` targets the current account. */
42 accountIds: string[];
43 /**
44 * EC2 instances to scan, selected by resource tag, e.g.
45 * `{ Environment: ["production"] }`.
46 */
47 targetResourceTags: Record<string, string[]>;
48 };
49
50 /**
51 * Tags applied to the scan configuration. Alchemy ownership tags are
52 * merged in automatically.
53 */
54 tags?: Record<string, string>;
55 }
56
57 /** @resource */
58 export interface CisScanConfiguration extends Resource<
59 "AWS.Inspector2.CisScanConfiguration",
60 CisScanConfigurationProps,
61 {
62 /** ARN of the CIS scan configuration (its identity). */
63 scanConfigurationArn: string;
64 /** Name of the CIS scan configuration. */
65 scanName: string;
66 /** CIS Benchmark level the scan checks against. */
67 securityLevel: CisSecurityLevel;
68 /** Account that owns the scan configuration. */
69 ownerId: string | undefined;
70 },
71 never,
72 Providers
73 > {}
74
75 /**
76 * An Amazon Inspector CIS scan configuration — schedules CIS Benchmark
77 * scans of SSM-managed EC2 instances selected by resource tags. Name,
78 * level, schedule, and targets are all updatable in place; identity is the
79 * configuration's ARN.
80 *
81 * ### Scheduling CIS Scans
82 * **Example:** Daily Level 1 scan of production instances
83 * ```typescript
84 * const scan = yield* AWS.Inspector2.CisScanConfiguration("NightlyCis", {
85 * securityLevel: "LEVEL_1",
86 * schedule: {
87 * daily: { startTime: { timeOfDay: "02:00", timezone: "UTC" } },
88 * },
89 * targets: {
90 * accountIds: ["SELF"],
91 * targetResourceTags: { Environment: ["production"] },
92 * },
93 * });
94 * ```
95 *
96 * **Example:** One-time Level 2 audit
97 * ```typescript
98 * const audit = yield* AWS.Inspector2.CisScanConfiguration("Level2Audit", {
99 * scanName: "level2-audit",
100 * securityLevel: "LEVEL_2",
101 * schedule: { oneTime: {} },
102 * targets: {
103 * accountIds: ["SELF"],
104 * targetResourceTags: { Audit: ["true"] },
105 * },
106 * });
107 * ```
108 */
109 const CisScanConfigurationResource = Resource<CisScanConfiguration>(
110 "AWS.Inspector2.CisScanConfiguration",
111 );
112
113 export { CisScanConfigurationResource as CisScanConfiguration };
114
115 export const CisScanConfigurationProvider = () =>
116 Provider.effect(
117 CisScanConfigurationResource,
118 Effect.gen(function* () {
119 const toName = (id: string, props: { scanName?: string }) =>
120 props.scanName
121 ? Effect.succeed(props.scanName)
122 : createPhysicalName({ id, maxLength: 128 });
123
124 const findBy = (filter: inspector2.ListCisScanConfigurationsFilterCriteria) =>
125 inspector2
126 .listCisScanConfigurations({ filterCriteria: filter })
127 .pipe(Effect.map((r) => r.scanConfigurations?.[0]));
128
129 const findByArn = (arn: string) =>
130 findBy({
131 scanConfigurationArnFilters: [{ comparison: "EQUALS", value: arn }],
132 });
133
134 const findByName = (name: string) =>
135 findBy({ scanNameFilters: [{ comparison: "EQUALS", value: name }] });
136
137 const buildAttrs = (c: inspector2.CisScanConfiguration) => ({
138 scanConfigurationArn: c.scanConfigurationArn,
139 scanName: c.scanName ?? "",
140 securityLevel: c.securityLevel as CisSecurityLevel,
141 ownerId: c.ownerId,
142 });
143
144 return {
145 stables: ["scanConfigurationArn", "ownerId"],
146 read: Effect.fn(function* ({ id, olds, output }) {
147 const live = output?.scanConfigurationArn
148 ? yield* findByArn(output.scanConfigurationArn)
149 : yield* findByName(yield* toName(id, olds ?? {}));
150 if (!live) return undefined;
151 const attrs = buildAttrs(live);
152 return (yield* hasAlchemyTags(id, live.tags)) ? attrs : Unowned(attrs);
153 }),
154 list: () =>
155 inspector2.listCisScanConfigurations.items({}).pipe(
156 Stream.map(buildAttrs),
157 Stream.runCollect,
158 Effect.map((c) => Array.from(c)),
159 ),
160 reconcile: Effect.fn(function* ({ id, news, output, session }) {
161 const scanName = yield* toName(id, news);
162 const internalTags = yield* createInternalTags(id);
163 const desiredTags = { ...news.tags, ...internalTags };
164
165 // 1. OBSERVE — cloud state is authoritative. The ARN survives
166 // renames; fall back to a name lookup otherwise.
167 let live = output?.scanConfigurationArn
168 ? yield* findByArn(output.scanConfigurationArn)
169 : yield* findByName(scanName);
170
171 // 2. ENSURE — create when missing.
172 if (!live) {
173 const { scanConfigurationArn } = yield* inspector2.createCisScanConfiguration({
174 scanName,
175 securityLevel: news.securityLevel,
176 schedule: news.schedule,
177 targets: news.targets,
178 tags: desiredTags,
179 });
180 live = scanConfigurationArn
181 ? yield* findByArn(scanConfigurationArn)
182 : yield* findByName(scanName);
183 if (!live) {
184 return yield* Effect.die(
185 new Error(`Inspector2 CIS scan configuration ${scanName} not visible after create`),
186 );
187 }
188 }
189
190 // 3. SYNC settings — observed ↔ desired.
191 const drift =
192 live.scanName !== scanName ||
193 live.securityLevel !== news.securityLevel ||
194 JSON.stringify(live.schedule) !== JSON.stringify(news.schedule) ||
195 JSON.stringify(live.targets?.accountIds) !== JSON.stringify(news.targets.accountIds) ||
196 JSON.stringify(live.targets?.targetResourceTags) !==
197 JSON.stringify(news.targets.targetResourceTags);
198 if (drift) {
199 yield* inspector2.updateCisScanConfiguration({
200 scanConfigurationArn: live.scanConfigurationArn,
201 scanName,
202 securityLevel: news.securityLevel,
203 schedule: news.schedule,
204 targets: news.targets,
205 });
206 }
207
208 // 3b. SYNC tags — diff against OBSERVED cloud tags so adoption
209 // converges foreign tags too.
210 const { upsert, removed } = diffTags(tagRecord(live.tags), desiredTags);
211 if (upsert.length > 0) {
212 yield* inspector2.tagResource({
213 resourceArn: live.scanConfigurationArn,
214 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
215 });
216 }
217 if (removed.length > 0) {
218 yield* inspector2.untagResource({
219 resourceArn: live.scanConfigurationArn,
220 tagKeys: removed,
221 });
222 }
223
224 // 4. RETURN fresh attributes.
225 const final = yield* findByArn(live.scanConfigurationArn);
226 yield* session.note(live.scanConfigurationArn);
227 return buildAttrs(final ?? live);
228 }),
229 delete: Effect.fn(function* ({ output }) {
230 // Idempotent — the configuration may already be gone.
231 yield* inspector2
232 .deleteCisScanConfiguration({
233 scanConfigurationArn: output.scanConfigurationArn,
234 })
235 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
236 }),
237 };
238 }),
239 );