feat: save Bitbucket credentials from Source Control settings (#14103)

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-28 18:38:24 -07:00
1 parent e518866d28
commit 5da55957d4
13 files changed
+679 -54

No files matched your search

@@ -16,6 +16,7 @@ import {
import { GitCommandError } from "@t3tools/contracts";
import * as BitbucketApi from "./BitbucketApi.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import type * as VcsDriver from "../vcs/VcsDriver.ts";
@@ -64,6 +65,7 @@ function makeLayer(input: {
request: HttpClientRequest.HttpClientRequest,
) => HttpClientError.HttpClientError;
readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
readonly env?: Record<string, string>;
}) {
const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
input.requestFailure
@@ -150,7 +152,7 @@ function makeLayer(input: {
Layer.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
env: input.env ?? {
T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0",
T3CODE_BITBUCKET_EMAIL: "[email protected]",
T3CODE_BITBUCKET_API_TOKEN: "token",
@@ -158,6 +160,7 @@ function makeLayer(input: {
}),
),
),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
@@ -509,6 +512,78 @@ it.effect("reports auth status through the Bitbucket REST /user endpoint", () =>
}).pipe(Effect.provide(layer));
});
it.effect("prefers credentials saved in settings over the environment, without a restart", () => {
const { execute, layer } = makeLayer({
response: () => Response.json({ username: "bitbucket-user" }),
});
const lastAuthorization = () => execute.mock.calls.at(-1)?.[0].headers.authorization;
const basic = (user: string, password: string) => `Basic ${btoa(`${user}:${password}`)}`;
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const settings = yield* ServerSettings.ServerSettingsService;
yield* bitbucket.probeAuth;
assert.strictEqual(lastAuthorization(), basic("[email protected]", "token"));
yield* settings.updateSettings({
bitbucket: { email: "[email protected]", apiToken: "saved-api-token" },
});
yield* bitbucket.probeAuth;
assert.strictEqual(lastAuthorization(), basic("[email protected]", "saved-api-token"));
yield* settings.updateSettings({ bitbucket: { accessToken: "saved-access-token" } });
yield* bitbucket.probeAuth;
assert.strictEqual(lastAuthorization(), "Bearer saved-access-token");
yield* settings.updateSettings({ bitbucket: { accessToken: "", apiToken: "" } });
yield* bitbucket.probeAuth;
assert.strictEqual(lastAuthorization(), basic("[email protected]", "token"));
}).pipe(Effect.provide(layer));
});
it.effect("never puts a saved token that is unsafe for an HTTP header on the wire", () => {
const { execute, layer } = makeLayer({
response: () => Response.json({ username: "bitbucket-user" }),
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const settings = yield* ServerSettings.ServerSettingsService;
// Fetch would reject this header with an error quoting the token, and that error reaches
// clients. The unusable token is ignored, so the environment credential is used instead.
yield* settings.updateSettings({ bitbucket: { accessToken: "saved\ntoken" } });
yield* bitbucket.probeAuth;
assert.strictEqual(
execute.mock.calls.at(-1)?.[0].headers.authorization,
`Basic ${btoa("[email protected]:token")}`,
);
}).pipe(Effect.provide(layer));
});
it.effect("reports saved credentials as configured when Bitbucket cannot confirm them", () => {
const { layer } = makeLayer({
response: () => new Response(null, { status: 401 }),
env: { T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0" },
});
return Effect.gen(function* () {
const bitbucket = yield* BitbucketApi.BitbucketApi;
const settings = yield* ServerSettings.ServerSettingsService;
assert.strictEqual((yield* bitbucket.probeAuth).status, "unauthenticated");
yield* settings.updateSettings({ bitbucket: { accessToken: "saved-access-token" } });
assert.deepStrictEqual(yield* bitbucket.probeAuth, {
status: "unknown",
account: Option.none(),
host: Option.some("bitbucket.org"),
detail: Option.some("An access token is configured."),
});
}).pipe(Effect.provide(layer));
});
it.effect("preserves the HTTP client failure without deriving the domain message from it", () => {
const transportCause = new Error("socket reset by peer");
let requestFailure: HttpClientError.HttpClientError | undefined;
+79 -21
View File
@@ -7,8 +7,10 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
DEFAULT_SERVER_SETTINGS,
NonNegativeInt,
TrimmedNonEmptyString,
type BitbucketSettings,
type SourceControlProviderAuth,
type SourceControlRepositoryCloneUrls,
type SourceControlRepositoryVisibility,
@@ -28,6 +30,7 @@ import {
} from "./bitbucketPullRequests.ts";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
import * as SourceControlProvider from "./SourceControlProvider.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import { retryAtFromHeader } from "./SourceControlRateLimit.ts";
@@ -537,24 +540,64 @@ function repositoryOwnerName(repositoryName: string): string {
return repositoryName.split("/")[0]?.trim() || "bitbucket";
}
function authFromConfig(
config: Config.Success<typeof BitbucketApiEnvConfig>,
): SourceControlProviderAuth {
if (Option.isSome(config.accessToken)) {
type BitbucketCredential =
| { readonly kind: "access-token"; readonly accessToken: string }
| { readonly kind: "api-token"; readonly email: string; readonly apiToken: string };
/**
* Visible ASCII only. A value the HTTP stack rejects makes it throw an error quoting the whole
* header, and that error travels to clients as a cause, so an unusable token is treated as unset.
*/
const HEADER_SAFE = /^[\x21-\x7e]+$/u;
function credentialFrom(input: {
readonly accessToken: string;
readonly email: string;
readonly apiToken: string;
}): BitbucketCredential | null {
if (HEADER_SAFE.test(input.accessToken)) {
return { kind: "access-token", accessToken: input.accessToken };
}
if (HEADER_SAFE.test(input.email) && HEADER_SAFE.test(input.apiToken)) {
return { kind: "api-token", email: input.email, apiToken: input.apiToken };
}
return null;
}
/**
* Credentials saved in settings win over the `T3CODE_BITBUCKET_*` environment variables, which
* stay as a fallback. Within each source the access token wins.
*/
function resolveCredential(
settings: BitbucketSettings,
env: Config.Success<typeof BitbucketApiEnvConfig>,
): BitbucketCredential | null {
return (
credentialFrom(settings) ??
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") {
return {
status: "unknown",
account: Option.none(),
host: Option.some("bitbucket.org"),
detail: Option.some("Bitbucket access token is configured."),
detail: Option.some("An access token is configured."),
};
}
if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
if (credential?.kind === "api-token") {
return {
status: "unknown",
account: config.email,
account: Option.some(credential.email),
host: Option.some("bitbucket.org"),
detail: Option.some("Bitbucket API token is configured."),
detail: Option.some("An API token is configured."),
};
}
@@ -563,7 +606,7 @@ function authFromConfig(
account: Option.none(),
host: Option.some("bitbucket.org"),
detail: Option.some(
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
"Add a Bitbucket token in Settings → Source Control, or set the T3CODE_BITBUCKET_* environment variables on the server.",
),
};
}
@@ -612,6 +655,7 @@ function responseError(
/** @public Service construction is part of the canonical Effect module API. */
export const make = Effect.gen(function* () {
const config = yield* BitbucketApiEnvConfig;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const httpClient = yield* HttpClient.HttpClient;
const fileSystem = yield* FileSystem.FileSystem;
const git = yield* GitVcsDriver.GitVcsDriver;
@@ -619,15 +663,27 @@ export const make = Effect.gen(function* () {
const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
const withAuth = (request: HttpClientRequest.HttpClientRequest) => {
if (Option.isSome(config.accessToken)) {
return request.pipe(HttpClientRequest.bearerToken(config.accessToken.value));
}
if (Option.isSome(config.email) && Option.isSome(config.apiToken)) {
return request.pipe(HttpClientRequest.basicAuth(config.email.value, config.apiToken.value));
}
return request;
};
// Read on every request so credentials saved in settings apply without a restart.
const currentCredential = serverSettings.getSettings.pipe(
Effect.map((settings) => resolveCredential(settings.bitbucket, config)),
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(DEFAULT_SERVER_SETTINGS.bitbucket, config))),
),
);
const withAuth = (request: HttpClientRequest.HttpClientRequest) =>
currentCredential.pipe(
Effect.map((credential) =>
credential === null
? request
: credential.kind === "access-token"
? request.pipe(HttpClientRequest.bearerToken(credential.accessToken))
: request.pipe(HttpClientRequest.basicAuth(credential.email, credential.apiToken)),
),
);
const decodeResponse = <S extends Schema.Top>(
operation: BitbucketApiOperation,
@@ -654,7 +710,8 @@ export const make = Effect.gen(function* () {
request: HttpClientRequest.HttpClientRequest,
schema: S,
): Effect.Effect<S["Type"], BitbucketApiError, S["DecodingServices"]> =>
httpClient.execute(withAuth(request.pipe(HttpClientRequest.acceptJson))).pipe(
withAuth(request.pipe(HttpClientRequest.acceptJson)).pipe(
Effect.flatMap(httpClient.execute),
Effect.mapError(
(cause) =>
new BitbucketRequestError({
@@ -847,7 +904,8 @@ export const make = Effect.gen(function* () {
input.body === undefined
? base
: base.pipe(HttpClientRequest.bodyText(input.body, "application/json"));
return httpClient.execute(withAuth(withBody)).pipe(
return withAuth(withBody).pipe(
Effect.flatMap(httpClient.execute),
Effect.mapError(
(cause): BitbucketApiError => new BitbucketRequestError({ operation: "request", cause }),
),
@@ -913,7 +971,7 @@ export const make = Effect.gen(function* () {
host: Option.some("bitbucket.org"),
detail: Option.none<string>(),
})),
Effect.orElseSucceed(() => authFromConfig(config)),
Effect.catch(() => currentCredential.pipe(Effect.map(authFromCredential))),
),
listPullRequests: (input) =>
resolveRepository(input).pipe(
@@ -192,8 +192,7 @@ export const makeDiscovery = Effect.gen(function* () {
type: "api",
kind: "bitbucket",
label: "Bitbucket",
installHint:
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN on the server (use a Bitbucket API token with pull request, repository, and user read scopes).",
installHint: "Add a Bitbucket token in Settings → Source Control.",
probeAuth: bitbucket.probeAuth,
} satisfies SourceControlApiDiscoverySpec;
});
@@ -423,7 +423,7 @@ it.effect("reports implemented tools separately from locally available executabl
account: Option.none(),
host: Option.some("bitbucket.org"),
detail: Option.some(
"Set T3CODE_BITBUCKET_EMAIL and T3CODE_BITBUCKET_API_TOKEN, or T3CODE_BITBUCKET_ACCESS_TOKEN.",
"Add a Bitbucket token in Settings → Source Control, or set the T3CODE_BITBUCKET_* environment variables on the server.",
),
}),
},