@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 493 lines 15.9 KB
Raw
1 import * as kms from "@distilled.cloud/gcp/cloudkms_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 { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const DEFAULT_PROTECTION: kms.ImportJobProtectionLevelEnum = "SOFTWARE";
13 const DEFAULT_IMPORT_METHOD: kms.ImportJobImportMethodEnum = "RSA_OAEP_3072_SHA256_AES_256";
14 const MAX_NAME_LENGTH = 63;
15
16 export type ImportJobProps = {
17 /**
18 * Parent KeyRing. Full name
19 * `projects/{project}/locations/{location}/keyRings/{keyRing}` or the
20 * key ring id (combined with `location`). Immutable — changing it
21 * replaces the import job.
22 */
23 keyRing: string;
24 /**
25 * Cloud KMS location (`us-central1`, `global`, `us`, …). Used when
26 * `keyRing` is a bare id. Immutable — changing it replaces the import
27 * job. `US-CENTRAL1` is accepted and normalized to `us-central1`.
28 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
29 */
30 location?: string;
31 /**
32 * Import job id (the last path segment). If omitted, a unique name is
33 * generated from the stack, stage, and logical id. Must match
34 * `[a-zA-Z0-9_-]{1,63}`. Immutable — changing it replaces the job.
35 */
36 importJobId?: string;
37 /**
38 * Wrapping method for incoming key material. Immutable. Cloud KMS has
39 * no update API, so a later change is ignored unless `importJobId`
40 * also changes.
41 * @default "RSA_OAEP_3072_SHA256_AES_256"
42 */
43 importMethod?: kms.ImportJobImportMethodEnum;
44 /**
45 * Protection level of the wrapping key. Must match the CryptoKey
46 * version template when importing. Immutable.
47 * @default "SOFTWARE"
48 */
49 protectionLevel?: kms.ImportJobProtectionLevelEnum;
50 /**
51 * Backend for `HSM_SINGLE_TENANT` wrapping keys. Immutable.
52 */
53 cryptoKeyBackend?: string;
54 };
55
56 export type ImportJobAttrs = {
57 /** Full resource name `projects/.../importJobs/{importJob}`. */
58 name: string;
59 /** Import job id (last path segment). */
60 importJobId: string;
61 /** Parent KeyRing resource name. */
62 keyRing: string;
63 /** Location id (`us-central1`, `global`, …). */
64 location: string;
65 /** Project id. */
66 project: string;
67 /** Wrapping method. */
68 importMethod: string;
69 /** Protection level of the wrapping key. */
70 protectionLevel: string;
71 /** Current job state (`PENDING_GENERATION`, `ACTIVE`, `EXPIRED`). */
72 state: string | undefined;
73 /** RFC3339 scheduled expiration (typically create + 3 days). */
74 expireTime: string | undefined;
75 /** RFC3339 time the job expired, if `state` is `EXPIRED`. */
76 expireEventTime: string | undefined;
77 /** RFC3339 time the wrapping key was generated. */
78 generateTime: string | undefined;
79 /** RFC3339 creation timestamp. */
80 createTime: string | undefined;
81 /** PEM wrapping public key. Present when `state` is `ACTIVE`. */
82 publicKeyPem: string | undefined;
83 /** Wrapping public key in the requested format, if any. */
84 publicKeyData: string | undefined;
85 /** External / single-tenant HSM backend, if any. */
86 cryptoKeyBackend: string | undefined;
87 };
88
89 export type ImportJob = Resource<
90 "GCP.KMS.ImportJob",
91 ImportJobProps,
92 ImportJobAttrs,
93 never,
94 Providers
95 >;
96
97 /**
98 * A Cloud KMS ImportJob — a wrapping-key job used to import pre-existing
99 * key material into a CryptoKeyVersion.
100 *
101 * Parent KeyRing, location, and id are identity (changing them replaces
102 * the job). `importMethod`, `protectionLevel`, and `cryptoKeyBackend` are
103 * immutable create-only fields. Cloud KMS has no ImportJob delete or
104 * update API; destroy removes the resource from state only. Jobs expire
105 * about 3 days after create and remain as `EXPIRED` residue until Google
106 * garbage-collects them. Account-wide nuke skips this type for the same
107 * reason. ImportJobs have no labels, so `list` returns every job under
108 * listed KeyRings.
109 *
110 * ### Creating an ImportJob
111 * **Example:** Generated name on an existing KeyRing
112 * ```typescript
113 * const ring = yield* GCP.KMS.KeyRing("Keys", {});
114 * const job = yield* GCP.KMS.ImportJob("Wrap", {
115 * keyRing: ring.name,
116 * });
117 * ```
118 *
119 * **Example:** Explicit id, method, and protection level
120 * ```typescript
121 * const job = yield* GCP.KMS.ImportJob("Wrap", {
122 * keyRing: ring.name,
123 * importJobId: "wrap-keys",
124 * importMethod: "RSA_OAEP_4096_SHA256_AES_256",
125 * protectionLevel: "HSM",
126 * });
127 * ```
128 *
129 * @resource
130 * @category KMS
131 */
132 export const ImportJob = Resource<ImportJob>("GCP.KMS.ImportJob");
133
134 export class ImportJobNotResolved extends Data.TaggedError("GCP.KMS.ImportJobNotResolved")<{
135 resourceName: string;
136 }> {}
137
138 export class ImportJobPending extends Data.TaggedError("GCP.KMS.ImportJobPending")<{
139 resourceName: string;
140 state: string;
141 }> {}
142
143 const lastSegment = (value: string) => {
144 const trimmed = value.replace(/\/+$/, "");
145 const parts = trimmed.split("/");
146 return parts[parts.length - 1] || trimmed;
147 };
148
149 const normalizeLocation = (location: string | undefined, fallback: string) =>
150 lastSegment(location ?? fallback).toLowerCase();
151
152 const normalizeProtection = (value: string | undefined): kms.ImportJobProtectionLevelEnum =>
153 !value || value === "PROTECTION_LEVEL_UNSPECIFIED"
154 ? DEFAULT_PROTECTION
155 : (value as kms.ImportJobProtectionLevelEnum);
156
157 const parseName = (name: string, fallbackLocation: string) => {
158 const parts = name.split("/").filter((part) => part.length > 0);
159 const importJobsAt = parts.lastIndexOf("importJobs");
160 const keyRingsAt = parts.lastIndexOf("keyRings");
161 const locationsAt = parts.lastIndexOf("locations");
162 const projectsAt = parts.lastIndexOf("projects");
163 const keyRing = keyRingsAt >= 0 ? parts.slice(0, keyRingsAt + 2).join("/") : "";
164 return {
165 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
166 location:
167 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
168 keyRing,
169 importJobId:
170 importJobsAt >= 0 && parts[importJobsAt + 1] ? parts[importJobsAt + 1]! : lastSegment(name),
171 };
172 };
173
174 const resolveParent = (
175 project: string,
176 keyRing: string,
177 location: string | undefined,
178 region: string,
179 ) => {
180 if (keyRing.includes("/")) {
181 const parsed = parseName(
182 keyRing.includes("/importJobs/") ? keyRing : `${keyRing}/importJobs/_`,
183 region,
184 );
185 return {
186 parent: parsed.keyRing,
187 location: parsed.location,
188 project: parsed.project || project,
189 };
190 }
191 const loc = normalizeLocation(location, region);
192 return {
193 parent: `projects/${project}/locations/${loc}/keyRings/${keyRing}`,
194 location: loc,
195 project,
196 };
197 };
198
199 const resourceName = (parent: string, importJobId: string) => `${parent}/importJobs/${importJobId}`;
200
201 const toId = (id: string, importJobId: string | undefined, existing?: string) =>
202 Effect.gen(function* () {
203 return (
204 importJobId ??
205 existing ??
206 (yield* createPhysicalName({
207 id,
208 maxLength: MAX_NAME_LENGTH,
209 lowercase: true,
210 }))
211 );
212 });
213
214 const toAttrs = (job: kms.ImportJob, project: string, region: string): ImportJobAttrs => {
215 const name = job.name ?? "";
216 const parsed = parseName(name, region);
217 return {
218 name,
219 importJobId: parsed.importJobId,
220 keyRing: parsed.keyRing,
221 location: parsed.location,
222 project: parsed.project || project,
223 importMethod: job.importMethod ?? DEFAULT_IMPORT_METHOD,
224 protectionLevel: job.protectionLevel ?? DEFAULT_PROTECTION,
225 state: job.state,
226 expireTime: job.expireTime,
227 expireEventTime: job.expireEventTime,
228 generateTime: job.generateTime,
229 createTime: job.createTime,
230 publicKeyPem: job.publicKey?.pem,
231 publicKeyData: job.publicKey?.data,
232 cryptoKeyBackend: job.cryptoKeyBackend,
233 };
234 };
235
236 const getByName = (name: string) =>
237 kms
238 .getProjectsLocationsKeyRingsImportJobs({ name })
239 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
240
241 const paginate = <A, E, R>(
242 fetch: (
243 pageToken: string | undefined,
244 ) => Effect.Effect<{ items: A[]; nextPageToken?: string }, E, R>,
245 ) =>
246 Effect.gen(function* () {
247 const found: A[] = [];
248 let pageToken: string | undefined;
249 for (let page = 0; page < 10; page++) {
250 const response = yield* fetch(pageToken);
251 found.push(...response.items);
252 pageToken = response.nextPageToken;
253 if (pageToken === undefined || pageToken === "") break;
254 }
255 return found;
256 });
257
258 const listKeyRingsAt = (parent: string) =>
259 paginate((pageToken) =>
260 kms
261 .listProjectsLocationsKeyRings({
262 parent,
263 pageSize: 1000,
264 pageToken,
265 })
266 .pipe(
267 Effect.map((response) => ({
268 items: response.keyRings ?? [],
269 nextPageToken: response.nextPageToken,
270 })),
271 Effect.catchTag("NotFound", () =>
272 Effect.succeed({
273 items: [] as kms.KeyRing[],
274 nextPageToken: undefined,
275 }),
276 ),
277 ),
278 );
279
280 const listImportJobsInRing = (parent: string) =>
281 paginate((pageToken) =>
282 kms
283 .listProjectsLocationsKeyRingsImportJobs({
284 parent,
285 pageSize: 1000,
286 pageToken,
287 })
288 .pipe(
289 Effect.map((response) => ({
290 items: response.importJobs ?? [],
291 nextPageToken: response.nextPageToken,
292 })),
293 Effect.catchTag("NotFound", () =>
294 Effect.succeed({
295 items: [] as kms.ImportJob[],
296 nextPageToken: undefined,
297 }),
298 ),
299 ),
300 );
301
302 const listImportJobsAt = (locationParent: string) =>
303 Effect.gen(function* () {
304 const rings = yield* listKeyRingsAt(locationParent);
305 const pages = yield* Effect.forEach(
306 rings,
307 (ring) =>
308 ring.name ? listImportJobsInRing(ring.name) : Effect.succeed([] as kms.ImportJob[]),
309 { concurrency: 4 },
310 );
311 return pages.flat();
312 });
313
314 const waitReady = (
315 name: string,
316 ): Effect.Effect<
317 kms.ImportJob,
318 ImportJobNotResolved | ImportJobPending | kms.GetProjectsLocationsKeyRingsImportJobsError,
319 kms.GcpOpContext
320 > => {
321 const probe: Effect.Effect<
322 kms.ImportJob,
323 ImportJobNotResolved | ImportJobPending | kms.GetProjectsLocationsKeyRingsImportJobsError,
324 kms.GcpOpContext
325 > = getByName(name).pipe(
326 Effect.flatMap((job): Effect.Effect<kms.ImportJob, ImportJobNotResolved | ImportJobPending> => {
327 if (job === undefined) {
328 return Effect.fail(new ImportJobNotResolved({ resourceName: name }));
329 }
330 if (job.state === "PENDING_GENERATION") {
331 return Effect.fail(
332 new ImportJobPending({
333 resourceName: name,
334 state: job.state,
335 }),
336 );
337 }
338 return Effect.succeed(job);
339 }),
340 );
341 return probe.pipe(
342 Effect.retry({
343 while: (error) => error._tag === "GCP.KMS.ImportJobPending",
344 times: 8,
345 schedule: Schedule.spaced("500 millis"),
346 }),
347 );
348 };
349
350 export const ImportJobProvider = () =>
351 Provider.succeed(ImportJob, {
352 // Cloud KMS has no ImportJob delete API. Destroy forgets state only,
353 // so nuke would loop forever on "deleted but still there".
354 nuke: { skip: true },
355 stables: [
356 "name",
357 "importJobId",
358 "keyRing",
359 "location",
360 "project",
361 "importMethod",
362 "protectionLevel",
363 "cryptoKeyBackend",
364 "createTime",
365 ],
366
367 diff: Effect.fn(function* ({ news, olds, output }) {
368 if (!isResolved(news)) return undefined;
369 const env = yield* GcpEnvironment.current;
370
371 const previousId = olds?.importJobId ?? output?.importJobId;
372 const nextId = news.importJobId ?? previousId;
373 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
374
375 const previousParent =
376 output?.keyRing ??
377 (olds?.keyRing
378 ? resolveParent("", olds.keyRing, olds.location, env.region).parent
379 : undefined);
380 const nextParent = resolveParent(
381 output?.project ?? "",
382 news.keyRing,
383 news.location ?? output?.location,
384 env.region,
385 ).parent;
386 const parentChanged = previousParent !== undefined && previousParent !== nextParent;
387
388 if (!idChanged && !parentChanged) return undefined;
389 // Cannot delete the old job; create the replacement first.
390 return { action: "replace" as const, deleteFirst: false };
391 }),
392
393 read: Effect.fn(function* ({ id, olds, output }) {
394 const env = yield* GcpEnvironment.current;
395 const importJobId = yield* toId(id, olds?.importJobId, output?.importJobId);
396 const name =
397 output?.name ??
398 (olds?.keyRing || output?.keyRing
399 ? resourceName(
400 resolveParent(
401 env.project,
402 olds?.keyRing ?? output?.keyRing ?? "",
403 olds?.location ?? output?.location,
404 env.region,
405 ).parent,
406 importJobId,
407 )
408 : undefined);
409 if (name === undefined) return undefined;
410 const existing = yield* getByName(name);
411 if (existing === undefined) return undefined;
412 // ImportJobs have no labels, so existence at the computed name is
413 // ownership. Adopting an expired job is harmless.
414 return toAttrs(existing, env.project, env.region);
415 }),
416
417 list: () =>
418 Effect.gen(function* () {
419 const env = yield* GcpEnvironment.current;
420 const found: ImportJobAttrs[] = [];
421 let pageToken: string | undefined;
422 for (let page = 0; page < 10; page++) {
423 const response = yield* kms.listProjectsLocations({
424 name: `projects/${env.project}`,
425 pageSize: 100,
426 pageToken,
427 });
428 const parents = (response.locations ?? [])
429 .map((location) => location.name)
430 .filter((name): name is string => !!name);
431 const batches = yield* Effect.forEach(parents, (parent) => listImportJobsAt(parent), {
432 concurrency: 4,
433 });
434 for (const jobs of batches) {
435 for (const job of jobs) {
436 found.push(toAttrs(job, env.project, env.region));
437 }
438 }
439 pageToken = response.nextPageToken;
440 if (pageToken === undefined || pageToken === "") break;
441 }
442 return found;
443 }),
444
445 reconcile: Effect.fn(function* ({ id, news, output }) {
446 const env = yield* GcpEnvironment.current;
447 const importJobId = yield* toId(id, news.importJobId, output?.importJobId);
448 const parent = resolveParent(
449 env.project,
450 news.keyRing,
451 news.location ?? output?.location,
452 env.region,
453 );
454 const name = resourceName(parent.parent, importJobId);
455 const importMethod = news.importMethod ?? DEFAULT_IMPORT_METHOD;
456 const protectionLevel = normalizeProtection(news.protectionLevel);
457
458 let current = yield* getByName(name);
459
460 if (current === undefined) {
461 const created = yield* kms
462 .createProjectsLocationsKeyRingsImportJobs({
463 parent: parent.parent,
464 importJobId,
465 body: {
466 importMethod,
467 protectionLevel,
468 cryptoKeyBackend: news.cryptoKeyBackend,
469 },
470 })
471 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
472 current = created ?? undefined;
473 }
474
475 if (current === undefined) {
476 return yield* new ImportJobNotResolved({ resourceName: name });
477 }
478
479 if (current.state === "PENDING_GENERATION") {
480 current = yield* waitReady(name);
481 }
482
483 return toAttrs(current, env.project, env.region);
484 }),
485
486 delete: Effect.fn(function* ({ output }) {
487 // Cloud KMS has no ImportJob delete API. Forget it from state; the
488 // job remains until it expires (~3 days) and Google GC's it.
489 yield* Effect.logWarning(
490 `GCP Cloud KMS has no ImportJob delete API — "${output.name}" was removed from state but still exists.`,
491 );
492 }),
493 });