Skip to content
Myr

rest.test.ts

This file

Path

packages/artifacts/test/rest.test.ts

682 lines · 20.9 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { RepoPath } from "@repo/protocol/ids";4import type { CommitSha } from "@repo/protocol/ids";5import { gitClient } from "@repo/testkit/git-client";6import { httpBackend } from "@repo/testkit/http-backend";7import {8  Duration,9  Effect,10  Exit,11  Layer,12  Option,13  Redacted,14  Ref,15  Schema,16} from "effect";17import type { Scope } from "effect";18import type { ChildProcessSpawner } from "effect/process";19import { readCommit } from "isomorphic-git";2021import { Fetch, FetchFailed } from "../src/fetch.ts";22import {23  BranchName,24  ForkInProgress,25  ImportRefused,26  ObjectId,27  RefName,28  RepoExists,29  RepoHost,30  RepoName,31  RepoNotFound,32  Revision,33} from "../src/repo-host.ts";34import type { PushSource } from "../src/repo-host.ts";35import { RepoHostLocal } from "../src/repo-host/local.ts";36import { memoryFs } from "../src/repo-host/memory-fs.ts";37import { RepoHostRest } from "../src/repo-host/rest.ts";38import { fakeRest } from "./fake-rest.ts";39import type { FakeRestOptions } from "./fake-rest.ts";40import { describeRepoHost } from "./repo-host-contract.ts";41import { temporaryRoot } from "./temporary-root.ts";4243const main = RefName.make("refs/heads/main");4445const accountId = "0123456789abcdef0123456789abcdef";4647const namespace = "projects-test";4849const api = `https://api.cloudflare.com/client/v4/accounts/${accountId}/artifacts/namespaces/${namespace}`;5051const remoteBase = `https://${accountId}.artifacts.test/git/${namespace}`;5253const apiToken = "cf-api-token-for-the-rest-tests";5455interface Seen {56  readonly method: string;57  readonly url: string;58  readonly headers: readonly (readonly [string, string])[];59  readonly body: string;60  readonly status: number;61  readonly reply: string;62}6364const textOf = (message: Request | Response) =>65  Effect.promise(() => message.clone().arrayBuffer()).pipe(66    Effect.map((buffer) => new TextDecoder().decode(buffer))67  );6869const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));7071const decodeMinted = Schema.decodeEffect(72  Schema.fromJsonString(73    Schema.Struct({74      result: Schema.Struct({ id: Schema.String, plaintext: Schema.String }),75    })76  )77);7879const world = (80  options: Omit<FakeRestOptions, "accountId" | "namespace" | "token"> = {}81) =>82  Effect.gen(function* () {83    const root = yield* temporaryRoot;8485    const spawner =86      yield* Effect.context<ChildProcessSpawner.ChildProcessSpawner>();8788    const backend = httpBackend(root);89    const seen = yield* Ref.make<readonly Seen[]>([]);9091    const git = (request: Request) =>92      Effect.scoped(backend(request)).pipe(Effect.provide(spawner));9394    const store = yield* RepoHost.pipe(95      Effect.provide(96        RepoHostLocal.layer({ remoteBase, root }).pipe(97          Layer.provide(Layer.succeed(Fetch, Fetch.of({ fetch: git })))98        )99      )100    );101102    const serve = yield* fakeRest(store, {103      ...options,104      accountId,105      namespace,106      token: apiToken,107    });108109    const route = (request: Request) => {110      if (request.url.startsWith(`${api}/`)) {111        return serve(request);112      }113114      if (request.url.startsWith(`${remoteBase}/`)) {115        return git(request);116      }117118      return Effect.fail(119        new FetchFailed({ reason: "no route to host", url: request.url })120      );121    };122123    const fetch = Fetch.of({124      fetch: (request) =>125        Effect.gen(function* () {126          const body = yield* textOf(request);127          const response = yield* route(request);128          const reply = yield* textOf(response);129130          yield* Ref.update(seen, (all) => [131            ...all,132            {133              body,134              headers: [...request.headers.entries()],135              method: request.method,136              reply,137              status: response.status,138              url: request.url,139            },140          ]);141142          return response;143        }),144    });145146    return {147      layer: RepoHostRest.layer({148        accountId,149        namespace,150        token: Redacted.make(apiToken),151      }).pipe(Layer.provide(Layer.succeed(Fetch, fetch))),152      seen,153      store,154    };155  });156157type World = Effect.Success<ReturnType<typeof world>>;158159const answering = (reply: () => Response) =>160  RepoHostRest.layer({161    accountId,162    namespace,163    token: Redacted.make(apiToken),164  }).pipe(165    Layer.provide(166      Layer.succeed(Fetch, Fetch.of({ fetch: () => Effect.sync(reply) }))167    )168  );169170const refused = (status: number, code: number, message: string) => () =>171  Response.json(172    { errors: [{ code, message }], messages: [], result: null, success: false },173    { status }174  );175176const within = <A, E>(177  body: (178    world: World179  ) => Effect.Effect<180    A,181    E,182    RepoHost | Scope.Scope | ChildProcessSpawner.ChildProcessSpawner183  >,184  options?: Parameters<typeof world>[0]185) =>186  Effect.gen(function* () {187    const made = yield* world(options);188189    return yield* body(made).pipe(Effect.provide(made.layer));190  }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));191192describeRepoHost(193  "rest",194  Layer.unwrap(Effect.map(world(), ({ layer }) => layer)).pipe(195    Layer.provide(NodeServices.layer)196  ),197  {198    importUrl: (name) =>199      RepoHost.use((repos) => repos.remote(name)).pipe(Effect.orDie),200  }201);202203const seeded = (name: RepoName) =>204  Effect.gen(function* () {205    const repos = yield* RepoHost;206    const client = yield* gitClient(memoryFs());207    const first = yield* client.commit("first", [["a.txt", "1"]]);208209    yield* repos.create(name).pipe(Effect.orDie);210    yield* repos211      .push(name, client.source, [212        { from: Option.none(), ref: main, to: first },213      ])214      .pipe(Effect.orDie);215216    return { client, first };217  });218219const requestsTo = (220  seen: Ref.Ref<readonly Seen[]>,221  method: string,222  path: string223) =>224  Ref.get(seen).pipe(225    Effect.map((all) =>226      all.filter(227        (request) =>228          request.method === method && request.url === `${api}${path}`229      )230    )231  );232233const treeOf = (source: PushSource, oid: CommitSha) =>234  Effect.promise(() => readCommit({ ...source, oid })).pipe(235    Effect.map(({ commit }) => ObjectId.make(commit.tree))236  );237238const authorizationOf = ({ headers }: Seen) =>239  headers.find(([name]) => name === "authorization")?.[1] ?? "";240241describe("forks over REST, which name their target", () => {242  // cf's schema has no `name` for a fork (cf #180); the REST API takes one.243  it.live("forks the default branch only, to the name it was given", () =>244    within(({ seen }) =>245      Effect.gen(function* () {246        const repos = yield* RepoHost;247        const base = RepoName.make("demo");248        const name = RepoName.make("demo--fix--alice");249        const { first } = yield* seeded(base);250        const created = yield* repos.fork(base, name).pipe(Effect.orDie);251        const forks = yield* requestsTo(seen, "POST", `/repos/${base}/fork`);252253        expect(created).toStrictEqual({254          name,255          remote: `${remoteBase}/${name}.git`,256        });257        expect(258          yield* Effect.forEach(forks, ({ body }) => decodeJson(body))259        ).toStrictEqual([{ default_branch_only: true, name }]);260        expect(yield* repos.refs(name).pipe(Effect.orDie)).toStrictEqual(261          new Map([[main, first]])262        );263      })264    )265  );266267  // Under load a fork answers 500 (code 10400) after making the repo,268  // and a retry answers 409 (code 10201), or 500 again.269  it.live.each([270    { failures: 1, retry: "an already-exists" },271    { failures: 2, retry: "a second 500" },272  ])(273    "makes one fork through a 500 with code 10400 and then $retry",274    ({ failures }) =>275      within(276        ({ seen, store }) =>277          Effect.gen(function* () {278            const repos = yield* RepoHost;279            const base = RepoName.make("demo");280            const name = RepoName.make("demo--fix--bob");281            const { first } = yield* seeded(base);282            const created = yield* repos.fork(base, name).pipe(Effect.orDie);283284            const forks = yield* requestsTo(285              seen,286              "POST",287              `/repos/${base}/fork`288            );289290            expect(created).toStrictEqual({291              name,292              remote: `${remoteBase}/${name}.git`,293            });294            expect(forks.map(({ status }) => status)).toStrictEqual(295              failures === 1 ? [500, 409] : [500, 500]296            );297            expect(298              yield* Effect.forEach(forks.slice(0, 1), ({ reply }) =>299                decodeJson(reply)300              )301            ).toMatchObject([{ errors: [{ code: 10_400 }], success: false }]);302            expect(yield* store.refs(name).pipe(Effect.orDie)).toStrictEqual(303              new Map([[main, first]])304            );305          }),306        { forkFailures: failures }307      )308  );309310  it.live("reads a fork that two 500s left unmade as ForkInProgress", () =>311    within(312      ({ seen, store }) =>313        Effect.gen(function* () {314          const repos = yield* RepoHost;315          const base = RepoName.make("demo");316          const name = RepoName.make("demo--fix--carol");317318          yield* seeded(base);319320          expect(yield* Effect.flip(repos.fork(base, name))).toStrictEqual(321            new ForkInProgress({ name })322          );323          expect(324            yield* requestsTo(seen, "POST", `/repos/${base}/fork`)325          ).toHaveLength(2);326          expect(yield* Effect.flip(store.remote(name))).toStrictEqual(327            new RepoNotFound({ name })328          );329        }),330      { forkFailures: 2, forkLost: true }331    )332  );333});334335describe("the tokens the REST adapter carries", () => {336  it.live(337    "sends the API token to the API and repo tokens to git, each only as Authorization: Bearer",338    () =>339      within(({ seen }) =>340        Effect.gen(function* () {341          const repos = yield* RepoHost;342          const name = RepoName.make("tokens");343          const at = Revision.Branch({ name: BranchName.make("main") });344          const { client, first } = yield* seeded(name);345346          const second = yield* client.commit(347            "second",348            [["a.txt", "2"]],349            [first]350          );351352          yield* repos353            .push(name, client.source, [354              { from: Option.some(first), ref: main, to: second },355            ])356            .pipe(Effect.orDie);357          yield* repos.refs(name).pipe(Effect.orDie);358          yield* repos.readFile(name, at, RepoPath.make("a.txt"));359          yield* repos.log(name, at, 5);360          yield* repos.fork(name, RepoName.make("tokens--fork"));361362          const minted = yield* repos.mintToken(363            name,364            "read",365            Duration.minutes(5)366          );367368          yield* repos.revokeToken(name, minted.id);369370          const requests = yield* Ref.get(seen);371          const toApi = requests.filter(({ url }) => url.startsWith(api));372373          const toGit = requests.filter(({ url }) =>374            url.startsWith(remoteBase)375          );376377          const repoTokens = yield* Effect.forEach(378            yield* requestsTo(seen, "POST", "/tokens"),379            ({ reply }) =>380              decodeMinted(reply).pipe(381                Effect.map(({ result }) => result.plaintext)382              )383          );384385          const secrets = [apiToken, ...repoTokens];386387          const leaks = requests.flatMap(({ body, headers, url }) =>388            secrets.filter(389              (secret) =>390                url.includes(secret) ||391                body.includes(secret) ||392                headers.some(393                  ([header, value]) =>394                    header !== "authorization" && value.includes(secret)395                )396            )397          );398399          expect(new Set(toApi.map(authorizationOf))).toStrictEqual(400            new Set([`Bearer ${apiToken}`])401          );402          expect(toGit).not.toHaveLength(0);403          expect(404            toGit.filter(405              (request) =>406                !repoTokens407                  .map((token) => `Bearer ${token}`)408                  .includes(authorizationOf(request))409            )410          ).toStrictEqual([]);411          expect(leaks).toStrictEqual([]);412        })413      )414  );415416  it.live(417    "revokes the tokens it minted for its own git calls when it closes",418    () =>419      Effect.gen(function* () {420        const made = yield* world();421        const name = RepoName.make("closing");422423        yield* Effect.gen(function* () {424          const repos = yield* RepoHost;425          const { client, first } = yield* seeded(name);426427          const second = yield* client.commit(428            "second",429            [["a.txt", "2"]],430            [first]431          );432433          yield* repos434            .push(name, client.source, [435              { from: Option.some(first), ref: main, to: second },436            ])437            .pipe(Effect.orDie);438          yield* repos.refs(name).pipe(Effect.orDie);439        }).pipe(Effect.provide(made.layer));440441        const used = new Set(442          (yield* Ref.get(made.seen))443            .filter(({ url }) => url.startsWith(remoteBase))444            .map(authorizationOf)445        );446447        const ids = yield* Effect.forEach(448          yield* requestsTo(made.seen, "POST", "/tokens"),449          ({ reply }) => decodeMinted(reply)450        ).pipe(451          Effect.map((all) =>452            all453              .filter(({ result }) => used.has(`Bearer ${result.plaintext}`))454              .map(({ result }) => result.id)455          )456        );457458        const revoked = yield* Effect.forEach(ids, (id) =>459          requestsTo(made.seen, "DELETE", `/tokens/${id}`)460        );461462        const live = yield* Effect.forEach(ids, (id) =>463          made.store.revokeToken(name, id).pipe(Effect.orDie)464        );465466        expect(ids).toHaveLength(2);467        expect(ids).toHaveLength(used.size);468        expect(revoked.map((requests) => requests.length)).toStrictEqual([469          1, 1,470        ]);471        expect(live).toStrictEqual([false, false]);472      }).pipe(Effect.scoped, Effect.provide(NodeServices.layer))473  );474475  // cf's help for `tokens revoke`: ids resolve through an eventually476  // consistent index, so a revocation within about a second of the mint can477  // be 404.478  it.live("tries a revocation again when the token index lags its mint", () =>479    within(480      ({ seen }) =>481        Effect.gen(function* () {482          const repos = yield* RepoHost;483          const name = RepoName.make("lagging");484485          yield* repos.create(name).pipe(Effect.orDie);486487          const token = yield* repos488            .mintToken(name, "read", Duration.minutes(5))489            .pipe(Effect.orDie);490491          expect(492            yield* repos.revokeToken(name, token.id).pipe(Effect.orDie)493          ).toBeTruthy();494          expect(495            yield* requestsTo(seen, "DELETE", `/tokens/${token.id}`)496          ).toHaveLength(2);497          expect(498            yield* repos.revokeToken(name, token.id).pipe(Effect.orDie)499          ).toBeFalsy();500        }),501      { revokeLag: 1 }502    )503  );504505  // A removed repo's tokens go with it (workers-types), so git calls to a506  // repo made again under its name need a token of the new repo's.507  it.live(508    "mints a fresh token for git calls to a repo made again under a removed one's name",509    () =>510      within(({ seen }) =>511        Effect.gen(function* () {512          const repos = yield* RepoHost;513          const name = RepoName.make("again");514515          yield* repos.create(name).pipe(Effect.orDie);516          yield* repos.refs(name).pipe(Effect.orDie);517          yield* repos.remove(name);518          yield* repos.create(name).pipe(Effect.orDie);519          yield* repos.refs(name).pipe(Effect.orDie);520521          // The fake's tokens repeat across a repo's lives, so count mints.522          const mints = yield* Effect.forEach(523            yield* requestsTo(seen, "POST", "/tokens"),524            ({ body }) => decodeJson(body)525          );526527          expect(mints).toMatchObject([528            { repo: name, scope: "read" },529            { repo: name, scope: "read" },530          ]);531        })532      )533  );534});535536describe("Artifacts' error codes, read as the port's errors", () => {537  // 10104 is "the source URL does not point to a valid git repository", and538  // 10200 "the repository or remote resource does not exist" (errors page).539  it.live("refuses an import from no repo, and a token for no repo", () =>540    within(() =>541      Effect.gen(function* () {542        const repos = yield* RepoHost;543        const name = RepoName.make("imported");544        const missing = RepoName.make("missing");545        const url = "file:///nowhere/at/all.git";546547        expect(548          yield* Effect.flip(repos.importFrom(name, { url }))549        ).toStrictEqual(550          new ImportRefused({ name, reason: `no repo at ${url}` })551        );552        expect(553          yield* Effect.flip(554            repos.mintToken(missing, "read", Duration.minutes(5))555          )556        ).toStrictEqual(new RepoNotFound({ name: missing }));557      })558    )559  );560561  // 10302 is "an import is in progress for this repository", 10303 "a fork562  // is in progress" (errors page): the name is taken, as `importFrom` reads it.563  it.effect.each([564    { code: 10_302, making: "an import" },565    { code: 10_303, making: "a fork" },566  ])(567    "refuses to create a repo while $making of that name is in progress",568    ({ code, making }) =>569      Effect.gen(function* () {570        const repos = yield* RepoHost;571        const name = RepoName.make("being-made");572573        expect(yield* Effect.exit(repos.create(name))).toStrictEqual(574          Exit.fail(new RepoExists({ name }))575        );576      }).pipe(577        Effect.provide(answering(refused(409, code, `${making} in progress`)))578      )579  );580581  // A proxy's or an edge's reply carries no envelope: its status is all it says.582  it.effect("reads a refusal that names no code by its status", () =>583    Effect.gen(function* () {584      const repos = yield* RepoHost;585      const name = RepoName.make("unseen");586587      expect(yield* Effect.exit(repos.remote(name))).toStrictEqual(588        Exit.fail(new RepoNotFound({ name }))589      );590    }).pipe(591      Effect.provide(592        answering(() => new Response("Not Found", { status: 404 }))593      )594    )595  );596597  // Cloudflare's own codes, such as 7000 for a route it does not know, say the598  // adapter asked for the wrong thing. Read by status, a wrong route, account599  // or namespace would pass for a missing repo, and a remove for a done one.600  it.effect(601    "fails as a defect on a refusal that names only Cloudflare's own codes",602    () =>603      Effect.gen(function* () {604        const repos = yield* RepoHost;605        const name = RepoName.make("unrouted");606607        const died = [608          Exit.hasDies(yield* Effect.exit(repos.remote(name))),609          Exit.hasDies(yield* Effect.exit(repos.remove(name))),610          Exit.hasDies(611            yield* Effect.exit(612              repos.readBlob(name, ObjectId.make("0".repeat(40)))613            )614          ),615        ];616617        expect(died).toStrictEqual([true, true, true]);618      }).pipe(619        Effect.provide(answering(refused(404, 7000, "No route for that URI")))620      )621  );622});623624describe("reads whose replies the REST docs do not show", () => {625  it.live.each([{ casing: "snake" as const }, { casing: "camel" as const }])(626    "reads a commit and a log whose metadata is in $casing case",627    ({ casing }) =>628      within(629        () =>630          Effect.gen(function* () {631            const repos = yield* RepoHost;632            const name = RepoName.make("metadata");633            const { client, first } = yield* seeded(name);634            const written = yield* treeOf(client.source, first);635636            const commit = yield* repos637              .readCommit(name, first)638              .pipe(Effect.orDie);639640            expect(commit).toStrictEqual(641              Option.some({642                author: { email: "answerer@example.com", name: "Answerer" },643                authoredAt: 1_791_300_000,644                committedAt: 1_791_300_000,645                committer: { email: "answerer@example.com", name: "Answerer" },646                message: "first",647                parents: [],648                sha: first,649                tree: written,650              })651            );652            expect(653              yield* repos654                .log(name, Revision.Commit({ sha: first }), 10)655                .pipe(Effect.orDie)656            ).toStrictEqual(Option.toArray(commit));657          }),658        { casing }659      )660  );661662  it.live("reads no tree at a blob's id or a commit's id", () =>663    within(() =>664      Effect.gen(function* () {665        const repos = yield* RepoHost;666        const name = RepoName.make("kinds");667        const { client, first } = yield* seeded(name);668        const tree = yield* treeOf(client.source, first);669        const entries = yield* repos.readTree(name, tree).pipe(Effect.orDie);670        const blob = Option.getOrThrow(entries)[0]?.sha ?? tree;671672        expect(blob).not.toBe(tree);673        expect(yield* Effect.exit(repos.readTree(name, blob))).toStrictEqual(674          Exit.succeed(Option.none())675        );676        expect(677          yield* Effect.exit(repos.readTree(name, ObjectId.make(first)))678        ).toStrictEqual(Exit.succeed(Option.none()));679      })680    )681  );682});