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

main
ts 342 lines 12.5 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { unownedUnlessPrevious } 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 * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import { lastSegment, orgParent, organizationFromName, sameJson, toResourceId } from "./names.ts";
12
13 const MAX_NAME_LENGTH = 59;
14 const ALCHEMY_ID_PREFIX = "alc-";
15
16 export type MonitoredResource = {
17 /** Resource id (API proxy id or API Hub deployment id). */
18 name: string;
19 /** Resource type. */
20 type:
21 | apigee.GoogleCloudApigeeV1BatchComputeSecurityAssessmentResultsRequestResourceArrayResourceTypeEnum
22 | (string & {});
23 };
24
25 export type SecurityMonitoringConditionProps = {
26 /**
27 * Apigee organization id. Defaults to the current GCP project id.
28 * Immutable — changing it replaces the condition.
29 */
30 organization?: string;
31 /**
32 * Condition id (the `{security_monitoring_condition}` segment of
33 * `organizations/{org}/securityMonitoringConditions/{id}`). If
34 * omitted, a unique `alc-` prefixed name is generated. 4–63
35 * characters, lowercase letters and hyphens. Immutable — changing it
36 * replaces the condition.
37 */
38 securityMonitoringConditionId?: string;
39 /**
40 * Security profile id or full name this condition scores against.
41 * Required.
42 */
43 profile: string;
44 /**
45 * Risk assessment type.
46 * @default "APIGEE"
47 */
48 riskAssessmentType?:
49 | apigee.GoogleCloudApigeeV1SecurityMonitoringConditionRiskAssessmentTypeEnum
50 | (string & {});
51 /**
52 * Environment scope when `riskAssessmentType` is `APIGEE`.
53 */
54 scope?: string;
55 /**
56 * API Hub gateway when `riskAssessmentType` is `API_HUB`
57 * (`projects/{project}/locations/{location}/plugins/{plugin}/instances/{instance}`).
58 */
59 apiHubGateway?: string;
60 /**
61 * When true, include every resource under `scope`. Mutually exclusive
62 * with `include`.
63 * @default false
64 */
65 includeAllResources?: boolean;
66 /**
67 * Explicit resources to include. Mutually exclusive with
68 * `includeAllResources`.
69 */
70 include?: MonitoredResource[];
71 };
72
73 export type SecurityMonitoringCondition = Resource<
74 "GCP.Apigee.SecurityMonitoringCondition",
75 SecurityMonitoringConditionProps,
76 {
77 /** Full resource name `organizations/{org}/securityMonitoringConditions/{id}`. */
78 name: string;
79 /** Condition id (last path segment). */
80 securityMonitoringConditionId: string;
81 /** Apigee organization id. */
82 organization: string;
83 /** Security profile id. */
84 profile: string;
85 /** Risk assessment type. */
86 riskAssessmentType: string | undefined;
87 /** Environment scope. */
88 scope: string | undefined;
89 /** API Hub gateway, if set. */
90 apiHubGateway: string | undefined;
91 /** Whether all resources under scope are included. */
92 includeAllResources: boolean;
93 /** Explicit included resources. */
94 include: MonitoredResource[];
95 /** Total deployed resources in scope. */
96 totalDeployedResources: number | undefined;
97 /** Total monitored resources. */
98 totalMonitoredResources: number | undefined;
99 /** RFC3339 creation timestamp. */
100 createTime: string | undefined;
101 /** RFC3339 last-update timestamp. */
102 updateTime: string | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * An Advanced API Security monitoring condition (risk assessment v2).
110 *
111 * Conditions have no labels or description. Generated ids are prefixed
112 * `alc-` so `list` / nuke can distinguish Alchemy rows from
113 * Google-defined conditions. Organization and id are identity —
114 * changing them replaces the condition. Profile, scope, include, and
115 * include-all update in place.
116 *
117 * ### Creating a Condition
118 * **Example:** Monitor every proxy in an environment
119 * ```typescript
120 * const profile = yield* GCP.Apigee.SecurityProfilesV2("Default", {});
121 * const condition = yield* GCP.Apigee.SecurityMonitoringCondition("Eval", {
122 * profile: profile.name,
123 * scope: "eval",
124 * includeAllResources: true,
125 * });
126 * ```
127 *
128 * @resource
129 * @category Apigee
130 */
131 export const SecurityMonitoringCondition = Resource<SecurityMonitoringCondition>(
132 "GCP.Apigee.SecurityMonitoringCondition",
133 );
134
135 export class SecurityMonitoringConditionNotResolved extends Data.TaggedError(
136 "GCP.Apigee.SecurityMonitoringConditionNotResolved",
137 )<{
138 resourceName: string;
139 }> {}
140
141 const resourceName = (organization: string, conditionId: string) =>
142 `${orgParent(organization)}/securityMonitoringConditions/${conditionId}`;
143
144 const conditionIdOf = (condition: apigee.GoogleCloudApigeeV1SecurityMonitoringCondition) =>
145 lastSegment(condition.name ?? "");
146
147 const toConditionId = (id: string, explicit: string | undefined, existing: string | undefined) =>
148 Effect.gen(function* () {
149 if (explicit !== undefined) return explicit;
150 if (existing !== undefined) return existing;
151 const generated = yield* toResourceId(id, undefined, undefined, MAX_NAME_LENGTH);
152 return generated.startsWith(ALCHEMY_ID_PREFIX)
153 ? generated
154 : `${ALCHEMY_ID_PREFIX}${generated}`.slice(0, 63);
155 });
156
157 const isAlchemyId = (conditionId: string) => conditionId.startsWith(ALCHEMY_ID_PREFIX);
158
159 const includeOf = (
160 include:
161 | apigee.GoogleCloudApigeeV1BatchComputeSecurityAssessmentResultsRequestResourceArray
162 | undefined,
163 ): MonitoredResource[] =>
164 (include?.resources ?? []).flatMap((resource) =>
165 resource.name !== undefined && resource.type !== undefined
166 ? [{ name: resource.name, type: resource.type }]
167 : [],
168 );
169
170 const toAttrs = (
171 condition: apigee.GoogleCloudApigeeV1SecurityMonitoringCondition,
172 organization: string,
173 ) => {
174 const securityMonitoringConditionId = conditionIdOf(condition);
175 const name = condition.name?.includes("/")
176 ? condition.name
177 : resourceName(organization, securityMonitoringConditionId);
178 return {
179 name,
180 securityMonitoringConditionId,
181 organization: organizationFromName(name) ?? organization,
182 profile: condition.profile ?? "",
183 riskAssessmentType: condition.riskAssessmentType,
184 scope: condition.scope,
185 apiHubGateway: condition.apiHubGateway,
186 includeAllResources: condition.includeAllResources !== undefined,
187 include: includeOf(condition.include),
188 totalDeployedResources: condition.totalDeployedResources,
189 totalMonitoredResources: condition.totalMonitoredResources,
190 createTime: condition.createTime,
191 updateTime: condition.updateTime,
192 };
193 };
194
195 const getByName = (name: string) =>
196 apigee
197 .getOrganizationsSecurityMonitoringConditions({ name })
198 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.undefined));
199
200 const toBody = (
201 news: SecurityMonitoringConditionProps,
202 ): apigee.GoogleCloudApigeeV1SecurityMonitoringCondition => ({
203 profile: news.profile,
204 riskAssessmentType: news.riskAssessmentType,
205 scope: news.scope,
206 apiHubGateway: news.apiHubGateway,
207 includeAllResources: news.includeAllResources === true ? {} : undefined,
208 include:
209 news.includeAllResources === true
210 ? undefined
211 : news.include !== undefined
212 ? { resources: news.include }
213 : undefined,
214 });
215
216 export const SecurityMonitoringConditionProvider = () =>
217 Provider.succeed(SecurityMonitoringCondition, {
218 stables: ["name", "securityMonitoringConditionId", "organization", "createTime"],
219
220 diff: Effect.fn(function* ({ news, olds, output }) {
221 if (!isResolved(news)) return undefined;
222 const previousId =
223 olds?.securityMonitoringConditionId ?? output?.securityMonitoringConditionId;
224 const previousOrg = olds?.organization ?? output?.organization;
225 if (
226 (previousId !== undefined &&
227 news.securityMonitoringConditionId !== undefined &&
228 news.securityMonitoringConditionId !== previousId) ||
229 (previousOrg !== undefined &&
230 news.organization !== undefined &&
231 news.organization !== previousOrg)
232 ) {
233 return { action: "replace" as const, deleteFirst: true };
234 }
235 return undefined;
236 }),
237
238 read: Effect.fn(function* ({ id, olds, output, previous }) {
239 const env = yield* GcpEnvironment.current;
240 const organization = organizationFromName(output?.name) ?? olds?.organization ?? env.project;
241 const securityMonitoringConditionId = yield* toConditionId(
242 id,
243 olds?.securityMonitoringConditionId,
244 output?.securityMonitoringConditionId,
245 );
246 const name = output?.name ?? resourceName(organization, securityMonitoringConditionId);
247 const existing = yield* getByName(name);
248 if (existing === undefined) return undefined;
249 const attrs = toAttrs(existing, organization);
250 return isAlchemyId(attrs.securityMonitoringConditionId) ||
251 (olds?.securityMonitoringConditionId !== undefined &&
252 olds.securityMonitoringConditionId === attrs.securityMonitoringConditionId)
253 ? attrs
254 : unownedUnlessPrevious(attrs, previous, "name");
255 }),
256
257 list: () =>
258 Effect.gen(function* () {
259 const env = yield* GcpEnvironment.current;
260 return yield* apigee.listOrganizationsSecurityMonitoringConditions
261 .pages({
262 parent: orgParent(env.project),
263 pageSize: 1000,
264 })
265 .pipe(
266 Stream.flatMap((page) => Stream.fromIterable(page.securityMonitoringConditions ?? [])),
267 Stream.filter((condition) => isAlchemyId(conditionIdOf(condition))),
268 Stream.map((condition) => toAttrs(condition, env.project)),
269 Stream.runCollect,
270 Effect.map((chunk) => Array.from(chunk)),
271 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
272 Effect.succeed([] as SecurityMonitoringCondition["Attributes"][]),
273 ),
274 );
275 }),
276
277 reconcile: Effect.fn(function* ({ id, news, output }) {
278 const env = yield* GcpEnvironment.current;
279 const organization = news.organization ?? output?.organization ?? env.project;
280 const securityMonitoringConditionId = yield* toConditionId(
281 id,
282 news.securityMonitoringConditionId,
283 output?.securityMonitoringConditionId,
284 );
285 const name = resourceName(organization, securityMonitoringConditionId);
286
287 let current = yield* getByName(output?.name ?? name);
288
289 if (current === undefined) {
290 const created = yield* apigee
291 .createOrganizationsSecurityMonitoringConditions({
292 parent: orgParent(organization),
293 securityMonitoringConditionId,
294 body: toBody(news),
295 })
296 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
297 current = created ?? undefined;
298 }
299
300 if (current === undefined) {
301 return yield* new SecurityMonitoringConditionNotResolved({ resourceName: name });
302 }
303
304 const desiredIncludeAll = news.includeAllResources === true;
305 const observedIncludeAll = current.includeAllResources !== undefined;
306 const profileChanged = (current.profile ?? "") !== news.profile;
307 const scopeChanged = (current.scope ?? "") !== (news.scope ?? "");
308 const gatewayChanged = (current.apiHubGateway ?? "") !== (news.apiHubGateway ?? "");
309 const includeAllChanged = desiredIncludeAll !== observedIncludeAll;
310 const includeChanged = !sameJson(includeOf(current.include), news.include ?? []);
311 const typeChanged =
312 (current.riskAssessmentType ?? "") !==
313 (news.riskAssessmentType ?? current.riskAssessmentType ?? "");
314
315 const updateMask = [
316 profileChanged ? "profile" : undefined,
317 scopeChanged ? "scope" : undefined,
318 gatewayChanged ? "apiHubGateway" : undefined,
319 includeAllChanged ? "include_all_resources" : undefined,
320 includeChanged ? "include" : undefined,
321 typeChanged ? "riskAssessmentType" : undefined,
322 ].filter((field): field is string => field !== undefined);
323
324 if (updateMask.length > 0) {
325 current = yield* apigee.patchOrganizationsSecurityMonitoringConditions({
326 name: current.name?.includes("/") ? current.name : name,
327 updateMask: updateMask.join(","),
328 body: toBody(news),
329 });
330 }
331
332 return toAttrs(current, organization);
333 }),
334
335 delete: Effect.fn(function* ({ output }) {
336 yield* apigee
337 .deleteOrganizationsSecurityMonitoringConditions({
338 name: output.name,
339 })
340 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
341 }),
342 });