Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1031,6 +1031,16 @@ fallback key; `ecr doctor` diagnoses setup.
`ecr setup-auth` again for a new token. It signs in again unless a review
would take the current token without a warning.

For CI, a scheduled workflow must refresh the token. Start that chain with
`ecr setup-auth --ci-store <owner/repo> --ci-target <owner/repo>`. It signs in
to SuperGrok in a temporary store, only for CI, and writes the tokens to GitHub
Actions secrets with `gh`. The store repo gets `XAI_OAUTH_REFRESH_TOKEN` and
`XAI_OAUTH_ACCESS_TOKEN`. Each target repo gets `XAI_OAUTH_ACCESS_TOKEN`. The
workflow in the store repo then sends the refresh token to xAI before the
access token expires, and it writes the new tokens back. Keep the refresh
token out of every repo that runs reviews, and do not reuse your own OpenCode
sign-in for CI.

`XAI_OAUTH_ACCESS_TOKEN` needs `"mode": "oauth"`. An entry that names it
without that mode is refused.

Expand Down
3 changes: 2 additions & 1 deletion llp/0007-cli-commands-and-ci.explainer.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,12 @@ doctor resolves auth the way real reviews do: a `routing.jsonc` `defaults.auth`

`ecr setup-auth` derives a plan from the repo's auth config via a pure `planFromAuth`, then guides local credential acquisition. Its decisions:

- It hands out only ACCESS tokens; the refresh token never leaves OpenCode's store, because OpenCode's refresh tokens are SINGLE-USE (rotation) and OpenCode is their sole legitimate consumer — a copy in a shell config or CI secret dies on the next rotation and can take the whole sign-in down with it [observed: `src/commands/setup-auth.ts:87-93`].
- It hands out only ACCESS tokens; the refresh token never leaves OpenCode's store, because OpenCode's refresh tokens are SINGLE-USE (rotation) and OpenCode is their sole legitimate consumer — a copy in a shell config or CI secret dies on the next rotation and can take the whole sign-in down with it [observed: `src/commands/setup-auth.ts:87-93`]. The CI seed below is the one exception, and it uses a login that no OpenCode store keeps.
- The exported shell line single-quotes the token value so a token containing shell metacharacters (`$HOME`, `!`) is never expanded when sourced [observed: `src/commands/setup-auth.ts:127-131`; test in `src/__tests__/setup-auth.test.ts`]. A single quote in the value is escaped. The env name is printed unquoted, and the config that names it comes from the repo, so the schema refuses an `auth` `tokenEnv` that is not an env var name. That check sits on the `auth` union, not on the field: a field error in the map shape would fall through to the legacy shape and load the default auth [observed: `src/commands/setup-auth.ts` `exportLine`; `src/config/schema.ts` `ENV_VAR_NAME`; test in `src/__tests__/config-load.test.ts`].
- `anthropic` auth is always satisfied by the Claude Code CLI subscription-login flow regardless of the declared `mode` (oauth vs api-key) — mode is irrelevant for that provider [observed: `src/commands/setup-auth.ts:50-59`].
- A `meta` API-key entry is a manual-key plan: setup-auth points to the Meta AI developer portal and prints the configured `META_API_KEY` export, while doctor uses the same generic provider readiness check as the real review [observed: `src/commands/setup-auth.ts` `planFromAuth` / manual-key guidance; `src/core/auth.ts` `PROVIDER_KEY_ENV`].
- A `xai` oauth entry is a SuperGrok login. setup-auth runs the bundled CLI as `opencode auth login -p xai -m "SuperGrok Subscription"` (`SUPERGROK_LOGIN_ARGS`), with cwd `os.tmpdir()`. OpenCode prints a device code for `https://accounts.x.ai/oauth2/device`. setup-auth then reads `xai.access` from OpenCode's own auth.json and exports that access token. The refresh token stays in the store. A stored token, or one already in the token env, is reused only when a review would take it with no error and no expiry warning. Otherwise setup-auth signs in again, because the review names this command as the fix for both. setup-auth cannot refresh: after the token lapses, it runs the device login again. An xAI api-key entry stays manual and points at `https://console.x.ai` [observed: `src/commands/setup-auth.ts` `planFromAuth`, `accessTokenFromStore`, `superGrokTokenComplaint`].
- The CI seed (`--ci-store`, `--ci-target`) starts a token rotation for a SuperGrok subscription. A 6-hour access token needs a scheduled workflow that refreshes it, and that workflow needs a refresh token that no other client uses. So the seed runs the same device login with `XDG_DATA_HOME` set to a directory made for the call, reads both tokens, and deletes the directory. It sends each value to `gh secret set` through stdin, so no token is on a command line, in an error message, or on the terminal. The refresh token goes to the store repo only and is written first: with it saved, the next rotation repairs an access token write that failed. The developer's own OpenCode sign-in is not read and not changed. A token that a review would refuse is not written, and `gh` access to each repo is checked before the login [observed: `src/commands/setup-auth.ts` `parseCiSeedArgs`, `superGrokLoginInTemporaryStore`, `runCiSeed`; `src/core/ci-secrets.ts`; tests in `src/__tests__/ci-secrets.test.ts`, `src/__tests__/setup-auth.test.ts`]. The rotation workflow itself is not part of `ecr`.
- The two interactive logins run via `spawnSync` with `stdio: "inherit"` and `cwd: os.tmpdir()` — the tmpdir cwd keeps a possibly-untrusted checkout from becoming the login subprocess's working directory, and the `inherit` stdio is why these two calls cannot be converted to `exec.ts`'s capturing `run()` [observed: `src/commands/setup-auth.ts:200-203,256-259`]. The temp dir alone is not enough for OpenCode, which also reads `opencode.json` and `.opencode/` from every parent of its cwd, and the temp dir is the shared `/tmp` on Linux. So the OpenCode logins set `OPENCODE_DISABLE_PROJECT_CONFIG=1` [observed: `src/commands/setup-auth.ts` `opencodeLoginEnv`; the pinned `opencode debug config` loads a parent directory's `opencode.json` without the flag and not with it]. `ecr attach` is interactive too, but it stays inside `exec.ts` via `spawnInherited` because the opened session needs the terminal (see [Session archive](#session-archive)).

## init and dismiss
Expand Down
133 changes: 133 additions & 0 deletions src/__tests__/ci-secrets.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { afterEach, beforeEach, expect, test } from "bun:test";
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path, { delimiter } from "node:path";

import {
assertSecretsReachable,
CI_ACCESS_SECRET,
CI_REFRESH_SECRET,
ciSecretWrites,
oauthPairFromStore,
parseRepoSlug,
writeSecrets,
} from "../core/ci-secrets.js";
import { resetTrustedToolCache } from "../core/exec.js";

// Records each call as "argv | stdin", so a test can prove where a token went.
const FAKE_GH = `#!/bin/sh
case "$*" in
"api repos/"*"/actions/secrets/public-key")
case "$*" in *"$FAKE_GH_UNREACHABLE"*) [ -n "$FAKE_GH_UNREACHABLE" ] && { echo "HTTP 404: Not Found" >&2; exit 1; } ;; esac
printf '%s | \\n' "$*" >> "$FAKE_GH_DIR/calls.log"
printf '{"key_id":"k"}' ;;
"secret set "*)
value=$(cat)
case "$*" in *"$FAKE_GH_FAIL_WRITE"*) [ -n "$FAKE_GH_FAIL_WRITE" ] && { echo "HTTP 403: Resource not accessible" >&2; exit 1; } ;; esac
printf '%s | %s\\n' "$*" "$value" >> "$FAKE_GH_DIR/calls.log" ;;
*) echo "unexpected gh call: $*" >&2; exit 1 ;;
esac
`;

const PAIR = { access: "eyJ.ACCESS-TOKEN.sig", refresh: "REFRESH-TOKEN" };
const REPOS = { store: "expo/code-review-sessions", targets: ["expo/expo"] };

let dir = "";
const saved: Record<string, string | undefined> = {};

async function calls(): Promise<string[]> {
return (await readFile(path.join(dir, "calls.log"), "utf8")).split("\n").filter(Boolean);
}

beforeEach(async () => {
dir = await mkdtemp(path.join(tmpdir(), "ecr-ci-secrets-"));
await writeFile(path.join(dir, "gh"), FAKE_GH, "utf8");
await chmod(path.join(dir, "gh"), 0o755);
await writeFile(path.join(dir, "calls.log"), "", "utf8");
for (const name of ["PATH", "FAKE_GH_DIR", "FAKE_GH_UNREACHABLE", "FAKE_GH_FAIL_WRITE"]) {
saved[name] = process.env[name];
}
process.env.PATH = `${dir}${delimiter}${saved.PATH ?? ""}`;
process.env.FAKE_GH_DIR = dir;
delete process.env.FAKE_GH_UNREACHABLE;
delete process.env.FAKE_GH_FAIL_WRITE;
resetTrustedToolCache();
});

afterEach(async () => {
for (const [name, value] of Object.entries(saved)) {
if (value === undefined) {
delete process.env[name];
} else {
process.env[name] = value;
}
}
resetTrustedToolCache();
await rm(dir, { recursive: true, force: true });
});

test("a repo slug is owner/repo and nothing that gh could read as a flag", () => {
expect(parseRepoSlug("expo/expo")).toBe("expo/expo");
expect(parseRepoSlug("my-org/repo.name_2")).toBe("my-org/repo.name_2");
for (const bad of ["expo", "expo/", "/expo", "a/b/c", "--repo/x", "a b/c", ""]) {
expect(() => parseRepoSlug(bad)).toThrow(/<owner>\/<repo>/);
}
});

test("the token pair needs both halves of an oauth entry", () => {
expect(oauthPairFromStore({ xai: { type: "oauth", ...PAIR } }, "xai")).toEqual(PAIR);
expect(oauthPairFromStore({ xai: { type: "oauth", access: PAIR.access } }, "xai")).toBeNull();
expect(oauthPairFromStore({ xai: { type: "oauth", refresh: PAIR.refresh } }, "xai")).toBeNull();
expect(oauthPairFromStore({ xai: { type: "api", ...PAIR } }, "xai")).toBeNull();
expect(oauthPairFromStore({ openai: { type: "oauth", ...PAIR } }, "xai")).toBeNull();
});

test("the refresh token is written first, and only to the store repo", () => {
expect(ciSecretWrites(PAIR, REPOS)).toEqual([
{ name: CI_REFRESH_SECRET, repo: "expo/code-review-sessions", value: PAIR.refresh },
{ name: CI_ACCESS_SECRET, repo: "expo/code-review-sessions", value: PAIR.access },
{ name: CI_ACCESS_SECRET, repo: "expo/expo", value: PAIR.access },
]);
// A target that repeats, or that is the store, gets one write.
const repeated = ciSecretWrites(PAIR, { store: "a/s", targets: ["a/t", "a/s", "a/t"] });
expect(repeated.map((write) => `${write.name}@${write.repo}`)).toEqual([
`${CI_REFRESH_SECRET}@a/s`,
`${CI_ACCESS_SECRET}@a/s`,
`${CI_ACCESS_SECRET}@a/t`,
]);
});

test("each secret value goes to gh through stdin, never on the command line", async () => {
await writeSecrets(ciSecretWrites(PAIR, REPOS));
expect(await calls()).toEqual([
`secret set ${CI_REFRESH_SECRET} --repo expo/code-review-sessions | ${PAIR.refresh}`,
`secret set ${CI_ACCESS_SECRET} --repo expo/code-review-sessions | ${PAIR.access}`,
`secret set ${CI_ACCESS_SECRET} --repo expo/expo | ${PAIR.access}`,
]);
});

test("a failed write stops the rest and names what is already saved, with no token", async () => {
process.env.FAKE_GH_FAIL_WRITE = "--repo expo/expo";
const error = await writeSecrets(ciSecretWrites(PAIR, REPOS)).catch((caught: Error) => caught);
expect(error).toBeInstanceOf(Error);
const message = (error as Error).message;
expect(message).toContain(`could not write ${CI_ACCESS_SECRET} to expo/expo`);
expect(message).toContain("HTTP 403");
expect(message).toContain(`${CI_REFRESH_SECRET} in expo/code-review-sessions`);
expect(message).not.toContain(PAIR.access);
expect(message).not.toContain(PAIR.refresh);
expect(await calls()).toHaveLength(2);
});

test("an unreachable repo fails before any login or write", async () => {
await assertSecretsReachable(["expo/code-review-sessions", "expo/expo", "expo/expo"]);
expect(await calls()).toEqual([
"api repos/expo/code-review-sessions/actions/secrets/public-key | ",
"api repos/expo/expo/actions/secrets/public-key | ",
]);

process.env.FAKE_GH_UNREACHABLE = "repos/expo/expo/";
await expect(assertSecretsReachable(["expo/code-review-sessions", "expo/expo"])).rejects.toThrow(
/cannot reach the Actions secrets of expo\/expo \(HTTP 404: Not Found\).*Nothing was changed/s,
);
});
120 changes: 120 additions & 0 deletions src/__tests__/setup-auth.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { test, expect } from "bun:test";
import { chmod, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";

import {
parseCiSeedArgs,
superGrokLoginInTemporaryStore,
planFromAuth,
exportLine,
opencodeAuthJsonPath,
Expand Down Expand Up @@ -162,3 +167,118 @@ test("opencode auth.json path honors XDG_DATA_HOME and falls back to ~/.local/sh
);
expect(opencodeAuthJsonPath({})).toContain("/.local/share/opencode/auth.json");
});

test("--ci-store selects the CI seed, and --ci-target may repeat", () => {
expect(parseCiSeedArgs([])).toBeNull();
expect(parseCiSeedArgs(["--yes"])).toBeNull();
expect(parseCiSeedArgs(["--ci-store", "expo/code-review-sessions"])).toEqual({
store: "expo/code-review-sessions",
targets: [],
});
expect(
parseCiSeedArgs([
"--yes",
"--ci-target",
"expo/expo",
"--ci-store",
"expo/code-review-sessions",
"--ci-target",
"expo/eas-cli",
"--ci-target",
"expo/expo",
]),
).toEqual({ store: "expo/code-review-sessions", targets: ["expo/expo", "expo/eas-cli"] });
});

test("a CI seed flag with a missing or bad repository is a usage error", () => {
expect(() => parseCiSeedArgs(["--ci-target", "expo/expo"])).toThrow(/needs --ci-store/);
expect(() => parseCiSeedArgs(["--ci-store"])).toThrow(/--ci-store needs a repository/);
expect(() => parseCiSeedArgs(["--ci-store", "--yes"])).toThrow(/--ci-store needs a repository/);
expect(() => parseCiSeedArgs(["--ci-store", "a/b", "--ci-store", "c/d"])).toThrow(/one time/);
expect(() => parseCiSeedArgs(["--ci-store", "not-a-repo"])).toThrow(/<owner>\/<repo>/);
expect(() => parseCiSeedArgs(["--ci-store", "a/b", "--ci-target", "x"])).toThrow(
/<owner>\/<repo>/,
);
});

// Stands in for `opencode auth login`: records how it was called, then acts on FAKE_OPENCODE_MODE.
const FAKE_OPENCODE = `#!/bin/sh
{
echo "argv=$*"
echo "data=$XDG_DATA_HOME"
echo "project_config_off=$OPENCODE_DISABLE_PROJECT_CONFIG"
} > "$FAKE_OPENCODE_DIR/call.log"
[ "$FAKE_OPENCODE_MODE" = "fail" ] && exit 3
[ "$FAKE_OPENCODE_MODE" = "nothing" ] && exit 0
mkdir -p "$XDG_DATA_HOME/opencode"
if [ "$FAKE_OPENCODE_MODE" = "norefresh" ]; then
printf '{"xai":{"type":"oauth","access":"eyJ.SEED.sig","refresh":"","expires":1}}' > "$XDG_DATA_HOME/opencode/auth.json"
else
printf '{"xai":{"type":"oauth","access":"eyJ.SEED.sig","refresh":"SEED-REFRESH","expires":1}}' > "$XDG_DATA_HOME/opencode/auth.json"
fi
`;

async function withFakeOpencode(
mode: string,
body: (cli: string, callLog: () => Promise<Record<string, string>>) => Promise<void>,
): Promise<void> {
const dir = await mkdtemp(path.join(tmpdir(), "ecr-fake-opencode-"));
const cli = path.join(dir, "opencode");
await writeFile(cli, FAKE_OPENCODE, "utf8");
await chmod(cli, 0o755);
const saved = {
dir: process.env.FAKE_OPENCODE_DIR,
mode: process.env.FAKE_OPENCODE_MODE,
xdg: process.env.XDG_DATA_HOME,
};
process.env.FAKE_OPENCODE_DIR = dir;
process.env.FAKE_OPENCODE_MODE = mode;
try {
await body(cli, async () =>
Object.fromEntries(
(await readFile(path.join(dir, "call.log"), "utf8"))
.split("\n")
.filter(Boolean)
.map((line) => line.split(/=(.*)/s).slice(0, 2) as [string, string]),
),
);
// The login must not move this process to the temporary store.
expect(process.env.XDG_DATA_HOME).toBe(saved.xdg);
} finally {
for (const [name, value] of [
["FAKE_OPENCODE_DIR", saved.dir],
["FAKE_OPENCODE_MODE", saved.mode],
] as const) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
await rm(dir, { recursive: true, force: true });
}
}

test("the CI login runs in a store of its own and deletes that store", async () => {
await withFakeOpencode("ok", async (cli, callLog) => {
expect(await superGrokLoginInTemporaryStore(cli)).toEqual({
access: "eyJ.SEED.sig",
refresh: "SEED-REFRESH",
});
const call = await callLog();
expect(call.argv).toBe("auth login -p xai -m SuperGrok Subscription");
expect(call.project_config_off).toBe("1");
expect(path.basename(call.data!)).toMatch(/^ecr-ci-seed-/);
await expect(stat(call.data!)).rejects.toThrow();
});
});

test("a CI login that fails or stores no token pair changes nothing and leaves no store", async () => {
for (const [mode, message] of [
["fail", /exited with 3; nothing was changed/],
["nothing", /stored no SuperGrok access and refresh token/],
["norefresh", /stored no SuperGrok access and refresh token/],
] as const) {
await withFakeOpencode(mode, async (cli, callLog) => {
await expect(superGrokLoginInTemporaryStore(cli)).rejects.toThrow(message);
await expect(stat((await callLog()).data!)).rejects.toThrow();
});
}
});
2 changes: 1 addition & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Usage:
ecr undismiss --pr <n> <id...> Restore a dismissed finding.
ecr feedback [--repo <owner/repo>] [--limit <n>] Report what humans pushed back on (see \`ecr feedback --help\`).
ecr init [--monorepo] [--scope <dir>] Scaffold .expo-code-review/ in this repo.
ecr setup-auth [--yes] Walk through getting model credentials for local runs.
ecr setup-auth [--yes] Walk through getting model credentials for local runs, or seed CI secrets (see \`ecr setup-auth --help\`).
ecr doctor [--list-scopes] Check environment, config, credentials, and scopes.
ecr verify-config [--expected <env>] [--json] Refuse to run if a config could redirect the credential (CI guard).
ecr ref-check [--root <dir>] [--json] Fail if the review setup cites code that moved or vanished.
Expand Down
Loading
Loading