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

main
ts 302 lines 10.2 KB
Raw
1 import * as securityhub from "@distilled.cloud/aws/securityhub";
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 type { Providers } from "../Providers.ts";
9
10 /** Whether the automation rule is applied to new and updated findings. */
11 export type RuleStatus = "ENABLED" | "DISABLED";
12
13 export interface AutomationRuleProps {
14 /**
15 * Name of the rule. If omitted, a unique name is generated. Updatable in
16 * place.
17 */
18 ruleName?: string;
19
20 /**
21 * Description of the rule. Updatable in place.
22 */
23 description: string;
24
25 /**
26 * Order in which rules are applied (1 first; lower wins on conflicts).
27 * Updatable in place.
28 */
29 ruleOrder: number;
30
31 /**
32 * Whether the rule is applied to findings: `ENABLED` or `DISABLED`.
33 * Updatable in place.
34 * @default "ENABLED"
35 */
36 ruleStatus?: RuleStatus;
37
38 /**
39 * Whether matching findings stop evaluating further rules. Updatable in
40 * place.
41 * @default false
42 */
43 isTerminal?: boolean;
44
45 /**
46 * The criteria findings are matched against, e.g.
47 * `{ SeverityLabel: [{ Value: "INFORMATIONAL", Comparison: "EQUALS" }] }`.
48 * Updatable in place.
49 */
50 criteria: securityhub.AutomationRulesFindingFilters;
51
52 /**
53 * The updates applied to matching findings, e.g.
54 * `[{ Type: "FINDING_FIELDS_UPDATE", FindingFieldsUpdate: { Workflow: { Status: "SUPPRESSED" } } }]`.
55 * Updatable in place.
56 */
57 actions: securityhub.AutomationRulesAction[];
58
59 /**
60 * Tags applied to the rule. Alchemy ownership tags are merged in
61 * automatically.
62 */
63 tags?: Record<string, string>;
64 }
65
66 /** @resource */
67 export interface AutomationRule extends Resource<
68 "AWS.SecurityHub.AutomationRule",
69 AutomationRuleProps,
70 {
71 /** ARN of the automation rule (its identity). */
72 ruleArn: string;
73 /** Name of the rule. */
74 ruleName: string;
75 /** Evaluation order of the rule. */
76 ruleOrder: number | undefined;
77 /** Whether the rule is applied to findings. */
78 ruleStatus: string | undefined;
79 /** Whether matching findings stop evaluating further rules. */
80 isTerminal: boolean | undefined;
81 },
82 never,
83 Providers
84 > {}
85
86 /**
87 * A Security Hub automation rule — automatically updates findings that match
88 * its criteria (suppress, change severity, add notes) as they are ingested.
89 *
90 * ### Automating Finding Triage
91 * **Example:** Suppress Informational Findings
92 * ```typescript
93 * const rule = yield* AWS.SecurityHub.AutomationRule("SuppressInfo", {
94 * description: "Suppress informational findings",
95 * ruleOrder: 1,
96 * criteria: {
97 * SeverityLabel: [{ Value: "INFORMATIONAL", Comparison: "EQUALS" }],
98 * },
99 * actions: [{
100 * Type: "FINDING_FIELDS_UPDATE",
101 * FindingFieldsUpdate: { Workflow: { Status: "SUPPRESSED" } },
102 * }],
103 * });
104 * ```
105 *
106 * **Example:** Escalate Production Findings
107 * ```typescript
108 * const rule = yield* AWS.SecurityHub.AutomationRule("EscalateProd", {
109 * description: "Raise severity of findings on production resources",
110 * ruleOrder: 2,
111 * isTerminal: true,
112 * criteria: {
113 * ResourceTags: [{ Key: "env", Value: "prod", Comparison: "EQUALS" }],
114 * },
115 * actions: [{
116 * Type: "FINDING_FIELDS_UPDATE",
117 * FindingFieldsUpdate: { Severity: { Label: "CRITICAL" } },
118 * }],
119 * });
120 * ```
121 */
122 const AutomationRuleResource = Resource<AutomationRule>("AWS.SecurityHub.AutomationRule");
123
124 export { AutomationRuleResource as AutomationRule };
125
126 export const AutomationRuleProvider = () =>
127 Provider.effect(
128 AutomationRuleResource,
129 Effect.gen(function* () {
130 const toName = (id: string, props: { ruleName?: string }) =>
131 props.ruleName
132 ? Effect.succeed(props.ruleName)
133 : createPhysicalName({ id, maxLength: 128 });
134
135 const getRule = (arn: string) =>
136 securityhub.batchGetAutomationRules({ AutomationRulesArns: [arn] }).pipe(
137 Effect.map((r) => r.Rules?.[0]),
138 Effect.catchTags({
139 ResourceNotFoundException: () => Effect.undefined,
140 InvalidAccessException: () => Effect.undefined,
141 }),
142 );
143
144 // `ListAutomationRules` is not modeled as paginated in the Smithy spec
145 // (no `.pages` helper) — page manually, bounded (accounts are limited
146 // to 100 rules).
147 const listRules = Effect.gen(function* () {
148 const out: securityhub.AutomationRulesMetadata[] = [];
149 let nextToken: string | undefined;
150 for (let i = 0; i < 10; i++) {
151 const page = yield* securityhub.listAutomationRules({
152 MaxResults: 100,
153 NextToken: nextToken,
154 });
155 out.push(...(page.AutomationRulesMetadata ?? []));
156 nextToken = page.NextToken;
157 if (!nextToken) break;
158 }
159 return out;
160 }).pipe(
161 Effect.catchTag("InvalidAccessException", () =>
162 Effect.succeed([] as securityhub.AutomationRulesMetadata[]),
163 ),
164 );
165
166 const readTags = (arn: string) =>
167 securityhub.listTagsForResource({ ResourceArn: arn }).pipe(
168 Effect.map((r) => tagRecord(r.Tags)),
169 Effect.orElseSucceed(() => ({})),
170 );
171
172 const buildAttrs = (r: {
173 RuleArn?: string;
174 RuleName?: string;
175 RuleOrder?: number;
176 RuleStatus?: string;
177 IsTerminal?: boolean;
178 }) => ({
179 ruleArn: r.RuleArn!,
180 ruleName: r.RuleName ?? "",
181 ruleOrder: r.RuleOrder,
182 ruleStatus: r.RuleStatus,
183 isTerminal: r.IsTerminal,
184 });
185
186 return {
187 stables: ["ruleArn"],
188 read: Effect.fn(function* ({ id, olds, output }) {
189 let arn = output?.ruleArn;
190 if (!arn) {
191 // No prior state — find by (deterministic) name.
192 const name = yield* toName(id, olds ?? {});
193 const all = yield* listRules;
194 arn = all.find((r) => r.RuleName === name)?.RuleArn;
195 }
196 if (!arn) return undefined;
197 const live = yield* getRule(arn);
198 if (!live) return undefined;
199 const attrs = buildAttrs(live);
200 const tags = yield* readTags(arn);
201 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
202 }),
203 list: () =>
204 listRules.pipe(
205 Effect.map((all) => all.filter((r) => r.RuleArn).map((r) => buildAttrs(r))),
206 ),
207 reconcile: Effect.fn(function* ({ id, news, output, session }) {
208 const name = yield* toName(id, news);
209 const internalTags = yield* createInternalTags(id);
210 const desiredTags = { ...news.tags, ...internalTags };
211
212 // 1. OBSERVE — by cached ARN first, then by name.
213 let arn = output?.ruleArn;
214 let live = arn ? yield* getRule(arn) : undefined;
215 if (!live) {
216 const all = yield* listRules;
217 arn = all.find((r) => r.RuleName === name)?.RuleArn;
218 live = arn ? yield* getRule(arn) : undefined;
219 }
220
221 if (!live) {
222 // 2. ENSURE — create with tags applied inline.
223 const { RuleArn } = yield* securityhub.createAutomationRule({
224 RuleName: name,
225 Description: news.description,
226 RuleOrder: news.ruleOrder,
227 RuleStatus: news.ruleStatus ?? "ENABLED",
228 IsTerminal: news.isTerminal ?? false,
229 Criteria: news.criteria,
230 Actions: news.actions,
231 Tags: desiredTags,
232 });
233 arn = RuleArn!;
234 } else {
235 arn = live.RuleArn!;
236 // 3. SYNC settings — observed ↔ desired.
237 const desiredStatus = news.ruleStatus ?? "ENABLED";
238 const desiredTerminal = news.isTerminal ?? false;
239 const drift =
240 live.RuleName !== name ||
241 live.Description !== news.description ||
242 live.RuleOrder !== news.ruleOrder ||
243 live.RuleStatus !== desiredStatus ||
244 (live.IsTerminal ?? false) !== desiredTerminal ||
245 JSON.stringify(live.Criteria) !== JSON.stringify(news.criteria) ||
246 JSON.stringify(live.Actions) !== JSON.stringify(news.actions);
247 if (drift) {
248 yield* securityhub.batchUpdateAutomationRules({
249 UpdateAutomationRulesRequestItems: [
250 {
251 RuleArn: arn,
252 RuleName: name,
253 Description: news.description,
254 RuleOrder: news.ruleOrder,
255 RuleStatus: desiredStatus,
256 IsTerminal: desiredTerminal,
257 Criteria: news.criteria,
258 Actions: news.actions,
259 },
260 ],
261 });
262 }
263
264 // 3b. SYNC tags — diff against OBSERVED cloud tags.
265 const currentTags = yield* readTags(arn);
266 const { upsert, removed } = diffTags(currentTags, desiredTags);
267 if (upsert.length > 0) {
268 yield* securityhub.tagResource({
269 ResourceArn: arn,
270 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
271 });
272 }
273 if (removed.length > 0) {
274 yield* securityhub.untagResource({
275 ResourceArn: arn,
276 TagKeys: removed,
277 });
278 }
279 }
280
281 // 4. RETURN fresh attributes.
282 const final = yield* getRule(arn);
283 yield* session.note(arn);
284 return buildAttrs(final ?? { RuleArn: arn, RuleName: name });
285 }),
286 delete: Effect.fn(function* ({ output }) {
287 // Idempotent — an unknown ARN comes back in
288 // UnprocessedAutomationRules rather than as an error.
289 yield* securityhub
290 .batchDeleteAutomationRules({
291 AutomationRulesArns: [output.ruleArn],
292 })
293 .pipe(
294 Effect.catchTags({
295 ResourceNotFoundException: () => Effect.void,
296 InvalidAccessException: () => Effect.void,
297 }),
298 );
299 }),
300 };
301 }),
302 );