@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 390 lines 13.2 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 { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_GLOBAL,
14 changedFields,
15 collectPages,
16 hasAlchemyLabelKeys,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 rfc1035,
21 sameJson,
22 toPhysicalId,
23 userLabels,
24 waitForOperation,
25 waitUntilGone,
26 waitUntilPresent,
27 } from "./internal.ts";
28
29 const COLLECTION = "clientTlsPolicies";
30
31 export type GrpcEndpoint = {
32 /** gRPC UDS target URI. Must start with `unix:`. */
33 targetUri?: string;
34 };
35
36 export type CertificateProviderInstance = {
37 /**
38 * Plugin instance name. Use `google_cloud_private_spiffe` for
39 * Certificate Authority Service.
40 */
41 pluginInstance?: string;
42 };
43
44 export type ValidationCA = {
45 /** gRPC endpoint used to obtain the CA certificate. */
46 grpcEndpoint?: GrpcEndpoint;
47 /** Certificate provider instance loaded by the data plane. */
48 certificateProviderInstance?: CertificateProviderInstance;
49 };
50
51 export type CertificateProvider = {
52 /** gRPC endpoint used to obtain the cert and private key. */
53 grpcEndpoint?: GrpcEndpoint;
54 /** Certificate provider instance loaded by the data plane. */
55 certificateProviderInstance?: CertificateProviderInstance;
56 };
57
58 export type ClientTlsPolicyProps = {
59 /**
60 * ClientTlsPolicy id (the `{clientTlsPolicy}` segment of
61 * `projects/{project}/locations/{location}/clientTlsPolicies/{clientTlsPolicy}`).
62 * If omitted, a unique name is generated from the stack, stage, and
63 * logical id. Must be 1-63 characters and not start with a number.
64 * Immutable — changing it replaces the policy.
65 */
66 clientTlsPolicyId?: string;
67 /**
68 * Location (`global`, `us-central1`, …). Immutable — changing it
69 * replaces the policy. `US-CENTRAL1` is accepted and normalized to
70 * `us-central1`.
71 * @default "global"
72 */
73 location?: string;
74 /**
75 * Human-readable description.
76 */
77 description?: string;
78 /**
79 * Server Name Indication presented during the TLS handshake
80 * (e.g. `secure.example.com`).
81 */
82 sni?: string;
83 /**
84 * Mechanism used to obtain CA certificates that validate the server
85 * certificate. Empty means the client does not validate the server.
86 */
87 serverValidationCa?: ValidationCA[];
88 /**
89 * Mechanism used to provision client identity for mTLS. Presence of
90 * this field enables mTLS.
91 */
92 clientCertificate?: CertificateProvider;
93 /**
94 * User labels. Alchemy ownership labels are merged in automatically.
95 */
96 labels?: Record<string, string>;
97 };
98
99 export type ClientTlsPolicy = Resource<
100 "GCP.NetworkSecurity.ClientTlsPolicy",
101 ClientTlsPolicyProps,
102 {
103 /** Full resource name `projects/{project}/locations/{location}/clientTlsPolicies/{clientTlsPolicy}`. */
104 name: string;
105 /** ClientTlsPolicy id (last path segment). */
106 clientTlsPolicyId: string;
107 /** Project id. */
108 project: string;
109 /** Location id (`global`, `us-central1`, …). */
110 location: string;
111 /** User-provided description. */
112 description: string | undefined;
113 /** SNI string presented to the server, if set. */
114 sni: string | undefined;
115 /** Server-validation CAs currently configured. */
116 serverValidationCa: ValidationCA[];
117 /** Client certificate provider used for mTLS, if set. */
118 clientCertificate: CertificateProvider | undefined;
119 /** User labels (Alchemy ownership labels stripped). */
120 labels: Record<string, string>;
121 /** RFC3339 creation timestamp. */
122 createTime: string | undefined;
123 /** RFC3339 last-update timestamp. */
124 updateTime: string | undefined;
125 },
126 never,
127 Providers
128 >;
129
130 /**
131 * A Network Security ClientTlsPolicy — how a client authenticates
132 * connections to backends. The policy has no effect until it is
133 * attached to a backend service.
134 *
135 * Changing `clientTlsPolicyId` or `location` replaces the policy.
136 * Description, labels, SNI, server-validation CAs, and the client
137 * certificate provider update in place.
138 *
139 * ### Creating a ClientTlsPolicy
140 * **Example:** Generated name
141 * ```typescript
142 * const policy = yield* GCP.NetworkSecurity.ClientTlsPolicy("BackendTls", {
143 * sni: "backend.example.com",
144 * });
145 * ```
146 *
147 * **Example:** Named policy with labels
148 * ```typescript
149 * const policy = yield* GCP.NetworkSecurity.ClientTlsPolicy("BackendTls", {
150 * clientTlsPolicyId: "app-backend-tls",
151 * description: "prod backends",
152 * labels: { env: "prod" },
153 * sni: "backend.example.com",
154 * });
155 * ```
156 *
157 * ### mTLS
158 * **Example:** Private SPIFFE identity plus CA validation
159 * ```typescript
160 * const policy = yield* GCP.NetworkSecurity.ClientTlsPolicy("Mtls", {
161 * sni: "secure.example.com",
162 * clientCertificate: {
163 * certificateProviderInstance: {
164 * pluginInstance: "google_cloud_private_spiffe",
165 * },
166 * },
167 * serverValidationCa: [
168 * {
169 * certificateProviderInstance: {
170 * pluginInstance: "google_cloud_private_spiffe",
171 * },
172 * },
173 * ],
174 * });
175 * ```
176 *
177 * @resource
178 * @category NetworkSecurity
179 */
180 export const ClientTlsPolicy = Resource<ClientTlsPolicy>("GCP.NetworkSecurity.ClientTlsPolicy");
181
182 const resourceName = (project: string, location: string, clientTlsPolicyId: string) =>
183 `projects/${project}/locations/${location}/clientTlsPolicies/${clientTlsPolicyId}`;
184
185 const toCa = (ca: ValidationCA | networksecurity.ValidationCA): ValidationCA => ({
186 grpcEndpoint: ca.grpcEndpoint ? { targetUri: ca.grpcEndpoint.targetUri } : undefined,
187 certificateProviderInstance: ca.certificateProviderInstance
188 ? { pluginInstance: ca.certificateProviderInstance.pluginInstance }
189 : undefined,
190 });
191
192 const toProvider = (
193 provider:
194 | CertificateProvider
195 | networksecurity.GoogleCloudNetworksecurityV1CertificateProvider
196 | undefined,
197 ): CertificateProvider | undefined => {
198 if (provider === undefined) return undefined;
199 const grpcEndpoint = provider.grpcEndpoint
200 ? { targetUri: provider.grpcEndpoint.targetUri }
201 : undefined;
202 const certificateProviderInstance = provider.certificateProviderInstance
203 ? { pluginInstance: provider.certificateProviderInstance.pluginInstance }
204 : undefined;
205 if (grpcEndpoint === undefined && certificateProviderInstance === undefined) {
206 return undefined;
207 }
208 return { grpcEndpoint, certificateProviderInstance };
209 };
210
211 const toAttrs = (policy: networksecurity.ClientTlsPolicy, project: string) => {
212 const name = policy.name ?? "";
213 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
214 return {
215 name,
216 clientTlsPolicyId: parsed.id,
217 project: parsed.project || project,
218 location: parsed.location || DEFAULT_GLOBAL,
219 description: policy.description,
220 sni: policy.sni,
221 serverValidationCa: (policy.serverValidationCa ?? []).map(toCa),
222 clientCertificate: toProvider(policy.clientCertificate),
223 labels: userLabels(policy.labels),
224 createTime: policy.createTime,
225 updateTime: policy.updateTime,
226 };
227 };
228
229 const getByName = (name: string) =>
230 networksecurity
231 .getProjectsLocationsClientTlsPolicies({ name })
232 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
233
234 export const ClientTlsPolicyProvider = () =>
235 Provider.succeed(ClientTlsPolicy, {
236 stables: ["name", "clientTlsPolicyId", "project", "location", "createTime"],
237
238 diff: Effect.fn(function* ({ news, olds, output }) {
239 if (!isResolved(news)) return undefined;
240 const previousId = olds?.clientTlsPolicyId ?? output?.clientTlsPolicyId;
241 const nextId = news.clientTlsPolicyId
242 ? rfc1035(news.clientTlsPolicyId, "client-tls-policy")
243 : previousId;
244 const previousLocation = normalizeLocation(
245 olds?.location ?? output?.location,
246 DEFAULT_GLOBAL,
247 );
248 const nextLocation = normalizeLocation(
249 news.location ?? olds?.location ?? output?.location,
250 DEFAULT_GLOBAL,
251 );
252 if (
253 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
254 previousLocation !== nextLocation
255 ) {
256 return { action: "replace" as const };
257 }
258 return undefined;
259 }),
260
261 read: Effect.fn(function* ({ id, olds, output }) {
262 const env = yield* GcpEnvironment.current;
263 const clientTlsPolicyId = yield* toPhysicalId(
264 id,
265 olds?.clientTlsPolicyId,
266 output?.clientTlsPolicyId,
267 "client-tls-policy",
268 );
269 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
270 const name = output?.name ?? resourceName(env.project, location, clientTlsPolicyId);
271 const existing = yield* getByName(name);
272 if (existing === undefined) return undefined;
273 const attrs = toAttrs(existing, env.project);
274 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
275 }),
276
277 list: () =>
278 Effect.gen(function* () {
279 const env = yield* GcpEnvironment.current;
280 const items = yield* collectPages(
281 networksecurity.listProjectsLocationsClientTlsPolicies.pages({
282 parent: parentOf(env.project, "-"),
283 pageSize: 1000,
284 }),
285 (page) => page.clientTlsPolicies,
286 );
287 return items
288 .filter((item) => hasAlchemyLabelKeys(item.labels))
289 .map((item) => toAttrs(item, env.project));
290 }),
291
292 reconcile: Effect.fn(function* ({ id, news, output }) {
293 const env = yield* GcpEnvironment.current;
294 const clientTlsPolicyId = yield* toPhysicalId(
295 id,
296 news.clientTlsPolicyId,
297 output?.clientTlsPolicyId,
298 "client-tls-policy",
299 );
300 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
301 const name = resourceName(env.project, location, clientTlsPolicyId);
302 const desiredLabels = {
303 ...toLabels(news.labels),
304 ...(yield* createInternalLabels(id)),
305 };
306 const desiredCa = (news.serverValidationCa ?? []).map(toCa);
307 const desiredClient = toProvider(news.clientCertificate);
308
309 let current = yield* getByName(name);
310
311 if (current === undefined) {
312 const created = yield* networksecurity
313 .createProjectsLocationsClientTlsPolicies({
314 parent: parentOf(env.project, location),
315 clientTlsPolicyId,
316 body: {
317 description: news.description,
318 labels: desiredLabels,
319 sni: news.sni,
320 serverValidationCa: desiredCa,
321 clientCertificate: desiredClient,
322 },
323 })
324 .pipe(
325 Effect.retry({
326 while: (error) => error._tag === "Conflict",
327 times: 5,
328 schedule: Schedule.spaced("2 seconds"),
329 }),
330 Effect.catchTag("Conflict", () => Effect.undefined),
331 );
332 if (created !== undefined) {
333 yield* waitForOperation(created);
334 }
335 current = yield* waitUntilPresent(getByName(name), name);
336 }
337
338 const observedLabels = tagRecord(current.labels);
339 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
340 const labelsChanged = upsert.length > 0 || removed.length > 0;
341 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
342 const sniChanged = (current.sni ?? "") !== (news.sni ?? "");
343 const caChanged = !sameJson((current.serverValidationCa ?? []).map(toCa), desiredCa);
344 const clientChanged = !sameJson(toProvider(current.clientCertificate), desiredClient);
345
346 const updateMask = changedFields([
347 ["labels", labelsChanged],
348 ["description", descriptionChanged],
349 ["sni", sniChanged],
350 ["serverValidationCa", caChanged],
351 ["clientCertificate", clientChanged],
352 ]);
353
354 if (updateMask.length > 0) {
355 const operation = yield* networksecurity.patchProjectsLocationsClientTlsPolicies({
356 name: current.name ?? name,
357 updateMask: updateMask.join(","),
358 body: {
359 name: current.name ?? name,
360 labels: desiredLabels,
361 description: news.description,
362 sni: news.sni,
363 serverValidationCa: desiredCa,
364 clientCertificate: desiredClient,
365 },
366 });
367 yield* waitForOperation(operation);
368 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
369 }
370
371 return toAttrs(current, env.project);
372 }),
373
374 delete: Effect.fn(function* ({ output }) {
375 const operation = yield* networksecurity
376 .deleteProjectsLocationsClientTlsPolicies({ name: output.name })
377 .pipe(
378 Effect.retry({
379 while: (error) => error._tag === "Conflict",
380 times: 8,
381 schedule: Schedule.spaced("2 seconds"),
382 }),
383 Effect.catchTag("NotFound", () => Effect.undefined),
384 );
385 if (operation !== undefined) {
386 yield* waitForOperation(operation, { notFoundOk: true });
387 }
388 yield* waitUntilGone(getByName(output.name), output.name);
389 }),
390 });