@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, 06:00 UTC

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