diff --git a/CHANGELOG.md b/CHANGELOG.md index e3de86a2..3c578b40 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,37 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/). ### Added +- **`[context]` can declare the IDENTITY a repo must use, and kit asserts it** (#503). `kit check` + printed `✓ vercel authenticated ` and compared it to nothing, while `kit context check` + asserted only ids read from repo-local files — so a CLI answering as the wrong account was + green. New fields: `vercel.user`, `github.user` (distinct from `github.org`, which is the + remote's owner) and `convex.account`. They behave exactly like `git.email`: declared → asserted, + mismatch → red and non-zero, unreadable → `unknown` rather than a mismatch, since "cannot tell" + and "wrong account" are different findings. + + What the gap cost, measured: a session whose CLI was logged in as a personal account with + read-only rights on the production environment read a FILTERED variable list as a complete one. + `env ls` showed four variables and looked whole (the ones that also existed in preview), the + production-only ones were invisible, and `env pull --environment=production` failed as though + the variable did not exist. Two contradictory conclusions were drawn before a web UI settled it. + + A mismatch now also names the mechanism that scopes an identity to a repo, because a global + login is what produces a wrong one: `vercel -Q ` / `VERCEL_TOKEN`, `gh auth switch`, + `gcloud config configurations activate`, `AWS_PROFILE`, stripe project profiles — and for + convex, that it has **no** profiles (`~/.convex/config.json` is global and `convex login` + overwrites it), so the isolation is `CONVEX_DEPLOY_KEY` / `CONVEX_DEPLOYMENT` per repo. + + And it says the part that turns a wrong identity into wrong conclusions out loud: *anything you + already read as this identity may have been a PARTIAL view — permissions filter listings + silently.* + + `kit context check`'s ready-to-paste block offers the detected identities, hedged (`⚠ the gh + account logged in NOW — VERIFY it is right for THIS repo`), since the live identity is exactly + what the lock exists to question. A value kit could not resolve to a real identity is reported + but never offered as something to declare. + +### Added + - **`kit tools list` — the inventory that did not exist**, and the measurement three surfaces were missing (#500). Per tool: the resolved path, the installer that owns it (classified from the path, never assumed), the installed version, and with `--latest` how far behind it is. diff --git a/docs/COMMANDS.md b/docs/COMMANDS.md index 352ef1b0..072b22bc 100644 --- a/docs/COMMANDS.md +++ b/docs/COMMANDS.md @@ -353,6 +353,7 @@ scope/RoE, so a profile can move to a fresh host without trusting the transport. | `kit ci [--strict] [--attest]` | One-shot CI gate (check + design + tests). Scanner-health gate: a crashed / missing / token-less scanner can no longer exit 0 (default warns); `--strict` / `KIT_CI_STRICT=1` (or `[governance.scan].required_scanners`) hard-fails any non-running scanner. | | `kit context [--format json]` | Print kit context for agent introspection. | | `kit context check [--json] [--require-declaration]` | Verify the live CLI state against `[context]` — each tool's declared (account, project) pair, never inferred from whatever is logged in. With no `[context]` block it prints a ready-to-paste one from the detected state and exits 0; `--require-declaration` makes that absence a **failure** instead, which is what the `context-check` pre-push hook runs — a gate with nothing to compare against is a check that could not run, not a pass. | +| `[context.vercel].user` · `[context.github].user` · `[context.convex].account` | The **identity** each CLI must be logged in as — asserted like `git.email`, not merely reported. A mismatch is red and exits non-zero, and names the per-tool mechanism that scopes an identity to a repo (`vercel -Q`, `gh auth switch`, `gcloud config configurations activate`; convex has none, so `CONVEX_DEPLOY_KEY` per repo). An unreadable identity is `unknown`, never a mismatch. Why it matters: when a command's output depends on the caller's role, a wrong identity returns a filtered subset that looks complete. | | `kit create-plugin ` | Scaffold a new adapter. | | `kit add ` · `kit add --list` | Add service to `.kit.toml`; `--list` prints every available adapter (so does bare `kit add`, which exits 1 as a usage error). | | `kit version` | Print kit version + exit. | diff --git a/src/commands/context.ts b/src/commands/context.ts index 2b33e02f..9b56f654 100644 --- a/src/commands/context.ts +++ b/src/commands/context.ts @@ -86,6 +86,26 @@ async function cmdContextCheck(): Promise { console.log( `\n${c.red}${mismatches.length} mismatch(es) — you are NOT locked to the declared account/project. Do not run outward/destructive commands until this is green.${c.reset}`, ); + // An identity mismatch is not fixed by logging in again — a global login is what produced + // it. Name the per-tool mechanism that scopes an identity to a repo (#503). + const { identityRemediation } = await import("../context-lock.js"); + const seen = new Set(); + for (const f of mismatches) { + if (f.field !== "user" && f.field !== "account") continue; + const hint = identityRemediation(f.tool); + if (hint && !seen.has(hint)) { + seen.add(hint); + console.log(` ${c.dim}${hint}${c.reset}`); + } + } + // A wrong identity does not merely mean "wrong account": the output of everything you ran + // as it may have been a filtered subset, which is how this defect cost two wrong + // conclusions in a row. + if (mismatches.some((f) => f.field === "user" || f.field === "account")) { + console.log( + ` ${c.yellow}Anything you already read as this identity may have been a PARTIAL view — permissions filter listings silently.${c.reset}`, + ); + } } // Mismatch = non-zero exit so this can gate a hook / agent before acting. // Unknown (tool absent / unreadable) does not block. diff --git a/src/config.ts b/src/config.ts index 124ce598..ec38d197 100644 --- a/src/config.ts +++ b/src/config.ts @@ -385,8 +385,17 @@ export interface EnvOverride { */ export interface ContextConfig { gcloud?: { account?: string; project?: string; config?: string; region?: string }; - vercel?: { team?: string; project?: string }; - github?: { org?: string; remote?: string }; + /** + * `user` is the IDENTITY the CLI must be logged in as — declared and asserted like + * `gcloud.account` already was. Reporting an identity without comparing it is how a session + * ran as a personal account with read-only rights on the production environment and read a + * FILTERED variable list as a complete one, with `kit check` green throughout (#503). + */ + vercel?: { team?: string; project?: string; user?: string }; + /** `user` is the logged-in gh account, as distinct from `org` (the remote's owner). */ + github?: { org?: string; remote?: string; user?: string }; + /** Convex has no profiles: `~/.convex/config.json` is global and `convex login` overwrites it. */ + convex?: { account?: string }; gitlab?: { group?: string; remote?: string }; bitbucket?: { workspace?: string; remote?: string }; /** SSH identity this repo must push/deploy with. Declare any of these. */ @@ -815,13 +824,22 @@ export const kitConfigSchema = z .passthrough() .optional(), vercel: z - .object({ team: z.string().optional(), project: z.string().optional() }) + .object({ + team: z.string().optional(), + project: z.string().optional(), + user: z.string().optional(), + }) .passthrough() .optional(), github: z - .object({ org: z.string().optional(), remote: z.string().optional() }) + .object({ + org: z.string().optional(), + remote: z.string().optional(), + user: z.string().optional(), + }) .passthrough() .optional(), + convex: z.object({ account: z.string().optional() }).passthrough().optional(), gitlab: z .object({ group: z.string().optional(), remote: z.string().optional() }) .passthrough() diff --git a/src/context-identity.test.ts b/src/context-identity.test.ts new file mode 100644 index 00000000..3eab1cdf --- /dev/null +++ b/src/context-identity.test.ts @@ -0,0 +1,178 @@ +/** + * Identity is now asserted, not merely printed. + * + * `kit check` reported `✓ vercel authenticated ` and compared it to nothing, while + * `kit context check` asserted only ids from repo-local files. The gap cost real work: a session + * whose CLI was logged in as a personal account with read-only rights on the production + * environment read a FILTERED variable list as a complete one — `env ls` showed four variables + * and looked whole, `env pull --environment=production` failed as if the variable did not exist, + * and two contradictory conclusions were drawn before a web UI settled it (#503). + * + * The tests below pin the three properties that make the fix worth having: a declared identity + * that differs is a MISMATCH (red, non-zero), an identity that cannot be read is UNKNOWN rather + * than a mismatch ("cannot tell" ≠ "wrong account"), and a mismatch tells you the per-tool + * mechanism that scopes an identity to a repo — because "log in again" is what created the + * problem. + */ + +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { + compareContext, + identityRemediation, + normaliseIdentity, + readConvexAccount, + suggestContextToml, + type LiveContext, +} from "./context-lock.js"; + +describe("identity assertion", () => { + it("a declared identity that differs is a mismatch, not a note", () => { + const findings = compareContext( + { vercel: { user: "deploy-bot" }, github: { user: "octocat" } }, + { + vercel: { orgId: null, projectId: null, user: "someones-personal-account" }, + github: { org: null, remote: null, user: "octocat" }, + } as LiveContext, + ); + const vercel = findings.find((f) => f.tool === "vercel" && f.field === "user"); + const github = findings.find((f) => f.tool === "github" && f.field === "user"); + assert.equal(vercel?.status, "mismatch"); + assert.equal(vercel?.expected, "deploy-bot"); + assert.equal(vercel?.actual, "someones-personal-account"); + assert.equal(github?.status, "ok"); + }); + + it("an unreadable identity is unknown — cannot tell is not wrong account", () => { + const findings = compareContext({ vercel: { user: "deploy-bot" } }, { + vercel: { orgId: null, projectId: null, user: null }, + } as LiveContext); + const f = findings.find((x) => x.tool === "vercel" && x.field === "user"); + assert.equal(f?.status, "unknown"); + assert.equal(f?.actual, null); + }); + + it("an undeclared identity is not checked at all", () => { + const findings = compareContext({ vercel: { team: "team_x" } }, { + vercel: { orgId: "team_x", projectId: null, user: "whoever" }, + } as LiveContext); + assert.equal( + findings.some((f) => f.field === "user"), + false, + "nothing declared, nothing asserted", + ); + }); + + it("convex is checked as an account, since it has no profiles to scope", () => { + const findings = compareContext({ convex: { account: "ops@example.test" } }, { + convex: { account: "someone-else@example.test" }, + } as LiveContext); + const f = findings.find((x) => x.tool === "convex"); + assert.equal(f?.status, "mismatch"); + }); +}); + +describe("normaliseIdentity", () => { + it("takes the answer, not the CLI's chatter", () => { + assert.equal(normaliseIdentity("Retrieving scope…\nacme-team\n"), "acme-team"); + assert.equal(normaliseIdentity(" octocat "), "octocat"); + }); + + it("returns null for no answer, an error, or a not-authenticated notice", () => { + assert.equal(normaliseIdentity(null), null); + assert.equal(normaliseIdentity(""), null); + assert.equal(normaliseIdentity("Error: not authenticated"), null); + assert.equal(normaliseIdentity("You are not authenticated. Run login."), null); + }); + + it("refuses an implausibly long line rather than reporting a paragraph as an identity", () => { + assert.equal(normaliseIdentity("x".repeat(300)), null); + }); +}); + +describe("readConvexAccount", () => { + let home = ""; + const withConfig = (body: unknown): string => { + home = mkdtempSync(join(tmpdir(), "kit-convex-")); + mkdirSync(join(home, ".convex"), { recursive: true }); + writeFileSync(join(home, ".convex", "config.json"), JSON.stringify(body)); + return home; + }; + + it("reads the identity out of the global config", () => { + const h = withConfig({ email: "ops@example.test" }); + try { + assert.equal(readConvexAccount(h), "ops@example.test"); + } finally { + rmSync(h, { recursive: true, force: true }); + } + }); + + it("says logged-in-but-unreadable rather than nothing when only a token is present", () => { + const h = withConfig({ accessToken: "secret" }); + try { + const got = readConvexAccount(h); + assert.match(String(got), /logged in/); + assert.doesNotMatch(String(got), /secret/, "never echo the token"); + } finally { + rmSync(h, { recursive: true, force: true }); + } + }); + + it("returns null when there is no config to read", () => { + const h = mkdtempSync(join(tmpdir(), "kit-convex-empty-")); + try { + assert.equal(readConvexAccount(h), null); + } finally { + rmSync(h, { recursive: true, force: true }); + } + }); +}); + +describe("identityRemediation", () => { + it("names the per-tool mechanism, never 'log in again'", () => { + assert.match(String(identityRemediation("vercel")), /-Q|VERCEL_TOKEN/); + assert.match(String(identityRemediation("github")), /gh auth switch/); + assert.match(String(identityRemediation("gcloud")), /configurations activate/); + for (const tool of ["vercel", "github", "gcloud", "aws", "stripe"]) { + assert.doesNotMatch( + String(identityRemediation(tool)), + /^log in again/i, + `${tool}: a global login is what produced the wrong identity`, + ); + } + }); + + it("says outright that convex has no profiles, instead of inventing one", () => { + const hint = String(identityRemediation("convex")); + assert.match(hint, /NO profiles/); + assert.match(hint, /CONVEX_DEPLOY_KEY/); + }); + + it("has nothing to say about a tool with no mechanism", () => { + assert.equal(identityRemediation("jq"), null); + }); +}); + +describe("suggestContextToml", () => { + it("offers the identities it detected, hedged — they are what the lock questions", () => { + const out = suggestContextToml({ + github: { org: "acme", remote: "github.com/acme/x", user: "octocat" }, + vercel: { orgId: "team_1", projectId: "prj_1", user: "octocat" }, + } as LiveContext); + assert.match(out, /user = "octocat"/); + assert.match(out, /VERIFY it is right for THIS repo/); + }); + + it("does not offer a parenthetical note as a value to declare", () => { + const out = suggestContextToml({ + convex: { account: "(logged in, identity not in config)" }, + } as LiveContext); + assert.doesNotMatch(out, /logged in, identity not in config/); + assert.doesNotMatch(out, /\[context\.convex\]/); + }); +}); diff --git a/src/context-lock.ts b/src/context-lock.ts index 280d3cdf..d077f16b 100644 --- a/src/context-lock.ts +++ b/src/context-lock.ts @@ -31,12 +31,13 @@ export interface ContextFinding { export interface LiveContext { gcloud?: { account: string | null; project: string | null }; git?: { email: string | null }; - github?: { org: string | null; remote: string | null }; + github?: { org: string | null; remote: string | null; user?: string | null }; gitlab?: { group: string | null; remote: string | null }; bitbucket?: { workspace: string | null; remote: string | null }; ssh?: { identity: string | null; fingerprint: string | null; host_alias: string | null }; npm?: { registry: string | null }; - vercel?: { orgId: string | null; projectId: string | null }; + vercel?: { orgId: string | null; projectId: string | null; user?: string | null }; + convex?: { account: string | null }; keycloak?: { realm: string | null }; auth0?: { tenant: string | null }; clerk?: { env: string | null }; @@ -88,6 +89,27 @@ const FIELD_SPECS: { declared: (d) => d.github?.remote, live: (l) => l.github?.remote ?? null, }, + { + // The IDENTITY the CLI is logged in as. Declared, therefore asserted — the whole point of + // #503: kit printed `authenticated ` and compared it to nothing, so a session with + // read-only rights on production read a filtered env list as a complete one. + tool: "vercel", + field: "user", + declared: (d) => d.vercel?.user, + live: (l) => l.vercel?.user ?? null, + }, + { + tool: "github", + field: "user", + declared: (d) => d.github?.user, + live: (l) => l.github?.user ?? null, + }, + { + tool: "convex", + field: "account", + declared: (d) => d.convex?.account, + live: (l) => l.convex?.account ?? null, + }, { tool: "gitlab", field: "group", @@ -186,7 +208,9 @@ export function compareContext(declared: ContextConfig, live: LiveContext): Cont export function suggestContextToml(live: LiveContext): string { const out: string[] = []; const emit = (header: string, rows: [string, string | null | undefined, string][]): void => { - const present = rows.filter(([, v]) => v); + // A parenthetical note ("(logged in, identity not in config)") is honest as a LIVE reading + // and useless as a declaration — asserting it would compare a sentence. Report, don't pin. + const present = rows.filter(([, v]) => v && !v.startsWith("(")); if (present.length === 0) return; out.push(header); for (const [k, v, note] of present) { @@ -198,6 +222,13 @@ export function suggestContextToml(live: LiveContext): string { emit("[context.github]", [ ["org", live.github?.org, "from origin remote — authoritative"], ["remote", live.github?.remote, ""], + // Identity is the currently-logged-in account, which is exactly what the lock exists to + // question — hedged, like the ambient gcloud values below (#503). + [ + "user", + live.github?.user, + "⚠ the gh account logged in NOW — VERIFY it is right for THIS repo", + ], ]); emit("[context.gitlab]", [ ["group", live.gitlab?.group, "from origin remote — authoritative"], @@ -210,6 +241,18 @@ export function suggestContextToml(live: LiveContext): string { emit("[context.vercel]", [ ["team", live.vercel?.orgId, "orgId from .vercel/project.json — authoritative"], ["project", live.vercel?.projectId, "projectId"], + [ + "user", + live.vercel?.user, + "⚠ the vercel account logged in NOW — VERIFY it is right for THIS repo", + ], + ]); + emit("[context.convex]", [ + [ + "account", + live.convex?.account, + "⚠ global ~/.convex/config.json — convex has no profiles, so this is machine-wide", + ], ]); emit("[context.gcloud]", [ [ @@ -375,11 +418,23 @@ export async function gatherLive(cwd: string = process.cwd()): Promise`, or VERCEL_TOKEN / `--token` for one command). A global `vercel login` is what makes one identity leak across repos."; + case "github": + return "gh: `gh auth login` stores multiple accounts; `gh auth switch --user ` picks one per shell."; + case "convex": + return "convex has NO profiles — ~/.convex/config.json is global and `convex login` overwrites it. Isolate per repo with CONVEX_DEPLOY_KEY / CONVEX_DEPLOYMENT in the repo's env instead."; + case "gcloud": + return "gcloud: `gcloud config configurations activate ` (or CLOUDSDK_ACTIVE_CONFIG_NAME) scopes account+project per repo."; + case "aws": + return "aws: AWS_PROFILE per repo."; + case "stripe": + return "stripe: `stripe config --list` / project profiles (`--project-name`)."; + default: + return null; + } +} + +/** + * Last non-empty line, trimmed — CLIs print notices before the answer (`vercel whoami` emits a + * "Retrieving…" line, `gh` can print an upgrade notice). Empty or error output becomes null so a + * failed read never reads as an identity. + */ +export function normaliseIdentity(out: string | null): string | null { + if (!out) return null; + const lines = out + .split("\n") + .map((l) => l.trim()) + .filter((l) => l.length > 0 && !/^[>!]|error|not authenticated/i.test(l)); + const last = lines[lines.length - 1]; + return last && last.length <= 200 ? last : null; +} + +/** The Convex account from its global config, or null when there is none to read. */ +export function readConvexAccount(home: string = homedir()): string | null { + for (const rel of [ + [".convex", "config.json"], + [".convex", "auth.json"], + ]) { + try { + const raw = readFileSync(resolve(home, ...rel), "utf8"); + const j = JSON.parse(raw) as { + email?: string; + account?: string; + accessToken?: unknown; + teams?: unknown; + }; + const id = j.email ?? j.account ?? null; + if (typeof id === "string" && id.length > 0) return id; + // A config with a token but no readable identity is still evidence of a login; saying + // "logged in, identity unreadable" beats claiming nothing is there. + if (j.accessToken) return "(logged in, identity not in config)"; + } catch { + /* next candidate */ + } + } + return null; +} + /** * GCP project ids the REPO ITSELF declares (#251). `.firebaserc` is the * deterministic, repo-local source of truth: {"projects": {"default": "x", ...}}.