@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, 04:45 UTC

main
ts 604 lines 20.2 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
14 import type { Providers } from "../Providers.ts";
15 import { waitGlobalOperation } from "./operations.ts";
16
17 export interface FirewallRule {
18 /**
19 * IP protocol this rule matches. One of `tcp`, `udp`, `icmp`, `esp`,
20 * `ah`, `ipip`, `sctp`, or an IP protocol number.
21 */
22 protocol: string;
23 /**
24 * Destination ports or ranges (e.g. `"22"`, `"80"`, `"8000-8080"`).
25 * Only valid for `tcp` and `udp`. Omit to match every port.
26 */
27 ports?: string[];
28 }
29
30 export interface FirewallLogConfig {
31 /**
32 * Whether to export logs for this rule to Cloud Logging.
33 * @default false
34 */
35 enable?: boolean;
36 /**
37 * Whether log entries include metadata. Only set when `enable` is true.
38 */
39 metadata?: "EXCLUDE_ALL_METADATA" | "INCLUDE_ALL_METADATA";
40 }
41
42 export type FirewallProps = {
43 /**
44 * Firewall name. If omitted, a unique RFC1035 name is generated from the
45 * stack, stage, and logical id. Must be 1-63 characters and match
46 * `[a-z]([-a-z0-9]*[a-z0-9])?`. Changing the name replaces the rule.
47 */
48 firewallName?: string;
49 /**
50 * VPC network the rule belongs to. Accepts a name (`default`), a partial
51 * URL (`global/networks/default`), or a full URL. Immutable — changing it
52 * replaces the rule.
53 * @default "global/networks/default"
54 */
55 network?: string;
56 /**
57 * Human-readable description. Alchemy ownership markers are stored in
58 * this field (Compute firewalls have no labels) and stripped from
59 * attributes.
60 */
61 description?: string;
62 /**
63 * Priority in `[0, 65535]`. Lower values take precedence. DENY wins
64 * over ALLOW at the same priority.
65 * @default 1000
66 */
67 priority?: number;
68 /**
69 * Traffic direction. Immutable — changing it replaces the rule.
70 * @default "INGRESS"
71 */
72 direction?: "INGRESS" | "EGRESS";
73 /**
74 * When true, the rule exists but is not enforced.
75 * @default false
76 */
77 disabled?: boolean;
78 /**
79 * ALLOW match conditions. A rule must specify `allowed` or `denied`,
80 * not both. Switching action replaces the rule.
81 */
82 allowed?: FirewallRule[];
83 /**
84 * DENY match conditions. A rule must specify `allowed` or `denied`,
85 * not both. Switching action replaces the rule.
86 */
87 denied?: FirewallRule[];
88 /**
89 * Source CIDR ranges. For INGRESS, omit together with `sourceTags` and
90 * `sourceServiceAccounts` to match `0.0.0.0/0`.
91 */
92 sourceRanges?: string[];
93 /**
94 * Destination CIDR ranges.
95 */
96 destinationRanges?: string[];
97 /**
98 * Source network tags (INGRESS). Cannot be combined with service-account
99 * targeting.
100 */
101 sourceTags?: string[];
102 /**
103 * Target network tags. If omitted, the rule applies to every instance on
104 * the network.
105 */
106 targetTags?: string[];
107 /**
108 * Source service accounts (INGRESS). Cannot be combined with network tags.
109 */
110 sourceServiceAccounts?: string[];
111 /**
112 * Target service accounts. Cannot be combined with network tags.
113 */
114 targetServiceAccounts?: string[];
115 /**
116 * Firewall Rules Logging options.
117 */
118 logConfig?: FirewallLogConfig;
119 };
120
121 export type Firewall = Resource<
122 "GCP.Compute.Firewall",
123 FirewallProps,
124 {
125 /** Firewall name. */
126 firewallName: string;
127 /** Project id. */
128 project: string;
129 /** Network URL. */
130 network: string;
131 /** User description (ownership marker stripped). */
132 description: string | undefined;
133 /** Priority. */
134 priority: number;
135 /** `INGRESS` or `EGRESS`. */
136 direction: string;
137 /** Whether the rule is not enforced. */
138 disabled: boolean;
139 /** ALLOW match conditions. */
140 allowed: FirewallRule[];
141 /** DENY match conditions. */
142 denied: FirewallRule[];
143 /** Source CIDR ranges. */
144 sourceRanges: string[];
145 /** Destination CIDR ranges. */
146 destinationRanges: string[];
147 /** Source network tags. */
148 sourceTags: string[];
149 /** Target network tags. */
150 targetTags: string[];
151 /** Source service accounts. */
152 sourceServiceAccounts: string[];
153 /** Target service accounts. */
154 targetServiceAccounts: string[];
155 /** Logging options, if enabled. */
156 logConfig: FirewallLogConfig | undefined;
157 /** Server-assigned numeric id. */
158 id: string | undefined;
159 /** Server-defined URL. */
160 selfLink: string | undefined;
161 /** RFC3339 creation timestamp. */
162 creationTimestamp: string | undefined;
163 },
164 never,
165 Providers
166 >;
167
168 /**
169 * A VPC firewall rule that allows or denies ingress/egress traffic for
170 * instances on a network.
171 *
172 * Compute Engine firewalls have no resource labels. Alchemy stamps
173 * ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) into the
174 * description so `read` and `list` (and `pnpm nuke:gcp`) can find them.
175 *
176 * Name, network, direction, and allow-vs-deny are immutable — changing any
177 * of them replaces the rule.
178 *
179 * ### Creating a Firewall
180 * **Example:** Generated name, HTTP from a private range
181 * ```typescript
182 * const http = yield* GCP.Compute.Firewall("AllowHttp", {
183 * allowed: [{ protocol: "tcp", ports: ["80"] }],
184 * sourceRanges: ["10.0.0.0/8"],
185 * targetTags: ["web"],
186 * });
187 * ```
188 *
189 * **Example:** Explicit name, HTTPS deny, logging
190 * ```typescript
191 * const deny = yield* GCP.Compute.Firewall("DenyHttps", {
192 * firewallName: "deny-https-egress",
193 * direction: "EGRESS",
194 * denied: [{ protocol: "tcp", ports: ["443"] }],
195 * destinationRanges: ["0.0.0.0/0"],
196 * priority: 800,
197 * logConfig: { enable: true, metadata: "INCLUDE_ALL_METADATA" },
198 * });
199 * ```
200 *
201 * @resource
202 * @category Compute
203 */
204 export const Firewall = Resource<Firewall>("GCP.Compute.Firewall");
205
206 export class FirewallNotResolved extends Data.TaggedError("GCP.Compute.FirewallNotResolved")<{
207 firewallName: string;
208 }> {}
209
210 const DEFAULT_NETWORK = "global/networks/default";
211 const DEFAULT_DIRECTION = "INGRESS";
212 const DEFAULT_PRIORITY = 1000;
213 const OWNERSHIP_KEYS = ["alchemy-stack", "alchemy-stage", "alchemy-id"] as const;
214
215 const backoff = Schedule.min([
216 Schedule.exponential(Duration.millis(300), 1.5),
217 Schedule.spaced(Duration.seconds(2)),
218 ]);
219
220 const networkId = (network: string | undefined) => {
221 if (network === undefined || network.length === 0) return undefined;
222 const parts = network.split("/").filter((part) => part.length > 0);
223 return parts[parts.length - 1];
224 };
225
226 const toNetworkUrl = (network: string | undefined, project: string) => {
227 if (network === undefined || network.length === 0) {
228 return `projects/${project}/global/networks/default`;
229 }
230 if (network.includes("/")) return network;
231 return `projects/${project}/global/networks/${network}`;
232 };
233
234 const toName = (id: string, name: string | undefined, existing?: string) =>
235 Effect.gen(function* () {
236 if (name !== undefined) return name;
237 if (existing !== undefined) return existing;
238 const generated = yield* createPhysicalName({
239 id,
240 maxLength: 63,
241 lowercase: true,
242 });
243 const rfc = generated.replace(/^[^a-z]+/, "f").replace(/-+$/g, "");
244 return rfc.slice(0, 63);
245 });
246
247 const encodeDescription = (user: string | undefined, labels: Record<string, string>) => {
248 const marker = OWNERSHIP_KEYS.map((key) => `${key}=${labels[key] ?? ""}`).join(" ");
249 const trimmed = user?.trim() ?? "";
250 return trimmed.length > 0 ? `${marker}\n${trimmed}` : marker;
251 };
252
253 const parseDescription = (description: string | undefined) => {
254 if (description === undefined || description.length === 0) {
255 return { labels: {} as Record<string, string>, description: undefined };
256 }
257 const newline = description.indexOf("\n");
258 const first = newline === -1 ? description : description.slice(0, newline);
259 const rest = newline === -1 ? undefined : description.slice(newline + 1);
260 if (!first.includes("alchemy-id=") || !first.includes("alchemy-stack=")) {
261 return { labels: {} as Record<string, string>, description };
262 }
263 const labels: Record<string, string> = {};
264 for (const part of first.split(/\s+/)) {
265 const eq = part.indexOf("=");
266 if (eq > 0) labels[part.slice(0, eq)] = part.slice(eq + 1);
267 }
268 return {
269 labels,
270 description: rest && rest.length > 0 ? rest : undefined,
271 };
272 };
273
274 const hasAlchemyMarker = (description: string | undefined) =>
275 Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-"));
276
277 const toApiRules = (
278 rules: FirewallRule[] | undefined,
279 ): compute.FirewallAllowedItemList | undefined => {
280 if (rules === undefined || rules.length === 0) return undefined;
281 return rules.map((rule) => ({
282 IPProtocol: rule.protocol,
283 ports: rule.ports !== undefined && rule.ports.length > 0 ? rule.ports : undefined,
284 }));
285 };
286
287 const fromApiRules = (rules: compute.FirewallAllowedItemList | undefined): FirewallRule[] =>
288 (rules ?? []).flatMap((rule) =>
289 rule.IPProtocol
290 ? [
291 {
292 protocol: rule.IPProtocol,
293 ports: rule.ports,
294 },
295 ]
296 : [],
297 );
298
299 const toApiLogConfig = (
300 log: FirewallLogConfig | undefined,
301 ): compute.FirewallLogConfig | undefined => {
302 if (log === undefined || log.enable !== true) return undefined;
303 return {
304 enable: true,
305 metadata: log.metadata,
306 };
307 };
308
309 const fromApiLogConfig = (
310 log: compute.FirewallLogConfig | undefined,
311 ): FirewallLogConfig | undefined =>
312 log?.enable === true
313 ? {
314 enable: true,
315 metadata: log.metadata as FirewallLogConfig["metadata"],
316 }
317 : undefined;
318
319 const listsEqual = (left?: string[], right?: string[]) => {
320 const a = [...(left ?? [])].sort();
321 const b = [...(right ?? [])].sort();
322 return a.length === b.length && a.every((value, i) => value === b[i]);
323 };
324
325 const rulesEqual = (left?: FirewallRule[], right?: FirewallRule[]) => {
326 const canon = (rules?: FirewallRule[]) =>
327 JSON.stringify(
328 (rules ?? [])
329 .map((rule) => ({
330 protocol: rule.protocol.toLowerCase(),
331 ports: [...(rule.ports ?? [])].sort(),
332 }))
333 .sort(
334 (a, b) =>
335 a.protocol.localeCompare(b.protocol) ||
336 JSON.stringify(a.ports).localeCompare(JSON.stringify(b.ports)),
337 ),
338 );
339 return canon(left) === canon(right);
340 };
341
342 const logConfigEqual = (
343 left: FirewallLogConfig | undefined,
344 right: FirewallLogConfig | undefined,
345 ) =>
346 (left?.enable === true) === (right?.enable === true) &&
347 (left?.enable === true ? left.metadata : undefined) ===
348 (right?.enable === true ? right.metadata : undefined);
349
350 type FirewallAction = "allow" | "deny";
351
352 const actionOf = (
353 props:
354 | {
355 allowed?: unknown[];
356 denied?: unknown[];
357 }
358 | undefined,
359 ): FirewallAction | undefined => {
360 if (props === undefined) return undefined;
361 if (props.denied !== undefined && props.denied.length > 0) return "deny";
362 if (props.allowed !== undefined && props.allowed.length > 0) return "allow";
363 return undefined;
364 };
365
366 const toAttrs = (firewall: compute.Firewall, project: string) => ({
367 firewallName: firewall.name ?? firewall.id ?? "",
368 project,
369 network: firewall.network ?? "",
370 description: parseDescription(firewall.description).description,
371 priority: firewall.priority ?? DEFAULT_PRIORITY,
372 direction: (firewall.direction ?? DEFAULT_DIRECTION).toUpperCase(),
373 disabled: firewall.disabled === true,
374 allowed: fromApiRules(firewall.allowed),
375 denied: fromApiRules(firewall.denied),
376 sourceRanges: firewall.sourceRanges ?? [],
377 destinationRanges: firewall.destinationRanges ?? [],
378 sourceTags: firewall.sourceTags ?? [],
379 targetTags: firewall.targetTags ?? [],
380 sourceServiceAccounts: firewall.sourceServiceAccounts ?? [],
381 targetServiceAccounts: firewall.targetServiceAccounts ?? [],
382 logConfig: fromApiLogConfig(firewall.logConfig),
383 id: firewall.id,
384 selfLink: firewall.selfLink,
385 creationTimestamp: firewall.creationTimestamp,
386 });
387
388 const getByName = (project: string, firewall: string) =>
389 compute
390 .getFirewalls({ project, firewall })
391 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
392
393 const insertBody = (
394 firewallName: string,
395 project: string,
396 news: FirewallProps,
397 description: string,
398 ): compute.Firewall => ({
399 name: firewallName,
400 network: toNetworkUrl(news.network, project),
401 description,
402 priority: news.priority ?? DEFAULT_PRIORITY,
403 direction: (news.direction ?? DEFAULT_DIRECTION).toUpperCase(),
404 disabled: news.disabled === true,
405 allowed: toApiRules(news.allowed),
406 denied: toApiRules(news.denied),
407 sourceRanges: news.sourceRanges,
408 destinationRanges: news.destinationRanges,
409 sourceTags: news.sourceTags,
410 targetTags: news.targetTags,
411 sourceServiceAccounts: news.sourceServiceAccounts,
412 targetServiceAccounts: news.targetServiceAccounts,
413 logConfig: toApiLogConfig(news.logConfig),
414 });
415
416 export const FirewallProvider = () =>
417 Provider.succeed(Firewall, {
418 stables: [
419 "firewallName",
420 "project",
421 "network",
422 "direction",
423 "id",
424 "selfLink",
425 "creationTimestamp",
426 ],
427
428 diff: Effect.fn(function* ({ news, olds, output }) {
429 if (!isResolved(news)) return undefined;
430 const prevName = olds?.firewallName ?? output?.firewallName;
431 const nextName = news.firewallName ?? prevName;
432 const nameChanged = prevName !== undefined && nextName !== undefined && prevName !== nextName;
433
434 const prevNetwork = networkId(olds?.network ?? output?.network);
435 const nextNetwork = networkId(news.network ?? prevNetwork ?? DEFAULT_NETWORK);
436 const networkChanged =
437 prevNetwork !== undefined && nextNetwork !== undefined && prevNetwork !== nextNetwork;
438
439 const prevDir = (olds?.direction ?? output?.direction)?.toUpperCase();
440 const nextDir = (news.direction ?? prevDir ?? DEFAULT_DIRECTION).toUpperCase();
441 const directionChanged = prevDir !== undefined && prevDir !== nextDir;
442
443 const prevAction = actionOf(olds) ?? actionOf(output);
444 const nextAction = actionOf(news);
445 const actionChanged =
446 prevAction !== undefined && nextAction !== undefined && prevAction !== nextAction;
447
448 if (nameChanged || networkChanged || directionChanged || actionChanged) {
449 return {
450 action: "replace" as const,
451 deleteFirst: !nameChanged,
452 };
453 }
454 return undefined;
455 }),
456
457 read: Effect.fn(function* ({ id, olds, output }) {
458 const env = yield* GcpEnvironment.current;
459 const firewallName = yield* toName(id, olds?.firewallName, output?.firewallName);
460 const existing = yield* getByName(env.project, firewallName);
461 if (existing === undefined) return undefined;
462 const attrs = toAttrs(existing, env.project);
463 return (yield* hasAlchemyLabels(id, parseDescription(existing.description).labels))
464 ? attrs
465 : Unowned(attrs);
466 }),
467
468 list: () =>
469 Effect.gen(function* () {
470 const env = yield* GcpEnvironment.current;
471 return yield* compute.listFirewalls.items({ project: env.project }).pipe(
472 Stream.filter((firewall) => hasAlchemyMarker(firewall.description)),
473 Stream.map((firewall) => toAttrs(firewall, env.project)),
474 Stream.runCollect,
475 Effect.map((chunk) => Array.from(chunk)),
476 );
477 }),
478
479 reconcile: Effect.fn(function* ({ id, news, output }) {
480 const env = yield* GcpEnvironment.current;
481 const firewallName = yield* toName(id, news.firewallName, output?.firewallName);
482 const desiredLabels = yield* createInternalLabels(id);
483 const desiredDescription = encodeDescription(news.description, desiredLabels);
484 const desiredPriority = news.priority ?? DEFAULT_PRIORITY;
485 const desiredDisabled = news.disabled === true;
486 const desiredAllowed = news.allowed ?? [];
487 const desiredDenied = news.denied ?? [];
488 const desiredSourceRanges = news.sourceRanges ?? [];
489 const desiredDestinationRanges = news.destinationRanges ?? [];
490 const desiredSourceTags = news.sourceTags ?? [];
491 const desiredTargetTags = news.targetTags ?? [];
492 const desiredSourceServiceAccounts = news.sourceServiceAccounts ?? [];
493 const desiredTargetServiceAccounts = news.targetServiceAccounts ?? [];
494 const desiredLogConfig = toApiLogConfig(news.logConfig);
495
496 let current = yield* getByName(env.project, firewallName);
497
498 if (current === undefined) {
499 yield* compute
500 .insertFirewalls({
501 project: env.project,
502 body: insertBody(firewallName, env.project, news, desiredDescription),
503 })
504 .pipe(
505 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
506 Effect.catchTag("Conflict", () => Effect.void),
507 );
508 current = yield* getByName(env.project, firewallName).pipe(
509 Effect.flatMap((firewall) =>
510 firewall !== undefined
511 ? Effect.succeed(firewall)
512 : Effect.fail(new FirewallNotResolved({ firewallName })),
513 ),
514 Effect.retry({
515 while: (error) => error._tag === "GCP.Compute.FirewallNotResolved",
516 times: 8,
517 schedule: backoff,
518 }),
519 Effect.catchTag("GCP.Compute.FirewallNotResolved", () => Effect.undefined),
520 );
521 }
522
523 if (current === undefined) {
524 return yield* new FirewallNotResolved({ firewallName });
525 }
526
527 const observed = toAttrs(current, env.project);
528 const patch: compute.Firewall = {};
529
530 if ((current.description ?? "") !== desiredDescription) {
531 patch.description = desiredDescription;
532 }
533 if (observed.priority !== desiredPriority) {
534 patch.priority = desiredPriority;
535 }
536 if (observed.disabled !== desiredDisabled) {
537 patch.disabled = desiredDisabled;
538 }
539 if (!rulesEqual(observed.allowed, desiredAllowed)) {
540 patch.allowed = toApiRules(desiredAllowed) ?? [];
541 }
542 if (!rulesEqual(observed.denied, desiredDenied)) {
543 patch.denied = toApiRules(desiredDenied) ?? [];
544 }
545 if (!listsEqual(observed.sourceRanges, desiredSourceRanges)) {
546 patch.sourceRanges = desiredSourceRanges;
547 }
548 if (!listsEqual(observed.destinationRanges, desiredDestinationRanges)) {
549 patch.destinationRanges = desiredDestinationRanges;
550 }
551 if (!listsEqual(observed.sourceTags, desiredSourceTags)) {
552 patch.sourceTags = desiredSourceTags;
553 }
554 if (!listsEqual(observed.targetTags, desiredTargetTags)) {
555 patch.targetTags = desiredTargetTags;
556 }
557 if (!listsEqual(observed.sourceServiceAccounts, desiredSourceServiceAccounts)) {
558 patch.sourceServiceAccounts = desiredSourceServiceAccounts;
559 }
560 if (!listsEqual(observed.targetServiceAccounts, desiredTargetServiceAccounts)) {
561 patch.targetServiceAccounts = desiredTargetServiceAccounts;
562 }
563 if (!logConfigEqual(observed.logConfig, fromApiLogConfig(desiredLogConfig))) {
564 patch.logConfig = desiredLogConfig ?? { enable: false };
565 }
566
567 if (Object.keys(patch).length > 0) {
568 yield* compute
569 .patchFirewalls({
570 project: env.project,
571 firewall: firewallName,
572 body: patch,
573 })
574 .pipe(
575 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
576 Effect.retry({
577 while: (error) => error._tag === "Conflict",
578 times: 5,
579 schedule: backoff,
580 }),
581 );
582 current = (yield* getByName(env.project, firewallName)) ?? current;
583 }
584
585 return toAttrs(current, env.project);
586 }),
587
588 delete: Effect.fn(function* ({ output }) {
589 const env = yield* GcpEnvironment.current;
590 yield* compute
591 .deleteFirewalls({
592 project: env.project,
593 firewall: output.firewallName,
594 })
595 .pipe(
596 Effect.flatMap((operation) =>
597 waitGlobalOperation(env.project, operation, {
598 ignore: ["RESOURCE_NOT_FOUND"],
599 }),
600 ),
601 Effect.catchTag("NotFound", () => Effect.void),
602 );
603 }),
604 });