Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BitbucketApi.test.ts

986 lines31.9 KB

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