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

BitbucketApi.test.ts

805 lines27.0 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 Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Schema from "effect/Schema";
14import * as TestClock from "effect/testing/TestClock";
15import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
16​
17import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
18import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost";
19import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
20​
21import * as BitbucketApi from "./BitbucketApi.ts";
22​
23type HostGit = SourceControlHost.SourceControlHost["Service"]["git"];
24​
25const isBitbucketRepositoryLocatorError = Schema.is(BitbucketApi.BitbucketRepositoryLocatorError);
26​
27const bitbucketPullRequest = {
28 id: 42,
29 title: "Add Bitbucket provider",
30 state: "OPEN",
31 updated_on: "2026-01-02T00:00:00.000Z",
32 links: {
33 html: {
34 href: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
35 },
36 },
37 source: {
38 branch: { name: "feature/source-control" },
39 repository: {
40 full_name: "octocat/t3code",
41 workspace: { slug: "octocat" },
42 },
43 },
44 destination: {
45 branch: { name: "main" },
46 repository: {
47 full_name: "pingdotgg/t3code",
48 workspace: { slug: "pingdotgg" },
49 },
50 },
51};
52​
53const repositoryJson = {
54 full_name: "pingdotgg/t3code",
55 links: {
56 html: { href: "https://bitbucket.org/pingdotgg/t3code" },
57 clone: [
58 { name: "https", href: "https://bitbucket.org/pingdotgg/t3code.git" },
59 { name: "ssh", href: "git@bitbucket.org:pingdotgg/t3code.git" },
60 ],
61 },
62 mainbranch: { name: "main" },
63};
64​
65function makeLayer(input: {
66 readonly response: (request: HttpClientRequest.HttpClientRequest) => Response;
67 /** Holds the answer until it resolves, in place of answering at once. */
68 readonly answer?: (response: Response) => Effect.Effect<Response>;
69 readonly requestFailure?: (
70 request: HttpClientRequest.HttpClientRequest,
71 ) => HttpClientError.HttpClientError;
72 readonly stall?: boolean;
73 readonly git?: Partial<HostGit>;
74 readonly env?: Record<string, string>;
75}) {
76 const execute = vi.fn((request: HttpClientRequest.HttpClientRequest) =>
77 input.stall
78 ? Effect.never
79 : input.requestFailure
80 ? Effect.fail(input.requestFailure(request))
81 : (input.answer ?? Effect.succeed)(input.response(request)).pipe(
82 Effect.map((response) => HttpClientResponse.fromWeb(request, response)),
83 ),
84 );
85 const gitMock = {
86 readConfigValue: vi.fn<HostGit["readConfigValue"]>(() =>
87 Effect.succeed<string | null>("git@bitbucket.org:pingdotgg/t3code.git"),
88 ),
89 resolvePrimaryRemoteName: vi.fn<HostGit["resolvePrimaryRemoteName"]>(() =>
90 Effect.succeed("origin"),
91 ),
92 ensureRemote: vi.fn<HostGit["ensureRemote"]>(() => Effect.succeed("octocat")),
93 fetchRemoteBranch: vi.fn<HostGit["fetchRemoteBranch"]>(() => Effect.void),
94 fetchRemoteTrackingBranch: vi.fn<HostGit["fetchRemoteTrackingBranch"]>(() => Effect.void),
95 setBranchUpstream: vi.fn<HostGit["setBranchUpstream"]>(() => Effect.void),
96 switchRef: vi.fn<HostGit["switchRef"]>((request) =>
97 Effect.succeed({ refName: request.refName }),
98 ),
99 listLocalBranchNames: vi.fn<HostGit["listLocalBranchNames"]>(() => Effect.succeed([])),
100 };
101 const git = {
102 ...gitMock,
103 ...input.git,
104 } satisfies Partial<HostGit>;
105​
106 const listRemotes = vi.fn(() =>
107 Effect.succeed({
108 remotes: [
109 {
110 name: "origin",
111 url: "git@bitbucket.org:pingdotgg/t3code.git",
112 pushUrl: Option.none(),
113 isPrimary: true,
114 },
115 ],
116 freshness: {
117 source: "live-local" as const,
118 observedAt: DateTime.makeUnsafe("1970-01-01T00:00:00.000Z"),
119 expiresAt: Option.none(),
120 },
121 }),
122 );
123 // The outer effect resolves the repository; the inner one lists its remotes.
124 const resolve = vi.fn((_cwd: string) => Effect.succeed(Effect.suspend(listRemotes)));
125​
126 const layer = BitbucketApi.layer.pipe(
127 Layer.provide(SourceControlRateLimit.layer),
128 Layer.provide(
129 Layer.succeed(
130 HttpClient.HttpClient,
131 HttpClient.make((request) => execute(request)),
132 ),
133 ),
134 Layer.provide(
135 ConfigProvider.layer(
136 ConfigProvider.fromEnv({
137 env: input.env ?? {
138 T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0",
139 T3CODE_BITBUCKET_EMAIL: "user@example.com",
140 T3CODE_BITBUCKET_API_TOKEN: "token",
141 },
142 }),
143 ),
144 ),
145 Layer.provideMerge(TestSourceControlHost.layer({ git: { ...git, remotes: resolve } })),
146 Layer.provideMerge(NodeServices.layer),
147 );
148​
149 return { execute, git: gitMock, resolve, listRemotes, layer };
151​
152it.effect("parses pull request responses from the Bitbucket REST API", () => {
153 const { execute, layer } = makeLayer({
154 response: () =>
155 Response.json({
156 ...bitbucketPullRequest,
157 }),
158 });
159​
160 return Effect.gen(function* () {
161 const bitbucket = yield* BitbucketApi.BitbucketApi;
162 const result = yield* bitbucket.getPullRequest({
163 cwd: "/repo",
164 reference: "#42",
165 });
166​
167 assert.deepStrictEqual(result, {
168 number: 42,
169 title: "Add Bitbucket provider",
170 url: "https://bitbucket.org/pingdotgg/t3code/pull-requests/42",
171 baseRefName: "main",
172 headRefName: "feature/source-control",
173 state: "open",
174 updatedAt: Option.some(DateTime.makeUnsafe("2026-01-02T00:00:00.000Z")),
175 isCrossRepository: true,
176 headRepositoryNameWithOwner: "octocat/t3code",
177 headRepositoryOwnerLogin: "octocat",
178 });
179 assert.strictEqual(
180 execute.mock.calls[0]?.[0].url,
181 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests/42",
182 );
183 }).pipe(Effect.provide(layer));
184});
185​
186it.effect("lists pull requests with Bitbucket state and source branch query params", () => {
187 const { execute, layer } = makeLayer({
188 response: () =>
189 Response.json({
190 values: [
191 {
192 ...bitbucketPullRequest,
193 id: 7,
194 state: "MERGED",
195 source: {
196 branch: { name: "feature/merged" },
197 repository: { full_name: "pingdotgg/t3code" },
198 },
199 },
200 ],
201 }),
202 });
203​
204 return Effect.gen(function* () {
205 const bitbucket = yield* BitbucketApi.BitbucketApi;
206 const result = yield* bitbucket.listPullRequests({
207 cwd: "/repo",
208 headSelector: "origin:feature/merged",
209 state: "merged",
210 limit: 10,
211 });
212​
213 assert.strictEqual(result[0]?.state, "merged");
214 const request = execute.mock.calls[0]?.[0];
215 assert.strictEqual(
216 request?.url,
217 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
218 );
219 assert.deepStrictEqual(request?.urlParams.params, [
220 ["pagelen", "10"],
221 ["sort", "-updated_on"],
222 ["q", 'source.branch.name = "feature/merged" AND state = "MERGED"'],
223 ["state", "MERGED"],
224 ]);
225 }).pipe(Effect.provide(layer));
226});
227​
228it.effect("reads repository clone URLs and default branch", () => {
229 const { layer } = makeLayer({
230 response: (request) =>
231 Response.json(
232 request.url.endsWith("/branching-model")
233 ? {
234 development: {
235 branch: { name: "main" },
236 name: "main",
237 use_mainbranch: true,
238 },
239 }
240 : repositoryJson,
241 ),
242 });
243​
244 return Effect.gen(function* () {
245 const bitbucket = yield* BitbucketApi.BitbucketApi;
246 const cloneUrls = yield* bitbucket.getRepositoryCloneUrls({
247 cwd: "/repo",
248 repository: "pingdotgg/t3code",
249 });
250 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
251​
252 assert.deepStrictEqual(cloneUrls, {
253 nameWithOwner: "pingdotgg/t3code",
254 url: "https://bitbucket.org/pingdotgg/t3code.git",
255 sshUrl: "git@bitbucket.org:pingdotgg/t3code.git",
256 });
257 assert.strictEqual(defaultBranch, "main");
258 }).pipe(Effect.provide(layer));
259});
260​
261it.effect.each([false, true])(
262 "rejects invalid explicit repositories before fallback, context=%s",
263 (withContext) => {
264 const { execute, resolve, listRemotes, layer } = makeLayer({
265 response: () => Response.json(repositoryJson),
266 });
267​
268 return Effect.gen(function* () {
269 const bitbucket = yield* BitbucketApi.BitbucketApi;
270 for (const repository of ["t3code", "", " \t "]) {
271 const error = yield* bitbucket
272 .getRepositoryCloneUrls({
273 cwd: "/repo",
274 repository,
275 ...(withContext
276 ? {
277 context: {
278 provider: {
279 kind: SourceControlProviderKind.make("bitbucket"),
280 name: "Bitbucket",
281 baseUrl: "https://bitbucket.org",
282 },
283 remoteName: "origin",
284 remoteUrl: "git@bitbucket.org:pingdotgg/t3code.git",
285 },
286 }
287 : {}),
288 })
289 .pipe(Effect.match({ onFailure: (error) => error, onSuccess: () => null }));
290​
291 assert.instanceOf(error, BitbucketApi.BitbucketRepositoryLocatorError);
292 assert.strictEqual(
293 isBitbucketRepositoryLocatorError(error) ? error.repository : null,
294 repository,
295 );
296 assert.strictEqual(resolve.mock.calls.length, 0);
297 assert.strictEqual(listRemotes.mock.calls.length, 0);
298 assert.strictEqual(execute.mock.calls.length, 0);
299 }
300 }).pipe(Effect.provide(layer));
301 },
302);
303​
304it.effect("prefers an explicit repository and uses context when the repository is omitted", () => {
305 const { execute, resolve, listRemotes, layer } = makeLayer({
306 response: (request) =>
307 Response.json(request.url.endsWith("/branching-model") ? {} : repositoryJson),
308 });
309​
310 return Effect.gen(function* () {
311 const bitbucket = yield* BitbucketApi.BitbucketApi;
312 const context = {
313 provider: {
314 kind: SourceControlProviderKind.make("bitbucket"),
315 name: "Bitbucket",
316 baseUrl: "https://bitbucket.org",
317 },
318 remoteName: "origin",
319 remoteUrl: "git@bitbucket.org:another/context.git",
320 };
321 for (const repository of ["pingdotgg/t3code", "https://bitbucket.org/pingdotgg/t3code.git"]) {
322 yield* bitbucket.getRepositoryCloneUrls({ cwd: "/repo", context, repository });
323 }
324 yield* bitbucket.getDefaultBranch({ cwd: "/repo", context });
325​
326 assert.deepStrictEqual(
327 execute.mock.calls.map(([request]) => request.url).toSorted(),
328 [
329 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
330 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
331 "https://api.test.local/2.0/repositories/another/context",
332 "https://api.test.local/2.0/repositories/another/context/branching-model",
333 ].toSorted(),
334 );
335 assert.strictEqual(resolve.mock.calls.length, 0);
336 assert.strictEqual(listRemotes.mock.calls.length, 0);
337 }).pipe(Effect.provide(layer));
338});
339​
340it.effect(
341 "prefers the Bitbucket branching model development branch as the default PR target",
342 () => {
343 const { execute, layer } = makeLayer({
344 response: (request) =>
345 Response.json(
346 request.url.endsWith("/branching-model")
347 ? {
348 development: {
349 branch: { name: "develop" },
350 name: "develop",
351 use_mainbranch: false,
352 },
353 }
354 : repositoryJson,
355 ),
356 });
357​
358 return Effect.gen(function* () {
359 const bitbucket = yield* BitbucketApi.BitbucketApi;
360 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
361​
362 assert.strictEqual(defaultBranch, "develop");
363 assert.deepStrictEqual(
364 execute.mock.calls.map((call) => call[0].url).toSorted(),
365 [
366 "https://api.test.local/2.0/repositories/pingdotgg/t3code",
367 "https://api.test.local/2.0/repositories/pingdotgg/t3code/branching-model",
368 ].toSorted(),
369 );
370 }).pipe(Effect.provide(layer));
371 },
372);
373​
374it.effect(
375 "falls back to the repository main branch when the Bitbucket development branch is invalid",
376 () => {
377 const { layer } = makeLayer({
378 response: (request) =>
379 Response.json(
380 request.url.endsWith("/branching-model")
381 ? {
382 development: {
383 name: "develop",
384 use_mainbranch: false,
385 is_valid: false,
386 },
387 }
388 : repositoryJson,
389 ),
390 });
391​
392 return Effect.gen(function* () {
393 const bitbucket = yield* BitbucketApi.BitbucketApi;
394 const defaultBranch = yield* bitbucket.getDefaultBranch({ cwd: "/repo" });
395​
396 assert.strictEqual(defaultBranch, "main");
397 }).pipe(Effect.provide(layer));
398 },
399);
400​
401it.effect("creates pull requests using the official REST payload shape", () => {
402 const { execute, layer } = makeLayer({
403 response: () => Response.json(bitbucketPullRequest),
404 });
405​
406 return Effect.gen(function* () {
407 const fileSystem = yield* FileSystem.FileSystem;
408 const bodyFile = yield* fileSystem.makeTempFileScoped({ prefix: "bitbucket-pr-body-" });
409 yield* fileSystem.writeFileString(bodyFile, "PR body");
410​
411 const bitbucket = yield* BitbucketApi.BitbucketApi;
412 yield* bitbucket.createPullRequest({
413 cwd: "/repo",
414 baseBranch: "main",
415 headSelector: "owner:feature/provider",
416 title: "Provider PR",
417 bodyFile,
418 });
419​
420 const request = execute.mock.calls[0]?.[0];
421 assert.strictEqual(
422 request?.url,
423 "https://api.test.local/2.0/repositories/pingdotgg/t3code/pullrequests",
424 );
425 assert.strictEqual(request?.method, "POST");
426 assert.ok(request);
427 const rawBody = (request.body as { readonly body?: Uint8Array }).body;
428 assert.ok(rawBody);
429 assert.deepStrictEqual(JSON.parse(new TextDecoder().decode(rawBody)), {
430 title: "Provider PR",
431 description: "PR body",
432 source: {
433 branch: { name: "feature/provider" },
434 repository: { full_name: "owner/t3code" },
435 },
436 destination: {
437 branch: { name: "main" },
438 },
439 });
440 }).pipe(Effect.provide(layer), Effect.scoped);
441});
442​
443it.effect("reports the account Bitbucket confirms for the configured credential", () => {
444 const { layer } = makeLayer({
445 response: () => Response.json({ username: "bitbucket-user" }),
446 });
447​
448 return Effect.gen(function* () {
449 const bitbucket = yield* BitbucketApi.BitbucketApi;
450 const auth = yield* bitbucket.probeAuth;
451 assert.strictEqual(auth.status, "authenticated");
452 assert.deepStrictEqual(auth.account, Option.some("bitbucket-user"));
453 assert.deepStrictEqual(auth.host, Option.some("bitbucket.org"));
454 }).pipe(Effect.provide(layer));
455});
456​
457it.effect("prefers credentials saved in settings over the environment, without a restart", () => {
458 const { execute, layer } = makeLayer({
459 response: () => Response.json({ username: "bitbucket-user" }),
460 });
461 const lastAuthorization = () => execute.mock.calls.at(-1)?.[0].headers.authorization;
462 const basic = (user: string, password: string) => `Basic ${btoa(`${user}:${password}`)}`;
463​
464 return Effect.gen(function* () {
465 const bitbucket = yield* BitbucketApi.BitbucketApi;
466 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
467​
468 yield* bitbucket.probeAuth;
469 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
470​
471 yield* settings.update({
472 sourceControlHosts: {
473 bitbucket: { email: "saved@example.com", apiToken: "saved-api-token" },
474 },
475 });
476 yield* bitbucket.probeAuth;
477 assert.strictEqual(lastAuthorization(), basic("saved@example.com", "saved-api-token"));
478​
479 yield* settings.update({
480 sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } },
481 });
482 yield* bitbucket.probeAuth;
483 assert.strictEqual(lastAuthorization(), "Bearer saved-access-token");
484​
485 yield* settings.update({
486 sourceControlHosts: { bitbucket: { accessToken: "", apiToken: "" } },
487 });
488 yield* bitbucket.probeAuth;
489 assert.strictEqual(lastAuthorization(), basic("user@example.com", "token"));
490 }).pipe(Effect.provide(layer));
491});
492​
493it.effect("never puts a saved token that is unsafe for an HTTP header on the wire", () => {
494 const { execute, layer } = makeLayer({
495 response: () => Response.json({ username: "bitbucket-user" }),
496 });
497​
498 return Effect.gen(function* () {
499 const bitbucket = yield* BitbucketApi.BitbucketApi;
500 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
501​
502 // Fetch would reject this header with an error quoting the token, and that error reaches
503 // clients. The unusable token is ignored, so the environment credential is used instead.
504 yield* settings.update({
505 sourceControlHosts: { bitbucket: { accessToken: "saved\ntoken" } },
506 });
507 yield* bitbucket.probeAuth;
508 assert.strictEqual(
509 execute.mock.calls.at(-1)?.[0].headers.authorization,
510 `Basic ${btoa("user@example.com:token")}`,
511 );
512 }).pipe(Effect.provide(layer));
513});
514​
515it.effect("reports saved credentials as configured when Bitbucket cannot confirm them", () => {
516 const { layer } = makeLayer({
517 response: () => new Response(null, { status: 401 }),
518 env: { T3CODE_BITBUCKET_API_BASE_URL: "https://api.test.local/2.0" },
519 });
520​
521 return Effect.gen(function* () {
522 const bitbucket = yield* BitbucketApi.BitbucketApi;
523 const settings = yield* TestSourceControlHost.TestSourceControlHostSettings;
524​
525 assert.strictEqual((yield* bitbucket.probeAuth).status, "unauthenticated");
526​
527 yield* settings.update({
528 sourceControlHosts: { bitbucket: { accessToken: "saved-access-token" } },
529 });
530 assert.deepStrictEqual(yield* bitbucket.probeAuth, {
531 status: "unknown",
532 account: Option.none(),
533 host: Option.some("bitbucket.org"),
534 detail: Option.some("An access token is configured."),
535 });
536 }).pipe(Effect.provide(layer));
537});
538​
539it.effect("keeps Bitbucket response bodies out of checkout diagnostics", () => {
540 const responseBody = '{"error":{"message":"credential=secret-value"}}';
541 const { layer } = makeLayer({
542 response: () => new Response(responseBody, { status: 403 }),
543 });
544​
545 return Effect.gen(function* () {
546 const bitbucket = yield* BitbucketApi.BitbucketApi;
547 const error = yield* bitbucket
548 .checkoutPullRequest({ cwd: "/repo", reference: "42" })
549 .pipe(Effect.flip);
550​
551 assert.instanceOf(error, BitbucketApi.BitbucketResponseError);
552 assert.strictEqual(error.operation, "getPullRequest");
553 assert.strictEqual(error.status, 403);
554 assert.strictEqual(error.responseBodyLength, responseBody.length);
555 assert.notProperty(error, "responseBody");
556 assert.strictEqual(
557 error.message,
558 "Bitbucket API failed in getPullRequest: Bitbucket returned HTTP 403.",
559 );
560 assert.notInclude(error.message, "secret-value");
561 }).pipe(Effect.provide(layer));
562});
563​
564it.effect("checks out fork pull requests through an ensured fork remote", () => {
565 const { git, layer } = makeLayer({
566 response: (request) => {
567 if (request.url.endsWith("/repositories/octocat/t3code")) {
568 return Response.json({
569 ...repositoryJson,
570 full_name: "octocat/t3code",
571 links: {
572 html: { href: "https://bitbucket.org/octocat/t3code" },
573 clone: [
574 { name: "https", href: "https://bitbucket.org/octocat/t3code.git" },
575 { name: "ssh", href: "git@bitbucket.org:octocat/t3code.git" },
576 ],
577 },
578 });
579 }
580 return Response.json({
581 ...bitbucketPullRequest,
582 source: {
583 branch: { name: "main" },
584 repository: {
585 full_name: "octocat/t3code",
586 workspace: { slug: "octocat" },
587 },
588 },
589 });
590 },
591 });
592​
593 return Effect.gen(function* () {
594 const bitbucket = yield* BitbucketApi.BitbucketApi;
595 yield* bitbucket.checkoutPullRequest({
596 cwd: "/repo",
597 reference: "42",
598 force: true,
599 });
600​
601 assert.deepStrictEqual(git.ensureRemote.mock.calls[0]?.[0], {
602 cwd: "/repo",
603 preferredName: "octocat",
604 url: "git@bitbucket.org:octocat/t3code.git",
605 });
606 assert.deepStrictEqual(git.fetchRemoteBranch.mock.calls[0]?.[0], {
607 cwd: "/repo",
608 remoteName: "octocat",
609 remoteBranch: "main",
610 localBranch: "t3code/pr-42/main",
611 });
612 assert.deepStrictEqual(git.setBranchUpstream.mock.calls[0]?.[0], {
613 cwd: "/repo",
614 branch: "t3code/pr-42/main",
615 remoteName: "octocat",
616 remoteBranch: "main",
617 });
618 assert.deepStrictEqual(git.switchRef.mock.calls[0]?.[0], {
619 cwd: "/repo",
620 refName: "t3code/pr-42/main",
621 });
622 }).pipe(Effect.provide(layer));
623});
624​
625it.effect("refuses a url that points away from the configured Bitbucket", () => {
626 const { layer, execute } = makeLayer({ response: () => new Response("{}", { status: 200 }) });
627 return Effect.gen(function* () {
628 const bitbucket = yield* BitbucketApi.BitbucketApi;
629​
630 const error = yield* Effect.flip(
631 bitbucket.request({ method: "GET", url: "https://attacker.example/2.0/repositories" }),
632 );
633​
634 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
635 assert.strictEqual(execute.mock.calls.length, 0);
636 }).pipe(Effect.provide(layer));
637});
638​
639it.effect("keeps only the host of a url it refuses, never its query", () =>
640 Effect.gen(function* () {
641 const bitbucket = yield* BitbucketApi.BitbucketApi;
642​
643 const error = yield* Effect.flip(
644 bitbucket.request({
645 method: "GET",
646 url: "https://attacker.example/asset?signature=secret-token",
647 }),
648 );
649​
650 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
651 assert.strictEqual(
652 error._tag === "BitbucketUntrustedUrlError" ? error.host : "",
653 "https://attacker.example",
654 );
655 assert.notInclude(error.message, "secret-token");
656 }).pipe(Effect.provide(makeLayer({ response: () => new Response("{}", { status: 200 }) }).layer)),
657);
658​
659it.effect("does not follow a redirect off the configured Bitbucket", () =>
660 Effect.gen(function* () {
661 const bitbucket = yield* BitbucketApi.BitbucketApi;
662​
663 const error = yield* Effect.flip(
664 bitbucket.request({ method: "GET", url: "/repositories/acme/web/pullrequests/1/diff" }),
665 );
666​
667 assert.strictEqual(error._tag, "BitbucketUntrustedUrlError");
668 }).pipe(
669 Effect.provide(
670 makeLayer({
671 response: () =>
672 new Response(null, {
673 status: 302,
674 headers: { location: "https://attacker.example/stolen" },
675 }),
676 }).layer,
677 ),
678 ),
679);
680​
681it.effect("follows a redirect that stays on the configured Bitbucket", () =>
682 Effect.gen(function* () {
683 const bitbucket = yield* BitbucketApi.BitbucketApi;
684​
685 const result = yield* bitbucket.request({
686 method: "GET",
687 url: "/repositories/acme/web/pullrequests/1/diff",
688 });
689​
690 assert.strictEqual(result.body, "diff --git a/a.ts b/a.ts");
691 assert.isFalse(result.truncated);
692 }).pipe(
693 Effect.provide(
694 makeLayer({
695 response: (request) =>
696 request.url.endsWith("/pullrequests/1/diff")
697 ? new Response(null, {
698 status: 302,
699 headers: { location: "https://api.test.local/2.0/repositories/acme/web/diff/abc" },
700 })
701 : new Response("diff --git a/a.ts b/a.ts", { status: 200 }),
702 }).layer,
703 ),
704 ),
705);
706​
707it.effect("cuts a response short rather than reading an unbounded diff into memory", () =>
708 Effect.gen(function* () {
709 const bitbucket = yield* BitbucketApi.BitbucketApi;
710​
711 const result = yield* bitbucket.request({
712 method: "GET",
713 url: "/repositories/acme/web/pullrequests/1/diff",
714 maxBytes: 8,
715 });
716​
717 assert.strictEqual(result.body, "12345678");
718 assert.isTrue(result.truncated);
719 }).pipe(
720 Effect.provide(
721 makeLayer({ response: () => new Response("1234567890", { status: 200 }) }).layer,
722 ),
723 ),
724);
725​
726it.effect("pauses background reads after a 429 until Bitbucket's retry-after passes", () => {
727 let answered = 0;
728 const { execute, layer } = makeLayer({
729 response: () => {
730 answered += 1;
731 return answered === 1
732 ? new Response("Rate limit exceeded", { status: 429, headers: { "retry-after": "60" } })
733 : Response.json({ values: [] });
734 },
735 });
736​
737 return Effect.gen(function* () {
738 const bitbucket = yield* BitbucketApi.BitbucketApi;
739 const lookup = bitbucket.listPullRequests({
740 cwd: "/repo",
741 headSelector: "feature/a",
742 state: "all",
743 });
744​
745 yield* Effect.flip(lookup);
746 const paused = yield* Effect.flip(lookup);
747 // Keyed by the repository host, where PullRequestService records its own backoff.
748 assert.deepInclude(paused, {
749 _tag: "SourceControlRateLimitPausedError",
750 host: "bitbucket.org",
751 retryAt: 60_000,
752 });
753 assert.strictEqual(execute.mock.calls.length, 1);
754​
755 // A user waiting on an answer is not held back by the background pause, and their success
756 // does not end it early.
757 yield* lookup.pipe(Effect.provideService(SourceControlRateLimit.Interactive, true));
758 yield* bitbucket.request({
759 method: "POST",
760 url: "/repositories/acme/web/pullrequests/1/approve",
761 });
762​
763 yield* TestClock.adjust("59 seconds");
764 assert.strictEqual((yield* Effect.flip(lookup))._tag, "SourceControlRateLimitPausedError");
765​
766 yield* TestClock.adjust("1 second");
767 yield* lookup;
768 }).pipe(Effect.provide(layer));
769});
770​
771it.effect("keeps a sweep over many branches to a few Bitbucket requests at a time", () =>
772 Effect.gen(function* () {
773 const started = yield* Queue.unbounded<void>();
774 const release = yield* Deferred.make<void>();
775 let inFlight = 0;
776 let peak = 0;
777 const { layer } = makeLayer({
778 response: () => Response.json({ values: [] }),
779 answer: (response) =>
780 Effect.gen(function* () {
781 inFlight += 1;
782 peak = Math.max(peak, inFlight);
783 yield* Queue.offer(started, undefined);
784 yield* Deferred.await(release);
785 inFlight -= 1;
786 return response;
787 }),
788 });
789​
790 yield* Effect.gen(function* () {
791 const bitbucket = yield* BitbucketApi.BitbucketApi;
792 const sweep = yield* Effect.forEach(
793 Array.from({ length: 12 }, (_, index) => `feature/${index}`),
794 (branch) =>
795 bitbucket.listPullRequests({ cwd: "/repo", headSelector: branch, state: "all" }),
796 { concurrency: "unbounded", discard: true },
797 ).pipe(Effect.forkChild);
798 for (let index = 0; index < 4; index += 1) yield* Queue.take(started);
799 yield* Deferred.succeed(release, undefined);
800 yield* Fiber.join(sweep);
801 }).pipe(Effect.provide(layer));
802​
803 assert.strictEqual(peak, 4);
804 }),
805);