Skip to content

Commit 5da5595

Browse files
gabrielelpidioclaudejuliusmarminge
authored
feat: save Bitbucket credentials from Source Control settings (pingdotgg#14103)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Julius Marminge <[email protected]>
1 parent e518866 commit 5da5595

13 files changed

Lines changed: 678 additions & 53 deletions

‎apps/server/scripts/evaluate-thread-titles.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import * as GitLabCli from "../src/sourceControl/GitLabCli.ts";
2828
import * as ForgejoCli from "../src/sourceControl/ForgejoCli.ts";
2929
import * as AzureDevOpsCli from "../src/sourceControl/AzureDevOpsCli.ts";
3030
import * as BitbucketApi from "../src/sourceControl/BitbucketApi.ts";
31+
import * as ServerSettings from "../src/serverSettings.ts";
3132
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
3233
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
3334
import * as VcsProjectConfig from "../src/vcs/VcsProjectConfig.ts";
@@ -155,7 +156,8 @@ await Effect.runPromise(
155156
GitLabCli.layer,
156157
ForgejoCli.layer,
157158
AzureDevOpsCli.layer,
158-
BitbucketApi.layer,
159+
// No saved credentials here; Bitbucket falls back to T3CODE_BITBUCKET_* variables.
160+
BitbucketApi.layer.pipe(Layer.provide(ServerSettings.layerTest())),
159161
),
160162
),
161163
Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))),

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

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ const makeServerSettingsLayer = () =>
4444
),
4545
);
4646

47+
/** Like `makeServerSettingsLayer`, but also exposes the secret store for assertions. */
48+
const makeServerSettingsLayerWithSecrets = () =>
49+
ServerSettingsModule.layer.pipe(
50+
Layer.provideMerge(ServerSecretStore.layer),
51+
Layer.provideMerge(Layer.fresh(SqlitePersistenceMemory)),
52+
Layer.provideMerge(
53+
Layer.fresh(
54+
ServerConfig.layerTest(process.cwd(), {
55+
prefix: "t3code-server-settings-test-",
56+
}),
57+
),
58+
),
59+
);
60+
4761
const makeFailingSecretStoreLayer = (cause: ServerSecretStore.SecretStoreError) =>
4862
Layer.succeed(
4963
ServerSecretStore.ServerSecretStore,
@@ -1278,6 +1292,128 @@ it.layer(NodeServices.layer)("server settings", (it) => {
12781292
}).pipe(Effect.provide(makeServerSettingsLayer())),
12791293
);
12801294

1295+
it.effect(
1296+
"keeps Bitbucket tokens in the secret store and tells clients only that one is set",
1297+
() =>
1298+
Effect.gen(function* () {
1299+
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1300+
const secrets = yield* ServerSecretStore.ServerSecretStore;
1301+
const serverConfig = yield* ServerConfig.ServerConfig;
1302+
const fileSystem = yield* FileSystem.FileSystem;
1303+
1304+
const saved = yield* serverSettings.updateSettings({
1305+
bitbucket: { email: "[email protected]", accessToken: "bb-access", apiToken: "bb-api" },
1306+
});
1307+
assert.deepEqual(saved.bitbucket, {
1308+
1309+
accessToken: "bb-access",
1310+
apiToken: "bb-api",
1311+
});
1312+
1313+
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
1314+
assert.notInclude(raw, "bb-access");
1315+
assert.notInclude(raw, "bb-api");
1316+
assert.include(raw, "[email protected]");
1317+
1318+
const forClient = ServerSettingsModule.redactServerSettingsForClient(saved).bitbucket;
1319+
assert.equal(forClient.email, "[email protected]");
1320+
assert.notInclude(forClient.accessToken, "bb-access");
1321+
assert.notInclude(forClient.apiToken, "bb-api");
1322+
assert.isAbove(forClient.accessToken.length, 0);
1323+
assert.isAbove(forClient.apiToken.length, 0);
1324+
1325+
// A client echoing the redacted values back, or omitting them, keeps the saved tokens.
1326+
yield* serverSettings.updateSettings({ bitbucket: forClient });
1327+
yield* serverSettings.updateSettings({ bitbucket: { email: "[email protected]" } });
1328+
assert.deepEqual((yield* serverSettings.getSettings).bitbucket, {
1329+
1330+
accessToken: "bb-access",
1331+
apiToken: "bb-api",
1332+
});
1333+
1334+
const cleared = yield* serverSettings.updateSettings({ bitbucket: { accessToken: "" } });
1335+
assert.equal(cleared.bitbucket.accessToken, "");
1336+
assert.equal(cleared.bitbucket.apiToken, "bb-api");
1337+
assert.isTrue(Option.isNone(yield* secrets.get("bitbucket-access-token")));
1338+
assert.equal(
1339+
ServerSettingsModule.redactServerSettingsForClient(cleared).bitbucket.accessToken,
1340+
"",
1341+
);
1342+
}).pipe(Effect.provide(makeServerSettingsLayerWithSecrets())),
1343+
);
1344+
1345+
it.effect("removes a Bitbucket secret once its token is cleared by hand in settings.json", () =>
1346+
Effect.gen(function* () {
1347+
const serverConfig = yield* ServerConfig.ServerConfig;
1348+
const fileSystem = yield* FileSystem.FileSystem;
1349+
const secrets = yield* ServerSecretStore.ServerSecretStore;
1350+
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1351+
// A token was saved, then the user deleted it from settings.json directly.
1352+
yield* secrets.set("bitbucket-access-token", new TextEncoder().encode("stale-token"));
1353+
yield* fileSystem.writeFileString(serverConfig.settingsPath, "{}");
1354+
1355+
yield* serverSettings.updateSettings({ cursorKeychainUsageEnabled: true });
1356+
1357+
assert.isTrue(Option.isNone(yield* secrets.get("bitbucket-access-token")));
1358+
}).pipe(Effect.provide(makeServerSettingsLayerWithSecrets())),
1359+
);
1360+
1361+
it.effect("moves a hand-edited Bitbucket token into the secret store when settings load", () =>
1362+
Effect.gen(function* () {
1363+
const serverConfig = yield* ServerConfig.ServerConfig;
1364+
const fileSystem = yield* FileSystem.FileSystem;
1365+
const secrets = yield* ServerSecretStore.ServerSecretStore;
1366+
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1367+
yield* fileSystem.writeFileString(
1368+
serverConfig.settingsPath,
1369+
'{"bitbucket":{"accessToken":"hand-edited-token"}}',
1370+
);
1371+
1372+
// Loading alone moves it: no settings update is needed.
1373+
const loaded = yield* serverSettings.getSettings;
1374+
1375+
assert.equal(loaded.bitbucket.accessToken, "hand-edited-token");
1376+
assert.notInclude(
1377+
yield* fileSystem.readFileString(serverConfig.settingsPath),
1378+
"hand-edited-token",
1379+
);
1380+
const stored = yield* secrets.get("bitbucket-access-token");
1381+
assert.equal(
1382+
Option.isSome(stored) ? new TextDecoder().decode(stored.value) : null,
1383+
"hand-edited-token",
1384+
);
1385+
}).pipe(Effect.provide(makeServerSettingsLayerWithSecrets())),
1386+
);
1387+
1388+
it.effect(
1389+
"moves a hand-edited Bitbucket token into the secret store when a client echoes the marker",
1390+
() =>
1391+
Effect.gen(function* () {
1392+
const serverConfig = yield* ServerConfig.ServerConfig;
1393+
const fileSystem = yield* FileSystem.FileSystem;
1394+
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
1395+
yield* fileSystem.writeFileString(
1396+
serverConfig.settingsPath,
1397+
'{"bitbucket":{"email":"[email protected]","apiToken":"hand-edited-token"}}',
1398+
);
1399+
1400+
// The form resends the redacted token when only the email changes.
1401+
const forClient = ServerSettingsModule.redactServerSettingsForClient(
1402+
yield* serverSettings.getSettings,
1403+
).bitbucket;
1404+
const updated = yield* serverSettings.updateSettings({
1405+
bitbucket: { email: "[email protected]", apiToken: forClient.apiToken },
1406+
});
1407+
1408+
assert.equal(updated.bitbucket.apiToken, "hand-edited-token");
1409+
assert.equal((yield* serverSettings.getSettings).bitbucket.apiToken, "hand-edited-token");
1410+
assert.notInclude(
1411+
yield* fileSystem.readFileString(serverConfig.settingsPath),
1412+
"hand-edited-token",
1413+
);
1414+
}).pipe(Effect.provide(makeServerSettingsLayer())),
1415+
);
1416+
12811417
it.effect("materializes provider secrets for terminal environment resolution", () =>
12821418
Effect.gen(function* () {
12831419
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;

‎apps/server/src/serverSettings.ts‎

Lines changed: 89 additions & 12 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<
@@ -555,6 +568,35 @@ const make = Effect.gen(function* () {
555568
),
556569
);
557570

571+
/**
572+
* Moves Bitbucket tokens hand-edited into settings.json into the secret store as they load,
573+
* so plaintext does not stay on disk. If the store is unavailable, the token keeps working
574+
* from the file and the move is retried on the next load.
575+
*/
576+
const moveInlineBitbucketTokens = (settings: ServerSettings) =>
577+
Effect.gen(function* () {
578+
const bitbucket = { ...settings.bitbucket };
579+
let moved = false;
580+
for (const field of BITBUCKET_SECRET_FIELDS) {
581+
const value = bitbucket[field];
582+
if (value.length === 0 || value === SECRET_REDACTED) continue;
583+
const stored = yield* secretStore
584+
.set(BITBUCKET_SECRET_NAMES[field], textEncoder.encode(value))
585+
.pipe(
586+
Effect.as(true),
587+
Effect.catch(() =>
588+
Effect.logWarning("failed to move a Bitbucket token into the secret store", {
589+
field,
590+
}).pipe(Effect.as(false)),
591+
),
592+
);
593+
if (!stored) continue;
594+
bitbucket[field] = SECRET_REDACTED;
595+
moved = true;
596+
}
597+
return moved ? { ...settings, bitbucket } : settings;
598+
});
599+
558600
const loadSettingsFromDisk = Effect.gen(function* () {
559601
let settings = DEFAULT_SERVER_SETTINGS;
560602
let persisted: typeof PersistedOptionalProviderSettings.Type = {};
@@ -639,10 +681,12 @@ const make = Effect.gen(function* () {
639681
const folded = settingsFileTrusted
640682
? foldLegacyProjectSettings(loaded, legacyProjectRows)
641683
: loaded;
642-
if (folded !== loaded) {
643-
yield* writeSettingsAtomically(folded);
684+
// Only rewrite a file that decoded cleanly; an untrusted one stays for the user to repair.
685+
const migrated = settingsFileTrusted ? yield* moveInlineBitbucketTokens(folded) : folded;
686+
if (migrated !== loaded) {
687+
yield* writeSettingsAtomically(migrated);
644688
}
645-
return folded;
689+
return migrated;
646690
});
647691

648692
const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
@@ -693,7 +737,7 @@ const make = Effect.gen(function* () {
693737
}
694738
const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
695739
for (const [sourceId, source] of Object.entries(settings.usageLimitSources)) {
696-
if (source.managementKey !== USAGE_LIMIT_SOURCE_KEY_REDACTED) {
740+
if (source.managementKey !== SECRET_REDACTED) {
697741
usageLimitSources[sourceId] = source;
698742
continue;
699743
}
@@ -709,10 +753,23 @@ const make = Effect.gen(function* () {
709753
managementKey: Option.isSome(secret) ? textDecoder.decode(secret.value) : "",
710754
};
711755
}
756+
const bitbucket = { ...settings.bitbucket };
757+
for (const field of BITBUCKET_SECRET_FIELDS) {
758+
if (bitbucket[field] !== SECRET_REDACTED) continue;
759+
const secret = yield* secretStore
760+
.get(BITBUCKET_SECRET_NAMES[field])
761+
.pipe(
762+
Effect.mapError(
763+
(cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),
764+
),
765+
);
766+
bitbucket[field] = Option.isSome(secret) ? textDecoder.decode(secret.value) : "";
767+
}
712768
return {
713769
...settings,
714770
providerInstances: providerInstances as ServerSettings["providerInstances"],
715771
usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
772+
bitbucket,
716773
};
717774
});
718775

@@ -829,7 +886,7 @@ const make = Effect.gen(function* () {
829886
const usageLimitSources: Record<string, UsageLimitSourceConfig> = {};
830887
for (const [sourceId, source] of Object.entries(next.usageLimitSources)) {
831888
const secretName = usageLimitSourceSecretName(sourceId);
832-
if (source.managementKey === USAGE_LIMIT_SOURCE_KEY_REDACTED) {
889+
if (source.managementKey === SECRET_REDACTED) {
833890
usageLimitSources[sourceId] = source;
834891
continue;
835892
}
@@ -843,7 +900,7 @@ const make = Effect.gen(function* () {
843900
secretName,
844901
value: textEncoder.encode(source.managementKey),
845902
});
846-
usageLimitSources[sourceId] = { ...source, managementKey: USAGE_LIMIT_SOURCE_KEY_REDACTED };
903+
usageLimitSources[sourceId] = { ...source, managementKey: SECRET_REDACTED };
847904
}
848905
for (const sourceId of Object.keys(current.usageLimitSources)) {
849906
if (sourceId in next.usageLimitSources) continue;
@@ -854,11 +911,31 @@ const make = Effect.gen(function* () {
854911
});
855912
}
856913

914+
const bitbucket = { ...next.bitbucket };
915+
for (const field of BITBUCKET_SECRET_FIELDS) {
916+
let value = bitbucket[field];
917+
if (value === SECRET_REDACTED) {
918+
// The marker keeps what is saved. A plaintext value hand-edited into settings.json
919+
// is not in the secret store yet, so move it there instead of dropping it.
920+
const inline = current.bitbucket[field];
921+
if (inline === SECRET_REDACTED || inline.length === 0) continue;
922+
value = inline;
923+
}
924+
const secretName = BITBUCKET_SECRET_NAMES[field];
925+
if (value.length === 0) {
926+
changes.push({ kind: "remove", secretName, operation: "remove-secret" });
927+
continue;
928+
}
929+
changes.push({ kind: "write", secretName, value: textEncoder.encode(value) });
930+
bitbucket[field] = SECRET_REDACTED;
931+
}
932+
857933
return {
858934
settings: {
859935
...next,
860936
providerInstances: providerInstances as ServerSettings["providerInstances"],
861937
usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],
938+
bitbucket,
862939
},
863940
changes,
864941
};

0 commit comments

Comments
 (0)