@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, 04:45 UTC

main
ts 852 lines 30.3 KB
Raw
1 import * as NodeOs from "node:os";
2 import {
3 AuthError,
4 AuthProviderLayer,
5 NeedsReauth,
6 reconfigureHint,
7 refreshHint,
8 type ConfigureField,
9 type ConfigureMethod,
10 type ProviderDetails,
11 } from "alchemy/Auth/AuthProvider";
12 import { CredentialsStore, displayRedacted } from "alchemy/Auth/Credentials";
13 import { getEnv, getEnvRedacted, mapPromptCancellation } from "alchemy/Auth/Env";
14 import * as Interaction from "alchemy/Interaction";
15 import { exec } from "alchemy/Util/exec";
16 import * as Deferred from "effect/Deferred";
17 import * as Effect from "effect/Effect";
18 import * as Fiber from "effect/Fiber";
19 import * as FileSystem from "effect/FileSystem";
20 import * as Match from "effect/Match";
21 import * as Path from "effect/Path";
22 import { ChildProcess } from "effect/process";
23 import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
24 import * as Redacted from "effect/Redacted";
25 import * as Ref from "effect/Ref";
26 import * as Schema from "effect/Schema";
27 import * as Stream from "effect/Stream";
28 import { mintAccessToken, parseServiceAccountKey, type ServiceAccountKey } from "./Token.ts";
29
30 export const GCP_AUTH_PROVIDER_NAME = "GCP";
31 export const GOOGLE_ACCESS_TOKEN_ENV = "GOOGLE_ACCESS_TOKEN";
32 export const GOOGLE_PROJECT_ID_ENV = "GOOGLE_PROJECT_ID";
33 export const GOOGLE_CLOUD_PROJECT_ENV = "GOOGLE_CLOUD_PROJECT";
34 export const GOOGLE_APPLICATION_CREDENTIALS_ENV = "GOOGLE_APPLICATION_CREDENTIALS";
35 /** Overrides gcloud's configuration directory (default `~/.config/gcloud`). */
36 export const CLOUDSDK_CONFIG_ENV = "CLOUDSDK_CONFIG";
37 /** Region when neither the environment nor the profile names one. */
38 export const DEFAULT_GCP_REGION = "us-central1";
39
40 /**
41 * Default region for regional resources created without an explicit
42 * location. Like the project, it is part of the profile.
43 */
44 const region = Schema.optionalKey(Schema.String);
45
46 export const GcpAuthConfigSchema = Schema.Union([
47 Schema.Struct({
48 method: Schema.Literal("gcloud"),
49 /**
50 * Named gcloud configuration (`gcloud config configurations list`) to
51 * sign in with, like an AWS named profile. Its account, project and
52 * `compute/region` apply without activating it.
53 */
54 configuration: Schema.String,
55 /** Project to deploy into; defaults to the configuration's project. */
56 project: Schema.optionalKey(Schema.String),
57 region,
58 }),
59 Schema.Struct({
60 method: Schema.Literal("serviceAccount"),
61 credentialsFile: Schema.optionalKey(Schema.String),
62 region,
63 }),
64 Schema.Struct({ method: Schema.Literal("stored"), region }),
65 ]);
66 export type GcpAuthConfig = typeof GcpAuthConfigSchema.Type;
67
68 export const GcpStoredCredentialsSchema = Schema.Union([
69 Schema.Struct({
70 type: Schema.Literal("token"),
71 accessToken: Schema.String,
72 project: Schema.String,
73 }),
74 Schema.Struct({
75 type: Schema.Literal("serviceAccount"),
76 json: Schema.String,
77 project: Schema.optionalKey(Schema.String),
78 }),
79 ]);
80 export type GcpStoredCredentials = typeof GcpStoredCredentialsSchema.Type;
81
82 export type GcpResolvedCredentials = {
83 type: "token";
84 accessToken: Redacted.Redacted<string>;
85 project: string;
86 /** Default region: the profile's, else the gcloud configuration's `compute/region`, else `us-central1`. */
87 region: string;
88 /** Epoch millis when a minted service-account token expires; absent for supplied tokens. */
89 expiresAt?: number;
90 source: { type: GcpAuthConfig["method"] | "env"; details?: string };
91 };
92
93 const options: Array<{
94 value: GcpAuthConfig["method"];
95 label: string;
96 description?: string;
97 }> = [
98 {
99 value: "gcloud",
100 label: "gcloud login",
101 description: "your Google account, through a gcloud configuration",
102 },
103 {
104 value: "serviceAccount",
105 label: "Service account JSON",
106 description: "path to a service-account key file",
107 },
108 {
109 value: "stored",
110 label: "Stored",
111 description: "token or key stored in ~/.alchemy/credentials",
112 },
113 ];
114
115 export const GcpAuth = AuthProviderLayer<GcpAuthConfig, GcpResolvedCredentials>()(
116 GCP_AUTH_PROVIDER_NAME,
117 Effect.gen(function* () {
118 const store = yield* CredentialsStore;
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 const spawner = yield* ChildProcessSpawner;
122 const readKeyFile = (path: string): Effect.Effect<ServiceAccountKey, AuthError> =>
123 fs.readFileString(path).pipe(
124 Effect.flatMap(parseServiceAccountKey),
125 Effect.mapError((e) =>
126 AuthError.make({
127 message: `Failed to read service-account key at ${path}`,
128 cause: e,
129 }),
130 ),
131 );
132
133 // Minted tokens are cached by the `Credentials` layer until shortly
134 // before `expiresAt` (see `lazyCredentials`), not here.
135 const mint = (
136 sa: ServiceAccountKey,
137 project: string,
138 ): Effect.Effect<Omit<GcpResolvedCredentials, "region">, AuthError> =>
139 mintAccessToken(sa).pipe(
140 Effect.map((minted) => ({
141 type: "token" as const,
142 accessToken: minted.accessToken,
143 project,
144 expiresAt: minted.expirationMs,
145 source: {
146 type: "serviceAccount" as const,
147 details: sa.client_email,
148 },
149 })),
150 );
151
152 const resolveFromServiceAccount = (
153 sa: ServiceAccountKey,
154 explicitProject?: string,
155 ): Effect.Effect<Omit<GcpResolvedCredentials, "region">, AuthError> => {
156 const project = explicitProject ?? sa.project_id;
157 if (!project) {
158 return Effect.fail(
159 AuthError.make({
160 message: `Set ${GOOGLE_PROJECT_ID_ENV} (service-account JSON has no project_id)`,
161 }),
162 );
163 }
164 return mint(sa, project);
165 };
166
167 const gcloudConfigDir = Effect.gen(function* () {
168 const configDir = yield* getEnv(CLOUDSDK_CONFIG_ENV);
169 if (configDir) return configDir;
170 const platform = yield* Effect.sync(() => process.platform);
171 const appData = platform === "win32" ? yield* getEnv("APPDATA") : undefined;
172 if (appData) return path.join(appData, "gcloud");
173 const home = yield* Effect.sync(() => NodeOs.homedir());
174 return path.join(home, ".config", "gcloud");
175 });
176
177 /** gcloud reads `CLOUDSDK_CONFIG` itself; pass on the one Alchemy resolved. */
178 const gcloudEnv = getEnv(CLOUDSDK_CONFIG_ENV).pipe(
179 Effect.map((dir): Record<string, string> => (dir ? { [CLOUDSDK_CONFIG_ENV]: dir } : {})),
180 );
181
182 const runGcloud = Effect.fn(function* (args: ReadonlyArray<string>) {
183 const env = yield* gcloudEnv;
184 return yield* exec(
185 ChildProcess.make("gcloud", [...args], {
186 env: { ...env, CLOUDSDK_CORE_DISABLE_PROMPTS: "1" },
187 extendEnv: true,
188 }),
189 ).pipe(
190 Effect.scoped,
191 Effect.mapError(gcloudNotInstalled),
192 Effect.provideService(ChildProcessSpawner, spawner),
193 );
194 });
195
196 const configurationExists = (configuration: string) =>
197 gcloudConfigDir.pipe(
198 Effect.flatMap((dir) =>
199 fs.exists(path.join(dir, "configurations", `config_${configuration}`)),
200 ),
201 Effect.orElseSucceed(() => false),
202 );
203
204 const listGcloudConfigurations = runGcloud([
205 "config",
206 "configurations",
207 "list",
208 "--format=value(name)",
209 ]).pipe(
210 Effect.map(({ exitCode, stdout }) =>
211 exitCode === 0
212 ? stdout
213 .split("\n")
214 .map((line) => line.trim())
215 .filter((line) => line.length > 0)
216 : [],
217 ),
218 );
219
220 /**
221 * A fresh access token plus the properties of a named gcloud
222 * configuration. `config-helper` refreshes the configuration's account
223 * (and honors `auth/impersonate_service_account`) without activating it.
224 */
225 const readGcloudConfiguration = Effect.fn(function* (
226 profileName: string,
227 configuration: string,
228 ) {
229 if (!(yield* configurationExists(configuration))) {
230 return yield* AuthError.make({
231 message: `GCP: gcloud configuration '${configuration}' does not exist. Create it with \`gcloud config configurations create ${configuration} --no-activate\`, or ${reconfigureHint(GCP_AUTH_PROVIDER_NAME, profileName)}`,
232 });
233 }
234 const { exitCode, stdout, stderr } = yield* runGcloud([
235 "config",
236 "config-helper",
237 "--format=json",
238 `--configuration=${configuration}`,
239 ]);
240 if (exitCode !== 0) {
241 const detail = stderr
242 .split("\n")
243 .find((line) => line.startsWith("ERROR:"))
244 ?.replace(/^ERROR: \([^)]*\) /, "");
245 return yield* NeedsReauth.make({
246 provider: GCP_AUTH_PROVIDER_NAME,
247 profile: profileName,
248 message: `GCP: gcloud configuration '${configuration}' needs a login${detail ? ` (${detail})` : ""}. ${refreshHint(GCP_AUTH_PROVIDER_NAME, profileName)}`,
249 });
250 }
251 return yield* Schema.decodeEffect(Schema.fromJsonString(ConfigHelperOutput))(stdout).pipe(
252 Effect.mapError((cause) =>
253 AuthError.make({
254 message: `GCP: unexpected output from gcloud config config-helper`,
255 cause,
256 }),
257 ),
258 );
259 });
260
261 /** Creates the configuration if needed, then runs `gcloud auth login` in it. */
262 const loginGcloudConfiguration = Effect.fn(function* (configuration: string) {
263 if (!(yield* configurationExists(configuration))) {
264 const created = yield* runGcloud([
265 "config",
266 "configurations",
267 "create",
268 configuration,
269 "--no-activate",
270 ]);
271 if (created.exitCode !== 0) {
272 return yield* AuthError.make({
273 message: `gcloud config configurations create ${configuration} exited with code ${created.exitCode}: ${created.stderr.trim()}`,
274 });
275 }
276 }
277 yield* loginGcloud(["auth", "login", `--configuration=${configuration}`], yield* gcloudEnv);
278 });
279
280 /** The configuration's account, project and region, refreshed by gcloud. */
281 const resolveFromGcloud = Effect.fn(function* (
282 profileName: string,
283 config: Extract<GcpAuthConfig, { method: "gcloud" }>,
284 ) {
285 const { configuration } = config;
286 const { configuration: gcloud, credential } = yield* readGcloudConfiguration(
287 profileName,
288 configuration,
289 );
290 const { core, compute } = gcloud.properties;
291 const project = config.project ?? core?.project ?? undefined;
292 if (!project) {
293 return yield* AuthError.make({
294 message: `GCP: gcloud configuration '${configuration}' has no project. Set one with \`gcloud config set project <project> --configuration=${configuration}\`, or ${reconfigureHint(GCP_AUTH_PROVIDER_NAME, profileName)}`,
295 });
296 }
297 const expiresAt = credential.token_expiry ? Date.parse(credential.token_expiry) : NaN;
298 const account = core?.account ?? undefined;
299 return {
300 type: "token" as const,
301 accessToken: Redacted.make(credential.access_token),
302 project,
303 ...(Number.isNaN(expiresAt) ? {} : { expiresAt }),
304 ...(compute?.region ? { gcloudRegion: compute.region } : {}),
305 source: {
306 type: "gcloud" as const,
307 details: `configuration ${configuration}${account ? ` (${account})` : ""}`,
308 },
309 };
310 });
311
312 const loginStored = Effect.fn(function* (profileName: string) {
313 const kind = yield* Interaction.select({
314 message: "GCP stored credential type",
315 options: [
316 {
317 value: "token" as const,
318 label: "Access token",
319 description: "paste a bearer token from gcloud auth print-access-token",
320 },
321 {
322 value: "serviceAccount" as const,
323 label: "Service account JSON",
324 description: "paste the key file contents",
325 },
326 ],
327 }).pipe(mapPromptCancellation);
328
329 const project = yield* Interaction.text({
330 message: "GCP project id",
331 validate: (v) => (v.length === 0 ? "Required" : undefined),
332 }).pipe(mapPromptCancellation);
333
334 if (kind === "token") {
335 const accessToken = yield* Interaction.password({
336 message: "Google access token",
337 validate: (v) => (v.length === 0 ? "Required" : undefined),
338 }).pipe(mapPromptCancellation);
339 yield* store.write(profileName, GCP_AUTH_PROVIDER_NAME, GcpStoredCredentialsSchema, {
340 type: "token",
341 accessToken,
342 project,
343 });
344 } else {
345 const json = yield* Interaction.password({
346 message: "Service account JSON",
347 validate: (v) => (v.length === 0 ? "Required" : undefined),
348 }).pipe(mapPromptCancellation);
349 yield* parseServiceAccountKey(json);
350 yield* store.write(profileName, GCP_AUTH_PROVIDER_NAME, GcpStoredCredentialsSchema, {
351 type: "serviceAccount",
352 json,
353 project,
354 });
355 }
356 yield* Interaction.success("GCP: credentials saved.");
357 return { method: "stored" as const };
358 });
359
360 /**
361 * Sign in to a named gcloud configuration if it has no working login.
362 * The project and region follow the configuration unless it has none.
363 */
364 const configureConfiguration = Effect.fn(function* (
365 profileName: string,
366 configuration: string,
367 ) {
368 const read = readGcloudConfiguration(profileName, configuration);
369 const gcloud = yield* read.pipe(
370 Effect.catchTag("NeedsReauth", () =>
371 loginGcloudConfiguration(configuration).pipe(Effect.andThen(read)),
372 ),
373 Effect.catchTag("AuthError", () =>
374 loginGcloudConfiguration(configuration).pipe(Effect.andThen(read)),
375 ),
376 );
377 const { core, compute } = gcloud.configuration.properties;
378 const project = core?.project
379 ? undefined
380 : yield* Interaction.text({
381 message: "GCP project id",
382 validate: (v) => (v.length === 0 ? "Required" : undefined),
383 }).pipe(mapPromptCancellation);
384 const region = compute?.region ? undefined : yield* promptRegion;
385 return {
386 method: "gcloud" as const,
387 configuration,
388 ...(project ? { project: project.trim() } : {}),
389 ...(region ? { region } : {}),
390 };
391 });
392
393 const NEW_CONFIGURATION = "@new";
394
395 const configureGcloud = Effect.fn(function* (profileName: string) {
396 const configurations = yield* listGcloudConfigurations;
397 const choice = yield* Interaction.select({
398 message: "gcloud credentials",
399 options: [
400 ...configurations.map((name) => ({
401 value: name,
402 label: name,
403 description: "gcloud configuration",
404 })),
405 {
406 value: NEW_CONFIGURATION,
407 label: "New configuration",
408 description: "create a gcloud configuration and sign in to it",
409 },
410 ],
411 }).pipe(mapPromptCancellation);
412 const configuration =
413 choice === NEW_CONFIGURATION
414 ? (yield* Interaction.text({
415 message: "gcloud configuration name",
416 validate: (v) =>
417 /^[a-z][-a-z0-9]*$/.test(v)
418 ? undefined
419 : "Lowercase letters, digits and hyphens, starting with a letter",
420 }).pipe(mapPromptCancellation)).trim()
421 : choice;
422 return yield* configureConfiguration(profileName, configuration);
423 });
424
425 const configureInteractive = (profileName: string) =>
426 Interaction.select({
427 message: "GCP authentication method",
428 options,
429 }).pipe(
430 mapPromptCancellation,
431 Effect.flatMap((method) =>
432 Match.value(method).pipe(
433 Match.when("gcloud", () => configureGcloud(profileName)),
434 Match.when("serviceAccount", () =>
435 Interaction.text({
436 message: `Path to service-account JSON (Enter for $${GOOGLE_APPLICATION_CREDENTIALS_ENV})`,
437 placeholder: `$${GOOGLE_APPLICATION_CREDENTIALS_ENV}`,
438 }).pipe(
439 mapPromptCancellation,
440 Effect.map((path) => {
441 const trimmed = (path ?? "").trim();
442 return {
443 method: "serviceAccount" as const,
444 ...(trimmed.length > 0 ? { credentialsFile: trimmed } : {}),
445 };
446 }),
447 ),
448 ),
449 Match.when("stored", () => loginStored(profileName)),
450 Match.exhaustive,
451 ),
452 ),
453 );
454
455 const promptRegion = Interaction.text({
456 message: "Default GCP region",
457 placeholder: DEFAULT_GCP_REGION,
458 }).pipe(
459 mapPromptCancellation,
460 Effect.map((value) => (value ?? "").trim() || DEFAULT_GCP_REGION),
461 );
462
463 const configureCredentials = (_profileName: string) =>
464 configureInteractive(_profileName).pipe(
465 // The gcloud flow asks for a region only when gcloud has none.
466 Effect.flatMap((config) =>
467 config.method === "gcloud"
468 ? Effect.succeed<GcpAuthConfig>(config)
469 : promptRegion.pipe(Effect.map((region) => ({ ...config, region }))),
470 ),
471 Effect.mapError((e) =>
472 AuthError.make({
473 message: "failed to configure credentials",
474 cause: e,
475 }),
476 ),
477 );
478
479 const regionField: ConfigureField = {
480 name: "region",
481 label: "Default GCP region",
482 placeholder: DEFAULT_GCP_REGION,
483 optional: true,
484 };
485
486 const serviceAccountFields: ReadonlyArray<ConfigureField> = [
487 {
488 name: "credentialsFile",
489 label: "Path to service-account JSON",
490 optional: true,
491 },
492 regionField,
493 ];
494
495 const gcloudFields: ReadonlyArray<ConfigureField> = [
496 {
497 name: "configuration",
498 label: "gcloud configuration name",
499 },
500 { name: "project", label: "GCP project id", optional: true },
501 regionField,
502 ];
503
504 const configureMethods: ReadonlyArray<ConfigureMethod> = [
505 { method: "gcloud", fields: gcloudFields },
506 { method: "serviceAccount", fields: serviceAccountFields },
507 ];
508
509 const regionOf = (values: Record<string, string>) => {
510 const value = (values.region ?? "").trim();
511 return value.length > 0 ? { region: value } : {};
512 };
513
514 const configureWith = (
515 _profileName: string,
516 input: {
517 readonly method: string;
518 readonly values: Record<string, string>;
519 },
520 ): Effect.Effect<GcpAuthConfig, AuthError> => {
521 if (input.method === "gcloud") {
522 // `gcloud auth login` is interactive, so it is
523 // NOT run here; the user runs `alchemy profile refresh` afterwards.
524 const configuration = (input.values.configuration ?? "").trim();
525 if (configuration.length === 0) {
526 return Effect.fail(
527 AuthError.make({
528 message:
529 "GCP: --method gcloud needs a configuration, e.g. --set configuration=work (see `gcloud config configurations list`).",
530 }),
531 );
532 }
533 const project = (input.values.project ?? "").trim();
534 return Effect.succeed({
535 method: "gcloud" as const,
536 configuration,
537 ...(project.length > 0 ? { project } : {}),
538 ...regionOf(input.values),
539 });
540 }
541 if (input.method === "serviceAccount") {
542 const trimmed = (input.values.credentialsFile ?? "").trim();
543 return Effect.succeed({
544 method: "serviceAccount" as const,
545 ...(trimmed.length > 0 ? { credentialsFile: trimmed } : {}),
546 ...regionOf(input.values),
547 });
548 }
549 return Effect.fail(
550 AuthError.make({
551 message: `GCP: unknown method '${input.method}'. Valid methods: gcloud, serviceAccount. (stored is interactive-only.)`,
552 }),
553 );
554 };
555
556 const resolveFromEnv = (): Effect.Effect<Omit<GcpResolvedCredentials, "region">, AuthError> =>
557 Effect.gen(function* () {
558 const project =
559 (yield* getEnv(GOOGLE_PROJECT_ID_ENV)) ?? (yield* getEnv(GOOGLE_CLOUD_PROJECT_ENV));
560 const token = yield* getEnvRedacted(GOOGLE_ACCESS_TOKEN_ENV);
561 if (token) {
562 if (!project) {
563 return yield* AuthError.make({
564 message: `GCP env credentials missing ${GOOGLE_PROJECT_ID_ENV}`,
565 });
566 }
567 return {
568 type: "token" as const,
569 accessToken: token,
570 project,
571 source: { type: "env" as const, details: GOOGLE_ACCESS_TOKEN_ENV },
572 };
573 }
574 const keyPath = yield* getEnv(GOOGLE_APPLICATION_CREDENTIALS_ENV);
575 if (!keyPath) {
576 return yield* AuthError.make({
577 message: `GCP env credentials not found. Set ${GOOGLE_ACCESS_TOKEN_ENV}+${GOOGLE_PROJECT_ID_ENV} or ${GOOGLE_APPLICATION_CREDENTIALS_ENV}.`,
578 });
579 }
580 const sa = yield* readKeyFile(keyPath);
581 return yield* resolveFromServiceAccount(sa, project);
582 });
583
584 const resolveFromServiceAccountFile = (
585 credentialsFile: string | undefined,
586 ): Effect.Effect<Omit<GcpResolvedCredentials, "region">, AuthError> =>
587 Effect.gen(function* () {
588 const fromEnv = yield* getEnv(GOOGLE_APPLICATION_CREDENTIALS_ENV);
589 const path = credentialsFile ?? fromEnv;
590 if (!path) {
591 return yield* AuthError.make({
592 message: `GCP service-account key not found. Set ${GOOGLE_APPLICATION_CREDENTIALS_ENV}.`,
593 });
594 }
595 const sa = yield* readKeyFile(path);
596 const project =
597 (yield* getEnv(GOOGLE_PROJECT_ID_ENV)) ?? (yield* getEnv(GOOGLE_CLOUD_PROJECT_ENV));
598 return yield* resolveFromServiceAccount(sa, project);
599 });
600
601 const resolveFromStored = (
602 profileName: string,
603 ): Effect.Effect<Omit<GcpResolvedCredentials, "region">, AuthError | NeedsReauth> =>
604 Effect.gen(function* () {
605 const creds = yield* store.read(
606 profileName,
607 GCP_AUTH_PROVIDER_NAME,
608 GcpStoredCredentialsSchema,
609 );
610 if (creds == null) {
611 return yield* NeedsReauth.make({
612 provider: GCP_AUTH_PROVIDER_NAME,
613 profile: profileName,
614 message: `GCP stored credentials not found. ${refreshHint(GCP_AUTH_PROVIDER_NAME, profileName)}`,
615 });
616 }
617 if (creds.type === "token") {
618 return {
619 type: "token" as const,
620 accessToken: Redacted.make(creds.accessToken),
621 project: creds.project,
622 source: { type: "stored" as const },
623 };
624 }
625 const sa = yield* parseServiceAccountKey(creds.json);
626 return yield* resolveFromServiceAccount(sa, creds.project);
627 });
628
629 const resolveToken = (
630 profileName: string,
631 config: GcpAuthConfig,
632 ): Effect.Effect<GcloudToken, AuthError | NeedsReauth> => {
633 switch (config.method) {
634 case "gcloud":
635 return resolveFromGcloud(profileName, config);
636 case "serviceAccount":
637 return resolveFromServiceAccountFile(config.credentialsFile);
638 case "stored":
639 return resolveFromStored(profileName);
640 }
641 };
642
643 // The region is part of the credential (the profile's `region`).
644 // Google SDKs define no default-region environment variable; override
645 // per stack with the `GCP.Region(...)` layer.
646 const resolveCredentials = (
647 profileName: string,
648 config: GcpAuthConfig,
649 ): Effect.Effect<GcpResolvedCredentials, AuthError | NeedsReauth> =>
650 Effect.gen(function* () {
651 const { gcloudRegion, ...token } = yield* resolveToken(profileName, config);
652 return { ...token, region: config.region ?? gcloudRegion ?? DEFAULT_GCP_REGION };
653 });
654
655 const logout = (profileName: string, config: GcpAuthConfig) =>
656 Match.value(config).pipe(
657 // The login belongs to gcloud and other tools share it.
658 Match.when({ method: "gcloud" }, ({ configuration }) =>
659 Interaction.info(
660 `GCP: run \`gcloud auth revoke --configuration=${configuration}\` to sign out of gcloud.`,
661 ),
662 ),
663 Match.when({ method: "serviceAccount" }, () => Effect.void),
664 Match.when({ method: "stored" }, () =>
665 store
666 .delete(profileName, GCP_AUTH_PROVIDER_NAME)
667 .pipe(Effect.andThen(Interaction.success("GCP: stored credentials removed"))),
668 ),
669 Match.exhaustive,
670 );
671
672 const login = (profileName: string, config: GcpAuthConfig) =>
673 Match.value(config).pipe(
674 Match.when({ method: "gcloud" }, (cfg) =>
675 loginGcloudConfiguration(cfg.configuration).pipe(
676 Effect.andThen(resolveFromGcloud(profileName, cfg)),
677 Effect.as(cfg),
678 ),
679 ),
680 Match.when({ method: "serviceAccount" }, (cfg) =>
681 resolveFromServiceAccountFile(cfg.credentialsFile).pipe(Effect.as(cfg)),
682 ),
683 Match.when({ method: "stored" }, () =>
684 store
685 .read(profileName, GCP_AUTH_PROVIDER_NAME, GcpStoredCredentialsSchema)
686 .pipe(
687 Effect.flatMap((creds) =>
688 creds == null
689 ? loginStored(profileName).pipe(
690 Effect.map((stored) => ({ ...config, ...stored })),
691 )
692 : Effect.succeed(config),
693 ),
694 ),
695 ),
696 Match.exhaustive,
697 Effect.mapError((e) => AuthError.make({ message: `login failed: ${e.message}`, cause: e })),
698 );
699
700 const details = (
701 profileName: string,
702 config: GcpAuthConfig,
703 ): Effect.Effect<ProviderDetails, AuthError | NeedsReauth> =>
704 resolveCredentials(profileName, config).pipe(
705 Effect.map((creds) => {
706 const sourceStr = creds.source.details
707 ? `${creds.source.type} - ${creds.source.details}`
708 : creds.source.type;
709 return {
710 lines: [
711 { key: "project", value: creds.project },
712 { key: "region", value: creds.region },
713 {
714 key: "accessToken",
715 value: displayRedacted(creds.accessToken, 8),
716 },
717 { key: "source", value: sourceStr },
718 ],
719 };
720 }),
721 );
722
723 const readEnvironment = resolveFromEnv().pipe(
724 Effect.map((token) => ({ ...token, region: DEFAULT_GCP_REGION })),
725 );
726
727 return {
728 configSchema: GcpAuthConfigSchema,
729 configure: configureCredentials,
730 configureWith,
731 configureMethods,
732 logout,
733 login,
734 details,
735 read: resolveCredentials,
736 readEnvironment,
737 environment: [
738 // A project variable alone is not a credential: shells often export
739 // GOOGLE_CLOUD_PROJECT, and it must not shadow the profile.
740 {
741 name: GOOGLE_ACCESS_TOKEN_ENV,
742 required: true,
743 secret: true,
744 alternatives: [GOOGLE_APPLICATION_CREDENTIALS_ENV],
745 description: `Bearer access token, or ${GOOGLE_APPLICATION_CREDENTIALS_ENV}: path to a service-account JSON key.`,
746 },
747 {
748 name: GOOGLE_PROJECT_ID_ENV,
749 required: false,
750 alternatives: [GOOGLE_CLOUD_PROJECT_ENV],
751 description:
752 "GCP project id. Required with an access token; a key defaults to its project_id.",
753 },
754 ],
755 };
756 }),
757 );
758
759 /** A resolved token, plus the region a gcloud configuration names. */
760 type GcloudToken = Omit<GcpResolvedCredentials, "region"> & { gcloudRegion?: string };
761
762 const gcloudNotInstalled = (cause: unknown) =>
763 AuthError.make({
764 message:
765 "Failed to run gcloud. Install the Google Cloud CLI: https://cloud.google.com/sdk/docs/install",
766 cause,
767 });
768
769 const gcloudProperty = Schema.String.pipe(Schema.NullOr, Schema.optionalKey);
770
771 /** `gcloud config config-helper --format=json`: the token and the configuration's properties. */
772 const ConfigHelperOutput = Schema.Struct({
773 configuration: Schema.Struct({
774 properties: Schema.Struct({
775 core: Schema.optionalKey(Schema.Struct({ account: gcloudProperty, project: gcloudProperty })),
776 compute: Schema.optionalKey(Schema.Struct({ region: gcloudProperty })),
777 }),
778 }),
779 credential: Schema.Struct({
780 access_token: Schema.String,
781 token_expiry: gcloudProperty,
782 }),
783 });
784
785 /** The authorization URL in gcloud's login prompt. */
786 export const parseGcloudLoginOutput = (output: string): string | undefined =>
787 output.match(/https:\/\/accounts\.google\.com\/[^\s]+/)?.[0];
788
789 /**
790 * `gcloud auth login` waits on a localhost callback and prints its
791 * authorization URL on stderr.
792 * `BROWSER=true` stops gcloud opening a tab of its own, so the URL goes
793 * through the same authorization screen as the AWS logins.
794 */
795 const loginGcloud = Effect.fn(function* (args: ReadonlyArray<string>, env: Record<string, string>) {
796 const interaction = yield* Interaction.Interaction;
797 const authorizationUrl = yield* Deferred.make<string>();
798 const stderr = yield* Ref.make("");
799 const handle = yield* ChildProcess.make("gcloud", [...args], {
800 shell: false,
801 stdin: "ignore",
802 stdout: "pipe",
803 stderr: "pipe",
804 env: { ...env, BROWSER: "true" },
805 extendEnv: true,
806 }).pipe(Effect.mapError(gcloudNotInstalled));
807 const collectStderr = handle.stderr.pipe(
808 Stream.decodeText(),
809 Stream.runForEach((chunk) =>
810 Effect.gen(function* () {
811 const combined = yield* Ref.updateAndGet(stderr, (current) => current + chunk);
812 const url = parseGcloudLoginOutput(combined);
813 if (url !== undefined) {
814 yield* Deferred.succeed(authorizationUrl, url);
815 }
816 }),
817 ),
818 );
819 const process = Effect.gen(function* () {
820 const [exitCode] = yield* Effect.all(
821 [handle.exitCode, Stream.runDrain(handle.stdout), collectStderr],
822 { concurrency: 3 },
823 );
824 if (exitCode !== 0) {
825 const detail = (yield* Ref.get(stderr)).trim();
826 return yield* AuthError.make({
827 message: `gcloud ${args.join(" ")} exited with code ${exitCode}${detail === "" ? "" : `: ${detail}`}`,
828 });
829 }
830 });
831 const processFiber = yield* Effect.forkScoped(process);
832 const url = yield* Deferred.await(authorizationUrl).pipe(
833 Effect.raceFirst(
834 Fiber.join(processFiber).pipe(
835 Effect.flatMap(() =>
836 Effect.fail(
837 AuthError.make({
838 message: "gcloud login completed without providing an authorization URL.",
839 }),
840 ),
841 ),
842 ),
843 ),
844 );
845 yield* Interaction.browserLogin({
846 provider: "GCP",
847 waitingLabel: "waiting for browser authorization…",
848 url,
849 waitFor: Fiber.join(processFiber),
850 });
851 yield* interaction.output.success("GCP: gcloud login complete");
852 }, Effect.scoped);