@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 308 lines 9.79 KB
Raw
1 import * as cloudasset from "@distilled.cloud/gcp/cloudasset_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 { tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import { GcpEnvironment } from "../Environment.ts";
10 import {
11 createInternalLabels,
12 diffLabels,
13 hasAlchemyLabels,
14 stripInternalLabels,
15 toLabels,
16 } from "../Labels.ts";
17 import type { Providers } from "../Providers.ts";
18 import {
19 lastSegment,
20 listSavedQueries,
21 MAX_SAVED_QUERY_DESCRIPTION,
22 parentOf,
23 projectParent,
24 replaceOn,
25 scopeParent,
26 sameJson,
27 sameText,
28 toPhysicalId,
29 updateMaskOf,
30 } from "./internal.ts";
31
32 export type IamPolicyAnalysisQuery = cloudasset.IamPolicyAnalysisQuery;
33 export type QueryContent = cloudasset.QueryContent;
34
35 export type SavedQueryProps = {
36 /**
37 * Saved query id (the `{savedQuery}` segment of
38 * `projects/{project}/savedQueries/{savedQuery}`). If omitted, a
39 * unique RFC1035 name is generated (4-63 characters, `a-z0-9-`).
40 * Immutable — changing it replaces the query.
41 */
42 savedQueryId?: string;
43 /**
44 * Parent project, folder, or organization
45 * (`projects/{project}`, `folders/{folder}`,
46 * `organizations/{organization}`). Defaults to the current project.
47 * Immutable — changing it replaces the query.
48 */
49 parent?: string;
50 /**
51 * Human-readable description (max 255 characters).
52 */
53 description?: string;
54 /**
55 * User labels. Alchemy ownership labels are merged in automatically.
56 * At most 10 entries including ownership labels; keys and values are
57 * under 64 characters.
58 */
59 labels?: Record<string, string>;
60 /**
61 * Query payload. Defaults to an IAM policy analysis of the current
62 * project.
63 */
64 content?: QueryContent;
65 };
66
67 export type SavedQuery = Resource<
68 "GCP.CloudAsset.SavedQuery",
69 SavedQueryProps,
70 {
71 /** Full resource name `projects/{project}/savedQueries/{savedQuery}`. */
72 name: string;
73 /** Saved query id (last path segment). */
74 savedQueryId: string;
75 /** Parent project, folder, or organization. */
76 parent: string;
77 /** Project id used when the query was reconciled. */
78 project: string;
79 /** User description. */
80 description: string | undefined;
81 /** User labels (Alchemy ownership labels stripped). */
82 labels: Record<string, string>;
83 /** Query payload. */
84 content: QueryContent | undefined;
85 /** RFC3339 creation timestamp. */
86 createTime: string | undefined;
87 /** Account that created the query. */
88 creator: string | undefined;
89 /** RFC3339 last-update timestamp. */
90 lastUpdateTime: string | undefined;
91 /** Account that last updated the query. */
92 lastUpdater: string | undefined;
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * A Cloud Asset Inventory saved query, typically an IAM policy analysis
100 * that can be rerun later.
101 *
102 * Saved query id and parent are identity. Description, labels, and
103 * content update in place. Alchemy ownership is stored in labels so
104 * `list` / nuke can find the query.
105 *
106 * ### Creating a Saved Query
107 * **Example:** Analyze IAM in the current project
108 * ```typescript
109 * const query = yield* GCP.CloudAsset.SavedQuery("IamAudit", {
110 * description: "who can act as service accounts",
111 * content: {
112 * iamPolicyAnalysisQuery: {
113 * scope: `projects/${project}`,
114 * accessSelector: {
115 * permissions: ["iam.serviceAccounts.actAs"],
116 * },
117 * },
118 * },
119 * });
120 * ```
121 *
122 * **Example:** Generated id with labels
123 * ```typescript
124 * const query = yield* GCP.CloudAsset.SavedQuery("IamAudit", {
125 * labels: { env: "dev" },
126 * });
127 * ```
128 *
129 * ### Updating a Saved Query
130 * **Example:** Change the description and selector
131 * ```typescript
132 * // Same logical id, changed props: the query is patched in place.
133 * const query = yield* GCP.CloudAsset.SavedQuery("IamAudit", {
134 * description: "roles and permissions",
135 * labels: { env: "prod" },
136 * content: {
137 * iamPolicyAnalysisQuery: {
138 * scope: `projects/${project}`,
139 * accessSelector: {
140 * roles: ["roles/owner"],
141 * },
142 * },
143 * },
144 * });
145 * ```
146 *
147 * @resource
148 * @category CloudAsset
149 */
150 export const SavedQuery = Resource<SavedQuery>("GCP.CloudAsset.SavedQuery");
151
152 export class SavedQueryNotResolved extends Data.TaggedError(
153 "GCP.CloudAsset.SavedQueryNotResolved",
154 )<{
155 resourceName: string;
156 }> {}
157
158 const resourceName = (parent: string, savedQueryId: string) =>
159 `${parent}/savedQueries/${savedQueryId}`;
160
161 const userLabels = (
162 labels: Record<string, string | undefined> | null | undefined,
163 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
164
165 const desiredContent = (project: string, content: QueryContent | undefined): QueryContent => ({
166 iamPolicyAnalysisQuery: {
167 ...content?.iamPolicyAnalysisQuery,
168 scope: content?.iamPolicyAnalysisQuery?.scope ?? projectParent(project),
169 },
170 });
171
172 const toAttrs = (query: cloudasset.SavedQuery, project: string) => {
173 const name = query.name ?? "";
174 return {
175 name,
176 savedQueryId: lastSegment(name),
177 parent: parentOf(name, "savedQueries"),
178 project,
179 description: query.description,
180 labels: userLabels(query.labels),
181 content: query.content,
182 createTime: query.createTime,
183 creator: query.creator,
184 lastUpdateTime: query.lastUpdateTime,
185 lastUpdater: query.lastUpdater,
186 };
187 };
188
189 const getByName = (name: string) =>
190 name.length === 0
191 ? Effect.undefined
192 : cloudasset
193 .getSavedQueries({ name })
194 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
195
196 const observe = (project: string, savedQueryId: string, outputName?: string) =>
197 Effect.gen(function* () {
198 const parent = yield* scopeParent(project);
199 const candidates = [outputName, resourceName(parent, savedQueryId)].filter(
200 (name): name is string => name !== undefined && name.length > 0,
201 );
202 for (const name of candidates) {
203 const found = yield* getByName(name);
204 if (found !== undefined) return found;
205 }
206 const queries = yield* listSavedQueries(parent);
207 return queries.find((query) => lastSegment(query.name ?? "") === savedQueryId);
208 });
209
210 export const SavedQueryProvider = () =>
211 Provider.succeed(SavedQuery, {
212 stables: ["name", "savedQueryId", "parent", "project", "createTime"],
213
214 diff: Effect.fn(function* ({ news, olds, output }) {
215 if (!isResolved(news)) return undefined;
216 return (
217 replaceOn(olds?.savedQueryId ?? output?.savedQueryId, news.savedQueryId) ??
218 replaceOn(olds?.parent, news.parent)
219 );
220 }),
221
222 read: Effect.fn(function* ({ id, olds, output }) {
223 const env = yield* GcpEnvironment.current;
224 const savedQueryId = yield* toPhysicalId(id, olds?.savedQueryId, output?.savedQueryId);
225 const existing = yield* observe(env.project, savedQueryId, output?.name);
226 if (existing === undefined) return undefined;
227 const attrs = toAttrs(existing, env.project);
228 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
229 }),
230
231 list: () =>
232 Effect.gen(function* () {
233 const env = yield* GcpEnvironment.current;
234 const parent = yield* scopeParent(env.project);
235 const queries = yield* listSavedQueries(parent);
236 return queries
237 .filter((query) =>
238 Object.keys(query.labels ?? {}).some((key) => key.startsWith("alchemy-")),
239 )
240 .map((query) => toAttrs(query, env.project));
241 }),
242
243 reconcile: Effect.fn(function* ({ id, news, output }) {
244 const env = yield* GcpEnvironment.current;
245 const savedQueryId = yield* toPhysicalId(id, news.savedQueryId, output?.savedQueryId);
246 const parent = yield* scopeParent(env.project, news.parent);
247 const name = resourceName(parent, savedQueryId);
248 const desiredLabels = {
249 ...toLabels(news.labels),
250 ...(yield* createInternalLabels(id)),
251 };
252 const description = news.description?.slice(0, MAX_SAVED_QUERY_DESCRIPTION);
253 const content = desiredContent(env.project, news.content);
254 const body: cloudasset.SavedQuery = {
255 description,
256 labels: desiredLabels,
257 content,
258 };
259
260 let current = yield* observe(env.project, savedQueryId, output?.name);
261
262 if (current === undefined) {
263 const created = yield* cloudasset
264 .createSavedQueries({
265 parent,
266 savedQueryId,
267 body,
268 })
269 .pipe(
270 Effect.catchTag("Conflict", () => observe(env.project, savedQueryId, output?.name)),
271 );
272 current = created ?? undefined;
273 }
274
275 if (current === undefined) {
276 return yield* new SavedQueryNotResolved({ resourceName: name });
277 }
278
279 const currentName = current.name ?? name;
280 const observedLabels = tagRecord(current.labels);
281 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
282 const labelsChanged = upsert.length > 0 || removed.length > 0;
283 const descriptionChanged = !sameText(current.description, description);
284 const contentChanged = !sameJson(current.content, content);
285 const updateMask = updateMaskOf(
286 descriptionChanged ? "description" : undefined,
287 labelsChanged ? "labels" : undefined,
288 contentChanged ? "content" : undefined,
289 );
290
291 if (updateMask.length > 0) {
292 current = yield* cloudasset.patchSavedQueries({
293 name: currentName,
294 updateMask,
295 body: { ...body, name: currentName },
296 });
297 }
298
299 return toAttrs(current, env.project);
300 }),
301
302 delete: Effect.fn(function* ({ output }) {
303 if (!output.name) return;
304 yield* cloudasset
305 .deleteSavedQueries({ name: output.name })
306 .pipe(Effect.catchTag(["NotFound", "BadRequest"], () => Effect.void));
307 }),
308 });