@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 356 lines 11.9 KB
Raw
1 import * as networksecurity from "@distilled.cloud/gcp/networksecurity_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 Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 normalizeLocation,
15 projectParent,
16 parseResourceName,
17 ResourceNotResolved,
18 sameJson,
19 toPhysicalId,
20 userLabels,
21 waitForOperation,
22 waitUntilExists,
23 waitUntilGone,
24 } from "./operations.ts";
25
26 const DEFAULT_ACTION = "ALLOW" satisfies networksecurity.AuthorizationPolicyActionEnum;
27
28 export type AuthorizationPolicyAction =
29 | networksecurity.AuthorizationPolicyActionEnum
30 | (string & {});
31
32 export type AuthorizationPolicySource = {
33 /** Peer identities to match (exact, prefix, suffix, or `*`). */
34 principals?: string[];
35 /** Source IP CIDR ranges. */
36 ipBlocks?: string[];
37 };
38
39 export type AuthorizationPolicyHttpHeaderMatch = {
40 /** Regular expression matched against the header value. */
41 regexMatch?: string;
42 /** HTTP header name (`:authority`, `:method`, `Host`, …). */
43 headerName?: string;
44 };
45
46 export type AuthorizationPolicyDestination = {
47 /** Host names matched against the `:authority` header. */
48 hosts?: string[];
49 /** Destination ports. */
50 ports?: number[];
51 /** HTTP methods. Must be omitted for gRPC. */
52 methods?: string[];
53 /** Optional HTTP header match. */
54 httpHeaderMatch?: AuthorizationPolicyHttpHeaderMatch;
55 };
56
57 export type AuthorizationPolicyRule = {
58 /** Source matchers. All sources must match. */
59 sources?: AuthorizationPolicySource[];
60 /** Destination matchers. All destinations must match. */
61 destinations?: AuthorizationPolicyDestination[];
62 };
63
64 export type AuthorizationPolicyProps = {
65 /**
66 * Authorization policy id. If omitted, a unique RFC1035 name is
67 * generated from the stack, stage, and logical id. Immutable —
68 * changing it replaces the policy.
69 */
70 authorizationPolicyId?: string;
71 /**
72 * Location (`global`, `us-central1`, …). Immutable — changing it
73 * replaces the policy.
74 * @default "global"
75 */
76 location?: string;
77 /**
78 * Action taken when a rule matches.
79 * @default "ALLOW"
80 */
81 action?: AuthorizationPolicyAction;
82 /**
83 * Match rules. At least one rule must match for `action` to apply. An
84 * empty list applies `action` to every request.
85 */
86 rules?: AuthorizationPolicyRule[];
87 /**
88 * Human-readable description.
89 */
90 description?: string;
91 /**
92 * User labels. Alchemy ownership labels are merged in automatically.
93 */
94 labels?: Record<string, string>;
95 };
96
97 export type AuthorizationPolicy = Resource<
98 "GCP.NetworkSecurity.AuthorizationPolicy",
99 AuthorizationPolicyProps,
100 {
101 /** Full resource name `projects/{project}/locations/{location}/authorizationPolicies/{authorizationPolicy}`. */
102 name: string;
103 /** Authorization policy id (last path segment). */
104 authorizationPolicyId: string;
105 /** Project id. */
106 project: string;
107 /** Location id. */
108 location: string;
109 /** Action (`ALLOW` or `DENY`). */
110 action: string;
111 /** Match rules. */
112 rules: AuthorizationPolicyRule[];
113 /** User-provided description. */
114 description: string | undefined;
115 /** User labels (Alchemy ownership labels stripped). */
116 labels: Record<string, string>;
117 /** RFC3339 creation timestamp. */
118 createTime: string | undefined;
119 /** RFC3339 last-update timestamp. */
120 updateTime: string | undefined;
121 },
122 never,
123 Providers
124 >;
125
126 /**
127 * A Network Security authorization policy for Traffic Director /
128 * endpoint-config selectors.
129 *
130 * Changing `authorizationPolicyId` or `location` replaces the policy.
131 * Action, rules, description, and labels update in place. Attach the
132 * policy to a target HTTPS proxy or endpoint config selector to enforce
133 * it.
134 *
135 * ### Creating an Authorization Policy
136 * **Example:** Allow all
137 * ```typescript
138 * const policy = yield* GCP.NetworkSecurity.AuthorizationPolicy("Allow", {
139 * action: "ALLOW",
140 * });
141 * ```
142 *
143 * **Example:** Allow specific hosts
144 * ```typescript
145 * const policy = yield* GCP.NetworkSecurity.AuthorizationPolicy("Allow", {
146 * action: "ALLOW",
147 * rules: [
148 * {
149 * destinations: [{ hosts: ["api.example.com"], ports: [443] }],
150 * },
151 * ],
152 * labels: { env: "prod" },
153 * });
154 * ```
155 *
156 * @resource
157 * @category NetworkSecurity
158 */
159 export const AuthorizationPolicy = Resource<AuthorizationPolicy>(
160 "GCP.NetworkSecurity.AuthorizationPolicy",
161 );
162
163 const resourceName = (project: string, location: string, authorizationPolicyId: string) =>
164 `projects/${project}/locations/${location}/authorizationPolicies/${authorizationPolicyId}`;
165
166 const actionOf = (value: string | undefined) => (value ?? DEFAULT_ACTION).toUpperCase();
167
168 const toRules = (
169 rules: networksecurity.RuleList | AuthorizationPolicyRule[] | undefined,
170 ): AuthorizationPolicyRule[] =>
171 (rules ?? []).map((rule) => ({
172 sources: rule.sources,
173 destinations: rule.destinations,
174 }));
175
176 const toAttrs = (policy: networksecurity.AuthorizationPolicy, project: string) => {
177 const name = policy.name ?? "";
178 const parsed = parseResourceName(name);
179 return {
180 name,
181 authorizationPolicyId: parsed.id,
182 project: parsed.parentId || project,
183 location: parsed.location,
184 action: policy.action ?? DEFAULT_ACTION,
185 rules: toRules(policy.rules),
186 description: policy.description,
187 labels: userLabels(policy.labels),
188 createTime: policy.createTime,
189 updateTime: policy.updateTime,
190 };
191 };
192
193 const getByName = (name: string) =>
194 networksecurity
195 .getProjectsLocationsAuthorizationPolicies({ name })
196 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
197
198 const listOwned = (project: string) =>
199 networksecurity.listProjectsLocationsAuthorizationPolicies
200 .pages({
201 parent: projectParent(project, "-"),
202 pageSize: 1000,
203 })
204 .pipe(
205 Stream.flatMap((page) => Stream.fromIterable(page.authorizationPolicies ?? [])),
206 Stream.filter((policy) =>
207 Object.keys(policy.labels ?? {}).some((key) => key.startsWith("alchemy-")),
208 ),
209 Stream.map((policy) => toAttrs(policy, project)),
210 Stream.runCollect,
211 Effect.map((chunk) => Array.from(chunk)),
212 Effect.catchTag("NotFound", () => Effect.succeed([])),
213 );
214
215 export const AuthorizationPolicyProvider = () =>
216 Provider.succeed(AuthorizationPolicy, {
217 stables: ["name", "authorizationPolicyId", "project", "location", "createTime"],
218
219 diff: Effect.fn(function* ({ news, olds, output }) {
220 if (!isResolved(news)) return undefined;
221 const previousId = olds?.authorizationPolicyId ?? output?.authorizationPolicyId;
222 const nextId = news.authorizationPolicyId ?? previousId;
223 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
224 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
225 const replace =
226 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
227 previousLocation !== nextLocation;
228 if (!replace) return undefined;
229 return {
230 action: "replace" as const,
231 deleteFirst:
232 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
233 };
234 }),
235
236 read: Effect.fn(function* ({ id, olds, output }) {
237 const env = yield* GcpEnvironment.current;
238 const authorizationPolicyId = yield* toPhysicalId(
239 id,
240 olds?.authorizationPolicyId,
241 output?.authorizationPolicyId,
242 "authzpolicy",
243 );
244 const location = normalizeLocation(olds?.location ?? output?.location);
245 const name = output?.name ?? resourceName(env.project, location, authorizationPolicyId);
246 const existing = yield* getByName(name);
247 if (existing === undefined) return undefined;
248 const attrs = toAttrs(existing, env.project);
249 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
250 }),
251
252 list: () =>
253 Effect.gen(function* () {
254 const env = yield* GcpEnvironment.current;
255 return yield* listOwned(env.project);
256 }),
257
258 reconcile: Effect.fn(function* ({ id, news, output }) {
259 const env = yield* GcpEnvironment.current;
260 const authorizationPolicyId = yield* toPhysicalId(
261 id,
262 news.authorizationPolicyId,
263 output?.authorizationPolicyId,
264 "authzpolicy",
265 );
266 const location = normalizeLocation(news.location ?? output?.location);
267 const name = resourceName(env.project, location, authorizationPolicyId);
268 const action = actionOf(news.action);
269 const rules = news.rules;
270 const desiredLabels = {
271 ...toLabels(news.labels),
272 ...(yield* createInternalLabels(id)),
273 };
274
275 let current = yield* getByName(name);
276
277 if (current === undefined) {
278 const created = yield* networksecurity
279 .createProjectsLocationsAuthorizationPolicies({
280 parent: projectParent(env.project, location),
281 authorizationPolicyId,
282 body: {
283 action,
284 rules,
285 description: news.description,
286 labels: desiredLabels,
287 },
288 })
289 .pipe(
290 Effect.retry({
291 while: (error) => error._tag === "Conflict",
292 times: 5,
293 schedule: Schedule.spaced("2 seconds"),
294 }),
295 Effect.catchTag("Conflict", () => Effect.undefined),
296 );
297 if (created !== undefined) {
298 yield* waitForOperation(created);
299 }
300 current = yield* waitUntilExists(getByName(name), name);
301 }
302
303 if (current === undefined) {
304 return yield* new ResourceNotResolved({ resourceName: name });
305 }
306
307 const observedLabels = tagRecord(current.labels);
308 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
309 const labelsChanged = upsert.length > 0 || removed.length > 0;
310 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
311 const actionChanged = actionOf(current.action) !== action;
312 const rulesChanged = !sameJson(toRules(current.rules), toRules(rules));
313
314 if (labelsChanged || descriptionChanged || actionChanged || rulesChanged) {
315 const updateMask = [
316 labelsChanged ? "labels" : undefined,
317 descriptionChanged ? "description" : undefined,
318 actionChanged ? "action" : undefined,
319 rulesChanged ? "rules" : undefined,
320 ].filter((field): field is string => field !== undefined);
321
322 const operation = yield* networksecurity.patchProjectsLocationsAuthorizationPolicies({
323 name: current.name ?? name,
324 updateMask: updateMask.join(","),
325 body: {
326 name: current.name ?? name,
327 labels: desiredLabels,
328 description: news.description,
329 action,
330 rules,
331 },
332 });
333 yield* waitForOperation(operation);
334 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
335 }
336
337 return toAttrs(current, env.project);
338 }),
339
340 delete: Effect.fn(function* ({ output }) {
341 const operation = yield* networksecurity
342 .deleteProjectsLocationsAuthorizationPolicies({ name: output.name })
343 .pipe(
344 Effect.retry({
345 while: (error) => error._tag === "Conflict",
346 times: 8,
347 schedule: Schedule.spaced("2 seconds"),
348 }),
349 Effect.catchTag("NotFound", () => Effect.undefined),
350 );
351 if (operation !== undefined) {
352 yield* waitForOperation(operation, { notFoundOk: true });
353 }
354 yield* waitUntilGone(getByName(output.name), output.name);
355 }),
356 });