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