Skip to content

Commit 3c3a8f5

Browse files
only21milclaudecodexmaria-rcks
authored
fix(bitbucket): skip Cloud API reads for unsupported Server remotes (pingdotgg#22029)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: GPT-6.1 Sol <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent 915bb6d commit 3c3a8f5

7 files changed

Lines changed: 177 additions & 3 deletions

File tree

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,52 @@ it.effect("reads nothing from a host with no implementation, but reports it", ()
482482
}),
483483
);
484484

485+
it.effect("reads nothing from a host its provider does not serve, but reports it", () =>
486+
Effect.gen(function* () {
487+
const reached = new Set<string>();
488+
const bitbucket = (id: string, host: string) =>
489+
project({
490+
id,
491+
title: host,
492+
workspaceRoot: `/${id}`,
493+
repository: "proj/repo",
494+
provider: SourceControlProviderKind.make("bitbucket"),
495+
host,
496+
});
497+
const service = yield* makeService({
498+
projects: [bitbucket("p1", "bitbucket.org"), bitbucket("p2", "bitbucket.example.com")],
499+
providers: [
500+
fakePullRequestProvider(SourceControlProviderKind.make("bitbucket"), {
501+
servesHost: (host) => host === "bitbucket.org",
502+
getViewer: ({ host }) => {
503+
reached.add(host ?? "");
504+
return Effect.succeed("bilal");
505+
},
506+
listChangeRequests: ({ host }) => {
507+
reached.add(host);
508+
return Effect.succeed({ items: [], truncated: false, continues: false });
509+
},
510+
}),
511+
],
512+
});
513+
514+
const result = yield* service.list({ state: "open" });
515+
516+
assert.deepStrictEqual([...reached], ["bitbucket.org"]);
517+
assert.deepStrictEqual(
518+
result.providers.map(({ host, configured, detail }) => ({ host, configured, detail })),
519+
[
520+
{ host: "bitbucket.org", configured: true, detail: null },
521+
{
522+
host: "bitbucket.example.com",
523+
configured: false,
524+
detail: "This host cannot be browsed here yet.",
525+
},
526+
],
527+
);
528+
}),
529+
);
530+
485531
it.effect("says where each repository carries on, and from nothing it has run out of", () =>
486532
Effect.gen(function* () {
487533
const service = yield* makeService({

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,7 @@ function withRateLimitBackoff(
515515
? {}
516516
: { unavailableRequirement: api.unavailableRequirement }),
517517
...(api.repositoryKey === undefined ? {} : { repositoryKey: api.repositoryKey }),
518+
...(api.servesHost === undefined ? {} : { servesHost: api.servesHost }),
518519
...(api.readsPublicHostWithoutCheckout === undefined
519520
? {}
520521
: { readsPublicHostWithoutCheckout: api.readsPublicHostWithoutCheckout }),
@@ -925,7 +926,8 @@ export const make = Effect.gen(function* () {
925926
if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
926927
continue;
927928
}
928-
const api = registry.get(kind);
929+
const registered = registry.get(kind);
930+
const api = registered?.servesHost?.(host) === false ? null : registered;
929931
if (api !== null) {
930932
const roots = viewerRoots.get(host);
931933
if (roots === undefined) viewerRoots.set(host, [project.workspaceRoot]);

‎packages/source-control-bitbucket/src/server/BitbucketApi.test.ts‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as FileSystem from "effect/FileSystem";
1010
import * as Layer from "effect/Layer";
1111
import * as Option from "effect/Option";
1212
import * as Queue from "effect/Queue";
13+
import * as Result from "effect/Result";
1314
import * as Schema from "effect/Schema";
1415
import * as TestClock from "effect/testing/TestClock";
1516
import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
@@ -72,6 +73,7 @@ function makeLayer(input: {
7273
readonly stall?: boolean;
7374
readonly git?: Partial<HostGit>;
7475
readonly env?: Record<string, string>;
76+
readonly remoteUrl?: string;
7577
}) {
7678
const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
7779
input.stall
@@ -108,7 +110,7 @@ function makeLayer(input: {
108110
remotes: [
109111
{
110112
name: "origin",
111-
url: "[email protected]:pingdotgg/t3code.git",
113+
url: input.remoteUrl ?? "[email protected]:pingdotgg/t3code.git",
112114
pushUrl: Option.none(),
113115
isPrimary: true,
114116
},
@@ -337,6 +339,78 @@ it.effect("prefers an explicit repository and uses context when the repository i
337339
}).pipe(Effect.provide(layer));
338340
});
339341

342+
it.effect("sends a self-hosted Bitbucket remote nowhere unless an API base url is configured", () =>
343+
Effect.gen(function* () {
344+
const remoteUrl = "https://bitbucket.example.com/scm/proj/repo.git";
345+
const context = {
346+
provider: {
347+
kind: SourceControlProviderKind.make("bitbucket"),
348+
name: "Bitbucket Self-Hosted",
349+
baseUrl: "https://bitbucket.example.com",
350+
},
351+
remoteName: "origin",
352+
remoteUrl,
353+
};
354+
const cloudEnv = {
355+
T3CODE_BITBUCKET_EMAIL: "[email protected]",
356+
T3CODE_BITBUCKET_API_TOKEN: "t",
357+
};
358+
const response = (request: HttpClientRequest.HttpClientRequest) =>
359+
Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson);
360+
const defaultBranch = (setup: ReturnType<typeof makeLayer>, withContext: boolean) =>
361+
BitbucketApi.BitbucketApi.pipe(
362+
Effect.flatMap((bitbucket) =>
363+
bitbucket.getDefaultBranch({ cwd: "/repo", ...(withContext ? { context } : {}) }),
364+
),
365+
Effect.provide(setup.layer),
366+
);
367+
const requestedUrls = (setup: ReturnType<typeof makeLayer>) =>
368+
setup.execute.mock.calls.map(([request]) => request.url).toSorted();
369+
370+
// A self-hosted remote in the checkout, then a self-hosted context beside a Cloud remote.
371+
for (const [setup, withContext] of [
372+
[makeLayer({ response, env: cloudEnv, remoteUrl }), false],
373+
[makeLayer({ response, env: cloudEnv }), true],
374+
] as const) {
375+
const result = yield* defaultBranch(setup, withContext).pipe(Effect.result);
376+
assert.deepStrictEqual(requestedUrls(setup), []);
377+
assert.strictEqual(
378+
Result.isFailure(result) && result.failure._tag,
379+
"BitbucketRepositoryRemoteNotFoundError",
380+
);
381+
}
382+
383+
// An explicit repository does not let a self-hosted context reach the Cloud API.
384+
const explicit = makeLayer({ response, env: cloudEnv });
385+
const cloneUrls = yield* BitbucketApi.BitbucketApi.pipe(
386+
Effect.flatMap((bitbucket) =>
387+
bitbucket.getRepositoryCloneUrls({ cwd: "/repo", context, repository: "proj/repo" }),
388+
),
389+
Effect.provide(explicit.layer),
390+
Effect.result,
391+
);
392+
assert.deepStrictEqual(requestedUrls(explicit), []);
393+
assert.strictEqual(
394+
Result.isFailure(cloneUrls) && cloneUrls.failure._tag,
395+
"BitbucketRepositoryRemoteNotFoundError",
396+
);
397+
398+
const cloud = makeLayer({ response, env: cloudEnv });
399+
yield* defaultBranch(cloud, false);
400+
assert.deepStrictEqual(requestedUrls(cloud), [
401+
"https://api.bitbucket.org/2.0/repositories/pingdotgg/t3code",
402+
"https://api.bitbucket.org/2.0/repositories/pingdotgg/t3code/branching-model",
403+
]);
404+
405+
const configured = makeLayer({ response, remoteUrl });
406+
yield* defaultBranch(configured, true);
407+
assert.deepStrictEqual(requestedUrls(configured), [
408+
"https://api.test.local/2.0/repositories/proj/repo",
409+
"https://api.test.local/2.0/repositories/proj/repo/branching-model",
410+
]);
411+
}),
412+
);
413+
340414
it.effect(
341415
"prefers the Bitbucket branching model development branch as the default PR target",
342416
() => {

‎packages/source-control-bitbucket/src/server/BitbucketApi.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
SourceControlProviderKind,
1313
TrimmedNonEmptyString,
1414
type SourceControlProviderAuth,
15+
type SourceControlProviderInfo,
1516
type SourceControlRepositoryCloneUrls,
1617
type SourceControlRepositoryVisibility,
1718
} from "@t3tools/contracts";
@@ -51,6 +52,15 @@ const BitbucketApiEnvConfig = Config.all({
5152
apiToken: Config.String("T3CODE_BITBUCKET_API_TOKEN").pipe(Config.option),
5253
});
5354

55+
// Server and Data Center use a different API; a custom Cloud endpoint must be explicit.
56+
export const BitbucketServesHost = Config.String("T3CODE_BITBUCKET_API_BASE_URL").pipe(
57+
Config.option,
58+
Config.map(
59+
(baseUrl) => (host: string) =>
60+
Option.isSome(baseUrl) || host === "bitbucket.org" || host.endsWith(".bitbucket.org"),
61+
),
62+
);
63+
5464
const BitbucketApiOperation = Schema.Literals([
5565
"resolveRepository",
5666
"getRepository",
@@ -646,6 +656,11 @@ export const make = Effect.gen(function* () {
646656
host: "bitbucket.org",
647657
};
648658

659+
const servesHost = yield* BitbucketServesHost;
660+
661+
const servesProvider = (provider: SourceControlProviderInfo | null) =>
662+
provider?.kind === "bitbucket" && servesHost(URL.parse(provider.baseUrl)?.hostname ?? "");
663+
649664
const apiUrl = (path: string) => `${config.baseUrl.replace(/\/+$/u, "")}${path}`;
650665

651666
const currentCredential = host.settings.get.pipe(
@@ -757,6 +772,10 @@ export const make = Effect.gen(function* () {
757772
readonly context?: SourceControlProvider.SourceControlProviderContext;
758773
readonly repository?: string;
759774
}) {
775+
if (input.context?.provider.kind === "bitbucket" && !servesProvider(input.context.provider)) {
776+
// Falling back to another remote could act on a different repository.
777+
return yield* new BitbucketRepositoryRemoteNotFoundError({ cwd: input.cwd });
778+
}
760779
if (input.repository !== undefined) {
761780
return yield* requireRepositoryLocator(input.repository);
762781
}
@@ -787,7 +806,7 @@ export const make = Effect.gen(function* () {
787806
);
788807

789808
for (const remote of remotes.remotes) {
790-
if (recognizeRemoteWith(definition, remote.url) === null) continue;
809+
if (!servesProvider(recognizeRemoteWith(definition, remote.url))) continue;
791810
const parsed = parseBitbucketRemoteUrl(remote.url);
792811
if (parsed) return parsed;
793812
}

‎packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { SourceControlProviderKind } from "@t3tools/contracts";
22
import { describe, expect, it } from "@effect/vitest";
3+
import * as ConfigProvider from "effect/ConfigProvider";
34
import * as Effect from "effect/Effect";
45
import * as Layer from "effect/Layer";
56
import * as Result from "effect/Result";
@@ -178,6 +179,30 @@ it.effect("reads checks and PR state without diff, mergeability, or permission r
178179
}),
179180
);
180181

182+
it.effect("serves only Bitbucket Cloud hosts unless an API base url is configured", () =>
183+
Effect.gen(function* () {
184+
const servedHosts = (env: Record<string, string>) =>
185+
make.pipe(
186+
Effect.map(({ servesHost }) =>
187+
["bitbucket.org", "altssh.bitbucket.org", "bitbucket.example.com"].filter(
188+
(host) => servesHost?.(host) === true,
189+
),
190+
),
191+
Effect.provide(
192+
Layer.merge(
193+
Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}),
194+
ConfigProvider.layer(ConfigProvider.fromEnv({ env })),
195+
),
196+
),
197+
);
198+
199+
expect(yield* servedHosts({})).toEqual(["bitbucket.org", "altssh.bitbucket.org"]);
200+
expect(
201+
yield* servedHosts({ T3CODE_BITBUCKET_API_BASE_URL: "https://bitbucket.example.com/api" }),
202+
).toEqual(["bitbucket.org", "altssh.bitbucket.org", "bitbucket.example.com"]);
203+
}),
204+
);
205+
181206
describe("bitbucketProviderFailure", () => {
182207
it("treats only an HTTP 401 as unusable credentials", () => {
183208
const responseError = (status: number) =>

‎packages/source-control-bitbucket/src/server/BitbucketPullRequestProvider.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { resolvePullRequestAuthorFilter, SourceControlProviderKind } from "@t3to
22
import * as Effect from "effect/Effect";
33
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
44

5+
import * as BitbucketApi from "./BitbucketApi.ts";
56
import * as BitbucketPullRequestApi from "./BitbucketPullRequestApi.ts";
67
import {
78
PullRequestProviderError,
@@ -109,6 +110,7 @@ function toChangeRequest(pullRequest: BitbucketPullRequest): ProviderChangeReque
109110

110111
export const make = Effect.gen(function* () {
111112
const api = yield* BitbucketPullRequestApi.BitbucketPullRequestApi;
113+
const servesHost = yield* BitbucketApi.BitbucketServesHost.pipe(Effect.orDie);
112114

113115
const fail =
114116
(operation: string) => (error: BitbucketPullRequestApi.BitbucketPullRequestApiError) =>
@@ -148,6 +150,7 @@ export const make = Effect.gen(function* () {
148150
const provider: PullRequestProviderApi = {
149151
kind: SourceControlProviderKind.make("bitbucket"),
150152
capabilities: CAPABILITIES,
153+
servesHost,
151154
unavailableRequirement: UNAVAILABLE_REQUIREMENT,
152155
readsPublicHostWithoutCheckout: true,
153156

‎packages/source-control-core/src/server/PullRequestProvider.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,11 @@ export interface PullRequestProviderApi {
308308
* definition's `publicHost` can be read from a project with no checkout of its repository.
309309
*/
310310
readonly readsPublicHostWithoutCheckout?: boolean;
311+
/**
312+
* Absent means every host detected as this kind is read. A host it refuses is listed as one that
313+
* cannot be browsed here, and nothing is sent for it.
314+
*/
315+
readonly servesHost?: (host: string) => boolean;
311316

312317
readonly getViewer: (input: {
313318
readonly cwd: string;

0 commit comments

Comments
 (0)