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

BitbucketApi.test.ts

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