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

main
ts 391 lines 12.2 KB
Raw
1 import * as scc from "@distilled.cloud/gcp/securitycenter_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 collectPages,
14 encodeOwnership,
15 findOwned,
16 hasOwnershipMarker,
17 jsonEqual,
18 lastSegment,
19 ownedByAlchemy,
20 parseOwnership,
21 projectOf,
22 replaceOn,
23 sameText,
24 shaDisplayNameOf,
25 shaSettingsParent,
26 updateMaskOf,
27 } from "./internal.ts";
28
29 export type SecurityHealthAnalyticsEnablementState =
30 | "ENABLEMENT_STATE_UNSPECIFIED"
31 | "ENABLED"
32 | "DISABLED"
33 | "INHERITED";
34
35 export type SecurityHealthAnalyticsCloudProvider =
36 | "CLOUD_PROVIDER_UNSPECIFIED"
37 | "GOOGLE_CLOUD_PLATFORM"
38 | "AMAZON_WEB_SERVICES"
39 | "MICROSOFT_AZURE";
40
41 export type SecurityHealthAnalyticsSeverity =
42 | "SEVERITY_UNSPECIFIED"
43 | "CRITICAL"
44 | "HIGH"
45 | "MEDIUM"
46 | "LOW";
47
48 export type Expr = {
49 /** CEL expression. */
50 expression?: string;
51 /** Short title. */
52 title?: string;
53 /** Human-readable description. */
54 description?: string;
55 /** Source location of the expression. */
56 location?: string;
57 };
58
59 export type CustomOutputProperty = {
60 /** Property name. */
61 name?: string;
62 /** CEL expression that produces the property value. */
63 valueExpression?: Expr;
64 };
65
66 export type CustomConfig = {
67 /** CEL predicate that selects resources. */
68 predicate?: Expr;
69 /** Resource types this module inspects. */
70 resourceSelector?: {
71 /** Fully-qualified resource type names. */
72 resourceTypes?: string[];
73 };
74 /** Finding severity. */
75 severity?: SecurityHealthAnalyticsSeverity;
76 /**
77 * Finding description. Alchemy ownership is stored in a `[alchemy …]`
78 * prefix here (custom modules have no labels) and stripped from
79 * attributes.
80 */
81 description?: string;
82 /** Recommended next steps. */
83 recommendation?: string;
84 /** Extra properties written onto findings. */
85 customOutput?: {
86 properties?: CustomOutputProperty[];
87 };
88 };
89
90 export type SecurityHealthAnalyticsSettingsCustomModuleProps = {
91 /**
92 * Module id (the `{customModule}` segment of
93 * `projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`).
94 * Server-assigned on create. Supply it to target an existing module.
95 * Immutable — changing it replaces the module.
96 */
97 moduleId?: string;
98 /**
99 * Display name. Becomes the finding category. Must start with an
100 * uppercase letter, contain only letters, digits, or underscores, and
101 * be at most 128 characters. Immutable — changing it replaces the
102 * module.
103 */
104 displayName?: string;
105 /**
106 * Enablement state at this parent.
107 * @default "ENABLED"
108 */
109 enablementState?: SecurityHealthAnalyticsEnablementState;
110 /**
111 * Detection configuration. Required on create.
112 */
113 customConfig: CustomConfig;
114 /**
115 * Cloud provider this module applies to.
116 */
117 cloudProvider?: SecurityHealthAnalyticsCloudProvider;
118 };
119
120 export type SecurityHealthAnalyticsSettingsCustomModule = Resource<
121 "GCP.SecurityCenter.SecurityHealthAnalyticsSettingsCustomModule",
122 SecurityHealthAnalyticsSettingsCustomModuleProps,
123 {
124 /** Full resource name `projects/{project}/securityHealthAnalyticsSettings/customModules/{customModule}`. */
125 name: string;
126 /** Module id (last path segment). */
127 moduleId: string;
128 /** Project id. */
129 project: string;
130 /** Display name. */
131 displayName: string | undefined;
132 /** Enablement state. */
133 enablementState: string | undefined;
134 /** Detection configuration with the Alchemy ownership prefix stripped. */
135 customConfig: CustomConfig | undefined;
136 /** Cloud provider. */
137 cloudProvider: string | undefined;
138 /** Ancestor module this one inherits from, if any. */
139 ancestorModule: string | undefined;
140 /** RFC3339 last-update timestamp. */
141 updateTime: string | undefined;
142 /** Last editor email. */
143 lastEditor: string | undefined;
144 },
145 never,
146 Providers
147 >;
148
149 /**
150 * A project-scoped Security Health Analytics custom module.
151 *
152 * Custom modules have no labels field — Alchemy stamps ownership into
153 * `customConfig.description` so `list` / nuke can find them. Module id
154 * and display name are identity (the id is server-assigned). Enablement
155 * and custom config update in place.
156 *
157 * ### Creating a Custom Module
158 * **Example:** Always-true compute instance check
159 * ```typescript
160 * const module = yield* GCP.SecurityCenter.SecurityHealthAnalyticsSettingsCustomModule(
161 * "AlwaysTrue",
162 * {
163 * displayName: "AlchemyAlwaysTrue",
164 * customConfig: {
165 * predicate: { expression: 'resource.name == "alchemy-nonexistent"' },
166 * resourceSelector: {
167 * resourceTypes: ["compute.googleapis.com/Instance"],
168 * },
169 * severity: "LOW",
170 * description: "always true",
171 * recommendation: "n/a",
172 * },
173 * },
174 * );
175 * ```
176 *
177 * ### Updating a Custom Module
178 * **Example:** Disable the module
179 * ```typescript
180 * const module = yield* GCP.SecurityCenter.SecurityHealthAnalyticsSettingsCustomModule(
181 * "AlwaysTrue",
182 * {
183 * enablementState: "DISABLED",
184 * displayName: "AlchemyAlwaysTrue",
185 * customConfig: {
186 * predicate: { expression: 'resource.name == "alchemy-nonexistent"' },
187 * resourceSelector: {
188 * resourceTypes: ["compute.googleapis.com/Instance"],
189 * },
190 * severity: "LOW",
191 * },
192 * },
193 * );
194 * ```
195 *
196 * @resource
197 * @category SecurityCenter
198 */
199 export const SecurityHealthAnalyticsSettingsCustomModule =
200 Resource<SecurityHealthAnalyticsSettingsCustomModule>(
201 "GCP.SecurityCenter.SecurityHealthAnalyticsSettingsCustomModule",
202 );
203
204 export class SecurityHealthAnalyticsSettingsCustomModuleNotResolved extends Data.TaggedError(
205 "GCP.SecurityCenter.SecurityHealthAnalyticsSettingsCustomModuleNotResolved",
206 )<{
207 resourceName: string;
208 }> {}
209
210 const resourceName = (project: string, moduleId: string) =>
211 `projects/${project}/securityHealthAnalyticsSettings/customModules/${moduleId}`;
212
213 const customConfigOf = (
214 config: scc.GoogleCloudSecuritycenterV1CustomConfig | undefined,
215 stripOwnership: boolean,
216 ): CustomConfig | undefined => {
217 if (config === undefined) return undefined;
218 const description = stripOwnership ? parseOwnership(config.description).text : config.description;
219 return {
220 predicate: config.predicate,
221 resourceSelector: config.resourceSelector,
222 severity: config.severity as SecurityHealthAnalyticsSeverity | undefined,
223 description,
224 recommendation: config.recommendation,
225 customOutput: config.customOutput,
226 };
227 };
228
229 const desiredCustomConfig = (
230 config: CustomConfig,
231 ownership: Record<string, string>,
232 ): scc.GoogleCloudSecuritycenterV1CustomConfig => ({
233 ...config,
234 description: encodeOwnership(ownership, config.description),
235 });
236
237 const toAttrs = (
238 module: scc.GoogleCloudSecuritycenterV1SecurityHealthAnalyticsCustomModule,
239 project: string,
240 ) => {
241 const name = module.name ?? "";
242 return {
243 name,
244 moduleId: lastSegment(name),
245 project: projectOf(name) || project,
246 displayName: module.displayName,
247 enablementState: module.enablementState,
248 customConfig: customConfigOf(module.customConfig, true),
249 cloudProvider: module.cloudProvider,
250 ancestorModule: module.ancestorModule,
251 updateTime: module.updateTime,
252 lastEditor: module.lastEditor,
253 };
254 };
255
256 const getByName = (name: string) =>
257 name.length === 0
258 ? Effect.undefined
259 : scc
260 .getProjectsSecurityHealthAnalyticsSettingsCustomModules({ name })
261 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
262
263 const listModules = (project: string) =>
264 collectPages(
265 scc.listProjectsSecurityHealthAnalyticsSettingsCustomModules.pages({
266 parent: shaSettingsParent(`projects/${project}`),
267 pageSize: 100,
268 }),
269 (page) => page.securityHealthAnalyticsCustomModules,
270 ).pipe(
271 Effect.catchTag("NotFound", () =>
272 Effect.succeed([] as scc.GoogleCloudSecuritycenterV1SecurityHealthAnalyticsCustomModule[]),
273 ),
274 );
275
276 const observe = (project: string, id: string, name: string) =>
277 Effect.gen(function* () {
278 const existing = yield* getByName(name);
279 if (existing !== undefined) return existing;
280 const items = yield* listModules(project);
281 return yield* findOwned(items, (item) => item.customConfig?.description, id);
282 });
283
284 export const SecurityHealthAnalyticsSettingsCustomModuleProvider = () =>
285 Provider.succeed(SecurityHealthAnalyticsSettingsCustomModule, {
286 stables: ["name", "moduleId", "project", "displayName", "ancestorModule"],
287
288 diff: Effect.fn(function* ({ news, olds, output }) {
289 if (!isResolved(news)) return undefined;
290 return (
291 replaceOn(olds?.moduleId ?? output?.moduleId, news.moduleId) ??
292 replaceOn(olds?.displayName ?? output?.displayName, news.displayName)
293 );
294 }),
295
296 read: Effect.fn(function* ({ id, olds, output }) {
297 const env = yield* GcpEnvironment.current;
298 const moduleId = olds?.moduleId ?? output?.moduleId;
299 const name = output?.name ?? (moduleId ? resourceName(env.project, moduleId) : "");
300 const existing = yield* observe(env.project, id, name);
301 if (existing === undefined) return undefined;
302 const attrs = toAttrs(existing, env.project);
303 return (yield* ownedByAlchemy(id, existing.customConfig?.description))
304 ? attrs
305 : Unowned(attrs);
306 }),
307
308 list: () =>
309 Effect.gen(function* () {
310 const env = yield* GcpEnvironment.current;
311 const items = yield* listModules(env.project);
312 return items
313 .filter((module) => hasOwnershipMarker(module.customConfig?.description))
314 .map((module) => toAttrs(module, env.project));
315 }),
316
317 reconcile: Effect.fn(function* ({ id, news, output }) {
318 const env = yield* GcpEnvironment.current;
319 const parent = shaSettingsParent(`projects/${env.project}`);
320 const moduleId = news.moduleId ?? output?.moduleId;
321 const name = output?.name ?? (moduleId ? resourceName(env.project, moduleId) : "");
322 const ownership = yield* createInternalLabels(id);
323 const customConfig = desiredCustomConfig(news.customConfig, ownership);
324 const enablementState = news.enablementState ?? "ENABLED";
325 const displayName =
326 news.displayName ??
327 shaDisplayNameOf(
328 yield* createPhysicalName({
329 id,
330 maxLength: 63,
331 lowercase: true,
332 }),
333 );
334 const body: scc.GoogleCloudSecuritycenterV1SecurityHealthAnalyticsCustomModule = {
335 displayName,
336 enablementState,
337 customConfig,
338 cloudProvider: news.cloudProvider,
339 };
340
341 let current = yield* observe(env.project, id, name);
342
343 if (current === undefined) {
344 current = yield* scc.createProjectsSecurityHealthAnalyticsSettingsCustomModules({
345 parent,
346 body,
347 });
348 }
349
350 if (current === undefined) {
351 return yield* new SecurityHealthAnalyticsSettingsCustomModuleNotResolved({
352 resourceName: name || parent,
353 });
354 }
355
356 const currentName = current.name ?? name;
357 const enablementChanged = !sameText(current.enablementState, enablementState);
358 const configChanged = !jsonEqual(
359 {
360 ...current.customConfig,
361 description: current.customConfig?.description,
362 },
363 customConfig,
364 );
365 const updateMask = updateMaskOf(
366 enablementChanged ? "enablement_state" : undefined,
367 configChanged ? "custom_config" : undefined,
368 );
369
370 if (updateMask.length > 0) {
371 current = yield* scc.patchProjectsSecurityHealthAnalyticsSettingsCustomModules({
372 name: currentName,
373 updateMask,
374 body: {
375 enablementState,
376 customConfig,
377 },
378 });
379 }
380
381 return toAttrs(current, env.project);
382 }),
383
384 delete: Effect.fn(function* ({ output }) {
385 yield* scc
386 .deleteProjectsSecurityHealthAnalyticsSettingsCustomModules({
387 name: output.name,
388 })
389 .pipe(Effect.catchTag("NotFound", () => Effect.void));
390 }),
391 });