@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 403 lines 13.3 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 Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { GcpEnvironment } from "../Environment.ts";
12 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import { waitGlobalOperation } from "./operations.ts";
15
16 export type SslPolicyMinTlsVersion = "TLS_1_0" | "TLS_1_1" | "TLS_1_2" | "TLS_1_3";
17
18 export type SslPolicyProfile = "COMPATIBLE" | "MODERN" | "RESTRICTED" | "FIPS_202205" | "CUSTOM";
19
20 export type SslPolicyPostQuantumKeyExchange = "DEFAULT" | "ENABLED" | "DEFERRED";
21
22 export type SslPolicyProps = {
23 /**
24 * SSL policy name (RFC1035, 1-63 chars). If omitted, a unique name is
25 * generated from the stack, stage, and logical id. Changing it replaces
26 * the resource.
27 */
28 sslPolicyName?: string;
29 /**
30 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
31 * prefix so `list` / nuke can find resources (Compute SslPolicy has no
32 * labels field).
33 */
34 description?: string;
35 /**
36 * Minimum TLS version clients may use (`TLS_1_0`, `TLS_1_1`, `TLS_1_2`,
37 * `TLS_1_3`). `TLS_1_3` requires `profile: "RESTRICTED"`.
38 * @default "TLS_1_0"
39 */
40 minTlsVersion?: SslPolicyMinTlsVersion;
41 /**
42 * Cipher-suite profile (`COMPATIBLE`, `MODERN`, `RESTRICTED`,
43 * `FIPS_202205`, `CUSTOM`). `CUSTOM` requires `customFeatures`.
44 * `FIPS_202205` requires `minTlsVersion: "TLS_1_2"`.
45 * @default "COMPATIBLE"
46 */
47 profile?: SslPolicyProfile;
48 /**
49 * Features enabled when `profile` is `CUSTOM`. Must be empty for every
50 * other profile. Use `listAvailableFeaturesSslPolicies` for the
51 * allowed set.
52 */
53 customFeatures?: string[];
54 /**
55 * Whether the load balancer negotiates X25519MLKEM768 (`DEFAULT`,
56 * `ENABLED`, `DEFERRED`).
57 */
58 postQuantumKeyExchange?: SslPolicyPostQuantumKeyExchange;
59 };
60
61 export type SslPolicy = Resource<
62 "GCP.Compute.SslPolicy",
63 SslPolicyProps,
64 {
65 /** SSL policy name. */
66 sslPolicyName: string;
67 /** Project id. */
68 project: string;
69 /** User description with the Alchemy ownership prefix stripped. */
70 description: string | undefined;
71 /** Minimum TLS version. */
72 minTlsVersion: SslPolicyMinTlsVersion;
73 /** Cipher-suite profile. */
74 profile: SslPolicyProfile;
75 /** Custom features (only when `profile` is `CUSTOM`). */
76 customFeatures: string[];
77 /** Features currently enabled by the selected profile. */
78 enabledFeatures: string[];
79 /** Post-quantum key exchange mode, if set. */
80 postQuantumKeyExchange: string | undefined;
81 /** Server-defined URL. */
82 selfLink: string | undefined;
83 /** Server-assigned numeric id. */
84 sslPolicyId: string | undefined;
85 /** Optimistic-locking fingerprint. */
86 fingerprint: string | undefined;
87 /** RFC3339 creation timestamp. */
88 creationTimestamp: string | undefined;
89 /** Resource kind. */
90 kind: string | undefined;
91 },
92 never,
93 Providers
94 >;
95
96 /**
97 * A global Compute Engine SSL policy for HTTPS and SSL load balancing.
98 *
99 * SSL policies control the TLS versions and cipher suites offered by
100 * Application Load Balancers and proxy Network Load Balancers. This
101 * resource maps to the global `sslPolicies` collection
102 * (`regionSslPolicies` is a separate resource). Compute SslPolicy has no
103 * labels field — Alchemy ownership is stored in the description so nuke
104 * can find leaked policies.
105 *
106 * ### Creating an SSL Policy
107 * **Example:** Generated name (COMPATIBLE, TLS 1.0)
108 * ```typescript
109 * const policy = yield* GCP.Compute.SslPolicy("Frontend", {});
110 * ```
111 *
112 * **Example:** Modern profile and TLS 1.2
113 * ```typescript
114 * const policy = yield* GCP.Compute.SslPolicy("Frontend", {
115 * description: "prod frontend",
116 * profile: "MODERN",
117 * minTlsVersion: "TLS_1_2",
118 * });
119 * ```
120 *
121 * ### Custom Cipher Suites
122 * **Example:** CUSTOM profile
123 * ```typescript
124 * const policy = yield* GCP.Compute.SslPolicy("Frontend", {
125 * profile: "CUSTOM",
126 * minTlsVersion: "TLS_1_2",
127 * customFeatures: [
128 * "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
129 * "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
130 * ],
131 * });
132 * ```
133 *
134 * @resource
135 * @category Compute
136 */
137 export const SslPolicy = Resource<SslPolicy>("GCP.Compute.SslPolicy");
138
139 export class SslPolicyNotResolved extends Data.TaggedError("GCP.Compute.SslPolicyNotResolved")<{
140 sslPolicyName: string;
141 }> {}
142
143 const DEFAULT_PROFILE: SslPolicyProfile = "COMPATIBLE";
144 const DEFAULT_MIN_TLS: SslPolicyMinTlsVersion = "TLS_1_0";
145
146 const rfc1035 = (name: string): string => {
147 let next = name
148 .toLowerCase()
149 .replace(/[^a-z0-9-]/g, "-")
150 .replace(/-+/g, "-")
151 .replace(/^-+/, "")
152 .replace(/-+$/, "");
153 if (!/^[a-z]/.test(next)) {
154 next = `s${next}`;
155 }
156 next = next.slice(0, 63).replace(/-+$/, "");
157 return next.length > 0 ? next : "sslpolicy";
158 };
159
160 const toName = (id: string, name: string | undefined, existing?: string) =>
161 Effect.gen(function* () {
162 if (name !== undefined) return name;
163 if (existing !== undefined) return existing;
164 return rfc1035(
165 yield* createPhysicalName({
166 id,
167 maxLength: 63,
168 lowercase: true,
169 }),
170 );
171 });
172
173 const encodeDescription = (
174 labels: Record<string, string>,
175 description: string | undefined,
176 ): string => {
177 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
178 return description ? `${marker}\n${description}` : marker;
179 };
180
181 const parseDescription = (
182 description: string | undefined,
183 ): {
184 labels: Record<string, string>;
185 description: string | undefined;
186 } => {
187 if (!description?.startsWith("[alchemy ")) {
188 return { labels: {}, description };
189 }
190 const end = description.indexOf("]");
191 if (end < 0) return { labels: {}, description };
192 const labels: Record<string, string> = {};
193 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
194 const eq = part.indexOf("=");
195 if (eq > 0) {
196 labels[part.slice(0, eq)] = part.slice(eq + 1);
197 }
198 }
199 const rest = description.slice(end + 1).replace(/^\n/, "");
200 return { labels, description: rest.length > 0 ? rest : undefined };
201 };
202
203 const asProfile = (value: string | undefined): SslPolicyProfile => {
204 switch (value) {
205 case "COMPATIBLE":
206 case "MODERN":
207 case "RESTRICTED":
208 case "FIPS_202205":
209 case "CUSTOM":
210 return value;
211 default:
212 return DEFAULT_PROFILE;
213 }
214 };
215
216 const asMinTlsVersion = (value: string | undefined): SslPolicyMinTlsVersion => {
217 switch (value) {
218 case "TLS_1_0":
219 case "TLS_1_1":
220 case "TLS_1_2":
221 case "TLS_1_3":
222 return value;
223 default:
224 return DEFAULT_MIN_TLS;
225 }
226 };
227
228 const featuresOf = (features: readonly string[] | undefined): string[] => [...(features ?? [])];
229
230 const sameFeatures = (observed?: readonly string[], desired?: readonly string[]) =>
231 [...(observed ?? [])].sort().join("\0") === [...(desired ?? [])].sort().join("\0");
232
233 const toBody = (
234 sslPolicyName: string,
235 props: SslPolicyProps,
236 ownership: Record<string, string>,
237 fingerprint?: string,
238 ): compute.SslPolicy => {
239 const profile = props.profile ?? DEFAULT_PROFILE;
240 return {
241 name: sslPolicyName,
242 fingerprint,
243 description: encodeDescription(ownership, props.description),
244 profile,
245 minTlsVersion: props.minTlsVersion ?? DEFAULT_MIN_TLS,
246 customFeatures: profile === "CUSTOM" ? featuresOf(props.customFeatures) : [],
247 postQuantumKeyExchange: props.postQuantumKeyExchange,
248 };
249 };
250
251 const toAttrs = (policy: compute.SslPolicy, project: string): SslPolicy["Attributes"] => {
252 const parsed = parseDescription(policy.description);
253 return {
254 sslPolicyName: policy.name ?? policy.id ?? "",
255 project,
256 description: parsed.description,
257 minTlsVersion: asMinTlsVersion(policy.minTlsVersion),
258 profile: asProfile(policy.profile),
259 customFeatures: featuresOf(policy.customFeatures),
260 enabledFeatures: featuresOf(policy.enabledFeatures),
261 postQuantumKeyExchange: policy.postQuantumKeyExchange,
262 selfLink: policy.selfLink,
263 sslPolicyId: policy.id,
264 fingerprint: policy.fingerprint,
265 creationTimestamp: policy.creationTimestamp,
266 kind: policy.kind,
267 };
268 };
269
270 const needsUpdate = (current: compute.SslPolicy, desired: compute.SslPolicy) => {
271 if ((current.description ?? "") !== (desired.description ?? "")) return true;
272 if (asProfile(current.profile) !== asProfile(desired.profile)) return true;
273 if (asMinTlsVersion(current.minTlsVersion) !== asMinTlsVersion(desired.minTlsVersion)) {
274 return true;
275 }
276 if (!sameFeatures(current.customFeatures, desired.customFeatures)) {
277 return true;
278 }
279 if (
280 desired.postQuantumKeyExchange !== undefined &&
281 (current.postQuantumKeyExchange ?? "DEFAULT") !== desired.postQuantumKeyExchange
282 ) {
283 return true;
284 }
285 return false;
286 };
287
288 const getByName = (project: string, sslPolicy: string) =>
289 compute
290 .getSslPolicies({ project, sslPolicy })
291 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
292
293 const awaitResource = (project: string, sslPolicyName: string) =>
294 getByName(project, sslPolicyName).pipe(
295 Effect.repeat({
296 schedule: Schedule.spaced("1 second"),
297 until: (policy) => policy !== undefined,
298 times: 8,
299 }),
300 );
301
302 export const SslPolicyProvider = () =>
303 Provider.succeed(SslPolicy, {
304 stables: ["sslPolicyName", "project", "sslPolicyId", "selfLink", "creationTimestamp"],
305
306 diff: Effect.fn(function* ({ news, olds, output }) {
307 if (!isResolved(news)) return undefined;
308 const previousName = olds?.sslPolicyName ?? output?.sslPolicyName;
309 const nextName = news.sslPolicyName;
310 if (previousName !== undefined && nextName !== undefined && previousName !== nextName) {
311 return { action: "replace" as const };
312 }
313 return undefined;
314 }),
315
316 read: Effect.fn(function* ({ id, olds, output }) {
317 const env = yield* GcpEnvironment.current;
318 const sslPolicyName = yield* toName(id, olds?.sslPolicyName, output?.sslPolicyName);
319 const existing = yield* getByName(env.project, sslPolicyName);
320 if (existing === undefined) return undefined;
321 const attrs = toAttrs(existing, env.project);
322 const { labels } = parseDescription(existing.description);
323 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
324 }),
325
326 list: () =>
327 Effect.gen(function* () {
328 const env = yield* GcpEnvironment.current;
329 return yield* compute.listSslPolicies.items({ project: env.project, maxResults: 500 }).pipe(
330 Stream.filter((policy) => {
331 const { labels } = parseDescription(policy.description);
332 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
333 }),
334 Stream.map((policy) => toAttrs(policy, env.project)),
335 Stream.runCollect,
336 Effect.map((chunk) => Array.from(chunk)),
337 );
338 }),
339
340 reconcile: Effect.fn(function* ({ id, news, output }) {
341 const env = yield* GcpEnvironment.current;
342 const sslPolicyName = yield* toName(id, news.sslPolicyName, output?.sslPolicyName);
343 const ownership = yield* createInternalLabels(id);
344 const desired = toBody(sslPolicyName, news, ownership);
345
346 let current = yield* getByName(env.project, sslPolicyName);
347
348 if (current === undefined) {
349 yield* compute
350 .insertSslPolicies({
351 project: env.project,
352 body: desired,
353 })
354 .pipe(
355 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
356 Effect.catchTag("Conflict", () => Effect.undefined),
357 );
358 current = yield* awaitResource(env.project, sslPolicyName);
359 }
360
361 if (current === undefined) {
362 return yield* new SslPolicyNotResolved({ sslPolicyName });
363 }
364
365 if (needsUpdate(current, desired)) {
366 yield* compute
367 .patchSslPolicies({
368 project: env.project,
369 sslPolicy: sslPolicyName,
370 body: toBody(sslPolicyName, news, ownership, current.fingerprint),
371 })
372 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
373 current = yield* getByName(env.project, sslPolicyName);
374 if (current === undefined) {
375 return yield* new SslPolicyNotResolved({ sslPolicyName });
376 }
377 }
378
379 return toAttrs(current, env.project);
380 }),
381
382 delete: Effect.fn(function* ({ output }) {
383 const env = yield* GcpEnvironment.current;
384 const operation = yield* compute
385 .deleteSslPolicies({
386 project: env.project,
387 sslPolicy: output.sslPolicyName,
388 })
389 .pipe(
390 Effect.retry({
391 while: (error) => error._tag === "Conflict",
392 schedule: Schedule.spaced("2 seconds"),
393 times: 8,
394 }),
395 Effect.catchTag("NotFound", () => Effect.undefined),
396 );
397 if (operation !== undefined) {
398 yield* waitGlobalOperation(env.project, operation).pipe(
399 Effect.catchTag("NotFound", () => Effect.void),
400 );
401 }
402 }),
403 });