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

main
ts 175 lines 6.94 KB
Raw
1 import {
2 GCP_AUTH_PROVIDER_NAME,
3 GcpAuth,
4 parseGcloudLoginOutput,
5 type GcpAuthConfig,
6 type GcpResolvedCredentials,
7 } from "@alchemy.run/gcp/AuthProvider";
8 import { describe, expect, it } from "@alchemy.run/test";
9 import * as NodeServices from "@effect/platform-node/NodeServices";
10 import { AuthProvidersLive, getAuthProvider, presentEnvironment } from "alchemy/Auth/AuthProvider";
11 import { CredentialsStore } from "alchemy/Auth/Credentials";
12 import * as Interaction from "alchemy/Interaction";
13 import * as ConfigProvider from "effect/ConfigProvider";
14 import * as Effect from "effect/Effect";
15 import * as FileSystem from "effect/FileSystem";
16 import * as FetchHttpClient from "effect/http/FetchHttpClient";
17 import * as HttpClient from "effect/http/HttpClient";
18 import * as HttpClientRequest from "effect/http/HttpClientRequest";
19 import * as Layer from "effect/Layer";
20 import * as Path from "effect/Path";
21 import * as Redacted from "effect/Redacted";
22
23 const credentialsStore: CredentialsStore["Service"] = {
24 read: () => Effect.succeed(undefined),
25 write: () => Effect.void,
26 delete: () => Effect.void,
27 deleteProfile: () => Effect.void,
28 scoped: () => credentialsStore,
29 };
30
31 const testLayer = (env: Record<string, string>) =>
32 GcpAuth.pipe(
33 Layer.provideMerge(
34 Layer.mergeAll(
35 NodeServices.layer,
36 AuthProvidersLive,
37 Layer.succeed(CredentialsStore, credentialsStore),
38 ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
39 Interaction.layerNonInteractive(),
40 ),
41 ),
42 );
43
44 const readGcloud = (config: Omit<Extract<GcpAuthConfig, { method: "gcloud" }>, "method">) =>
45 Effect.gen(function* () {
46 const auth = yield* getAuthProvider<GcpAuthConfig, GcpResolvedCredentials>(
47 GCP_AUTH_PROVIDER_NAME,
48 );
49 return yield* auth.read("default", Effect.succeed({ method: "gcloud" as const, ...config }));
50 });
51
52 /**
53 * Runs `effect` with gcloud's config directory set to a fresh one holding
54 * the named `configurations` (gcloud's INI properties files).
55 */
56 const withGcloudConfig = <A, E, R>(
57 effect: Effect.Effect<A, E, R>,
58 configurations: Record<string, string> = {},
59 ) =>
60 Effect.gen(function* () {
61 const fs = yield* FileSystem.FileSystem;
62 const path = yield* Path.Path;
63 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-gcloud-" });
64 yield* fs.makeDirectory(path.join(dir, "configurations"));
65 for (const [name, properties] of Object.entries(configurations)) {
66 yield* fs.writeFileString(path.join(dir, "configurations", `config_${name}`), properties);
67 }
68 return yield* effect.pipe(Effect.provide(testLayer({ CLOUDSDK_CONFIG: dir })));
69 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
70
71 describe("parseGcloudLoginOutput", { tags: ["unit", "provider:gcp", "local"] }, () => {
72 it("reads the authorization URL from gcloud's prompt", () => {
73 expect(
74 parseGcloudLoginOutput(`Your browser has been opened to visit:
75
76 https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=abc&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F
77
78 `),
79 ).toBe(
80 "https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=abc&redirect_uri=http%3A%2F%2Flocalhost%3A8085%2F",
81 );
82 });
83
84 it("waits until the URL has been printed", () => {
85 expect(parseGcloudLoginOutput("Your browser has been opened to visit:\n")).toBeUndefined();
86 });
87 });
88
89 /** The variables that would override the selected profile, given `env`. */
90 const environmentOverride = (env: Record<string, string>) =>
91 Effect.gen(function* () {
92 const auth = yield* getAuthProvider<GcpAuthConfig, GcpResolvedCredentials>(
93 GCP_AUTH_PROVIDER_NAME,
94 );
95 return yield* presentEnvironment(auth.environment ?? []);
96 }).pipe(Effect.provide(testLayer(env)));
97
98 describe("environment credentials", { tags: ["unit", "provider:gcp", "local"] }, () => {
99 it.effect("a project variable alone does not override the profile", () =>
100 Effect.gen(function* () {
101 expect(yield* environmentOverride({ GOOGLE_CLOUD_PROJECT: "p" })).toBeUndefined();
102 }),
103 );
104
105 it.effect("a token or key file overrides the profile", () =>
106 Effect.gen(function* () {
107 expect(
108 yield* environmentOverride({ GOOGLE_ACCESS_TOKEN: "t", GOOGLE_PROJECT_ID: "p" }),
109 ).toEqual(["GOOGLE_ACCESS_TOKEN", "GOOGLE_PROJECT_ID"]);
110 expect(yield* environmentOverride({ GOOGLE_APPLICATION_CREDENTIALS: "/key.json" })).toEqual([
111 "GOOGLE_APPLICATION_CREDENTIALS",
112 ]);
113 }),
114 );
115 });
116
117 describe("gcloud configuration", { tags: ["unit", "provider:gcp", "local"] }, () => {
118 it.effect("rejects a configuration that does not exist", () =>
119 Effect.gen(function* () {
120 const error = yield* withGcloudConfig(readGcloud({ configuration: "work" })).pipe(
121 Effect.flip,
122 );
123 expect(error._tag).toBe("AuthError");
124 expect(error.message).toContain("gcloud configuration 'work' does not exist");
125 expect(error.message).toContain("gcloud config configurations create work --no-activate");
126 }),
127 );
128 });
129
130 describe("gcloud configuration", { tags: ["provider:gcp", "live"] }, () => {
131 it.live("asks for a refresh when the configuration's account has no login", () =>
132 withGcloudConfig(readGcloud({ configuration: "work" }), {
133 work: "[core]\naccount = nobody@example.com\nproject = p\n",
134 }).pipe(
135 Effect.flip,
136 Effect.map((error) => {
137 expect(error._tag).toBe("NeedsReauth");
138 expect(error.message).toContain("gcloud configuration 'work' needs a login");
139 expect(error.message).toContain("alchemy profile refresh --profile default --provider GCP");
140 }),
141 ),
142 );
143 });
144
145 // Needs a named gcloud configuration with a login and a project on this
146 // machine (`gcloud auth login --configuration=<name>`). Set
147 // GCP_TEST_GCLOUD_CONFIGURATION to its name.
148 const gcloudConfiguration = process.env.GCP_TEST_GCLOUD_CONFIGURATION;
149
150 describe.skipIf(!gcloudConfiguration)(
151 "gcloud configuration with a real login",
152 { tags: ["provider:gcp", "live"] },
153 () => {
154 it.live("deploys as the configuration's account into its project", () =>
155 Effect.gen(function* () {
156 const credentials = yield* readGcloud({ configuration: gcloudConfiguration! }).pipe(
157 Effect.provide(testLayer({})),
158 );
159 expect(credentials.source.type).toBe("gcloud");
160 expect(credentials.source.details).toContain(`configuration ${gcloudConfiguration}`);
161 expect(credentials.expiresAt).toBeGreaterThan(Date.now());
162
163 const http = yield* HttpClient.HttpClient;
164 const response = yield* http.execute(
165 HttpClientRequest.get(
166 `https://cloudresourcemanager.googleapis.com/v3/projects/${credentials.project}`,
167 ).pipe(HttpClientRequest.bearerToken(Redacted.value(credentials.accessToken))),
168 );
169 expect(response.status).toBe(200);
170 const project = (yield* response.json) as { projectId: string };
171 expect(project.projectId).toBe(credentials.project);
172 }).pipe(Effect.provide(FetchHttpClient.layer)),
173 );
174 },
175 );