@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 429 lines 14.6 KB
Raw
1 import * as sqladmin from "@distilled.cloud/gcp/sqladmin_v1";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
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 { ALCHEMY_LABEL_PREFIX } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import { recoverIfInstanceMissing, waitForSqlOperation } from "./operations.ts";
14
15 const MAX_COMMON_NAME_LENGTH = 64;
16
17 export type SslCertProps = {
18 /**
19 * Cloud SQL instance id (the `{instance}` segment of
20 * `projects/{project}/instances/{instance}`). Full resource names are
21 * accepted and reduced to the last path segment. Immutable — changing
22 * it replaces the certificate.
23 */
24 instance: string;
25 /**
26 * Common name used to identify the client certificate. If omitted, a
27 * unique name is generated from the stack, stage, and logical id.
28 * Must be distinct from other certificates on the instance. Constrained
29 * to letters, digits, dots, hyphens, underscores, and spaces. Immutable
30 * — changing it replaces the certificate.
31 */
32 commonName?: string;
33 };
34
35 export type SslCert = Resource<
36 "GCP.SQL.SslCert",
37 SslCertProps,
38 {
39 /** Common name used to identify the client certificate. */
40 commonName: string;
41 /** Cloud SQL instance id. */
42 instance: string;
43 /** Project id. */
44 project: string;
45 /** SHA-1 fingerprint; the API id for get/delete. */
46 sha1Fingerprint: string;
47 /** PEM-encoded client certificate. */
48 cert: string | undefined;
49 /**
50 * PEM-encoded private key. Returned only by insert and persisted in
51 * state — subsequent gets omit it.
52 */
53 privateKey: string | undefined;
54 /** Serial number extracted from the certificate. */
55 certSerialNumber: string | undefined;
56 /** RFC3339 creation timestamp. */
57 createTime: string | undefined;
58 /** RFC3339 expiry timestamp. */
59 expirationTime: string | undefined;
60 /** SQL Admin self-link. */
61 selfLink: string | undefined;
62 /**
63 * PEM-encoded server CA certificate from insert. Subsequent gets omit
64 * it, so the value is persisted from the create response.
65 */
66 serverCaCert: string | undefined;
67 },
68 never,
69 Providers
70 >;
71
72 /**
73 * A Cloud SQL client SSL certificate.
74 *
75 * Insert returns the private key once; it is stored on the resource and
76 * cannot be recovered from the API later. Certificates have no labels
77 * field. `list` enumerates certs on alchemy-labeled instances so
78 * `pnpm nuke:gcp` can find leaked rows. Changing `instance` or
79 * `commonName` replaces the certificate. The new certificate is not
80 * usable until the instance is restarted.
81 *
82 * ### Creating a Certificate
83 * **Example:** Generated common name on a Cloud SQL instance
84 * ```typescript
85 * const instance = yield* GCP.SQL.Instance("AppDb", {
86 * tier: "db-f1-micro",
87 * backup: { enabled: false },
88 * });
89 * const cert = yield* GCP.SQL.SslCert("Client", {
90 * instance: instance.instanceName,
91 * });
92 * ```
93 *
94 * **Example:** Explicit common name
95 * ```typescript
96 * const cert = yield* GCP.SQL.SslCert("Client", {
97 * instance: instance.instanceName,
98 * commonName: "app-client",
99 * });
100 * ```
101 *
102 * @resource
103 * @category SQL
104 */
105 export const SslCert = Resource<SslCert>("GCP.SQL.SslCert");
106
107 export class SslCertNotResolved extends Data.TaggedError("GCP.SQL.SslCertNotResolved")<{
108 instance: string;
109 sha1Fingerprint: string;
110 }> {}
111
112 export class SslCertStillExists extends Data.TaggedError("GCP.SQL.SslCertStillExists")<{
113 instance: string;
114 sha1Fingerprint: string;
115 }> {}
116
117 const lastSegment = (value: string) => {
118 const trimmed = value.replace(/\/+$/, "");
119 const parts = trimmed.split("/");
120 return parts[parts.length - 1] || trimmed;
121 };
122
123 const instanceIdOf = (value: string) => lastSegment(value);
124
125 const hasAlchemyInstanceLabels = (labels: Record<string, string | undefined> | null | undefined) =>
126 Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX));
127
128 const sanitizeCommonName = (name: string) => {
129 const mapped = name.replace(/[0-9]/g, (digit) => "abcdefghij"[Number(digit)] ?? "a");
130 let next = mapped.replace(/[^a-zA-Z.\-_ ]/g, "-").replace(/[-\s]+/g, "-");
131 next = next.replace(/^[-. ]+|[-. ]+$/g, "");
132 if (!/^[a-zA-Z]/.test(next)) next = `c${next}`;
133 next = next.slice(0, MAX_COMMON_NAME_LENGTH).replace(/[-. ]+$/g, "");
134 return next.length > 0 ? next : "cert";
135 };
136
137 const toCommonName = (id: string, commonName: string | undefined, existing?: string) =>
138 Effect.gen(function* () {
139 if (commonName !== undefined) return commonName;
140 if (existing !== undefined) return existing;
141 return sanitizeCommonName(
142 yield* createPhysicalName({
143 id,
144 maxLength: MAX_COMMON_NAME_LENGTH,
145 lowercase: true,
146 delimiter: "-",
147 }),
148 );
149 });
150
151 type SslCertSecrets = {
152 privateKey?: string;
153 serverCaCert?: string;
154 };
155
156 const toAttrs = (
157 cert: sqladmin.SslCert,
158 project: string,
159 instance: string,
160 secrets?: SslCertSecrets,
161 ) => ({
162 commonName: cert.commonName ?? "",
163 instance: cert.instance ?? instance,
164 project,
165 sha1Fingerprint: cert.sha1Fingerprint ?? "",
166 cert: cert.cert,
167 privateKey: secrets?.privateKey,
168 certSerialNumber: cert.certSerialNumber,
169 createTime: cert.createTime,
170 expirationTime: cert.expirationTime,
171 selfLink: cert.selfLink,
172 serverCaCert: secrets?.serverCaCert,
173 });
174
175 const getByFingerprint = (project: string, instance: string, sha1Fingerprint: string) =>
176 sha1Fingerprint.length === 0
177 ? Effect.undefined
178 : sqladmin.getSslCerts({ project, instance, sha1Fingerprint }).pipe(
179 Effect.catchTag("NotFound", () => Effect.undefined),
180 recoverIfInstanceMissing(project, instance, () => undefined),
181 );
182
183 const findByCommonName = (project: string, instance: string, commonName: string) =>
184 commonName.length === 0
185 ? Effect.undefined
186 : sqladmin.listSslCerts({ project, instance }).pipe(
187 Effect.map((page) => (page.items ?? []).find((cert) => cert.commonName === commonName)),
188 Effect.catchTag("NotFound", () => Effect.undefined),
189 recoverIfInstanceMissing(project, instance, () => undefined),
190 );
191
192 const observe = (
193 project: string,
194 instance: string,
195 sha1Fingerprint: string | undefined,
196 commonName: string,
197 ) =>
198 Effect.gen(function* () {
199 if (sha1Fingerprint !== undefined && sha1Fingerprint.length > 0) {
200 const byFingerprint = yield* getByFingerprint(project, instance, sha1Fingerprint);
201 if (byFingerprint !== undefined) return byFingerprint;
202 }
203 return yield* findByCommonName(project, instance, commonName);
204 });
205
206 const waitForOperation = (
207 project: string,
208 operation: sqladmin.Operation,
209 options?: { notFoundOk?: boolean },
210 ) =>
211 waitForSqlOperation(project, operation, {
212 budget: "10 minutes",
213 notFoundOk: options?.notFoundOk,
214 });
215
216 const waitUntilExists = (project: string, instance: string, sha1Fingerprint: string) =>
217 getByFingerprint(project, instance, sha1Fingerprint).pipe(
218 Effect.flatMap((cert) =>
219 cert
220 ? Effect.succeed(cert)
221 : Effect.fail(new SslCertNotResolved({ instance, sha1Fingerprint })),
222 ),
223 Effect.retry({
224 while: (error) => error._tag === "GCP.SQL.SslCertNotResolved",
225 times: 8,
226 schedule: Schedule.spaced("1 second"),
227 }),
228 );
229
230 const waitUntilGone = (project: string, instance: string, sha1Fingerprint: string) =>
231 getByFingerprint(project, instance, sha1Fingerprint).pipe(
232 Effect.flatMap((cert) =>
233 cert === undefined
234 ? Effect.void
235 : Effect.fail(new SslCertStillExists({ instance, sha1Fingerprint })),
236 ),
237 Effect.retry({
238 while: (error) => error._tag === "GCP.SQL.SslCertStillExists",
239 times: 10,
240 schedule: Schedule.spaced("1 second"),
241 }),
242 );
243
244 export const SslCertProvider = () =>
245 Provider.succeed(SslCert, {
246 stables: [
247 "commonName",
248 "instance",
249 "project",
250 "sha1Fingerprint",
251 "selfLink",
252 "privateKey",
253 "serverCaCert",
254 "certSerialNumber",
255 "createTime",
256 ],
257
258 diff: Effect.fn(function* ({ news, olds, output }) {
259 if (!isResolved(news)) return undefined;
260 const previousInstance = olds?.instance ?? output?.instance;
261 const nextInstance = news.instance;
262 const previousName = olds?.commonName ?? output?.commonName;
263 const nextName = news.commonName ?? previousName;
264 const instanceChanged =
265 previousInstance !== undefined &&
266 instanceIdOf(previousInstance) !== instanceIdOf(nextInstance);
267 const nameChanged =
268 previousName !== undefined && nextName !== undefined && previousName !== nextName;
269 if (!instanceChanged && !nameChanged) return undefined;
270 return {
271 action: "replace" as const,
272 deleteFirst: false,
273 };
274 }),
275
276 read: Effect.fn(function* ({ id, olds, output }) {
277 const env = yield* GcpEnvironment.current;
278 const instance = instanceIdOf(olds?.instance ?? output?.instance ?? "");
279 if (instance.length === 0) return undefined;
280 const commonName = yield* toCommonName(id, olds?.commonName, output?.commonName);
281 const existing = yield* observe(env.project, instance, output?.sha1Fingerprint, commonName);
282 if (existing === undefined) return undefined;
283 return toAttrs(existing, env.project, instance, {
284 privateKey: output?.privateKey,
285 serverCaCert: output?.serverCaCert,
286 });
287 }),
288
289 list: () =>
290 Effect.gen(function* () {
291 const env = yield* GcpEnvironment.current;
292 const instances = yield* sqladmin.listInstances
293 .items({
294 project: env.project,
295 maxResults: 1000,
296 filter: "instanceType:CLOUD_SQL_INSTANCE",
297 })
298 .pipe(
299 Stream.filter((instance) => hasAlchemyInstanceLabels(instance.settings?.userLabels)),
300 Stream.runCollect,
301 Effect.map((chunk) => Array.from(chunk)),
302 Effect.catchTag("NotFound", () => Effect.succeed([] as sqladmin.DatabaseInstance[])),
303 );
304 const pages = yield* Effect.forEach(
305 instances,
306 (instance) => {
307 const instanceName = instance.name;
308 if (instanceName === undefined || instanceName.length === 0) {
309 return Effect.succeed([] as SslCert["Attributes"][]);
310 }
311 return sqladmin
312 .listSslCerts({
313 project: env.project,
314 instance: instanceName,
315 })
316 .pipe(
317 Effect.map((page) =>
318 (page.items ?? []).map((cert) => toAttrs(cert, env.project, instanceName)),
319 ),
320 // The instance may be deleted mid-listing.
321 Effect.catchTag("NotFound", () => Effect.succeed([] as SslCert["Attributes"][])),
322 recoverIfInstanceMissing(
323 env.project,
324 instanceName,
325 () => [] as SslCert["Attributes"][],
326 ),
327 );
328 },
329 { concurrency: 4 },
330 );
331 return pages.flat();
332 }),
333
334 reconcile: Effect.fn(function* ({ id, news, output }) {
335 const env = yield* GcpEnvironment.current;
336 const instance = instanceIdOf(news.instance);
337 const commonName = yield* toCommonName(id, news.commonName, output?.commonName);
338
339 let current = yield* observe(env.project, instance, output?.sha1Fingerprint, commonName);
340 let secrets: SslCertSecrets = {
341 privateKey: output?.privateKey,
342 serverCaCert: output?.serverCaCert,
343 };
344
345 if (current === undefined) {
346 const inserted = yield* sqladmin
347 .insertSslCerts({
348 project: env.project,
349 instance,
350 body: { commonName },
351 })
352 .pipe(
353 Effect.tap((response) =>
354 response.operation ? waitForOperation(env.project, response.operation) : Effect.void,
355 ),
356 Effect.catchTag("Conflict", (error) =>
357 findByCommonName(env.project, instance, commonName).pipe(
358 Effect.flatMap((existing) => (existing ? Effect.undefined : Effect.fail(error))),
359 ),
360 ),
361 Effect.retry({
362 while: (error) => error._tag === "Conflict",
363 times: 8,
364 schedule: Schedule.spaced("5 seconds"),
365 }),
366 );
367
368 if (inserted !== undefined) {
369 secrets = {
370 privateKey: inserted.clientCert?.certPrivateKey ?? secrets.privateKey,
371 serverCaCert: inserted.serverCaCert?.cert ?? secrets.serverCaCert,
372 };
373 const fingerprint = inserted.clientCert?.certInfo?.sha1Fingerprint ?? "";
374 current =
375 inserted.clientCert?.certInfo ??
376 (fingerprint.length > 0
377 ? yield* waitUntilExists(env.project, instance, fingerprint)
378 : yield* findByCommonName(env.project, instance, commonName));
379 } else {
380 current = yield* findByCommonName(env.project, instance, commonName);
381 }
382 }
383
384 if (current === undefined || (current.sha1Fingerprint ?? "").length === 0) {
385 return yield* new SslCertNotResolved({
386 instance,
387 sha1Fingerprint: current?.sha1Fingerprint ?? "",
388 });
389 }
390
391 if ((current.cert ?? "").length === 0) {
392 current = yield* waitUntilExists(env.project, instance, current.sha1Fingerprint ?? "");
393 }
394
395 return toAttrs(current, env.project, instance, secrets);
396 }),
397
398 delete: Effect.fn(function* ({ olds, output }) {
399 const project = output.project;
400 const instance = instanceIdOf(output.instance);
401 let sha1Fingerprint = output.sha1Fingerprint;
402 if (sha1Fingerprint.length === 0) {
403 const existing = yield* findByCommonName(
404 project,
405 instance,
406 output.commonName || olds.commonName || "",
407 );
408 sha1Fingerprint = existing?.sha1Fingerprint ?? "";
409 }
410 if (sha1Fingerprint.length === 0) return;
411 yield* sqladmin
412 .deleteSslCerts({
413 project,
414 instance,
415 sha1Fingerprint,
416 })
417 .pipe(
418 Effect.flatMap((operation) => waitForOperation(project, operation, { notFoundOk: true })),
419 Effect.catchTag("NotFound", () => Effect.void),
420 recoverIfInstanceMissing(project, instance, () => undefined),
421 Effect.retry({
422 while: (error) => error._tag === "Conflict",
423 times: 8,
424 schedule: Schedule.spaced("5 seconds"),
425 }),
426 );
427 yield* waitUntilGone(project, instance, sha1Fingerprint);
428 }),
429 });