The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { describe, expect } from "bun:test"; |
| 2 | import * as GCP from "@alchemy.run/gcp"; |
| 3 | import * as Test from "@alchemy.run/test/Bun"; |
| 4 | import * as artifactregistry from "@distilled.cloud/gcp/artifactregistry_v1"; |
| 5 | import * as kms from "@distilled.cloud/gcp/cloudkms_v1"; |
| 6 | import * as run from "@distilled.cloud/gcp/run_v2"; |
| 7 | import * as secretmanager from "@distilled.cloud/gcp/secretmanager_v1"; |
| 8 | import * as Alchemy from "alchemy"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 11 | import * as HttpClient from "effect/http/HttpClient"; |
| 12 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 13 | import * as Layer from "effect/Layer"; |
| 14 | import * as Schedule from "effect/Schedule"; |
| 15 | import Stack from "../alchemy.run.ts"; |
| 16 | |
| 17 | const { test, beforeAll, afterAll, deploy, destroy } = Test.make({ |
| 18 | providers: GCP.providers(), |
| 19 | state: Alchemy.localState(), |
| 20 | }); |
| 21 | |
| 22 | const { getWhenReady } = Test; |
| 23 | |
| 24 | // Out-of-band calls to the Google APIs resolve the same stored credentials |
| 25 | // the deploy uses, so the test runs against the configured profile. |
| 26 | const GcpHttp = Layer.mergeAll(GCP.GcpAuth, GCP.fromAuthProvider(), FetchHttpClient.layer); |
| 27 | |
| 28 | const API_KEY = "integ-test-key"; |
| 29 | |
| 30 | // Deploy, tests and destroy all sit behind the same Docker guard. |
| 31 | describe("gcp-secrets-kms", () => { |
| 32 | const stack = beforeAll( |
| 33 | Effect.gen(function* () { |
| 34 | const outputs = yield* deploy(Stack); |
| 35 | // The secret is created empty on purpose — the value is an operator |
| 36 | // step. Add the version the service will read. |
| 37 | yield* secretmanager |
| 38 | .addVersionProjectsSecrets({ |
| 39 | parent: outputs.secretName, |
| 40 | body: { payload: { data: btoa(API_KEY) } }, |
| 41 | }) |
| 42 | .pipe(Effect.orDie, Effect.provide(GcpHttp)); |
| 43 | return outputs; |
| 44 | }), |
| 45 | { timeout: 900_000 }, |
| 46 | ); |
| 47 | |
| 48 | afterAll.skipIf(!!process.env.NO_DESTROY)( |
| 49 | Effect.gen(function* () { |
| 50 | const outputs = yield* stack; |
| 51 | yield* destroy(Stack); |
| 52 | if (outputs === undefined) return; |
| 53 | |
| 54 | // KMS cannot delete a key for at least a day: destroy releases it. |
| 55 | const key = yield* kms |
| 56 | .getProjectsLocationsKeyRingsCryptoKeys({ name: outputs.cryptoKeyName }) |
| 57 | .pipe(Effect.orDie, Effect.provide(GcpHttp)); |
| 58 | expect(Object.keys(key.labels ?? {})).toContain("alchemy-released"); |
| 59 | // Released keys hold no usable key material. |
| 60 | expect(key.primary?.state).not.toBe("ENABLED"); |
| 61 | |
| 62 | const secret = yield* secretmanager.getProjectsSecrets({ name: outputs.secretName }).pipe( |
| 63 | Effect.map(() => "present" as const), |
| 64 | Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)), |
| 65 | Effect.orDie, |
| 66 | Effect.provide(GcpHttp), |
| 67 | ); |
| 68 | expect(secret).toBe("gone"); |
| 69 | |
| 70 | const service = yield* run.getProjectsLocationsServices({ name: outputs.serviceName }).pipe( |
| 71 | Effect.map(() => "present" as const), |
| 72 | Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)), |
| 73 | Effect.orDie, |
| 74 | Effect.provide(GcpHttp), |
| 75 | ); |
| 76 | expect(service).toBe("gone"); |
| 77 | |
| 78 | // The image repository the service was built into goes with it. Its |
| 79 | // id is `{serviceId}-src`, cut to Cloud Run's 49-character limit. |
| 80 | const serviceId = outputs.serviceName.split("/").pop()!; |
| 81 | const repositoryId = `${serviceId}-src`.slice(0, 49).replace(/-+$/, ""); |
| 82 | const repository = yield* artifactregistry |
| 83 | .getProjectsLocationsRepositories({ |
| 84 | name: outputs.serviceName.replace(/services\/.*$/, `repositories/${repositoryId}`), |
| 85 | }) |
| 86 | .pipe( |
| 87 | Effect.map(() => "present" as const), |
| 88 | Effect.catchTag("NotFound", () => Effect.succeed("gone" as const)), |
| 89 | Effect.orDie, |
| 90 | Effect.provide(GcpHttp), |
| 91 | ); |
| 92 | expect(repository).toBe("gone"); |
| 93 | }), |
| 94 | { timeout: 600_000 }, |
| 95 | ); |
| 96 | |
| 97 | const baseUrlOf = (url: string | undefined) => { |
| 98 | if (url === undefined) throw new Error("the service has no URL"); |
| 99 | return url.replace(/\/+$/, ""); |
| 100 | }; |
| 101 | |
| 102 | /** POST JSON, sending `key` as `x-api-key` unless it is `null`. */ |
| 103 | const post = (url: string, body: unknown, key: string | null = API_KEY) => |
| 104 | HttpClient.execute( |
| 105 | HttpClientRequest.post(url).pipe( |
| 106 | key === null ? (request) => request : HttpClientRequest.setHeader("x-api-key", key), |
| 107 | HttpClientRequest.bodyJsonUnsafe(body), |
| 108 | ), |
| 109 | ); |
| 110 | |
| 111 | test( |
| 112 | "rejects a missing or wrong API key with 401", |
| 113 | Effect.gen(function* () { |
| 114 | const { url } = yield* stack; |
| 115 | expect(url).toMatch(/^https:\/\//); |
| 116 | const baseUrl = baseUrlOf(url); |
| 117 | yield* getWhenReady(`${baseUrl}/`); |
| 118 | |
| 119 | const missing = yield* post(`${baseUrl}/encrypt`, { plaintext: "hi" }, null); |
| 120 | expect(missing.status).toBe(401); |
| 121 | |
| 122 | const wrong = yield* post(`${baseUrl}/encrypt`, { plaintext: "hi" }, "no"); |
| 123 | expect(wrong.status).toBe(401); |
| 124 | |
| 125 | const wrongDecrypt = yield* post( |
| 126 | `${baseUrl}/decrypt`, |
| 127 | { ciphertext: "AAAA" }, |
| 128 | "integ-test-kez", |
| 129 | ); |
| 130 | expect(wrongDecrypt.status).toBe(401); |
| 131 | }), |
| 132 | { timeout: 120_000 }, |
| 133 | ); |
| 134 | |
| 135 | test( |
| 136 | "encrypts with KMS and decrypts back, in and out of band", |
| 137 | Effect.gen(function* () { |
| 138 | const { url, cryptoKeyName } = yield* stack; |
| 139 | const baseUrl = baseUrlOf(url); |
| 140 | yield* getWhenReady(`${baseUrl}/`); |
| 141 | |
| 142 | const plaintext = "the eagle lands at midnight"; |
| 143 | |
| 144 | // The KMS grants on a fresh service account can take a minute or two |
| 145 | // to propagate; until then encrypt fails with Forbidden (500). |
| 146 | const encrypted = yield* post(`${baseUrl}/encrypt`, { plaintext }).pipe( |
| 147 | Effect.repeat({ |
| 148 | schedule: Schedule.spaced("10 seconds"), |
| 149 | until: (response) => response.status !== 500, |
| 150 | times: 30, |
| 151 | }), |
| 152 | ); |
| 153 | expect(encrypted.status).toBe(200); |
| 154 | const { ciphertext } = (yield* encrypted.json) as { ciphertext: string }; |
| 155 | expect(ciphertext).toEqual(expect.any(String)); |
| 156 | expect(ciphertext).not.toEqual(plaintext); |
| 157 | expect(ciphertext).not.toEqual(btoa(plaintext)); |
| 158 | expect(atob(ciphertext)).not.toContain(plaintext); |
| 159 | |
| 160 | const decrypted = yield* post(`${baseUrl}/decrypt`, { ciphertext }).pipe( |
| 161 | Effect.repeat({ |
| 162 | schedule: Schedule.spaced("10 seconds"), |
| 163 | until: (response) => response.status !== 500, |
| 164 | times: 30, |
| 165 | }), |
| 166 | ); |
| 167 | expect(decrypted.status).toBe(200); |
| 168 | expect((yield* decrypted.json) as { plaintext: string }).toEqual({ |
| 169 | plaintext, |
| 170 | }); |
| 171 | |
| 172 | // The ciphertext is real KMS output: decrypt it directly with the key. |
| 173 | const direct = yield* kms |
| 174 | .decryptProjectsLocationsKeyRingsCryptoKeys({ |
| 175 | name: cryptoKeyName, |
| 176 | body: { ciphertext }, |
| 177 | }) |
| 178 | .pipe(Effect.orDie, Effect.provide(GcpHttp)); |
| 179 | expect(Buffer.from(direct.plaintext ?? "", "base64").toString("utf8")).toEqual(plaintext); |
| 180 | |
| 181 | // Garbage ciphertext is the caller's error, not a server failure. |
| 182 | const garbage = yield* post(`${baseUrl}/decrypt`, { |
| 183 | ciphertext: btoa("not a kms ciphertext"), |
| 184 | }); |
| 185 | expect(garbage.status).toBe(400); |
| 186 | }), |
| 187 | { timeout: 600_000 }, |
| 188 | ); |
| 189 | }); |