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

BitbucketApi.test.ts

1,101 lines36.2 KB

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