Skip to content

Commit ceb05fe

Browse files
committed
fix(server): stop sending self-hosted Bitbucket repositories to Bitbucket Cloud
1 parent 5cc99e1 commit ceb05fe

4 files changed

Lines changed: 173 additions & 4 deletions

File tree

‎apps/server/src/pullRequest/PullRequestService.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
22
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
33
import * as KeyValueStore from "effect/unstable/persistence/KeyValueStore";
44
import { assert, it } from "@effect/vitest";
5+
import * as ConfigProvider from "effect/ConfigProvider";
56
import * as Deferred from "effect/Deferred";
67
import * as Effect from "effect/Effect";
78
import * as Fiber from "effect/Fiber";
@@ -592,6 +593,91 @@ it.effect("reads nothing from a host with no implementation, but reports it", ()
592593
}),
593594
);
594595

596+
it.effect(
597+
"reports a self-hosted Bitbucket as unimplemented instead of asking Bitbucket Cloud",
598+
() =>
599+
Effect.gen(function* () {
600+
const listed: string[] = [];
601+
const service = yield* makeService({
602+
projects: [
603+
project({
604+
id: "p1",
605+
title: "cloud",
606+
workspaceRoot: "/a",
607+
repository: "workspace/cloud",
608+
provider: "bitbucket",
609+
host: "bitbucket.org",
610+
}),
611+
project({
612+
id: "p2",
613+
title: "data center",
614+
workspaceRoot: "/b",
615+
repository: "proj/repo",
616+
provider: "bitbucket",
617+
host: "bitbucket.example.com",
618+
}),
619+
],
620+
providers: [
621+
fakeProvider("bitbucket", {
622+
listChangeRequests: (input) => {
623+
listed.push(input.repository);
624+
return Effect.succeed({ items: [], truncated: false, continues: true });
625+
},
626+
}),
627+
],
628+
});
629+
630+
const result = yield* service.list({ state: "open" });
631+
632+
assert.deepStrictEqual(listed, ["workspace/cloud"]);
633+
assert.deepStrictEqual(
634+
result.providers.map((summary) => ({ host: summary.host, configured: summary.configured })),
635+
[
636+
{ host: "bitbucket.org", configured: true },
637+
{ host: "bitbucket.example.com", configured: false },
638+
],
639+
);
640+
}),
641+
);
642+
643+
it.effect("reads a self-hosted Bitbucket through a Cloud root that was set on purpose", () =>
644+
Effect.gen(function* () {
645+
const listed: string[] = [];
646+
const service = yield* makeService({
647+
projects: [
648+
project({
649+
id: "p1",
650+
title: "data center",
651+
workspaceRoot: "/b",
652+
repository: "proj/repo",
653+
provider: "bitbucket",
654+
host: "bitbucket.example.com",
655+
}),
656+
],
657+
providers: [
658+
fakeProvider("bitbucket", {
659+
listChangeRequests: (input) => {
660+
listed.push(input.repository);
661+
return Effect.succeed({ items: [], truncated: false, continues: true });
662+
},
663+
}),
664+
],
665+
}).pipe(
666+
Effect.provide(
667+
ConfigProvider.layer(
668+
ConfigProvider.fromEnv({
669+
env: { T3CODE_BITBUCKET_API_BASE_URL: "https://bitbucket-proxy.example.com/2.0" },
670+
}),
671+
),
672+
),
673+
);
674+
675+
yield* service.list({ state: "open" });
676+
677+
assert.deepStrictEqual(listed, ["proj/repo"]);
678+
}),
679+
);
680+
595681
it.effect("asks for a whole page of a host, and for the reader's own size when given one", () =>
596682
Effect.gen(function* () {
597683
const limits: number[] = [];

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ import {
7272
} from "@t3tools/contracts";
7373
import { detectSourceControlProviderFromRemoteUrl } from "@t3tools/shared/sourceControl";
7474

75+
import * as BitbucketApi from "../sourceControl/BitbucketApi.ts";
7576
import { AllowGitHubReserve } from "../sourceControl/GitHubCli.ts";
7677
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
7778
import * as PullRequestFilesViewed from "../persistence/PullRequestFilesViewed.ts";
@@ -626,6 +627,7 @@ export const make = Effect.gen(function* () {
626627
const rateLimits = yield* SourceControlRateLimit.SourceControlRateLimit;
627628
const filesViewedStore = yield* PullRequestFilesViewed.PullRequestFilesViewedRepository;
628629
const readCache = yield* PullRequestReadCache.PullRequestReadCache;
630+
const bitbucketApiBaseUrlConfigured = yield* BitbucketApi.BitbucketApiBaseUrlConfigured;
629631

630632
const refineUnknownProjectKinds = (
631633
projects: ReadonlyArray<OrchestrationProjectShell>,
@@ -758,7 +760,13 @@ export const make = Effect.gen(function* () {
758760
if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
759761
continue;
760762
}
761-
const api = registry.get(kind);
763+
// The Bitbucket provider speaks only Bitbucket Cloud's API. Unless a Cloud root was set
764+
// on purpose, a Server or Data Center host has no implementation here, rather than one
765+
// that asks bitbucket.org about it.
766+
const api =
767+
kind === "bitbucket" && host !== "bitbucket.org" && !bitbucketApiBaseUrlConfigured
768+
? null
769+
: registry.get(kind);
762770
// Recorded before the de-duplication below, so the viewer lookup keeps the alternates
763771
// the listing is about to drop.
764772
if (api !== null) {

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

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ function makeLayer(input: {
6666
) => HttpClientError.HttpClientError;
6767
readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
6868
readonly env?: Record<string, string>;
69+
readonly remoteUrl?: string;
6970
}) {
7071
const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
7172
input.requestFailure
@@ -109,7 +110,7 @@ function makeLayer(input: {
109110
remotes: [
110111
{
111112
name: "origin",
112-
url: "[email protected]:pingdotgg/t3code.git",
113+
url: input.remoteUrl ?? "[email protected]:pingdotgg/t3code.git",
113114
pushUrl: Option.none(),
114115
isPrimary: true,
115116
},
@@ -717,6 +718,60 @@ it.effect("keeps the 429 retry time when the response body cannot be read", () =
717718
}).pipe(Effect.provide(layer));
718719
});
719720

721+
it.effect("never asks Bitbucket Cloud about a self-hosted Bitbucket remote", () => {
722+
const remoteUrl = "https://bitbucket.example.com/scm/proj/repo.git";
723+
const { execute, layer } = makeLayer({
724+
response: () => Response.json({ values: [] }),
725+
remoteUrl,
726+
env: { T3CODE_BITBUCKET_EMAIL: "[email protected]", T3CODE_BITBUCKET_API_TOKEN: "token" },
727+
});
728+
729+
return Effect.gen(function* () {
730+
const bitbucket = yield* BitbucketApi.BitbucketApi;
731+
const error = yield* bitbucket
732+
.listPullRequests({
733+
cwd: "/repo",
734+
context: {
735+
provider: {
736+
kind: "bitbucket",
737+
name: "Bitbucket Self-Hosted",
738+
baseUrl: "https://bitbucket.example.com",
739+
},
740+
remoteName: "origin",
741+
remoteUrl,
742+
},
743+
headSelector: "feature/x",
744+
state: "open",
745+
})
746+
.pipe(Effect.flip);
747+
748+
assert.strictEqual(error._tag, "BitbucketRepositoryRemoteNotFoundError");
749+
assert.strictEqual(execute.mock.calls.length, 0);
750+
}).pipe(Effect.provide(layer));
751+
});
752+
753+
it.effect("sends a self-hosted Bitbucket remote to a Cloud root that was set on purpose", () => {
754+
const remoteUrl = "https://bitbucket.example.com/scm/proj/repo.git";
755+
const { execute, layer } = makeLayer({
756+
response: () => Response.json({ values: [] }),
757+
remoteUrl,
758+
});
759+
760+
return Effect.gen(function* () {
761+
const bitbucket = yield* BitbucketApi.BitbucketApi;
762+
yield* bitbucket.listPullRequests({
763+
cwd: "/repo",
764+
headSelector: "feature/x",
765+
state: "open",
766+
});
767+
768+
assert.strictEqual(
769+
execute.mock.calls[0]?.[0].url,
770+
"https://api.test.local/2.0/repositories/proj/repo/pullrequests",
771+
);
772+
}).pipe(Effect.provide(layer));
773+
});
774+
720775
it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
721776
const { git, layer } = makeLayer({
722777
response: () =>

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

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,18 @@ const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
4141
/** Bitbucket redirects a diff once; this leaves room without following a chain forever. */
4242
const MAX_REDIRECTS = 3;
4343

44+
/**
45+
* Whether a Cloud API root was set on purpose. Only then is a Bitbucket remote on a host other
46+
* than bitbucket.org sent to it; by default that host is Server or Data Center, which this
47+
* client cannot speak to.
48+
*/
49+
export const BitbucketApiBaseUrlConfigured = Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
50+
Config.option,
51+
Config.map(Option.isSome),
52+
);
53+
4454
const BitbucketApiEnvConfig = Config.all({
55+
baseUrlConfigured: BitbucketApiBaseUrlConfigured,
4556
baseUrl: Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
4657
Config.withDefault(DEFAULT_API_BASE_URL),
4758
),
@@ -663,6 +674,15 @@ export const make = Effect.gen(function* () {
663674

664675
const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
665676

677+
/** This API is Bitbucket Cloud's; a Server or Data Center remote is not one it can address. */
678+
const isAddressableRemote = (remoteUrl: string) => {
679+
const provider = detectSourceControlProviderFromRemoteUrl(remoteUrl);
680+
return (
681+
provider?.kind === "bitbucket" &&
682+
(config.baseUrlConfigured || provider.baseUrl === "https://bitbucket.org")
683+
);
684+
};
685+
666686
// Read on every request so credentials saved in settings apply without a restart.
667687
const currentCredential = serverSettings.getSettings.pipe(
668688
Effect.map((settings) => resolveCredential(settings.bitbucket, config)),
@@ -732,7 +752,7 @@ export const make = Effect.gen(function* () {
732752
if (fromRepository) return fromRepository;
733753

734754
const fromContext =
735-
input.context?.provider.kind === "bitbucket"
755+
input.context?.provider.kind === "bitbucket" && isAddressableRemote(input.context.remoteUrl)
736756
? parseBitbucketRemoteUrl(input.context.remoteUrl)
737757
: null;
738758
if (fromContext) return fromContext;
@@ -757,7 +777,7 @@ export const make = Effect.gen(function* () {
757777
);
758778

759779
for (const remote of remotes.remotes) {
760-
if (detectSourceControlProviderFromRemoteUrl(remote.url)?.kind !== "bitbucket") continue;
780+
if (!isAddressableRemote(remote.url)) continue;
761781
const parsed = parseBitbucketRemoteUrl(remote.url);
762782
if (parsed) return parsed;
763783
}

0 commit comments

Comments
 (0)