TypeScript
fix(server): a saved source control token that can't be read no longer falls back to another account (#31646)
Julius Marminged694c44d0784
diff --git a/apps/server/src/secrets/settingsSecretValue.ts b/apps/server/src/secrets/settingsSecretValue.tsindex 50a99b953d3..6f869531eae 100644--- a/apps/server/src/secrets/settingsSecretValue.ts+++ b/apps/server/src/secrets/settingsSecretValue.ts@@ -1,16 +1,18 @@import {isSecretReference,secretReferencesInSettings,+ SettingsSecretUnresolvedError,type SettingsSecretValue,withSettingsSecrets,} from "@t3tools/contracts";import type * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";import * as Effect from "effect/Effect";-import * as Schema from "effect/Schema";+import type * as Schema from "effect/Schema";/*** Replaces each reference in the slots `schema` declares as `SettingsSecretValue` with the secret- * it names, read in one batch. An unreadable secret comes back as `""`, so it behaves as unset.+ * it names, read in one batch. A secret that cannot be read, or reads empty, keeps its reference,+ * which `requireSettingsSecretLiteral` turns into an error for the consumer of that field.*/export const resolveSettingsSecrets = Effect.fn("SettingsSecrets.resolve")(function* <Settings extends Readonly<Record<string, unknown>>,@@ -20,19 +22,13 @@ export const resolveSettingsSecrets = Effect.fn("SettingsSecrets.resolve")(functconst values = yield* resolver.read(pending.map(({ reference }) => reference));return withSettingsSecrets(settings,- pending.map((slot, index) => ({ ...slot, value: values[index] ?? "" })),+ pending.flatMap((slot, index) => {+ const value = values[index];+ return value === undefined || value.trim() === "" ? [] : [{ ...slot, value }];+ }),);});-export class SettingsSecretUnresolvedError extends Schema.TaggedError<SettingsSecretUnresolvedError>()(- "SettingsSecretUnresolvedError",- { provider: Schema.String },-) {- override get message(): string {- return `Could not read the credential from the secret provider "${this.provider}". Unlock or fix it in Settings, then try again.`;- }-}-/*** The secret a credential setting holds or names. A named secret that cannot be read, or reads* empty, fails instead of passing for a missing token, so callers that would fall back to anotherdiff --git a/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts b/apps/server/src/sourceControl/sourceControlHostSecrets.test.tsindex 45c156895f4..c3ff7a880de 100644--- a/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts+++ b/apps/server/src/sourceControl/sourceControlHostSecrets.test.ts@@ -58,11 +58,11 @@ it.effect(}),);-it.effect("treats a reference the provider cannot read as an unset credential", () =>+it.effect("keeps a reference the provider cannot read, so it never passes for an unset one", () =>Effect.gen(function* () {const { reads, resolver } = countingResolver();const resolved = yield* resolveSourceControlHostSecrets(resolver, hosts, "gitcafe");- assert.deepEqual(resolved.gitcafe, { token: "" });+ assert.deepEqual(resolved.gitcafe, { token: source("missing#token") });assert.deepEqual(reads, ["missing#token"]);}),);diff --git a/packages/contracts/src/settingsSecretValue.ts b/packages/contracts/src/settingsSecretValue.tsindex 97558c82d57..669c8040132 100644--- a/packages/contracts/src/settingsSecretValue.ts+++ b/packages/contracts/src/settingsSecretValue.ts@@ -1,3 +1,4 @@+import * as Effect from "effect/Effect";import * as Schema from "effect/Schema";import * as SchemaAST from "effect/SchemaAST";@@ -22,6 +23,35 @@ export function settingsSecretLiteral(value: SettingsSecretValue | undefined): sreturn typeof value === "string" ? value : "";}+export class SettingsSecretUnresolvedError extends Schema.TaggedError<SettingsSecretUnresolvedError>()(+ "SettingsSecretUnresolvedError",+ { provider: Schema.String },+) {+ override get message(): string {+ return `Could not read the credential from the secret provider "${this.provider}". Unlock or fix it in Settings, then try again.`;+ }+}++/**+ * The literal a credential setting holds once its secret is resolved. A reference still in place+ * could not be read, and fails instead of passing for a missing token, so callers that would fall+ * back to another credential cannot silently switch accounts.+ */+export const requireSettingsSecretLiteral = (+ value: SettingsSecretValue | undefined,+ secretProviders: Readonly<Record<string, { readonly label: string } | undefined>>,+): Effect.Effect<string, SettingsSecretUnresolvedError> =>+ isSecretReference(value)+ ? Effect.fail(+ new SettingsSecretUnresolvedError({+ provider:+ (Object.hasOwn(secretProviders, value.provider)+ ? secretProviders[value.provider]?.label.trim()+ : undefined) || value.provider,+ }),+ )+ : Effect.succeed(value ?? "");+export function acceptsSecretReference(schema: Schema.Top): boolean {return Schema.resolveAnnotationsKey(schema)?.settingsSecretReference === true;}diff --git a/packages/source-control-bitbucket/src/server/BitbucketApi.test.ts b/packages/source-control-bitbucket/src/server/BitbucketApi.test.tsindex f18c8f72421..ddfe567273e 100644--- a/packages/source-control-bitbucket/src/server/BitbucketApi.test.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketApi.test.ts@@ -1,4 +1,4 @@-import { SourceControlProviderKind } from "@t3tools/contracts";+import { SecretProviderId, SourceControlProviderKind } from "@t3tools/contracts";import { assert, it, vi } from "@effect/vitest";import * as NodeServices from "@effect/platform-node/NodeServices";import * as ConfigProvider from "effect/ConfigProvider";@@ -669,6 +669,24 @@ it.effect("prefers credentials saved in settings over the environment, without a});yield* bitbucket.probeAuth;assert.strictEqual(lastAuthorization(), basic("[email protected]", "token"));++ // A reference left in place by getWithSecrets is one its secret provider could not read.+ const requests = execute.mock.calls.length;+ yield* settings.update({+ sourceControlHosts: {+ bitbucket: {+ accessToken: { provider: SecretProviderId.make("vault"), reference: "bb#token" },+ },+ },+ });+ const auth = yield* bitbucket.probeAuth;+ assert.strictEqual(auth.status, "unauthenticated");+ assert.include(Option.getOrThrow(auth.detail), '"vault"');+ const error = yield* Effect.flip(+ bitbucket.listPullRequests({ cwd: "/repo", headSelector: "feature", state: "open" }),+ );+ assert.strictEqual(error._tag, "SettingsSecretUnresolvedError");+ assert.strictEqual(execute.mock.calls.length, requests);}).pipe(Effect.provide(layer));});diff --git a/packages/source-control-bitbucket/src/server/BitbucketApi.ts b/packages/source-control-bitbucket/src/server/BitbucketApi.tsindex 2f46fcb80a6..fe68110cbfa 100644--- a/packages/source-control-bitbucket/src/server/BitbucketApi.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketApi.ts@@ -9,9 +9,11 @@ import * as Schema from "effect/Schema";import * as Semaphore from "effect/Semaphore";import {NonNegativeInt,- settingsSecretLiteral,+ requireSettingsSecretLiteral,+ SettingsSecretUnresolvedError,SourceControlProviderKind,TrimmedNonEmptyString,+ type ServerSettings,type SourceControlProviderAuth,type SourceControlProviderInfo,type SourceControlRepositoryCloneUrls,@@ -277,6 +279,7 @@ export const BitbucketApiError = Schema.Union([BitbucketPullRequestBodyReadError,BitbucketCheckoutError,SourceControlRateLimit.SourceControlRateLimitPausedError,+ SettingsSecretUnresolvedError,]);export type BitbucketApiError = typeof BitbucketApiError.Type;const isBitbucketApiError = Schema.is(BitbucketApiError);@@ -563,23 +566,24 @@ function credentialFrom(input: {return null;}-function resolveCredential(+const resolveCredential = Effect.fn("BitbucketApi.resolveCredential")(function* (settings: BitbucketClient.BitbucketSettings,+ secretProviders: ServerSettings["secretProviders"],env: Config.Success<typeof BitbucketApiEnvConfig>,-): BitbucketCredential | null {+) {+ const accessToken = yield* requireSettingsSecretLiteral(settings.accessToken, secretProviders);+ const apiToken = HEADER_SAFE.test(accessToken)+ ? ""+ : yield* requireSettingsSecretLiteral(settings.apiToken, secretProviders);return (- credentialFrom({- accessToken: settingsSecretLiteral(settings.accessToken),- email: settings.email,- apiToken: settingsSecretLiteral(settings.apiToken),- }) ??+ credentialFrom({ accessToken, email: settings.email, apiToken }) ??credentialFrom({accessToken: Option.getOrElse(env.accessToken, () => ""),email: Option.getOrElse(env.email, () => ""),apiToken: Option.getOrElse(env.apiToken, () => ""),}));-}+});function authFromCredential(credential: BitbucketCredential | null): SourceControlProviderAuth {if (credential?.kind === "access-token") {@@ -669,25 +673,27 @@ export const make = Effect.gen(function* () {const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;const currentCredential = host.settings.getWithSecrets(BitbucketClient.definition.kind).pipe(- Effect.map((settings) =>- resolveCredential(- readSourceControlHostSettings(- BitbucketClient.settings,- settings.sourceControlHosts[BitbucketClient.definition.kind],- ),- config,+ Effect.map((settings) => ({+ bitbucket: readSourceControlHostSettings(+ BitbucketClient.settings,+ settings.sourceControlHosts[BitbucketClient.definition.kind],),- ),+ secretProviders: settings.secretProviders,+ })),Effect.catch((error) =>// No cause: a settings decode error can quote a hand-edited token.Effect.logWarning("failed to read Bitbucket credentials from settings", {operation: error.operation,}).pipe(- Effect.as(- resolveCredential(readSourceControlHostSettings(BitbucketClient.settings, {}), config),- ),+ Effect.as({+ bitbucket: readSourceControlHostSettings(BitbucketClient.settings, {}),+ secretProviders: {},+ }),),),+ Effect.flatMap(({ bitbucket, secretProviders }) =>+ resolveCredential(bitbucket, secretProviders, config),+ ),);const withAuth = (request: HttpClientRequest.HttpClientRequest) =>@@ -756,13 +762,10 @@ export const make = Effect.gen(function* () {throttled(request.method,withAuth(request.pipe(HttpClientRequest.acceptJson)).pipe(- Effect.flatMap(httpClient.execute),- Effect.mapError(- (cause) =>- new BitbucketRequestError({- operation,- cause,- }),+ Effect.flatMap((authed) =>+ httpClient+ .execute(authed)+ .pipe(Effect.mapError((cause) => new BitbucketRequestError({ operation, cause }))),),Effect.flatMap((response) => decodeResponse(operation, schema, response)),Effect.timeout(BITBUCKET_API_REQUEST_TIMEOUT),@@ -960,9 +963,15 @@ export const make = Effect.gen(function* () {? base: base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));return withAuth(withBody).pipe(- Effect.flatMap(httpClient.execute),- Effect.mapError(- (cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),+ Effect.flatMap((request) =>+ httpClient+ .execute(request)+ .pipe(+ Effect.mapError(+ (cause): BitbucketApiError =>+ new BitbucketRequestError({ operation: "request", cause }),+ ),+ ),),Effect.flatMap((response) => {const location = response.headers.location;@@ -1042,6 +1051,15 @@ export const make = Effect.gen(function* () {Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),),),+ Effect.catchTags({+ SettingsSecretUnresolvedError: (error) =>+ Effect.succeed<SourceControlProviderAuth>({+ status: "unauthenticated",+ account: Option.none(),+ host: Option.some("bitbucket.org"),+ detail: Option.some(error.message),+ }),+ }),),listPullRequests: Effect.fn("BitbucketApi.listPullRequests")(function (input) {return resolveRepository(input).pipe(diff --git a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.tsindex b5db87d089a..087d3b9dc8f 100644--- a/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts+++ b/packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts@@ -61,7 +61,10 @@ export function bitbucketViewerPermissions(input: {export function bitbucketProviderFailure(error: BitbucketPullRequestApi.BitbucketPullRequestApiError,): PullRequestProviderFailure {- if (error._tag === "BitbucketResponseError" && error.status === 401) {+ if (+ (error._tag === "BitbucketResponseError" && error.status === 401) ||+ error._tag === "SettingsSecretUnresolvedError"+ ) {return { reason: "unauthenticated" };}if (error._tag === "SourceControlRateLimitPausedError") {@@ -135,7 +138,7 @@ export const make = Effect.gen(function* () {provider: SourceControlProviderKind.make("bitbucket"),operation,...bitbucketProviderFailure(error),- detail: error.detail,+ detail: error._tag === "SettingsSecretUnresolvedError" ? error.message : error.detail,cause: error,});diff --git a/packages/source-control-core/src/server/SourceControlHost.ts b/packages/source-control-core/src/server/SourceControlHost.tsindex 5d5f72dd044..e3d6f604cfd 100644--- a/packages/source-control-core/src/server/SourceControlHost.ts+++ b/packages/source-control-core/src/server/SourceControlHost.ts@@ -70,8 +70,9 @@ export class SourceControlHost extends Context.Service<readonly get: Effect.Effect<ServerSettings, ServerSettingsError>;/*** Like `get`, with each secret provider reference in one host kind's credentials replaced- * by the secret it names. An unreadable reference reads as unset. Only a reader of that- * kind should call it: resolving can wait on a secret provider.+ * by the secret it names. An unreadable reference stays in place; read the field with+ * `requireSettingsSecretLiteral` so it fails rather than passing for an unset credential.+ * Only a reader of that kind should call it: resolving can wait on a secret provider.*/readonly getWithSecrets: (kind: string) => Effect.Effect<ServerSettings, ServerSettingsError>;/** For credentials the host obtains itself, such as a sign-in it refreshes. */diff --git a/packages/source-control-gitcafe/src/server/GitCafeApi.ts b/packages/source-control-gitcafe/src/server/GitCafeApi.tsindex 6d5538de6dc..45e70f8b0ff 100644--- a/packages/source-control-gitcafe/src/server/GitCafeApi.ts+++ b/packages/source-control-gitcafe/src/server/GitCafeApi.ts@@ -82,7 +82,7 @@ const credentialFailure = (): typeof GitCafeApiFailure.Type =>error._tag === "GitCafeCliMissingError"? "missing-tool"- : error._tag === "GitCafeNotSignedInError"+ : error._tag === "GitCafeNotSignedInError" || error._tag === "SettingsSecretUnresolvedError"? "unauthenticated": "failed";diff --git a/packages/source-control-gitcafe/src/server/GitCafeCredentials.test.ts b/packages/source-control-gitcafe/src/server/GitCafeCredentials.test.tsindex e183f12c7c1..7ec49114a0d 100644--- a/packages/source-control-gitcafe/src/server/GitCafeCredentials.test.ts+++ b/packages/source-control-gitcafe/src/server/GitCafeCredentials.test.ts@@ -1,4 +1,5 @@import { assert, describe, it } from "@effect/vitest";+import { SecretProviderId } from "@t3tools/contracts";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";import * as Redacted from "effect/Redacted";@@ -94,6 +95,24 @@ describe("GitCafeCredentials", () => {yield* settings.update({ sourceControlHosts: { gitcafe: { token: "" } } });assert.strictEqual((yield* credentials.get("git.cafe")).source, "env");++ // A reference left in place by getWithSecrets is one its secret provider could not read,+ // here one naming a removed provider whose id is also an Object.prototype key.+ yield* settings.update({+ sourceControlHosts: {+ gitcafe: {+ token: { provider: SecretProviderId.make("constructor"), reference: "cafe#token" },+ },+ },+ });+ const error = yield* Effect.flip(credentials.get("git.cafe"));+ assert.strictEqual(error._tag, "SettingsSecretUnresolvedError");+ assert.include(error.message, '"constructor"');+ assert.strictEqual(+ (yield* Effect.flip(credentials.cliEnv("git.cafe")))._tag,+ "SettingsSecretUnresolvedError",+ );+ assert.strictEqual(calls.length, 1);}).pipe(Effect.provide(layer));});diff --git a/packages/source-control-gitcafe/src/server/GitCafeCredentials.ts b/packages/source-control-gitcafe/src/server/GitCafeCredentials.tsindex 7823924a4ad..ae5d661ee86 100644--- a/packages/source-control-gitcafe/src/server/GitCafeCredentials.ts+++ b/packages/source-control-gitcafe/src/server/GitCafeCredentials.ts@@ -1,4 +1,7 @@-import { settingsSecretLiteral } from "@t3tools/contracts";+import {+ requireSettingsSecretLiteral,+ type SettingsSecretUnresolvedError,+} from "@t3tools/contracts";import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";import * as Cache from "effect/Cache";import * as Context from "effect/Context";@@ -55,7 +58,8 @@ export class GitCafeCliFailedError extends Schema.TaggedError<GitCafeCliFailedErexport type GitCafeCredentialUnavailableError =| GitCafeCliMissingError| GitCafeNotSignedInError- | GitCafeCliFailedError;+ | GitCafeCliFailedError+ | SettingsSecretUnresolvedError;export class GitCafeCredentials extends Context.Service<GitCafeCredentials,@@ -64,7 +68,9 @@ export class GitCafeCredentials extends Context.Service<host: string,) => Effect.Effect<GitCafeCredential, GitCafeCredentialUnavailableError>;readonly invalidate: (host: string) => Effect.Effect<void>;- readonly cliEnv: (host: string) => Effect.Effect<Readonly<Record<string, string>>>;+ readonly cliEnv: (+ host: string,+ ) => Effect.Effect<Readonly<Record<string, string>>, SettingsSecretUnresolvedError>;}>()("@t3tools/source-control-gitcafe/server/GitCafeCredentials") {}@@ -130,16 +136,18 @@ export const make = Effect.gen(function* () {normalizeHost(host) !== DEFAULT_HOST? Effect.succeed(null): sourceControlHost.settings.getWithSecrets(GitCafeClient.definition.kind).pipe(- Effect.map(- (settings) =>- settingsSecretLiteral(- readSourceControlHostSettings(- GitCafeClient.settings,- settings.sourceControlHosts[GitCafeClient.definition.kind],- ).token,- ) || null,+ Effect.map((settings) => ({+ token: readSourceControlHostSettings(+ GitCafeClient.settings,+ settings.sourceControlHosts[GitCafeClient.definition.kind],+ ).token,+ secretProviders: settings.secretProviders,+ })),+ Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),+ Effect.flatMap(({ token, secretProviders }) =>+ requireSettingsSecretLiteral(token, secretProviders),),- Effect.orElseSucceed(() => null),+ Effect.map((token) => token || null),);const lookup = Effect.fn("GitCafeCredentials.lookup")(function* (diff --git a/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts b/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.tsindex 6c7b413541d..99e54a31195 100644--- a/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts+++ b/packages/source-control-gitcafe/src/server/GitCafeSourceControlProvider.ts@@ -109,12 +109,32 @@ export const makeDiscovery = Effect.gen(function* () {installHint: cliDiscovery.installHint,probe: (cwd: string) =>credentials.cliEnv(AUTH_HOST).pipe(+ Effect.result,Effect.flatMap((env) =>probeSourceControlProvider({cwd,spec: cliDiscovery,- process: { run: (input) => process.run({ ...input, env: { ...input.env, ...env } }) },- }),+ process: {+ run: (input) =>+ process.run({+ ...input,+ env: { ...input.env, ...(Result.isSuccess(env) ? env.success : {}) },+ }),+ },+ }).pipe(+ Effect.map((item) =>+ Result.isSuccess(env)+ ? item+ : {+ ...item,+ auth: providerAuth({+ status: "unauthenticated",+ host: AUTH_HOST,+ detail: env.failure.message,+ }),+ },+ ),+ ),),),refineUnknownRemote: () => Effect.succeed(null),diff --git a/packages/source-control-github/src/server/GitHubCredentials.test.ts b/packages/source-control-github/src/server/GitHubCredentials.test.tsindex 35d0eb23bf4..88d37393c83 100644--- a/packages/source-control-github/src/server/GitHubCredentials.test.ts+++ b/packages/source-control-github/src/server/GitHubCredentials.test.ts@@ -6,7 +6,7 @@ import * as Redacted from "effect/Redacted";import { HttpClient } from "effect/http";import { ChildProcessSpawner } from "effect/process";-import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";+import { DEFAULT_SERVER_SETTINGS, SecretProviderId, SecretProviderKind } from "@t3tools/contracts";import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";@@ -137,9 +137,31 @@ describe("GitHubCredentials", () => {const { layer, calls } = harness({}, [], { "github.com": "saved-token" });return Effect.gen(function* () {const credentials = yield* GitHubCredentials.GitHubCredentials;+ const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;const credential = yield* credentials.get("github.com");expect(Redacted.value(credential.token)).toBe("saved-token");expect(credential.source).toBe("settings");++ // A reference left in place by getWithSecrets is one its secret provider could not read.+ yield* settings.update({+ secretProviders: {+ [SecretProviderId.make("vault")]: {+ kind: SecretProviderKind.make("one_password"),+ label: "Work vault",+ config: {},+ },+ },+ sourceControlHosts: {+ github: {+ tokens: {+ "github.com": { provider: SecretProviderId.make("vault"), reference: "gh#token" },+ },+ },+ },+ });+ const error = yield* Effect.flip(credentials.get("github.com"));+ expect(error._tag).toBe("SettingsSecretUnresolvedError");+ expect(error.message).toContain('"Work vault"');expect(calls).toEqual([]);}).pipe(Effect.provide(layer));});diff --git a/packages/source-control-github/src/server/GitHubCredentials.ts b/packages/source-control-github/src/server/GitHubCredentials.tsindex db3aee2df2c..5a7d940c76a 100644--- a/packages/source-control-github/src/server/GitHubCredentials.ts+++ b/packages/source-control-github/src/server/GitHubCredentials.ts@@ -16,7 +16,11 @@ import * as HostProcess from "@t3tools/shared/HostProcess";import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";import { readSourceControlHostSettings } from "@t3tools/source-control-core/shared/definition";-import { settingsSecretLiteral, type ServerSettings } from "@t3tools/contracts";+import {+ requireSettingsSecretLiteral,+ type ServerSettings,+ type SettingsSecretUnresolvedError,+} from "@t3tools/contracts";import * as GitHubClient from "../shared/definition.ts";@@ -81,7 +85,8 @@ export type GitHubCredentialUnavailableError =| GitHubCliMissingError| GitHubNotSignedInError| GitHubHostDisabledError- | GitHubCliFailedError;+ | GitHubCliFailedError+ | SettingsSecretUnresolvedError;export class GitHubCredentials extends Context.Service<GitHubCredentials,@@ -94,7 +99,7 @@ export class GitHubCredentials extends Context.Service<host: string,) => Effect.Effect<Option.Option<GitHubCredential>,- GitHubHostDisabledError | GitHubNotSignedInError+ GitHubHostDisabledError | GitHubNotSignedInError | SettingsSecretUnresolvedError>;readonly fingerprint: (host: string, token: string) => Effect.Effect<string>;readonly invalidate: (host: string) => Effect.Effect<void>;@@ -195,10 +200,15 @@ export const make = Effect.gen(function* () {const savedToken = (host: string) =>sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe(- Effect.map(- (settings) => settingsSecretLiteral(readSettings(settings).tokens[host]).trim() || null,+ Effect.map((settings) => ({+ token: readSettings(settings).tokens[host],+ secretProviders: settings.secretProviders,+ })),+ Effect.orElseSucceed(() => ({ token: undefined, secretProviders: {} })),+ Effect.flatMap(({ token, secretProviders }) =>+ requireSettingsSecretLiteral(token, secretProviders),),- Effect.orElseSucceed(() => null),+ Effect.map((token) => token.trim() || null),);const cacheKey = (host: string, account: string | undefined) =>diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.tsindex b998d2be735..14936af269d 100644--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts@@ -111,6 +111,7 @@ function gitHubProviderFailure(return { reason: "missing-tool" };case "GitHubNotSignedInError":case "GitHubHostDisabledError":+ case "SettingsSecretUnresolvedError":case "GitHubApiAuthenticationError":return { reason: "unauthenticated" };case "GitHubApiRateLimitError":diff --git a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts b/packages/source-control-github/src/server/GitHubSourceControlProvider.tsindex 0048560977c..4abb3d8d666 100644--- a/packages/source-control-github/src/server/GitHubSourceControlProvider.ts+++ b/packages/source-control-github/src/server/GitHubSourceControlProvider.ts@@ -1,4 +1,4 @@-import { settingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";+import { requireSettingsSecretLiteral, SourceControlProviderKind } from "@t3tools/contracts";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -222,12 +222,12 @@ export const makeDiscovery = Effect.gen(function* () {label: discovery.label,installHint: discovery.installHint,probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {+ const current = yield* sourceControlHost.settings+ .getWithSecrets(GitHubClient.definition.kind)+ .pipe(Effect.orElseSucceed(() => undefined));const settings = readSourceControlHostSettings(GitHubClient.settings,- yield* sourceControlHost.settings.getWithSecrets(GitHubClient.definition.kind).pipe(- Effect.map((current) => current.sourceControlHosts[GitHubClient.definition.kind]),- Effect.orElseSucceed(() => undefined),- ),+ current?.sourceControlHosts[GitHubClient.definition.kind],);const cli = yield* probeSourceControlProvider({cwd,@@ -236,8 +236,21 @@ export const makeDiscovery = Effect.gen(function* () {},spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },});- const token = settings.tokens["github.com"];- const savedToken = settingsSecretLiteral(token).trim() !== "";+ const saved = yield* Effect.result(+ requireSettingsSecretLiteral(settings.tokens["github.com"], current?.secretProviders ?? {}),+ );+ if (Result.isFailure(saved) && settings.hosts["github.com"]?.enabled !== false) {+ return offerAppSignIn({+ ...cli,+ status: "available" as const,+ auth: providerAuth({+ status: "unauthenticated",+ host: "github.com",+ detail: saved.failure.message,+ }),+ });+ }+ const savedToken = Result.isSuccess(saved) && saved.success.trim() !== "";const signedIn =appSignIn.enabled && !savedToken && (settings.signIns["github.com"] ?? "").trim() !== "";const variable = environmentTokenVariable(environment);@@ -339,6 +352,7 @@ function fromGitHubApiError();case "GitHubNotSignedInError":case "GitHubHostDisabledError":+ case "SettingsSecretUnresolvedError":return failure(error.message, error);case "GitHubApiAuthenticationError":return failure(diff --git a/packages/source-control-github/src/server/gitHubDiscovery.test.ts b/packages/source-control-github/src/server/gitHubDiscovery.test.tsindex b108d71f755..c1f4304f4b0 100644--- a/packages/source-control-github/src/server/gitHubDiscovery.test.ts+++ b/packages/source-control-github/src/server/gitHubDiscovery.test.ts@@ -92,9 +92,26 @@ const referencedTokenSettings = decodeSettings({});it.effect.each([- { name: "readable", token: "resolved-token", source: "the token saved in Settings" },- { name: "unreadable", token: "", source: "GH_TOKEN from the server environment" },-])("checks the $name GitHub token reference against the API", (scenario) =>+ {+ name: "a readable",+ token: "resolved-token",+ status: "authenticated",+ detail: "the token saved in Settings",+ },+ {+ name: "no",+ token: "",+ status: "authenticated",+ detail: "GH_TOKEN from the server environment",+ },+ // getWithSecrets leaves a reference its secret provider could not read in place.+ {+ name: "an unreadable",+ token: { provider: "vault", reference: "op://v/gh" },+ status: "unauthenticated",+ detail: 'secret provider "vault"',+ },+])("reports $name saved GitHub token instead of another credential", (scenario) =>Effect.gen(function* () {const paths: Array<string> = [];const discovery = yield* GitHubSourceControlProvider.makeDiscovery.pipe(@@ -153,9 +170,13 @@ it.effect.each([);if (discovery.type !== "managed-cli") return assert.fail("expected a managed CLI");const item = yield* discovery.probe("/repo");- assert.deepStrictEqual(paths, ["user"]);- assert.strictEqual(item.auth.status, "authenticated");- assert.deepStrictEqual(item.auth.account, Option.some("octocat"));- assert.include(Option.getOrThrow(item.auth.detail), scenario.source);+ const authenticated = scenario.status === "authenticated";+ assert.deepStrictEqual(paths, authenticated ? ["user"] : []);+ assert.strictEqual(item.auth.status, scenario.status);+ assert.deepStrictEqual(+ item.auth.account,+ authenticated ? Option.some("octocat") : Option.none(),+ );+ assert.include(Option.getOrThrow(item.auth.detail), scenario.detail);}),);