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

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