Skip to content

Commit daff7b0

Browse files
feat: save Bitbucket credentials from Source Control settings
Bitbucket could only be configured through T3CODE_BITBUCKET_* environment variables and a server restart. Settings → Source Control now has fields for an access token or an Atlassian email + API token, saved on the environment's server. Tokens follow the existing write-only secret path: the server keeps them in its secret store, and settings.json and clients only see a redaction marker. BitbucketApi resolves credentials per request (saved settings first, then the environment variables), so changes apply without a restart. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent d15210c commit daff7b0

12 files changed

Lines changed: 448 additions & 44 deletions

‎apps/server/src/serverSettings.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1278,6 +1278,70 @@ it.layer(NodeServices.layer)("server settings", (it) => {
12781278
}).pipe(Effect.provide(makeServerSettingsLayer())),
12791279
);
12801280

1281+
it.effect(
1282+
"keeps Bitbucket tokens in the secret store and tells clients only that one is set",
1283+
() =>
1284+
Effect.gen(function* () {
1285+
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1286+
const secrets = yield* ServerSecretStore.ServerSecretStore;
1287+
const serverConfig = yield* ServerConfig.ServerConfig;
1288+
const fileSystem = yield* FileSystem.FileSystem;
1289+
1290+
const saved = yield* serverSettings.updateSettings({
1291+
bitbucket: { email: "[email protected]", accessToken: "bb-access", apiToken: "bb-api" },
1292+
});
1293+
assert.deepEqual(saved.bitbucket, {
1294+
1295+
accessToken: "bb-access",
1296+
apiToken: "bb-api",
1297+
});
1298+
1299+
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
1300+
assert.notInclude(raw, "bb-access");
1301+
assert.notInclude(raw, "bb-api");
1302+
assert.include(raw, "[email protected]");
1303+
1304+
const forClient = ServerSettingsModule.redactServerSettingsForClient(saved).bitbucket;
1305+
assert.equal(forClient.email, "[email protected]");
1306+
assert.notInclude(forClient.accessToken, "bb-access");
1307+
assert.notInclude(forClient.apiToken, "bb-api");
1308+
assert.isAbove(forClient.accessToken.length, 0);
1309+
assert.isAbove(forClient.apiToken.length, 0);
1310+
1311+
// A client echoing the redacted values back, or omitting them, keeps the saved tokens.
1312+
yield* serverSettings.updateSettings({ bitbucket: forClient });
1313+
yield* serverSettings.updateSettings({ bitbucket: { email: "[email protected]" } });
1314+
assert.deepEqual((yield* serverSettings.getSettings).bitbucket, {
1315+
1316+
accessToken: "bb-access",
1317+
apiToken: "bb-api",
1318+
});
1319+
1320+
const cleared = yield* serverSettings.updateSettings({ bitbucket: { accessToken: "" } });
1321+
assert.equal(cleared.bitbucket.accessToken, "");
1322+
assert.equal(cleared.bitbucket.apiToken, "bb-api");
1323+
assert.isTrue(Option.isNone(yield* secrets.get("bitbucket-access-token")));
1324+
assert.equal(
1325+
ServerSettingsModule.redactServerSettingsForClient(cleared).bitbucket.accessToken,
1326+
"",
1327+
);
1328+
}).pipe(
1329+
Effect.provide(
1330+
ServerSettingsModule.layer.pipe(
1331+
Layer.provideMerge(ServerSecretStore.layer),
1332+
Layer.provideMerge(Layer.fresh(SqlitePersistenceMemory)),
1333+
Layer.provideMerge(
1334+
Layer.fresh(
1335+
ServerConfig.layerTest(process.cwd(), {
1336+
prefix: "t3code-server-settings-test-",
1337+
}),
1338+
),
1339+
),
1340+
),
1341+
),
1342+
),
1343+
);
1344+
12811345
it.effect("materializes provider secrets for terminal environment resolution", () =>
12821346
Effect.gen(function* () {
12831347
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;

‎apps/server/src/serverSettings.ts‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -140,16 +140,24 @@ function providerEnvironmentSecretName(input: {
140140
}
141141

142142
/**
143-
* On disk the hub key is replaced by this marker and the real value lives in
144-
* the secret store, mirroring provider environment secrets. A client that
145-
* sends the marker back means "keep what you have".
143+
* On disk a hub key or Bitbucket token is replaced by this marker and the
144+
* real value lives in the secret store, mirroring provider environment
145+
* secrets. A client that sends the marker back means "keep what you have".
146146
*/
147-
const USAGE_LIMIT_SOURCE_KEY_REDACTED = "\u2022\u2022\u2022\u2022\u2022\u2022";
147+
const SECRET_REDACTED = "\u2022\u2022\u2022\u2022\u2022\u2022";
148148

149149
function usageLimitSourceSecretName(sourceId: string): string {
150150
return `usage-limit-source-${Buffer.from(sourceId, "utf8").toString("base64url")}`;
151151
}
152152

153+
const BITBUCKET_SECRET_NAMES = {
154+
accessToken: "bitbucket-access-token",
155+
apiToken: "bitbucket-api-token",
156+
} as const;
157+
const BITBUCKET_SECRET_FIELDS = ["accessToken", "apiToken"] as const;
158+
159+
const redactSecret = (value: string) => (value.length > 0 ? SECRET_REDACTED : "");
160+
153161
function redactProviderEnvironmentVariable(
154162
variable: ProviderInstanceEnvironmentVariable,
155163
): ProviderInstanceEnvironmentVariable {
@@ -182,11 +190,16 @@ export function redactServerSettingsForClient(settings: ServerSettings): ServerS
182190
id,
183191
{
184192
...source,
185-
managementKey: source.managementKey.length > 0 ? USAGE_LIMIT_SOURCE_KEY_REDACTED : "",
193+
managementKey: redactSecret(source.managementKey),
186194
},
187195
]),
188196
);
189-
return { ...settings, providerInstances, usageLimitSources };
197+
const bitbucket = {
198+
...settings.bitbucket,
199+
accessToken: redactSecret(settings.bitbucket.accessToken),
200+
apiToken: redactSecret(settings.bitbucket.apiToken),
201+
};
202+
return { ...settings, providerInstances, usageLimitSources, bitbucket };
190203
}
191204

192205
export class ServerSettingsService extends Context.Service<
@@ -693,7 +706,7 @@ const make = Effect.gen(function* () {
693706
}
694707
const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
695708
for (const [sourceId, source] of Object.entries(settings.usageLimitSources)) {
696-
if (source.managementKey !== USAGE_LIMIT_SOURCE_KEY_REDACTED) {
709+
if (source.managementKey !== SECRET_REDACTED) {
697710
usageLimitSources[sourceId] = source;
698711
continue;
699712
}
@@ -709,10 +722,23 @@ const make = Effect.gen(function* () {
709722
managementKey: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
710723
};
711724
}
725+
const bitbucket = { ...settings.bitbucket };
726+
for (const field of BITBUCKET_SECRET_FIELDS) {
727+
if (bitbucket[field] !== SECRET_REDACTED) continue;
728+
const secret = yield* secretStore
729+
.get(BITBUCKET_SECRET_NAMES[field])
730+
.pipe(
731+
Effect.mapError(
732+
(cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),
733+
),
734+
);
735+
bitbucket[field] = Option.isSome(secret) ? textDecoder.decode(secret.value) : "";
736+
}
712737
return {
713738
...settings,
714739
providerInstances: providerInstances as ServerSettings["providerInstances"],
715740
usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
741+
bitbucket,
716742
};
717743
});
718744

@@ -829,7 +855,7 @@ const make = Effect.gen(function* () {
829855
const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
830856
for (const [sourceId, source] of Object.entries(next.usageLimitSources)) {
831857
const secretName = usageLimitSourceSecretName(sourceId);
832-
if (source.managementKey === USAGE_LIMIT_SOURCE_KEY_REDACTED) {
858+
if (source.managementKey === SECRET_REDACTED) {
833859
usageLimitSources[sourceId] = source;
834860
continue;
835861
}
@@ -843,7 +869,7 @@ const make = Effect.gen(function* () {
843869
secretName,
844870
value: textEncoder.encode(source.managementKey),
845871
});
846-
usageLimitSources[sourceId] = { ...source, managementKey: USAGE_LIMIT_SOURCE_KEY_REDACTED };
872+
usageLimitSources[sourceId] = { ...source, managementKey: SECRET_REDACTED };
847873
}
848874
for (const sourceId of Object.keys(current.usageLimitSources)) {
849875
if (sourceId in next.usageLimitSources) continue;
@@ -854,11 +880,26 @@ const make = Effect.gen(function* () {
854880
});
855881
}
856882

883+
const bitbucket = { ...next.bitbucket };
884+
for (const field of BITBUCKET_SECRET_FIELDS) {
885+
const value = bitbucket[field];
886+
if (value === SECRET_REDACTED) continue;
887+
if (value.length === 0 && current.bitbucket[field].length === 0) continue;
888+
const secretName = BITBUCKET_SECRET_NAMES[field];
889+
if (value.length === 0) {
890+
changes.push({ kind: "remove", secretName, operation: "remove-secret" });
891+
continue;
892+
}
893+
changes.push({ kind: "write", secretName, value: textEncoder.encode(value) });
894+
bitbucket[field] = SECRET_REDACTED;
895+
}
896+
857897
return {
858898
settings: {
859899
...next,
860900
providerInstances: providerInstances as ServerSettings["providerInstances"],
861901
usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
902+
bitbucket,
862903
},
863904
changes,
864905
};

‎apps/server/src/sourceControl/BitbucketApi.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616

1717
import { GitCommandError } from "@t3tools/contracts";
1818
import * as BitbucketApi from "./BitbucketApi.ts";
19+
import * as ServerSettings from "../serverSettings.ts";
1920
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
2021
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
2122
import type * as VcsDriver from "../vcs/VcsDriver.ts";
@@ -64,6 +65,7 @@ function makeLayer(input: {
6465
request: HttpClientRequest.HttpClientRequest,
6566
) => HttpClientError.HttpClientError;
6667
readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
68+
readonly env?: Record<string, string>;
6769
}) {
6870
const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
6971
input.requestFailure
@@ -150,14 +152,15 @@ function makeLayer(input: {
150152
Layer.provide(
151153
ConfigProvider.layer(
152154
ConfigProvider.fromEnv({
153-
env: {
155+
env: input.env ?? {
154156
T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0",
155157
T3CODE_BITBUCKET_EMAIL: "[email protected]",
156158
T3CODE_BITBUCKET_API_TOKEN: "token",
157159
},
158160
}),
159161
),
160162
),
163+
Layer.provideMerge(ServerSettings.layerTest()),
161164
Layer.provideMerge(NodeServices.layer),
162165
);
163166

@@ -509,6 +512,58 @@ it.effect("reports auth status through the Bitbucket REST /user endpoint", () =>
509512
}).pipe(Effect.provide(layer));
510513
});
511514

515+
it.effect("prefers credentials saved in settings over the environment, without a restart", () => {
516+
const { execute, layer } = makeLayer({
517+
response: () => Response.json({ username: "bitbucket-user" }),
518+
});
519+
const lastAuthorization = () => execute.mock.calls.at(-1)?.[0].headers.authorization;
520+
const basic = (user: string, password: string) => `Basic ${btoa(`${user}:${password}`)}`;
521+
522+
return Effect.gen(function* () {
523+
const bitbucket = yield* BitbucketApi.BitbucketApi;
524+
const settings = yield* ServerSettings.ServerSettingsService;
525+
526+
yield* bitbucket.probeAuth;
527+
assert.strictEqual(lastAuthorization(), basic("[email protected]", "token"));
528+
529+
yield* settings.updateSettings({
530+
bitbucket: { email: "[email protected]", apiToken: "saved-api-token" },
531+
});
532+
yield* bitbucket.probeAuth;
533+
assert.strictEqual(lastAuthorization(), basic("[email protected]", "saved-api-token"));
534+
535+
yield* settings.updateSettings({ bitbucket: { accessToken: "saved-access-token" } });
536+
yield* bitbucket.probeAuth;
537+
assert.strictEqual(lastAuthorization(), "Bearer saved-access-token");
538+
539+
yield* settings.updateSettings({ bitbucket: { accessToken: "", apiToken: "" } });
540+
yield* bitbucket.probeAuth;
541+
assert.strictEqual(lastAuthorization(), basic("[email protected]", "token"));
542+
}).pipe(Effect.provide(layer));
543+
});
544+
545+
it.effect("reports saved credentials as configured when Bitbucket cannot confirm them", () => {
546+
const { layer } = makeLayer({
547+
response: () => new Response(null, { status: 401 }),
548+
env: { T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0" },
549+
});
550+
551+
return Effect.gen(function* () {
552+
const bitbucket = yield* BitbucketApi.BitbucketApi;
553+
const settings = yield* ServerSettings.ServerSettingsService;
554+
555+
assert.strictEqual((yield* bitbucket.probeAuth).status, "unauthenticated");
556+
557+
yield* settings.updateSettings({ bitbucket: { accessToken: "saved-access-token" } });
558+
assert.deepStrictEqual(yield* bitbucket.probeAuth, {
559+
status: "unknown",
560+
account: Option.none(),
561+
host: Option.some("bitbucket.org"),
562+
detail: Option.some("Bitbucket access token is configured."),
563+
});
564+
}).pipe(Effect.provide(layer));
565+
});
566+
512567
it.effect("preserves the HTTP client failure without deriving the domain message from it", () => {
513568
const transportCause = new Error("socket reset by peer");
514569
let requestFailure: HttpClientError.HttpClientError | undefined;

0 commit comments

Comments
 (0)