Open History to see the last commit
1import { assert, it, vi } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as DateTime from "effect/DateTime";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Schema from "effect/Schema";
10import * as TestClock from "effect/testing/TestClock";
11import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
12
13import { GitCommandError } from "@t3tools/contracts";
14import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi";
15import * as ServerSettings from "../serverSettings.ts";
16import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
17import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
18import type * as VcsDriver from "../vcs/VcsDriver.ts";
19import * as ServerSourceControlHost from "./ServerSourceControlHost.ts";
20import * as VcsProcess from "../vcs/VcsProcess.ts";
21
22const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
23
24const bitbucketPullRequest = {
25 id: 42,
26 title: "Add Bitbucket provider",
27 state: "OPEN",
28 updated_on: "2026-01-02T00:00:00.000Z",
29 links: {
30 html: {
31 href: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
32 },
33 },
34 source: {
35 branch: { name: "feature/source-control" },
36 repository: {
37 full_name: "octocat/t3code",
38 workspace: { slug: "octocat" },
39 },
40 },
41 destination: {
42 branch: { name: "main" },
43 repository: {
44 full_name: "pingdotgg/t3code",
45 workspace: { slug: "pingdotgg" },
46 },
47 },
48};
49
50const repositoryJson = {
51 full_name: "pingdotgg/t3code",
52 links: {
53 html: { href: "https://bitbucket.org/pingdotgg/t3code" },
54 clone: [
55 { name: "https", href: "https://bitbucket.org/pingdotgg/t3code.git" },
56 { name: "ssh", href: "git@bitbucket.org:pingdotgg/t3code.git" },
57 ],
58 },
59 mainbranch: { name: "main" },
60};
61
62function makeLayer(input: {
63 readonly response: (request: HttpClientRequest.HttpClientRequest) => Response;
64 readonly requestFailure?: (
65 request: HttpClientRequest.HttpClientRequest,
66 ) => HttpClientError.HttpClientError;
67 readonly git?: Partial<GitVcsDriver.GitVcsDriver["Service"]>;
68 readonly env?: Record<string, string>;
69}) {
70 const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
71 input.requestFailure
72 ? Effect.fail(input.requestFailure(request))
73 : Effect.succeed(HttpClientResponse.fromWeb(request, input.response(request))),
74 );
75 const gitMock = {
76 readConfigValue: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["readConfigValue"]>(() =>
77 Effect.succeed<string | null>("git@bitbucket.org:pingdotgg/t3code.git"),
78 ),
79 resolvePrimaryRemoteName: vi.fn<
80 GitVcsDriver.GitVcsDriver["Service"]["resolvePrimaryRemoteName"]
81 >(() => Effect.succeed("origin")),
82 ensureRemote: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["ensureRemote"]>(() =>
83 Effect.succeed("octocat"),
84 ),
85 fetchRemoteBranch: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteBranch"]>(
86 () => Effect.void,
87 ),
88 fetchRemoteTrackingBranch: vi.fn<
89 GitVcsDriver.GitVcsDriver["Service"]["fetchRemoteTrackingBranch"]
90 >(() => Effect.void),
91 setBranchUpstream: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["setBranchUpstream"]>(
92 () => Effect.void,
93 ),
94 switchRef: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["switchRef"]>((request) =>
95 Effect.succeed({ refName: request.refName }),
96 ),
97 listLocalBranchNames: vi.fn<GitVcsDriver.GitVcsDriver["Service"]["listLocalBranchNames"]>(() =>
98 Effect.succeed([]),
99 ),
100 };
101 const git = {
102 ...gitMock,
103 ...input.git,
104 } satisfies Partial<GitVcsDriver.GitVcsDriver["Service"]>;
105
106 const driver = {
107 listRemotes: vi.fn(() =>
108 Effect.succeed({
109 remotes: [
110 {
111 name: "origin",
112 url: "git@bitbucket.org:pingdotgg/t3code.git",
113 pushUrl: Option.none(),
114 isPrimary: true,
115 },
116 ],
117 freshness: {
118 source: "live-local" as const,
119 observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
120 expiresAt: Option.none(),
121 },
122 }),
123 ),
124 } satisfies Partial<VcsDriver.VcsDriver["Service"]>;
125
126 const resolve = vi.fn(() =>
127 Effect.succeed({
128 kind: "git" as const,
129 repository: {
130 kind: "git" as const,
131 rootPath: "/repo",
132 metadataPath: null,
133 freshness: {
134 source: "live-local" as const,
135 observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
136 expiresAt: Option.none(),
137 },
138 },
139 driver: driver as unknown as VcsDriver.VcsDriver["Service"],
140 }),
141 );
142
143 const layer = BitbucketApi.layer.pipe(
144 Layer.provide(ServerSourceControlHost.layer),
145 Layer.provide(Layer.mock(VcsProcess.VcsProcess)({})),
146 Layer.provide(
147 Layer.succeed(
148 HttpClient.HttpClient,
149 HttpClient.make((request) => execute(request)),
150 ),
151 ),
152 Layer.provide(
153 Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
154 resolve,
155 }),
156 ),
157 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)(git)),
158 Layer.provide(
159 ConfigProvider.layer(
160 ConfigProvider.fromEnv({
161 env: input.env ?? {
162 T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0",
163 T3CODE_BITBUCKET_EMAIL: "user@example.com",
164 T3CODE_BITBUCKET_API_TOKEN: "token",
165 },
166 }),
167 ),
168 ),
169 Layer.provideMerge(ServerSettings.layerTest()),
170 Layer.provideMerge(NodeServices.layer),
171 );
172
173 return { execute, git: gitMock, resolve, listRemotes: driver.listRemotes, layer };
174}
175
176it.effect("parses pull request responses from the Bitbucket REST API", () => {
177 const { execute, layer } = makeLayer({
178 response: () =>
179 Response.json({
180 ...bitbucketPullRequest,
181 }),
182 });
183
184 return Effect.gen(function* () {
185 const bitbucket = yield* BitbucketApi.BitbucketApi;
186 const result = yield* bitbucket.getPullRequest({
187 cwd: "/repo",
188 reference: "#42",
189 });
190
191 assert.deepStrictEqual(result, {
192 number: 42,
193 title: "Add Bitbucket provider",
194 url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
195 baseRefName: "main",
196 headRefName: "feature/source-control",
197 state: "open",
198 updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
199 isCrossRepository: true,
200 headRepositoryNameWithOwner: "octocat/t3code",
201 headRepositoryOwnerLogin: "octocat",
202 });
203 assert.strictEqual(
204 execute.mock.calls[0]?.[0].url,
205 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests/42",
206 );
207 }).pipe(Effect.provide(layer));
208});
209
210it.effect("lists pull requests with Bitbucket state and source branch query params", () => {
211 const { execute, layer } = makeLayer({
212 response: () =>
213 Response.json({
214 values: [
215 {
216 ...bitbucketPullRequest,
217 id: 7,
218 state: "MERGED",
219 source: {
220 branch: { name: "feature/merged" },
221 repository: { full_name: "pingdotgg/t3code" },
222 },
223 },
224 ],
225 }),
226 });
227
228 return Effect.gen(function* () {
229 const bitbucket = yield* BitbucketApi.BitbucketApi;
230 const result = yield* bitbucket.listPullRequests({
231 cwd: "/repo",
232 headSelector: "origin:feature/merged",
233 state: "merged",
234 limit: 10,
235 });
236
237 assert.strictEqual(result[0]?.state, "merged");
238 const request = execute.mock.calls[0]?.[0];
239 assert.strictEqual(
240 request?.url,
241 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
242 );
243 assert.deepStrictEqual(request?.urlParams.params, [
244 ["pagelen", "10"],
245 ["sort", "-updated_on"],
246 ["q", 'source.branch.name = "feature/merged" AND state = "MERGED"'],
247 ["state", "MERGED"],
248 ]);
249 }).pipe(Effect.provide(layer));
250});
251
252it.effect("lists closed pull requests with both closed Bitbucket states", () => {
253 const { execute, layer } = makeLayer({
254 response: () =>
255 Response.json({
256 values: [],
257 }),
258 });
259
260 return Effect.gen(function* () {
261 const bitbucket = yield* BitbucketApi.BitbucketApi;
262 yield* bitbucket.listPullRequests({
263 cwd: "/repo",
264 headSelector: "feature/closed",
265 state: "closed",
266 limit: 10,
267 });
268
269 assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [
270 ["pagelen", "10"],
271 ["sort", "-updated_on"],
272 [
273 "q",
274 'source.branch.name = "feature/closed" AND (state = "DECLINED" OR state = "SUPERSEDED")',
275 ],
276 ["state", "DECLINED"],
277 ["state", "SUPERSEDED"],
278 ]);
279 }).pipe(Effect.provide(layer));
280});
281
282it.effect("expands all-state pull request listing instead of relying on Bitbucket defaults", () => {
283 const { execute, layer } = makeLayer({
284 response: () =>
285 Response.json({
286 values: [],
287 }),
288 });
289
290 return Effect.gen(function* () {
291 const bitbucket = yield* BitbucketApi.BitbucketApi;
292 yield* bitbucket.listPullRequests({
293 cwd: "/repo",
294 headSelector: "feature/all",
295 state: "all",
296 limit: 10,
297 });
298
299 assert.deepStrictEqual(execute.mock.calls[0]?.[0].urlParams.params, [
300 ["pagelen", "10"],
301 ["sort", "-updated_on"],
302 [
303 "q",
304 'source.branch.name = "feature/all" AND (state = "OPEN" OR state = "MERGED" OR state = "DECLINED" OR state = "SUPERSEDED")',
305 ],
306 ["state", "OPEN"],
307 ["state", "MERGED"],
308 ["state", "DECLINED"],
309 ["state", "SUPERSEDED"],
310 ]);
311 }).pipe(Effect.provide(layer));
312});
313
314it.effect("reads repository clone URLs and default branch", () => {
315 const { layer } = makeLayer({
316 response: (request) =>
317 Response.json(
318 request.url.endsWith("/branching-model")
319 ? {
320 development: {
321 branch: { name: "main" },
322 name: "main",
323 use_mainbranch: true,
324 },
325 }
326 : repositoryJson,
327 ),
328 });
329
330 return Effect.gen(function* () {
331 const bitbucket = yield* BitbucketApi.BitbucketApi;
332 const cloneUrls = yield* bitbucket.getRepositoryCloneUrls({
333 cwd: "/repo",
334 repository: "pingdotgg/t3code",
335 });
336 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
337
338 assert.deepStrictEqual(cloneUrls, {
339 nameWithOwner: "pingdotgg/t3code",
340 url: "https://bitbucket.org/pingdotgg/t3code.git",
341 sshUrl: "git@bitbucket.org:pingdotgg/t3code.git",
342 });
343 assert.strictEqual(defaultBranch, "main");
344 }).pipe(Effect.provide(layer));
345});
346
347it.effect.each([false, true])(
348 "rejects invalid explicit repositories before fallback, context=%s",
349 (withContext) => {
350 const { execute, resolve, listRemotes, layer } = makeLayer({
351 response: () => Response.json(repositoryJson),
352 });
353
354 return Effect.gen(function* () {
355 const bitbucket = yield* BitbucketApi.BitbucketApi;
356 for (const repository of ["t3code", "", " \t "]) {
357 const error = yield* bitbucket
358 .getRepositoryCloneUrls({
359 cwd: "/repo",
360 repository,
361 ...(withContext
362 ? {
363 context: {
364 provider: {
365 kind: "bitbucket" as const,
366 name: "Bitbucket",
367 baseUrl: "https://bitbucket.org",
368 },
369 remoteName: "origin",
370 remoteUrl: "git@bitbucket.org:pingdotgg/t3code.git",
371 },
372 }
373 : {}),
374 })
375 .pipe(Effect.match({ onFailure: (error) => error, onSuccess: () => null }));
376
377 assert.instanceOf(error, BitbucketApi.BitbucketRepositoryLocatorError);
378 assert.strictEqual(
379 isBitbucketRepositoryLocatorError(error) ? error.repository : null,
380 repository,
381 );
382 assert.strictEqual(resolve.mock.calls.length, 0);
383 assert.strictEqual(listRemotes.mock.calls.length, 0);
384 assert.strictEqual(execute.mock.calls.length, 0);
385 }
386 }).pipe(Effect.provide(layer));
387 },
388);
389
390it.effect("prefers an explicit repository and uses context when the repository is omitted", () => {
391 const { execute, resolve, listRemotes, layer } = makeLayer({
392 response: (request) =>
393 Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson),
394 });
395
396 return Effect.gen(function* () {
397 const bitbucket = yield* BitbucketApi.BitbucketApi;
398 const context = {
399 provider: { kind: "bitbucket" as const, name: "Bitbucket", baseUrl: "https://bitbucket.org" },
400 remoteName: "origin",
401 remoteUrl: "git@bitbucket.org:another/context.git",
402 };
403 for (const repository of ["pingdotgg/t3code", "https://bitbucket.org/pingdotgg/t3code.git"]) {
404 yield* bitbucket.getRepositoryCloneUrls({ cwd: "/repo", context, repository });
405 }
406 yield* bitbucket.getDefaultBranch({ cwd: "/repo", context });
407
408 assert.deepStrictEqual(
409 execute.mock.calls.map(([request]) => request.url).toSorted(),
410 [
411 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
412 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
413 "https://api.test.local/2.0/repositories/another/context",
414 "https://api.test.local/2.0/repositories/another/context/branching-model",
415 ].toSorted(),
416 );
417 assert.strictEqual(resolve.mock.calls.length, 0);
418 assert.strictEqual(listRemotes.mock.calls.length, 0);
419 }).pipe(Effect.provide(layer));
420});
421
422it.effect("discovers the repository from cwd remotes when the repository is omitted", () => {
423 const { execute, resolve, listRemotes, layer } = makeLayer({
424 response: (request) =>
425 Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson),
426 });
427
428 return Effect.gen(function* () {
429 const bitbucket = yield* BitbucketApi.BitbucketApi;
430 const branch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
431
432 assert.strictEqual(branch, "main");
433 assert.deepStrictEqual(resolve.mock.calls, [[{ cwd: "/repo" }]]);
434 assert.deepStrictEqual(listRemotes.mock.calls, [["/repo"]]);
435 assert.isTrue(
436 execute.mock.calls.every(([request]) =>
437 request.url.startsWith("https://api.test.local/2.0/repositories/pingdotgg/t3code"),
438 ),
439 );
440 }).pipe(Effect.provide(layer));
441});
442
443it.effect(
444 "prefers the Bitbucket branching model development branch as the default PR target",
445 () => {
446 const { execute, layer } = makeLayer({
447 response: (request) =>
448 Response.json(
449 request.url.endsWith("/branching-model")
450 ? {
451 development: {
452 branch: { name: "develop" },
453 name: "develop",
454 use_mainbranch: false,
455 },
456 }
457 : repositoryJson,
458 ),
459 });
460
461 return Effect.gen(function* () {
462 const bitbucket = yield* BitbucketApi.BitbucketApi;
463 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
464
465 assert.strictEqual(defaultBranch, "develop");
466 assert.deepStrictEqual(
467 execute.mock.calls.map((call) => call[0].url).toSorted(),
468 [
469 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
470 "https://api.test.local/2.0/repositories/pingdotgg/t3code/branching-model",
471 ].toSorted(),
472 );
473 }).pipe(Effect.provide(layer));
474 },
475);
476
477it.effect(
478 "falls back to the repository main branch when the Bitbucket development branch is invalid",
479 () => {
480 const { layer } = makeLayer({
481 response: (request) =>
482 Response.json(
483 request.url.endsWith("/branching-model")
484 ? {
485 development: {
486 name: "develop",
487 use_mainbranch: false,
488 is_valid: false,
489 },
490 }
491 : repositoryJson,
492 ),
493 });
494
495 return Effect.gen(function* () {
496 const bitbucket = yield* BitbucketApi.BitbucketApi;
497 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
498
499 assert.strictEqual(defaultBranch, "main");
500 }).pipe(Effect.provide(layer));
501 },
502);
503
504it.effect(
505 "falls back to the repository main branch when the Bitbucket branching model is unavailable",
506 () => {
507 const { layer } = makeLayer({
508 response: (request) =>
509 request.url.endsWith("/branching-model")
510 ? Response.json({ error: { message: "Not found" } }, { status: 404 })
511 : Response.json(repositoryJson),
512 });
513
514 return Effect.gen(function* () {
515 const bitbucket = yield* BitbucketApi.BitbucketApi;
516 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
517
518 assert.strictEqual(defaultBranch, "main");
519 }).pipe(Effect.provide(layer));
520 },
521);
522
523it.effect("creates repositories through the Bitbucket REST API", () => {
524 const { execute, layer } = makeLayer({
525 response: () => Response.json(repositoryJson),
526 });
527
528 return Effect.gen(function* () {
529 const bitbucket = yield* BitbucketApi.BitbucketApi;
530 const cloneUrls = yield* bitbucket.createRepository({
531 cwd: "/repo",
532 repository: "pingdotgg/t3code",
533 visibility: "private",
534 });
535
536 assert.deepStrictEqual(cloneUrls, {
537 nameWithOwner: "pingdotgg/t3code",
538 url: "https://bitbucket.org/pingdotgg/t3code.git",
539 sshUrl: "git@bitbucket.org:pingdotgg/t3code.git",
540 });
541
542 const request = execute.mock.calls[0]?.[0];
543 assert.strictEqual(request?.url, "https://api.test.local/2.0/repositories/pingdotgg/t3code");
544 assert.strictEqual(request?.method, "POST");
545 assert.ok(request);
546 const rawBody = (request.body as { readonly body?: Uint8Array }).body;
547 assert.ok(rawBody);
548 assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
549 scm: "git",
550 is_private: true,
551 });
552 }).pipe(Effect.provide(layer));
553});
554
555it.effect("creates pull requests using the official REST payload shape", () => {
556 const { execute, layer } = makeLayer({
557 response: () => Response.json(bitbucketPullRequest),
558 });
559
560 return Effect.gen(function* () {
561 const fileSystem = yield* FileSystem.FileSystem;
562 const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "bitbucket-pr-body-" });
563 yield* fileSystem.writeFileString(bodyFile, "PR body");
564
565 const bitbucket = yield* BitbucketApi.BitbucketApi;
566 yield* bitbucket.createPullRequest({
567 cwd: "/repo",
568 baseBranch: "main",
569 headSelector: "owner:feature/provider",
570 title: "Provider PR",
571 bodyFile,
572 });
573
574 const request = execute.mock.calls[0]?.[0];
575 assert.strictEqual(
576 request?.url,
577 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
578 );
579 assert.strictEqual(request?.method, "POST");
580 assert.ok(request);
581 const rawBody = (request.body as { readonly body?: Uint8Array }).body;
582 assert.ok(rawBody);
583 assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
584 title: "Provider PR",
585 description: "PR body",
586 source: {
587 branch: { name: "feature/provider" },
588 repository: { full_name: "owner/t3code" },
589 },
590 destination: {
591 branch: { name: "main" },
592 },
593 });
594 }).pipe(Effect.provide(layer), Effect.scoped);
595});
596
597it.effect("reports auth status through the Bitbucket REST /user endpoint", () => {
598 const { layer } = makeLayer({
599 response: () => Response.json({ username: "bitbucket-user" }),
600 });
601
602 return Effect.gen(function* () {
603 const bitbucket = yield* BitbucketApi.BitbucketApi;
604 const auth = yield* bitbucket.probeAuth;
605
606 assert.deepStrictEqual(auth, {
607 status: "authenticated",
608 account: Option.some("bitbucket-user"),
609 host: Option.some("bitbucket.org"),
610 detail: Option.none(),
611 });
612 }).pipe(Effect.provide(layer));
613});
614
615it.effect("prefers credentials saved in settings over the environment, without a restart", () => {
616 const { execute, layer } = makeLayer({
617 response: () => Response.json({ username: "bitbucket-user" }),
618 });
619 const lastAuthorization = () => execute.mock.calls.at(-1)?.[0].headers.authorization;
620 const basic = (user: string, password: string) => `Basic ${btoa(`${user}:${password}`)}`;
621
622 return Effect.gen(function* () {
623 const bitbucket = yield* BitbucketApi.BitbucketApi;
624 const settings = yield* ServerSettings.ServerSettingsService;
625
626 yield* bitbucket.probeAuth;
627 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
628
629 yield* settings.updateSettings({
630 bitbucket: { email: "saved@example.com", apiToken: "saved-api-token" },
631 });
632 yield* bitbucket.probeAuth;
633 assert.strictEqual(lastAuthorization(), basic("saved@example.com", "saved-api-token"));
634
635 yield* settings.updateSettings({ bitbucket: { accessToken: "saved-access-token" } });
636 yield* bitbucket.probeAuth;
637 assert.strictEqual(lastAuthorization(), "Bearer saved-access-token");
638
639 yield* settings.updateSettings({ bitbucket: { accessToken: "", apiToken: "" } });
640 yield* bitbucket.probeAuth;
641 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
642 }).pipe(Effect.provide(layer));
643});
644
645it.effect("never puts a saved token that is unsafe for an HTTP header on the wire", () => {
646 const { execute, layer } = makeLayer({
647 response: () => Response.json({ username: "bitbucket-user" }),
648 });
649
650 return Effect.gen(function* () {
651 const bitbucket = yield* BitbucketApi.BitbucketApi;
652 const settings = yield* ServerSettings.ServerSettingsService;
653
654 // Fetch would reject this header with an error quoting the token, and that error reaches
655 // clients. The unusable token is ignored, so the environment credential is used instead.
656 yield* settings.updateSettings({ bitbucket: { accessToken: "saved\ntoken" } });
657 yield* bitbucket.probeAuth;
658 assert.strictEqual(
659 execute.mock.calls.at(-1)?.[0].headers.authorization,
660 `Basic ${btoa("user@example.com:token")}`,
661 );
662 }).pipe(Effect.provide(layer));
663});
664
665it.effect("reports saved credentials as configured when Bitbucket cannot confirm them", () => {
666 const { layer } = makeLayer({
667 response: () => new Response(null, { status: 401 }),
668 env: { T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0" },
669 });
670
671 return Effect.gen(function* () {
672 const bitbucket = yield* BitbucketApi.BitbucketApi;
673 const settings = yield* ServerSettings.ServerSettingsService;
674
675 assert.strictEqual((yield* bitbucket.probeAuth).status, "unauthenticated");
676
677 yield* settings.updateSettings({ bitbucket: { accessToken: "saved-access-token" } });
678 assert.deepStrictEqual(yield* bitbucket.probeAuth, {
679 status: "unknown",
680 account: Option.none(),
681 host: Option.some("bitbucket.org"),
682 detail: Option.some("An access token is configured."),
683 });
684 }).pipe(Effect.provide(layer));
685});
686
687it.effect("preserves the HTTP client failure without deriving the domain message from it", () => {
688 const transportCause = new Error("socket reset by peer");
689 let requestFailure: HttpClientError.HttpClientError | undefined;
690 const { layer } = makeLayer({
691 response: () => Response.json({}),
692 requestFailure: (request) => {
693 requestFailure = new HttpClientError.HttpClientError({
694 reason: new HttpClientError.TransportError({
695 request,
696 cause: transportCause,
697 }),
698 });
699 return requestFailure;
700 },
701 });
702
703 return Effect.gen(function* () {
704 const bitbucket = yield* BitbucketApi.BitbucketApi;
705 const error = yield* Effect.flip(
706 bitbucket.getPullRequest({
707 cwd: "/repo",
708 reference: "42",
709 }),
710 );
711
712 assert.instanceOf(error, BitbucketApi.BitbucketRequestError);
713 assert.strictEqual(error.operation, "getPullRequest");
714 assert.strictEqual(
715 error.message,
716 "Bitbucket API failed in getPullRequest: Failed to send the Bitbucket request.",
717 );
718 assert.strictEqual(error.cause, requestFailure);
719 assert.strictEqual(requestFailure?.cause, transportCause);
720 }).pipe(Effect.provide(layer));
721});
722
723it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
724 const responseBody = '{"error":{"message":"credential=secret-value"}}';
725 const { layer } = makeLayer({
726 response: () => new Response(responseBody, { status: 403 }),
727 });
728
729 return Effect.gen(function* () {
730 const bitbucket = yield* BitbucketApi.BitbucketApi;
731 const error = yield* bitbucket
732 .checkoutPullRequest({ cwd: "/repo", reference: "42" })
733 .pipe(Effect.flip);
734
735 assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
736 assert.strictEqual(error.operation, "getPullRequest");
737 assert.strictEqual(error.status, 403);
738 assert.strictEqual(error.responseBodyLength, responseBody.length);
739 assert.notProperty(error, "responseBody");
740 assert.strictEqual(
741 error.message,
742 "Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
743 );
744 assert.notInclude(error.message, "secret-value");
745 }).pipe(Effect.provide(layer));
746});
747
748it.effect("keeps a 429 Retry-After time on the response error", () => {
749 const { layer } = makeLayer({
750 response: () => new Response("busy", { status: 429, headers: { "Retry-After": "120" } }),
751 });
752
753 return Effect.gen(function* () {
754 yield* TestClock.setTime(1_000);
755 const bitbucket = yield* BitbucketApi.BitbucketApi;
756 const error = yield* bitbucket
757 .request({ method: "GET", url: "/repositories/acme/web" })
758 .pipe(Effect.flip);
759
760 assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
761 assert.strictEqual(error.status, 429);
762 assert.strictEqual(error.retryAt, 121_000);
763 }).pipe(Effect.provide(layer));
764});
765
766it.effect("preserves Bitbucket response body read failures as their immediate cause", () => {
767 const cause = new Error("response stream failed");
768 const { layer } = makeLayer({
769 response: () =>
770 new Response(
771 new ReadableStream<Uint8Array>({
772 start: (controller) => controller.error(cause),
773 }),
774 { status: 502 },
775 ),
776 });
777
778 return Effect.gen(function* () {
779 const bitbucket = yield* BitbucketApi.BitbucketApi;
780 const error = yield* bitbucket
781 .getPullRequest({ cwd: "/repo", reference: "42" })
782 .pipe(Effect.flip);
783
784 assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
785 assert.strictEqual(error.operation, "getPullRequest");
786 assert.strictEqual(error.status, 502);
787 assert.instanceOf(error.cause, HttpClientError.HttpClientError);
788 assert.strictEqual(error.cause.cause, cause);
789 assert.strictEqual(
790 error.message,
791 "Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 502.",
792 );
793 }).pipe(Effect.provide(layer));
794});
795
796it.effect("keeps the 429 retry time when the response body cannot be read", () => {
797 const { layer } = makeLayer({
798 response: () =>
799 new Response(
800 new ReadableStream<Uint8Array>({
801 start: (controller) => controller.error(new Error("response stream failed")),
802 }),
803 { status: 429, headers: { "Retry-After": "120" } },
804 ),
805 });
806
807 return Effect.gen(function* () {
808 yield* TestClock.setTime(1_000);
809 const bitbucket = yield* BitbucketApi.BitbucketApi;
810 const error = yield* bitbucket
811 .request({ method: "GET", url: "/repositories/acme/web" })
812 .pipe(Effect.flip);
813
814 assert.instanceOf(error, BitbucketApi.BitbucketResponseBodyReadError);
815 assert.strictEqual(error.status, 429);
816 assert.strictEqual(error.retryAt, 121_000);
817 }).pipe(Effect.provide(layer));
818});
819
820it.effect("checks out same-repository pull requests with the existing Bitbucket remote", () => {
821 const { git, layer } = makeLayer({
822 response: () =>
823 Response.json({
824 ...bitbucketPullRequest,
825 source: {
826 branch: { name: "feature/source-control" },
827 repository: {
828 full_name: "pingdotgg/t3code",
829 workspace: { slug: "pingdotgg" },
830 },
831 },
832 }),
833 });
834
835 return Effect.gen(function* () {
836 const bitbucket = yield* BitbucketApi.BitbucketApi;
837 yield* bitbucket.checkoutPullRequest({
838 cwd: "/repo",
839 context: {
840 provider: {
841 kind: "bitbucket",
842 name: "Bitbucket",
843 baseUrl: "https://bitbucket.org",
844 },
845 remoteName: "origin",
846 remoteUrl: "git@bitbucket.org:pingdotgg/t3code.git",
847 },
848 reference: "42",
849 force: true,
850 });
851
852 assert.strictEqual(git.ensureRemote.mock.calls.length, 0);
853 assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
854 cwd: "/repo",
855 remoteName: "origin",
856 remoteBranch: "feature/source-control",
857 localBranch: "feature/source-control",
858 });
859 assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
860 cwd: "/repo",
861 branch: "feature/source-control",
862 remoteName: "origin",
863 remoteBranch: "feature/source-control",
864 });
865 assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
866 cwd: "/repo",
867 refName: "feature/source-control",
868 });
869 }).pipe(Effect.provide(layer));
870});
871
872it.effect("preserves Git checkout failures without deriving the domain message from them", () => {
873 const gitCause = new GitCommandError({
874 operation: "fetchRemoteBranch",
875 command: "git fetch origin feature/source-control",
876 cwd: "/repo",
877 detail: "remote rejected the request",
878 });
879 const { layer } = makeLayer({
880 response: () =>
881 Response.json({
882 ...bitbucketPullRequest,
883 source: {
884 branch: { name: "feature/source-control" },
885 repository: {
886 full_name: "pingdotgg/t3code",
887 workspace: { slug: "pingdotgg" },
888 },
889 },
890 }),
891 git: {
892 fetchRemoteBranch: () => Effect.fail(gitCause),
893 },
894 });
895
896 return Effect.gen(function* () {
897 const bitbucket = yield* BitbucketApi.BitbucketApi;
898 const error = yield* Effect.flip(
899 bitbucket.checkoutPullRequest({
900 cwd: "/repo",
901 reference: "42",
902 force: true,
903 }),
904 );
905
906 assert.instanceOf(error, BitbucketApi.BitbucketCheckoutError);
907 assert.strictEqual(error.cwd, "/repo");
908 assert.strictEqual(error.reference, "42");
909 assert.strictEqual(
910 error.message,
911 "Bitbucket API failed in checkoutPullRequest: Failed to check out the Bitbucket pull request.",
912 );
913 assert.strictEqual(error.cause, gitCause);
914 }).pipe(Effect.provide(layer));
915});
916
917it.effect("checks out fork pull requests through an ensured fork remote", () => {
918 const { git, layer } = makeLayer({
919 response: (request) => {
920 if (request.url.endsWith("/repositories/octocat/t3code")) {
921 return Response.json({
922 ...repositoryJson,
923 full_name: "octocat/t3code",
924 links: {
925 html: { href: "https://bitbucket.org/octocat/t3code" },
926 clone: [
927 { name: "https", href: "https://bitbucket.org/octocat/t3code.git" },
928 { name: "ssh", href: "git@bitbucket.org:octocat/t3code.git" },
929 ],
930 },
931 });
932 }
933 return Response.json({
934 ...bitbucketPullRequest,
935 source: {
936 branch: { name: "main" },
937 repository: {
938 full_name: "octocat/t3code",
939 workspace: { slug: "octocat" },
940 },
941 },
942 });
943 },
944 });
945
946 return Effect.gen(function* () {
947 const bitbucket = yield* BitbucketApi.BitbucketApi;
948 yield* bitbucket.checkoutPullRequest({
949 cwd: "/repo",
950 reference: "42",
951 force: true,
952 });
953
954 assert.deepStrictEqual(git.ensureRemote.mock.calls[0]?.[0], {
955 cwd: "/repo",
956 preferredName: "octocat",
957 url: "git@bitbucket.org:octocat/t3code.git",
958 });
959 assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
960 cwd: "/repo",
961 remoteName: "octocat",
962 remoteBranch: "main",
963 localBranch: "t3code/pr-42/main",
964 });
965 assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
966 cwd: "/repo",
967 branch: "t3code/pr-42/main",
968 remoteName: "octocat",
969 remoteBranch: "main",
970 });
971 assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
972 cwd: "/repo",
973 refName: "t3code/pr-42/main",
974 });
975 }).pipe(Effect.provide(layer));
976});
977
978it.effect("refuses a url that points away from the configured Bitbucket", () => {
979 // A whole url reaches `request` from inside a response — a pagination cursor, say — so
980 // following one off-host would hand the account's credentials to whoever wrote it.
981 const { layer, execute } = makeLayer({ response: () => new Response("{}", { status: 200 }) });
982 return Effect.gen(function* () {
983 const bitbucket = yield* BitbucketApi.BitbucketApi;
984
985 const error = yield* Effect.flip(
986 bitbucket.request({ method: "GET", url: "https://attacker.example/2.0/repositories" }),
987 );
988
989 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
990 // Nothing was sent at all, so no header travelled anywhere.
991 assert.strictEqual(execute.mock.calls.length, 0);
992 }).pipe(Effect.provide(layer));
993});
994
995it.effect("keeps only the host of a url it refuses, never its query", () =>
996 Effect.gen(function* () {
997 const bitbucket = yield* BitbucketApi.BitbucketApi;
998
999 const error = yield* Effect.flip(
1000 bitbucket.request({
1001 method: "GET",
1002 // A signed link, whose query is the credential.
1003 url: "https://attacker.example/asset?signature=secret-token",
1004 }),
1005 );
1006
1007 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
1008 assert.strictEqual(
1009 error._tag === "BitbucketUntrustedUrlError" ? error.host : "",
1010 "https://attacker.example",
1011 );
1012 assert.notInclude(error.message, "secret-token");
1013 }).pipe(Effect.provide(makeLayer({ response: () => new Response("{}", { status: 200 }) }).layer)),
1014);
1015
1016it.effect("does not follow a redirect off the configured Bitbucket", () =>
1017 Effect.gen(function* () {
1018 const bitbucket = yield* BitbucketApi.BitbucketApi;
1019
1020 const error = yield* Effect.flip(
1021 bitbucket.request({ method: "GET", url: "/repositories/acme/web/pullrequests/1/diff" }),
1022 );
1023
1024 // The client would carry every header to the new host, so the hop is checked here instead.
1025 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
1026 }).pipe(
1027 Effect.provide(
1028 makeLayer({
1029 response: () =>
1030 new Response(null, {
1031 status: 302,
1032 headers: { location: "https://attacker.example/stolen" },
1033 }),
1034 }).layer,
1035 ),
1036 ),
1037);
1038
1039it.effect("follows a redirect that stays on the configured Bitbucket", () =>
1040 Effect.gen(function* () {
1041 const bitbucket = yield* BitbucketApi.BitbucketApi;
1042
1043 const result = yield* bitbucket.request({
1044 method: "GET",
1045 url: "/repositories/acme/web/pullrequests/1/diff",
1046 });
1047
1048 // Bitbucket serves a diff as a redirect to a commit range, so the hop has to be followed.
1049 assert.strictEqual(result.body, "diff --git a/a.ts b/a.ts");
1050 assert.isFalse(result.truncated);
1051 }).pipe(
1052 Effect.provide(
1053 makeLayer({
1054 response: (request) =>
1055 request.url.endsWith("/pullrequests/1/diff")
1056 ? new Response(null, {
1057 status: 302,
1058 // The same host the harness configures, which is not bitbucket.org: a
1059 // self-hosted base url has to be trusted on its own terms.
1060 headers: { location: "https://api.test.local/2.0/repositories/acme/web/diff/abc" },
1061 })
1062 : new Response("diff --git a/a.ts b/a.ts", { status: 200 }),
1063 }).layer,
1064 ),
1065 ),
1066);
1067
1068it.effect("cuts a response short rather than reading an unbounded diff into memory", () =>
1069 Effect.gen(function* () {
1070 const bitbucket = yield* BitbucketApi.BitbucketApi;
1071
1072 const result = yield* bitbucket.request({
1073 method: "GET",
1074 url: "/repositories/acme/web/pullrequests/1/diff",
1075 maxBytes: 8,
1076 });
1077
1078 assert.strictEqual(result.body, "12345678");
1079 assert.isTrue(result.truncated);
1080 // Bounded as the body arrives, so an oversized diff is never held whole.
1081 }).pipe(
1082 Effect.provide(
1083 makeLayer({ response: () => new Response("1234567890", { status: 200 }) }).layer,
1084 ),
1085 ),
1086);