@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 300 lines 10 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 DEFAULT_ETD_TYPE,
15 defaultEtdConfig,
16 encodeDescription,
17 etdSettingsParent,
18 fingerprint,
19 hasOwnershipMarker,
20 lastSegment,
21 organizationIdOf,
22 organizationParent,
23 ownedByAlchemy,
24 parseName,
25 parseOwnership,
26 replaceOn,
27 resolveOrganization,
28 sameText,
29 SecuritycenterNotResolved,
30 tryResolveOrganization,
31 updateMaskOf,
32 } from "./internal.ts";
33
34 export type OrganizationEventThreatDetectionSettingsCustomModuleProps = {
35 /**
36 * Parent organization (`organizations/{organization}` or the numeric
37 * id). Defaults to the project's Resource
38 * Manager ancestor. Immutable — changing it replaces the module.
39 */
40 organization?: string;
41 /**
42 * Custom module type (for example `CONFIGURABLE_BAD_IP`). Immutable —
43 * changing it replaces the module.
44 * @default "CONFIGURABLE_BAD_IP"
45 */
46 type?: string;
47 /**
48 * Module configuration matching `type`.
49 */
50 config?: scc.DocumentMap;
51 /**
52 * Enablement state.
53 * @default "ENABLED"
54 */
55 enablementState?: scc.EventThreatDetectionCustomModuleEnablementStateEnum | (string & {});
56 /**
57 * Cloud provider this module applies to.
58 * @default "GOOGLE_CLOUD_PLATFORM"
59 */
60 cloudProvider?: scc.EventThreatDetectionCustomModuleCloudProviderEnum | (string & {});
61 /**
62 * Human-readable display name.
63 */
64 displayName?: string;
65 /**
66 * Human-readable description. Event Threat Detection custom modules
67 * have no labels field, so Alchemy ownership is stored in a
68 * `[alchemy …]` prefix and stripped from attributes.
69 */
70 description?: string;
71 };
72
73 export type OrganizationEventThreatDetectionSettingsCustomModule = Resource<
74 "GCP.SecurityCenter.OrganizationEventThreatDetectionSettingsCustomModule",
75 OrganizationEventThreatDetectionSettingsCustomModuleProps,
76 {
77 /** Full resource name `{organization}/eventThreatDetectionSettings/customModules/{module}`. */
78 name: string;
79 /** Module id (last path segment; server assigned). */
80 moduleId: string;
81 /** Organization resource name. */
82 organization: string;
83 /** Organization id. */
84 organizationId: string;
85 /** Project id of the deploying stack. */
86 project: string;
87 /** Custom module type. */
88 type: string | undefined;
89 /** Module configuration. */
90 config: scc.DocumentMap | undefined;
91 /** Enablement state. */
92 enablementState: string | undefined;
93 /** Cloud provider. */
94 cloudProvider: string | undefined;
95 /** Display name. */
96 displayName: string | undefined;
97 /** User description with the Alchemy ownership prefix stripped. */
98 description: string | undefined;
99 /** Ancestor module this one inherits from, if any. */
100 ancestorModule: string | undefined;
101 /** Last editor of the module. */
102 lastEditor: string | undefined;
103 /** RFC3339 last-update timestamp. */
104 updateTime: string | undefined;
105 },
106 never,
107 Providers
108 >;
109
110 /**
111 * An organization-scoped Event Threat Detection custom module.
112 *
113 * Custom modules have no labels field — Alchemy stamps ownership into the
114 * description so `list` / nuke can find them. The module id is assigned by
115 * the API. Organization and type are identity. Config, enablement, display
116 * name, and description update in place.
117 *
118 * ### Creating a Custom Module
119 * **Example:** Flag a test IP
120 * ```typescript
121 * const module = yield* GCP.SecurityCenter.OrganizationEventThreatDetectionSettingsCustomModule(
122 * "BadIp",
123 * {
124 * type: "CONFIGURABLE_BAD_IP",
125 * config: {
126 * metadata: { severity: "LOW" },
127 * ips: ["192.0.2.1"],
128 * },
129 * description: "test bad ip",
130 * },
131 * );
132 * ```
133 *
134 * @resource
135 * @category SecurityCenter
136 */
137 export const OrganizationEventThreatDetectionSettingsCustomModule =
138 Resource<OrganizationEventThreatDetectionSettingsCustomModule>(
139 "GCP.SecurityCenter.OrganizationEventThreatDetectionSettingsCustomModule",
140 );
141
142 const toAttrs = (
143 module: scc.EventThreatDetectionCustomModule,
144 organization: string,
145 project: string,
146 ) => {
147 const name = module.name ?? "";
148 const parsed = parseName(name, "customModules");
149 const ownership = parseOwnership(module.description);
150 return {
151 name,
152 moduleId: parsed.id || lastSegment(name),
153 organization,
154 organizationId: organizationIdOf(organization),
155 project,
156 type: module.type,
157 config: module.config,
158 enablementState: module.enablementState,
159 cloudProvider: module.cloudProvider,
160 displayName: module.displayName,
161 description: ownership.text,
162 ancestorModule: module.ancestorModule,
163 lastEditor: module.lastEditor,
164 updateTime: module.updateTime,
165 };
166 };
167
168 const getByName = (name: string) =>
169 name.length === 0
170 ? Effect.undefined
171 : scc
172 .getOrganizationsEventThreatDetectionSettingsCustomModules({ name })
173 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
174
175 const listAt = (parent: string) =>
176 scc.listOrganizationsEventThreatDetectionSettingsCustomModules
177 .pages({ parent, pageSize: 100 })
178 .pipe(
179 Stream.flatMap((page) => Stream.fromIterable(page.eventThreatDetectionCustomModules ?? [])),
180 Stream.runCollect,
181 Effect.map((chunk) => Array.from(chunk)),
182 Effect.catchTag("NotFound", () => Effect.succeed([])),
183 );
184
185 const findOwned = (parent: string, id: string) =>
186 Effect.gen(function* () {
187 const modules = yield* listAt(parent);
188 for (const module of modules) {
189 if (yield* ownedByAlchemy(id, module.description)) return module;
190 }
191 return undefined;
192 });
193
194 export const OrganizationEventThreatDetectionSettingsCustomModuleProvider = () =>
195 Provider.succeed(OrganizationEventThreatDetectionSettingsCustomModule, {
196 stables: ["name", "moduleId", "organization", "organizationId", "project", "type"],
197
198 diff: Effect.fn(function* ({ news, olds, output }) {
199 if (!isResolved(news)) return undefined;
200 return (
201 replaceOn(
202 olds?.organization ?? output?.organization,
203 news.organization !== undefined ? organizationParent(news.organization) : undefined,
204 ) ?? replaceOn(olds?.type ?? output?.type, news.type)
205 );
206 }),
207
208 read: Effect.fn(function* ({ id, olds, output }) {
209 const env = yield* GcpEnvironment.current;
210 const organization = yield* resolveOrganization(
211 olds?.organization ?? output?.organization,
212 output?.organization,
213 );
214 let existing = yield* getByName(output?.name ?? "");
215 if (existing === undefined) {
216 existing = yield* findOwned(etdSettingsParent(organization), id);
217 }
218 if (existing === undefined) return undefined;
219 const attrs = toAttrs(existing, organization, env.project);
220 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
221 }),
222
223 list: () =>
224 Effect.gen(function* () {
225 const env = yield* GcpEnvironment.current;
226 const organization = yield* tryResolveOrganization();
227 if (organization === undefined) return [];
228 const modules = yield* listAt(etdSettingsParent(organization));
229 return modules
230 .filter((module) => hasOwnershipMarker(module.description))
231 .map((module) => toAttrs(module, organization, env.project));
232 }),
233
234 reconcile: Effect.fn(function* ({ id, news, output }) {
235 const env = yield* GcpEnvironment.current;
236 const organization = yield* resolveOrganization(news.organization, output?.organization);
237 const parent = etdSettingsParent(organization);
238 const ownership = yield* createInternalLabels(id);
239 const description = encodeDescription(ownership, news.description);
240 const type = news.type ?? DEFAULT_ETD_TYPE;
241 const config = news.config ?? defaultEtdConfig;
242 const enablementState = news.enablementState ?? DEFAULT_ENABLEMENT;
243 const cloudProvider = news.cloudProvider ?? DEFAULT_CLOUD_PROVIDER;
244 const displayName = news.displayName;
245
246 let current = yield* getByName(output?.name ?? "");
247 if (current === undefined) {
248 current = yield* findOwned(parent, id);
249 }
250
251 if (current === undefined) {
252 const created = yield* scc
253 .createOrganizationsEventThreatDetectionSettingsCustomModules({
254 parent,
255 body: {
256 type,
257 config,
258 enablementState,
259 cloudProvider,
260 displayName,
261 description,
262 },
263 })
264 .pipe(Effect.catchTag("Conflict", () => findOwned(parent, id)));
265 current = created ?? undefined;
266 }
267
268 if (current === undefined) {
269 return yield* new SecuritycenterNotResolved({
270 resourceName: `${parent}/customModules`,
271 });
272 }
273
274 const currentName = current.name ?? "";
275 const updateMask = updateMaskOf(
276 fingerprint(current.config) !== fingerprint(config) ? "config" : undefined,
277 !sameText(current.enablementState, enablementState) ? "enablementState" : undefined,
278 !sameText(current.displayName, displayName) ? "displayName" : undefined,
279 !sameText(current.description, description) ? "description" : undefined,
280 );
281
282 if (updateMask.length > 0) {
283 current = yield* scc.patchOrganizationsEventThreatDetectionSettingsCustomModules({
284 name: currentName,
285 updateMask,
286 body: { config, enablementState, displayName, description },
287 });
288 }
289
290 return toAttrs(current, organization, env.project);
291 }),
292
293 delete: Effect.fn(function* ({ output }) {
294 yield* scc
295 .deleteOrganizationsEventThreatDetectionSettingsCustomModules({
296 name: output.name,
297 })
298 .pipe(Effect.catchTag("NotFound", () => Effect.void));
299 }),
300 });