Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,51 @@ 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
# 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, 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
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.
- 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,
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
Expand Down
23 changes: 23 additions & 0 deletions agent/agent.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
14 changes: 8 additions & 6 deletions agent/ops.js
Original file line number Diff line number Diff line change
Expand Up @@ -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') {
Expand All @@ -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;
Expand All @@ -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') {
Expand All @@ -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}`);
}
}

Expand Down
23 changes: 21 additions & 2 deletions scripts/browser-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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');
Expand Down
76 changes: 76 additions & 0 deletions server/api-tokens.js
Original file line number Diff line number Diff line change
@@ -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)) };
}
Loading
Loading