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