@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 250 lines 8.28 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 encodeDescription,
13 folderIdOf,
14 folderParent,
15 hasOwnershipMarker,
16 lastSegment,
17 ownedByAlchemy,
18 parseName,
19 parseOwnership,
20 replaceOn,
21 resolveFolder,
22 sameText,
23 SecuritycenterNotResolved,
24 toPhysicalId,
25 tryResolveFolder,
26 updateMaskOf,
27 } from "./internal.ts";
28
29 export type FolderNotificationConfigProps = {
30 /**
31 * Config id (the `{config}` segment of
32 * `folders/{folder}/notificationConfigs/{config}`). If omitted, a unique
33 * id is generated from the stack, stage, and logical id. Letters,
34 * digits, and hyphens; max 63 characters. Immutable — changing it
35 * replaces the config.
36 */
37 configId?: string;
38 /**
39 * Parent folder (`folders/{folder}` or the numeric id). Defaults to
40 * the project's Resource Manager folder ancestor.
41 * Immutable — changing it replaces the config.
42 */
43 folder?: string;
44 /**
45 * Pub/Sub topic that receives findings
46 * (`projects/{project}/topics/{topic}`).
47 */
48 pubsubTopic: string;
49 /**
50 * Finding filter. Empty exports every finding under the parent.
51 */
52 filter?: string;
53 /**
54 * Human-readable description. Notification configs have no labels field,
55 * so Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
56 * from attributes.
57 */
58 description?: string;
59 };
60
61 export type FolderNotificationConfig = Resource<
62 "GCP.SecurityCenter.FolderNotificationConfig",
63 FolderNotificationConfigProps,
64 {
65 /** Full resource name `folders/{folder}/notificationConfigs/{config}`. */
66 name: string;
67 /** Config id (last path segment). */
68 configId: string;
69 /** Folder resource name. */
70 folder: string;
71 /** Folder id. */
72 folderId: string;
73 /** Project id of the deploying stack. */
74 project: string;
75 /** Pub/Sub topic that receives findings. */
76 pubsubTopic: string;
77 /** Finding filter. */
78 filter: string | undefined;
79 /** User description with the Alchemy ownership prefix stripped. */
80 description: string | undefined;
81 /** Service account Security Command Center uses to publish. */
82 serviceAccount: string | undefined;
83 },
84 never,
85 Providers
86 >;
87
88 /**
89 * A folder-scoped Security Command Center notification config.
90 *
91 * Notification configs have no labels field — Alchemy stamps ownership
92 * into the description so `list` / nuke can find them. Config id and
93 * folder are identity. Pub/Sub topic, filter, and description update in
94 * place.
95 *
96 * ### Creating a Notification Config
97 * **Example:** Stream findings to Pub/Sub
98 * ```typescript
99 * const topic = yield* GCP.PubSub.Topic("SccFindings", {});
100 * const config = yield* GCP.SecurityCenter.FolderNotificationConfig(
101 * "Findings",
102 * {
103 * pubsubTopic: topic.name,
104 * filter: 'state="ACTIVE"',
105 * description: "active findings",
106 * },
107 * );
108 * ```
109 *
110 * **Example:** Named config on an explicit folder
111 * ```typescript
112 * const config = yield* GCP.SecurityCenter.FolderNotificationConfig(
113 * "Findings",
114 * {
115 * folder: "folders/123456789",
116 * configId: "active-findings",
117 * pubsubTopic: "projects/my-project/topics/scc",
118 * },
119 * );
120 * ```
121 *
122 * @resource
123 * @category SecurityCenter
124 */
125 export const FolderNotificationConfig = Resource<FolderNotificationConfig>(
126 "GCP.SecurityCenter.FolderNotificationConfig",
127 );
128
129 const resourceName = (folder: string, configId: string) =>
130 `${folder}/notificationConfigs/${configId}`;
131
132 const toAttrs = (config: scc.NotificationConfig, folder: string, project: string) => {
133 const name = config.name ?? "";
134 const parsed = parseName(name, "notificationConfigs");
135 const ownership = parseOwnership(config.description);
136 return {
137 name,
138 configId: parsed.id || lastSegment(name),
139 folder,
140 folderId: folderIdOf(folder),
141 project,
142 pubsubTopic: config.pubsubTopic ?? "",
143 filter: config.streamingConfig?.filter,
144 description: ownership.text,
145 serviceAccount: config.serviceAccount,
146 };
147 };
148
149 const getByName = (name: string) =>
150 name.length === 0
151 ? Effect.undefined
152 : scc
153 .getFoldersNotificationConfigs({ name })
154 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
155
156 export const FolderNotificationConfigProvider = () =>
157 Provider.succeed(FolderNotificationConfig, {
158 stables: ["name", "configId", "folder", "folderId", "project"],
159
160 diff: Effect.fn(function* ({ news, olds, output }) {
161 if (!isResolved(news)) return undefined;
162 return (
163 replaceOn(olds?.configId ?? output?.configId, news.configId) ??
164 replaceOn(
165 olds?.folder ?? output?.folder,
166 news.folder !== undefined ? folderParent(news.folder) : undefined,
167 )
168 );
169 }),
170
171 read: Effect.fn(function* ({ id, olds, output }) {
172 const env = yield* GcpEnvironment.current;
173 const folder = yield* resolveFolder(olds?.folder ?? output?.folder, output?.folder);
174 const configId = yield* toPhysicalId(id, olds?.configId, output?.configId);
175 const name = output?.name ?? resourceName(folder, configId);
176 const existing = yield* getByName(name);
177 if (existing === undefined) return undefined;
178 const attrs = toAttrs(existing, folder, env.project);
179 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
180 }),
181
182 list: () =>
183 Effect.gen(function* () {
184 const env = yield* GcpEnvironment.current;
185 const folder = yield* tryResolveFolder();
186 if (folder === undefined) return [];
187 return yield* scc.listFoldersNotificationConfigs
188 .pages({ parent: folder, pageSize: 100 })
189 .pipe(
190 Stream.flatMap((page) => Stream.fromIterable(page.notificationConfigs ?? [])),
191 Stream.filter((config) => hasOwnershipMarker(config.description)),
192 Stream.map((config) => toAttrs(config, folder, env.project)),
193 Stream.runCollect,
194 Effect.map((chunk) => Array.from(chunk)),
195 Effect.catchTag("NotFound", () => Effect.succeed([])),
196 );
197 }),
198
199 reconcile: Effect.fn(function* ({ id, news, output }) {
200 const env = yield* GcpEnvironment.current;
201 const folder = yield* resolveFolder(news.folder, output?.folder);
202 const configId = yield* toPhysicalId(id, news.configId, output?.configId);
203 const name = resourceName(folder, configId);
204 const ownership = yield* createInternalLabels(id);
205 const description = encodeDescription(ownership, news.description);
206 const pubsubTopic = news.pubsubTopic;
207 const filter = news.filter ?? "";
208 const streamingConfig = { filter };
209
210 let current = yield* getByName(output?.name ?? name);
211
212 if (current === undefined) {
213 const created = yield* scc
214 .createFoldersNotificationConfigs({
215 parent: folder,
216 configId,
217 body: { pubsubTopic, description, streamingConfig },
218 })
219 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
220 current = created ?? undefined;
221 }
222
223 if (current === undefined) {
224 return yield* new SecuritycenterNotResolved({ resourceName: name });
225 }
226
227 const currentName = current.name ?? name;
228 const updateMask = updateMaskOf(
229 !sameText(current.pubsubTopic, pubsubTopic) ? "pubsubTopic" : undefined,
230 !sameText(current.description, description) ? "description" : undefined,
231 !sameText(current.streamingConfig?.filter, filter) ? "streamingConfig.filter" : undefined,
232 );
233
234 if (updateMask.length > 0) {
235 current = yield* scc.patchFoldersNotificationConfigs({
236 name: currentName,
237 updateMask,
238 body: { pubsubTopic, description, streamingConfig },
239 });
240 }
241
242 return toAttrs(current, folder, env.project);
243 }),
244
245 delete: Effect.fn(function* ({ output }) {
246 yield* scc
247 .deleteFoldersNotificationConfigs({ name: output.name })
248 .pipe(Effect.catchTag("NotFound", () => Effect.void));
249 }),
250 });