From 25465b855923fe1b982a3531e36ddfe6d9a4a382 Mon Sep 17 00:00:00 2001 From: ktechmidas <9920871+ktechmidas@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:24:28 +0300 Subject: [PATCH 1/2] feat: API tokens so bots can operate networks without a GitHub sign-in The operator API only accepted a GitHub OAuth session cookie plus a CSRF value, so anything that is not a person in a browser could not queue or confirm an operation. An admin now issues API tokens in Settings (label, role, networks, optional expiry). A token is sent as `Authorization: Bearer dst_...`, needs no cookie, Origin or CSRF value, and is shown once; only its SHA-256 is stored in data/api-tokens.json. A token acts for the admin account that issued it and can only narrow that account's access: the role is the lower of the two and the networks are the overlap. Demoting or removing the account takes its tokens with it on the next request, and the agent keeps re-checking the account exactly as it does for browser requests. Tokens operate networks: reads, and creating, confirming, cancelling and resuming operations their role allows, including devnet lifecycle and Platform resets for admin tokens. They never change settings, access, tokens, remediation controls or CI reporters and never read private devnet keys; those answer 403 and need a signed-in account. A request that presents a token is that token or nothing: an unknown, revoked or expired one is 401 and never falls back to a browser session. Operations record the account and the token id, shown as "via API token" on the operation and in its log. Co-Authored-By: Claude Fable 5.2 --- README.md | 34 ++++++++++ agent/agent.test.js | 23 +++++++ agent/ops.js | 14 ++-- scripts/browser-check.mjs | 23 ++++++- server/api-tokens.js | 76 ++++++++++++++++++++++ server/web.js | 67 ++++++++++++++++---- server/web.test.js | 130 +++++++++++++++++++++++++++++++++++++- shared/settings.js | 17 ++++- shared/shared.test.js | 20 ++++++ src/pages/Operation.jsx | 2 +- src/pages/Operations.jsx | 2 +- src/pages/Settings.jsx | 73 +++++++++++++++++++++ 12 files changed, 457 insertions(+), 24 deletions(-) create mode 100644 server/api-tokens.js diff --git a/README.md b/README.md index 138d72a..aa09ab2 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,40 @@ silence monitoring indefinitely. Manual maintenance/journal gates remain separat Deployment requires both the status web/incident-worker changes and the broker refresh check. Merging this source does not deploy either component. +### API tokens for bots + +A bot operates networks with an API token instead of a GitHub sign-in. An admin +issues one in Settings → **API tokens** (label, role, networks, optional expiry). +The token is shown once; the console keeps only its SHA-256 in +`data/api-tokens.json`. + +```sh +export DASH_STATUS_TOKEN=dst_... # from a secret store, never a script or a log +api() { curl -fsS -H "Authorization: Bearer $DASH_STATUS_TOKEN" -H 'Content-Type: application/json' "$@"; } +api https://status.testnet.networks.dash.org/api/me +id=$(api -X POST https://status.testnet.networks.dash.org/api/networks/devnet-x/ops -d '{"action":"doctor","nodes":[]}' | jq -r .id) +api https://status.testnet.networks.dash.org/api/ops/$id # status, steps, review, log tail +api -X POST https://status.testnet.networks.dash.org/api/ops/$id/confirm -d '{"planId":""}' +``` + +- A token **acts for the admin account that issued it** and can only narrow that + account's access: its role is the lower of the two, its networks the overlap. + Demoting or removing the account takes its tokens with it, on the next request. + The agent re-checks the account, as it does for a browser request. +- Token requests need no cookie, `Origin` or CSRF value. A request that presents a + token is that token or nothing; an unknown, revoked or expired one is `401` and + never falls back to a browser session. +- Tokens operate networks: read granted networks, operations and logs; create, + confirm, cancel and resume operations their role allows (an `admin` token + includes devnet lifecycle and Platform resets). They never change settings, + access, tokens, remediation controls or CI reporters and never read private + devnet keys; those answer `403` and need a signed-in account. +- Operations record the account and the token id (`actor.token`), shown as + "via API token" on the operation and in its log. Issue and revoke are logged by + the web process with the admin's id. `lastUsedAt` is kept to the minute. +- Revoke in Settings. A token that may have leaked is revoked first and replaced + after. + ### Devnet operator keys Connect → **Private devnet keys** is available to operators of that managed diff --git a/agent/agent.test.js b/agent/agent.test.js index 0de9c9b..cb9a472 100644 --- a/agent/agent.test.js +++ b/agent/agent.test.js @@ -235,6 +235,29 @@ test('requests from non-operators are dropped', async () => { assert.equal(existsSync(join(dirs.ops, `${id}.json`)), false); }); +test('a request made through an API token records the token; access is still the account', async () => { + const root = mkdtempSync(join(tmpdir(), 'ops-')); + const dirs = { data: root, private: join(root, 'private'), requests: join(root, 'req'), ops: join(root, 'ops'), work: join(root, 'work'), state: join(root, 'state') }; + const ops = createOps({ settings: () => settings, dirs, key: { path: '/key' }, pool: { knownHosts: () => '', pins: {} }, binary: 'dashnet', log: () => {}, spawnImpl: fakeDashnet([]) }); + const read = (id) => JSON.parse(readFileSync(join(dirs.ops, `${id}.json`), 'utf8')); + const a = '7c8139ad-e92f-40da-943d-1e001efaccb6', b = '7c8139ad-e92f-40da-943d-1e001efaccb7', c = '7c8139ad-e92f-40da-943d-1e001efaccb8'; + const request = (id, network, actor) => writeFileSync(join(dirs.requests, `${id}.json`), JSON.stringify({ type: 'create', id, network, action: 'doctor', nodes: ['seed-1'], actor })); + request(a, 'testnet', { id: 9920871, login: 'ktechmidas', token: '0a1b2c3d', grant: { role: 'admin', networks: ['*'] } }); + // A grant in a request file is never honoured: an unknown account stays unknown. + request(c, 'testnet', { id: 1, login: 'mallory', token: '0a1b2c3d', grant: { role: 'admin', networks: ['*'] } }); + ops.tick(); + assert.deepEqual(read(a).actor, { id: 9920871, login: 'ktechmidas', token: '0a1b2c3d' }); + assert.match(readFileSync(join(dirs.ops, `${a}.log`), 'utf8'), /requested by ktechmidas \(API token 0a1b2c3d\): doctor/); + assert.equal(existsSync(join(dirs.ops, `${c}.json`)), false); + // Anything that is not a token id is dropped from the record. + const root2 = mkdtempSync(join(tmpdir(), 'ops-')); + const dirs2 = { data: root2, private: join(root2, 'private'), requests: join(root2, 'req'), ops: join(root2, 'ops'), work: join(root2, 'work'), state: join(root2, 'state') }; + const ops2 = createOps({ settings: () => settings, dirs: dirs2, key: { path: '/key' }, pool: { knownHosts: () => '', pins: {} }, binary: 'dashnet', log: () => {}, spawnImpl: fakeDashnet([]) }); + writeFileSync(join(dirs2.requests, `${b}.json`), JSON.stringify({ type: 'create', id: b, network: 'testnet', action: 'doctor', nodes: ['seed-1'], actor: { id: 9920871, login: 'ktechmidas', token: '../../etc' } })); + ops2.tick(); + assert.deepEqual(JSON.parse(readFileSync(join(dirs2.ops, `${b}.json`), 'utf8')).actor, { id: 9920871, login: 'ktechmidas' }); +}); + test('devnet requests: admin-only fields, permanent names, placement from settings', async () => { const { validateDevnetRequest, networkYaml, estimate } = await import('./devnets.js'); const s = structuredClone(settings); diff --git a/agent/ops.js b/agent/ops.js index 4ef19b5..ab34033 100644 --- a/agent/ops.js +++ b/agent/ops.js @@ -421,7 +421,9 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh } function handle(s, q) { - const actor = q.actor && Number.isInteger(q.actor.id) ? { id: q.actor.id, login: String(q.actor.login).slice(0, 39) } : null; + // `token` is audit detail only (the API token a bot acted through); access is the account's. + const actor = q.actor && Number.isInteger(q.actor.id) ? { id: q.actor.id, login: String(q.actor.login).slice(0, 39), ...(/^[a-f0-9]{8}$/.test(q.actor.token) ? { token: q.actor.token } : {}) } : null; + const who = actor?.token ? `${actor.login} (API token ${actor.token})` : actor?.login; const lifecycle = LIFECYCLE.has(q.action) || LIFECYCLE.has(load(q.id)?.request?.action); if (!actor || !(lifecycle ? adminFor(s, actor) : operatorFor(s, actor, q.network))) throw new Error(lifecycle ? 'only admins create or delete devnets' : 'actor is not an operator for this network'); if (q.type === 'create') { @@ -431,7 +433,7 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh let r = { id: q.id, network: q.network, actor, createdAt: new Date().toISOString(), request, status: 'queued', steps: [] }; if (existsSync(recordPath(q.id))) throw new Error('duplicate request id'); try { validateRequest(s, request, devnets.registry()); } catch (e) { r = { ...r, status: 'rejected', error: e.message }; } - save(r); write(r.id, `requested by ${actor.login}: ${request.action} ${request.nodes.join(',')} ${request.components.join(',')} ${Object.values(request.images).join(' ')}`); + save(r); write(r.id, `requested by ${who}: ${request.action} ${request.nodes.join(',')} ${request.components.join(',')} ${Object.values(request.images).join(' ')}`); return; } const r = UUID.test(q.id || '') ? load(q.id) : null; @@ -441,16 +443,16 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh if (r.status !== 'review' || q.planId !== r.review?.planId) throw new Error('plan changed or not awaiting review'); if (Date.now() - Date.parse(r.review.preparedAt) > 60 * 60_000) { r.status = 'failed'; r.error = 'review expired after 60 minutes; prepare again'; save(r); return; } r.status = 'confirmed'; r.confirmedBy = actor; r.confirmedAt = new Date().toISOString(); save(r); - write(r.id, `confirmed by ${actor.login}: plan ${r.review.planId}`); + write(r.id, `confirmed by ${who}: plan ${r.review.planId}`); } else if (q.type === 'cancel') { const active = running.get(r.network); const mine = live.get(r.id); if (active?.id === r.id && mine) { // The running copy owns the record: flag it there so the next save keeps it. - mine.cancelRequested = true; save(mine); write(r.id, `cancel requested by ${actor.login}`); + mine.cancelRequested = true; save(mine); write(r.id, `cancel requested by ${who}`); active.child?.kill('SIGTERM'); } else if (['queued', 'review', 'confirmed'].includes(r.status)) { - r.status = 'cancelled'; save(r); write(r.id, `cancelled by ${actor.login}`); + r.status = 'cancelled'; save(r); write(r.id, `cancelled by ${who}`); if (r.request.action === 'devnet-platform') devnets.markPlatformFailed?.(r.network); } } else if (q.type === 'resume') { @@ -461,7 +463,7 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh Object.assign(r, { status: 'queued', steps: [], review: undefined, stages: undefined, anchor: undefined, targets: undefined, execId: `${r.id}.${Date.now()}` }); } else r.status = 'confirmed'; - r.error = undefined; save(r); write(r.id, `resume requested by ${actor.login}`); + r.error = undefined; save(r); write(r.id, `resume requested by ${who}`); } } diff --git a/scripts/browser-check.mjs b/scripts/browser-check.mjs index 890dd7d..3ef17bb 100644 --- a/scripts/browser-check.mjs +++ b/scripts/browser-check.mjs @@ -126,8 +126,9 @@ try { await page.getByPlaceholder('GitHub login, e.g. octocat').fill('octocat'); await page.getByRole('button', { name: 'Look up' }).click(); await page.getByText('The Octocat').waitFor(); - await page.locator('form select').selectOption('viewer'); - await page.locator('form .chip', { hasText: 'devnet-moutai' }).click(); + const accessForm = page.locator('form', { hasText: 'Add a GitHub user' }); + await accessForm.locator('select').selectOption('viewer'); + await accessForm.locator('.chip', { hasText: 'devnet-moutai' }).click(); await page.getByRole('button', { name: 'Add @octocat' }).click(); // Saved on add, with no page-wide Save: a reload keeps the new account. await page.getByText('saved', { exact: true }).waitFor(); @@ -136,7 +137,25 @@ try { await page.getByText('@octocat').waitFor(); const saved = JSON.parse(readFileSync(join(dataDir, 'settings.json'), 'utf8')); assert.deepEqual(saved.operators.find((o) => o.login === 'octocat'), { id: 583231, login: 'octocat', role: 'viewer', networks: ['devnet-moutai'] }); + // API tokens: issued once in Settings, used by a bot with no session, revoked from the table. + const tokenForm = page.locator('form', { hasText: 'Issue a token for a bot' }); + await tokenForm.getByPlaceholder('label, e.g. infraclaw').fill('fixture bot'); + await tokenForm.locator('select').selectOption('admin'); + await tokenForm.getByRole('button', { name: 'Issue token' }).click(); + const apiToken = (await tokenForm.locator('.select-all').innerText()).trim(); + assert.match(apiToken, /^dst_[a-f0-9]{8}_[A-Za-z0-9_-]{43}$/); + const asBot = (path, init = {}) => fetch(origin + path, { ...init, headers: { authorization: `Bearer ${apiToken}`, ...(init.body ? { 'content-type': 'application/json' } : {}) } }); + const botMe = await (await asBot('/api/me')).json(); + assert.deepEqual([botMe.user.login, botMe.admin], ['fixture-operator', true]); + assert.equal((await asBot('/api/tokens')).status, 403, 'a token never manages tokens'); + const tokenRow = page.getByRole('row', { name: /fixture bot/ }); + await tokenRow.waitFor(); await page.screenshot({ path: 'artifacts/settings.png', fullPage: true }); + page.once('dialog', (d) => d.accept()); + await tokenRow.getByRole('button', { name: 'revoke' }).click(); + await page.getByText('No API tokens.').waitFor(); + assert.equal((await asBot('/api/me')).status, 401, 'revoked'); + assert.equal(await page.getByRole('button', { name: 'Save settings' }).isDisabled(), true, 'tokens leave nothing unsaved'); // Infrastructure pages: CI runners (a reporter's push) and the AWS inventory. const { id: reporter } = app.ci.addReporter('mac-runner-fixture'); diff --git a/server/api-tokens.js b/server/api-tokens.js new file mode 100644 index 0000000..52e1ce2 --- /dev/null +++ b/server/api-tokens.js @@ -0,0 +1,76 @@ +// API tokens: network operations for bots, without a browser session. +// +// data/api-tokens.json token id -> { label, hash (sha256 of the token), owner { id, login }, +// role, networks, createdAt, expiresAt, lastUsedAt } +// +// A token acts for the admin account that issued it and can only narrow that +// account's access (shared/settings.js accessFor): removing or demoting the +// account takes its tokens with it. Only the hash is stored; the token itself is +// shown once, when issued. Tokens operate networks. They never manage access, +// settings or other tokens and never read private keys (server/web.js). +import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; +import { join } from 'node:path'; +import { ROLES, readJSON, writeAtomic } from '../shared/settings.js'; + +const LABEL = /^[A-Za-z0-9][A-Za-z0-9 ._-]{0,39}$/; +const NETWORK = /^[a-z][a-z0-9-]{0,62}$/; +const BEARER = /^Bearer (dst_([a-f0-9]{8})_[A-Za-z0-9_-]{43})$/; +const MAX_TOKENS = 50; +const USED_EVERY_MS = 60_000; +const sha256 = (s) => createHash('sha256').update(s).digest('hex'); + +// True for any request that presents an API token, valid or not. +export const presentsApiToken = (header) => /^Bearer dst_/.test(header || ''); + +export function createApiTokens({ dataDir, clock = Date.now }) { + const path = join(dataDir, 'api-tokens.json'); + const all = () => readJSON(path, {}); + const save = (tokens) => writeAtomic(path, JSON.stringify(tokens, null, 1), 0o600); + const view = ([id, t]) => ({ id, label: t.label, owner: t.owner, role: t.role, networks: t.networks, createdAt: t.createdAt, expiresAt: t.expiresAt || null, lastUsedAt: t.lastUsedAt || null }); + + function issue(owner, { label, role, networks, expiresDays } = {}) { + if (!Number.isInteger(owner?.id) || typeof owner.login !== 'string') throw new Error('a token needs the account that issues it'); + if (typeof label !== 'string' || !LABEL.test(label.trim())) throw new Error('label: 1-40 letters, digits, spaces and . _ -'); + if (!ROLES.includes(role)) throw new Error(`role must be ${ROLES.join(', ')}`); + const nets = role === 'admin' ? ['*'] : networks; + if (!Array.isArray(nets) || !nets.length || nets.length > 40 || !nets.every((n) => n === '*' || (typeof n === 'string' && NETWORK.test(n)))) throw new Error('grant at least one network'); + if (expiresDays != null && (!Number.isInteger(expiresDays) || expiresDays < 1 || expiresDays > 365)) throw new Error('expiry must be 1 to 365 days, or empty for none'); + const tokens = all(); + if (Object.keys(tokens).length >= MAX_TOKENS) throw new Error(`at most ${MAX_TOKENS} tokens; revoke one first`); + let id; + do id = randomBytes(4).toString('hex'); while (Object.hasOwn(tokens, id)); + const token = `dst_${id}_${randomBytes(32).toString('base64url')}`; + const now = clock(); + tokens[id] = { label: label.trim(), hash: sha256(token), owner: { id: owner.id, login: owner.login }, role, networks: [...new Set(nets)], createdAt: new Date(now).toISOString(), + ...(expiresDays ? { expiresAt: new Date(now + expiresDays * 86400_000).toISOString() } : {}) }; + save(tokens); + return { ...view([id, tokens[id]]), token }; + } + + function revoke(id) { + const tokens = all(); + if (!Object.hasOwn(tokens, id)) throw new Error('no such token'); + delete tokens[id]; + save(tokens); + } + + // The token's own record, or null. Whether its owner still has access is + // decided per request against the current settings, not here. + function authenticate(header) { + const m = BEARER.exec(header || ''); + if (!m) return null; + const tokens = all(); + const t = Object.hasOwn(tokens, m[2]) ? tokens[m[2]] : null; + const want = Buffer.from(String(t?.hash || ''), 'hex'), got = Buffer.from(sha256(m[1]), 'hex'); + if (want.length !== got.length || !timingSafeEqual(want, got)) return null; + const now = clock(); + if (t.expiresAt && Date.parse(t.expiresAt) <= now) return null; + if (!(now - Date.parse(t.lastUsedAt) < USED_EVERY_MS)) { + // Best effort: a read-only data directory must not turn a valid token away. + try { t.lastUsedAt = new Date(now).toISOString(); save(tokens); } catch { /* keep serving */ } + } + return view([m[2], t]); + } + + return { issue, revoke, authenticate, list: () => Object.entries(all()).map(view).sort((a, b) => a.createdAt.localeCompare(b.createdAt)) }; +} diff --git a/server/web.js b/server/web.js index e1f088a..ce07754 100644 --- a/server/web.js +++ b/server/web.js @@ -22,6 +22,7 @@ import { COMPONENTS, COMPONENT_REPOS, accessFor, adminFor, loadSettings, memberO import { expectations } from '../shared/monitoring.js'; import { evaluateNetwork, projectNetwork } from '../shared/evaluate.js'; import { requestDevnetKeys } from './devnet-keys.js'; +import { createApiTokens, presentsApiToken } from './api-tokens.js'; import { devnetFiles } from '../shared/devnet-files.js'; import { validateRequest } from '../agent/ops.js'; import { validateMainnetReport } from '../shared/mainnet.js'; @@ -53,6 +54,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl const reloadSettings = () => { settings = loadSettings(settingsPath); return settings; }; const app = express(); const auth = createAuth({ origin }, { store: join(dataDir, 'sessions.json'), ...authDeps }); + const tokens = createApiTokens({ dataDir, clock }); const clients = new Set(); const cache = new Map(); // Each module reads the other only when a request is served, so ci gets a late-bound runningJobs. @@ -108,6 +110,17 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl app.use(express.json({ limit: '64kb' })); app.use('/api', (req, res, next) => { res.set('Cache-Control', 'no-store'); next(); }); auth.install(app); + // Bots authenticate with an API token instead of a browser session. A request + // that presents one is that token or nothing: it never falls back to a cookie. + app.use('/api', (req, res, next) => { + if (!presentsApiToken(req.get('authorization'))) return next(); + const t = tokens.authenticate(req.get('authorization')); + const bot = t && { token: t.id, user: { id: t.owner.id, login: t.owner.login, token: t.id, grant: { role: t.role, networks: t.networks } } }; + // Checked against the settings on disk: a revoked account loses its tokens at once. + if (!bot || !accessFor(reloadSettings(), bot.user)) return res.status(401).json({ error: 'API token unknown, revoked or expired' }); + req.bot = bot; + next(); + }); // The limited Mainnet board is fed by a separately managed observer/fullnode // (not the existing mainnet-support fleet). Keep this write path token-only, @@ -124,7 +137,19 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl } catch (e) { res.status(400).json({ error: e.message }); } }); - const user = (req) => auth.session(req)?.user || null; + // Who is asking: an API token (req.bot) or the signed-in browser session. + const principal = (req) => req.bot || auth.session(req); + const user = (req) => principal(req)?.user || null; + // What is recorded and shown: the account, and the token it acted through. + const identity = (u) => (u ? { id: u.id, login: u.login, ...(u.token ? { token: u.token } : {}) } : null); + // CSRF protects cookies. A bearer token is not sent by a browser on its own. + const csrf = (req, res, next) => (req.bot ? next() : auth.csrf(req, res, next)); + const signedIn = (req, res, next) => { + if (req.bot) return res.status(403).json({ error: 'This needs a signed-in account; API tokens operate networks only' }); + const s = auth.session(req); + if (!s) return res.status(401).json({ error: 'Sign in required' }); + req.session = s; next(); + }; const isOperator = (req, network) => operatorFor(settings, user(req), network); const isMember = (req, network) => memberOf(settings, user(req), network); const isAdmin = (req) => adminFor(settings, user(req)); @@ -168,7 +193,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl const a = accessFor(settings, u); // allNetworks: access covers every network, including ones created after this // session loaded (a devnet being created is not yet in the network list). - res.json({ user: u, role: a?.role || null, allNetworks: !!a?.networks.includes('*'), operatorOf: u ? settings.networks.filter((n) => isOperator(req, n.name)).map((n) => n.name) : [], + res.json({ user: identity(u), role: a?.role || null, allNetworks: !!a?.networks.includes('*'), operatorOf: u ? settings.networks.filter((n) => isOperator(req, n.name)).map((n) => n.name) : [], memberOf: u ? settings.networks.filter((n) => isMember(req, n.name)).map((n) => n.name) : [], admin: isAdmin(req) }); }); app.get('/api/overview', (req, res) => { @@ -245,7 +270,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl // Operator API. const requireAccess = (check, message) => (req, res, next) => { - const s = auth.session(req); + const s = principal(req); if (!s) return res.status(401).json({ error: 'Sign in required' }); req.session = s; const network = req.params.name || readJSON(join(dirs.ops, `${req.params.id}.json`))?.network; @@ -288,7 +313,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl app.post('/api/networks/:name/keys', (req, res, next) => { try { validateSettings(JSON.parse(readFileSync(settingsPath, 'utf8'))); reloadSettings(); next(); } catch { res.status(503).json({ error: 'Key access settings unavailable' }); } - }, requireOperator, auth.csrf, + }, signedIn, requireOperator, auth.csrf, rateLimit({ windowMs: 60_000, limit: 6, standardHeaders: true, legacyHeaders: false }), async (req, res) => { const n = settings.networks.find(x => x.name === req.params.name); if (!n || n.kind !== 'dashnet' || n.chainType !== 'devnet' || !/^devnet-[a-z0-9-]+$/.test(n.name)) return res.status(404).json({ error: 'Keys are available for managed devnets only' }); @@ -301,7 +326,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl return res.json(result); } catch { return res.status(503).json({ error: 'Keys unavailable: the devnet must be idle and all node identities must verify' }); } }); - app.post('/api/networks/:name/ops', requireOperator, auth.csrf, (req, res) => { + app.post('/api/networks/:name/ops', requireOperator, csrf, (req, res) => { const n = settings.networks.find((x) => x.name === req.params.name); if (!n) return res.status(404).json({ error: 'Network not found' }); const body = req.body || {}; @@ -310,7 +335,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl try { validateRequest(settings, q, registry()); } catch (e) { return res.status(400).json({ error: e.message }); } const busy = listOps(n.name).find((r) => ['queued', 'preparing', 'confirmed', 'running'].includes(r.status)); if (busy) return res.status(409).json({ error: `operation ${busy.id.slice(0, 8)} (${busy.request.action}) is ${busy.status} on this network`, id: busy.id }); - request({ type: 'create', ...q, actor: req.session.user }); + request({ type: 'create', ...q, actor: identity(req.session.user) }); res.status(202).json({ id: q.id }); }); // New devnets (admins; billable). The agent prepares a plan that must be confirmed. @@ -318,13 +343,13 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl if (!isAdmin(req)) return res.status(403).json({ error: 'Only admins create devnets' }); res.json({ defaults: reloadSettings().devnets, existing: [...settings.networks.map((n) => n.name), ...Object.entries(registry()).filter(([, reg]) => reg?.status !== 'deleted').map(([name]) => name)] }); }); - app.post('/api/devnets', (req, res, next) => { const s = auth.session(req); if (!s) return res.status(401).json({ error: 'Sign in required' }); req.session = s; next(); }, auth.csrf, (req, res) => { + app.post('/api/devnets', (req, res, next) => { const s = principal(req); if (!s) return res.status(401).json({ error: 'Sign in required' }); req.session = s; next(); }, csrf, (req, res) => { if (!isAdmin(req)) return res.status(403).json({ error: 'Only admins create devnets' }); const body = req.body || {}; const q = { id: randomUUID(), network: body.name, action: 'create-devnet', nodes: [], devnet: body.devnet || {} }; try { validateRequest(reloadSettings(), q, registry()); } catch (e) { return res.status(400).json({ error: e.message }); } if (listOps(q.network).some((r) => !['failed', 'cancelled', 'rejected', 'succeeded'].includes(r.status))) return res.status(409).json({ error: 'an operation for this name is already active' }); - request({ type: 'create', ...q, actor: req.session.user }); + request({ type: 'create', ...q, actor: identity(req.session.user) }); res.status(202).json({ id: q.id, network: q.network }); }); @@ -356,12 +381,12 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl req.on('close', () => clearInterval(timer)); }); for (const type of ['confirm', 'cancel', 'resume']) { - app.post(`/api/ops/:id/${type}`, requireOperator, auth.csrf, (req, res) => { + app.post(`/api/ops/:id/${type}`, requireOperator, csrf, (req, res) => { if (!UUID.test(req.params.id)) return res.status(400).json({ error: 'invalid id' }); const r = readJSON(join(dirs.ops, `${req.params.id}.json`)); if (type === 'confirm' && (r?.status !== 'review' || req.body?.planId !== r.review?.planId)) return res.status(409).json({ error: 'The plan changed or is not awaiting review' }); if (LIFECYCLE_ACTIONS.includes(r?.request?.action) && !isAdmin(req)) return res.status(403).json({ error: 'Only admins confirm, cancel or resume devnet lifecycle and Platform resets' }); - request({ type, id: req.params.id, network: req.network, planId: req.body?.planId, actor: req.session.user }); + request({ type, id: req.params.id, network: req.network, planId: req.body?.planId, actor: identity(req.session.user) }); res.status(202).json({ ok: true }); }); } @@ -373,7 +398,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl // Non-admins see only the networks they were granted. res.json({ settings: isAdmin(req) ? s : { ...s, networks: s.networks.filter((n) => memberOf(s, user(req), n.name)) }, admin: isAdmin(req) }); }); - app.put('/api/settings', (req, res, next) => { const s = auth.session(req); if (!s) return res.status(401).json({ error: 'Sign in required' }); req.session = s; next(); }, auth.csrf, (req, res) => { + app.put('/api/settings', signedIn, auth.csrf, (req, res) => { if (!isAdmin(req)) return res.status(403).json({ error: 'Only admins can change settings' }); try { // Access has its own endpoints; a page-wide save never carries a stale @@ -387,7 +412,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl // Access changes save immediately (no page-wide Save). Each call edits the // current file, never a stale browser copy of the whole settings document. - const adminWrite = [(req, res, next) => { const s = auth.session(req); if (!s) return res.status(401).json({ error: 'Sign in required' }); req.session = s; next(); }, auth.csrf, + const adminWrite = [signedIn, auth.csrf, (req, res, next) => (isAdmin(req) ? next() : res.status(403).json({ error: 'Only admins can change access' }))]; const changeAccess = (req, res, fn) => { try { @@ -413,6 +438,24 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl next.operators = next.operators.filter((o) => o.id !== id); })); + // API tokens for bots: issued and revoked by signed-in admins, never by a + // token. The token is in the response to its creation and nowhere afterwards. + app.get('/api/tokens', signedIn, (req, res) => (isAdmin(req) ? res.json({ tokens: tokens.list() }) : res.status(403).json({ error: 'Only admins manage API tokens' }))); + app.post('/api/tokens', ...adminWrite, (req, res) => { + try { + const issued = tokens.issue(req.session.user, req.body || {}); + console.info(JSON.stringify({ event: 'api-token-issued', token: issued.id, role: issued.role, networks: issued.networks, actorId: req.session.user.id, at: new Date(clock()).toISOString() })); + res.status(201).set('Cache-Control', 'private, no-store').json(issued); + } catch (e) { res.status(400).json({ error: e.message }); } + }); + app.delete('/api/tokens/:id', ...adminWrite, (req, res) => { + try { + tokens.revoke(req.params.id); + console.info(JSON.stringify({ event: 'api-token-revoked', token: req.params.id, actorId: req.session.user.id, at: new Date(clock()).toISOString() })); + res.json({ tokens: tokens.list() }); + } catch (e) { res.status(404).json({ error: e.message }); } + }); + // Remediation controls: administrators only. They record the request; the // incident sidecar forwards it on its next signed heartbeat and the board // shows it as pending until the receiver acknowledges it. A command is diff --git a/server/web.test.js b/server/web.test.js index ccbd29a..8019883 100644 --- a/server/web.test.js +++ b/server/web.test.js @@ -33,7 +33,7 @@ async function start(userId = 9920871, extraUsers = [], options = {}) { await req(`/api/auth/callback?state=${state}&code=x`); return (await (await req('/api/session')).json()).csrf; }; - return { dataDir, req, login, cookie: () => cookie, close: () => { app.close(); server.close(); } }; + return { dataDir, base, req, login, cookie: () => cookie, close: () => { app.close(); server.close(); } }; } test('public board needs no session and hides operator fields', async () => { @@ -492,3 +492,131 @@ test('public projection cache keeps its 15 s lifetime and evicts expired keys on cached.delete('ci'); assert.equal(cached('ci', () => ++calls), 7); }); + +// A bot: no cookie jar, no Origin header, only the bearer token. +const bot = (w, token) => (path, opts = {}) => fetch(w.base + path, { ...opts, headers: { ...(opts.body ? { 'content-type': 'application/json' } : {}), ...(token ? { authorization: `Bearer ${token}` } : {}), ...(opts.headers || {}) } }); +const issueToken = async (w, csrf, body) => { + const r = await w.req('/api/tokens', { method: 'POST', body: JSON.stringify(body), headers: { 'content-type': 'application/json', 'x-csrf-token': csrf } }); + return { status: r.status, ...(await r.json()) }; +}; + +test('API tokens: an admin issues one; a bot queues and confirms operations with it, without a session or CSRF', async () => { + const w = await start(); + try { + assert.equal((await w.req('/api/tokens')).status, 401, 'signed out'); + const csrf = await w.login(); + assert.equal((await w.req('/api/tokens', { method: 'POST', body: JSON.stringify({ label: 'infraclaw', role: 'admin' }), headers: { 'content-type': 'application/json' } })).status, 403, 'CSRF required to issue'); + assert.equal((await issueToken(w, csrf, { label: '', role: 'admin' })).status, 400); + assert.equal((await issueToken(w, csrf, { label: 'x', role: 'root' })).status, 400); + assert.equal((await issueToken(w, csrf, { label: 'x', role: 'operator', networks: [] })).status, 400); + assert.equal((await issueToken(w, csrf, { label: 'x', role: 'operator', networks: ['testnet'], expiresDays: 0 })).status, 400); + const issued = await issueToken(w, csrf, { label: 'infraclaw', role: 'admin', networks: ['testnet'] }); + assert.equal(issued.status, 201); + assert.match(issued.token, /^dst_[a-f0-9]{8}_[A-Za-z0-9_-]{43}$/); + assert.deepEqual([issued.role, issued.networks, issued.owner], ['admin', ['*'], { id: 9920871, login: 'someone' }]); + // Only the hash is kept, and the list never returns the token. + const stored = readFileSync(join(w.dataDir, 'api-tokens.json'), 'utf8'); + assert.ok(!stored.includes(issued.token) && !stored.includes(issued.token.split('_')[2])); + const listed = await (await w.req('/api/tokens')).json(); + assert.deepEqual(listed.tokens.map((t) => [t.id, t.label, t.token]), [[issued.id, 'infraclaw', undefined]]); + + const call = bot(w, issued.token); + const me = await (await call('/api/me')).json(); + assert.deepEqual(me.user, { id: 9920871, login: 'someone', token: issued.id }); + assert.deepEqual([me.role, me.admin, me.allNetworks], ['admin', true, true]); + assert.equal((await (await call('/api/networks/testnet')).json()).hosts[0].instanceId, 'i-0eb19958115adb5d0', 'member detail'); + const body = JSON.stringify({ action: 'upgrade', nodes: ['seed-2'], components: ['tenderdash'], images: { tenderdash: 'dashpay/tenderdash:1.8.2' } }); + assert.equal((await bot(w)('/api/networks/testnet/ops', { method: 'POST', body })).status, 401, 'no token, no session'); + const queued = await call('/api/networks/testnet/ops', { method: 'POST', body }); + assert.equal(queued.status, 202); + const { id } = await queued.json(); + const q = JSON.parse(readFileSync(join(w.dataDir, 'requests', `${id}.json`), 'utf8')); + assert.deepEqual(q.actor, { id: 9920871, login: 'someone', token: issued.id }, 'the account, and the token it acted through; never the grant'); + // Review, then confirm with the plan id, as the console does. + mkdirSync(join(w.dataDir, 'ops'), { recursive: true }); + writeFileSync(join(w.dataDir, 'ops', `${id}.json`), JSON.stringify({ id, network: 'testnet', status: 'review', review: { planId: 'plan-1' }, request: { action: 'upgrade' }, createdAt: new Date().toISOString() })); + assert.equal((await (await call(`/api/ops/${id}`)).json()).status, 'review'); + assert.equal((await call(`/api/ops/${id}/confirm`, { method: 'POST', body: JSON.stringify({ planId: 'stale' }) })).status, 409); + assert.equal((await call(`/api/ops/${id}/confirm`, { method: 'POST', body: JSON.stringify({ planId: 'plan-1' }) })).status, 202); + const confirm = readdirSync(join(w.dataDir, 'requests')).find((f) => f.startsWith(`${id}.confirm-`)); + assert.deepEqual(JSON.parse(readFileSync(join(w.dataDir, 'requests', confirm), 'utf8')).actor, { id: 9920871, login: 'someone', token: issued.id }); + assert.ok((await (await w.req('/api/tokens')).json()).tokens[0].lastUsedAt, 'use is recorded'); + + // A presented token is that token or nothing: a wrong one never falls back to the browser session. + const wrong = `${issued.token.slice(0, -1)}${issued.token.endsWith('A') ? 'B' : 'A'}`; + assert.equal((await w.req('/api/me', { headers: { authorization: `Bearer ${wrong}` } })).status, 401); + assert.equal((await bot(w, 'dst_nope')('/api/overview')).status, 401); + // Revoked: dead at once. + assert.equal((await w.req('/api/tokens/ffffffff', { method: 'DELETE', headers: { 'x-csrf-token': csrf } })).status, 404); + assert.equal((await w.req(`/api/tokens/${issued.id}`, { method: 'DELETE', headers: { 'x-csrf-token': csrf } })).status, 200); + assert.equal((await call('/api/me')).status, 401); + assert.equal((await call('/api/networks/testnet/ops', { method: 'POST', body })).status, 401); + } finally { w.close(); } +}); + +test('API tokens operate networks only: no settings, access, tokens, remediation or private keys', async () => { + const w = await start(); + try { + const csrf = await w.login(); + writeFileSync(join(w.dataDir, 'devnets.json'), JSON.stringify({ 'devnet-palmatum': { status: 'ready', coreNetwork: 'palmatum-g1' } })); + const { token } = await issueToken(w, csrf, { label: 'admin bot', role: 'admin' }); + const call = bot(w, token); + const { settings } = await (await call('/api/settings')).json(); + assert.ok(settings.networks.length, 'settings are readable'); + const refused = [ + ['PUT', '/api/settings', { settings }], ['PUT', '/api/access/583231', { login: 'octocat', role: 'admin' }], ['DELETE', '/api/access/9920871'], + ['GET', '/api/tokens'], ['POST', '/api/tokens', { label: 'more', role: 'admin' }], ['DELETE', '/api/tokens/00000000'], + ['POST', '/api/remediation/dispatch', { enabled: true }], ['POST', '/api/remediation/clear'], ['POST', '/api/ci/reporters', { label: 'h' }], + ['POST', '/api/networks/devnet-palmatum/keys'], + ]; + for (const [method, path, body] of refused) { + // Even with the admin's own cookie and CSRF value attached, a token request stays a token request. + const r = await w.req(path, { method, ...(body ? { body: JSON.stringify(body) } : {}), headers: { 'content-type': 'application/json', authorization: `Bearer ${token}`, 'x-csrf-token': csrf } }); + assert.equal(r.status, 403, `${method} ${path}`); + assert.match((await r.json()).error, /signed-in account/, `${method} ${path}`); + } + assert.equal(Object.keys(JSON.parse(readFileSync(join(w.dataDir, 'api-tokens.json'), 'utf8'))).length, 1); + assert.equal((await call('/api/auth/logout', { method: 'POST' })).status, 401); + // Admin tokens do manage devnet lifecycle and Platform resets, which is what a bot is for. + const reset = await call('/api/networks/devnet-palmatum/ops', { method: 'POST', body: JSON.stringify({ action: 'platform-reset', images: { drive: 'dashpay/drive:5.0.3' }, options: { genesisProtocolVersion: 14 } }) }); + assert.equal(reset.status, 202); + } finally { w.close(); } +}); + +test('API tokens narrow their account: role, networks, expiry, and the account losing access', async () => { + let now = Date.now(); + const w = await start(9920871, [{ id: 77, login: 'op', role: 'operator', networks: ['testnet'] }], { clock: () => now }); + try { + const csrf = await w.login(); + writeFileSync(join(w.dataDir, 'devnets.json'), JSON.stringify({ 'devnet-palmatum': { status: 'ready', coreNetwork: 'palmatum-g1', public: false } })); + const doctor = JSON.stringify({ action: 'doctor', nodes: ['seed-2'] }); + const viewer = bot(w, (await issueToken(w, csrf, { label: 'viewer', role: 'viewer', networks: ['testnet'] })).token); + assert.equal((await viewer('/api/networks/testnet/ops')).status, 200); + assert.equal((await viewer('/api/networks/testnet/ops', { method: 'POST', body: doctor })).status, 403); + assert.equal((await viewer('/api/networks/devnet-palmatum')).status, 404, 'a private network outside the grant stays hidden'); + assert.deepEqual((await (await viewer('/api/settings')).json()).settings.networks.map((n) => n.name), ['testnet']); + + const operator = bot(w, (await issueToken(w, csrf, { label: 'testnet operator', role: 'operator', networks: ['testnet'], expiresDays: 2 })).token); + assert.deepEqual((await (await operator('/api/me')).json()).operatorOf, ['testnet']); + assert.equal((await operator('/api/networks/testnet/ops', { method: 'POST', body: doctor })).status, 202); + assert.equal((await operator('/api/networks/devnet-palmatum/ops', { method: 'POST', body: doctor })).status, 403, 'not granted'); + const wide = bot(w, (await issueToken(w, csrf, { label: 'all networks', role: 'operator', networks: ['*'] })).token); + assert.equal((await wide('/api/networks/devnet-palmatum/ops', { method: 'POST', body: JSON.stringify({ action: 'platform-reset' }) })).status, 403, 'lifecycle needs an admin token'); + assert.equal((await wide('/api/devnets', { method: 'POST', body: JSON.stringify({ name: 'devnet-new' }) })).status, 403); + now += 2 * 86400_000; + assert.equal((await operator('/api/me')).status, 401, 'expired'); + assert.equal((await wide('/api/me')).status, 200, 'no expiry'); + + // The issuing admin is demoted by another admin: its tokens follow at once. + const s = JSON.parse(readFileSync(join(w.dataDir, 'settings.json'), 'utf8')); + s.operators = [{ id: 77, login: 'op', role: 'admin', networks: ['*'] }, { id: 9920871, login: 'someone', role: 'operator', networks: ['testnet'] }]; + writeFileSync(join(w.dataDir, 'settings.json'), JSON.stringify(s)); + const me = await (await wide('/api/me')).json(); + assert.deepEqual([me.role, me.operatorOf, me.allNetworks], ['operator', ['testnet'], false]); + assert.equal((await wide('/api/networks/devnet-palmatum/ops', { method: 'POST', body: doctor })).status, 403); + s.operators = [{ id: 77, login: 'op', role: 'admin', networks: ['*'] }]; + writeFileSync(join(w.dataDir, 'settings.json'), JSON.stringify(s)); + assert.equal((await wide('/api/me')).status, 401, 'account removed'); + assert.equal((await viewer('/api/networks/testnet/ops')).status, 401); + } finally { w.close(); } +}); diff --git a/shared/settings.js b/shared/settings.js index 1d2fa6d..c5cc743 100644 --- a/shared/settings.js +++ b/shared/settings.js @@ -245,7 +245,22 @@ export function readJSON(path, fallback = null) { export function accessFor(settings, user) { const o = user ? settings.operators.find((x) => x.id === user.id) : null; - return o ? { ...o, role: o.role || (o.networks.includes('*') ? 'admin' : 'operator') } : null; + if (!o) return null; + const account = { ...o, role: o.role || (o.networks.includes('*') ? 'admin' : 'operator') }; + return user.grant ? narrowAccess(account, user.grant) : account; +} +// An API token (server/api-tokens.js) acts for the account that issued it: its +// own grant can lower that account's role and shorten its networks, never widen +// them. `grant` is set by the web process from a verified token only; the agent +// rebuilds every actor from its id and login. +export function narrowAccess(account, grant) { + if (!ROLES.includes(grant.role) || !Array.isArray(grant.networks)) return null; + const role = ROLES[Math.max(ROLES.indexOf(account.role), ROLES.indexOf(grant.role))]; + const networks = role === 'admin' ? ['*'] + : account.networks.includes('*') ? grant.networks + : grant.networks.includes('*') ? account.networks + : account.networks.filter((n) => grant.networks.includes(n)); + return networks.length ? { ...account, role, networks } : null; } const covers = (a, network) => network === undefined || a.networks.includes('*') || a.networks.includes(network); // Members (any role) see granted networks in full detail, including private ones. diff --git a/shared/shared.test.js b/shared/shared.test.js index a2c48df..b54d49d 100644 --- a/shared/shared.test.js +++ b/shared/shared.test.js @@ -222,3 +222,23 @@ test('console devnets carry their images and dashmate release; sidecars are labe assert.equal(sidecarOf({ repo: 'redis', name: 'some-cache' }), null, 'only the rate limiter store is a sidecar'); assert.equal(sidecarOf({ repo: 'dashpay/drive', name: 'x-drive_abci' }), null); }); + +test('API token grants only narrow the account they act for', async () => { + const { accessFor, adminFor, memberOf } = await import('./settings.js'); + const s = structuredClone(settings); + s.operators.push({ id: 6, login: 'o', role: 'operator', networks: ['testnet', 'devnet-a'] }, { id: 5, login: 'v', role: 'viewer', networks: ['testnet'] }); + const v = validateSettings(s); + const as = (id, role, networks) => accessFor(v, { id, grant: { role, networks } }); + assert.deepEqual([as(9920871, 'admin', ['*']).role, as(9920871, 'admin', ['*']).networks], ['admin', ['*']]); + assert.deepEqual([as(9920871, 'operator', ['testnet']).role, as(9920871, 'operator', ['testnet']).networks], ['operator', ['testnet']]); + assert.equal(adminFor(v, { id: 9920871, grant: { role: 'operator', networks: ['*'] } }), false); + // An account below the token's role or outside its networks wins. + assert.deepEqual([as(6, 'admin', ['*']).role, as(6, 'admin', ['*']).networks], ['operator', ['testnet', 'devnet-a']]); + assert.deepEqual(as(6, 'operator', ['devnet-a', 'devnet-b']).networks, ['devnet-a']); + assert.equal(as(6, 'operator', ['devnet-b']), null); + assert.equal(as(5, 'operator', ['testnet']).role, 'viewer'); + assert.equal(operatorFor(v, { id: 5, grant: { role: 'operator', networks: ['testnet'] } }, 'testnet'), false); + assert.equal(memberOf(v, { id: 6, grant: { role: 'viewer', networks: ['testnet'] } }, 'devnet-a'), false); + assert.equal(as(1, 'admin', ['*']), null, 'no account, no access'); + assert.equal(as(6, 'owner', ['testnet']), null, 'unknown role'); +}); diff --git a/src/pages/Operation.jsx b/src/pages/Operation.jsx index b82b15c..03531a9 100644 --- a/src/pages/Operation.jsx +++ b/src/pages/Operation.jsx @@ -41,7 +41,7 @@ export default function Operation({ name, id }) {
network {op.network}
-
requested by {op.actor.login} {ago(op.createdAt, now)} ago
+
requested by {op.actor.login}{op.actor.token && via API token {op.actor.token}} {ago(op.createdAt, now)} ago
nodes {q.nodes.length > 6 ? `${q.nodes.slice(0, 6).join(', ')} +${q.nodes.length - 6}` : q.nodes.join(', ')}
images {Object.values(q.images || {}).join(' ') || (q.components || []).join(', ') || '—'}
{op.confirmedBy &&
confirmed by {op.confirmedBy.login} {clock(op.confirmedAt)}
} diff --git a/src/pages/Operations.jsx b/src/pages/Operations.jsx index 8ae1b5a..a8e98c9 100644 --- a/src/pages/Operations.jsx +++ b/src/pages/Operations.jsx @@ -19,7 +19,7 @@ export default function Operations({ network, operator }) { {o.request.action} {o.request.nodes.length > 4 ? `${o.request.nodes.slice(0, 4).join(', ')} +${o.request.nodes.length - 4}` : o.request.nodes.join(', ')} {Object.values(o.request.images || {}).join(' ') || (o.request.components || []).join(', ') || '—'} - {o.actor.login} + {o.actor.login}{o.actor.token && · token} {ago(o.createdAt, now)} {ago(o.updatedAt, now)} diff --git a/src/pages/Settings.jsx b/src/pages/Settings.jsx index 7bbd90a..bd8ff33 100644 --- a/src/pages/Settings.jsx +++ b/src/pages/Settings.jsx @@ -76,6 +76,8 @@ export default function Settings() { + {admin && n.name)} />} + set((x) => fn(x.devnets))} />
set((d) => { d.networks.push(blankNetwork()); })}>Add network}> @@ -234,6 +236,77 @@ function Access({ doc, ro, setOperators, self }) { ); } +// Tokens for bots. Each acts for the admin who issued it, within the role and +// networks chosen here, and is shown once. +const TOKEN_ROLE_TEXT = { admin: 'operate every network, including devnet lifecycle and Platform resets', operator: ROLE_TEXT.operator, viewer: ROLE_TEXT.viewer }; +function ApiTokens({ names }) { + const [tokens, setTokens] = useState(null); + const [label, setLabel] = useState(''); + const [role, setRole] = useState('operator'); + const [networks, setNetworks] = useState([]); + const [days, setDays] = useState(''); + const [issued, setIssued] = useState(null); + const [err, setErr] = useState(null); + useEffect(() => { api('/api/tokens').then((r) => setTokens(r.tokens), setErr); }, []); + const toggle = (n) => setNetworks((l) => (l.includes(n) ? l.filter((x) => x !== n) : [...l, n])); + const issue = async (e) => { + e.preventDefault(); setErr(null); setIssued(null); + try { + const t = await api('/api/tokens', { method: 'POST', body: { label, role, networks: role === 'admin' ? ['*'] : networks, ...(days ? { expiresDays: Number(days) } : {}) } }); + setIssued(t); setLabel(''); setNetworks([]); setDays(''); + setTokens((await api('/api/tokens')).tokens); + } catch (x) { setErr(x); } + }; + const revoke = async (t) => { + if (!window.confirm(`Revoke API token "${t.label}" (${t.id})? It stops working at once.`)) return; + setErr(null); + try { setTokens((await api(`/api/tokens/${t.id}`, { method: 'DELETE' })).tokens); if (issued?.id === t.id) setIssued(null); } catch (x) { setErr(x); } + }; + return ( +
+
+ Issue a token for a bot + setLabel(e.target.value)} /> + + {role !== 'admin' &&
{['*', ...names].map((n) => toggle(n)}>{n === '*' ? 'all networks' : n})}
} + setDays(e.target.value.replace(/\D/g, ''))} /> + + {TOKEN_ROLE_TEXT[role]}. Sent as Authorization: Bearer …. Tokens never change settings, access or tokens and never read private keys. + {issued && ( +
+
Copy this token now. It is not shown again.
+
{issued.token}
+
+ )} +
+ + {tokens?.length ? ( +
+ + + {tokens.map((t) => ( + + + + + + + + + + + ))} + +
tokenacts forrolenetworkscreatedexpireslast used
{t.label} {t.id}@{t.owner.login}{t.role}{t.networks.includes('*') ? all networks : t.networks.join(', ')}{t.createdAt.slice(0, 10)}{t.expiresAt ? t.expiresAt.slice(0, 10) : 'never'}{t.lastUsedAt ? t.lastUsedAt.slice(0, 16).replace('T', ' ') : 'never'}
+
+ ) : tokens && No API tokens.} +
A token can only narrow the access of the account it acts for; removing or demoting that account takes its tokens with it.
+
+ ); +} + function DevnetDefaults({ d, ro, update }) { if (!d) return null; const T = (label, key, mono = true) => update((x) => { x[key] = v.trim(); })} />; From d7c74cf3f97fd8db69b43722780c2d9369edd064 Mon Sep 17 00:00:00 2001 From: ktechmidas <9920871+ktechmidas@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:39:27 +0300 Subject: [PATCH 2/2] fix: close the gaps the review found in API token handling A presented token is now enforced before the browser's own session routes: with a wrong token and a valid cookie, /api/session answered as the browser user, and a valid token could log the browser session out. Those routes answer 401 for a wrong token and 403 for a valid one. Token requests read the access settings from disk without the default fallback and answer 503 when the file is missing or does not validate. loadSettings falls back to built-in defaults that name an admin, and a token must never be authorized by that. The CI and AWS pages are not divided by network. A token now sees them in full only when its grant covers every network; a narrowed token gets the public projection, without costs. The event stream and an operation's log stream re-check their token as they go and end when it is revoked, expires or loses the network. Also: the confirmation line names the token that confirmed, the issue form cannot be submitted twice, its fields have accessible names and its network chips are buttons, the README no longer shows a confirm step for a health check, and a test that split the secret on underscores no longer fails for one token in 64. Co-Authored-By: Claude Fable 5.2 --- README.md | 15 ++++++- server/web.js | 64 +++++++++++++++++++------- server/web.test.js | 99 ++++++++++++++++++++++++++++++++++++++++- src/pages/Operation.jsx | 2 +- src/pages/Settings.jsx | 18 +++++--- 5 files changed, 170 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index aa09ab2..08c9667 100644 --- a/README.md +++ b/README.md @@ -339,9 +339,14 @@ The token is shown once; the console keeps only its SHA-256 in export DASH_STATUS_TOKEN=dst_... # from a secret store, never a script or a log api() { curl -fsS -H "Authorization: Bearer $DASH_STATUS_TOKEN" -H 'Content-Type: application/json' "$@"; } api https://status.testnet.networks.dash.org/api/me +# A health check runs at once and ends succeeded or failed: id=$(api -X POST https://status.testnet.networks.dash.org/api/networks/devnet-x/ops -d '{"action":"doctor","nodes":[]}' | jq -r .id) -api https://status.testnet.networks.dash.org/api/ops/$id # status, steps, review, log tail -api -X POST https://status.testnet.networks.dash.org/api/ops/$id/confirm -d '{"planId":""}' +api https://status.testnet.networks.dash.org/api/ops/$id # status, steps, result, log tail +# An upgrade or a Platform reset prepares a plan and waits in `review` until it is confirmed: +id=$(api -X POST https://status.testnet.networks.dash.org/api/networks/devnet-x/ops \ + -d '{"action":"platform-reset","images":{"drive":"dashpay/drive:5.0.3","dapi":"dashpay/rs-dapi:5.0.3"}}' | jq -r .id) +plan=$(api https://status.testnet.networks.dash.org/api/ops/$id | jq -r .review.planId) # once status is "review"; read the review first +api -X POST https://status.testnet.networks.dash.org/api/ops/$id/confirm -d "{\"planId\":\"$plan\"}" ``` - A token **acts for the admin account that issued it** and can only narrow that @@ -351,6 +356,12 @@ api -X POST https://status.testnet.networks.dash.org/api/ops/$id/confirm -d '{"p - Token requests need no cookie, `Origin` or CSRF value. A request that presents a token is that token or nothing; an unknown, revoked or expired one is `401` and never falls back to a browser session. +- The CI and AWS pages are not divided by network, so a token sees them in full + only when its grant covers every network; otherwise it gets the public view. +- Open streams (`/api/stream`, an operation's log) re-check their token as they + go and end when it is revoked, expires or loses the network. +- If `settings.json` cannot be read or does not validate, token requests answer + `503`: a token is never authorized by the built-in default settings. - Tokens operate networks: read granted networks, operations and logs; create, confirm, cancel and resume operations their role allows (an `admin` token includes devnet lifecycle and Platform resets). They never change settings, diff --git a/server/web.js b/server/web.js index ce07754..2e92924 100644 --- a/server/web.js +++ b/server/web.js @@ -109,18 +109,32 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl }); app.use(express.json({ limit: '64kb' })); app.use('/api', (req, res, next) => { res.set('Cache-Control', 'no-store'); next(); }); - auth.install(app); // Bots authenticate with an API token instead of a browser session. A request - // that presents one is that token or nothing: it never falls back to a cookie. + // that presents one is that token or nothing: it never falls back to a cookie, + // so this runs before the browser's own session routes. + const resolveBot = (header) => { + // The grant is read from the settings on disk, and only from a file that + // validates: loadSettings falls back to the built-in defaults, which name an + // admin, and a token must never be authorized by that fallback. + try { validateSettings(JSON.parse(readFileSync(settingsPath, 'utf8'))); } catch { return { status: 503, error: 'Access settings unavailable' }; } + reloadSettings(); + const t = tokens.authenticate(header); + const bot = t && { token: t.id, user: { id: t.owner.id, login: t.owner.login, token: t.id, grant: { role: t.role, networks: t.networks } } }; + // A demoted or removed account takes its tokens with it at once. + return bot && accessFor(settings, bot.user) ? { bot } : { status: 401, error: 'API token unknown, revoked or expired' }; + }; + const SESSION_ONLY = 'This needs a signed-in account; API tokens operate networks only'; app.use('/api', (req, res, next) => { if (!presentsApiToken(req.get('authorization'))) return next(); - const t = tokens.authenticate(req.get('authorization')); - const bot = t && { token: t.id, user: { id: t.owner.id, login: t.owner.login, token: t.id, grant: { role: t.role, networks: t.networks } } }; - // Checked against the settings on disk: a revoked account loses its tokens at once. - if (!bot || !accessFor(reloadSettings(), bot.user)) return res.status(401).json({ error: 'API token unknown, revoked or expired' }); - req.bot = bot; + const r = resolveBot(req.get('authorization')); + if (!r.bot) return res.status(r.status).json({ error: r.error }); + if (req.path === '/session' || req.path.startsWith('/auth/')) return res.status(403).json({ error: SESSION_ONLY }); + req.bot = r.bot; next(); }); + // An open stream has no next request: it re-checks its token as it goes. + const botGone = (req) => !!req.bot && !resolveBot(req.get('authorization')).bot; + auth.install(app); // The limited Mainnet board is fed by a separately managed observer/fullnode // (not the existing mainnet-support fleet). Keep this write path token-only, @@ -145,7 +159,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl // CSRF protects cookies. A bearer token is not sent by a browser on its own. const csrf = (req, res, next) => (req.bot ? next() : auth.csrf(req, res, next)); const signedIn = (req, res, next) => { - if (req.bot) return res.status(403).json({ error: 'This needs a signed-in account; API tokens operate networks only' }); + if (req.bot) return res.status(403).json({ error: SESSION_ONLY }); const s = auth.session(req); if (!s) return res.status(401).json({ error: 'Sign in required' }); req.session = s; next(); @@ -154,6 +168,9 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl const isMember = (req, network) => memberOf(settings, user(req), network); const isAdmin = (req) => adminFor(settings, user(req)); const visible = (req) => settings.networks.filter((n) => n.public || isMember(req, n.name)); + // The CI and AWS pages are not divided by network. An account with any access + // sees them whole; a token does only when its grant covers every network. + const seesInfrastructure = (u) => !!memberOf(settings, u) && (!u.grant || accessFor(settings, u).networks.includes('*')); const stateOf = (name) => readJSON(join(dirs.state, `${name}.json`)); function view(network, operator) { @@ -213,12 +230,19 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl const client = { res, req, user: user(req) }; clients.add(client); res.write(`retry: 3000\n\n`); - const ping = setInterval(() => res.write(`: ping\n\n`), 25_000); + const ping = setInterval(() => (dropIfGone(client) ? clearInterval(ping) : res.write(`: ping\n\n`)), 25_000); req.on('close', () => { clearInterval(ping); clients.delete(client); }); }); + // A revoked or expired token stops receiving events, and its stream is closed. + const dropIfGone = (c) => { + if (!botGone(c.req)) return false; + clients.delete(c); + c.res.end(`event: error\ndata: ${JSON.stringify({ error: 'API token unknown, revoked or expired' })}\n\n`); + return true; + }; const push = (event, payload, filter = () => true) => { const data = `event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`; - for (const c of clients) if (filter(c)) c.res.write(data); + for (const c of [...clients]) if (!dropIfGone(c) && filter(c)) c.res.write(data); }; const debounce = new Map(); // A change to a private job is announced to members only: its timing is private too. @@ -228,7 +252,7 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl for (const members of scope === 'all' ? [true, false] : [true]) { const key = `ci-queue|${members}`; clearTimeout(debounce.get(key)); - debounce.set(key, setTimeout(() => push('ci-queue', { at: new Date(clock()).toISOString() }, (c) => !!memberOf(settings, c.user) === members), 1000)); + debounce.set(key, setTimeout(() => push('ci-queue', { at: new Date(clock()).toISOString() }, (c) => seesInfrastructure(c.user) === members), 1000)); } }; function onStateFile(file) { @@ -365,6 +389,12 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl res.set({ 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' }); res.flushHeaders(); const send = () => { + // A token is checked again on every tick: revoked, expired or no longer + // granted this network, it gets no more of the log. + if (req.bot && (botGone(req) || !memberOf(settings, req.bot.user, req.network))) { + clearInterval(timer); + return res.end(`event: error\ndata: ${JSON.stringify({ error: 'API token unknown, revoked or expired' })}\n\n`); + } try { if (!existsSync(path)) return; const size = statSync(path).size; @@ -376,9 +406,9 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl res.write(`event: log\ndata: ${JSON.stringify({ text: buf.toString(), offset })}\n\n`); } catch (e) { res.write(`event: error\ndata: ${JSON.stringify({ error: e.message })}\n\n`); } }; - send(); const timer = setInterval(send, 1000); req.on('close', () => clearInterval(timer)); + send(); }); for (const type of ['confirm', 'cancel', 'resume']) { app.post(`/api/ops/:id/${type}`, requireOperator, csrf, (req, res) => { @@ -477,12 +507,12 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl // sanitized view (statistics, nothing identifying). Spend is never shown // before sign-in. const cached = ttlCache(clock); - app.get('/api/ci', (req, res) => res.json(memberOf(settings, user(req)) ? ci.summary({ admin: isAdmin(req) }) : cached('ci', () => ci.publicSummary()))); + app.get('/api/ci', (req, res) => res.json(seesInfrastructure(user(req)) ? ci.summary({ admin: isAdmin(req) }) : cached('ci', () => ci.publicSummary()))); app.get('/api/ci/queue/capacity', (req, res) => { const window = typeof req.query.window === 'string' ? req.query.window : '7d'; - res.json(orgQueue.capacity({ full: !!memberOf(settings, user(req)), window })); + res.json(orgQueue.capacity({ full: seesInfrastructure(user(req)), window })); }); - app.get('/api/ci/queue', (req, res) => res.json(memberOf(settings, user(req)) ? orgQueue.summary({ full: true }) : cached('ci-queue', () => orgQueue.summary()))); + app.get('/api/ci/queue', (req, res) => res.json(seesInfrastructure(user(req)) ? orgQueue.summary({ full: true }) : cached('ci-queue', () => orgQueue.summary()))); app.post('/api/ci/reporters', ...adminWrite, (req, res) => { try { const { id, token } = ci.addReporter(req.body?.label); @@ -498,7 +528,9 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl const viewer = user(req); // Cost visibility follows the authenticated session, never query parameters. // Keep signed-in summaries separate from the anonymous projection cache. - res.vary('Cookie').json(memberOf(settings, viewer) ? inv : cached(`aws|${viewer ? 'signed-in' : 'public'}|${inv.at}`, () => publicInventory(inv, { includeCosts: !!viewer }))); + // A token narrowed to some networks gets the anonymous projection, without costs. + const browser = !!viewer && !req.bot; + res.vary('Cookie').json(seesInfrastructure(viewer) ? inv : cached(`aws|${browser ? 'signed-in' : 'public'}|${inv.at}`, () => publicInventory(inv, { includeCosts: browser }))); }); // GitHub account lookup so admins can grant access by login. diff --git a/server/web.test.js b/server/web.test.js index 8019883..8fef6c5 100644 --- a/server/web.test.js +++ b/server/web.test.js @@ -516,7 +516,10 @@ test('API tokens: an admin issues one; a bot queues and confirms operations with assert.deepEqual([issued.role, issued.networks, issued.owner], ['admin', ['*'], { id: 9920871, login: 'someone' }]); // Only the hash is kept, and the list never returns the token. const stored = readFileSync(join(w.dataDir, 'api-tokens.json'), 'utf8'); - assert.ok(!stored.includes(issued.token) && !stored.includes(issued.token.split('_')[2])); + // The secret is base64url and may itself contain or start with an underscore. + const secret = issued.token.slice(`dst_${issued.id}_`.length); + assert.equal(secret.length, 43); + assert.ok(!stored.includes(issued.token) && !stored.includes(secret)); const listed = await (await w.req('/api/tokens')).json(); assert.deepEqual(listed.tokens.map((t) => [t.id, t.label, t.token]), [[issued.id, 'infraclaw', undefined]]); @@ -576,7 +579,7 @@ test('API tokens operate networks only: no settings, access, tokens, remediation assert.match((await r.json()).error, /signed-in account/, `${method} ${path}`); } assert.equal(Object.keys(JSON.parse(readFileSync(join(w.dataDir, 'api-tokens.json'), 'utf8'))).length, 1); - assert.equal((await call('/api/auth/logout', { method: 'POST' })).status, 401); + assert.equal((await call('/api/auth/logout', { method: 'POST' })).status, 403); // Admin tokens do manage devnet lifecycle and Platform resets, which is what a bot is for. const reset = await call('/api/networks/devnet-palmatum/ops', { method: 'POST', body: JSON.stringify({ action: 'platform-reset', images: { drive: 'dashpay/drive:5.0.3' }, options: { genesisProtocolVersion: 14 } }) }); assert.equal(reset.status, 202); @@ -620,3 +623,95 @@ test('API tokens narrow their account: role, networks, expiry, and the account l assert.equal((await viewer('/api/networks/testnet/ops')).status, 401); } finally { w.close(); } }); + +test('API tokens: a presented token is enforced on the session routes, and never authorized by default settings', async () => { + const w = await start(); + try { + const csrf = await w.login(); + const { token } = await issueToken(w, csrf, { label: 'bot', role: 'admin' }); + // The browser's own cookie is attached to every one of these. + const withToken = (path, t, opts = {}) => w.req(path, { ...opts, headers: { authorization: `Bearer ${t}`, 'x-csrf-token': csrf, ...(opts.headers || {}) } }); + assert.equal((await withToken('/api/session', 'dst_nope')).status, 401, 'a wrong token does not fall back to the session'); + assert.equal((await withToken('/api/session', token)).status, 403); + assert.equal((await withToken('/api/auth/logout', token, { method: 'POST' })).status, 403); + assert.equal((await withToken('/api/auth/github', token)).status, 403); + assert.equal((await (await w.req('/api/session')).json()).user.id, 9920871, 'the browser session survived'); + + // Unreadable or invalid settings: loadSettings falls back to defaults that name an admin. + const saved = readFileSync(join(w.dataDir, 'settings.json'), 'utf8'); + for (const broken of ['{ not json', JSON.stringify({ ...JSON.parse(saved), pollSeconds: 1 })]) { + writeFileSync(join(w.dataDir, 'settings.json'), broken); + const r = await bot(w, token)('/api/me'); + assert.equal(r.status, 503); + assert.match((await r.json()).error, /settings unavailable/); + assert.equal((await bot(w, token)('/api/networks/testnet/ops', { method: 'POST', body: JSON.stringify({ action: 'doctor', nodes: ['seed-2'] }) })).status, 503); + } + rmSync(join(w.dataDir, 'settings.json')); + assert.equal((await bot(w, token)('/api/me')).status, 503, 'no settings file'); + assert.equal((await bot(w)('/api/overview')).status, 200, 'the public board still answers'); + writeFileSync(join(w.dataDir, 'settings.json'), saved); + assert.equal((await bot(w, token)('/api/me')).status, 200); + } finally { w.close(); } +}); + +test('API tokens: CI and AWS detail only for a grant that covers every network', async () => { + const w = await start(); + try { + const csrf = await w.login(); + mkdirSync(join(w.dataDir, 'aws'), { recursive: true }); + writeFileSync(join(w.dataDir, 'aws', 'inventory.json'), JSON.stringify({ at: 'now', regions: ['us-west-2'], errors: [], + instances: [{ region: 'us-west-2', id: 'i-0123456789abcdef0', type: 't4g.small', state: 'running', arch: 'arm64', publicIp: '192.0.2.9', tags: { Name: 'dn-devnet-secret-1', DashNetwork: 'devnet-secret' }, vcpus: 2, memoryMiB: 2048 }], + volumes: [], addresses: [], natGateways: [], loadBalancers: [], lambda: [], dynamodb: [], ecr: [], snapshots: [], cloudfront: [], s3: [], + costs: { at: 'now', month: '2026-11', monthToDate: 100, monthEndEstimate: 200, lastMonth: 150, byService: [], daily: [] } })); + const narrow = bot(w, (await issueToken(w, csrf, { label: 'testnet only', role: 'operator', networks: ['testnet'] })).token); + const wide = bot(w, (await issueToken(w, csrf, { label: 'everything', role: 'viewer', networks: ['*'] })).token); + const aws = await (await narrow('/api/aws')).json(); + assert.equal(aws.public, true); + assert.equal(aws.costs, undefined, 'no spend for a narrowed token'); + for (const leak of ['192.0.2.9', 'i-0123456789abcdef0', 'dn-devnet-secret-1']) assert.ok(!JSON.stringify(aws).includes(leak), `leaked ${leak}`); + assert.equal((await (await narrow('/api/ci')).json()).public, true); + assert.equal((await (await narrow('/api/ci/queue')).json()).public, true); + const all = await (await wide('/api/aws')).json(); + assert.equal(all.instances[0].publicIp, '192.0.2.9'); + assert.equal((await (await wide('/api/ci')).json()).public, undefined); + // The browser account keeps its view, and the anonymous cache is not poisoned by either. + assert.equal((await (await w.req('/api/aws')).json()).instances[0].id, 'i-0123456789abcdef0'); + assert.equal((await (await bot(w)('/api/aws')).json()).costs, undefined); + } finally { w.close(); } +}); + +test('API tokens: an open operation log and event stream end when the token is revoked', async () => { + const w = await start(); + try { + const csrf = await w.login(); + const issued = await issueToken(w, csrf, { label: 'stream', role: 'admin' }); + const id = '6c8139ad-e92f-40da-943d-1e001efaccb5'; + mkdirSync(join(w.dataDir, 'ops'), { recursive: true }); + writeFileSync(join(w.dataDir, 'ops', `${id}.json`), JSON.stringify({ id, network: 'testnet', status: 'running', request: { action: 'upgrade' }, createdAt: new Date().toISOString() })); + writeFileSync(join(w.dataDir, 'ops', `${id}.log`), 'first line\n'); + const text = new TextDecoder(); + // Reads until the server ends the stream; fails the test if it is still open after the limit. + const drain = async (response, limitMs) => { + const reader = response.body.getReader(); + let seen = ''; + const timeout = setTimeout(() => reader.cancel('still open'), limitMs); + try { for (;;) { const { done, value } = await reader.read(); if (done) break; seen += text.decode(value); } } finally { clearTimeout(timeout); } + return seen; + }; + const log = await bot(w, issued.token)(`/api/ops/${id}/log`); + const events = await bot(w, issued.token)('/api/stream'); + assert.equal(log.status, 200); assert.equal(events.status, 200); + const logDone = drain(log, 8000), eventsDone = drain(events, 8000); + await new Promise((r) => setTimeout(r, 300)); + assert.equal((await w.req(`/api/tokens/${issued.id}`, { method: 'DELETE', headers: { 'x-csrf-token': csrf } })).status, 200); + writeFileSync(join(w.dataDir, 'ops', `${id}.log`), 'first line\nwritten after the token was revoked\n'); + // The event stream is checked on its next event: an operation change is one. + writeFileSync(join(w.dataDir, 'ops', `${id}.json`), JSON.stringify({ id, network: 'testnet', status: 'succeeded', request: { action: 'upgrade' }, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() })); + const [logText, eventText] = await Promise.all([logDone, eventsDone]); + assert.match(logText, /first line/); + assert.ok(!logText.includes('written after the token was revoked'), 'nothing after revocation'); + assert.match(logText, /event: error\ndata: \{"error":"API token unknown, revoked or expired"\}/); + assert.match(eventText, /event: error/); + assert.ok(!eventText.includes('"status":"succeeded"'), 'no event after revocation'); + } finally { w.close(); } +}); diff --git a/src/pages/Operation.jsx b/src/pages/Operation.jsx index 03531a9..638a51c 100644 --- a/src/pages/Operation.jsx +++ b/src/pages/Operation.jsx @@ -44,7 +44,7 @@ export default function Operation({ name, id }) {
requested by {op.actor.login}{op.actor.token && via API token {op.actor.token}} {ago(op.createdAt, now)} ago
nodes {q.nodes.length > 6 ? `${q.nodes.slice(0, 6).join(', ')} +${q.nodes.length - 6}` : q.nodes.join(', ')}
images {Object.values(q.images || {}).join(' ') || (q.components || []).join(', ') || '—'}
- {op.confirmedBy &&
confirmed by {op.confirmedBy.login} {clock(op.confirmedAt)}
} + {op.confirmedBy &&
confirmed by {op.confirmedBy.login}{op.confirmedBy.token && via API token {op.confirmedBy.token}} {clock(op.confirmedAt)}
} {op.runner &&
dashnet runner {op.runner}
} {q.options?.observationWindow &&
observation window {q.options.observationWindow}
} {op.finishedAt &&
finished {clock(op.finishedAt)}
} diff --git a/src/pages/Settings.jsx b/src/pages/Settings.jsx index bd8ff33..7897a87 100644 --- a/src/pages/Settings.jsx +++ b/src/pages/Settings.jsx @@ -246,16 +246,20 @@ function ApiTokens({ names }) { const [networks, setNetworks] = useState([]); const [days, setDays] = useState(''); const [issued, setIssued] = useState(null); + const [busy, setBusy] = useState(false); const [err, setErr] = useState(null); useEffect(() => { api('/api/tokens').then((r) => setTokens(r.tokens), setErr); }, []); const toggle = (n) => setNetworks((l) => (l.includes(n) ? l.filter((x) => x !== n) : [...l, n])); const issue = async (e) => { - e.preventDefault(); setErr(null); setIssued(null); + e.preventDefault(); + // One token per submit: a second token's secret would replace the first on screen. + if (busy) return; + setBusy(true); setErr(null); setIssued(null); try { const t = await api('/api/tokens', { method: 'POST', body: { label, role, networks: role === 'admin' ? ['*'] : networks, ...(days ? { expiresDays: Number(days) } : {}) } }); setIssued(t); setLabel(''); setNetworks([]); setDays(''); setTokens((await api('/api/tokens')).tokens); - } catch (x) { setErr(x); } + } catch (x) { setErr(x); } finally { setBusy(false); } }; const revoke = async (t) => { if (!window.confirm(`Revoke API token "${t.label}" (${t.id})? It stops working at once.`)) return; @@ -266,13 +270,13 @@ function ApiTokens({ names }) {
Issue a token for a bot - setLabel(e.target.value)} /> - setLabel(e.target.value)} /> + - {role !== 'admin' &&
{['*', ...names].map((n) => toggle(n)}>{n === '*' ? 'all networks' : n})}
} - setDays(e.target.value.replace(/\D/g, ''))} /> - + {role !== 'admin' &&
{['*', ...names].map((n) => )}
} + setDays(e.target.value.replace(/\D/g, ''))} /> + {TOKEN_ROLE_TEXT[role]}. Sent as Authorization: Bearer …. Tokens never change settings, access or tokens and never read private keys. {issued && (