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

main
ts 506 lines 17.4 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 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 { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
13 import type { Providers } from "../Providers.ts";
14 import {
15 DEFAULT_LOCATION,
16 normalizeLocation,
17 parentOf,
18 parseResourceName,
19 resourceName,
20 toId,
21 userLabels,
22 } from "./names.ts";
23 import { waitForOperation } from "./operations.ts";
24 import { sameJson } from "./ownership.ts";
25
26 const COLLECTION = "serverTlsPolicies";
27
28 export type ServerTlsGrpcEndpoint = {
29 /** gRPC endpoint URI. Only UDS paths starting with `unix:` are supported. */
30 targetUri?: string;
31 };
32
33 export type ServerTlsCertificateProviderInstance = {
34 /**
35 * Plugin instance name. Set to `google_cloud_private_spiffe` to use
36 * Certificate Authority Service.
37 */
38 pluginInstance?: string;
39 };
40
41 export type ServerTlsCertificateProvider = {
42 /** gRPC endpoint used to obtain the certificate and private key. */
43 grpcEndpoint?: ServerTlsGrpcEndpoint;
44 /** Certificate provider plugin instance loaded by the data plane. */
45 certificateProviderInstance?: ServerTlsCertificateProviderInstance;
46 };
47
48 export type ServerTlsValidationCA = ServerTlsCertificateProvider;
49
50 export type ServerTlsClientValidationMode =
51 | "ALLOW_INVALID_OR_MISSING_CLIENT_CERT"
52 | "REJECT_INVALID"
53 | (string & {});
54
55 export type ServerTlsMtlsPolicy = {
56 /**
57 * Certificate authorities used to validate the client certificate
58 * (Traffic Director). Must be empty for Application Load Balancers.
59 */
60 clientValidationCa?: ServerTlsValidationCA[];
61 /**
62 * Certificate Manager TrustConfig used for chain validation. Allowed
63 * only with Application Load Balancers.
64 */
65 clientValidationTrustConfig?: string;
66 /**
67 * How the load balancer handles a missing or invalid client
68 * certificate. Required for Application Load Balancers; must be empty
69 * for Traffic Director.
70 */
71 clientValidationMode?: ServerTlsClientValidationMode;
72 };
73
74 export type ServerTlsPolicyProps = {
75 /**
76 * ServerTlsPolicy id (the `{serverTlsPolicy}` segment of
77 * `projects/{project}/locations/{location}/serverTlsPolicies/{serverTlsPolicy}`).
78 * If omitted, a unique RFC1035 name is generated from the stack, stage,
79 * and logical id. Must be 1-63 characters, letters, numbers, hyphens,
80 * and underscores, and must not start with a number. Immutable —
81 * changing it replaces the policy.
82 */
83 serverTlsPolicyId?: string;
84 /**
85 * Location (`global`, `us-central1`, …). Immutable — changing it
86 * replaces the policy. `US-CENTRAL1` is accepted and normalized to
87 * `us-central1`.
88 * @default "global"
89 */
90 location?: string;
91 /**
92 * Human-readable description.
93 */
94 description?: string;
95 /**
96 * User labels. Alchemy ownership labels are merged in automatically.
97 */
98 labels?: Record<string, string>;
99 /**
100 * When true, the server also accepts plaintext connections. Must be
101 * false for Application Load Balancer policies. Defaults to false.
102 * @default false
103 */
104 allowOpen?: boolean;
105 /**
106 * Server identity (public/private keys). Optional for Traffic Director.
107 * Must be empty for Application Load Balancers. Cannot be combined
108 * with `allowOpen`.
109 */
110 serverCertificate?: ServerTlsCertificateProvider;
111 /**
112 * Peer validation for mTLS. Required for Application Load Balancers;
113 * optional for Traffic Director. When omitted, client certificates are
114 * not requested (plain TLS).
115 */
116 mtlsPolicy?: ServerTlsMtlsPolicy;
117 };
118
119 export type ServerTlsPolicy = Resource<
120 "GCP.NetworkSecurity.ServerTlsPolicy",
121 ServerTlsPolicyProps,
122 {
123 /** Full resource name `projects/{project}/locations/{location}/serverTlsPolicies/{serverTlsPolicy}`. */
124 name: string;
125 /** ServerTlsPolicy id (last path segment). */
126 serverTlsPolicyId: string;
127 /** Project id. */
128 project: string;
129 /** Location id (`global`, `us-central1`, …). */
130 location: string;
131 /** User-provided description. */
132 description: string | undefined;
133 /** User labels (Alchemy ownership labels stripped). */
134 labels: Record<string, string>;
135 /** Whether plaintext connections are allowed. */
136 allowOpen: boolean;
137 /** Server certificate provider, if configured. */
138 serverCertificate: ServerTlsCertificateProvider | undefined;
139 /** mTLS policy, if configured. */
140 mtlsPolicy: ServerTlsMtlsPolicy | undefined;
141 /** RFC3339 creation timestamp. */
142 createTime: string | undefined;
143 /** RFC3339 last-update timestamp. */
144 updateTime: string | undefined;
145 },
146 never,
147 Providers
148 >;
149
150 /**
151 * A Network Security ServerTlsPolicy — how a server authenticates
152 * incoming requests. Attach it to a TargetHttpsProxy or EndpointPolicy;
153 * the policy itself does not serve traffic.
154 *
155 * Changing `serverTlsPolicyId` or `location` replaces the policy.
156 * Application Load Balancer policies (`mtlsPolicy.clientValidationMode`
157 * set) cannot be updated in place — any other change replaces them.
158 * Traffic Director policies update description, labels, `allowOpen`,
159 * `serverCertificate`, and `mtlsPolicy` in place.
160 *
161 * ### Creating a ServerTlsPolicy
162 * **Example:** Application Load Balancer mTLS
163 * ```typescript
164 * const policy = yield* GCP.NetworkSecurity.ServerTlsPolicy("FrontendTls", {
165 * description: "alb mtls",
166 * mtlsPolicy: {
167 * clientValidationMode: "ALLOW_INVALID_OR_MISSING_CLIENT_CERT",
168 * },
169 * });
170 * ```
171 *
172 * **Example:** Named policy with labels
173 * ```typescript
174 * const policy = yield* GCP.NetworkSecurity.ServerTlsPolicy("FrontendTls", {
175 * serverTlsPolicyId: "app-frontend-tls",
176 * location: "global",
177 * description: "prod frontend",
178 * labels: { env: "prod" },
179 * mtlsPolicy: {
180 * clientValidationMode: "ALLOW_INVALID_OR_MISSING_CLIENT_CERT",
181 * },
182 * });
183 * ```
184 *
185 * ### Updating a ServerTlsPolicy
186 * **Example:** Description and labels
187 * ```typescript
188 * const policy = yield* GCP.NetworkSecurity.ServerTlsPolicy("FrontendTls", {
189 * serverTlsPolicyId: "app-frontend-tls",
190 * location: "global",
191 * description: "prod frontend v2",
192 * labels: { env: "prod", role: "tls" },
193 * mtlsPolicy: {
194 * clientValidationMode: "ALLOW_INVALID_OR_MISSING_CLIENT_CERT",
195 * },
196 * });
197 * ```
198 *
199 * @resource
200 * @category NetworkSecurity
201 */
202 export const ServerTlsPolicy = Resource<ServerTlsPolicy>("GCP.NetworkSecurity.ServerTlsPolicy");
203
204 export class ServerTlsPolicyNotResolved extends Data.TaggedError(
205 "GCP.NetworkSecurity.ServerTlsPolicyNotResolved",
206 )<{
207 resourceName: string;
208 }> {}
209
210 export class ServerTlsPolicyStillExists extends Data.TaggedError(
211 "GCP.NetworkSecurity.ServerTlsPolicyStillExists",
212 )<{
213 resourceName: string;
214 }> {}
215
216 const toCertificateProvider = (
217 value:
218 | networksecurity.GoogleCloudNetworksecurityV1CertificateProvider
219 | ServerTlsCertificateProvider
220 | undefined,
221 ): ServerTlsCertificateProvider | undefined => {
222 if (value === undefined) return undefined;
223 const grpcEndpoint = value.grpcEndpoint ? { targetUri: value.grpcEndpoint.targetUri } : undefined;
224 const certificateProviderInstance = value.certificateProviderInstance
225 ? {
226 pluginInstance: value.certificateProviderInstance.pluginInstance,
227 }
228 : undefined;
229 if (grpcEndpoint === undefined && certificateProviderInstance === undefined) {
230 return undefined;
231 }
232 return { grpcEndpoint, certificateProviderInstance };
233 };
234
235 const toMtlsPolicy = (
236 value: networksecurity.MTLSPolicy | ServerTlsMtlsPolicy | undefined,
237 ): ServerTlsMtlsPolicy | undefined => {
238 if (value === undefined) return undefined;
239 return {
240 clientValidationCa: (value.clientValidationCa ?? [])
241 .map((entry) => toCertificateProvider(entry))
242 .filter((entry): entry is ServerTlsCertificateProvider => entry !== undefined),
243 clientValidationTrustConfig: value.clientValidationTrustConfig,
244 clientValidationMode: value.clientValidationMode,
245 };
246 };
247
248 const toAttrs = (policy: networksecurity.ServerTlsPolicy, project: string) => {
249 const name = policy.name ?? "";
250 const parsed = parseResourceName(name, COLLECTION);
251 return {
252 name,
253 serverTlsPolicyId: parsed.id,
254 project: parsed.project || project,
255 location: parsed.location || DEFAULT_LOCATION,
256 description: policy.description,
257 labels: userLabels(policy.labels),
258 allowOpen: policy.allowOpen === true,
259 serverCertificate: toCertificateProvider(policy.serverCertificate),
260 mtlsPolicy: toMtlsPolicy(policy.mtlsPolicy),
261 createTime: policy.createTime,
262 updateTime: policy.updateTime,
263 };
264 };
265
266 const getByName = (name: string) =>
267 networksecurity
268 .getProjectsLocationsServerTlsPolicies({ name })
269 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
270
271 const waitUntilExists = (name: string) =>
272 getByName(name).pipe(
273 Effect.flatMap((policy) =>
274 policy
275 ? Effect.succeed(policy)
276 : Effect.fail(new ServerTlsPolicyNotResolved({ resourceName: name })),
277 ),
278 Effect.retry({
279 while: (error) => error._tag === "GCP.NetworkSecurity.ServerTlsPolicyNotResolved",
280 times: 8,
281 schedule: Schedule.spaced("1 second"),
282 }),
283 );
284
285 const waitUntilGone = (name: string) =>
286 getByName(name).pipe(
287 Effect.flatMap((policy) =>
288 policy === undefined
289 ? Effect.void
290 : Effect.fail(new ServerTlsPolicyStillExists({ resourceName: name })),
291 ),
292 Effect.retry({
293 while: (error) => error._tag === "GCP.NetworkSecurity.ServerTlsPolicyStillExists",
294 times: 10,
295 schedule: Schedule.spaced("2 seconds"),
296 }),
297 );
298
299 const listOwned = (project: string) =>
300 networksecurity.listProjectsLocationsServerTlsPolicies
301 .pages({
302 parent: parentOf(project, "-"),
303 pageSize: 1000,
304 returnPartialSuccess: true,
305 })
306 .pipe(
307 Stream.flatMap((page) => Stream.fromIterable(page.serverTlsPolicies ?? [])),
308 Stream.filter((policy) =>
309 Object.keys(policy.labels ?? {}).some((key) => key.startsWith("alchemy-")),
310 ),
311 Stream.map((policy) => toAttrs(policy, project)),
312 Stream.runCollect,
313 Effect.map((chunk) => Array.from(chunk)),
314 Effect.catchTag("NotFound", () => Effect.succeed([])),
315 );
316
317 const toCreateBody = (
318 news: ServerTlsPolicyProps,
319 desiredLabels: Record<string, string>,
320 ): networksecurity.ServerTlsPolicy => ({
321 description: news.description,
322 labels: desiredLabels,
323 allowOpen: news.allowOpen === true ? true : false,
324 serverCertificate: toCertificateProvider(news.serverCertificate),
325 mtlsPolicy: toMtlsPolicy(news.mtlsPolicy),
326 });
327
328 export const ServerTlsPolicyProvider = () =>
329 Provider.succeed(ServerTlsPolicy, {
330 stables: ["name", "serverTlsPolicyId", "project", "location", "createTime"],
331
332 diff: Effect.fn(function* ({ news, olds, output }) {
333 if (!isResolved(news)) return undefined;
334 const previousId = olds?.serverTlsPolicyId ?? output?.serverTlsPolicyId;
335 const nextId = news.serverTlsPolicyId ?? previousId;
336 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
337 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
338 if (
339 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
340 previousLocation !== nextLocation
341 ) {
342 return { action: "replace" as const };
343 }
344 const alb =
345 (news.mtlsPolicy?.clientValidationMode ??
346 olds?.mtlsPolicy?.clientValidationMode ??
347 output?.mtlsPolicy?.clientValidationMode ??
348 "") !== "";
349 if (!alb) return undefined;
350 const descriptionChanged =
351 (news.description ?? "") !== (olds?.description ?? output?.description ?? "");
352 const labelsChanged = !sameJson(
353 toLabels(news.labels ?? {}),
354 toLabels(olds?.labels ?? output?.labels ?? {}),
355 );
356 const allowOpenChanged =
357 (news.allowOpen === true) !== (olds?.allowOpen === true || output?.allowOpen === true);
358 const mtlsChanged = !sameJson(
359 toMtlsPolicy(news.mtlsPolicy),
360 toMtlsPolicy(olds?.mtlsPolicy ?? output?.mtlsPolicy),
361 );
362 const certificateChanged = !sameJson(
363 toCertificateProvider(news.serverCertificate),
364 toCertificateProvider(olds?.serverCertificate ?? output?.serverCertificate),
365 );
366 if (
367 descriptionChanged ||
368 labelsChanged ||
369 allowOpenChanged ||
370 mtlsChanged ||
371 certificateChanged
372 ) {
373 return { action: "replace" as const };
374 }
375 return undefined;
376 }),
377
378 read: Effect.fn(function* ({ id, olds, output }) {
379 const env = yield* GcpEnvironment.current;
380 const serverTlsPolicyId = yield* toId(
381 id,
382 olds?.serverTlsPolicyId,
383 output?.serverTlsPolicyId,
384 "servertls",
385 );
386 const location = normalizeLocation(olds?.location ?? output?.location);
387 const name =
388 output?.name ?? resourceName(env.project, location, COLLECTION, serverTlsPolicyId);
389 const existing = yield* getByName(name);
390 if (existing === undefined) return undefined;
391 const attrs = toAttrs(existing, env.project);
392 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
393 }),
394
395 list: () =>
396 Effect.gen(function* () {
397 const env = yield* GcpEnvironment.current;
398 return yield* listOwned(env.project);
399 }),
400
401 reconcile: Effect.fn(function* ({ id, news, output }) {
402 const env = yield* GcpEnvironment.current;
403 const serverTlsPolicyId = yield* toId(
404 id,
405 news.serverTlsPolicyId,
406 output?.serverTlsPolicyId,
407 "servertls",
408 );
409 const location = normalizeLocation(news.location ?? output?.location);
410 const name = resourceName(env.project, location, COLLECTION, serverTlsPolicyId);
411 const desiredLabels = {
412 ...toLabels(news.labels),
413 ...(yield* createInternalLabels(id)),
414 };
415 const allowOpen = news.allowOpen === true;
416 const desiredCertificate = toCertificateProvider(news.serverCertificate);
417 const desiredMtls = toMtlsPolicy(news.mtlsPolicy);
418
419 let current = yield* getByName(output?.name ?? name);
420
421 if (current === undefined) {
422 const created = yield* networksecurity
423 .createProjectsLocationsServerTlsPolicies({
424 parent: parentOf(env.project, location),
425 serverTlsPolicyId,
426 body: toCreateBody(news, desiredLabels),
427 })
428 .pipe(
429 Effect.retry({
430 while: (error) => error._tag === "Conflict",
431 times: 5,
432 schedule: Schedule.spaced("2 seconds"),
433 }),
434 Effect.catchTag("Conflict", () => Effect.undefined),
435 );
436 if (created !== undefined) {
437 yield* waitForOperation(created);
438 }
439 current = yield* waitUntilExists(name);
440 }
441
442 if (current === undefined) {
443 return yield* new ServerTlsPolicyNotResolved({ resourceName: name });
444 }
445
446 const observedLabels = tagRecord(current.labels);
447 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
448 const labelsChanged = upsert.length > 0 || removed.length > 0;
449 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
450 const allowOpenChanged = (current.allowOpen === true) !== allowOpen;
451 const certificateChanged = !sameJson(
452 toCertificateProvider(current.serverCertificate),
453 desiredCertificate,
454 );
455 const mtlsChanged = !sameJson(toMtlsPolicy(current.mtlsPolicy), desiredMtls);
456
457 if (
458 labelsChanged ||
459 descriptionChanged ||
460 allowOpenChanged ||
461 certificateChanged ||
462 mtlsChanged
463 ) {
464 const updateMask = [
465 labelsChanged ? "labels" : undefined,
466 descriptionChanged ? "description" : undefined,
467 allowOpenChanged ? "allowOpen" : undefined,
468 certificateChanged ? "serverCertificate" : undefined,
469 mtlsChanged ? "mtlsPolicy" : undefined,
470 ].filter((field): field is string => field !== undefined);
471 const operation = yield* networksecurity.patchProjectsLocationsServerTlsPolicies({
472 name: current.name ?? name,
473 updateMask: updateMask.join(","),
474 body: {
475 name: current.name ?? name,
476 labels: desiredLabels,
477 description: news.description,
478 allowOpen,
479 serverCertificate: desiredCertificate,
480 mtlsPolicy: desiredMtls,
481 },
482 });
483 yield* waitForOperation(operation);
484 current = yield* waitUntilExists(current.name ?? name);
485 }
486
487 return toAttrs(current, env.project);
488 }),
489
490 delete: Effect.fn(function* ({ output }) {
491 const operation = yield* networksecurity
492 .deleteProjectsLocationsServerTlsPolicies({ name: output.name })
493 .pipe(
494 Effect.retry({
495 while: (error) => error._tag === "Conflict",
496 times: 8,
497 schedule: Schedule.spaced("2 seconds"),
498 }),
499 Effect.catchTag("NotFound", () => Effect.undefined),
500 );
501 if (operation !== undefined) {
502 yield* waitForOperation(operation, { notFoundOk: true });
503 }
504 yield* waitUntilGone(output.name);
505 }),
506 });