Skip to content
Merged
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
2 changes: 1 addition & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 10 additions & 2 deletions docs/rotation.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,19 @@ new-value-command | logicsrc teams rotate-keys <team> <project> <env> --key NAME
| `command` | your command prints the new value on stdout | yes, with `--approve` |
| `manual` | a person or agent follows the steps | no |
| `not-secret` | nothing: public config, dropped from the plan | n/a |
| `identifier` | nothing: an OAuth client id (`*_CLIENT_ID`) is registered at the provider, not a secret | never |

Each value can carry its own instructions in an encrypted companion entry,
`__ROTATE__<KEY>`, set with `logicsrc teams rotation-set`. Entries override the
built-in catalog, with one exception: an entry can never make a wallet,
signing or banned-provider key automatic.
built-in catalog, with two exceptions: an entry can never make a wallet,
signing or banned-provider key automatic, and an OAuth client id
(`COINPAY_CLIENT_ID`, `*_OAUTH_CLIENT_ID`, any `*_CLIENT_ID`) is never rotated
at all. A new client id is not a new credential, it is an unregistered client
(`invalid_client`); only the client secret rotates. `rotation-set` refuses an
automatic method for one, the plan reports a stale entry that claims one rotates,
the CoinPay rotators refuse it, and a rotation never writes into a client id that
happens to hold the rotated value under another name (it is named in the result
so the wrong value can be fixed by hand).

Specs can also say `disruptive` (what users notice, such as everyone being
signed out), `never` (never automated), `owner` (`agent` or the account
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@logicsrc/cli",
"version": "0.16.1",
"version": "0.16.2",
"description": "LogicSRC CLI: every LogicSRC standard and tool as one command.",
"type": "module",
"main": "./dist/index.js",
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -918,7 +918,7 @@ teams
.argument("<project>", "Project name")
.argument("<env>", "Environment name")
.argument("<key>", "Secret name the instructions are for")
.option("--method <method>", "random, ssh-keygen, command, or manual")
.option("--method <method>", "random, ssh-keygen, command, manual, or identifier (OAuth client ids: never rotated)")
.option("--json <spec>", "the whole spec as JSON instead of flags")
.option("--format <alphabet>", "random: hex, base64, base64url, alnum (default: like the old value)")
.option("--length <n>", "random: length in characters (default: like the old value, min 32)")
Expand Down
30 changes: 30 additions & 0 deletions packages/cli/src/rotate-flow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,4 +211,34 @@
expect(readFileSync(join(root, "a.com", "app.env"), "utf8")).toBe("RESEND_API_KEY=re_old_xxxxxxxxxxxxxxxx\n");
process.exitCode = 0;
});

it("never writes a rotated key into an OAuth client id holding the same value, nor its rotator state", async () => {
const SAME = "re_old_xxxxxxxxxxxxxxxx";
const team = await makeTeam({ "a--prod": { COINPAY_CLIENT_ID: SAME }, "b--prod": { RESEND_API_KEY: SAME } });
const fetch = (async (_url: any, init: any = {}) =>
(init.method ?? "GET") === "POST"
? new Response(JSON.stringify({ id: "new-id", token: "re_new_yyyyyyyyyyyyyyyy" }), { status: 201 })
: new Response(JSON.stringify({ data: [] }), { status: 200 })) as typeof globalThis.fetch;
const [r] = await teamsRotateKeysAction("t", { keys: ["RESEND_API_KEY"] }, { ...quiet, approve: true }, { ops: ops(), fetch, strayText: () => [], env: {} });
expect(r!.status).toBe("rotated");
expect(r!.written).toEqual(["b--prod:RESEND_API_KEY"]);
expect(r!.note).toMatch(/a--prod:COINPAY_CLIENT_ID/);
expect(await team.read("b--prod", "RESEND_API_KEY")).toBe("re_new_yyyyyyyyyyyyyyyy");
expect(await team.read("a--prod", "COINPAY_CLIENT_ID")).toBe(SAME);
expect(await team.read("a--prod", "__ROTATE__COINPAY_CLIENT_ID")).toBeUndefined();
expect(JSON.parse((await team.read("b--prod", "__ROTATE__RESEND_API_KEY"))!).state).toEqual({ keyId: "new-id" });
});

it("a client id with a stale provider entry is skipped, never minted", async () => {
const team = await makeTeam({
"c--prod": { COINPAY_CLIENT_ID: "cp_live_0123456789abcdef", __ROTATE__COINPAY_CLIENT_ID: JSON.stringify({ method: "provider", provider: "coinpay-api-key" }) }
});
const calls: string[] = [];
const fetch = (async (url: any) => (calls.push(String(url)), new Response("{}", { status: 200 }))) as typeof globalThis.fetch;
const [r] = await teamsRotateKeysAction("t", { keys: ["COINPAY_CLIENT_ID"] }, { ...quiet, approve: true }, { ops: ops(), fetch, strayText: () => [], env: { COINPAY_ROTATE_TOKEN: "s" } });
expect(r!.method).toBe("identifier");
expect(r!.status).toBe("skipped");
expect(calls).toEqual([]);
expect(await team.read("c--prod", "COINPAY_CLIENT_ID")).toBe("cp_live_0123456789abcdef");
});
});
44 changes: 40 additions & 4 deletions packages/cli/src/rotate-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
type PlannedRotation,
type RotationSpec
} from "./rotation-catalog.js";
import { identifierSpec, isIdentifier } from "./rotation-catalog.js";
import { ROTATORS, defaultRun, rewriteUrls, type Minted, type ProviderRotator, type RotatorContext } from "./rotators.js";
import { DesktopError, desktopHost, desktopReport, desktopRotator, type DesktopExec, type DesktopSession } from "./desktop-rotator.js";
import { DESKTOP_RECIPES } from "./desktop-recipes.js";
Expand Down Expand Up @@ -137,6 +138,20 @@ function siblings(team: Loaded, fingerprint: string): Array<{ vault: VaultState;
);
}

/**
* Where a rotation of `key` writes: every vault:key holding the value, except
* OAuth client ids under another name. A client id that holds a secret's value
* is a misconfiguration; overwriting it with a freshly minted key (and then
* recording the rotator's state under the client id's name) is how
* COINPAY_CLIENT_ID came to be "auto-rotated" by the CoinPay API key rotator.
* The plan's own key comes first, so rotator state lands on that key.
*/
export function rotationTargets<T extends { key: string }>(all: T[], key: string): { targets: T[]; skipped: T[] } {
const skipped = all.filter((t) => t.key !== key && isIdentifier(t.key));
const targets = all.filter((t) => !skipped.includes(t));
return { targets: [...targets.filter((t) => t.key === key), ...targets.filter((t) => t.key !== key)], skipped };
}

// ---- plan ------------------------------------------------------------------

export async function teamsRotationAction(slug: string, filter: RotationFilter, options: { format: OutputFormat }): Promise<void> {
Expand Down Expand Up @@ -203,8 +218,18 @@ export function specFromOptions(options: RotationSetOptions): RotationSpec {
);
}

/** OAuth client ids only take instructions that rotate nothing. */
export function checkSpecForKey(key: string, spec: RotationSpec): RotationSpec {
if (!isIdentifier(key)) return spec;
if (spec.method === "identifier" || spec.method === "not-secret") return { ...identifierSpec(), ...spec, method: "identifier", never: true };
if (spec.method === "manual") return { ...spec, never: true };
throw new Error(
`${key} is an OAuth client id: an identifier registered at the provider, not a secret. It cannot rotate by method ${spec.method} (a new value is an unregistered client). Use --method identifier, and rotate the client secret instead.`
);
}

export async function teamsRotationSetAction(slug: string, project: string, env: string, key: string, options: RotationSetOptions): Promise<void> {
const spec = specFromOptions(options);
const spec = checkSpecForKey(key, specFromOptions(options));
const team = await loadTeam(slug);
const name = vaultName(project, env);
const v = team.vaults.find((x) => x.name === name);
Expand Down Expand Up @@ -491,12 +516,16 @@ async function vaultValues(team: Loaded, v: VaultState): Promise<Record<string,
async function rotateTwoPhase(
team: Loaded,
p: PlannedRotation,
targets: Array<{ vault: VaultState; key: string }>,
targetsIn: Array<{ vault: VaultState; key: string }>,
base: RotationResult,
options: RotateKeysOptions,
deps: Required<Pick<RotateDeps, "ops" | "fetch" | "now" | "env">> & { strayText: () => string[]; rotatorFor: (spec: RotationSpec) => ProviderRotator | undefined }
): Promise<RotationResult> {
const spec = p.spec!;
let targets = targetsIn;
if (isIdentifier(p.key)) return { ...base, status: "skipped", error: "an OAuth client id is an identifier, not a secret: never rotated" };
targets = rotationTargets(targets, p.key).targets;
if (!targets.length) return { ...base, status: "skipped", error: "nothing to write" };
const first = targets[0]!;
const oldValue = await readValue(team, first.vault, first.key);
const firstValues = await vaultValues(team, first.vault);
Expand Down Expand Up @@ -666,8 +695,15 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
disruptive: spec?.disruptive,
note: spec?.note
};
const targets = siblings(team, p.fingerprint);
const { targets, skipped } = rotationTargets(siblings(team, p.fingerprint), p.key);
base.vaults = targets.map((t) => `${t.vault.name}:${t.key}`);
const skippedNote = skipped.length ? `not written (OAuth client ids holding this value; fix them by hand): ${skipped.map((t) => `${t.vault.name}:${t.key}`).join(", ")}` : "";
const withSkipped = (r: RotationResult): RotationResult => (skippedNote && !r.note?.includes(skippedNote) ? { ...r, note: [r.note, skippedNote].filter(Boolean).join("; ") } : r);
if (skippedNote) base.note = [base.note, skippedNote].filter(Boolean).join("; ");
if (isIdentifier(p.key) && stdinValue === undefined) {
results.push({ ...base, status: "skipped", error: "an OAuth client id is an identifier, not a secret: never rotated" });
continue;
}
if (stdinValue === undefined && !p.automatic) {
const todo: RotationResult = { ...base, status: "todo", steps: spec?.steps ?? ["No instructions: add some with logicsrc teams rotation-set."] };
// Report-only desktop keys: with --approve and a desktop host, an agent looks the key up (changes nothing).
Expand Down Expand Up @@ -704,7 +740,7 @@ export async function teamsRotateKeysAction(slug: string, filter: RotationFilter
}
try {
if (stdinValue === undefined && (spec?.method === "random" || spec?.method === "provider" || spec?.method === "desktop")) {
const r = await rotateTwoPhase(team, p, targets, base, options, deps);
const r = withSkipped(await rotateTwoPhase(team, p, targets, base, options, deps));
if (r.status === "rotated" || r.status === "rolled-back") live++;
if (r.status === "rotated") r.apps = await resealAppGrants(team, p.fingerprint);
results.push(r);
Expand Down
57 changes: 55 additions & 2 deletions packages/cli/src/rotation-catalog.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { catalogSpec, isAutomatic, isNotSecret, planRotations, baseKeyName, EMPTY_FINGERPRINT } from "./rotation-catalog.js";
import { scheduledBlock } from "./rotate-keys.js";
import { catalogSpec, isAutomatic, isIdentifier, isNotSecret, parseRotationSpec, planRotations, baseKeyName, EMPTY_FINGERPRINT } from "./rotation-catalog.js";
import { checkSpecForKey, rotationTargets, scheduledBlock } from "./rotate-keys.js";

const method = (k: string) => catalogSpec(k)?.method;

Expand Down Expand Up @@ -134,3 +134,56 @@ describe("scheduledBlock", () => {
expect(scheduledBlock(p(catalogSpec("SYSTEM_MNEMONIC_SOL")))).toMatch(/person|never/);
});
});

describe("OAuth client ids are identifiers, never rotated (c0upons invalid_client, 2026-11-22)", () => {
const row = (vault: string, key: string, fingerprint: string) => ({ vault, key, fingerprint, updatedAt: "2026-11-22T00:00:00Z" });

it("classifies every *_CLIENT_ID as an identifier that is never automatic", () => {
for (const k of ["COINPAY_CLIENT_ID", "COINPAY_OAUTH_CLIENT_ID", "GOOGLE_CLIENT_ID", "GITHUB_OAUTH_CLIENT_ID", "CLIENT_ID", "COINPAY_CLIENT_ID__1"]) {
expect(isIdentifier(k)).toBe(true);
const spec = catalogSpec(k);
expect(spec?.method).toBe("identifier");
expect(spec?.never).toBe(true);
expect(isAutomatic(spec)).toBe(false);
expect(spec?.note).toMatch(/not a secret/);
}
for (const k of ["COINPAY_CLIENT_SECRET", "COINPAY_API_KEY", "CLIENT_IDS_URL"]) expect(isIdentifier(k)).toBe(false);
expect(catalogSpec("COINPAY_API_KEY")?.provider).toBe("coinpay-api-key");
expect(isAutomatic(catalogSpec("COINPAY_API_KEY"))).toBe(true);
});

it("a __ROTATE__ entry claiming provider rotation is overridden and reported, not automatic", () => {
const entries = new Map([["c0upons--prod\u0000COINPAY_CLIENT_ID", parseRotationSpec(JSON.stringify({ method: "provider", provider: "coinpay-api-key", family: "coinpay" }))]]);
const plan = planRotations([row("c0upons--prod", "COINPAY_CLIENT_ID", "f1"), row("other--prod", "COINPAY_CLIENT_ID", "f2")], entries);
expect(plan).toHaveLength(1);
expect(plan[0]).toMatchObject({ key: "COINPAY_CLIENT_ID", method: "identifier", automatic: false, source: "entry" });
expect(plan[0]!.spec?.note).toMatch(/is ignored/);
expect(scheduledBlock(plan[0]!)).toBe("needs a person");
});

it("an identifier entry drops the key from the plan again", () => {
const entries = new Map([["a--prod\u0000COINPAY_CLIENT_ID", parseRotationSpec(JSON.stringify({ method: "identifier" }))]]);
expect(planRotations([row("a--prod", "COINPAY_CLIENT_ID", "f1")], entries)).toEqual([]);
});

it("rotation-set refuses an automatic method for a client id", () => {
for (const method of ["random", "provider", "command", "ssh-keygen"]) {
const spec = parseRotationSpec(JSON.stringify({ method, provider: "coinpay-api-key", command: "x" }));
expect(() => checkSpecForKey("COINPAY_CLIENT_ID", spec)).toThrow(/OAuth client id/);
}
expect(checkSpecForKey("COINPAY_CLIENT_ID", { method: "identifier" })).toMatchObject({ method: "identifier", never: true });
expect(checkSpecForKey("COINPAY_CLIENT_ID", { method: "manual", steps: ["x"] })).toMatchObject({ method: "manual", never: true });
expect(checkSpecForKey("COINPAY_API_KEY", { method: "provider", provider: "coinpay-api-key" }).method).toBe("provider");
});

it("a rotation never writes into a client id that shares the value, and the plan's key comes first", () => {
const all = [
{ vault: "a", key: "COINPAY_CLIENT_ID" },
{ vault: "b", key: "COINPAY_API_KEY" },
{ vault: "c", key: "CP_KEY" }
];
const { targets, skipped } = rotationTargets(all, "COINPAY_API_KEY");
expect(targets.map((t) => t.key)).toEqual(["COINPAY_API_KEY", "CP_KEY"]);
expect(skipped.map((t) => t.vault)).toEqual(["a"]);
});
});
Loading
Loading