@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 251 lines 9.22 KB
Raw
1 import * as kms from "@distilled.cloud/gcp/cloudkms_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { deterministicKmsId } from "./internal.ts";
10
11 export type KeyRingProps = {
12 /**
13 * Key ring id (the `{keyRing}` segment of
14 * `projects/{project}/locations/{location}/keyRings/{keyRing}`).
15 * If omitted, a deterministic name `{stack}-{id}-{stage}` is derived
16 * (no random suffix), so a redeploy after destroy reuses the same ring
17 * instead of leaking a new one. Must match `[a-zA-Z0-9_-]{1,63}`.
18 * Immutable — changing it replaces the key ring.
19 */
20 keyRingId?: string;
21 /**
22 * Cloud KMS location (`us-central1`, `global`, `us`, …). Immutable —
23 * changing it replaces the key ring. `US-CENTRAL1` is accepted and
24 * normalized to `us-central1`.
25 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
26 */
27 location?: string;
28 };
29
30 export type KeyRing = Resource<
31 "GCP.KMS.KeyRing",
32 KeyRingProps,
33 {
34 /** Full resource name `projects/{project}/locations/{location}/keyRings/{keyRing}`. */
35 name: string;
36 /** Key ring id (last path segment). */
37 keyRingId: string;
38 /** Location id (`us-central1`, `global`, …). */
39 location: string;
40 /** Project id. */
41 project: string;
42 /** RFC3339 creation timestamp. */
43 createTime: string | undefined;
44 },
45 never,
46 Providers
47 >;
48
49 /**
50 * A Cloud KMS KeyRing — a location-scoped container for CryptoKeys.
51 *
52 * Key rings have no labels and no update API. Name and location are
53 * identity; Cloud KMS also has no delete API, so destroy removes the
54 * resource from state only. Account-wide nuke skips this type for the
55 * same reason.
56 *
57 * Because the ring outlives destroy, the default `keyRingId` is
58 * deterministic per stack, stage, and logical id: deploying again after a
59 * destroy adopts the ring left behind rather than creating another one.
60 *
61 * ### Creating a KeyRing
62 * **Example:** Generated name
63 * ```typescript
64 * const keys = yield* GCP.KMS.KeyRing("Keys", {});
65 * ```
66 *
67 * **Example:** Explicit id and location
68 * ```typescript
69 * const keys = yield* GCP.KMS.KeyRing("Keys", {
70 * keyRingId: "app-keys",
71 * location: "us-central1",
72 * });
73 * ```
74 *
75 * @resource
76 * @category KMS
77 */
78 export const KeyRing = Resource<KeyRing>("GCP.KMS.KeyRing");
79
80 export class KeyRingNotResolved extends Data.TaggedError("GCP.KMS.KeyRingNotResolved")<{
81 resourceName: string;
82 }> {}
83
84 const lastSegment = (value: string) => {
85 const trimmed = value.replace(/\/+$/, "");
86 const parts = trimmed.split("/");
87 return parts[parts.length - 1] || trimmed;
88 };
89
90 const normalizeLocation = (location: string | undefined, fallback: string) =>
91 lastSegment(location ?? fallback).toLowerCase();
92
93 const resourceName = (project: string, location: string, keyRingId: string) =>
94 `projects/${project}/locations/${location}/keyRings/${keyRingId}`;
95
96 const parseName = (name: string, fallbackLocation: string) => {
97 const parts = name.split("/").filter((part) => part.length > 0);
98 const keyRingsAt = parts.lastIndexOf("keyRings");
99 const locationsAt = parts.lastIndexOf("locations");
100 const projectsAt = parts.lastIndexOf("projects");
101 return {
102 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
103 location:
104 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
105 keyRingId:
106 keyRingsAt >= 0 && parts[keyRingsAt + 1] ? parts[keyRingsAt + 1]! : lastSegment(name),
107 };
108 };
109
110 const toId = (id: string, keyRingId: string | undefined, existing?: string) =>
111 Effect.gen(function* () {
112 return keyRingId ?? existing ?? (yield* deterministicKmsId(id));
113 });
114
115 const toAttrs = (keyRing: kms.KeyRing, project: string, region: string) => {
116 const name = keyRing.name ?? "";
117 const parsed = parseName(name, region);
118 return {
119 name,
120 keyRingId: parsed.keyRingId,
121 location: parsed.location,
122 project: parsed.project || project,
123 createTime: keyRing.createTime,
124 };
125 };
126
127 const getByName = (name: string) =>
128 kms
129 .getProjectsLocationsKeyRings({ name })
130 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
131
132 const listKeyRingsAt = (parent: string) =>
133 Effect.gen(function* () {
134 const found: kms.KeyRing[] = [];
135 let pageToken: string | undefined;
136 for (let page = 0; page < 10; page++) {
137 const response = yield* kms.listProjectsLocationsKeyRings({
138 parent,
139 pageSize: 1000,
140 pageToken,
141 });
142 found.push(...(response.keyRings ?? []));
143 pageToken = response.nextPageToken;
144 if (pageToken === undefined || pageToken === "") break;
145 }
146 return found;
147 }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as kms.KeyRing[])));
148
149 export const KeyRingProvider = () =>
150 Provider.succeed(KeyRing, {
151 // Cloud KMS has no KeyRing delete API. Destroy forgets state only, so
152 // nuke would loop forever on "deleted but still there".
153 nuke: { skip: true },
154 stables: ["name", "keyRingId", "location", "project", "createTime"],
155
156 diff: Effect.fn(function* ({ news, olds, output }) {
157 if (!isResolved(news)) return undefined;
158 const env = yield* GcpEnvironment.current;
159 const previousId = olds?.keyRingId ?? output?.keyRingId;
160 const nextId = news.keyRingId ?? previousId;
161 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
162
163 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
164 const nextLocation = normalizeLocation(news.location ?? output?.location, env.region);
165 const locationChanged = previousLocation !== nextLocation;
166
167 if (idChanged || locationChanged) {
168 // Cannot delete the old ring; create the replacement first.
169 return { action: "replace" as const, deleteFirst: false };
170 }
171 return undefined;
172 }),
173
174 read: Effect.fn(function* ({ id, olds, output }) {
175 const env = yield* GcpEnvironment.current;
176 const keyRingId = yield* toId(id, olds?.keyRingId, output?.keyRingId);
177 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
178 const name = output?.name ?? resourceName(env.project, location, keyRingId);
179 const existing = yield* getByName(name);
180 if (existing === undefined) return undefined;
181 // KeyRings have no labels, so ownership cannot be checked. A ring at
182 // the deterministic `{stack}-{id}-{stage}` name can only come from an
183 // earlier deploy of this same logical resource (rings are never
184 // deleted, so destroy leaves it behind); adopt it. A ring is an empty
185 // namespace — the keys inside carry their own ownership labels.
186 return toAttrs(existing, env.project, env.region);
187 }),
188
189 list: () =>
190 Effect.gen(function* () {
191 const env = yield* GcpEnvironment.current;
192 const found: ReturnType<typeof toAttrs>[] = [];
193 let pageToken: string | undefined;
194 for (let page = 0; page < 10; page++) {
195 const response = yield* kms.listProjectsLocations({
196 name: `projects/${env.project}`,
197 pageSize: 100,
198 pageToken,
199 });
200 const parents = (response.locations ?? [])
201 .map((location) => location.name)
202 .filter((name): name is string => !!name);
203 const pages = yield* Effect.forEach(parents, (parent) => listKeyRingsAt(parent), {
204 concurrency: 4,
205 });
206 for (const keyRings of pages) {
207 for (const keyRing of keyRings) {
208 found.push(toAttrs(keyRing, env.project, env.region));
209 }
210 }
211 pageToken = response.nextPageToken;
212 if (pageToken === undefined || pageToken === "") break;
213 }
214 return found;
215 }),
216
217 reconcile: Effect.fn(function* ({ id, news, output }) {
218 const env = yield* GcpEnvironment.current;
219 const keyRingId = yield* toId(id, news.keyRingId, output?.keyRingId);
220 const location = normalizeLocation(news.location ?? output?.location, env.region);
221 const name = resourceName(env.project, location, keyRingId);
222
223 // A ring already at this name is adopted as ours (see `read`).
224 let current = yield* getByName(name);
225
226 if (current === undefined) {
227 const created = yield* kms
228 .createProjectsLocationsKeyRings({
229 parent: `projects/${env.project}/locations/${location}`,
230 keyRingId,
231 body: {},
232 })
233 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
234 current = created ?? undefined;
235 }
236
237 if (current === undefined) {
238 return yield* new KeyRingNotResolved({ resourceName: name });
239 }
240
241 return toAttrs(current, env.project, env.region);
242 }),
243
244 delete: Effect.fn(function* ({ output }) {
245 // Cloud KMS has no KeyRing delete API. Forget it from state; the
246 // empty ring remains in the project until Google adds deletion.
247 yield* Effect.logWarning(
248 `GCP Cloud KMS has no KeyRing delete API — "${output.name}" was removed from state but still exists.`,
249 );
250 }),
251 });