kernel / core / lib / src / cli / git.test.tsmain at 949894f
// Git's credential helper and the config that `iterate git setup` writes (./git.ts), against a
// stand-in for the issuer's token endpoint and a sign-in folder of the test's own.
import { mkdtempDisposableSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { expect, test as base, vi } from "vitest";
// the CLI's folder is read once, when ./config.ts is loaded: so before the import
const config = mkdtempDisposableSync(join(tmpdir(), "iterate-test-"));
vi.stubEnv("XDG_CONFIG_HOME", config.path);
const { CONFIG_DIR, readSession, writeSession } = await import("./config.ts");
const {
credentialInputOf,
gitConfigOf,
gitCredential,
gitHostOf,
HOST_TOKEN_LEAST_LEFT_MS,
isHostOfMind,
mindOfGitHost,
personIsThere,
repoOfGitPath,
} = await import("./git.ts");
/** `test`, with the folder removed after the file's last test. */
const test = base.extend<{ folderRemoved: void }>({
folderRemoved: [
// oxlint-disable-next-line no-empty-pattern -- vitest reads the fixture's needs from this pattern
async ({}, use) => {
await use();
config.remove();
},
{ scope: "file", auto: true },
],
});
const ADDRESS = "iterate.example.com";
const ISSUER = `https://${ADDRESS}`;
const TOKEN_ENDPOINT = `${ISSUER}/oauth2/token`;
const session = { issuer: ISSUER, tokenEndpoint: TOKEN_ENDPOINT, clientId: "cli", token: "api-1" };
const ASKED = "protocol=https\nhost=git.example.com\nwwwauth[]=Basic realm=x\n\n";
test("the sign-ins of this file are in its own folder, not the person's", () => {
expect(CONFIG_DIR).toBe(join(config.path, "iterate"));
});
test("setup writes the helper for the one host, with the inherited helpers cleared, and the marker", () => {
expect(gitConfigOf({ host: "git.example.com", helper: "iterate git-credential --mind m" })).toEqual(
[
["--replace-all", "credential.https://git.example.com.helper", ""],
["--add", "credential.https://git.example.com.helper", "!iterate git-credential --mind m"],
["--replace-all", "credential.https://git.example.com.useHttpPath", "false"],
["--replace-all", "http.https://git.example.com/.extraHeader", "X-Iterate-Git: 1"],
],
);
// in a sandbox git names the repo to the helper
expect(gitConfigOf({ host: "git.example.com", helper: "h", namesRepo: true })[2]).toEqual([
"--replace-all",
"credential.https://git.example.com.useHttpPath",
"true",
]);
});
test("in a sandbox of the mind, get answers the mind's own token for the repo that git names, and keeps nothing", async () => {
await run(issuerOf(), "erase");
const issuer = issuerOf();
const minted: string[] = [];
const io = {
...issuer.io,
repoToken: async (repo: string, host: string) => {
expect(host).toBe("git.example.com");
minted.push(repo);
if (repo === "/repos/away") throw new Error("no such repo");
return `token-of-${repo}`;
},
};
const get = (path: string) =>
gitCredential({
operation: "get",
asked: `protocol=https\nhost=git.example.com\n${path}\n`,
address: ADDRESS,
interactive: false,
io,
});
expect(await get("path=repos/config.git")).toBe(
"username=iterate\npassword=token-of-/repos/config\n",
);
expect(await get("path=repos/away")).toBe("quit=1\n");
// git named no repo: the setup of a sandbox has it name one
expect(await get("")).toBe("quit=1\n");
expect(minted).toEqual(["/repos/config", "/repos/away"]);
expect(issuer.said).toEqual([
"iterate: this sandbox got no token for /repos/away from iterate.example.com: no such repo",
"iterate: git named no repo of git.example.com to its helper. Run this, then the same git command again:\n npx iterate git setup git.example.com",
]);
// no session was asked for, no exchange was made, and nothing is kept
expect([issuer.sessions, issuer.asked, readSession("https://git.example.com")]).toEqual([
[],
[],
null,
]);
});
test("a git host is a hostname, typed bare or as a remote's address, and its mind is the host without its first label", () => {
expect([
gitHostOf("git.example.com"),
gitHostOf("https://Git.Example.com/repos/config"),
mindOfGitHost("git.example.com"),
]).toEqual(["git.example.com", "git.example.com", "example.com"]);
for (const typed of ["localhost", "http://git.example.com", "git.example.com:8443"])
expect(() => gitHostOf(typed)).toThrow("no https host");
});
test("a host of the mind is its apex or a name under it, and nothing that only looks like it", () => {
const mind = "https://example.com";
expect(
["git.example.com", "example.com", "GIT.Example.com", "git.example.com.evil.test", "evilexample.com", "git.other.test"].map(
(host) => isHostOfMind(host, mind),
),
).toEqual([true, true, true, false, false, false]);
expect(isHostOfMind("git.example.com", "not an address")).toBe(false);
});
test("the path that git names is a repo of the mind, or none", () => {
expect(
["repos/config", "/repos/config.git/", "repos/github.com/iterate/core", "config", "repos/a b", undefined].map(
repoOfGitPath,
),
).toEqual(["/repos/config", "/repos/config", "/repos/github.com/iterate/core", null, null, null]);
});
test("what git writes is read line by line up to the empty line", () => {
expect(credentialInputOf("protocol=https\r\nhost=git.example.com\npath=a=b\n\n")).toEqual({
protocol: "https",
host: "git.example.com",
path: "a=b",
});
});
test("get exchanges the session for the host's token, keeps it, and answers it as a Basic pair", async () => {
const issuer = issuerOf();
const stdout = await get(issuer);
expect(stdout).toBe("username=iterate\npassword=host-1\n");
expect(issuer.asked).toEqual([
{
url: TOKEN_ENDPOINT,
grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
subject_token: "api-1",
subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
resource: "https://git.example.com",
},
]);
// the session was asked for with enough left for a clone
expect(issuer.sessions).toEqual([{ leastLeftMs: 2 * HOST_TOKEN_LEAST_LEFT_MS, signIn: false }]);
// a second git command within the token's life asks nobody
expect(await get(issuer)).toBe(stdout);
expect(issuer.asked).toHaveLength(1);
// erase, which git calls after the host refused the token, forgets it and no more
expect(await run(issuer, "erase")).toBe("");
expect(readSession("https://git.example.com")).toBeNull();
expect(await get(issuer)).toBe("username=iterate\npassword=host-2\n");
});
test("a kept token that is about to end is exchanged again", async () => {
writeSession("https://git.example.com", {
...session,
token: "old",
expiresAt: new Date(Date.now() + HOST_TOKEN_LEAST_LEFT_MS - 1000).toISOString(),
});
expect(await get(issuerOf())).toBe("username=iterate\npassword=host-1\n");
});
test("with no sign-in and nobody there, get says what to run and tells git to stop", async () => {
await run(issuerOf(), "erase");
const issuer = issuerOf({ session: new Error("Not signed in to iterate.example.com.") });
expect(await get(issuer)).toBe("quit=1\n");
expect(issuer.said).toEqual([
"iterate: not signed in to iterate.example.com (Not signed in to iterate.example.com.). Run this, then the same git command again:\n npx iterate git setup git.example.com",
]);
expect(issuer.asked).toEqual([]);
});
test("a session that the issuer refuses for the host stops git with the issuer's words", async () => {
const issuer = issuerOf({
refusal: { error: "invalid_request", error_description: "The subject token is not live." },
});
expect(await get(issuer)).toBe("quit=1\n");
expect(issuer.said[0]).toContain(
"iterate.example.com gave no token for git.example.com (invalid_request: The subject token is not live.)",
);
expect(readSession("https://git.example.com")).toBeNull();
});
test("with a person there, a session that the issuer refuses is forgotten and signed in again, once", async () => {
await run(issuerOf(), "erase");
const issuer = issuerOf();
let refusals = 1;
const io = {
...issuer.io,
fetcher: (async (url: string, init: RequestInit) =>
refusals-- > 0
? Response.json({ error: "invalid_request" }, { status: 400 })
: issuer.io.fetcher(url, init)) as typeof fetch,
};
const stdout = await gitCredential({
operation: "get",
asked: ASKED,
address: ADDRESS,
interactive: true,
io,
});
expect(stdout).toBe("username=iterate\npassword=host-1\n");
expect(issuer.sessions).toEqual([
{ leastLeftMs: 2 * HOST_TOKEN_LEAST_LEFT_MS, signIn: true },
{ leastLeftMs: 2 * HOST_TOKEN_LEAST_LEFT_MS, signIn: true, anew: true },
]);
expect(issuer.said).toEqual(["iterate: your sign-in to iterate.example.com has ended."]);
});
test("store, an unknown word and a request that is not https answer nothing and ask nobody", async () => {
const issuer = issuerOf();
expect(await run(issuer, "store")).toBe("");
expect(await run(issuer, "capability")).toBe("");
expect(await run(issuer, "get", "protocol=http\nhost=git.example.com\n\n")).toBe("");
expect(issuer.asked).toEqual([]);
});
test("a person is there with a terminal on stderr, prompts on, and no coding agent", () => {
expect([
personIsThere({}, true),
personIsThere({}, false),
personIsThere({ GIT_TERMINAL_PROMPT: "0" }, true),
personIsThere({ AGENT: "1" }, true),
]).toEqual([true, false, false, false]);
});
/** A stand-in for the CLI's sign-in and the issuer's token endpoint: each exchange answers the
* next `host-<n>` for an hour, or `refusal`. */
function issuerOf(options: { session?: Error; refusal?: Record<string, string> } = {}) {
const asked: Record<string, string>[] = [];
const sessions: unknown[] = [];
const said: string[] = [];
return {
asked,
sessions,
said,
io: {
say: (line: string) => void said.push(line),
async session(input: { leastLeftMs: number; signIn: boolean; anew?: boolean }) {
sessions.push(input);
if (options.session) throw options.session;
return session;
},
fetcher: (async (url: string, init: RequestInit) => {
asked.push({ url, ...Object.fromEntries(new URLSearchParams(String(init.body))) });
return options.refusal
? Response.json(options.refusal, { status: 400 })
: Response.json({ access_token: `host-${asked.length}`, expires_in: 3600 });
}) as typeof fetch,
},
};
}
const run = (issuer: ReturnType<typeof issuerOf>, operation: string, asked = ASKED) =>
gitCredential({ operation, asked, address: ADDRESS, interactive: false, io: issuer.io });
const get = (issuer: ReturnType<typeof issuerOf>) => run(issuer, "get");