@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 336 lines 12 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 parseResourceName,
16 projectParent,
17 ResourceNotResolved,
18 toPhysicalId,
19 userLabels,
20 waitForOperation,
21 waitUntilExists,
22 waitUntilGone,
23 } from "./operations.ts";
24
25 const DEFAULT_WELL_KNOWN_ROOTS =
26 "NONE" satisfies networksecurity.BackendAuthenticationConfigWellKnownRootsEnum;
27
28 export type BackendAuthenticationConfigWellKnownRoots =
29 | networksecurity.BackendAuthenticationConfigWellKnownRootsEnum
30 | (string & {});
31
32 export type BackendAuthenticationConfigProps = {
33 /**
34 * Backend authentication config id. If omitted, a unique RFC1035 name
35 * is generated from the stack, stage, and logical id. Immutable —
36 * changing it replaces the config.
37 */
38 backendAuthenticationConfigId?: string;
39 /**
40 * Location (`global`, `us-central1`, …). Immutable — changing it
41 * replaces the config.
42 * @default "global"
43 */
44 location?: string;
45 /**
46 * Certificate Manager TrustConfig used to validate backend server
47 * certificates. Required unless `wellKnownRoots` is `PUBLIC_ROOTS`.
48 */
49 trustConfig?: string;
50 /**
51 * Certificate Manager certificate (CLIENT_AUTH scope) presented to
52 * the backend for mTLS.
53 */
54 clientCertificate?: string;
55 /**
56 * Whether public CAs are trusted in addition to `trustConfig`.
57 * @default "NONE"
58 */
59 wellKnownRoots?: BackendAuthenticationConfigWellKnownRoots;
60 /**
61 * Human-readable description.
62 */
63 description?: string;
64 /**
65 * User labels. Alchemy ownership labels are merged in automatically.
66 */
67 labels?: Record<string, string>;
68 };
69
70 export type BackendAuthenticationConfig = Resource<
71 "GCP.NetworkSecurity.BackendAuthenticationConfig",
72 BackendAuthenticationConfigProps,
73 {
74 /** Full resource name `projects/{project}/locations/{location}/backendAuthenticationConfigs/{backendAuthenticationConfig}`. */
75 name: string;
76 /** Config id (last path segment). */
77 backendAuthenticationConfigId: string;
78 /** Project id. */
79 project: string;
80 /** Location id. */
81 location: string;
82 /** TrustConfig resource name, if set. */
83 trustConfig: string | undefined;
84 /** Client certificate resource name, if set. */
85 clientCertificate: string | undefined;
86 /** Well-known roots setting. */
87 wellKnownRoots: string | undefined;
88 /** User-provided description. */
89 description: string | undefined;
90 /** User labels (Alchemy ownership labels stripped). */
91 labels: Record<string, string>;
92 /** Server-computed checksum. */
93 etag: string | undefined;
94 /** RFC3339 creation timestamp. */
95 createTime: string | undefined;
96 /** RFC3339 last-update timestamp. */
97 updateTime: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A Network Security BackendAuthenticationConfig — how a load balancer
105 * authenticates to backends (TrustConfig, public roots, optional mTLS
106 * client certificate).
107 *
108 * Changing `backendAuthenticationConfigId` or `location` replaces the
109 * config. TrustConfig, client certificate, well-known roots,
110 * description, and labels update in place.
111 *
112 * ### Creating a Backend Authentication Config
113 * **Example:** Trust public roots
114 * ```typescript
115 * const config = yield* GCP.NetworkSecurity.BackendAuthenticationConfig(
116 * "BackendTls",
117 * { wellKnownRoots: "PUBLIC_ROOTS" },
118 * );
119 * ```
120 *
121 * **Example:** TrustConfig plus public roots
122 * ```typescript
123 * const config = yield* GCP.NetworkSecurity.BackendAuthenticationConfig(
124 * "BackendTls",
125 * {
126 * trustConfig: trust.name,
127 * wellKnownRoots: "PUBLIC_ROOTS",
128 * labels: { env: "prod" },
129 * },
130 * );
131 * ```
132 *
133 * @resource
134 * @category NetworkSecurity
135 */
136 export const BackendAuthenticationConfig = Resource<BackendAuthenticationConfig>(
137 "GCP.NetworkSecurity.BackendAuthenticationConfig",
138 );
139
140 const resourceName = (project: string, location: string, backendAuthenticationConfigId: string) =>
141 `projects/${project}/locations/${location}/backendAuthenticationConfigs/${backendAuthenticationConfigId}`;
142
143 const rootsOf = (value: string | undefined) => (value ?? DEFAULT_WELL_KNOWN_ROOTS).toUpperCase();
144
145 const toAttrs = (config: networksecurity.BackendAuthenticationConfig, project: string) => {
146 const name = config.name ?? "";
147 const parsed = parseResourceName(name);
148 return {
149 name,
150 backendAuthenticationConfigId: parsed.id,
151 project: parsed.parentId || project,
152 location: parsed.location,
153 trustConfig: config.trustConfig,
154 clientCertificate: config.clientCertificate,
155 wellKnownRoots: config.wellKnownRoots,
156 description: config.description,
157 labels: userLabels(config.labels),
158 etag: config.etag,
159 createTime: config.createTime,
160 updateTime: config.updateTime,
161 };
162 };
163
164 const getByName = (name: string) =>
165 networksecurity
166 .getProjectsLocationsBackendAuthenticationConfigs({ name })
167 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
168
169 const listOwned = (project: string) =>
170 networksecurity.listProjectsLocationsBackendAuthenticationConfigs
171 .pages({
172 parent: projectParent(project, "-"),
173 pageSize: 1000,
174 })
175 .pipe(
176 Stream.flatMap((page) => Stream.fromIterable(page.backendAuthenticationConfigs ?? [])),
177 Stream.filter((config) =>
178 Object.keys(config.labels ?? {}).some((key) => key.startsWith("alchemy-")),
179 ),
180 Stream.map((config) => toAttrs(config, project)),
181 Stream.runCollect,
182 Effect.map((chunk) => Array.from(chunk)),
183 Effect.catchTag("NotFound", () => Effect.succeed([])),
184 );
185
186 export const BackendAuthenticationConfigProvider = () =>
187 Provider.succeed(BackendAuthenticationConfig, {
188 stables: ["name", "backendAuthenticationConfigId", "project", "location", "createTime"],
189
190 diff: Effect.fn(function* ({ news, olds, output }) {
191 if (!isResolved(news)) return undefined;
192 const previousId =
193 olds?.backendAuthenticationConfigId ?? output?.backendAuthenticationConfigId;
194 const nextId = news.backendAuthenticationConfigId ?? previousId;
195 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
196 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
197 const replace =
198 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
199 previousLocation !== nextLocation;
200 if (!replace) return undefined;
201 return {
202 action: "replace" as const,
203 deleteFirst:
204 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
205 };
206 }),
207
208 read: Effect.fn(function* ({ id, olds, output }) {
209 const env = yield* GcpEnvironment.current;
210 const backendAuthenticationConfigId = yield* toPhysicalId(
211 id,
212 olds?.backendAuthenticationConfigId,
213 output?.backendAuthenticationConfigId,
214 "backendauth",
215 );
216 const location = normalizeLocation(olds?.location ?? output?.location);
217 const name =
218 output?.name ?? resourceName(env.project, location, backendAuthenticationConfigId);
219 const existing = yield* getByName(name);
220 if (existing === undefined) return undefined;
221 const attrs = toAttrs(existing, env.project);
222 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
223 }),
224
225 list: () =>
226 Effect.gen(function* () {
227 const env = yield* GcpEnvironment.current;
228 return yield* listOwned(env.project);
229 }),
230
231 reconcile: Effect.fn(function* ({ id, news, output }) {
232 const env = yield* GcpEnvironment.current;
233 const backendAuthenticationConfigId = yield* toPhysicalId(
234 id,
235 news.backendAuthenticationConfigId,
236 output?.backendAuthenticationConfigId,
237 "backendauth",
238 );
239 const location = normalizeLocation(news.location ?? output?.location);
240 const name = resourceName(env.project, location, backendAuthenticationConfigId);
241 const wellKnownRoots = rootsOf(news.wellKnownRoots);
242 const desiredLabels = {
243 ...toLabels(news.labels),
244 ...(yield* createInternalLabels(id)),
245 };
246
247 let current = yield* getByName(name);
248
249 if (current === undefined) {
250 const created = yield* networksecurity
251 .createProjectsLocationsBackendAuthenticationConfigs({
252 parent: projectParent(env.project, location),
253 backendAuthenticationConfigId,
254 body: {
255 trustConfig: news.trustConfig,
256 clientCertificate: news.clientCertificate,
257 wellKnownRoots,
258 description: news.description,
259 labels: desiredLabels,
260 },
261 })
262 .pipe(
263 Effect.retry({
264 while: (error) => error._tag === "Conflict",
265 times: 5,
266 schedule: Schedule.spaced("2 seconds"),
267 }),
268 Effect.catchTag("Conflict", () => Effect.undefined),
269 );
270 if (created !== undefined) {
271 yield* waitForOperation(created);
272 }
273 current = yield* waitUntilExists(getByName(name), name);
274 }
275
276 if (current === undefined) {
277 return yield* new ResourceNotResolved({ resourceName: name });
278 }
279
280 const observedLabels = tagRecord(current.labels);
281 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
282 const labelsChanged = upsert.length > 0 || removed.length > 0;
283 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
284 const trustChanged = (current.trustConfig ?? "") !== (news.trustConfig ?? "");
285 const certChanged = (current.clientCertificate ?? "") !== (news.clientCertificate ?? "");
286 const rootsChanged = rootsOf(current.wellKnownRoots) !== wellKnownRoots;
287
288 if (labelsChanged || descriptionChanged || trustChanged || certChanged || rootsChanged) {
289 const updateMask = [
290 labelsChanged ? "labels" : undefined,
291 descriptionChanged ? "description" : undefined,
292 trustChanged ? "trustConfig" : undefined,
293 certChanged ? "clientCertificate" : undefined,
294 rootsChanged ? "wellKnownRoots" : undefined,
295 ].filter((field): field is string => field !== undefined);
296
297 const operation = yield* networksecurity.patchProjectsLocationsBackendAuthenticationConfigs(
298 {
299 name: current.name ?? name,
300 updateMask: updateMask.join(","),
301 body: {
302 name: current.name ?? name,
303 labels: desiredLabels,
304 description: news.description,
305 trustConfig: news.trustConfig,
306 clientCertificate: news.clientCertificate,
307 wellKnownRoots,
308 },
309 },
310 );
311 yield* waitForOperation(operation);
312 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
313 }
314
315 return toAttrs(current, env.project);
316 }),
317
318 delete: Effect.fn(function* ({ output }) {
319 const operation = yield* networksecurity
320 .deleteProjectsLocationsBackendAuthenticationConfigs({
321 name: output.name,
322 })
323 .pipe(
324 Effect.retry({
325 while: (error) => error._tag === "Conflict",
326 times: 8,
327 schedule: Schedule.spaced("2 seconds"),
328 }),
329 Effect.catchTag("NotFound", () => Effect.undefined),
330 );
331 if (operation !== undefined) {
332 yield* waitForOperation(operation, { notFoundOk: true });
333 }
334 yield* waitUntilGone(getByName(output.name), output.name);
335 }),
336 });