Skip to content
Open
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
1 change: 1 addition & 0 deletions changelog.d/1236.security.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`npm run rotate:drill` now proves a token rotation instead of assuming one: `--apply` mints a job token and an instance token in a throwaway database, uses both, revokes and replaces them, re-seals a bridge token, and fails unless the old values are refused and the replacements work. Each step writes one `rotation.drill.*` audit row, no token is printed, and the drill refuses production, the configured live database path and any path outside the temporary directory. The default dry run writes nothing.
15 changes: 15 additions & 0 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,21 @@ User model base URLs are validated before saving and before use:
`scripts/rotate-instance-tokens.mjs`; the GitHub development PAT is outside
Fledge and must be rotated in GitHub settings.

### Rotation drill

`npm run rotate:drill` is a dry run: it prints the steps and writes nothing.
With `--apply` it creates a throwaway database under the temporary directory,
mints a job token and an instance token, proves both are accepted, revokes and
replaces them, re-seals a bridge token, and fails unless both old values are
refused and both replacements work. Every step writes one `rotation.drill.*`
audit row; no token value is printed or stored in the row.

The drill refuses `NODE_ENV=production`, the configured `DB_PATH`/`DATA_DIR`, and
any path outside the temporary directory. `--db <path>` is only for a caller
that wants to inspect the throwaway copy; `--keep` keeps the default temporary
directory. `scripts/rotate-instance-tokens.mjs` remains the production rotation;
the drill proves the revocation rule, it does not replace the rotation.

DNS rebinding is not fully mitigated; deploy behind an egress policy if users
are untrusted.

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"db:restore-drill": "node scripts/restore-drill.mjs",
"role:set": "node scripts/set-role.mjs",
"role:set:dev": "tsx scripts/set-role.ts",
"rotate:drill": "tsx scripts/rotation-drill.ts",
"evolution:export": "tsx scripts/evolution-shadow.ts",
"evolution:report": "tsx scripts/evolution-shadow.ts --report",
"db:restore-drill:ci": "node scripts/restore-drill-ci.mjs",
Expand Down
126 changes: 126 additions & 0 deletions scripts/lib/rotationDrill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { tmpdir } from 'node:os'
import { resolve, sep } from 'node:path'
import type { FastifyRequest } from 'fastify'
import type { Store } from '../../src/db.js'
import { authenticateApiToken } from '../../src/lib/apiToken.js'
import { decryptSecret, encryptSecret, randomToken, sha256Hex } from '../../src/lib/secrets.js'

// #1236: a drill, not a rotation. It mints a job token and an instance token
// against a throwaway database, proves both resolve, revokes and replaces them,
// then proves the old values are refused and the new ones work. The "use" step is
// the same `authenticateApiToken` the gateway and the credential endpoint call,
// so the drill exercises the rule that decides 401/403 rather than a copy of it.
export interface RotationDrillInput {
store: Store
userId: string
repoId: string
jobId: string
/** A throwaway TOKEN_ENCRYPTION_KEY; the drill never touches the live one. */
key: string
random?: (bytes?: number) => string
}

export interface RotationDrillResult {
ok: boolean
steps: string[]
reason?: string
}

const GATEWAY_SCOPE = 'gateway' as const

function requestWith(token: string): FastifyRequest {
return { headers: { authorization: `Bearer ${token}` } } as unknown as FastifyRequest
}

function accepted(store: Store, token: string): boolean {
return authenticateApiToken(requestWith(token), store, GATEWAY_SCOPE).kind === 'ok'
}

export function runRotationDrill(input: RotationDrillInput): RotationDrillResult {
const { store, userId, repoId, jobId, key } = input
const random = input.random ?? randomToken
const steps: string[] = []
const audit = (action: string, detail: string): void => {
store.audit(userId, `rotation.drill.${action}`, detail)
}
const mint = (): string => `flg_${random(32)}`
const create = (kind: string, name: string, raw: string): string =>
store.createApiToken({
id: `tok_${random(8)}`,
userId,
kind,
name,
tokenHash: sha256Hex(raw),
prefix: raw.slice(0, 8),
repoId,
scope: GATEWAY_SCOPE,
expiresAt: null,
}).id

const oldJob = mint()
const oldInstance = mint()
const oldJobId = create('job', `job:${jobId}`, oldJob)
const oldInstanceId = create('instance', `flybot:${repoId}`, oldInstance)
audit('minted', `job=${jobId} repo=${repoId}`)
steps.push('minted a job token and an instance token')

if (!accepted(store, oldJob) || !accepted(store, oldInstance)) {
audit('failed', 'an old token was not accepted before rotation')
return { ok: false, steps, reason: 'an old token was not accepted before rotation' }
}
steps.push('accepted both old tokens')

const newJob = mint()
const newInstance = mint()
store.revokeApiToken(oldJobId, userId)
store.revokeApiToken(oldInstanceId, userId)
create('job', `job:${jobId}`, newJob)
create('instance', `flybot:${repoId}`, newInstance)
const bridge = random(32)
if (decryptSecret(encryptSecret(bridge, key), key) !== bridge) {
audit('failed', 'the bridge token did not decrypt after re-sealing')
return { ok: false, steps, reason: 'the bridge token did not decrypt after re-sealing' }
}
audit('rotated', `job=${jobId} repo=${repoId}`)
steps.push('revoked the old tokens, minted replacements and re-sealed the bridge token')

if (accepted(store, oldJob) || accepted(store, oldInstance)) {
audit('failed', 'an old token is still accepted after rotation')
return { ok: false, steps, reason: 'an old token is still accepted after rotation' }
}
if (!accepted(store, newJob) || !accepted(store, newInstance)) {
audit('failed', 'a replacement token was refused')
return { ok: false, steps, reason: 'a replacement token was refused' }
}
steps.push('refused both old tokens and accepted both replacements')
audit('passed', `job=${jobId} repo=${repoId}`)
return { ok: true, steps }
}

// The CLI always uses a fresh temporary directory, but a caller may pass
// `--db`. This guard is the one rule that decides whether a path is safe to
// write: production, the configured live DB/DATA_DIR, or anywhere outside the
// temporary root is refused before the file is opened.
export function drillDbRefusal(input: {
dbPath?: string
env?: NodeJS.ProcessEnv
tempRoot?: string
}): string | null {
const env = input.env ?? process.env
if (env.NODE_ENV === 'production') return 'refusing to run with NODE_ENV=production'
if (input.dbPath === undefined) return null
const target = resolve(input.dbPath)
const root = resolve(input.tempRoot ?? tmpdir())
if (target !== root && !target.startsWith(`${root}${sep}`)) {
return 'refusing a database outside the temporary directory'
}
const live = [env.DB_PATH, env.DATA_DIR]
.filter((value): value is string => typeof value === 'string' && value !== '')
.map((value) => resolve(value))
for (const path of live) {
if (target === path || target.startsWith(`${path}${sep}`)) {
return 'refusing the configured live database path'
}
}
return null
}
111 changes: 111 additions & 0 deletions scripts/rotation-drill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// #1236: prove a token rotation, do not assume one.
//
// npm run rotate:drill # dry run: prints the steps, writes nothing
// npm run rotate:drill -- --apply # mint, use, rotate and verify in a throwaway DB
//
// The drill never opens the live database. Without `--db` it creates a fresh
// temporary directory; `--db` is refused unless it is inside the temporary root
// and is not the configured DB_PATH or DATA_DIR. A production environment is
// refused before the file is opened. No token is printed: the audit rows name
// the job and repository only.

import { randomBytes } from 'node:crypto'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Store } from '../src/db.js'
import { drillDbRefusal, runRotationDrill } from './lib/rotationDrill.js'

function argValue(argv: string[], flag: string): string | undefined {
const index = argv.indexOf(flag)
if (index === -1) return undefined
const value = argv[index + 1]
return value === undefined || value.startsWith('--') ? undefined : value
}

export function main(argv = process.argv.slice(2)): number {
const apply = argv.includes('--apply')
const keep = argv.includes('--keep')
const dbArg = argValue(argv, '--db')

if (!apply) {
console.log('rotation: dry run — pass --apply to mint, rotate and verify in a throwaway database')
console.log('rotation: steps: mint a job token and an instance token; use both; revoke and replace; verify the old ones are refused and the new ones work; audit each step')
return 0
}

const refusal = drillDbRefusal({ dbPath: dbArg })
if (refusal !== null) {
console.error(`rotation: ${refusal}`)
return 2
}

const tempDir = dbArg === undefined ? mkdtempSync(join(tmpdir(), 'fledge-rotation-drill-')) : undefined
const store = new Store(dbArg ?? join(tempDir!, 'drill.db'))
try {
const user = store.upsertGithubUser({
id: 'usr_rotation_drill',
githubId: 0,
login: 'rotation-drill',
name: 'Rotation drill',
email: null,
avatarUrl: null,
isAdmin: false,
initialQuotaCny: 0,
})
store.setUserStatus(user.id, 'approved', 'rotation-drill')
const repo = store.createRepo({
id: 'repo_rotation_drill',
userId: user.id,
owner: 'drill',
name: 'rotation',
defaultBranch: 'main',
tokenEnc: '',
permission: 'admin',
repoRole: 'maintainer',
goal: '',
autoIterate: false,
intervalMinutes: 1440,
})
const job = store.createJob({
id: 'job_rotation_drill',
repoId: repo.id,
userId: user.id,
trigger: 'manual',
goal: 'rotation drill',
callbackHash: 'rotation-drill',
platformTokenHash: '',
})

const result = runRotationDrill({
store,
userId: user.id,
repoId: repo.id,
jobId: job.id,
key: randomBytes(32).toString('base64'),
})
for (const step of result.steps) console.log(`rotation: ${step}`)
const actions = store
.listAudit(20)
.filter((row) => row.action.startsWith('rotation.drill.'))
.map((row) => row.action)
console.log(`rotation: audit ${actions.join(', ')}`)
if (!result.ok) {
console.error(`rotation: drill failed — ${String(result.reason)}`)
return 1
}
console.log('rotation: drill passed')
return 0
} finally {
store.close()
if (tempDir !== undefined) {
if (keep) console.log(`rotation: kept ${tempDir}`)
else rmSync(tempDir, { recursive: true, force: true })
}
}
}

if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
process.exitCode = main()
}
93 changes: 93 additions & 0 deletions test/rotationDrill.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
import { Store } from '../src/db.js'
import { makeUser } from './helpers.js'
import { drillDbRefusal, runRotationDrill } from '../scripts/lib/rotationDrill.js'

function fixture(store: Store) {
const user = makeUser(store, { login: 'rotation-owner', status: 'approved' })
const repo = store.createRepo({
id: 'repo_rotation',
userId: user.id,
owner: 'octo',
name: 'rotation',
defaultBranch: 'main',
tokenEnc: 'x',
permission: 'admin',
repoRole: 'maintainer',
goal: '',
autoIterate: false,
intervalMinutes: 1440,
})
const job = store.createJob({
id: 'job_rotation',
repoId: repo.id,
userId: user.id,
trigger: 'manual',
goal: 'rotation drill',
callbackHash: 'cb_rotation',
platformTokenHash: '',
})
return { userId: user.id, repoId: repo.id, jobId: job.id }
}

function key(): string {
return randomBytes(32).toString('base64')
}

test('the drill refuses an old token and accepts its replacement', () => {
const store = new Store(':memory:')
try {
const ids = fixture(store)
const result = runRotationDrill({ store, ...ids, key: key() })
assert.equal(result.ok, true, result.reason ?? 'the drill failed')
assert.match(result.steps.join('\n'), /refused both old tokens and accepted both replacements/)

const audit = store.listAudit(20)
const actions = audit.map((row) => row.action)
assert.ok(actions.includes('rotation.drill.minted'))
assert.ok(actions.includes('rotation.drill.rotated'))
assert.ok(actions.includes('rotation.drill.passed'))
for (const row of audit) {
assert.doesNotMatch(String(row.detail ?? ''), /flg_/, 'an audit row must not carry a token')
}
} finally {
store.close()
}
})

test('a rotation that leaves an old token live fails and records the failure', () => {
const store = new Store(':memory:')
try {
const ids = fixture(store)
// Simulate a rotation that mints the replacement but never revokes the old
// rows. The drill must notice and must not report a pass.
;(store as unknown as { revokeApiToken: () => void }).revokeApiToken = () => {}
const result = runRotationDrill({ store, ...ids, key: key() })
assert.equal(result.ok, false)
assert.match(String(result.reason), /still accepted/)
const actions = store.listAudit(20).map((row) => row.action)
assert.ok(actions.includes('rotation.drill.failed'))
assert.equal(actions.includes('rotation.drill.passed'), false)
} finally {
store.close()
}
})

test('the drill refuses production, the configured live path and a path outside the temporary root', () => {
assert.match(
String(drillDbRefusal({ dbPath: '/tmp/drill.db', env: { NODE_ENV: 'production' } })),
/NODE_ENV=production/,
)
assert.match(
String(drillDbRefusal({ dbPath: '/tmp/live/drill.db', tempRoot: '/tmp', env: { DATA_DIR: '/tmp/live' } })),
/live database/,
)
assert.match(
String(drillDbRefusal({ dbPath: '/var/lib/fledge.db', tempRoot: '/tmp', env: {} })),
/outside the temporary directory/,
)
assert.equal(drillDbRefusal({ dbPath: '/tmp/fledge-drill/drill.db', tempRoot: '/tmp', env: {} }), null)
assert.equal(drillDbRefusal({ env: {} }), null)
})
Loading