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

main
ts 246 lines 7.81 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 BigQueryExportProps = {
26 /**
27 * Export id (the `{export}` segment of
28 * `projects/{project}/bigQueryExports/{export}`). If omitted, a unique
29 * id is generated. Lowercase letters, digits, and hyphens; must start
30 * with a letter; max 63 characters. Immutable — changing it replaces
31 * the export.
32 */
33 exportId?: string;
34 /**
35 * Destination dataset, as `projects/{project}/datasets/{dataset}`.
36 */
37 dataset: string;
38 /**
39 * Finding filter. Empty exports every finding in the parent.
40 */
41 filter?: string;
42 /**
43 * Human-readable description (max 1024 characters). BigQuery exports
44 * have no labels field, so Alchemy ownership is stored in a
45 * `[alchemy …]` prefix and stripped from attributes.
46 */
47 description?: string;
48 };
49
50 export type BigQueryExport = Resource<
51 "GCP.SecurityCenter.BigQueryExport",
52 BigQueryExportProps,
53 {
54 /** Full resource name `projects/{project}/bigQueryExports/{export}`. */
55 name: string;
56 /** Export id (last path segment). */
57 exportId: string;
58 /** Project id. */
59 project: string;
60 /** Destination dataset. */
61 dataset: string | undefined;
62 /** Finding filter. */
63 filter: string | undefined;
64 /** User description with the Alchemy ownership prefix stripped. */
65 description: string | undefined;
66 /** Service account SCC uses to write rows. */
67 principal: string | undefined;
68 /** RFC3339 creation timestamp. */
69 createTime: string | undefined;
70 /** RFC3339 last-update timestamp. */
71 updateTime: string | undefined;
72 /** Last editor email. */
73 mostRecentEditor: string | undefined;
74 },
75 never,
76 Providers
77 >;
78
79 /**
80 * A project-scoped Security Command Center BigQuery export that writes
81 * findings to a dataset.
82 *
83 * Exports have no labels field — Alchemy stamps ownership into the
84 * description so `list` / nuke can find them. Export id is identity.
85 * Dataset, filter, and description update in place.
86 *
87 * ### Creating a BigQuery Export
88 * **Example:** Export high-severity findings
89 * ```typescript
90 * const dataset = yield* GCP.BigQuery.Dataset("SccFindings", {
91 * location: "US",
92 * forceDestroy: true,
93 * });
94 * const exp = yield* GCP.SecurityCenter.BigQueryExport("High", {
95 * dataset: dataset.name,
96 * description: "high severity",
97 * filter: 'severity="HIGH"',
98 * });
99 * ```
100 *
101 * ### Updating a BigQuery Export
102 * **Example:** Also export critical findings
103 * ```typescript
104 * const exp = yield* GCP.SecurityCenter.BigQueryExport("High", {
105 * dataset: dataset.name,
106 * description: "high and critical",
107 * filter: 'severity="HIGH" OR severity="CRITICAL"',
108 * });
109 * ```
110 *
111 * @resource
112 * @category SecurityCenter
113 */
114 export const BigQueryExport = Resource<BigQueryExport>("GCP.SecurityCenter.BigQueryExport");
115
116 export class BigQueryExportNotResolved extends Data.TaggedError(
117 "GCP.SecurityCenter.BigQueryExportNotResolved",
118 )<{
119 resourceName: string;
120 }> {}
121
122 const resourceName = (project: string, exportId: string) =>
123 `projects/${project}/bigQueryExports/${exportId}`;
124
125 const toAttrs = (exp: scc.GoogleCloudSecuritycenterV1BigQueryExport, project: string) => {
126 const name = exp.name ?? "";
127 const parsed = parseOwnership(exp.description);
128 return {
129 name,
130 exportId: lastSegment(name),
131 project: projectOf(name) || project,
132 dataset: exp.dataset,
133 filter: exp.filter,
134 description: parsed.text,
135 principal: exp.principal,
136 createTime: exp.createTime,
137 updateTime: exp.updateTime,
138 mostRecentEditor: exp.mostRecentEditor,
139 };
140 };
141
142 const getByName = (name: string) =>
143 name.length === 0
144 ? Effect.undefined
145 : scc
146 .getProjectsBigQueryExports({ name })
147 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
148
149 export const BigQueryExportProvider = () =>
150 Provider.succeed(BigQueryExport, {
151 stables: ["name", "exportId", "project", "principal", "createTime"],
152
153 diff: Effect.fn(function* ({ news, olds, output }) {
154 if (!isResolved(news)) return undefined;
155 return replaceOn(olds?.exportId ?? output?.exportId, news.exportId);
156 }),
157
158 read: Effect.fn(function* ({ id, olds, output }) {
159 const env = yield* GcpEnvironment.current;
160 const exportId = yield* toResourceId(id, olds?.exportId, output?.exportId, "e");
161 const name = output?.name ?? resourceName(env.project, exportId);
162 const existing = yield* getByName(name);
163 if (existing === undefined) return undefined;
164 const attrs = toAttrs(existing, env.project);
165 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
166 }),
167
168 list: () =>
169 Effect.gen(function* () {
170 const env = yield* GcpEnvironment.current;
171 const items = yield* collectPages(
172 scc.listProjectsBigQueryExports.pages({
173 parent: `projects/${env.project}`,
174 pageSize: 100,
175 }),
176 (page) => page.bigQueryExports,
177 ).pipe(
178 Effect.catchTag("NotFound", () =>
179 Effect.succeed([] as scc.GoogleCloudSecuritycenterV1BigQueryExport[]),
180 ),
181 );
182 return items
183 .filter((exp) => hasOwnershipMarker(exp.description))
184 .map((exp) => toAttrs(exp, env.project));
185 }),
186
187 reconcile: Effect.fn(function* ({ id, news, output }) {
188 const env = yield* GcpEnvironment.current;
189 const exportId = yield* toResourceId(id, news.exportId, output?.exportId, "e");
190 const name = resourceName(env.project, exportId);
191 const ownership = yield* createInternalLabels(id);
192 const description = encodeOwnership(ownership, news.description);
193 const filter = news.filter ?? "";
194 const body: scc.GoogleCloudSecuritycenterV1BigQueryExport = {
195 dataset: news.dataset,
196 filter,
197 description,
198 };
199
200 let current = yield* getByName(output?.name ?? name);
201
202 if (current === undefined) {
203 const created = yield* scc
204 .createProjectsBigQueryExports({
205 parent: `projects/${env.project}`,
206 bigQueryExportId: exportId,
207 body,
208 })
209 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
210 current = created ?? undefined;
211 }
212
213 if (current === undefined) {
214 return yield* new BigQueryExportNotResolved({ resourceName: name });
215 }
216
217 const currentName = current.name ?? name;
218 const datasetChanged = !sameText(current.dataset, news.dataset);
219 const filterChanged = !sameText(current.filter, filter);
220 const descriptionChanged = !sameText(current.description, description);
221 const updateMask = updateMaskOf(
222 datasetChanged ? "dataset" : undefined,
223 filterChanged ? "filter" : undefined,
224 descriptionChanged ? "description" : undefined,
225 );
226
227 if (updateMask.length > 0) {
228 current = yield* scc.patchProjectsBigQueryExports({
229 name: currentName,
230 updateMask,
231 body: {
232 ...body,
233 name: currentName,
234 },
235 });
236 }
237
238 return toAttrs(current, env.project);
239 }),
240
241 delete: Effect.fn(function* ({ output }) {
242 yield* scc
243 .deleteProjectsBigQueryExports({ name: output.name })
244 .pipe(Effect.catchTag("NotFound", () => Effect.void));
245 }),
246 });