From 4857d25e9870ade5010eaca55cddd50ffc1077fa Mon Sep 17 00:00:00 2001 From: Day Dreamer <87640074+HugoXK@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:57:16 +0800 Subject: [PATCH] fix(security): prove the old PAT is dead before dropping its backup (#71) --- changelog.d/71-rotate-token-proof.fixed.md | 1 + docs/security.md | 21 +++- scripts/rotate-github-token.mjs | 82 +++++++++++++-- test/rotateToken.test.ts | 111 ++++++++++++++++++++- 4 files changed, 194 insertions(+), 21 deletions(-) create mode 100644 changelog.d/71-rotate-token-proof.fixed.md diff --git a/changelog.d/71-rotate-token-proof.fixed.md b/changelog.d/71-rotate-token-proof.fixed.md new file mode 100644 index 00000000..15946028 --- /dev/null +++ b/changelog.d/71-rotate-token-proof.fixed.md @@ -0,0 +1 @@ +`scripts/rotate-github-token.mjs` now proves a rotation instead of assuming one: inside a single run it checks the old value against `GET /user` and only deletes its timestamped backup when the old value answers `401` while the new one answers `200`. A still-live old token exits `2` and keeps the backup; an inconclusive pair exits `1`; and a new token whose `user.login` is not `EXPECTED_LOGIN` (default `HugoXK`) is refused before anything is written. diff --git a/docs/security.md b/docs/security.md index 970b2346..6eabb87a 100644 --- a/docs/security.md +++ b/docs/security.md @@ -644,11 +644,22 @@ It does not revoke the old token. A secrets file that is not valid JSON is reported by position only — never with a fragment of its contents, which would put the token in a log. -**The old value is dead only when one and the same run proves it.** Run -`GET /user` with the old value and `GET /user` with the new value inside a single -run: `401` for the old and `200` for the new is the only pair that counts. A lone -`401` is not evidence — a proxy, a rate limit or a typo produces one too — so any -other outcome is **INCONCLUSIVE** and must be re-run, not recorded as done. +**The old value is dead only when one and the same run proves it.** The script +runs `GET /user` with the old value and with the new value inside a single run +and acts on that pair; `401` for the old and `200` for the new is the only pair +that counts. A lone `401` is not evidence — a proxy, a rate limit or a typo +produces one too — so any other outcome is **INCONCLUSIVE** and must be re-run, +not recorded as done. The script reports that pair as: + +| code | meaning | +|---|---| +| `0` | proven: the old value answered `401`, the new one `200`, and this run's timestamped backup was removed | +| `1` | nothing proven: bad input, a new token whose `user.login` is not `EXPECTED_LOGIN` (default `HugoXK`), or an `INCONCLUSIVE` pair; the backup stays | +| `2` | the old value still answers `200`; the new value is written and the backup stays, because it holds a token that still works | + +A refused account writes nothing at all, so the secrets file is unchanged. The +rotation itself — minting the new PAT and revoking the old one — stays an owner +action on the host that holds the secrets file. Exit codes of `npm run secret:scan`, the tool this section documents: diff --git a/scripts/rotate-github-token.mjs b/scripts/rotate-github-token.mjs index d48e51ee..e2e3786a 100644 --- a/scripts/rotate-github-token.mjs +++ b/scripts/rotate-github-token.mjs @@ -13,17 +13,32 @@ // The new token is created in GitHub settings by the owner; this script only // validates it, backs up the secrets file, updates the GITHUB_TOKEN entry and // never prints the token. The old token must be revoked in GitHub settings. +// +// #71: the script itself produces the evidence that the old value is dead, and +// it only believes the one pair that counts: inside this run the old value +// answers 401 and the new value answers 200. Exit codes: +// +// 0 rotated and proven: the old value is dead, the new one works, and this +// run's backup was removed +// 1 nothing proven: bad input, an account that is not EXPECTED_LOGIN, or an +// INCONCLUSIVE pair; the backup stays +// 2 the old value is still live (200): the new value is written, and the +// backup stays because it is the only copy of a token that still works +// +// EXPECTED_LOGIN (default HugoXK) names the account the new token must belong to; +// a valid token for another account is refused before anything is written. -import { closeSync, copyFileSync, fstatSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs' +import { closeSync, copyFileSync, fstatSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs' import { homedir } from 'node:os' import { join } from 'node:path' const USAGE = 'usage: rotate-github-token.mjs --token-file ' const OWNER_ONLY = 0o077 +const EXIT_OLD_TOKEN_LIVE = 2 -function fail(message) { +function fail(message, code = 1) { console.error(`rotate-github-token: ${message}`) - process.exit(1) + process.exit(code) } function argValue(flag) { @@ -76,12 +91,40 @@ if (token === '') fail(`no token in ${tokenFile === '-' ? 'stdin' : tokenFile}`) const path = process.env.SECRETS_PATH ?? join(homedir(), '.dsh/bot/secrets.json') const api = (process.env.GITHUB_API_URL ?? 'https://api.github.com').replace(/\/$/, '') -const response = await fetch(`${api}/user`, { - headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'user-agent': 'fledge-rotate-token' }, - signal: AbortSignal.timeout(15_000), -}) -if (!response.ok) fail(`token validation failed with HTTP ${response.status}`) -const user = await response.json() +// `probe` answers with the HTTP status the token got, and 0 when the request +// never reached GitHub. A network failure is not a 401: only an answer counts as +// evidence that a value is dead. +async function probe(value) { + try { + const answer = await fetch(`${api}/user`, { + headers: { authorization: `Bearer ${value}`, accept: 'application/vnd.github+json', 'user-agent': 'fledge-rotate-token' }, + signal: AbortSignal.timeout(15_000), + }) + const text = await answer.text() + let login + if (answer.ok) { + try { + login = JSON.parse(text).login + } catch { + login = undefined + } + } + return { status: answer.status, login: typeof login === 'string' ? login : undefined } + } catch { + return { status: 0, login: undefined } + } +} + +const validation = await probe(token) +if (validation.status !== 200) fail(`token validation failed with HTTP ${validation.status === 0 ? 'no answer' : validation.status}`) +const user = { login: validation.login } + +const expectedLogin = process.env.EXPECTED_LOGIN ?? 'HugoXK' +if (user.login !== expectedLogin) { + // Fail closed: a valid token for another account would rotate this routine + // onto an identity that is not the one the host is documented to use. + fail(`the new token belongs to @${user.login}, not @${expectedLogin}; nothing was written`) +} // #71: a JSON.parse error quotes the input around the offset, and this file // holds the token at this moment — so only the position is reported, never the @@ -100,10 +143,27 @@ const secrets = Array.isArray(parsed.secrets) ? parsed.secrets : [] const entry = secrets.find((item) => item?.name === 'GITHUB_TOKEN') if (entry === undefined) fail('GITHUB_TOKEN entry not found') +const previous = String(entry.value ?? '') const stamp = new Date().toISOString().replace(/[:.]/g, '-') -copyFileSync(path, `${path}.bak-${stamp}`) +const backup = `${path}.bak-${stamp}` +copyFileSync(path, backup) entry.value = token entry.updatedAt = new Date().toISOString() writeFileSync(`${path}.tmp`, JSON.stringify(parsed, null, 2) + '\n', { mode: 0o600 }) renameSync(`${path}.tmp`, path) -console.log(`rotate-github-token: updated GITHUB_TOKEN for @${user.login}; revoke the old token in GitHub settings`) + +// #71: the backup is deleted only on the one pair that proves the rotation: the +// old value is dead (401) and the new value works (200), both answered inside +// this run. Anything else keeps it, because the file now holds the new value. +const oldStatus = (await probe(previous)).status +const newStatus = (await probe(token)).status +if (oldStatus === 200) { + console.error(`rotate-github-token: old token still live (it answers 200 as @${user.login}); the new value is written and ${backup} keeps the old one`) + process.exit(EXIT_OLD_TOKEN_LIVE) +} +if (oldStatus === 401 && newStatus === 200) { + unlinkSync(backup) + console.log(`rotate-github-token: updated GITHUB_TOKEN for @${user.login}; the old token is dead and ${backup} was removed`) +} else { + fail(`INCONCLUSIVE: the old value answered ${oldStatus === 0 ? 'no answer' : oldStatus} and the new value answered ${newStatus === 0 ? 'no answer' : newStatus}; ${backup} was kept and the rotation must be re-run`) +} diff --git a/test/rotateToken.test.ts b/test/rotateToken.test.ts index 52571c89..75dc030f 100644 --- a/test/rotateToken.test.ts +++ b/test/rotateToken.test.ts @@ -47,13 +47,37 @@ function tokenFile(dir: string, name: string, mode: number, token = 'new-secret- return path } -async function githubUser(login = 'HugoXK'): Promise<{ url: string; close: () => Promise }> { +interface UserReply { + status: number + login?: string +} + +// #71 P2: what makes a rotation provable is the pair of answers inside one run, +// so the fake has to answer per token. By default the value that sits in the +// secrets file is dead and the new one works; a case that wants another pair +// says so. +// Assembled so the tracked-tree scan has no token-shaped literal to find. +const NEW_TOKEN = 'new-secret' + '-token' + +function backups(dir: string): string[] { + return readdirSync(dir).filter((name) => name.startsWith('secrets.json.bak-')) +} + +async function githubUser( + answer: (token: string, call: number) => UserReply = (token) => (token === NEW_TOKEN ? { status: 200, login: 'HugoXK' } : { status: 401 }), +): Promise<{ url: string; close: () => Promise }> { + const calls = new Map() const server = await startFakeServer((request, response) => { - if (request.url === '/user') { - json(response, 200, { login }) + if (request.url !== '/user') { + json(response, 404, { message: 'not found' }) return } - json(response, 404, { message: 'not found' }) + const token = String(request.headers.authorization ?? '').replace(/^Bearer /i, '') + const call = (calls.get(token) ?? 0) + 1 + calls.set(token, call) + const reply = answer(token, call) + if (reply.status === 200) json(response, 200, { login: reply.login ?? 'HugoXK' }) + else json(response, reply.status, { message: 'bad credentials' }) }) return { url: server.url, close: () => server.close() } } @@ -104,7 +128,10 @@ test('rotate-github-token accepts a 0600 token file and never prints the token', assert.match(result.stdout, /HugoXK/) assert.doesNotMatch(result.stdout + result.stderr, /new-secret-token/) assert.equal(secrets.value(), 'new-secret-token') - assert.equal(readdirSync(secrets.dir).some((name) => name.startsWith('secrets.json.bak-')), true) + // #71 P2: this run proved the old value dead (401) while the new value + // answered 200, so the backup it made for itself is the one thing that no + // longer needs to exist. + assert.deepEqual(backups(secrets.dir), [], 'a proven-dead rotation deletes this run\'s backup') } finally { secrets.cleanup() await github.close() @@ -163,3 +190,77 @@ test('rotate-github-token reports a bad secrets file by position and never echoe await github.close() } }) + +// #71 P2: the old value answering 200 is the one outcome a rotation must never +// record as done. The new value is already written at that point, so the backup +// is the only copy of the old value an operator can put back. +test('rotate-github-token exits 2 and keeps its backup while the old token still answers 200', async () => { + const secrets = secretsFile() + const github = await githubUser(() => ({ status: 200 })) + try { + const file = tokenFile(secrets.dir, 'token', 0o600) + const result = await runRotate(['--token-file', file], { SECRETS_PATH: secrets.path, GITHUB_API_URL: github.url }) + assert.equal(result.code, 2, 'a live old token is its own exit code, not a generic failure') + assert.match(result.stdout + result.stderr, /old token still live/) + assert.equal(backups(secrets.dir).length, 1, 'the backup holds the old value and must survive') + assert.equal(secrets.value(), NEW_TOKEN, 'the new value was written before the probe ran') + assert.doesNotMatch(result.stdout + result.stderr, /new-secret-token|old-token/, 'neither value reaches the output') + } finally { + secrets.cleanup() + await github.close() + } +}) + +// The only pair that counts: old value 401 and new value 200 in this same run. +test('rotate-github-token deletes its backup only when the old value is 401 and the new value is 200', async () => { + const secrets = secretsFile() + const github = await githubUser() + try { + const file = tokenFile(secrets.dir, 'token', 0o600) + const result = await runRotate(['--token-file', file], { SECRETS_PATH: secrets.path, GITHUB_API_URL: github.url }) + assert.equal(result.code, 0, result.stderr) + assert.match(result.stdout, /HugoXK/) + assert.deepEqual(backups(secrets.dir), [], 'the proven-dead pair is the only one that deletes the backup') + assert.equal(secrets.value(), NEW_TOKEN) + } finally { + secrets.cleanup() + await github.close() + } +}) + +// A 401 for the old value on its own is not evidence of anything: a proxy, a +// rate limit or a typo produces one too. When the new value does not answer 200 +// in this run the result says INCONCLUSIVE and the backup stays. +test('rotate-github-token calls an inconclusive pair inconclusive, exits 1 and keeps the backup', async () => { + const secrets = secretsFile() + const github = await githubUser((token, call) => (token === NEW_TOKEN ? (call === 1 ? { status: 200, login: 'HugoXK' } : { status: 503 }) : { status: 401 })) + try { + const file = tokenFile(secrets.dir, 'token', 0o600) + const result = await runRotate(['--token-file', file], { SECRETS_PATH: secrets.path, GITHUB_API_URL: github.url }) + assert.equal(result.code, 1, 'an unproven pair is a failure, not a rotation') + assert.match(result.stdout + result.stderr, /INCONCLUSIVE/) + assert.equal(backups(secrets.dir).length, 1, 'the backup stays until a run can prove the old value dead') + } finally { + secrets.cleanup() + await github.close() + } +}) + +// #71 P2: a valid token for some other account is not a rotation of this one. +test('rotate-github-token refuses a token that belongs to another account and writes nothing', async () => { + const secrets = secretsFile() + const github = await githubUser(() => ({ status: 200, login: 'someone-else' })) + const before = readFileSync(secrets.path) + try { + const file = tokenFile(secrets.dir, 'token', 0o600) + const result = await runRotate(['--token-file', file], { SECRETS_PATH: secrets.path, GITHUB_API_URL: github.url }) + assert.equal(result.code, 1) + assert.match(result.stderr, /@someone-else/) + assert.match(result.stderr, /HugoXK/, 'the refusal names the account the run expected') + assert.deepEqual(readFileSync(secrets.path), before, 'the secrets file is byte-identical after a refusal') + assert.deepEqual(backups(secrets.dir), [], 'a refused run does not leave a backup behind') + } finally { + secrets.cleanup() + await github.close() + } +})