iterate.com / git

git clone https://git.iterate.com/repos/git

git / tests / app.test.mjsmain at 517348b

// tests/app.test.mjs — the git remote of the app (../app.ts), between a git client and a repo's
// Artifacts remote. The remote here is a local HTTP server that records what reaches it, and the
// mind is a fake `itx` with a kv and the Artifacts verbs the app calls. The app's own fetch goes
// to that server. pages.test.mjs has the pages a browser reads.
// Run it from the repo's root with `node --test "tests/*.test.mjs"`.
import "@repos/stdlib/testing/mind-loader.mjs";
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { test } from "node:test";

const { gitApp } = await import("../app.ts");

test("anyone clones a public repo: the app adds a read token of its own, minted once, and nothing of it is in the mind's kv", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });

  const refs = await git.fetch(
    new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"),
    mind,
  );
  assert.equal(refs.status, 200);
  assert.equal(await refs.text(), "refs of /remote/kernel");
  const pack = await git.fetch(
    new Request("https://git.example.com/repos/kernel/git-upload-pack", {
      method: "POST",
      headers: { "content-type": "application/x-git-upload-pack-request" },
      body: "want main",
    }),
    mind,
  );
  assert.equal(await pack.text(), "pack for: want main");

  const readToken = `Basic ${btoa("x:read-token-1-of-/repos/kernel")}`;
  assert.deepEqual(
    remote.requests.map(({ method, url, authorization }) => ({ method, url, authorization })),
    [
      {
        method: "GET",
        url: "/remote/kernel/info/refs?service=git-upload-pack",
        authorization: readToken,
      },
      { method: "POST", url: "/remote/kernel/git-upload-pack", authorization: readToken },
    ],
  );
  assert.deepEqual(mind.minted, [{ repo: "/repos/kernel", scope: "read", ttlSeconds: 600 }]);
  assert.deepEqual(mind.remotesAsked, ["/repos/kernel"]);
  assert.deepEqual(mind.kv, {});
});

test("what an earlier version kept in the kv is never read: not its token, and not its address for the repo", async () => {
  await using remote = await artifactsRemote();
  await using elsewhere = await artifactsRemote();
  const mind = fakeMind(remote);
  const old = `Basic ${btoa("x:read-token-of-an-earlier-version")}`;
  // an entry as the version before kept it, with an address that some other code wrote over it
  const entry = JSON.stringify({
    remote: `${elsewhere.origin}/remote/kernel`,
    readToken: { authorization: old, until: Date.now() + 3_000_000 },
  });
  mind.kv["git-app:/repos/kernel"] = entry;
  const git = gitApp({ public: ["/repos/kernel"], ...look });
  // a token of the caller's own, which the app passes on
  const own = `Basic ${btoa("x:art_v2_the-callers-own")}`;

  await git.fetch(
    new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"),
    mind,
  );
  await git.fetch(
    new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack", {
      headers: { authorization: own },
    }),
    mind,
  );
  assert.deepEqual(
    remote.requests.map(({ authorization }) => authorization),
    [`Basic ${btoa("x:read-token-1-of-/repos/kernel")}`, own],
  );
  // no credential went to the address in the kv, and the app wrote nothing there
  assert.deepEqual(elsewhere.requests, []);
  assert.deepEqual(mind.kv, { "git-app:/repos/kernel": entry });
});

test("requests that come together to a new isolate each ask, and the next request asks nothing", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });
  const read = () =>
    git.fetch(
      new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"),
      mind,
    );

  const answers = await Promise.all([read(), read(), read()]);
  assert.deepEqual(answers.map(({ status }) => status), [200, 200, 200]);
  // no request waits for another request's promise
  assert.equal(mind.minted.length, 3);
  assert.equal(mind.remotesAsked.length, 3);

  assert.equal((await read()).status, 200);
  assert.equal(mind.minted.length, 3);
  assert.equal(mind.remotesAsked.length, 3);
});

test("a request that ended before its token came leaves nothing that the next request waits for", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: [], ...look });
  const read = () =>
    git.fetch(
      new Request("https://git.example.com/repos/later/info/refs?service=git-upload-pack", {
        headers: asMember,
      }),
      mind,
    );

  // the repo is not there, and the mint never answers: as when the runtime ends the request first
  mind.stuck.add("/repos/later");
  assert.equal((await read()).status, 404);

  mind.stuck.clear();
  mind.repos.push("/repos/later");
  const answer = await Promise.race([
    read(),
    new Promise((resolve) => setTimeout(() => resolve({ status: "waited for the old request" }), 500)),
  ]);
  assert.equal(answer.status, 200);
});

test("a repo that was public and is taken off the list gets no token: a new isolate has none, and nothing is written down", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const read = (git) =>
    git.fetch(
      new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"),
      mind,
    );

  assert.equal((await read(gitApp({ public: ["/repos/kernel"], ...look }))).status, 200);
  // the config's next publish: the list no longer names the repo
  const refused = await read(gitApp({ public: [], ...look }));
  // the answer that says nothing of what exists, and Artifacts is not asked
  assert.equal(refused.status, 404);
  assert.equal(remote.requests.length, 1);
  assert.equal(mind.minted.length, 1);
});

test("a member's git reads a repo that is not public with a read token of the app's own, and the member's credential never leaves", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });

  const refs = await git.fetch(
    new Request("https://git.example.com/repos/config.git/info/refs?service=git-upload-pack", {
      headers: { ...asMember, cookie: "session=of-the-mind", "git-protocol": "version=2" },
    }),
    mind,
  );
  assert.equal(refs.status, 200);
  assert.deepEqual(
    remote.requests.map(({ url, authorization, cookie, gitProtocol }) => ({
      url,
      authorization,
      cookie,
      gitProtocol,
    })),
    [
      {
        url: "/remote/config/info/refs?service=git-upload-pack",
        authorization: `Basic ${btoa("x:read-token-1-of-/repos/config")}`,
        // a cookie of the mind's never leaves; what git says of its protocol does
        cookie: undefined,
        gitProtocol: "version=2",
      },
    ],
  );
  assert.deepEqual(mind.minted, [{ repo: "/repos/config", scope: "read", ttlSeconds: 600 }]);
  // in this isolate's memory alone
  assert.deepEqual(mind.kv, {});
});

test("a member's push goes with a write token minted for that one request, and the repo's log says who pushed what", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });

  const refs = await git.fetch(
    new Request("https://git.example.com/repos/kernel/info/refs?service=git-receive-pack", {
      headers: asMember,
    }),
    mind,
  );
  assert.equal(refs.status, 200);
  const pushed = await git.fetch(
    new Request("https://git.example.com/repos/kernel/git-receive-pack", {
      method: "POST",
      headers: asMember,
      body: "the pack, for refs/heads/add-b",
    }),
    mind,
  );
  assert.equal(await pushed.text(), "unpack ok\nok refs/heads/add-b\n");
  assert.deepEqual(
    remote.requests.map(({ url, authorization }) => ({ url, authorization })),
    [
      {
        url: "/remote/kernel/info/refs?service=git-receive-pack",
        authorization: `Basic ${btoa("x:write-token-1-of-/repos/kernel")}`,
      },
      {
        url: "/remote/kernel/git-receive-pack",
        authorization: `Basic ${btoa("x:write-token-2-of-/repos/kernel")}`,
      },
    ],
  );
  assert.deepEqual(mind.minted, [
    { repo: "/repos/kernel", scope: "write", ttlSeconds: 300 },
    { repo: "/repos/kernel", scope: "write", ttlSeconds: 300 },
  ]);
  // no write token is kept
  assert.doesNotMatch(JSON.stringify(mind.kv), /write-token/);
  assert.deepEqual(mind.appended, [
    {
      path: "/repos/kernel",
      event: { type: "git/pushed", payload: { by: "ada@example.com", refs: ["refs/heads/add-b"] } },
    },
  ]);
});

test("a push from a page is taken from this app's own page alone: another site's page pushes nothing with the member's sign-in", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });
  const push = (site, path = "git-receive-pack", method = "POST") =>
    git.fetch(
      new Request(`https://git.example.com/repos/kernel/${path}`, {
        method,
        headers: { ...asMember, ...(site && { "sec-fetch-site": site }) },
        ...(method === "POST" && { body: "the pack, for refs/heads/add-b" }),
      }),
      mind,
    );

  for (const site of ["cross-site", "same-site", "none"]) {
    const refused = await push(site);
    assert.equal(refused.status, 403, site);
    assert.equal(await refused.text(), "git: a page of another site does not push here\n");
  }
  assert.equal((await push("cross-site", "info/refs?service=git-receive-pack", "GET")).status, 403);
  assert.deepEqual([remote.requests.length, mind.minted.length, mind.appended.length], [0, 0, 0]);

  // the app's own page, as a member's edit pushes its branch
  const own = await push("same-origin");
  assert.equal(await own.text(), "unpack ok\nok refs/heads/add-b\n");
  assert.deepEqual(mind.appended.map(({ event }) => event.payload), [{ by: "ada@example.com", refs: ["refs/heads/add-b"] }]);
  // a read is as it was, wherever it comes from: nothing of it is the member's to lose
  assert.equal((await push("cross-site", "info/refs?service=git-upload-pack", "GET")).status, 200);
});

test("with no sign-in, a repo that is not public and a repo that is not there get the same answer, and so does a push", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });
  const asked = async (path, headers = {}) => {
    const answer = await git.fetch(new Request(`https://git.example.com${path}`, { headers }), mind);
    return {
      status: answer.status,
      challenge: answer.headers.get("www-authenticate"),
      type: answer.headers.get("content-type"),
      text: await answer.text(),
    };
  };
  const read = "/info/refs?service=git-upload-pack";

  // A GIT WITH NO HELPER: a 404, whose words git shows, with the command to run
  const fresh = await asked(`/repos/config${read}`);
  assert.deepEqual(fresh, {
    status: 404,
    challenge: null,
    type: "text/plain; charset=utf-8",
    text: "iterate: there is no repo here that you can read.\nIf it is private, sign in once, then run the same command again:\n  npx iterate git setup git.example.com\n",
  });
  assert.deepEqual(await asked(`/repos/missing${read}`), fresh);
  assert.deepEqual(await asked("/repos/kernel/info/refs?service=git-receive-pack"), fresh);

  // A GIT WITH THE HELPER and no credential yet: a 401, so git asks the helper
  const marked = { "x-iterate-git": "1" };
  const challenged = await asked(`/repos/config${read}`, marked);
  assert.deepEqual(
    { status: challenged.status, challenge: challenged.challenge },
    { status: 401, challenge: 'Basic realm="iterate git"' },
  );
  assert.deepEqual(await asked(`/repos/missing${read}`, marked), challenged);

  // A CREDENTIAL THAT THE BOUNDARY DID NOT TAKE (a sign-in that ended): a 401 with words, and git
  // forgets the token
  const ended = { ...marked, authorization: `Basic ${btoa("iterate:a-token-that-ended")}` };
  const refused = await asked(`/repos/config${read}`, ended);
  assert.deepEqual(refused, {
    status: 401,
    challenge: 'Basic realm="iterate git"',
    type: "text/plain; charset=utf-8",
    text: "iterate: this sign-in has ended or was taken away.\nSign in again, then run the same command:\n  npx iterate git setup git.example.com\n",
  });
  assert.deepEqual(await asked(`/repos/missing${read}`, ended), refused);

  // nothing was asked of Artifacts, and nothing was minted or kept
  assert.deepEqual(remote.requests, []);
  assert.deepEqual(mind.minted, []);
  assert.deepEqual(mind.kv, {});
});

test("a public repo is still read by a git whose sign-in ended", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });

  const refs = await git.fetch(
    new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack", {
      headers: { authorization: `Basic ${btoa("iterate:a-token-that-ended")}` },
    }),
    mind,
  );
  assert.equal(refs.status, 200);
  assert.equal(remote.requests[0].authorization, `Basic ${btoa("x:read-token-1-of-/repos/kernel")}`);
});

test("a caller's own Artifacts token is passed on as it came, and one that Artifacts refuses gets the answer that names no repo", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: [], ...look });
  const own = "Bearer art_v2_the-callers-own";

  const pushed = await git.fetch(
    new Request("https://git.example.com/repos/kernel/git-receive-pack", {
      method: "POST",
      headers: { authorization: own },
      body: "the pack, for refs/heads/main",
    }),
    mind,
  );
  assert.equal(await pushed.text(), "unpack ok\nok refs/heads/main\n");
  assert.equal(remote.requests[0].authorization, own);
  assert.deepEqual(mind.minted, []);
  // Artifacts knows a token and no person: nobody is written as the one who pushed
  assert.deepEqual(mind.appended, []);
  assert.deepEqual(mind.announced, ["/repos/kernel"]);

  const read = "/info/refs?service=git-upload-pack";
  const refusedBy = async (path) => {
    const answer = await git.fetch(
      new Request(`https://git.example.com${path}`, {
        headers: { authorization: `Basic ${btoa("x:art_v2_refused")}` },
      }),
      mind,
    );
    return [answer.status, await answer.text()];
  };
  const refused = await refusedBy(`/repos/config${read}`);
  assert.equal(refused[0], 401);
  assert.match(refused[1], /^iterate: this sign-in has ended/);
  assert.deepEqual(await refusedBy(`/repos/missing${read}`), refused);
});

test("a push that moved main tells the mind's repo, so the mind publishes what was pushed; a push of another branch tells it nothing", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: [], ...look });
  const push = (ref) =>
    git.fetch(
      new Request("https://git.example.com/repos/kernel/git-receive-pack", {
        method: "POST",
        headers: asMember,
        body: `the pack, for ${ref}`,
      }),
      mind,
    );

  const branch = await push("refs/heads/add-b");
  assert.equal(await branch.text(), "unpack ok\nok refs/heads/add-b\n");
  assert.deepEqual(mind.announced, []);

  const main = await push("refs/heads/main");
  // git gets the remote's report as it came
  assert.equal(await main.text(), "unpack ok\nok refs/heads/main\n");
  assert.deepEqual(mind.announced, ["/repos/kernel"]);
});

test("a push stands when the mind's repo could not be told, or its log not written: git gets the remote's report", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  mind.away.add("/repos/kernel");
  const git = gitApp({ public: [], ...look });

  const pushed = await git.fetch(
    new Request("https://git.example.com/repos/kernel/git-receive-pack", {
      method: "POST",
      headers: asMember,
      body: "the pack, for refs/heads/main",
    }),
    mind,
  );

  assert.equal(pushed.status, 200);
  assert.equal(await pushed.text(), "unpack ok\nok refs/heads/main\n");
  assert.deepEqual(mind.announced, []);
  assert.deepEqual(mind.appended, []);
});

test("a read token that is about to end is replaced, and the repo's remote is not asked for again", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });
  const read = () =>
    git.fetch(
      new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"),
      mind,
    );

  await read();
  await read();
  // the same isolate, the same token
  assert.equal(mind.minted.length, 1);
  // nine and a half minutes later the token ends in half a minute
  const realNow = Date.now;
  Date.now = () => realNow() + 570_000;
  try {
    await read();
  } finally {
    Date.now = realNow;
  }

  assert.equal(remote.requests.at(-1).authorization, `Basic ${btoa("x:read-token-2-of-/repos/kernel")}`);
  assert.equal(mind.minted.length, 2);
  assert.deepEqual(mind.remotesAsked, ["/repos/kernel"]);
});

test("when the mind does not answer, a public repo's reader and a member are told to try again; that is no word about the repo", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });
  mind.unavailable.add("/repos/kernel").add("/repos/config");
  const read = (repo, headers = {}) =>
    git.fetch(new Request(`https://git.example.com/repos/${repo}/info/refs?service=git-upload-pack`, { headers }), mind);

  for (const answer of [await read("kernel"), await read("kernel", asMember), await read("config", asMember)]) {
    assert.equal(answer.status, 503);
    assert.equal(answer.headers.get("retry-after"), "10");
    assert.equal(await answer.text(), "git: the mind did not answer just now. Try again in a few seconds.\n");
  }
  // anyone else is told what they are always told of a repo that is not public: nothing of it
  const stranger = await read("config");
  assert.equal(stranger.status, 404);
  assert.match(await stranger.text(), /there is no repo here that you can read/);
  assert.equal(remote.requests.length, 0);

  // the mind answers again: the same reader reads
  mind.unavailable.clear();
  assert.equal((await read("kernel")).status, 200);
});

test("what is no git request is refused before the mind is asked anything", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });

  const page = await git.fetch(new Request("https://git.example.com/about"), mind);
  assert.equal(page.status, 404);
  // git's older "dumb" protocol asks for info/refs with no service
  const dumb = await git.fetch(
    new Request("https://git.example.com/repos/kernel/info/refs"),
    mind,
  );
  assert.equal(dumb.status, 403);
  assert.deepEqual(remote.requests, []);
  assert.deepEqual(mind.kv, {});
});

test("a member is told when the mind has no such repo", async () => {
  await using remote = await artifactsRemote();
  const mind = fakeMind(remote);
  const git = gitApp({ public: ["/repos/kernel"], ...look });

  const answer = await git.fetch(
    new Request("https://git.example.com/repos/missing/info/refs?service=git-upload-pack", {
      headers: asMember,
    }),
    mind,
  );
  assert.equal(answer.status, 404);
  assert.match(await answer.text(), /^git: no repo at \/repos\/missing/);
  assert.deepEqual(remote.requests, []);
});

// ── the fixtures ──

/** What worker.ts hands the app for its pages, which no test here reads. */
const look = { icon: () => new Response("the icon") };

/** A request that the boundary stamped as a member's: the fake mind reads this header in the
 *  stamp's place (`fakeMind`). */
const asMember = { "x-test-member": "ada@example.com" };

/** The mind as the app reaches it: a kv, and the Artifacts repos `kernel` and `config`, served
 *  by `remote`. It records each token it mints, each repo whose remote it was asked for, and each
 *  repo that was told its main has a new tip, and each event appended to a repo's log. A repo in
 *  `away` throws when it is told or written to. */
function fakeMind(remote) {
  const kv = {};
  const minted = [];
  const remotesAsked = [];
  const announced = [];
  const appended = [];
  const away = new Set();
  // a repo whose mint never answers
  const stuck = new Set();
  // a repo for which the mind does not answer, as the platform says it: an error with a code
  const unavailable = new Set();
  const repos = ["/repos/kernel", "/repos/config"];
  const itx = {
    kv: {
      get: async (key) => kv[key] || null,
      put: async (key, value) => {
        kv[key] = value;
        return { ok: true };
      },
    },
    cfArtifacts: {
      get: async (repo) => ({
        remote: async () => {
          if (unavailable.has(repo))
            throw Object.assign(new Error("Durable Object is overloaded. Requests queued for too long."), {
              code: "UNAVAILABLE",
              data: { kind: "overloaded", retryAfterMs: 10_000 },
            });
          if (!repos.includes(repo)) throw new Error(`Artifacts: repo not found: ${repo}`);
          remotesAsked.push(repo);
          return `${remote.origin}/remote/${repo.split("/").at(-1)}`;
        },
        createToken: async (scope, ttlSeconds) => {
          if (stuck.has(repo)) await new Promise(() => {});
          minted.push({ repo, scope, ttlSeconds });
          return { plaintext: `${scope}-token-${minted.length}-of-${repo}` };
        },
      }),
    },
    repos: {
      get: (repo) => ({
        announceTip: async () => {
          if (away.has(repo)) throw new Error(`the repo ${repo} is away`);
          announced.push(repo);
          return "the tip";
        },
      }),
    },
    cd: (path) => ({
      append: async (event) => {
        if (away.has(path)) throw new Error(`the repo ${path} is away`);
        appended.push({ path, event });
      },
    }),
    [Symbol.dispose]() {},
  };
  // what is no git request is asked whether it is a member's socket: here none is
  return {
    kv,
    minted,
    stuck,
    unavailable,
    repos,
    remotesAsked,
    announced,
    appended,
    away,
    getItx: () => itx,
    auth: {
      memberPage: () => null,
      // the boundary's stamp, which the tests write as a header of their own
      principal: (request) => {
        const email = request.headers.get("x-test-member");
        return email ? { actor: "user_ada", email } : null;
      },
    },
  };
}

/** A repo's Artifacts remote: a server on this machine that records each request and answers as
 *  git's smart HTTP does in outline. A request with no credential, or with the one token that
 *  the tests call refused, gets Artifacts' own 401. */
async function artifactsRemote() {
  // Node's fetch wants `duplex: "half"` said for a body that is a stream, which the app's is.
  // workerd, where the app runs, takes a stream as it is.
  const nodeFetch = globalThis.fetch;
  globalThis.fetch = (input, init) => nodeFetch(input, { ...init, duplex: "half" });

  const requests = [];
  const server = createServer(async (request, response) => {
    const chunks = [];
    for await (const chunk of request) chunks.push(chunk);
    const body = Buffer.concat(chunks).toString();
    requests.push({
      method: request.method,
      url: request.url,
      authorization: request.headers.authorization,
      cookie: request.headers.cookie,
      gitProtocol: request.headers["git-protocol"],
    });
    const credential = request.headers.authorization || "";
    const refused = credential.includes("refused") || credential === `Basic ${btoa("x:art_v2_refused")}`;
    if (!credential || refused) {
      response.writeHead(401, { "www-authenticate": 'Basic realm="artifacts"' }).end();
      return;
    }
    const path = request.url.split("?")[0];
    response.writeHead(200, { "content-type": "application/x-git-advertisement" });
    if (path.endsWith("/info/refs")) response.end(`refs of ${path.replace("/info/refs", "")}`);
    // git's report of a push: the pack was read, and each branch that the push named was moved
    else if (path.endsWith("/git-receive-pack"))
      response.end(
        ["unpack ok\n", ...(body.match(/refs\/heads\/\S+/g) || []).map((ref) => `ok ${ref}\n`)].join(""),
      );
    else response.end(`pack for: ${body}`);
  });
  await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
  return {
    requests,
    origin: `http://127.0.0.1:${server.address().port}`,
    async [Symbol.asyncDispose]() {
      globalThis.fetch = nodeFetch;
      server.closeAllConnections();
      await new Promise((resolve) => server.close(resolve));
    },
  };
}