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

main
ts 376 lines 12.4 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_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 {
10 deployedConfig,
11 environmentIdOf,
12 environmentNameOf,
13 lastSegment,
14 listProjectEnvironments,
15 missingToUndefined,
16 organizationIdOf,
17 segmentAfter,
18 stripRevision,
19 toResourceId,
20 } from "./common.ts";
21
22 const MAX_NAME_LENGTH = 255;
23 const DEFAULT_FORMAT = "selfsignedcert";
24
25 export type AliasSubject = {
26 /** X.509 common name. */
27 commonName?: string;
28 /** ISO country code. */
29 countryCode?: string;
30 /** Email address. */
31 email?: string;
32 /** Locality. */
33 locality?: string;
34 /** Organization. */
35 org?: string;
36 /** Organizational unit. */
37 orgUnit?: string;
38 /** State or province. */
39 state?: string;
40 };
41
42 export type EnvironmentsKeystoresAliasProps = {
43 /**
44 * Apigee organization id or `organizations/{org}`. Defaults to the
45 * current GCP project id. Immutable — changing it replaces the alias.
46 */
47 organization?: string;
48 /**
49 * Environment id or `organizations/{org}/environments/{env}`. Immutable —
50 * changing it replaces the alias.
51 */
52 environment: string;
53 /**
54 * Parent keystore id or
55 * `organizations/{org}/environments/{env}/keystores/{keystore}`.
56 * Immutable — changing it replaces the alias.
57 */
58 keystore: string;
59 /**
60 * Alias id. If omitted, a unique name is generated from the stack,
61 * stage, and logical id. Must match `[\w\s-.]{1,255}`. Immutable —
62 * changing it replaces the alias.
63 */
64 aliasId?: string;
65 /**
66 * Upload format: `selfsignedcert`, `keycertfile`, or `pkcs12`.
67 * @default "selfsignedcert"
68 */
69 format?: "selfsignedcert" | "keycertfile" | "pkcs12" | (string & {});
70 /**
71 * Skip newline validation between certificates in a chain.
72 * @default false
73 */
74 ignoreNewlineValidation?: boolean;
75 /**
76 * Skip certificate expiry validation.
77 * @default false
78 */
79 ignoreExpiryValidation?: boolean;
80 /**
81 * Private key password when `format` is `keycertfile` or `pkcs12`.
82 */
83 password?: string;
84 /**
85 * RSA key size for `selfsignedcert` (`1024`, `2048`, `4096`).
86 * @default "2048"
87 */
88 keySize?: string;
89 /**
90 * Signature algorithm for `selfsignedcert`.
91 * @default "SHA256withRSA"
92 */
93 sigAlg?: string;
94 /**
95 * Certificate validity in days for `selfsignedcert`.
96 * @default 365
97 */
98 certValidityInDays?: number;
99 /**
100 * X.509 subject for `selfsignedcert`.
101 */
102 subject?: AliasSubject;
103 /**
104 * Subject alternative names for `selfsignedcert`.
105 */
106 subjectAlternativeNames?: string[];
107 /**
108 * PEM certificate (and optional chain) when `format` is `keycertfile`.
109 */
110 certPem?: string;
111 /**
112 * PEM private key when `format` is `keycertfile`.
113 */
114 keyPem?: string;
115 };
116
117 export type EnvironmentsKeystoresAlias = Resource<
118 "GCP.Apigee.EnvironmentsKeystoresAlias",
119 EnvironmentsKeystoresAliasProps,
120 {
121 /** Full resource name `organizations/{org}/environments/{env}/keystores/{keystore}/aliases/{alias}`. */
122 name: string;
123 /** Alias id. */
124 aliasId: string;
125 /** Parent keystore id. */
126 keystoreId: string;
127 /** Apigee organization id. */
128 organizationId: string;
129 /** Environment id. */
130 environmentId: string;
131 /** Alias type (`CERT` or `KEY_CERT`). */
132 type: string | undefined;
133 /** Subject of the leaf certificate, if returned. */
134 subject: string | undefined;
135 /** Certificate expiry in milliseconds since epoch, if returned. */
136 expiryDate: string | undefined;
137 },
138 never,
139 Providers
140 >;
141
142 /**
143 * An alias in an Apigee environment keystore — a certificate or
144 * key/certificate pair used for TLS.
145 *
146 * Aliases have no labels or description, so `list` enumerates every alias
147 * in keystores of Apigee environments mapped to this GCP project.
148 * Name, keystore, organization, and environment are identity. Certificate
149 * material can be rotated with an in-place update.
150 *
151 * ### Creating a Self-Signed Alias
152 * **Example:** Generated self-signed certificate
153 * ```typescript
154 * const keystore = yield* GCP.Apigee.EnvironmentsKeystore("Tls", {
155 * environment: "eval",
156 * });
157 * const alias = yield* GCP.Apigee.EnvironmentsKeystoresAlias("Server", {
158 * environment: "eval",
159 * keystore: keystore.keystoreId,
160 * subject: { commonName: "api.example.com" },
161 * });
162 * ```
163 *
164 * @resource
165 * @category Apigee
166 */
167 export const EnvironmentsKeystoresAlias = Resource<EnvironmentsKeystoresAlias>(
168 "GCP.Apigee.EnvironmentsKeystoresAlias",
169 );
170
171 export class EnvironmentsKeystoresAliasNotResolved extends Data.TaggedError(
172 "GCP.Apigee.EnvironmentsKeystoresAliasNotResolved",
173 )<{
174 resourceName: string;
175 }> {}
176
177 const keystoreIdOf = (value: string) => segmentAfter(value, "keystores") ?? lastSegment(value);
178
179 const resourceName = (
180 organizationId: string,
181 environmentId: string,
182 keystoreId: string,
183 aliasId: string,
184 ) =>
185 `${environmentNameOf(organizationId, environmentId)}/keystores/${keystoreId}/aliases/${aliasId}`;
186
187 const keystoreName = (organizationId: string, environmentId: string, keystoreId: string) =>
188 `${environmentNameOf(organizationId, environmentId)}/keystores/${keystoreId}`;
189
190 const toAttrs = (
191 alias: apigee.GoogleCloudApigeeV1Alias,
192 organizationId: string,
193 environmentId: string,
194 keystoreId: string,
195 ) => {
196 const aliasId = alias.alias ?? lastSegment(alias.alias ?? "");
197 const cert = alias.certsInfo?.certInfo?.[0];
198 const name = resourceName(organizationId, environmentId, keystoreId, aliasId || "alias");
199 return {
200 name,
201 aliasId: aliasId || lastSegment(name),
202 keystoreId,
203 organizationId,
204 environmentId,
205 type: alias.type,
206 subject: cert?.subject,
207 expiryDate: cert?.expiryDate,
208 };
209 };
210
211 const getByName = (name: string) =>
212 missingToUndefined(apigee.getOrganizationsEnvironmentsKeystoresAliases({ name }));
213
214 const selfSignedBody = (
215 aliasId: string,
216 news: EnvironmentsKeystoresAliasProps,
217 ): apigee.GoogleApiHttpBody =>
218 ({
219 alias: aliasId,
220 keySize: news.keySize ?? "2048",
221 sigAlg: news.sigAlg ?? "SHA256withRSA",
222 certValidityInDays: news.certValidityInDays ?? 365,
223 subject: {
224 commonName: news.subject?.commonName ?? news.subjectAlternativeNames?.[0] ?? aliasId,
225 countryCode: news.subject?.countryCode,
226 email: news.subject?.email,
227 locality: news.subject?.locality,
228 org: news.subject?.org,
229 orgUnit: news.subject?.orgUnit,
230 state: news.subject?.state,
231 },
232 subjectAlternativeNames: news.subjectAlternativeNames,
233 }) as apigee.GoogleApiHttpBody;
234
235 const keyCertBody = (news: EnvironmentsKeystoresAliasProps): apigee.GoogleApiHttpBody => ({
236 contentType: "application/x-pem-file",
237 data: news.certPem,
238 });
239
240 const createBody = (
241 aliasId: string,
242 news: EnvironmentsKeystoresAliasProps,
243 ): apigee.GoogleApiHttpBody => {
244 const format = news.format ?? DEFAULT_FORMAT;
245 if (format === "selfsignedcert") return selfSignedBody(aliasId, news);
246 if (news.certPem !== undefined) return keyCertBody(news);
247 return selfSignedBody(aliasId, news);
248 };
249
250 export const EnvironmentsKeystoresAliasProvider = () =>
251 Provider.succeed(EnvironmentsKeystoresAlias, {
252 stables: ["name", "aliasId", "keystoreId", "organizationId", "environmentId"],
253
254 diff: Effect.fn(function* ({ news, olds, output }) {
255 if (!isResolved(news)) return undefined;
256 const previousId = olds?.aliasId ?? output?.aliasId;
257 const previousKeystore = olds?.keystore ?? output?.keystoreId;
258 const previousOrg = olds?.organization ?? output?.organizationId;
259 const previousEnv = olds?.environment ?? output?.environmentId;
260 const idChanged =
261 previousId !== undefined && news.aliasId !== undefined && news.aliasId !== previousId;
262 const keystoreChanged =
263 previousKeystore !== undefined &&
264 keystoreIdOf(news.keystore) !== keystoreIdOf(previousKeystore);
265 const orgChanged =
266 previousOrg !== undefined &&
267 news.organization !== undefined &&
268 organizationIdOf(news.organization, "") !== organizationIdOf(previousOrg, "");
269 const envChanged =
270 previousEnv !== undefined &&
271 environmentIdOf(news.environment) !== environmentIdOf(previousEnv);
272 if (idChanged || keystoreChanged || orgChanged || envChanged) {
273 return { action: "replace" as const, deleteFirst: false };
274 }
275 return undefined;
276 }),
277
278 read: Effect.fn(function* ({ id, olds, output }) {
279 const { project } = yield* GcpEnvironment.current;
280 const organizationId = organizationIdOf(
281 olds?.organization ?? output?.organizationId,
282 project,
283 );
284 const environmentId = environmentIdOf(olds?.environment ?? output?.environmentId ?? "");
285 const keystoreId = keystoreIdOf(olds?.keystore ?? output?.keystoreId ?? "");
286 const aliasId = yield* toResourceId(id, olds?.aliasId, output?.aliasId, {
287 maxLength: MAX_NAME_LENGTH,
288 });
289 const name = output?.name ?? resourceName(organizationId, environmentId, keystoreId, aliasId);
290 const existing = yield* getByName(name);
291 if (existing === undefined) return undefined;
292 return toAttrs(existing, organizationId, environmentId, keystoreId);
293 }),
294
295 list: () =>
296 Effect.gen(function* () {
297 const environments = yield* listProjectEnvironments();
298 const found: EnvironmentsKeystoresAlias["Attributes"][] = [];
299 for (const item of environments) {
300 const config = yield* deployedConfig(item.parent);
301 for (const keystore of config?.keystores ?? []) {
302 const keystoreId = keystoreIdOf(keystore.name ?? "");
303 for (const aliasConfig of keystore.aliases ?? []) {
304 const aliasId = lastSegment(stripRevision(aliasConfig.name ?? ""));
305 if (aliasId.length === 0) continue;
306 const name = resourceName(
307 item.organizationId,
308 item.environmentId,
309 keystoreId,
310 aliasId,
311 );
312 const alias = yield* getByName(name);
313 found.push(
314 toAttrs(
315 alias ?? { alias: aliasId },
316 item.organizationId,
317 item.environmentId,
318 keystoreId,
319 ),
320 );
321 }
322 }
323 }
324 return found;
325 }),
326
327 reconcile: Effect.fn(function* ({ id, news, output }) {
328 const { project } = yield* GcpEnvironment.current;
329 const organizationId = organizationIdOf(news.organization, project);
330 const environmentId = environmentIdOf(news.environment);
331 const keystoreId = keystoreIdOf(news.keystore);
332 const aliasId = yield* toResourceId(id, news.aliasId, output?.aliasId, {
333 maxLength: MAX_NAME_LENGTH,
334 });
335 const parent = keystoreName(organizationId, environmentId, keystoreId);
336 const name = resourceName(organizationId, environmentId, keystoreId, aliasId);
337
338 let current = yield* getByName(output?.name ?? name);
339
340 if (current === undefined) {
341 const created = yield* apigee
342 .createOrganizationsEnvironmentsKeystoresAliases({
343 parent,
344 alias: aliasId,
345 format: news.format ?? DEFAULT_FORMAT,
346 ignoreNewlineValidation: news.ignoreNewlineValidation,
347 ignoreExpiryValidation: news.ignoreExpiryValidation,
348 _password: news.password,
349 body: createBody(aliasId, news),
350 })
351 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
352 current = created ?? undefined;
353 } else if (news.certPem !== undefined) {
354 current = yield* apigee.updateOrganizationsEnvironmentsKeystoresAliases({
355 name,
356 ignoreNewlineValidation: news.ignoreNewlineValidation,
357 ignoreExpiryValidation: news.ignoreExpiryValidation ?? true,
358 body: keyCertBody(news),
359 });
360 }
361
362 if (current === undefined) {
363 return yield* new EnvironmentsKeystoresAliasNotResolved({ resourceName: name });
364 }
365
366 return toAttrs(current, organizationId, environmentId, keystoreId);
367 }),
368
369 delete: Effect.fn(function* ({ output }) {
370 yield* apigee
371 .deleteOrganizationsEnvironmentsKeystoresAliases({
372 name: output.name,
373 })
374 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
375 }),
376 });