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

main
ts 135 lines 4.58 KB
Raw
1 import * as iam from "@distilled.cloud/gcp/unstable/iam_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 * as Redacted from "effect/Redacted";
8 import * as Schedule from "effect/Schedule";
9 import type { Providers } from "../Providers.ts";
10
11 export type ServiceAccountKeyProps = {
12 /**
13 * Email of the service account the key belongs to. Changing it replaces
14 * the key.
15 */
16 serviceAccount: string;
17 };
18
19 export type ServiceAccountKey = Resource<
20 "GCP.IAM.ServiceAccountKey",
21 ServiceAccountKeyProps,
22 {
23 /** Full resource name `projects/{project}/serviceAccounts/{email}/keys/{keyId}`. */
24 name: string;
25 /** Email of the service account the key belongs to. */
26 serviceAccount: string;
27 /** The key's `private_key_id`. */
28 privateKeyId: string;
29 /**
30 * The key's PKCS #8 PEM private key. Google returns it only when the key
31 * is created, so it lives in Alchemy's state.
32 */
33 privateKey: Redacted.Redacted<string>;
34 },
35 never,
36 Providers
37 >;
38
39 /**
40 * A key for a Google Cloud IAM service account, for code that runs outside
41 * GCP and has to sign as the account.
42 *
43 * Prefer running as the service account (Cloud Run, Cloud Functions, GKE
44 * Workload Identity) where you can: a key is a long-lived secret. Some
45 * organizations block key creation with the
46 * `iam.disableServiceAccountKeyCreation` policy.
47 *
48 * ### Creating a Key
49 * **Example:** Key for a service account
50 * ```typescript
51 * const account = yield* GCP.IAM.ServiceAccount("Ci", {});
52 * const key = yield* GCP.IAM.ServiceAccountKey("CiKey", {
53 * serviceAccount: account.email,
54 * });
55 * ```
56 *
57 * @resource
58 * @category IAM
59 */
60 export const ServiceAccountKey = Resource<ServiceAccountKey>("GCP.IAM.ServiceAccountKey");
61
62 export class ServiceAccountKeyInvalid extends Data.TaggedError("GCP.IAM.ServiceAccountKeyInvalid")<{
63 resourceName: string;
64 }> {}
65
66 /** The fields of a `TYPE_GOOGLE_CREDENTIALS_FILE` key that callers need. */
67 const decodeKeyFile = (name: string, privateKeyData: string) =>
68 Effect.try({
69 try: () => {
70 const file = JSON.parse(Buffer.from(privateKeyData, "base64").toString("utf8")) as {
71 private_key_id: string;
72 private_key: string;
73 };
74 return { privateKeyId: file.private_key_id, privateKey: Redacted.make(file.private_key) };
75 },
76 // The cause can quote key material, so it is not attached.
77 catch: () => new ServiceAccountKeyInvalid({ resourceName: name }),
78 });
79
80 const getKey = (name: string) =>
81 iam
82 .getProjectsServiceAccountsKeys({ name })
83 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
84
85 export const ServiceAccountKeyProvider = () =>
86 Provider.succeed(ServiceAccountKey, {
87 stables: ["name", "serviceAccount", "privateKeyId", "privateKey"],
88
89 diff: Effect.fn(function* ({ news, olds }) {
90 if (!isResolved(news)) return undefined;
91 if (olds !== undefined && news.serviceAccount !== olds.serviceAccount) {
92 return { action: "replace" as const };
93 }
94 return undefined;
95 }),
96
97 // A key carries no labels and its private half is only returned on
98 // create, so only a key recorded in state can be read back.
99 read: Effect.fn(function* ({ output }) {
100 if (output === undefined) return undefined;
101 return (yield* getKey(output.name)) === undefined ? undefined : output;
102 }),
103
104 reconcile: Effect.fn(function* ({ news, output }) {
105 // Observe: keep the key we made while it still exists.
106 if (output !== undefined && (yield* getKey(output.name)) !== undefined) return output;
107
108 // Ensure. A new account is eventually consistent: key creation can 404
109 // for a few seconds after the account is created.
110 const key = yield* iam
111 .createProjectsServiceAccountsKeys({
112 name: `projects/-/serviceAccounts/${news.serviceAccount}`,
113 body: { privateKeyType: "TYPE_GOOGLE_CREDENTIALS_FILE" },
114 })
115 .pipe(
116 Effect.retry({
117 while: (error) => error._tag === "NotFound",
118 schedule: Schedule.exponential("500 millis"),
119 times: 8,
120 }),
121 );
122 const name = key.name ?? "";
123 return {
124 name,
125 serviceAccount: news.serviceAccount,
126 ...(yield* decodeKeyFile(name, key.privateKeyData ?? "")),
127 };
128 }),
129
130 delete: Effect.fn(function* ({ output }) {
131 yield* iam
132 .deleteProjectsServiceAccountsKeys({ name: output.name })
133 .pipe(Effect.catchTag("NotFound", () => Effect.void));
134 }),
135 });