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

main
ts 325 lines 10.3 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 etdDisplayNameOf,
16 etdSettingsParent,
17 findOwned,
18 hasOwnershipMarker,
19 jsonEqual,
20 lastSegment,
21 ownedByAlchemy,
22 parseOwnership,
23 projectOf,
24 replaceOn,
25 sameText,
26 updateMaskOf,
27 } from "./internal.ts";
28
29 export type EventThreatDetectionEnablementState =
30 | "ENABLEMENT_STATE_UNSPECIFIED"
31 | "ENABLED"
32 | "DISABLED"
33 | "INHERITED";
34
35 export type EventThreatDetectionCloudProvider =
36 | "CLOUD_PROVIDER_UNSPECIFIED"
37 | "GOOGLE_CLOUD_PLATFORM"
38 | "AMAZON_WEB_SERVICES"
39 | "MICROSOFT_AZURE";
40
41 export type EventThreatDetectionConfig = scc.DocumentMap;
42
43 export type EventThreatDetectionSettingsCustomModuleProps = {
44 /**
45 * Module id (the `{module}` segment of
46 * `projects/{project}/eventThreatDetectionSettings/customModules/{module}`).
47 * Server-assigned on create. Supply it to target an existing module.
48 * Immutable — changing it replaces the module.
49 */
50 moduleId?: string;
51 /**
52 * Module type, e.g. `CONFIGURABLE_BAD_IP`. Immutable — changing it
53 * replaces the module.
54 */
55 type: string;
56 /**
57 * Display name (letters, digits, underscores; max 128 characters).
58 */
59 displayName?: string;
60 /**
61 * Human-readable description. Custom modules have no labels field, so
62 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
63 * from attributes.
64 */
65 description?: string;
66 /**
67 * Enablement state at this parent.
68 * @default "ENABLED"
69 */
70 enablementState?: EventThreatDetectionEnablementState;
71 /**
72 * Module configuration (template-specific JSON).
73 */
74 config?: EventThreatDetectionConfig;
75 /**
76 * Cloud provider this module applies to.
77 */
78 cloudProvider?: EventThreatDetectionCloudProvider;
79 };
80
81 export type EventThreatDetectionSettingsCustomModule = Resource<
82 "GCP.SecurityCenter.EventThreatDetectionSettingsCustomModule",
83 EventThreatDetectionSettingsCustomModuleProps,
84 {
85 /** Full resource name `projects/{project}/eventThreatDetectionSettings/customModules/{module}`. */
86 name: string;
87 /** Module id (last path segment). */
88 moduleId: string;
89 /** Project id. */
90 project: string;
91 /** Module type. */
92 type: string | undefined;
93 /** Display name. */
94 displayName: string | undefined;
95 /** User description with the Alchemy ownership prefix stripped. */
96 description: string | undefined;
97 /** Enablement state. */
98 enablementState: string | undefined;
99 /** Module configuration. */
100 config: EventThreatDetectionConfig | undefined;
101 /** Cloud provider. */
102 cloudProvider: string | undefined;
103 /** Ancestor module this one inherits from, if any. */
104 ancestorModule: string | undefined;
105 /** RFC3339 last-update timestamp. */
106 updateTime: string | undefined;
107 /** Last editor email. */
108 lastEditor: string | undefined;
109 },
110 never,
111 Providers
112 >;
113
114 /**
115 * A project-scoped Event Threat Detection custom module.
116 *
117 * Custom modules have no labels field — Alchemy stamps ownership into
118 * the description so `list` / nuke can find them. Module id and type are
119 * identity (the id is server-assigned). Display name, description,
120 * enablement, and config update in place.
121 *
122 * ### Creating a Custom Module
123 * **Example:** Flag connections to a test IP
124 * ```typescript
125 * const module = yield* GCP.SecurityCenter.EventThreatDetectionSettingsCustomModule(
126 * "BadIp",
127 * {
128 * type: "CONFIGURABLE_BAD_IP",
129 * displayName: "alchemy_bad_ip",
130 * description: "test bad ip",
131 * config: {
132 * metadata: {
133 * severity: "LOW",
134 * description: "test",
135 * recommendation: "investigate",
136 * },
137 * ips: ["192.0.2.1"],
138 * },
139 * },
140 * );
141 * ```
142 *
143 * ### Updating a Custom Module
144 * **Example:** Disable the module
145 * ```typescript
146 * const module = yield* GCP.SecurityCenter.EventThreatDetectionSettingsCustomModule(
147 * "BadIp",
148 * {
149 * type: "CONFIGURABLE_BAD_IP",
150 * enablementState: "DISABLED",
151 * },
152 * );
153 * ```
154 *
155 * @resource
156 * @category SecurityCenter
157 */
158 export const EventThreatDetectionSettingsCustomModule =
159 Resource<EventThreatDetectionSettingsCustomModule>(
160 "GCP.SecurityCenter.EventThreatDetectionSettingsCustomModule",
161 );
162
163 export class EventThreatDetectionSettingsCustomModuleNotResolved extends Data.TaggedError(
164 "GCP.SecurityCenter.EventThreatDetectionSettingsCustomModuleNotResolved",
165 )<{
166 resourceName: string;
167 }> {}
168
169 const resourceName = (project: string, moduleId: string) =>
170 `projects/${project}/eventThreatDetectionSettings/customModules/${moduleId}`;
171
172 const toAttrs = (module: scc.EventThreatDetectionCustomModule, project: string) => {
173 const name = module.name ?? "";
174 const parsed = parseOwnership(module.description);
175 return {
176 name,
177 moduleId: lastSegment(name),
178 project: projectOf(name) || project,
179 type: module.type,
180 displayName: module.displayName,
181 description: parsed.text,
182 enablementState: module.enablementState,
183 config: module.config,
184 cloudProvider: module.cloudProvider,
185 ancestorModule: module.ancestorModule,
186 updateTime: module.updateTime,
187 lastEditor: module.lastEditor,
188 };
189 };
190
191 const getByName = (name: string) =>
192 name.length === 0
193 ? Effect.undefined
194 : scc
195 .getProjectsEventThreatDetectionSettingsCustomModules({ name })
196 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
197
198 const listModules = (project: string) =>
199 collectPages(
200 scc.listProjectsEventThreatDetectionSettingsCustomModules.pages({
201 parent: etdSettingsParent(`projects/${project}`),
202 pageSize: 100,
203 }),
204 (page) => page.eventThreatDetectionCustomModules,
205 ).pipe(
206 Effect.catchTag("NotFound", () => Effect.succeed([] as scc.EventThreatDetectionCustomModule[])),
207 );
208
209 const observe = (project: string, id: string, name: string) =>
210 Effect.gen(function* () {
211 const existing = yield* getByName(name);
212 if (existing !== undefined) return existing;
213 const items = yield* listModules(project);
214 return yield* findOwned(items, (item) => item.description, id);
215 });
216
217 export const EventThreatDetectionSettingsCustomModuleProvider = () =>
218 Provider.succeed(EventThreatDetectionSettingsCustomModule, {
219 stables: ["name", "moduleId", "project", "type", "ancestorModule"],
220
221 diff: Effect.fn(function* ({ news, olds, output }) {
222 if (!isResolved(news)) return undefined;
223 return (
224 replaceOn(olds?.moduleId ?? output?.moduleId, news.moduleId) ??
225 replaceOn(olds?.type ?? output?.type, news.type)
226 );
227 }),
228
229 read: Effect.fn(function* ({ id, olds, output }) {
230 const env = yield* GcpEnvironment.current;
231 const moduleId = olds?.moduleId ?? output?.moduleId;
232 const name = output?.name ?? (moduleId ? resourceName(env.project, moduleId) : "");
233 const existing = yield* observe(env.project, id, name);
234 if (existing === undefined) return undefined;
235 const attrs = toAttrs(existing, env.project);
236 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
237 }),
238
239 list: () =>
240 Effect.gen(function* () {
241 const env = yield* GcpEnvironment.current;
242 const items = yield* listModules(env.project);
243 return items
244 .filter((module) => hasOwnershipMarker(module.description))
245 .map((module) => toAttrs(module, env.project));
246 }),
247
248 reconcile: Effect.fn(function* ({ id, news, output }) {
249 const env = yield* GcpEnvironment.current;
250 const parent = etdSettingsParent(`projects/${env.project}`);
251 const moduleId = news.moduleId ?? output?.moduleId;
252 const name = output?.name ?? (moduleId ? resourceName(env.project, moduleId) : "");
253 const ownership = yield* createInternalLabels(id);
254 const description = encodeOwnership(ownership, news.description);
255 const enablementState = news.enablementState ?? "ENABLED";
256 const displayName =
257 news.displayName ??
258 etdDisplayNameOf(
259 yield* createPhysicalName({
260 id,
261 maxLength: 63,
262 lowercase: true,
263 }),
264 );
265 const body: scc.EventThreatDetectionCustomModule = {
266 type: news.type,
267 displayName,
268 description,
269 enablementState,
270 config: news.config,
271 cloudProvider: news.cloudProvider,
272 };
273
274 let current = yield* observe(env.project, id, name);
275
276 if (current === undefined) {
277 const created = yield* scc.createProjectsEventThreatDetectionSettingsCustomModules({
278 parent,
279 body,
280 });
281 current = created;
282 }
283
284 if (current === undefined) {
285 return yield* new EventThreatDetectionSettingsCustomModuleNotResolved({
286 resourceName: name || parent,
287 });
288 }
289
290 const currentName = current.name ?? name;
291 const displayChanged = !sameText(current.displayName, displayName);
292 const descriptionChanged = !sameText(current.description, description);
293 const enablementChanged = !sameText(current.enablementState, enablementState);
294 const configChanged = !jsonEqual(current.config, news.config);
295 const updateMask = updateMaskOf(
296 displayChanged ? "display_name" : undefined,
297 descriptionChanged ? "description" : undefined,
298 enablementChanged ? "enablement_state" : undefined,
299 configChanged ? "config" : undefined,
300 );
301
302 if (updateMask.length > 0) {
303 current = yield* scc.patchProjectsEventThreatDetectionSettingsCustomModules({
304 name: currentName,
305 updateMask,
306 body: {
307 displayName,
308 description,
309 enablementState,
310 config: news.config,
311 },
312 });
313 }
314
315 return toAttrs(current, env.project);
316 }),
317
318 delete: Effect.fn(function* ({ output }) {
319 yield* scc
320 .deleteProjectsEventThreatDetectionSettingsCustomModules({
321 name: output.name,
322 })
323 .pipe(Effect.catchTag("NotFound", () => Effect.void));
324 }),
325 });