@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 433 lines 14.6 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_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 * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 encodeDescription,
15 environmentIdOf,
16 environmentNameOf,
17 hasOwnershipMarker,
18 lastSegment,
19 listProjectEnvironments,
20 missingToUndefined,
21 organizationIdOf,
22 ownedById,
23 parseDescription,
24 parseOrgEnv,
25 sameList,
26 sameText,
27 toResourceId,
28 } from "./common.ts";
29
30 const MAX_NAME_LENGTH = 63;
31 const DEFAULT_STATE = "ENABLED";
32
33 export type SecurityActionConditionConfig = {
34 /** Developer emails. Limit 1000. */
35 developers?: string[];
36 /** IPv4 or IPv6 ranges. Limit 100. */
37 ipAddressRanges?: string[];
38 /** API keys. Limit 1000. */
39 apiKeys?: string[];
40 /** Developer app names. Limit 1000. */
41 developerApps?: string[];
42 /** Exact user-agent matches. Limit 50. */
43 userAgents?: string[];
44 /** API product names. Limit 1000. */
45 apiProducts?: string[];
46 /** Access tokens. Limit 1000. */
47 accessTokens?: string[];
48 /** ASN numbers. */
49 asns?: string[];
50 /** Bot reasons (`Flooder`, `Robot Abuser`, …). */
51 botReasons?: string[];
52 /** ISO 3166-1 alpha-2 region codes. */
53 regionCodes?: string[];
54 /** HTTP methods (`GET`, `POST`, …). */
55 httpMethods?: string[];
56 };
57
58 export type SecurityActionDeny = {
59 /** HTTP response code when denying. */
60 responseCode?: number;
61 };
62
63 export type SecurityActionFlagHeader = {
64 /** Header name sent to the target. */
65 name?: string;
66 /** Header value sent to the target. */
67 value?: string;
68 };
69
70 export type SecurityActionFlag = {
71 /** Headers added when flagging. At least one is required. */
72 headers?: SecurityActionFlagHeader[];
73 };
74
75 export type EnvironmentsSecurityActionProps = {
76 /**
77 * Apigee organization id or `organizations/{org}`. Defaults to the
78 * current GCP project id. Immutable — changing it replaces the action.
79 */
80 organization?: string;
81 /**
82 * Environment id or `organizations/{org}/environments/{env}`. Immutable —
83 * changing it replaces the action.
84 */
85 environment: string;
86 /**
87 * Security action id (rfc1035, 1-63 chars). If omitted, a unique name
88 * is generated. Immutable — changing it replaces the action.
89 */
90 securityActionId?: string;
91 /**
92 * Human-readable description. Alchemy stamps ownership into a
93 * `[alchemy …]` prefix because security actions have no labels field.
94 */
95 description?: string;
96 /**
97 * Enforcement state. Only `ENABLED` actions are enforced.
98 * @default "ENABLED"
99 */
100 state?: apigee.GoogleCloudApigeeV1SecurityActionStateEnum | (string & {});
101 /**
102 * Conditions that must match. At least one field is required.
103 */
104 conditionConfig: SecurityActionConditionConfig;
105 /**
106 * Deny matching requests. Mutually exclusive with `allow` and `flag`.
107 */
108 deny?: SecurityActionDeny;
109 /**
110 * Allow matching requests through.
111 */
112 allow?: boolean;
113 /**
114 * Flag matching requests by adding headers.
115 */
116 flag?: SecurityActionFlag;
117 /**
118 * Input-only TTL (e.g. `"3600s"`).
119 */
120 ttl?: string;
121 /**
122 * Expiration timestamp.
123 */
124 expireTime?: string;
125 /**
126 * Limit enforcement to these API proxies. Omitted applies to all.
127 */
128 apiProxies?: string[];
129 };
130
131 export type EnvironmentsSecurityAction = Resource<
132 "GCP.Apigee.EnvironmentsSecurityAction",
133 EnvironmentsSecurityActionProps,
134 {
135 /** Full resource name `organizations/{org}/environments/{env}/securityActions/{id}`. */
136 name: string;
137 /** Security action id. */
138 securityActionId: string;
139 /** Apigee organization id. */
140 organizationId: string;
141 /** Environment id. */
142 environmentId: string;
143 /** User description with the Alchemy ownership prefix stripped. */
144 description: string | undefined;
145 /** Enforcement state. */
146 state: string | undefined;
147 /** Condition configuration. */
148 conditionConfig: SecurityActionConditionConfig | undefined;
149 /** Deny action, if set. */
150 deny: SecurityActionDeny | undefined;
151 /** Whether this is an allow action. */
152 allow: boolean;
153 /** Flag action, if set. */
154 flag: SecurityActionFlag | undefined;
155 /** Expiration timestamp. */
156 expireTime: string | undefined;
157 /** API proxies this action applies to. */
158 apiProxies: string[];
159 /** RFC3339 create time. */
160 createTime: string | undefined;
161 /** RFC3339 update time. */
162 updateTime: string | undefined;
163 },
164 never,
165 Providers
166 >;
167
168 /**
169 * An environment-level Apigee SecurityAction — allow, deny, or flag
170 * requests that match a condition.
171 *
172 * Security actions have no labels, so Alchemy stamps ownership into
173 * `description` for `list` / nuke. Name is identity; description, state,
174 * conditions, and the allow/deny/flag payload update in place.
175 *
176 * ### Creating a Deny Action
177 * **Example:** Deny a TEST-NET address
178 * ```typescript
179 * const action = yield* GCP.Apigee.EnvironmentsSecurityAction("BlockProbe", {
180 * environment: "eval",
181 * conditionConfig: { ipAddressRanges: ["192.0.2.1"] },
182 * deny: { responseCode: 403 },
183 * });
184 * ```
185 *
186 * @resource
187 * @category Apigee
188 */
189 export const EnvironmentsSecurityAction = Resource<EnvironmentsSecurityAction>(
190 "GCP.Apigee.EnvironmentsSecurityAction",
191 );
192
193 export class EnvironmentsSecurityActionNotResolved extends Data.TaggedError(
194 "GCP.Apigee.EnvironmentsSecurityActionNotResolved",
195 )<{
196 resourceName: string;
197 }> {}
198
199 const resourceName = (organizationId: string, environmentId: string, securityActionId: string) =>
200 `${environmentNameOf(organizationId, environmentId)}/securityActions/${securityActionId}`;
201
202 const conditionOf = (
203 config: apigee.GoogleCloudApigeeV1SecurityActionConditionConfig | undefined,
204 ): SecurityActionConditionConfig | undefined => {
205 if (config === undefined) return undefined;
206 return {
207 developers: config.developers,
208 ipAddressRanges: config.ipAddressRanges,
209 apiKeys: config.apiKeys,
210 developerApps: config.developerApps,
211 userAgents: config.userAgents,
212 apiProducts: config.apiProducts,
213 accessTokens: config.accessTokens,
214 asns: config.asns,
215 botReasons: config.botReasons,
216 regionCodes: config.regionCodes,
217 httpMethods: config.httpMethods,
218 };
219 };
220
221 const toAttrs = (
222 action: apigee.GoogleCloudApigeeV1SecurityAction,
223 organizationId: string,
224 environmentId: string,
225 ) => {
226 const raw = action.name ?? "";
227 const parsed = parseOrgEnv(raw);
228 const securityActionId = lastSegment(raw);
229 const description = parseDescription(action.description);
230 return {
231 name: raw.includes("/")
232 ? raw
233 : resourceName(organizationId, environmentId, securityActionId || raw),
234 securityActionId: securityActionId || raw,
235 organizationId: parsed.organizationId || organizationId,
236 environmentId: parsed.environmentId || environmentId,
237 description: description.description,
238 state: action.state,
239 conditionConfig: conditionOf(action.conditionConfig),
240 deny:
241 action.deny?.responseCode !== undefined
242 ? { responseCode: action.deny.responseCode }
243 : action.deny
244 ? {}
245 : undefined,
246 allow: action.allow !== undefined,
247 flag:
248 action.flag?.headers !== undefined
249 ? {
250 headers: (action.flag.headers ?? []).map((header) => ({
251 name: header.name,
252 value: header.value,
253 })),
254 }
255 : undefined,
256 expireTime: action.expireTime,
257 apiProxies: action.apiProxies ?? [],
258 createTime: action.createTime,
259 updateTime: action.updateTime,
260 };
261 };
262
263 const getByName = (name: string) =>
264 missingToUndefined(apigee.getOrganizationsEnvironmentsSecurityActions({ name }));
265
266 const toBody = (
267 news: EnvironmentsSecurityActionProps,
268 description: string,
269 securityActionId: string,
270 ): apigee.GoogleCloudApigeeV1SecurityAction => ({
271 name: securityActionId,
272 description,
273 state: news.state ?? DEFAULT_STATE,
274 conditionConfig: news.conditionConfig,
275 deny: news.deny,
276 allow: news.allow === true ? {} : undefined,
277 flag: news.flag,
278 ttl: news.ttl,
279 expireTime: news.expireTime,
280 apiProxies: news.apiProxies,
281 });
282
283 const jsonOf = (value: unknown) => JSON.stringify(value ?? null);
284
285 export const EnvironmentsSecurityActionProvider = () =>
286 Provider.succeed(EnvironmentsSecurityAction, {
287 stables: ["name", "securityActionId", "organizationId", "environmentId", "createTime"],
288
289 diff: Effect.fn(function* ({ news, olds, output }) {
290 if (!isResolved(news)) return undefined;
291 const previousId = olds?.securityActionId ?? output?.securityActionId;
292 const previousOrg = olds?.organization ?? output?.organizationId;
293 const previousEnv = olds?.environment ?? output?.environmentId;
294 const idChanged =
295 previousId !== undefined &&
296 news.securityActionId !== undefined &&
297 news.securityActionId !== previousId;
298 const orgChanged =
299 previousOrg !== undefined &&
300 news.organization !== undefined &&
301 organizationIdOf(news.organization, "") !== organizationIdOf(previousOrg, "");
302 const envChanged =
303 previousEnv !== undefined &&
304 environmentIdOf(news.environment) !== environmentIdOf(previousEnv);
305 if (idChanged || orgChanged || envChanged) {
306 return { action: "replace" as const, deleteFirst: false };
307 }
308 return undefined;
309 }),
310
311 read: Effect.fn(function* ({ id, olds, output }) {
312 const { project } = yield* GcpEnvironment.current;
313 const organizationId = organizationIdOf(
314 olds?.organization ?? output?.organizationId,
315 project,
316 );
317 const environmentId = environmentIdOf(olds?.environment ?? output?.environmentId ?? "");
318 const securityActionId = yield* toResourceId(
319 id,
320 olds?.securityActionId,
321 output?.securityActionId,
322 { maxLength: MAX_NAME_LENGTH, rfc1035: true },
323 );
324 const name = output?.name ?? resourceName(organizationId, environmentId, securityActionId);
325 const existing = yield* getByName(name);
326 if (existing === undefined) return undefined;
327 const attrs = toAttrs(existing, organizationId, environmentId);
328 const { labels } = parseDescription(existing.description);
329 return (yield* ownedById(id, tagRecord(labels))) ? attrs : Unowned(attrs);
330 }),
331
332 list: () =>
333 Effect.gen(function* () {
334 const environments = yield* listProjectEnvironments();
335 const found: EnvironmentsSecurityAction["Attributes"][] = [];
336 for (const item of environments) {
337 const actions = yield* apigee.listOrganizationsEnvironmentsSecurityActions
338 .pages({ parent: item.parent, pageSize: 100 })
339 .pipe(
340 Stream.flatMap((page) => Stream.fromIterable(page.securityActions ?? [])),
341 Stream.filter((action) => hasOwnershipMarker(action.description)),
342 Stream.map((action) => toAttrs(action, item.organizationId, item.environmentId)),
343 Stream.runCollect,
344 Effect.map((chunk) => Array.from(chunk)),
345 Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () =>
346 Effect.succeed([] as EnvironmentsSecurityAction["Attributes"][]),
347 ),
348 );
349 found.push(...actions);
350 }
351 return found;
352 }),
353
354 reconcile: Effect.fn(function* ({ id, news, output }) {
355 const { project } = yield* GcpEnvironment.current;
356 const organizationId = organizationIdOf(news.organization, project);
357 const environmentId = environmentIdOf(news.environment);
358 const securityActionId = yield* toResourceId(
359 id,
360 news.securityActionId,
361 output?.securityActionId,
362 { maxLength: MAX_NAME_LENGTH, rfc1035: true },
363 );
364 const parent = environmentNameOf(organizationId, environmentId);
365 const name = resourceName(organizationId, environmentId, securityActionId);
366 const ownership = yield* createInternalLabels(id);
367 const desiredDescription = encodeDescription(ownership, news.description);
368 const desiredState = news.state ?? DEFAULT_STATE;
369
370 let current = yield* getByName(output?.name ?? name);
371
372 if (current === undefined) {
373 const created = yield* apigee
374 .createOrganizationsEnvironmentsSecurityActions({
375 parent,
376 securityActionId,
377 body: toBody(news, desiredDescription, securityActionId),
378 })
379 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
380 current = created ?? undefined;
381 }
382
383 if (current === undefined) {
384 return yield* new EnvironmentsSecurityActionNotResolved({ resourceName: name });
385 }
386
387 const descriptionChanged = !sameText(current.description, desiredDescription);
388 const stateChanged = !sameText(current.state, desiredState);
389 const conditionChanged =
390 jsonOf(conditionOf(current.conditionConfig)) !== jsonOf(news.conditionConfig);
391 const denyChanged = jsonOf(current.deny) !== jsonOf(news.deny);
392 const allowChanged = (current.allow !== undefined) !== (news.allow === true);
393 const flagChanged = jsonOf(current.flag) !== jsonOf(news.flag);
394 const expireChanged = !sameText(current.expireTime, news.expireTime);
395 const proxiesChanged = !sameList(current.apiProxies, news.apiProxies);
396
397 if (
398 descriptionChanged ||
399 stateChanged ||
400 conditionChanged ||
401 denyChanged ||
402 allowChanged ||
403 flagChanged ||
404 expireChanged ||
405 proxiesChanged
406 ) {
407 current = yield* apigee.patchOrganizationsEnvironmentsSecurityActions({
408 name,
409 updateMask: [
410 descriptionChanged ? "description" : undefined,
411 stateChanged ? "state" : undefined,
412 conditionChanged ? "condition_config" : undefined,
413 denyChanged ? "deny" : undefined,
414 allowChanged ? "allow" : undefined,
415 flagChanged ? "flag" : undefined,
416 expireChanged ? "expire_time" : undefined,
417 proxiesChanged ? "api_proxies" : undefined,
418 ]
419 .filter((field): field is string => field !== undefined)
420 .join(","),
421 body: toBody(news, desiredDescription, securityActionId),
422 });
423 }
424
425 return toAttrs(current, organizationId, environmentId);
426 }),
427
428 delete: Effect.fn(function* ({ output }) {
429 yield* apigee
430 .deleteOrganizationsEnvironmentsSecurityActions({ name: output.name })
431 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
432 }),
433 });