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

main
ts 300 lines 10.1 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 * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 DEFAULT_CLOUD_PROVIDER,
13 DEFAULT_ENABLEMENT,
14 defaultShaCustomConfig,
15 encodeDescription,
16 fingerprint,
17 folderIdOf,
18 folderParent,
19 hasOwnershipMarker,
20 lastSegment,
21 ownedByAlchemy,
22 parseName,
23 parseOwnership,
24 replaceOn,
25 resolveFolder,
26 sameText,
27 SecuritycenterNotResolved,
28 shaSettingsParent,
29 toShaDisplayName,
30 tryResolveFolder,
31 updateMaskOf,
32 } from "./internal.ts";
33
34 export type FolderSecurityHealthAnalyticsSettingsCustomModuleProps = {
35 /**
36 * Parent folder (`folders/{folder}` or the numeric id). Defaults to
37 * the project's Resource Manager folder ancestor.
38 * Immutable — changing it replaces the module.
39 */
40 folder?: string;
41 /**
42 * Display name. Must start with a lowercase letter and contain only
43 * letters, digits, and underscores (max 128). Unique under the parent.
44 * If omitted, a unique name is generated. Custom modules have no labels
45 * field, so Alchemy ownership is stored in `customConfig.description`.
46 */
47 displayName?: string;
48 /**
49 * Detector configuration. When omitted, Alchemy uses a never-matching
50 * CEL predicate so the module stays inert.
51 */
52 customConfig?: scc.GoogleCloudSecuritycenterV1CustomConfig;
53 /**
54 * Enablement state.
55 * @default "ENABLED"
56 */
57 enablementState?:
58 | scc.GoogleCloudSecuritycenterV1SecurityHealthAnalyticsCustomModuleEnablementStateEnum
59 | (string & {});
60 /**
61 * Cloud provider this module applies to.
62 * @default "GOOGLE_CLOUD_PLATFORM"
63 */
64 cloudProvider?:
65 | scc.GoogleCloudSecuritycenterV1SecurityHealthAnalyticsCustomModuleCloudProviderEnum
66 | (string & {});
67 };
68
69 export type FolderSecurityHealthAnalyticsSettingsCustomModule = Resource<
70 "GCP.SecurityCenter.FolderSecurityHealthAnalyticsSettingsCustomModule",
71 FolderSecurityHealthAnalyticsSettingsCustomModuleProps,
72 {
73 /** Full resource name `{folder}/securityHealthAnalyticsSettings/customModules/{module}`. */
74 name: string;
75 /** Module id (last path segment; server assigned). */
76 moduleId: string;
77 /** Folder resource name. */
78 folder: string;
79 /** Folder id. */
80 folderId: string;
81 /** Project id of the deploying stack. */
82 project: string;
83 /** Display name. */
84 displayName: string | undefined;
85 /** Detector configuration with the Alchemy ownership prefix stripped from description. */
86 customConfig: scc.GoogleCloudSecuritycenterV1CustomConfig | undefined;
87 /** Enablement state. */
88 enablementState: string | undefined;
89 /** Cloud provider. */
90 cloudProvider: string | undefined;
91 /** Ancestor module this one inherits from, if any. */
92 ancestorModule: string | undefined;
93 /** Last editor of the module. */
94 lastEditor: string | undefined;
95 /** RFC3339 last-update timestamp. */
96 updateTime: string | undefined;
97 },
98 never,
99 Providers
100 >;
101
102 /**
103 * A folder-scoped Security Health Analytics custom module.
104 *
105 * Custom modules have no labels field — Alchemy stamps ownership into
106 * `customConfig.description` so `list` / nuke can find them. The module id
107 * is assigned by the API. Folder is identity. Display name, custom config,
108 * and enablement update in place.
109 *
110 * ### Creating a Custom Module
111 * **Example:** Never-matching detector
112 * ```typescript
113 * const module = yield* GCP.SecurityCenter.FolderSecurityHealthAnalyticsSettingsCustomModule(
114 * "Unused",
115 * {
116 * customConfig: {
117 * predicate: { expression: 'resource.name == "alchemy-nonexistent"' },
118 * resourceSelector: {
119 * resourceTypes: ["compute.googleapis.com/Instance"],
120 * },
121 * severity: "LOW",
122 * recommendation: "No action required.",
123 * },
124 * },
125 * );
126 * ```
127 *
128 * @resource
129 * @category SecurityCenter
130 */
131 export const FolderSecurityHealthAnalyticsSettingsCustomModule =
132 Resource<FolderSecurityHealthAnalyticsSettingsCustomModule>(
133 "GCP.SecurityCenter.FolderSecurityHealthAnalyticsSettingsCustomModule",
134 );
135
136 const desiredCustomConfig = (
137 ownership: Record<string, string>,
138 customConfig: scc.GoogleCloudSecuritycenterV1CustomConfig | undefined,
139 ): scc.GoogleCloudSecuritycenterV1CustomConfig => {
140 const base = customConfig ?? defaultShaCustomConfig;
141 return {
142 ...base,
143 description: encodeDescription(ownership, base.description),
144 };
145 };
146
147 const toAttrs = (
148 module: scc.GoogleCloudSecuritycenterV1SecurityHealthAnalyticsCustomModule,
149 folder: string,
150 project: string,
151 ) => {
152 const name = module.name ?? "";
153 const parsed = parseName(name, "customModules");
154 const ownership = parseOwnership(module.customConfig?.description);
155 const customConfig = module.customConfig
156 ? { ...module.customConfig, description: ownership.text }
157 : undefined;
158 return {
159 name,
160 moduleId: parsed.id || lastSegment(name),
161 folder,
162 folderId: folderIdOf(folder),
163 project,
164 displayName: module.displayName,
165 customConfig,
166 enablementState: module.enablementState,
167 cloudProvider: module.cloudProvider,
168 ancestorModule: module.ancestorModule,
169 lastEditor: module.lastEditor,
170 updateTime: module.updateTime,
171 };
172 };
173
174 const getByName = (name: string) =>
175 name.length === 0
176 ? Effect.undefined
177 : scc
178 .getFoldersSecurityHealthAnalyticsSettingsCustomModules({ name })
179 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
180
181 const listAt = (parent: string) =>
182 scc.listFoldersSecurityHealthAnalyticsSettingsCustomModules.pages({ parent, pageSize: 100 }).pipe(
183 Stream.flatMap((page) => Stream.fromIterable(page.securityHealthAnalyticsCustomModules ?? [])),
184 Stream.runCollect,
185 Effect.map((chunk) => Array.from(chunk)),
186 Effect.catchTag("NotFound", () => Effect.succeed([])),
187 );
188
189 const findOwned = (parent: string, id: string) =>
190 Effect.gen(function* () {
191 const modules = yield* listAt(parent);
192 for (const module of modules) {
193 if (yield* ownedByAlchemy(id, module.customConfig?.description)) {
194 return module;
195 }
196 }
197 return undefined;
198 });
199
200 export const FolderSecurityHealthAnalyticsSettingsCustomModuleProvider = () =>
201 Provider.succeed(FolderSecurityHealthAnalyticsSettingsCustomModule, {
202 stables: ["name", "moduleId", "folder", "folderId", "project"],
203
204 diff: Effect.fn(function* ({ news, olds, output }) {
205 if (!isResolved(news)) return undefined;
206 return replaceOn(
207 olds?.folder ?? output?.folder,
208 news.folder !== undefined ? folderParent(news.folder) : undefined,
209 );
210 }),
211
212 read: Effect.fn(function* ({ id, olds, output }) {
213 const env = yield* GcpEnvironment.current;
214 const folder = yield* resolveFolder(olds?.folder ?? output?.folder, output?.folder);
215 let existing = yield* getByName(output?.name ?? "");
216 if (existing === undefined) {
217 existing = yield* findOwned(shaSettingsParent(folder), id);
218 }
219 if (existing === undefined) return undefined;
220 const attrs = toAttrs(existing, folder, env.project);
221 return (yield* ownedByAlchemy(id, existing.customConfig?.description))
222 ? attrs
223 : Unowned(attrs);
224 }),
225
226 list: () =>
227 Effect.gen(function* () {
228 const env = yield* GcpEnvironment.current;
229 const folder = yield* tryResolveFolder();
230 if (folder === undefined) return [];
231 const modules = yield* listAt(shaSettingsParent(folder));
232 return modules
233 .filter((module) => hasOwnershipMarker(module.customConfig?.description))
234 .map((module) => toAttrs(module, folder, env.project));
235 }),
236
237 reconcile: Effect.fn(function* ({ id, news, output }) {
238 const env = yield* GcpEnvironment.current;
239 const folder = yield* resolveFolder(news.folder, output?.folder);
240 const parent = shaSettingsParent(folder);
241 const ownership = yield* createInternalLabels(id);
242 const displayName = yield* toShaDisplayName(id, news.displayName, output?.displayName);
243 const customConfig = desiredCustomConfig(ownership, news.customConfig);
244 const enablementState = news.enablementState ?? DEFAULT_ENABLEMENT;
245 const cloudProvider = news.cloudProvider ?? DEFAULT_CLOUD_PROVIDER;
246
247 let current = yield* getByName(output?.name ?? "");
248 if (current === undefined) {
249 current = yield* findOwned(parent, id);
250 }
251
252 if (current === undefined) {
253 const created = yield* scc
254 .createFoldersSecurityHealthAnalyticsSettingsCustomModules({
255 parent,
256 body: {
257 displayName,
258 customConfig,
259 enablementState,
260 cloudProvider,
261 },
262 })
263 .pipe(Effect.catchTag("Conflict", () => findOwned(parent, id)));
264 current = created ?? undefined;
265 }
266
267 if (current === undefined) {
268 return yield* new SecuritycenterNotResolved({
269 resourceName: `${parent}/customModules`,
270 });
271 }
272
273 const currentName = current.name ?? "";
274 const updateMask = updateMaskOf(
275 !sameText(current.displayName, displayName) ? "displayName" : undefined,
276 fingerprint(current.customConfig) !== fingerprint(customConfig)
277 ? "customConfig"
278 : undefined,
279 !sameText(current.enablementState, enablementState) ? "enablementState" : undefined,
280 );
281
282 if (updateMask.length > 0) {
283 current = yield* scc.patchFoldersSecurityHealthAnalyticsSettingsCustomModules({
284 name: currentName,
285 updateMask,
286 body: { displayName, customConfig, enablementState },
287 });
288 }
289
290 return toAttrs(current, folder, env.project);
291 }),
292
293 delete: Effect.fn(function* ({ output }) {
294 yield* scc
295 .deleteFoldersSecurityHealthAnalyticsSettingsCustomModules({
296 name: output.name,
297 })
298 .pipe(Effect.catchTag("NotFound", () => Effect.void));
299 }),
300 });