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