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

main
ts 244 lines 8.04 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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 collectPages,
13 encodeOwnership,
14 hasOwnershipMarker,
15 lastSegment,
16 ownedByAlchemy,
17 parseOwnership,
18 projectOf,
19 replaceOn,
20 sameText,
21 toResourceId,
22 updateMaskOf,
23 } from "./internal.ts";
24
25 export type StreamingConfig = {
26 /**
27 * Finding filter. Empty matches every finding in the parent.
28 */
29 filter?: string;
30 };
31
32 export type NotificationConfigProps = {
33 /**
34 * Config id (the `{config}` segment of
35 * `projects/{project}/notificationConfigs/{config}`). If omitted, a unique
36 * id is generated. Letters, digits, and hyphens; must start with a letter;
37 * max 63 characters. Immutable — changing it replaces the config.
38 */
39 configId?: string;
40 /**
41 * Pub/Sub topic that receives findings, as
42 * `projects/{project}/topics/{topic}`.
43 */
44 pubsubTopic: string;
45 /**
46 * Human-readable description (max 1024 characters). Notification configs
47 * have no labels field, so Alchemy ownership is stored in a
48 * `[alchemy …]` prefix and stripped from attributes.
49 */
50 description?: string;
51 /**
52 * Streaming config. `filter` selects which findings are published.
53 */
54 streamingConfig?: StreamingConfig;
55 };
56
57 export type NotificationConfig = Resource<
58 "GCP.SecurityCenter.NotificationConfig",
59 NotificationConfigProps,
60 {
61 /** Full resource name `projects/{project}/notificationConfigs/{config}`. */
62 name: string;
63 /** Config id (last path segment). */
64 configId: string;
65 /** Project id. */
66 project: string;
67 /** Pub/Sub topic findings are published to. */
68 pubsubTopic: string | undefined;
69 /** User description with the Alchemy ownership prefix stripped. */
70 description: string | undefined;
71 /** Streaming config. */
72 streamingConfig: StreamingConfig | undefined;
73 /** Service account SCC uses to publish. */
74 serviceAccount: string | undefined;
75 },
76 never,
77 Providers
78 >;
79
80 /**
81 * A project-scoped Security Command Center notification config that
82 * publishes findings to a Pub/Sub topic.
83 *
84 * Notification configs have no labels field — Alchemy stamps ownership
85 * into the description so `list` / nuke can find them. Config id is
86 * identity. Description, Pub/Sub topic, and streaming filter update in
87 * place.
88 *
89 * ### Creating a Notification Config
90 * **Example:** Publish high-severity findings
91 * ```typescript
92 * const topic = yield* GCP.PubSub.Topic("SccFindings", {});
93 * const config = yield* GCP.SecurityCenter.NotificationConfig("High", {
94 * pubsubTopic: topic.name,
95 * description: "high severity",
96 * streamingConfig: { filter: 'severity="HIGH"' },
97 * });
98 * ```
99 *
100 * ### Updating a Notification Config
101 * **Example:** Also publish critical findings
102 * ```typescript
103 * const config = yield* GCP.SecurityCenter.NotificationConfig("High", {
104 * pubsubTopic: topic.name,
105 * description: "high and critical",
106 * streamingConfig: { filter: 'severity="HIGH" OR severity="CRITICAL"' },
107 * });
108 * ```
109 *
110 * @resource
111 * @category SecurityCenter
112 */
113 export const NotificationConfig = Resource<NotificationConfig>(
114 "GCP.SecurityCenter.NotificationConfig",
115 );
116
117 export class NotificationConfigNotResolved extends Data.TaggedError(
118 "GCP.SecurityCenter.NotificationConfigNotResolved",
119 )<{
120 resourceName: string;
121 }> {}
122
123 const resourceName = (project: string, configId: string) =>
124 `projects/${project}/notificationConfigs/${configId}`;
125
126 const streamingOf = (
127 config: scc.StreamingConfig | StreamingConfig | undefined,
128 ): StreamingConfig | undefined => (config === undefined ? undefined : { filter: config.filter });
129
130 const toAttrs = (config: scc.NotificationConfig, project: string) => {
131 const name = config.name ?? "";
132 const parsed = parseOwnership(config.description);
133 return {
134 name,
135 configId: lastSegment(name),
136 project: projectOf(name) || project,
137 pubsubTopic: config.pubsubTopic,
138 description: parsed.text,
139 streamingConfig: streamingOf(config.streamingConfig),
140 serviceAccount: config.serviceAccount,
141 };
142 };
143
144 const getByName = (name: string) =>
145 name.length === 0
146 ? Effect.undefined
147 : scc
148 .getProjectsNotificationConfigs({ name })
149 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
150
151 export const NotificationConfigProvider = () =>
152 Provider.succeed(NotificationConfig, {
153 stables: ["name", "configId", "project", "serviceAccount"],
154
155 diff: Effect.fn(function* ({ news, olds, output }) {
156 if (!isResolved(news)) return undefined;
157 return replaceOn(olds?.configId ?? output?.configId, news.configId);
158 }),
159
160 read: Effect.fn(function* ({ id, olds, output }) {
161 const env = yield* GcpEnvironment.current;
162 const configId = yield* toResourceId(id, olds?.configId, output?.configId, "n");
163 const name = output?.name ?? resourceName(env.project, configId);
164 const existing = yield* getByName(name);
165 if (existing === undefined) return undefined;
166 const attrs = toAttrs(existing, env.project);
167 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
168 }),
169
170 list: () =>
171 Effect.gen(function* () {
172 const env = yield* GcpEnvironment.current;
173 const items = yield* collectPages(
174 scc.listProjectsNotificationConfigs.pages({
175 parent: `projects/${env.project}`,
176 pageSize: 100,
177 }),
178 (page) => page.notificationConfigs,
179 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as scc.NotificationConfig[])));
180 return items
181 .filter((config) => hasOwnershipMarker(config.description))
182 .map((config) => toAttrs(config, env.project));
183 }),
184
185 reconcile: Effect.fn(function* ({ id, news, output }) {
186 const env = yield* GcpEnvironment.current;
187 const configId = yield* toResourceId(id, news.configId, output?.configId, "n");
188 const name = resourceName(env.project, configId);
189 const ownership = yield* createInternalLabels(id);
190 const description = encodeOwnership(ownership, news.description);
191 const filter = news.streamingConfig?.filter ?? "";
192 const body: scc.NotificationConfig = {
193 pubsubTopic: news.pubsubTopic,
194 description,
195 streamingConfig: { filter },
196 };
197
198 let current = yield* getByName(output?.name ?? name);
199
200 if (current === undefined) {
201 const created = yield* scc
202 .createProjectsNotificationConfigs({
203 parent: `projects/${env.project}`,
204 configId,
205 body,
206 })
207 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
208 current = created ?? undefined;
209 }
210
211 if (current === undefined) {
212 return yield* new NotificationConfigNotResolved({ resourceName: name });
213 }
214
215 const currentName = current.name ?? name;
216 const descriptionChanged = !sameText(current.description, description);
217 const topicChanged = !sameText(current.pubsubTopic, news.pubsubTopic);
218 const filterChanged = !sameText(current.streamingConfig?.filter, filter);
219 const updateMask = updateMaskOf(
220 descriptionChanged ? "description" : undefined,
221 topicChanged ? "pubsub_topic" : undefined,
222 filterChanged ? "streaming_config.filter" : undefined,
223 );
224
225 if (updateMask.length > 0) {
226 current = yield* scc.patchProjectsNotificationConfigs({
227 name: currentName,
228 updateMask,
229 body: {
230 ...body,
231 name: currentName,
232 },
233 });
234 }
235
236 return toAttrs(current, env.project);
237 }),
238
239 delete: Effect.fn(function* ({ output }) {
240 yield* scc
241 .deleteProjectsNotificationConfigs({ name: output.name })
242 .pipe(Effect.catchTag("NotFound", () => Effect.void));
243 }),
244 });