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

main
ts 456 lines 15 KB
Raw
1 import * as vmwareengine from "@distilled.cloud/gcp/vmwareengine_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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 VmwareengineNotResolved,
12 changedFields,
13 collectPages,
14 createInternalLabels,
15 encodeOwnership,
16 expandName,
17 hasAlchemyLabels,
18 hasOwnershipMarker,
19 listAcrossLocations,
20 locationFromName,
21 normalizeLocation,
22 parseName,
23 parseOwnership,
24 replaceOnIdentity,
25 rfc1035,
26 sameJson,
27 toPhysicalId,
28 waitForOperation,
29 waitUntilGone,
30 waitUntilPresent,
31 waitUntilReady,
32 } from "./internal.ts";
33
34 const COLLECTION = "externalAccessRules";
35 const PARENT_COLLECTION = "networkPolicies";
36
37 export type IpRange = {
38 /** A single IP address (`10.0.0.5`). */
39 ipAddress?: string;
40 /** A CIDR range (`10.0.0.0/24`). */
41 ipAddressRange?: string;
42 /**
43 * ExternalAddress resource name reserved in the parent network policy
44 * scope.
45 */
46 externalAddress?: string;
47 };
48
49 export type ExternalAccessRuleAction = vmwareengine.ExternalAccessRuleActionEnum | (string & {});
50
51 export type NetworkPoliciesExternalAccessRuleProps = {
52 /**
53 * Parent NetworkPolicy resource name
54 * (`projects/{project}/locations/{location}/networkPolicies/{networkPolicy}`)
55 * or the policy id. Immutable — changing it replaces the rule.
56 */
57 networkPolicy: string;
58 /**
59 * Rule id (the `{externalAccessRule}` segment of
60 * `.../networkPolicies/{networkPolicy}/externalAccessRules/{externalAccessRule}`).
61 * If omitted, a unique RFC1035 name is generated. Immutable.
62 */
63 externalAccessRuleId?: string;
64 /**
65 * Region of the parent policy. Inferred from `networkPolicy` when that
66 * value is a full resource name. Immutable.
67 * @default the stack's GCP region (`GCP.Region`, else the profile
68 * region, else `us-central1`)
69 */
70 location?: string;
71 /**
72 * Rule priority (`100`–`4096`). Lower integers take precedence.
73 * @default 1000
74 */
75 priority?: number;
76 /**
77 * Action (`ALLOW` or `DENY`).
78 * @default "ALLOW"
79 */
80 action?: ExternalAccessRuleAction;
81 /**
82 * IP protocol (`tcp`, `udp`, or `icmp`).
83 * @default "tcp"
84 */
85 ipProtocol?: string;
86 /**
87 * Source IP ranges. Use `0.0.0.0/0` to match all sources.
88 */
89 sourceIpRanges?: IpRange[];
90 /**
91 * Source ports (`["22"]`, `["80","443"]`, `["12345-12349"]`). Use
92 * `["0-65535"]` to match all. TCP/UDP only.
93 */
94 sourcePorts?: string[];
95 /**
96 * Destination IP ranges. Must be reserved external IPs in the parent
97 * policy, or `0.0.0.0/0` for all.
98 */
99 destinationIpRanges?: IpRange[];
100 /**
101 * Destination ports. TCP/UDP only.
102 */
103 destinationPorts?: string[];
104 /**
105 * Human-readable description. Rules have no labels field, so Alchemy
106 * stamps ownership into a `[alchemy …]` prefix and strips it from
107 * attributes.
108 */
109 description?: string;
110 };
111
112 export type NetworkPoliciesExternalAccessRule = Resource<
113 "GCP.VMwareEngine.NetworkPoliciesExternalAccessRule",
114 NetworkPoliciesExternalAccessRuleProps,
115 {
116 /** Full resource name. */
117 name: string;
118 /** Rule id (last path segment). */
119 externalAccessRuleId: string;
120 /** Parent NetworkPolicy resource name. */
121 networkPolicy: string;
122 /** Project id. */
123 project: string;
124 /** Location id. */
125 location: string;
126 /** Rule priority. */
127 priority: number | undefined;
128 /** Action (`ALLOW` or `DENY`). */
129 action: string | undefined;
130 /** IP protocol. */
131 ipProtocol: string | undefined;
132 /** Source IP ranges. */
133 sourceIpRanges: IpRange[];
134 /** Source ports. */
135 sourcePorts: string[];
136 /** Destination IP ranges. */
137 destinationIpRanges: IpRange[];
138 /** Destination ports. */
139 destinationPorts: string[];
140 /** User description with the Alchemy ownership prefix stripped. */
141 description: string | undefined;
142 /** Server-reported state. */
143 state: string | undefined;
144 /** System-generated unique identifier. */
145 uid: string | undefined;
146 /** RFC3339 creation timestamp. */
147 createTime: string | undefined;
148 /** RFC3339 last-update timestamp. */
149 updateTime: string | undefined;
150 },
151 never,
152 Providers
153 >;
154
155 /**
156 * An inbound firewall rule on a VMware Engine network policy that filters
157 * traffic destined to ExternalAddress resources.
158 *
159 * Rules have no labels field, so Alchemy stamps ownership into the
160 * description for `list` / nuke. Changing the parent policy, rule id, or
161 * location replaces the rule. Priority, action, protocol, ranges, ports,
162 * and description update in place.
163 *
164 * ### Creating a NetworkPoliciesExternalAccessRule
165 * **Example:** Allow HTTPS from anywhere
166 * ```typescript
167 * const rule = yield* GCP.VMwareEngine.NetworkPoliciesExternalAccessRule(
168 * "Https",
169 * {
170 * networkPolicy: policy.name,
171 * action: "ALLOW",
172 * ipProtocol: "tcp",
173 * priority: 1000,
174 * sourceIpRanges: [{ ipAddressRange: "0.0.0.0/0" }],
175 * sourcePorts: ["0-65535"],
176 * destinationIpRanges: [{ ipAddressRange: "0.0.0.0/0" }],
177 * destinationPorts: ["443"],
178 * description: "allow https",
179 * },
180 * );
181 * ```
182 *
183 * @resource
184 * @category VMwareEngine
185 */
186 export const NetworkPoliciesExternalAccessRule = Resource<NetworkPoliciesExternalAccessRule>(
187 "GCP.VMwareEngine.NetworkPoliciesExternalAccessRule",
188 );
189
190 const parentPolicyName = (project: string, location: string, networkPolicy: string) =>
191 expandName(networkPolicy, project, location, PARENT_COLLECTION);
192
193 const resourceNameOf = (parent: string, ruleId: string) => `${parent}/${COLLECTION}/${ruleId}`;
194
195 const ipRangesOf = (
196 values: readonly vmwareengine.IpRange[] | readonly IpRange[] | undefined,
197 ): IpRange[] =>
198 (values ?? []).map((range) => ({
199 ipAddress: range.ipAddress,
200 ipAddressRange: range.ipAddressRange,
201 externalAddress: range.externalAddress,
202 }));
203
204 const toAttrs = (item: vmwareengine.ExternalAccessRule, project: string, region: string) => {
205 const name = item.name ?? "";
206 const parsed = parseName(name, COLLECTION, region);
207 const ownership = parseOwnership(item.description);
208 return {
209 name,
210 externalAccessRuleId: parsed.id,
211 networkPolicy: parsed.parent,
212 project: parsed.project || project,
213 location: parsed.location,
214 priority: item.priority,
215 action: item.action,
216 ipProtocol: item.ipProtocol,
217 sourceIpRanges: ipRangesOf(item.sourceIpRanges),
218 sourcePorts: item.sourcePorts ?? [],
219 destinationIpRanges: ipRangesOf(item.destinationIpRanges),
220 destinationPorts: item.destinationPorts ?? [],
221 description: ownership.text,
222 state: item.state,
223 uid: item.uid,
224 createTime: item.createTime,
225 updateTime: item.updateTime,
226 };
227 };
228
229 const getByName = (name: string) =>
230 vmwareengine
231 .getProjectsLocationsNetworkPoliciesExternalAccessRules({ name })
232 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
233
234 export const NetworkPoliciesExternalAccessRuleProvider = () =>
235 Provider.succeed(NetworkPoliciesExternalAccessRule, {
236 stables: [
237 "name",
238 "externalAccessRuleId",
239 "networkPolicy",
240 "project",
241 "location",
242 "uid",
243 "createTime",
244 ],
245
246 diff: Effect.fn(function* ({ news, olds, output }) {
247 if (!isResolved(news)) return undefined;
248 const env = yield* GcpEnvironment.current;
249 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
250 return replaceOnIdentity({
251 previousId: olds?.externalAccessRuleId ?? output?.externalAccessRuleId,
252 nextId: news.externalAccessRuleId
253 ? rfc1035(news.externalAccessRuleId, "rule")
254 : (olds?.externalAccessRuleId ?? output?.externalAccessRuleId),
255 previousLocation,
256 nextLocation: normalizeLocation(
257 news.location ?? locationFromName(news.networkPolicy, previousLocation),
258 env.region,
259 ),
260 previousParent: olds?.networkPolicy ?? output?.networkPolicy,
261 nextParent: news.networkPolicy,
262 });
263 }),
264
265 read: Effect.fn(function* ({ id, olds, output }) {
266 const env = yield* GcpEnvironment.current;
267 const location = normalizeLocation(
268 olds?.location ??
269 output?.location ??
270 (olds?.networkPolicy ? locationFromName(olds.networkPolicy, env.region) : undefined),
271 env.region,
272 );
273 const parent = parentPolicyName(
274 env.project,
275 location,
276 olds?.networkPolicy ?? output?.networkPolicy ?? "",
277 );
278 const ruleId = yield* toPhysicalId(
279 id,
280 olds?.externalAccessRuleId,
281 output?.externalAccessRuleId,
282 "rule",
283 );
284 const name = output?.name ?? resourceNameOf(parent, ruleId);
285 const existing = yield* getByName(name);
286 if (existing === undefined) return undefined;
287 const attrs = toAttrs(existing, env.project, env.region);
288 const { labels } = parseOwnership(existing.description);
289 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
290 }),
291
292 list: () =>
293 Effect.gen(function* () {
294 const env = yield* GcpEnvironment.current;
295 const policies = yield* listAcrossLocations(env.project, env.region, (parent) =>
296 collectPages(
297 vmwareengine.listProjectsLocationsNetworkPolicies.pages({
298 parent,
299 pageSize: 1000,
300 }),
301 (page) => page.networkPolicies,
302 ),
303 );
304 const nested = yield* Effect.forEach(
305 policies.filter((policy) => (policy.name ?? "").length > 0),
306 (policy) =>
307 collectPages(
308 vmwareengine.listProjectsLocationsNetworkPoliciesExternalAccessRules.pages({
309 parent: policy.name ?? "",
310 pageSize: 1000,
311 }),
312 (page) => page.externalAccessRules,
313 ),
314 { concurrency: 4 },
315 );
316 return nested
317 .flat()
318 .filter((item) => hasOwnershipMarker(item.description))
319 .map((item) => toAttrs(item, env.project, env.region));
320 }),
321
322 reconcile: Effect.fn(function* ({ id, news, output }) {
323 const env = yield* GcpEnvironment.current;
324 const location = normalizeLocation(
325 news.location ?? output?.location ?? locationFromName(news.networkPolicy, env.region),
326 env.region,
327 );
328 const parent = parentPolicyName(env.project, location, news.networkPolicy);
329 const ruleId = yield* toPhysicalId(
330 id,
331 news.externalAccessRuleId,
332 output?.externalAccessRuleId,
333 "rule",
334 );
335 const name = resourceNameOf(parent, ruleId);
336 const ownership = yield* createInternalLabels(id);
337 const desiredDescription = encodeOwnership(ownership, news.description);
338 const priority = news.priority ?? 1000;
339 const action = news.action ?? "ALLOW";
340 const ipProtocol = news.ipProtocol ?? "tcp";
341 const sourceIpRanges = news.sourceIpRanges ?? [{ ipAddressRange: "0.0.0.0/0" }];
342 const destinationIpRanges = news.destinationIpRanges ?? [{ ipAddressRange: "0.0.0.0/0" }];
343 const sourcePorts = news.sourcePorts ?? ["0-65535"];
344 const destinationPorts = news.destinationPorts ?? ["0-65535"];
345
346 let current = yield* getByName(output?.name ?? name);
347
348 if (current === undefined) {
349 const created = yield* vmwareengine
350 .createProjectsLocationsNetworkPoliciesExternalAccessRules({
351 parent,
352 externalAccessRuleId: ruleId,
353 body: {
354 priority,
355 action,
356 ipProtocol,
357 sourceIpRanges,
358 destinationIpRanges,
359 sourcePorts,
360 destinationPorts,
361 description: desiredDescription,
362 },
363 })
364 .pipe(
365 Effect.retry({
366 while: (error) => error._tag === "Conflict",
367 times: 5,
368 schedule: Schedule.spaced("2 seconds"),
369 }),
370 Effect.catchTag("Conflict", () => Effect.undefined),
371 );
372 if (created !== undefined) {
373 yield* waitForOperation(created);
374 }
375 current = yield* waitUntilPresent(getByName(name), name);
376 }
377
378 if (current === undefined) {
379 return yield* new VmwareengineNotResolved({ resourceName: name });
380 }
381
382 current = yield* waitUntilReady(
383 getByName(current.name ?? name),
384 current.name ?? name,
385 (item) => item.state,
386 );
387
388 const descriptionChanged = (current.description ?? "") !== desiredDescription;
389 const priorityChanged = (current.priority ?? 0) !== priority;
390 const actionChanged = (current.action ?? "") !== action;
391 const protocolChanged = (current.ipProtocol ?? "") !== ipProtocol;
392 const sourceRangesChanged = !sameJson(ipRangesOf(current.sourceIpRanges), sourceIpRanges);
393 const destRangesChanged = !sameJson(
394 ipRangesOf(current.destinationIpRanges),
395 destinationIpRanges,
396 );
397 const sourcePortsChanged = !sameJson(current.sourcePorts, sourcePorts);
398 const destPortsChanged = !sameJson(current.destinationPorts, destinationPorts);
399 const updateMask = changedFields([
400 ["description", descriptionChanged],
401 ["priority", priorityChanged],
402 ["action", actionChanged],
403 ["ipProtocol", protocolChanged],
404 ["sourceIpRanges", sourceRangesChanged],
405 ["destinationIpRanges", destRangesChanged],
406 ["sourcePorts", sourcePortsChanged],
407 ["destinationPorts", destPortsChanged],
408 ]);
409
410 if (updateMask.length > 0) {
411 const operation =
412 yield* vmwareengine.patchProjectsLocationsNetworkPoliciesExternalAccessRules({
413 name: current.name ?? name,
414 updateMask: updateMask.join(","),
415 body: {
416 name: current.name ?? name,
417 description: desiredDescription,
418 priority,
419 action,
420 ipProtocol,
421 sourceIpRanges,
422 destinationIpRanges,
423 sourcePorts,
424 destinationPorts,
425 },
426 });
427 yield* waitForOperation(operation);
428 current = yield* waitUntilReady(
429 getByName(current.name ?? name),
430 current.name ?? name,
431 (item) => item.state,
432 );
433 }
434
435 return toAttrs(current, env.project, env.region);
436 }),
437
438 delete: Effect.fn(function* ({ output }) {
439 const operation = yield* vmwareengine
440 .deleteProjectsLocationsNetworkPoliciesExternalAccessRules({
441 name: output.name,
442 })
443 .pipe(
444 Effect.retry({
445 while: (error) => error._tag === "Conflict",
446 times: 8,
447 schedule: Schedule.spaced("2 seconds"),
448 }),
449 Effect.catchTag("NotFound", () => Effect.undefined),
450 );
451 if (operation !== undefined) {
452 yield* waitForOperation(operation, { notFoundOk: true });
453 }
454 yield* waitUntilGone(getByName(output.name), output.name);
455 }),
456 });