From 81392171e0888a4d1300505ba4dc2b0129691047 Mon Sep 17 00:00:00 2001 From: ktechmidas <9920871+ktechmidas@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:55:44 +0300 Subject: [PATCH] Bring the live console's remaining integrations into the repository The console at status.testnet.networks.dash.org has been running master plus local integrations that were never pushed. This adds the ones master still lacked, taken from the exact source the running image was built from (local commit 9118cd3, whose files match the live web container byte for byte): - rollout options from the console: reviewed concurrency and automatic mining resume, bound from the request to the dashnet executor - devnet key export for Connect, as a separate on-demand key service - a selectable genesis Platform protocol version on devnet reset - seven-day sign-in sessions - remediation-only exclusion of chosen CI hosts - fail-closed handling of management journal read errors - the website performance collector, its systemd units and its tests - per-host and miner image tracking in network settings Where master is already ahead of the running image it is kept as it is: the image-drift targets from #67, the Websites and Mainnet fixes from #68, and the incident broker change from #66. Co-Authored-By: infraclaw-dash <283232465+infraclaw-dash@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- README.md | 60 +++++++ agent/agent.test.js | 90 +++++++++- agent/devnet-config.js | 2 +- agent/devnet-config.test.js | 3 +- agent/devnet-keys-service.js | 2 + agent/devnet-keys.js | 100 +++++++++++ agent/devnet-keys.py | 66 +++++++ agent/devnet-keys.test.js | 34 ++++ agent/devnets.js | 62 +++++-- agent/ops.js | 85 ++++++--- agent/reset-dashnet.py | 57 ++++-- agent/reset-journal.js | 27 ++- agent/reset-journal.test.js | 17 +- agent/reset-native.test.js | 16 +- agent/reset-remote.py | 18 +- agent/reset.js | 15 +- agent/test_reset_dashnet.py | 18 +- agent/test_reset_pv.py | 53 ++++++ deploy/deploy.sh | 5 + deploy/devnet-keys-compose.yml | 35 ++++ docs/platform-reset.md | 31 ++++ docs/rollout-options.md | 34 ++++ monitoring/websites/README.md | 61 +++++++ .../websites/dash-status-websites.service | 26 +++ .../websites/dash-status-websites.timer | 10 ++ monitoring/websites/probe.py | 168 ++++++++++++++++++ monitoring/websites/test_probe.py | 67 +++++++ scripts/browser-connect-keys.mjs | 48 +++++ scripts/browser-reset-pv-check.mjs | 83 +++++++++ scripts/browser-rollout-check.mjs | 84 +++++++++ scripts/check-console-features.mjs | 13 ++ scripts/check-rollout-backend.mjs | 20 +++ server/auth.js | 5 +- server/devnet-keys.js | 15 ++ server/incidents.js | 17 +- server/incidents.test.js | 26 +++ server/remediation.js | 2 +- server/remediation.test.js | 6 + server/web.js | 20 ++- server/web.test.js | 87 ++++----- shared/monitoring.js | 4 +- shared/rollout.js | 41 +++++ shared/rollout.test.js | 41 +++++ shared/settings.js | 2 +- src/RolloutOptions.jsx | 14 ++ src/pages/Connect.jsx | 14 +- src/pages/Deploy.jsx | 16 +- src/pages/DevnetKeys.jsx | 48 +++++ src/pages/Network.jsx | 8 +- src/pages/Operation.jsx | 9 +- src/pages/ResetPlatform.jsx | 10 +- 51 files changed, 1646 insertions(+), 149 deletions(-) create mode 100644 agent/devnet-keys-service.js create mode 100644 agent/devnet-keys.js create mode 100644 agent/devnet-keys.py create mode 100644 agent/devnet-keys.test.js create mode 100644 agent/test_reset_pv.py create mode 100644 deploy/devnet-keys-compose.yml create mode 100644 docs/platform-reset.md create mode 100644 docs/rollout-options.md create mode 100644 monitoring/websites/README.md create mode 100644 monitoring/websites/dash-status-websites.service create mode 100644 monitoring/websites/dash-status-websites.timer create mode 100644 monitoring/websites/probe.py create mode 100644 monitoring/websites/test_probe.py create mode 100644 scripts/browser-connect-keys.mjs create mode 100644 scripts/browser-reset-pv-check.mjs create mode 100644 scripts/browser-rollout-check.mjs create mode 100644 scripts/check-console-features.mjs create mode 100644 scripts/check-rollout-backend.mjs create mode 100644 server/devnet-keys.js create mode 100644 shared/rollout.js create mode 100644 shared/rollout.test.js create mode 100644 src/RolloutOptions.jsx create mode 100644 src/pages/DevnetKeys.jsx diff --git a/README.md b/README.md index 5ada8c2..138d72a 100644 --- a/README.md +++ b/README.md @@ -327,3 +327,63 @@ 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. + +### Devnet operator keys + +Connect → **Private devnet keys** is available to operators of that managed +console devnet (including admins), not viewers or anonymous users. Reveal uses +POST `/api/networks/:name/keys` with the existing session, same-origin and CSRF +checks. Grants reload before and after retrieval. Mainnet/Testnet are excluded. +The ordinary connection files and event stream never contain keys. + +Deploy `deploy/devnet-keys-compose.yml` with the same source image as web. +Create `/srv/dash-status/key-access` owned by uid1000, mode0700. The `keys` +service is a separate, read-only collector, not a network operation runner: +it exposes only a mode0600 Unix socket, checks current network/operator grants, +requires an idle ready devnet, uses existing pinned SSH identities without +provisioning, and verifies EC2 instance, Core chain and on-chain ProTx identities. +It reads only the registered voting/owner/collateral keys and BLS/P2P identities, +plus the devnet's spork/payout/faucet addresses. It never changes or unlocks a +wallet, generates keys, or writes keys to disk. RPC/SSH/TLS credentials are not +returned. Web mounts only the socket directory, never the agent's credentials. + +Responses are `private, no-store`; audit output contains only actor ID, network +and time. UI data clears on hiding, unmount, background tab or five minutes. +Downloads are explicit private JSON files. Failures return a generic error; +never log raw SSH/RPC responses while troubleshooting key access. + +### CI host remediation exclusions + +An operator can set `remediation.excludedCiHosts` in the persisted `settings.json` +to an array of exact CI reporter IDs (for example, `['strix-pasta']`, using JSON +quotes in the actual file). This excludes host-scoped incidents and failed jobs +from automated response and the remediation view without removing the reporter, +CI history, resource observations, or CI page entry. Existing incidents remain +recorded, not falsely resolved; unsent events are retained in quarantine with an +explicit exclusion reason. The receiver's fresh-issue suppression gate prevents +already-delivered events from starting repairs. Removing the ID re-enables +admission after a fresh observation. This does not cancel an already-running +response; settle that owner separately before changing its work. + +Console GitHub login sessions last seven days from sign-in (both the server session and browser cookie). Existing sessions keep their original expiry; sign in again to receive the new lifetime. + +After a console deployment, verify retained capabilities as well as legacy APIs: + +```sh +node scripts/check-console-features.mjs https://status.testnet.networks.dash.org +node scripts/check-legacy-api.mjs https://status.testnet.networks.dash.org 82 +``` + +The feature gate checks Remediation, website monitoring, CI queue APIs and their frontend navigation. A passing `/api/health` alone must not certify a console rollout. Preserve deployed integrations when updating the separately built network executor. + +For an executor/agent promotion, also run `scripts/check-rollout-backend.mjs` +inside **both candidate images** (mount the script read-only if it is not baked +in). It checks the actual agent validator, plan binding, and both CLI planning +commands without network access. Run the `requested concurrency` integration +test in `agent/agent.test.js` against the candidate agent modules as well. +Check retained features against the last verified complete release, not just the +currently deployed image: on 2026-11-17 a regressed agent silently dropped a +saved `concurrency: 3` request while the restored web correctly displayed it. +Retain the merged engine's Platform protocol compatibility fixes. Do not replace +an active operation's pinned executable/plan; promote only after the agent is +idle and recheck its queue and child processes at cutover. diff --git a/agent/agent.test.js b/agent/agent.test.js index c688ad2..0de9c9b 100644 --- a/agent/agent.test.js +++ b/agent/agent.test.js @@ -63,7 +63,7 @@ test('requests are validated against the network and component repositories', () }); // Fake dashnet: writes the --out artifact each command would produce. -function fakeDashnet(calls) { +function fakeDashnet(calls, journal = { missing: true }) { return (binary, args) => { const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); @@ -72,6 +72,14 @@ function fakeDashnet(calls) { const out = args[args.indexOf('--out') + 1]; setImmediate(() => { const cmd = args[0]; + if (cmd === 'managed-operation') { + if (journal.spawnError) { child.emit('error', new Error(journal.spawnError)); child.emit('close', -2); return; } + if (journal.missing) child.stderr.emit('data', 'dashnet: operation not found\n'); + else if (journal.error) child.stderr.emit('data', journal.error + '\n'); + else if (!journal.noOutput) writeFileSync(out, JSON.stringify(journal.record ? { record: journal.record } : journal)); + child.emit('close', journal.missing || journal.error ? 1 : 0); + return; + } if (cmd === 'managed-import') writeFileSync(out, JSON.stringify({ id: 'a'.repeat(64), nodes: { 'seed-2': { components: { tenderdash: { image: 'dashpay/tenderdash:1.8.1', digests: ['dashpay/tenderdash@sha256:' + 'b'.repeat(64)] } } } } })); if (cmd === 'managed-enroll') { child.stderr.emit('data', 'runner: ' + 'c'.repeat(32) + '\nenrolled seed-2; services unchanged\n'); writeFileSync(out, '{}'); } if (cmd === 'managed-plan') writeFileSync(out, JSON.stringify({ id: 'd'.repeat(64), operation: 'upgrade', images: { 'seed-2': { tenderdash: 'index.docker.io/dashpay/tenderdash@sha256:' + 'e'.repeat(64) } } })); @@ -81,12 +89,87 @@ function fakeDashnet(calls) { setTimeout(() => { child.stderr.emit('data', 'managed target seed-2 ready\nmanaged-verifying\nmanaged target seed-2 applied\nmanaged-verifying\n'); child.emit('close', 0); }, 150); return; } - child.emit('close', cmd === 'managed-operation' ? 1 : 0); + child.emit('close', 0); }); return child; }; } +async function prepareWithJournal(journal, options) { + const root = mkdtempSync(join(tmpdir(), 'ops-journal-')); + 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 calls = []; + const ops = createOps({ settings: () => settings, dirs, key: { path: '/key' }, pool: { knownHosts: () => 'x\n', pins: new Proxy({}, { get: () => ({ type: 'ssh-ed25519', key: 'k' }) }) }, binary: 'dashnet', log: () => {}, spawnImpl: fakeDashnet(calls, journal) }); + mkdirSync(dirs.state, { recursive: true }); + writeFileSync(join(dirs.state, 'testnet.json'), JSON.stringify({ hosts: [host('seed-2', 'seed', [['dashd', 'dashpay/dashd'], ['tenderdash', 'dashpay/tenderdash']])] })); + const id = '6c8139ad-e92f-40da-943d-1e001efaccb5', actor = { id: 9920871, login: 'ktechmidas' }; + writeFileSync(join(dirs.requests, `${id}.json`), JSON.stringify({ type: 'create', id, network: 'testnet', action: 'upgrade', options, nodes: ['seed-2'], components: ['tenderdash'], images: { tenderdash: 'dashpay/tenderdash:1.8.2' }, actor })); + const read = () => JSON.parse(readFileSync(join(dirs.ops, `${id}.json`), 'utf8')); + const until = async (statuses) => { + for (let i = 0; i < 200; i++) { ops.tick(); if (statuses.includes(read().status)) return read(); await new Promise((r) => setTimeout(r, 5)); } + throw new Error(`operation did not settle: ${read().status}`); + }; + await until(['review', 'failed']); + return { dirs, id, actor, calls, read, until }; +} + +test('requested concurrency reaches managed planner and ignored options cannot auto-run', async () => { + const { read, calls } = await prepareWithJournal({ record: { phase: 'enrolled', enrolled: { 'seed-2': true } } }, { concurrency: 3, pauseMining: false, autoRun: true }); + const args = calls.find((a) => a[0] === 'managed-plan'); + assert.equal(args[args.indexOf('--concurrency') + 1], '3'); + // This old-executor fixture returns no rollout policy: fail before confirmation. + assert.equal(read().status, 'failed'); + assert.match(read().error, /rollout|concurrency/); + assert.ok(!calls.some((a) => a[0] === 'managed-upgrade')); +}); + +test('journal failures stop before enrollment/planning and retain an actionable error', async (t) => { + for (const journal of [ + { error: 'dashnet: unenrolled target in operation' }, + { error: 'dashnet: AccessDeniedException: table not found' }, + { error: 'dashnet: operation not found\nextra failure' }, + { spawnError: 'spawn dashnet ENOENT' }, + { noOutput: true }, + { record: { enrolled: [] } }, + ]) await t.test(JSON.stringify(journal), async () => { + const { read, calls, dirs, id } = await prepareWithJournal(journal); + const r = read(); + assert.equal(r.status, 'failed'); + assert.match(r.error, /Cannot read management journal:/); + if (journal.error) assert.ok(r.error.includes(journal.error.split('\n').at(-1))); + assert.equal(r.steps.at(-1).name, 'Read management journal'); + assert.equal(r.steps.at(-1).status, 'failed'); + assert.ok(!calls.some((a) => ['managed-enroll', 'managed-plan', 'managed-upgrade', 'managed-unlock'].includes(a[0]))); + assert.ok(!readdirSync(join(dirs.work, id, '1')).some((f) => f.startsWith('journal-')), 'temporary journal result cleaned up'); + }); +}); + +test('successful journal reads reuse the exact instance enrollment', async () => { + const instanceId = host('seed-2', 'seed', []).instanceId; + const { read, calls } = await prepareWithJournal({ record: { phase: 'enrolled', enrolled: { 'seed-2': true }, instances: { 'seed-2': instanceId } } }); + assert.equal(read().status, 'review'); + assert.ok(calls.some((a) => a[0] === 'managed-plan')); + assert.ok(!calls.some((a) => a[0] === 'managed-enroll')); +}); + +test('a replacement instance still needs explicit enrollment', async () => { + const { read, calls } = await prepareWithJournal({ record: { phase: 'enrolled', enrolled: { 'seed-2': true }, instances: { 'seed-2': 'i-old' } } }); + assert.equal(read().status, 'review'); + assert.ok(calls.some((a) => a[0] === 'managed-enroll')); +}); + +test('a journal failure after confirmation stops before unlock or upgrade', async () => { + const journal = { record: { phase: 'enrolled', enrolled: { 'seed-2': true } } }; + const { dirs, id, actor, read, until, calls } = await prepareWithJournal(journal); + const r = read(); + assert.equal(r.status, 'review'); + journal.error = 'dashnet: journal revision mismatch'; + writeFileSync(join(dirs.requests, `${id}.confirm.json`), JSON.stringify({ type: 'confirm', id, network: 'testnet', planId: r.review.planId, actor })); + const failed = await until(['failed']); + assert.match(failed.error, /journal revision mismatch/); + assert.ok(!calls.some((a) => ['managed-unlock', 'managed-upgrade'].includes(a[0]))); +}); + test('operation lifecycle: request -> enroll -> plan -> review -> confirm -> upgrade', 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') }; @@ -245,13 +328,14 @@ test('platform reset: review from non-destructive stages; a failed wipe stops be const pool = { exec: async (h, cmd) => { const stage = cmd.split(' ')[4]; calls.push(`${stage}:${h.name}`); + assert.equal(JSON.parse(Buffer.from(cmd.split(' ')[5], 'base64')).genesisProtocolVersion,15); const result = { baseline: { images: { drive: 'dashpay/drive:1' }, anchor: 10, epochTime: 3600, dashmate: 'dm', configFormatVersion: '4.2.0', tor: { enabled: false }, height: 100, tenderdashImage: 'dashpay/tenderdash:1' }, anchor: { height: 99, hash: 'ab' }, canary: { checks: { epochTime: 3600, epochEnv: '3600', coreSectionUnchanged: true, anchor: 99 }, rendered: ['dynamic-compose.yml'] } }[stage] || {}; const ok = !(stage === 'wipe' && h.name === failWipeOn); return JSON.stringify({ ok, stage, result, error: ok ? undefined : 'boom' }); } }; const records = []; - const r = { id: 'x1', network: 'devnet-moutai', steps: [], request: { network: 'devnet-moutai', images: { drive: 'dashpay/drive:2', dapi: 'dashpay/rs-dapi:2', tenderdash: 'dashpay/tenderdash:2' }, options: {} } }; + const r = { id: 'x1', network: 'devnet-moutai', steps: [], request: { network: 'devnet-moutai', images: { drive: 'dashpay/drive:2', dapi: 'dashpay/rs-dapi:2', tenderdash: 'dashpay/tenderdash:2' }, options: {genesisProtocolVersion:15} } }; const ctx = { step: () => () => {}, save: (x) => records.push(x.status), write: () => {} }; const reset = createReset({ ctx, dirs, pool, getSettings: () => settings }); await reset.prepareReset(r); diff --git a/agent/devnet-config.js b/agent/devnet-config.js index dfd6900..8cbc612 100644 --- a/agent/devnet-config.js +++ b/agent/devnet-config.js @@ -48,7 +48,7 @@ export function devnetFacts({ name, reg = {}, plan, record, lock, reset }) { seeds: [...hosts.filter((h) => h.role === 'wallet'), ...validators].filter((h) => h.publicIp).slice(0, 4).map((h) => `${h.publicIp}:${ports.coreP2P}`), }, platform: { - chainId: plan.platformChainId, initialProtocolVersion: plan.initialProtocolVersion, epochSeconds: plan.platformEpochSeconds || 3600, + chainId: plan.platformChainId, initialProtocolVersion: reset?.genesisProtocolVersion ?? plan.initialProtocolVersion, epochSeconds: plan.platformEpochSeconds || 3600, genesisTime: plan.genesisTime, quorums: PROFILE.quorums, tenderdashP2P: ports.tenderdashP2P, gatewayTls: plan.gatewayTls ? 'letsencrypt' : 'self-signed', dapi: validators.filter((h) => h.publicIp).map((h) => `https://${h.publicIp}:${ports.gateway}`), diff --git a/agent/devnet-config.test.js b/agent/devnet-config.test.js index f648582..910880f 100644 --- a/agent/devnet-config.test.js +++ b/agent/devnet-config.test.js @@ -59,7 +59,8 @@ test('the agent writes facts for live console devnets and rewrites them when the utimesSync(join(work, 'deployment.json'), new Date(), new Date(Date.now() + 5000)); refresh(); assert.equal(JSON.parse(readFileSync(out, 'utf8')).platform.epochSeconds, 600); - writeFileSync(join(work, 'platform-reset.json'), JSON.stringify({ anchor: { height: 9000 } })); + writeFileSync(join(work, 'platform-reset.json'), JSON.stringify({ anchor: { height: 9000 }, genesisProtocolVersion:15 })); refresh(); + assert.equal(JSON.parse(readFileSync(out, 'utf8')).platform.initialProtocolVersion,15); assert.equal(JSON.parse(readFileSync(out, 'utf8')).core.genesisCoreHeight, 9000, 'Connect follows verified reset anchor, not the original creation'); }); diff --git a/agent/devnet-keys-service.js b/agent/devnet-keys-service.js new file mode 100644 index 0000000..75a9686 --- /dev/null +++ b/agent/devnet-keys-service.js @@ -0,0 +1,2 @@ +import { startKeyService } from './devnet-keys.js'; +startKeyService({ dataDir: process.env.STATUS_DATA_DIR || '/data', privateDir: process.env.AGENT_PRIVATE_DIR || '/agent', socketPath: process.env.DEVNET_KEYS_SOCKET || '/key-access/keys.sock' }); diff --git a/agent/devnet-keys.js b/agent/devnet-keys.js new file mode 100644 index 0000000..6be5c03 --- /dev/null +++ b/agent/devnet-keys.js @@ -0,0 +1,100 @@ +// Separate on-demand service. No secret cache or files; pinned SSH only. +import { readFileSync, readdirSync, chmodSync, unlinkSync } from 'node:fs'; +import { join } from 'node:path'; +import { createServer } from 'node:http'; +import ssh2 from 'ssh2'; +import { mergeDevnets, validateSettings, operatorFor, readJSON } from '../shared/settings.js'; + +const REMOTE = readFileSync(new URL('./devnet-keys.py', import.meta.url), 'utf8'); +export function keyScope(dataDir, privateDir, name, user) { + if (!/^devnet-[a-z0-9-]+$/.test(name)) throw Error('scope'); + // Key access must fail closed on malformed settings, never inherit defaults. + const settings = mergeDevnets(validateSettings(JSON.parse(readFileSync(join(dataDir, 'settings.json'), 'utf8'))), readJSON(join(dataDir, 'devnets.json'), {})); + const n = settings.networks.find(n => n.name === name); + const reg = readJSON(join(dataDir, 'devnets.json'), {})[name]; + if (!n || n.kind !== 'dashnet' || n.chainType !== 'devnet' || !reg || reg.status !== 'ready' || !operatorFor(settings, user, name)) throw Error('scope'); + const ops = join(dataDir, 'ops'); + if (readdirSync(ops).filter(f => f.endsWith('.json')).some(f => { const r = readJSON(join(ops, f)); return r?.network === name && ['queued', 'preparing', 'confirmed', 'running', 'queued-run'].includes(r.status); })) throw Error('busy'); + const work = join(privateDir, 'devnets', name); + const plan = readJSON(join(work, 'deployment.json')); + const records = readdirSync(work).filter(f => /^deployed\..*\.json$/.test(f)).sort(); + const deployment = readJSON(join(work, records.at(-1) || 'missing'))?.deployment; + if (!plan || !deployment || deployment.planId !== plan.id || !plan.targets?.length) throw Error('deployment'); + const chain = plan.coreNetwork.startsWith('devnet-') ? plan.coreNetwork : `devnet-${plan.coreNetwork}`; + if (chain !== n.coreNetwork) throw Error('chain'); + const hosts = plan.targets.filter(t => ['validator', 'wallet'].includes(t.role)).map(t => ({ + name: t.name, role: t.role, instanceId: t.instanceId, publicIp: t.sshAddress || t.peerAddress, + proTxHash: deployment.nodes[t.name]?.proTxHash, operatorPublicKey: deployment.nodes[t.name]?.operatorPublicKey, platformNodeId: deployment.nodes[t.name]?.platformNodeId, + })); + const validators = hosts.filter(h => h.role === 'validator'); + if (!validators.length || hosts.filter(h => h.role === 'wallet').length !== 1 || validators.some(h => !h.proTxHash || !h.operatorPublicKey || !h.platformNodeId)) throw Error('identities'); + return { network: name, chain, hosts, validators, sporkAddress: deployment.sporkAddress, payoutAddress: deployment.payoutAddress, faucetAddress: reg.walletAddress }; +} + +export function readHost(host, request, privateDir) { + return new Promise((resolve, reject) => { + const pin = readJSON(join(privateDir, 'hostkeys.json'), {})[host.instanceId]; + if (!pin) return reject(Error('missing verified SSH pin')); + const client = new ssh2.Client(); + let done = false; + const finish = (err, value) => { if (done) return; done = true; clearTimeout(timer); client.end(); err ? reject(Error('Devnet key read or identity verification failed')) : resolve(value); }; + const timer = setTimeout(() => finish(Error('timeout')), 90_000); + client.on('error', () => finish(Error('ssh'))); + client.on('close', () => { if (!done) finish(Error('closed')); }); + client.on('ready', () => { + // JSON is shell-quoted; keys never appear in the command or request. + const arg = JSON.stringify({ ...request, host }).replace(/'/g, "'\\''"); + client.exec(`sudo -n python3 - '${arg}'`, (err, stream) => { + if (err) return finish(err); + let out = ''; + stream.on('data', chunk => { out += chunk; if (out.length > 1024 * 1024) { stream.close(); finish(Error('size')); } }); + stream.stderr.resume(); // never log a remote diagnostic + stream.on('close', code => { + if (code !== 0) return finish(Error('remote')); + try { finish(null, JSON.parse(out)); } catch { finish(Error('format')); } + }); + stream.end(REMOTE); + }); + }); + client.connect({ host: host.publicIp, username: 'ubuntu', privateKey: readFileSync(join(privateDir, 'id_ed25519')), readyTimeout: 12_000, + algorithms: { serverHostKey: [pin.type] }, hostVerifier: raw => raw.toString('base64') === pin.key }); + }); +} + +export async function collectKeys({ dataDir, privateDir, network, user, read = readHost }) { + const scope = keyScope(dataDir, privateDir, network, user); + const wallet = scope.hosts.find(h => h.role === 'wallet'); + const walletKeys = await read(wallet, scope, privateDir); + const rows = []; + for (let i = 0; i < scope.validators.length; i += 4) { + rows.push(...await Promise.all(scope.validators.slice(i, i + 4).map(async h => ({ + name: h.name, proTxHash: h.proTxHash, operatorPublicKey: h.operatorPublicKey, platformNodeId: h.platformNodeId, + ...walletKeys.validators[h.name], ...await read(h, scope, privateDir), + })))); + } + // Recheck grants and deployment identity after the slow SSH work. + if (JSON.stringify(keyScope(dataDir, privateDir, network, user)) !== JSON.stringify(scope)) throw Error('scope changed'); + return { network, chain: scope.chain, verifiedAt: new Date().toISOString(), validators: rows, networkKeys: walletKeys.networkKeys }; +} + +export function startKeyService({ dataDir, privateDir, socketPath }) { + let busy = false; + const server = createServer(async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + if (req.method !== 'POST' || req.url !== '/keys') { res.writeHead(404).end(); return; } + if (busy) { res.writeHead(409).end(); return; } + busy = true; + try { + let body = ''; + for await (const chunk of req) { body += chunk; if (body.length > 2048) throw Error('size'); } + const { network, user } = JSON.parse(body); + const result = await collectKeys({ dataDir, privateDir, network, user }); + res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(result)); + } catch { res.writeHead(503).end(JSON.stringify({ error: 'Keys unavailable: devnet must be idle and all identities must verify' })); } + finally { busy = false; } + }); + server.requestTimeout = 30_000; + try { unlinkSync(socketPath); } catch (e) { if (e.code !== 'ENOENT') throw e; } + server.listen(socketPath, () => chmodSync(socketPath, 0o600)); + return server; +} diff --git a/agent/devnet-keys.py b/agent/devnet-keys.py new file mode 100644 index 0000000..36950bb --- /dev/null +++ b/agent/devnet-keys.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python3 +"""Read-only, identity-checked devnet key export; stdout is private transport only.""" +import base64 +import json +from pathlib import Path +import subprocess +import sys +import urllib.request + + +def collect(q): + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + token = opener.open(urllib.request.Request('http://169.254.169.254/latest/api/token', method='PUT', headers={'X-aws-ec2-metadata-token-ttl-seconds': '60'}), timeout=5).read().decode() + instance = opener.open(urllib.request.Request('http://169.254.169.254/latest/meta-data/instance-id', headers={'X-aws-ec2-metadata-token': token}), timeout=5).read().decode() + assert instance == q['host']['instanceId'] + ids = subprocess.check_output(['docker', 'ps', '-q', '--filter', 'label=dashnet.node=' + q['host']['name']], timeout=10).decode().split() + assert ids + containers = json.loads(subprocess.check_output(['docker', 'inspect', *ids], timeout=10)) + assert any(c['Config'].get('Labels', {}).get('dashnet.network') == q['network'] and c['Name'].endswith('-core') for c in containers) + secret = json.loads(Path('/var/lib/dashnet/secrets.json').read_text()) + + def rpc(method, params=None, wallet=None): + auth = base64.b64encode(('dashnet:' + secret['rpcPassword']).encode()).decode() + req = urllib.request.Request('http://127.0.0.1:20002/' + ('wallet/' + wallet if wallet else ''), data=json.dumps({'jsonrpc': '1.0', 'id': 'key-export', 'method': method, 'params': params or []}).encode(), headers={'Authorization': 'Basic ' + auth, 'Content-Type': 'application/json'}) + with opener.open(req, timeout=20) as response: + data = json.load(response) + assert not data.get('error') + return data['result'] + + assert rpc('getblockchaininfo')['chain'] == q['chain'] + if q['host']['role'] == 'validator': + h = q['host'] + state = rpc('protx', ['info', h['proTxHash']])['state'] + assert state['pubKeyOperator'] == h['operatorPublicKey'] == secret['operatorPublicKey'] + assert state['platformNodeID'].lower() == h['platformNodeId'].lower() == secret['platformNodeID'].lower() + return {'operatorPrivateKey': secret['operatorPrivateKey'], 'platformNodePrivateKey': secret['nodePrivateKey']} + + assert q['host']['role'] == 'wallet' + keys = {} + for h in q['validators']: + info = rpc('protx', ['info', h['proTxHash']]) + state = info['state'] + assert state['pubKeyOperator'] == h['operatorPublicKey'] + assert state['platformNodeID'].lower() == h['platformNodeId'].lower() + fields = {'owner': state['ownerAddress'], 'voting': state['votingAddress'], 'collateral': info['collateralAddress']} + row = {} + for kind, address in fields.items(): + row[kind + 'Address'] = address + row[kind + 'PrivateKey'] = rpc('dumpprivkey', [address], 'dashnet') + keys[h['name']] = row + network = {} + for kind, address, wallet in [('spork', q.get('sporkAddress'), 'dashnet'), ('payout', q.get('payoutAddress'), 'dashnet'), ('faucet', q.get('faucetAddress'), 'faucet')]: + if address: + network[kind + 'Address'] = address + network[kind + 'PrivateKey'] = rpc('dumpprivkey', [address], wallet) + return {'validators': keys, 'networkKeys': network} + + +if __name__ == '__main__': + try: + request = json.loads(sys.argv[1]) + print(json.dumps(collect(request))) + except Exception: + # Never expose RPC bodies, subprocess errors or secret-bearing tracebacks. + print('Devnet key read or identity verification failed', file=sys.stderr) + sys.exit(1) diff --git a/agent/devnet-keys.test.js b/agent/devnet-keys.test.js new file mode 100644 index 0000000..03cb341 --- /dev/null +++ b/agent/devnet-keys.test.js @@ -0,0 +1,34 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { collectKeys, keyScope } from './devnet-keys.js'; +import { DEFAULT_SETTINGS } from '../shared/settings.js'; + +test('collector scopes identities, rejects busy/deleted networks and rechecks grants', async () => { + const root = mkdtempSync(join(tmpdir(), 'key-scope-')); + const dataDir = join(root, 'data'), privateDir = join(root, 'agent'), work = join(privateDir, 'devnets/devnet-sakura'); + mkdirSync(work, { recursive: true }); mkdirSync(join(dataDir, 'ops'), { recursive: true }); + const write = (path, value) => writeFileSync(path, JSON.stringify(value)); + const settings = { ...structuredClone(DEFAULT_SETTINGS), operators: [...DEFAULT_SETTINGS.operators, { id: 77, login: 'fixture', role: 'operator', networks: ['devnet-sakura'] }] }; + const settingsPath = join(dataDir, 'settings.json'), registryPath = join(dataDir, 'devnets.json'); + write(settingsPath, settings); write(registryPath, { 'devnet-sakura': { status: 'ready', coreNetwork: 'sakura' } }); + write(join(work, 'deployment.json'), { id: 'plan', coreNetwork: 'sakura', targets: [ + { name: 'v1', role: 'validator', instanceId: 'i-v1', sshAddress: '192.0.2.1' }, { name: 'w1', role: 'wallet', instanceId: 'i-w1', sshAddress: '192.0.2.2' }, + ] }); + write(join(work, 'deployed.1.json'), { deployment: { planId: 'plan', nodes: { v1: { proTxHash: 'tx', operatorPublicKey: 'pub', platformNodeId: 'node' } } } }); + const args = { dataDir, privateDir, network: 'devnet-sakura', user: { id: 77 } }; + try { + assert.equal(keyScope(dataDir, privateDir, args.network, args.user).validators.length, 1); + assert.throws(() => keyScope(dataDir, privateDir, '../sakura', args.user)); + assert.throws(() => keyScope(dataDir, privateDir, args.network, { id: 88 })); + const read = async host => host.role === 'wallet' ? { validators: { v1: { votingPrivateKey: 'fixture' } }, networkKeys: {} } : { operatorPrivateKey: 'fixture-bls' }; + const data = await collectKeys({ ...args, read }); assert.equal(data.validators[0].votingPrivateKey, 'fixture'); + write(join(dataDir, 'ops/running.json'), { network: args.network, status: 'running' }); + await assert.rejects(collectKeys({ ...args, read })); rmSync(join(dataDir, 'ops/running.json')); + await assert.rejects(collectKeys({ ...args, read: async (...a) => { const value = await read(...a); write(settingsPath, { ...settings, operators: DEFAULT_SETTINGS.operators }); return value; } })); + write(settingsPath, settings); write(registryPath, { 'devnet-sakura': { status: 'deleted' } }); + assert.throws(() => keyScope(dataDir, privateDir, args.network, args.user)); + } finally { rmSync(root, { recursive: true, force: true }); } +}); diff --git a/agent/devnets.js b/agent/devnets.js index 2e4923f..767b989 100644 --- a/agent/devnets.js +++ b/agent/devnets.js @@ -1,3 +1,4 @@ +import { reviewedRollout, rolloutArgs, rolloutFor, trackRollout } from '../shared/rollout.js'; // New devnets from the console, using the dash-network-go lifecycle: // // network.yaml -> resolve -> provision-plan (prepare; nothing billable) @@ -179,7 +180,7 @@ export function createDevnets({ ctx, dirs, key, pool, getSettings, region, log = if (!binary || !existsSync(binary) || !r.artifacts.bin || !dep) return; const p = spawnSync(binary, ['recipes'], { encoding: 'utf8', timeout: 10_000 }); let rec; try { rec = JSON.parse(p.stdout); } catch { return; } - if (rec.upgrade !== plan.recipeSha256 || rec.node !== dep.recipeSha256) return; + if (rec.upgrade !== plan.recipeSha256 || rec.node !== dep.recipeSha256 || (plan.rollout?.miningRecipe && rec.mining !== plan.rollout.miningRecipe)) return; const [was, now] = [versionOf(r.artifacts.bin), versionOf(binary)]; if (!dated(now) || (dated(was) && dated(was) >= dated(now))) return; copyFileSync(binary, `${r.artifacts.bin}.next`); chmodSync(`${r.artifacts.bin}.next`, 0o700); renameSync(`${r.artifacts.bin}.next`, r.artifacts.bin); @@ -211,7 +212,8 @@ export function createDevnets({ ctx, dirs, key, pool, getSettings, region, log = function runtimeOf(dir) { const file = existsSync(join(dir, 'network-current.yaml')) ? 'network-current.yaml' : 'network.yaml'; const images = existsSync(join(dir, file)) ? imagesOf(readFileSync(join(dir, file), 'utf8')) : {}; - return { images, dashmate: readJSON(join(dir, 'deployment.json'))?.profile === DASHMATE_PROFILE }; + const runtime = readJSON(join(dir, 'runtime-images.json')); + return { images, hostImages: runtime?.nodes || null, minerImage: runtime?.miner || null, dashmate: readJSON(join(dir, 'deployment.json'))?.profile === DASHMATE_PROFILE }; } for (const [name, reg] of Object.entries(registry())) { if (reg.status === 'deleted' || reg.images) continue; @@ -509,13 +511,13 @@ export function createDevnets({ ctx, dirs, key, pool, getSettings, region, log = // runtime that rollout recorded. const PLATFORM = ['drive', 'dapi', 'gateway', 'helper', 'tenderdash']; const phasesOf = (components) => [ - ...(components.includes('core') ? [{ scope: 'core', components: ['core'] }] : []), - ...(components.some((c) => PLATFORM.includes(c)) ? [{ scope: components.every((c) => c === 'tenderdash' || c === 'core') ? 'tenderdash' : 'platform', components: components.filter((c) => PLATFORM.includes(c)) }] : []), + ...(components.some((c) => c === 'core' || c === 'miner') ? [{ scope: 'core', components: components.filter((c) => c === 'core' || c === 'miner') }] : []), + ...(components.some((c) => PLATFORM.includes(c)) ? [{ scope: components.every((c) => c === 'tenderdash' || c === 'core' || c === 'miner') ? 'tenderdash' : 'platform', components: components.filter((c) => PLATFORM.includes(c)) }] : []), ]; function candidate(dir, base, components, images) { let yaml = readFileSync(base, 'utf8'); - for (const c of components) { + for (const c of components.filter((c) => c !== 'miner')) { const ref = images[c].startsWith('docker.io/') ? images[c] : `docker.io/${images[c]}`; const re = new RegExp(`^( ${c}: ).*$`, 'm'); if (!re.test(yaml)) throw new Error(`network definition has no ${c} image`); @@ -532,33 +534,61 @@ export function createDevnets({ ctx, dirs, key, pool, getSettings, region, log = await run(r, 'resolve', ['resolve', '--network', join(dir, a.candidate), '--out', join(dir, a.lock)], { timeoutMs: 5 * 60_000, bin: r.artifacts.bin }); done('ok', phase.components.map((c) => `${c} ${r.request.images[c]}`).join(', ')); done = step(r, `Upgrade plan, scope ${phase.scope} (dashnet upgrade-plan)`); - await run(r, 'upgrade-plan', ['upgrade-plan', '--deployment-plan', join(dir, 'deployment.json'), '--network', join(dir, a.candidate), '--lock', join(dir, a.lock), '--scope', phase.scope, '--out', join(dir, a.plan)], { timeoutMs: 5 * 60_000, bin: r.artifacts.bin }); + const args = ['upgrade-plan', '--deployment-plan', join(dir, 'deployment.json'), '--network', join(dir, a.candidate), '--lock', join(dir, a.lock), '--scope', phase.scope, '--out', join(dir, a.plan)]; + args.push(...rolloutArgs(rolloutFor(r.request))); + if (r.request.nodes?.length) args.push('--nodes', r.request.nodes.join(','), '--components', phase.components.join(',')); + if (phase.components.includes('miner')) args.push('--miner-image', r.request.images.miner); + if (phase.scope !== 'core' && r.request.options?.allowCoreConfigRestart) args.push('--allow-core-config-restart'); + await run(r, 'upgrade-plan', args, { timeoutMs: 5 * 60_000, bin: r.artifacts.bin }); const plan = readJSON(join(dir, a.plan)); + const miners = (plan.deployment?.targets || []).filter((t) => ['wallet', 'miner'].includes(t.role)).map((t) => t.name); + const rollout = reviewedRollout(plan, rolloutFor(r.request), miners); const changes = []; for (const [node, to] of Object.entries(plan.to || {})) for (const [component, pin] of Object.entries(to)) { const from = plan.from?.[node]?.[component]; if (from !== pin) changes.push({ node, component, from, to: pin, requested: r.request.images[component] || null, dependency: !phase.components.includes(component), phase: phase.scope }); } + if (plan.fromMinerImage !== plan.toMinerImage) changes.push({ node: plan.deployment?.targets?.find((t) => t.role === 'wallet' || t.role === 'miner')?.name, component: 'miner', from: plan.fromMinerImage, to: plan.toMinerImage, requested: r.request.images.miner || null, phase: phase.scope }); + if (r.request.nodes?.length && changes.some((c) => !r.request.nodes.includes(c.node))) throw new Error('native plan changes an unselected host'); + if (r.request.nodes?.length && changes.some((c) => !phase.components.includes(c.component))) throw new Error('native plan changes an unselected image component'); done('ok', `${changes.length} container change(s)`); - return { ...phase, ...a, planId: plan.id, changes }; + return { ...phase, ...a, planId: plan.id, changes, ...(rollout ? { rollout } : {}) }; } async function prepareUpgrade(r) { const name = r.network, dir = workDir(name); if (!existsSync(join(dir, 'deployment.json'))) throw new Error('devnet is not deployed yet'); + const dep = readJSON(join(dir, 'deployment.json')); + if (r.request.nodes?.length) { + const known = new Set((dep.targets || []).map((t) => t.name)); + if (r.request.nodes.some((n) => !known.has(n))) throw new Error('selected host is not in this deployment'); + } adoptCompatible(r, name); + if (rolloutFor(r.request) && (!supports(name, 'upgrade-plan', 'concurrency') || !supports(name, 'upgrade-plan', 'pause-mining'))) throw new Error('this devnet executor does not support rollout controls; a compatible dashnet update is required'); + if (r.request.nodes?.length && !supports(name, 'upgrade-plan', 'nodes')) throw new Error('this devnet binary does not support host-scoped upgrades'); + if (r.request.options?.allowCoreConfigRestart && !supports(name, 'upgrade-plan', 'allow-core-config-restart')) throw new Error('this devnet binary does not support coordinated Core config restarts'); + if (r.request.components.includes('miner') && !supports(name, 'upgrade-plan', 'miner-image')) throw new Error('this devnet binary does not support separate miner pins'); r.status = 'preparing'; r.artifacts = { ts: stamp() }; // The upgrade executes with exactly the binary that planned it, even if the // devnet adopts a newer one meanwhile (upgrade plans bind its recipe). r.artifacts.bin = join(dir, `dashnet.upgrade-${r.artifacts.ts}`); copyFileSync(join(dir, 'dashnet'), r.artifacts.bin); chmodSync(r.artifacts.bin, 0o700); save(r); - const phases = phasesOf(r.request.components); + // A selected validator's combined migration is one native host unit: + // target helper render -> Core config/image -> Platform images. + const combined = r.request.options?.allowCoreConfigRestart === true + && r.request.components.includes('core') && r.request.components.includes('helper'); + if (combined && (!r.request.nodes?.length || r.request.components.includes('miner') + || r.request.nodes.some((name) => dep.targets.find((t) => t.name === name)?.role !== 'validator'))) { + throw new Error('combined Core/Platform migration requires named validators only'); + } + const phases = combined ? [{ scope: 'platform', components: r.request.components }] + : phasesOf(r.request.components); // The first phase is planned exactly now; a later one after its predecessor. const first = await planPhase(r, dir, phases[0], 0); r.artifacts.phases = [first, ...phases.slice(1)]; const later = phases.slice(1).map((p) => ({ scope: p.scope, components: p.components, images: Object.fromEntries(p.components.map((c) => [c, r.request.images[c]])) })); - r.review = { planId: first.planId, operation: 'upgrade', scope: phases.map((p) => p.scope).join(' + '), changes: first.changes, then: later, + r.review = { ...(first.rollout ? { rollout: first.rollout } : {}), planId: first.planId, operation: 'upgrade', scope: phases.map((p) => p.scope).join(' + '), changes: first.changes, then: later, targets: [...new Set(first.changes.map((c) => c.node))], preparedAt: new Date().toISOString() }; } @@ -574,23 +604,27 @@ export function createDevnets({ ctx, dirs, key, pool, getSettings, region, log = const plan = readJSON(join(dir, phase.plan)); if (!plan || plan.id !== phase.planId || (n === 0 && plan.id !== r.review?.planId)) throw new Error('reviewed upgrade plan missing'); refreshSnapshot(r, dir, plan); - const who = plan.scope === 'core' ? 'every node one at a time (Core: validators, then the mining node)' : 'validators one at a time'; + const who = plan.rollout ? `batches of up to ${plan.rollout.concurrency} nodes (miner last, separately)` : r.request.nodes?.length ? `selected hosts: ${r.request.nodes.join(', ')}` : plan.scope === 'core' ? 'every node one at a time (Core: validators, then the mining node)' : 'validators one at a time'; const done = step(r, `Upgrade ${who} (dashnet upgrade, scope ${plan.scope})`); r.progress = { phase: plan.scope, completed: [], current: null }; save(r); // A Core rollout visits every node and may wait up to a DKG cycle for its // quiet window; every node's health check needs two samples. - const d = readJSON(join(dir, 'request.json')), nodes = readJSON(join(dir, 'deployment.json'))?.targets?.length || 14; + const d = readJSON(join(dir, 'request.json')), nodes = r.request.nodes?.length || readJSON(join(dir, 'deployment.json'))?.targets?.length || 14; const window = observeSeconds(d); const minutes = plan.scope === 'core' ? Math.max(240, Math.ceil((nodes * (26 * blockSeconds(d) + 420 + window)) / 60)) : Math.max(110, Math.ceil((nodes * (2 * window + 180)) / 60)); await run(r, 'upgrade', ['upgrade', '--plan', join(dir, phase.plan), '--confirm', plan.id, ...access(dir), '--observation-window', `${window}s`, '--timeout', `${minutes}m`, '--out', join(dir, `upgrade-result.${stamp()}.json`)], { timeoutMs: (minutes + 1) * 60_000, bin: r.artifacts.bin, onLine: (line) => { - const m = /((?:validators|wallet|miner|fullnodes?)-\d+)/.exec(line); + trackRollout(r.progress, line, true); + save(r); + const m = plan.rollout ? null : /((?:validators|wallet|miner|fullnodes?)-\d+)/.exec(line); if (m && /appl|withdraw|replac|upgrad/i.test(line)) { r.progress.current = m[1]; if (/complete|done|verified|upgraded/i.test(line) && !r.progress.completed.includes(m[1])) r.progress.completed.push(m[1]); save(r); } }, }); - // The network file now carries this phase's images for later operations. - writeFileSync(join(dir, 'network-current.yaml'), readFileSync(join(dir, phase.candidate)), { mode: 0o600 }); + // A scoped candidate is NOT a fleet default. The native runtime journal + // retains exact host pins; publish the reviewed successful per-host map. + if (!r.request.nodes?.length) writeFileSync(join(dir, 'network-current.yaml'), readFileSync(join(dir, phase.candidate)), { mode: 0o600 }); + writeAtomic(join(dir, 'runtime-images.json'), JSON.stringify({ nodes: plan.to, miner: plan.toMinerImage || null, operation: r.id, planId: plan.id })); register(name, runtimeOf(dir)); r.done.push(`phase-${n}`); save(r); done('ok'); diff --git a/agent/ops.js b/agent/ops.js index bfc29a2..4ef19b5 100644 --- a/agent/ops.js +++ b/agent/ops.js @@ -2,6 +2,7 @@ // // The web process may only create request files; this module owns operation // records, logs and every dashnet artifact. One operation runs per network. +import { reviewedRollout, rolloutArgs, rolloutFor, trackRollout } from '../shared/rollout.js'; import { spawn } from 'node:child_process'; import { randomUUID } from 'node:crypto'; import { appendFileSync, chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; @@ -19,7 +20,8 @@ const IMAGE = (component) => new RegExp(`^(docker\\.io/)?${COMPONENT_REPOS[compo export function manifestFor(settings, network, state) { const targets = [], excluded = []; for (const h of state?.hosts || []) { - if (!['validator', 'masternode', 'seed'].includes(h.role) || h.duplicate) continue; + const miner = network.chainType === 'testnet' && ['miner-1', 'miner-2'].includes(h.name) && h.role === 'miner'; + if ((!['validator', 'masternode', 'seed'].includes(h.role) && !miner) || h.duplicate) continue; const why = h.state !== 'running' ? h.state : !h.publicIp ? 'no public address' : !h.tagged ? `missing ${settings.aws.tagKey} tag` : null; const containers = h.probe?.data?.containers || h.lastGood?.data?.containers; if (why || !containers) { excluded.push({ name: h.name, reason: why || 'not yet probed' }); continue; } @@ -29,11 +31,11 @@ export function manifestFor(settings, network, state) { if (component && !map[component]) map[component] = c.name; } let chosen = map; - if (h.role === 'masternode') chosen = map.core ? { core: map.core } : null; + if (h.role === 'masternode' || miner) chosen = map.core ? { core: map.core } : null; if (h.role === 'seed') chosen = map.tenderdash ? Object.fromEntries(['core', 'tenderdash'].filter((c) => map[c]).map((c) => [c, map[c]])) : null; if (h.role === 'validator' && !['core', 'drive', 'tenderdash', 'dapi', 'gateway'].every((c) => map[c])) chosen = null; if (!chosen) { excluded.push({ name: h.name, reason: 'expected containers not found' }); continue; } - targets.push({ name: h.name, instanceId: h.instanceId, address: h.publicIp, architecture: h.arch, role: h.role, containers: chosen }); + targets.push({ name: h.name, instanceId: h.instanceId, address: h.publicIp, architecture: h.arch, role: miner ? 'core' : h.role, ...(miner ? { miningService: 'dashd-generate-miner.service' } : {}), containers: chosen }); } return { manifest: { @@ -71,8 +73,10 @@ export function validateRequest(settings, q, registry = {}) { return { lifecycle: true }; } const network = settings.networks.find((n) => n.name === q.network); + const rollout = rolloutFor(q); + if (rollout && !['testnet', 'devnet'].includes(network?.chainType)) throw new Error('rollout controls support Testnet and devnets only'); if (network?.kind === 'dashnet') { - // Console devnets: dash-network-go native upgrade (all validators) and doctor. + // Native devnets support explicitly scoped rollouts; empty nodes retains the legacy fleet scope. if (!['upgrade', 'doctor'].includes(q.action)) throw new Error('console devnets support upgrade and health check'); if (!registry[q.network] || registry[q.network].status !== 'ready') throw new Error('devnet is not ready'); const components = q.components || [], images = q.images || {}; @@ -81,13 +85,20 @@ export function validateRequest(settings, q, registry = {}) { // dashnet upgrades a network-ready deployment only. if (['starting', 'stopped'].includes(registry[q.network].platform)) throw new Error('Platform has not started on this devnet yet; upgrade once its Platform operation has finished'); const core = (registry[q.network].upgradeScopes || []).includes('core'); - const allowed = ['drive', 'dapi', 'gateway', 'helper', 'tenderdash', ...(core ? ['core'] : [])]; + const allowed = ['drive', 'dapi', 'gateway', 'helper', 'tenderdash', ...(core ? ['core', 'miner'] : [])]; + if (!Array.isArray(q.nodes || []) || (q.nodes || []).length > 200 || new Set(q.nodes || []).size !== (q.nodes || []).length || !(q.nodes || []).every((n) => /^[a-z][a-z0-9-]{0,62}$/.test(n))) throw new Error('nodes must be a unique list of host names'); + if (q.options?.allowCoreConfigRestart !== undefined && typeof q.options.allowCoreConfigRestart !== 'boolean') throw new Error('allowCoreConfigRestart must be boolean'); + if ((components.includes('miner') || q.options?.allowCoreConfigRestart) && !q.nodes?.length) throw new Error('miner pins and Core config restarts require explicit nodes'); + if (q.options?.allowCoreConfigRestart && !components.some((c) => ['drive', 'dapi', 'helper', 'tenderdash', 'gateway'].includes(c))) throw new Error('Core config restart applies to Platform upgrades only'); if (components.includes('core') && !core) throw new Error('this devnet was created with a dash-network-go that cannot upgrade Core; devnets created since Core upgrades landed can'); if (!components.length || components.some((c) => !allowed.includes(c)) || new Set(components).size !== components.length) throw new Error(`select from ${allowed.join(', ')}`); - for (const c of components) if (!IMAGE(c).test(images[c] || '')) throw new Error(`${c}: image must be ${COMPONENT_REPOS[c]}: or @sha256:`); + for (const c of components) { + const repository = c === 'miner' ? 'core' : c; + if (!IMAGE(repository).test(images[c] || '') || (c === 'miner' && !/@sha256:[0-9a-f]{64}$/.test(images[c] || ''))) throw new Error(`${c}: image must be ${COMPONENT_REPOS[repository]}${c === 'miner' ? '@sha256:' : ': or @sha256:'}`); + } if (Object.keys(images).some((c) => !components.includes(c))) throw new Error('image for an unselected component'); } else if (components.length) throw new Error('components apply to upgrade only'); - return { network, native: true, components, images }; + return { network, native: true, components, images, rollout }; } if (!network?.deployable) throw new Error('network is not deployable'); if (!ACTIONS.has(q.action)) throw new Error('unsupported action'); @@ -104,7 +115,7 @@ export function validateRequest(settings, q, registry = {}) { const window = q.options?.observationWindow || network.observationWindow; const timeout = q.options?.timeout || network.operationTimeout; if (!d.test(window) || !d.test(timeout)) throw new Error('durations look like 4m / 110m'); - return { network, window, timeout, components, images }; + return { network, window, timeout, components, images, rollout }; } export function createOps({ settings: getSettings, dirs, key, pool, binary, onChange = () => {}, log = console.log, spawnImpl = spawn, devnetsImpl }) { @@ -183,7 +194,10 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh async function prepare(r) { const s = getSettings(); - const { network, components, images } = validateRequest(s, r.request); + const { network, components, images, rollout } = validateRequest(s, r.request); + const miners = rollout?.pauseMining ? ['miner-1', 'miner-2'] : []; + if (miners.length && network.chainType !== 'testnet') throw new Error('managed mining controls require legacy Testnet; native devnets use their deployment miner'); + const required = [...new Set([...r.request.nodes, ...miners])]; // Each preparation gets fresh artifacts; dashnet never overwrites outputs. r.attempt = (r.attempt || 0) + 1; const dir = join(work, r.id, String(r.attempt)); mkdirSync(dir, { recursive: true, mode: 0o700 }); @@ -193,7 +207,7 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh const state = await readState(network.name); const { manifest, excluded } = manifestFor(s, network, state); const names = new Set(manifest.targets.map((t) => t.name)); - const missing = r.request.nodes.filter((n) => !names.has(n)); + const missing = required.filter((n) => !names.has(n)); if (missing.length) { done('failed'); throw new Error(`not operable: ${missing.map((n) => `${n} (${excluded.find((e) => e.name === n)?.reason || 'unknown'})`).join(', ')}`); } writeFileSync(join(dir, 'manifest.json'), JSON.stringify(manifest, null, 1), { mode: 0o600 }); writeFileSync(join(dir, 'known_hosts'), pool.knownHosts(manifest.targets.map((t) => ({ instanceId: t.instanceId }))), { mode: 0o600 }); @@ -205,14 +219,16 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh const code = await dashnet(r, ['managed-import', '--manifest', join(dir, 'manifest.json'), ...access(dir), '--timeout', '6m', '--out', join(dir, 'snapshot.json')], { timeoutMs: 7 * 60_000 }); const snapshot = readJSON(join(dir, 'snapshot.json')); if (!snapshot) { done('failed'); throw new Error('import produced no snapshot'); } - const unavailable = r.request.nodes.filter((n) => { const o = snapshot.nodes?.[n]; return !o || o.error || o.problems?.length; }); + const unavailable = required.filter((n) => { const o = snapshot.nodes?.[n]; return !o || o.error || o.problems?.length; }); done(code === 0 ? 'ok' : 'warn', code === 0 ? `snapshot ${snapshot.id.slice(0, 12)}` : 'some unselected targets incomplete'); if (unavailable.length) throw new Error(`selected nodes not observable: ${unavailable.map((n) => `${n}: ${snapshot.nodes?.[n]?.error || snapshot.nodes?.[n]?.problems?.join(', ') || 'missing'}`).join('; ')}`); if (r.request.action === 'doctor') return { dir, snapshot, manifest }; + done = step(r, 'Read management journal'); const journal = await journalFor(dir); + done('ok', journal ? `phase ${journal.record.phase}` : 'not enrolled'); const enrolled = new Set(Object.entries(journal?.record?.enrolled || {}).filter(([n, v]) => v && (!journal.record.instances || journal.record.instances[n] === manifest.targets.find((t) => t.name === n)?.instanceId)).map(([n]) => n)); - const toEnroll = r.request.nodes.filter((n) => !enrolled.has(n)); + const toEnroll = required.filter((n) => !enrolled.has(n)); if (toEnroll.length) { done = step(r, `Enroll ${toEnroll.length} node(s) (no restarts)`); const c = await dashnet(r, ['managed-enroll', '--snapshot', join(dir, 'snapshot.json'), '--confirm', snapshot.id, '--nodes', toEnroll.join(','), ...access(dir), '--timeout', '15m', '--out', join(dir, 'enroll.json')], { timeoutMs: 16 * 60_000, onLine: parseRunner(r) }); @@ -226,30 +242,45 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh const explicit = Object.fromEntries(Object.entries(images).map(([c, ref]) => [c, ref.startsWith('docker.io/') ? ref : `docker.io/${ref}`])); writeFileSync(join(dir, 'images.json'), JSON.stringify(explicit), { mode: 0o600 }); const planArgs = ['managed-plan', '--snapshot', join(dir, 'snapshot.json'), '--operation', r.request.action, '--scope', components.join(','), '--nodes', r.request.nodes.join(','), '--timeout', '5m', '--out', join(dir, 'plan.json')]; - if (r.request.action === 'upgrade') planArgs.push('--images', join(dir, 'images.json')); + if (r.request.action === 'upgrade') planArgs.push('--images', join(dir, 'images.json'), ...rolloutArgs(rollout, miners)); const pc = await dashnet(r, planArgs, { timeoutMs: 6 * 60_000 }); const plan = readJSON(join(dir, 'plan.json')); if (pc !== 0 || !plan) { done('failed'); throw new Error('planning failed; see log'); } + const reviewed = reviewedRollout(plan, rollout, miners); const changes = []; for (const [node, pins] of Object.entries(plan.images || {})) for (const [component, to] of Object.entries(pins)) { const before = snapshot.nodes[node]?.components?.[component] || {}; changes.push({ node, component, from: before.image, fromDigest: before.digests?.[0]?.split('@')[1] || null, to, requested: images[component] || null, dependency: !components.includes(component) }); } done('ok', `${changes.length} container change(s)`); - r.review = { planId: plan.id, snapshotId: snapshot.id, changes, targets: r.request.nodes, operation: plan.operation, preparedAt: new Date().toISOString() }; + r.review = { ...(reviewed ? { rollout: reviewed } : {}), planId: plan.id, snapshotId: snapshot.id, changes, targets: r.request.nodes, operation: plan.operation, preparedAt: new Date().toISOString() }; return { dir, snapshot, manifest, plan }; } async function journalFor(dir) { const out = join(dir, `journal-${randomUUID()}.json`); - const code = await new Promise((resolve) => { - const child = spawnImpl(binary, ['managed-operation', '--manifest', join(dir, 'manifest.json'), '--timeout', '1m', '--out', out], { stdio: 'ignore' }); - const timer = setTimeout(() => child.kill('SIGKILL'), 90_000); - child.on('close', (c) => { clearTimeout(timer); resolve(c ?? 1); }); child.on('error', () => { clearTimeout(timer); resolve(1); }); - }); - const v = code === 0 ? readJSON(out) : null; - rmSync(out, { force: true }); - return v; + try { + const result = await new Promise((resolve) => { + const child = spawnImpl(binary, ['managed-operation', '--manifest', join(dir, 'manifest.json'), '--timeout', '1m', '--out', out], { stdio: ['ignore', 'ignore', 'pipe'], env: { ...process.env, AWS_REGION: getSettings().aws.region } }); + let stderr = '', timedOut = false; + child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-2000); }); + const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, 90_000); + child.on('close', (code) => { clearTimeout(timer); resolve({ code, stderr, timedOut }); }); + child.on('error', (e) => { clearTimeout(timer); resolve({ code: null, stderr: e.message }); }); + }); + // Only the CLI's exact missing-record sentinel permits first enrollment. + // Validation, cloud and runner failures must not masquerade as lost enrollment. + if (result.code === 1 && result.stderr.trim() === 'dashnet: operation not found') return null; + if (result.code !== 0) { + const detail = result.timedOut ? 'timed out' : result.stderr.trim().split('\n').pop()?.slice(0, 300) || `exit ${result.code}`; + throw new Error(`Cannot read management journal: ${detail}. Stopping before enrollment or workload changes.`); + } + const v = readJSON(out); + if (!v?.record || !v.record.enrolled || typeof v.record.enrolled !== 'object' || Array.isArray(v.record.enrolled)) { + throw new Error('Cannot read management journal: invalid result. Stopping before enrollment or workload changes.'); + } + return v; + } finally { rmSync(out, { force: true }); } } const parseRunner = (r) => (line) => { @@ -276,10 +307,8 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh parseRunner(r)(line); const p = r.progress; if (/^managed-(staging|applying|verifying)$/.test(line)) p.phase = line.slice(8); - let m = /^managed target (\S+) applying$/.exec(line); - if (m) p.current = m[1]; - m = /^managed target (\S+) applied$/.exec(line); - if (m) { p.completed.push(m[1]); p.current = null; } + trackRollout(p, line); + let m; m = /^managed health gate waiting: (.*)$/.exec(line); p.waiting = m ? m[1].slice(0, 300) : undefined; // A replaced node may take minutes to serve again (a new Core can migrate @@ -289,8 +318,8 @@ export function createOps({ settings: getSettings, dirs, key, pool, binary, onCh if (/^managed target \S+ (ready|applied)$/.test(line)) p.starting = undefined; save(r); }; - // The configured timeout is a per-node budget: nodes are replaced one at a - // time, each behind its own startup wait and fleet health gate. + // Keep the historical upper time budget for slow first-start migrations; + // new plan-bound batches use readiness, not fixed inter-node windows. const budget = operationBudget(timeout, r.review?.targets?.length || r.request.nodes.length); const c = await dashnet(r, [`managed-${plan.operation}`, '--plan', join(dir, 'plan.json'), '--confirm', plan.id, ...access(dir), '--observation-window', window, '--timeout', budget.flag, '--out', join(dir, `result-${Date.now()}.json`)], { timeoutMs: budget.ms + 60_000, onLine }); if (r.progress.starting) { r.progress.starting = undefined; save(r); } diff --git a/agent/reset-dashnet.py b/agent/reset-dashnet.py index 509d938..079aac6 100644 --- a/agent/reset-dashnet.py +++ b/agent/reset-dashnet.py @@ -2,7 +2,7 @@ """Platform-only reset of a dashnet-owned dashmate deployment. Renders the reviewed target release before wiping; the controller owns the -fenced dashnet journal transition. Epoch and protocol settings are preserved. Only the two chain-data volumes are +fenced dashnet journal transition. Epoch settings are preserved; genesis PV can be selected explicitly. Only the two chain-data volumes are removed; Core, Tor, logs, certificates and all non-Platform containers stay. """ import base64 @@ -85,6 +85,13 @@ def __init__(self, q, root=Path('/var/lib/dashnet'), state_root=Path('/var/lib/d self.config = self.home / self.node self.td = self.config / 'platform/drive/tenderdash' + def genesis_protocol(self, genesis): + version = self.q.get('genesisProtocolVersion') + if version is not None: + need(type(version) is int and 1 <= version <= 0xffffffff, 'invalid Platform version (PV)') + genesis['consensus_params']['version']['app_version'] = str(version) + return genesis + def all_containers(self): ids = run(['docker', 'ps', '-aq']).split() return json.loads(run(['docker', 'inspect', *ids])) if ids else [] @@ -213,7 +220,7 @@ def journal_baseline(self): images.update({k: owned[s]['Config']['Image'] for k, s in components.items() if s in owned}) marker = read(self.root / 'upgrade.json') if (self.root / 'upgrade.json').exists() else None need(not marker or marker.get('phase') == 'applied', 'unfinished native upgrade on host') - return {'images': images, 'previousId': marker.get('id', '') if marker else '', 'preservation': { + return {'images': images, 'previousId': marker.get('id', '') if marker else '', 'markerEvidence': {'phase': marker.get('phase'), 'images': marker.get('to')} if marker else None, 'preservation': { 'coreId': core['Id'], 'coreStarted': core['State']['StartedAt'], 'coreConfig': hashlib.sha256(self.normalized(path, path.read_bytes(), doc)).hexdigest(), 'coreGenesis': self.rpc('getblockhash', 1), @@ -252,7 +259,7 @@ def baseline(self): return b b = {'project': owned['core']['Config']['Labels']['com.docker.compose.project'], 'coreServices': {name: {'id': v['Id'], 'image': v['Config']['Image'], 'mounts': v['Mounts']} for name, v in owned.items() if name in ['core', 'core_tor']}, 'preserve': self.snapshot(), 'volumes': self.data_volumes(owned), 'height': info['blocks'], 'platform': {s: {'id': c['Id'], 'image': c['Config']['Image']} for s, c in owned.items() if s in PLATFORM}, - 'images': images, 'epochTime': epoch, 'anchor': read(self.td / 'genesis.json')['initial_core_chain_locked_height'], + 'images': images, 'genesisProtocolVersion': int(read(self.td / 'genesis.json')['consensus_params']['version']['app_version']), 'epochTime': epoch, 'anchor': read(self.td / 'genesis.json')['initial_core_chain_locked_height'], 'dashmate': (self.home / '.version').read_text().strip(), 'configFormatVersion': doc.get('configFormatVersion'), 'tor': {'enabled': c['core']['tor']['enabled']}, 'configHash': digest(self.home / 'config.json'), 'helper': images['helper'], 'journal': self.journal_baseline()} @@ -334,16 +341,26 @@ def core_changes(before, after): @staticmethod def core_compatibility_options(old, new): # Comments/spacing are not configuration changes. Everything outside - # release-owned RPC compatibility directives must remain identical. + # release-owned compatibility directives must remain identical. beta.5 + # adds exactly this loopback onion listener; never allow arbitrary bind + # changes, removals or duplicate listeners through the RPC migration gate. semantic = lambda data: [line.strip() for line in data.splitlines() if line.strip() and not line.lstrip().startswith(b'#')] strip = lambda data: [line for line in semantic(data) if not line.startswith((b'rpcwhitelist=', b'deprecatedrpc='))] - need(strip(old) == strip(new), 'Core migration changed preserved chain, data, credentials or network settings') + previous, desired = strip(old), strip(new) + onion = b'bind=127.0.0.1=onion' + changes = [] + if previous.count(onion) != desired.count(onion): + need(previous.count(onion) == 0 and desired.count(onion) == 1, + 'Core migration changed preserved chain, data, credentials or network settings') + desired = [line for line in desired if line != onion] + changes.append({'option': 'bind', 'added': ['127.0.0.1=onion'], 'removed': []}) + need(previous == desired, 'Core migration changed preserved chain, data, credentials or network settings') options = lambda data: sorted(line.decode().partition('=')[2] for line in semantic(data) if line.startswith(b'deprecatedrpc=')) before, after = options(old), options(new) if before == after: - return [] + return changes need(all(re.fullmatch('[a-zA-Z0-9_,.-]+', value) for value in after), 'invalid Core compatibility option') - return [{'option': 'deprecatedrpc', 'added': sorted(set(after) - set(before)), 'removed': sorted(set(before) - set(after))}] + return changes + [{'option': 'deprecatedrpc', 'added': sorted(set(after) - set(before)), 'removed': sorted(set(before) - set(after))}] def miner(self): need(self.q['role'] in ['wallet', 'miner'], 'mining control requires the deployment mining node') @@ -587,6 +604,7 @@ def release(self): entry['docker']['image'] = self.desired()[component] c['platform']['drive']['abci']['epochTime'] = b['epochTime'] c['platform']['drive']['tenderdash']['genesis']['initial_core_chain_locked_height'] = self.q['anchorHeight'] + self.genesis_protocol(c['platform']['drive']['tenderdash']['genesis']) write(stage / 'config.json', doc) self.helper(stage, 'render') need(read(stage / 'config.json') == doc, 'renderer changed configured target') @@ -606,10 +624,11 @@ def render(self): rel = Path(self.node) / 'platform/drive/tenderdash' old, new = read(self.td / 'genesis.json'), read(stage / rel / 'genesis.json') old['initial_core_chain_locked_height'] = self.q['anchorHeight'] - need(old == new, 'genesis changed beyond the anchor') + self.genesis_protocol(old) + need(old == new, 'genesis changed beyond reviewed anchor/protocol') need(digest(self.td / 'node_key.json') == digest(stage / rel / 'node_key.json'), 'node identity changed') # Hashes use dashnet's exact Platform service/content fingerprint - # algorithm; migrate Core/Tor fingerprints only for reviewed RPC changes. + # algorithm; migrate Core/Tor fingerprints only for reviewed compatibility changes. overrides = read(stage / '.dashnet-compose.json') for service, ref in self.q.get('sidecars', {}).items(): need(service in overrides['services'], 'unknown sidecar') @@ -623,7 +642,7 @@ def render(self): if name in live: need(services[name] == live[name], 'target release changes Core Compose service') # Keep salted credentials byte-identical; only the target release's - # reviewed RPC access/compatibility lines may change in Core's config. + # reviewed compatibility lines may change in Core's config. core_files = [] for path in (self.config / 'core').rglob('*'): if path.is_file(): @@ -637,7 +656,8 @@ def render(self): need(path.name == 'dash.conf', 'unexpected Core file migration') # Release templates also select Core RPC compatibility flags # (beta.2 restores deprecated masternode service/port fields). - # No chain, wallet, image, auth or network directive may move. + # The exact beta.5 loopback onion addition is also reviewed; + # all other chain, wallet, image, auth and network lines stay. release['coreMigration'].extend(self.core_compatibility_options(old_bytes, new_bytes)) auth = [line for line in path.read_bytes().splitlines(keepends=True) if line.startswith(b'rpcauth=')] lines = iter(auth) @@ -665,14 +685,15 @@ def render(self): entry.append(fingerprints['core']) fingerprints[name] = hashlib.sha256(json.dumps(entry, sort_keys=True).encode()).hexdigest() overrides['services'][name]['labels']['dashnet.config'] = fingerprints[name] + need(not self.q.get('requireUnchangedCore') or not release['coreMigration'], 'Core migration forbidden by reset preservation gate') if not release['coreMigration']: for name in ['core', 'core_tor']: if name in live: need(fingerprints[name] == live[name]['labels']['dashnet.config'], 'preserved Core fingerprint differs') write(stage / '.dashnet-compose.json', overrides) self.preserved(b) - write(self.state / 'prepared.json', {'anchor': self.q['anchorHeight'], 'coreMigration': release['coreMigration'], 'coreFiles': core_files, 'coreFingerprints': {s: fingerprints[s] for s in ['core', 'core_tor'] if s in fingerprints}, 'images': self.desired(), 'platform': {s: {'image': services[s]['image']} for s in b['platform']}, 'files': {str(p.relative_to(stage)): digest(p) for p in stage.rglob('*') if p.is_file()}}) - return {'checks': {'coreSectionUnchanged': not bool(release['coreMigration']), 'coreChainPreserved': True, 'coreMigration': release['coreMigration'], 'nodeKeyUnchanged': True, 'genesisOnlyAnchorChanged': True, + write(self.state / 'prepared.json', {'anchor': self.q['anchorHeight'], 'genesisProtocolVersion': self.q.get('genesisProtocolVersion'), 'coreMigration': release['coreMigration'], 'coreFiles': core_files, 'coreFingerprints': {s: fingerprints[s] for s in ['core', 'core_tor'] if s in fingerprints}, 'images': self.desired(), 'platform': {s: {'image': services[s]['image']} for s in b['platform']}, 'files': {str(p.relative_to(stage)): digest(p) for p in stage.rglob('*') if p.is_file()}}) + return {'checks': {'coreSectionUnchanged': not bool(release['coreMigration']), 'coreChainPreserved': True, 'coreMigration': release['coreMigration'], 'nodeKeyUnchanged': True, 'genesisOnlyAnchorChanged': self.q.get('genesisProtocolVersion') is None, 'genesisProtocolVersion': int(new['consensus_params']['version']['app_version']), 'anchor': self.q['anchorHeight'], 'epochTime': b['epochTime'], 'epochEnv': b['epochTime'], 'genesisChainId': new['chain_id']}, 'images': self.desired(), 'rendered': ['Target release Platform configuration and Compose templates', 'dashnet reset anchor and identity record']} def prewipe(self): @@ -683,6 +704,8 @@ def prewipe(self): self.preserved(b) need((self.state / 'prepared.json').is_file(), 'canary missing') prepared = read(self.state / 'prepared.json') + need(not self.q.get('requireUnchangedCore') or not prepared.get('coreMigration'), 'Core migration forbidden by reset preservation gate') + need(prepared.get('genesisProtocolVersion', self.q.get('genesisProtocolVersion')) == self.q.get('genesisProtocolVersion'), 'reviewed Platform version changed') need(prepared['images'] == self.desired(), 'reviewed target images changed') for rel, value in prepared['files'].items(): need(digest(self.state / 'render' / rel) == value, 'prepared files changed') @@ -718,6 +741,7 @@ def apply(self): stage = self.state / 'render' prepared = read(self.state / 'prepared.json') need(not prepared.get('coreMigration') or (self.state / 'baseline-effective.json').exists(), 'required Core migration has not completed') + need(prepared.get('genesisProtocolVersion', self.q.get('genesisProtocolVersion')) == self.q.get('genesisProtocolVersion'), 'reviewed Platform version changed') need(prepared['anchor'] == self.q['anchorHeight'], 'prepared anchor changed') for rel, value in prepared['files'].items(): need(digest(stage / rel) == value, 'prepared files changed') @@ -734,6 +758,7 @@ def apply(self): dst.write_bytes((stage / rel).read_bytes()) inputs = read(self.root / 'platform/inputs.json') inputs['genesisCoreHeight'] = self.q['anchorHeight'] + inputs['initialProtocolVersion'] = int(read(self.td / 'genesis.json')['consensus_params']['version']['app_version']) write(self.root / 'platform/inputs.json', inputs) write(self.root / 'platform/identity.json', {name: digest(self.td / name) for name in ['genesis.json', 'node_key.json']}) self.preserved(b) @@ -779,7 +804,9 @@ def verify(self): sync = result.get('result', result)['sync_info'] need(int(sync['latest_block_height']) > 0 and sync['catching_up'] is False, 'Platform consensus not ready') need(self.rpc('masternode','status').get('state') == 'READY', 'masternode not READY') - need(read(self.td / 'genesis.json')['initial_core_chain_locked_height'] == self.q['anchorHeight'], 'wrong reset anchor') + genesis = read(self.td / 'genesis.json') + need(genesis == self.genesis_protocol(copy.deepcopy(genesis)), 'wrong reset Platform version') + need(genesis['initial_core_chain_locked_height'] == self.q['anchorHeight'], 'wrong reset anchor') env = dict(x.split('=',1) for x in owned['drive_abci']['Config']['Env'] if '=' in x) cfg_epoch = read(self.home / 'config.json')['configs'][self.node]['platform']['drive']['abci']['epochTime'] parsed = run(['docker', 'exec', owned['drive_abci']['Id'], 'drive-abci', 'config'], timeout=60) @@ -789,7 +816,7 @@ def verify(self): need(self.rpc('mnsync', 'status').get('IsSynced') and not self.rpc('getblockchaininfo').get('initialblockdownload'), 'Core not synchronized') tls = run(['curl','-s','-o','/dev/null','-w','%{http_code}','--max-time','10',f'https://{self.q["address"]}:1443/']).strip() need(tls == '405', 'DAPI TLS not ready') - return {'consensus': {'height': int(sync['latest_block_height'])}, 'epochs': {'config': b['epochTime'], 'env': env['EPOCH_TIME_LENGTH_S'], 'parsed': int(match.group(1))}, + return {'genesisProtocolVersion': int(genesis['consensus_params']['version']['app_version']), 'consensus': {'height': int(sync['latest_block_height'])}, 'epochs': {'config': b['epochTime'], 'env': env['EPOCH_TIME_LENGTH_S'], 'parsed': int(match.group(1))}, 'core': {'chainPreserved': True, 'configurationMigrated': bool(prepared.get('coreMigration'))}, 'restarts': {s:c['RestartCount'] for s,c in owned.items() if s in PLATFORM and c['RestartCount']}} diff --git a/agent/reset-journal.js b/agent/reset-journal.js index bd00b01..8078cc4 100644 --- a/agent/reset-journal.js +++ b/agent/reset-journal.js @@ -21,6 +21,20 @@ export function candidateYaml(yaml, images) { } return yaml; } +export function resolutionNetwork(network, images) { + const result = clone(network); + result.nodes = result.nodes.filter((g) => g.role === 'validator'); + need(result.nodes.length > 0, 'no validator groups to resolve'); + if (result.aws?.provision?.amis) { + const arches = new Set(result.nodes.map((g) => g.architecture)); + result.aws.provision.amis = Object.fromEntries(Object.entries(result.aws.provision.amis).filter(([arch]) => arches.has(arch))); + } + for (const [c, ref] of Object.entries(images)) { + need(RESET_COMPONENTS.includes(c), 'resolution outside Platform images'); + result.images[c] = `docker.io/${ref.replace(/^(?:index\.)?docker\.io\//, '')}`; + } + return result; +} export function transitionRecord(original, plan, id, desired, observations, at) { const record = clone(original), from = original.runtime?.images || Object.fromEntries(plan.targets.map((t) => [t.name, Object.fromEntries(t.images.map((i) => [i.component, i.pinned]))])); const baseline = {}, completed = {}; @@ -28,13 +42,14 @@ export function transitionRecord(original, plan, id, desired, observations, at) const actual = observations[t.name]; need(actual && hash(actual.images) === hash(from[t.name]), `installed images differ from dashnet journal on ${t.name}`); // Native Platform upgrades stage the wallet helper without an upgrade marker. - need(actual.previousId === (original.runtime?.upgradeId || '') || (t.role !== 'validator' && !actual.previousId), `native upgrade marker differs on ${t.name}`); + const scopedMarker = /^[a-f0-9]{64}$/.test(actual.previousId || '') && actual.markerEvidence?.phase === 'applied' && hash(actual.markerEvidence.images) === hash(actual.images); + need(scopedMarker || actual.previousId === (original.runtime?.upgradeId || '') || (t.role !== 'validator' && !actual.previousId), `native upgrade marker differs on ${t.name}`); need(desired[t.name].core === from[t.name].core, 'reset attempted to change Core'); baseline[t.name] = actual.preservation; if (t.role === 'validator') completed[t.name] = false; } const sidecars = original.runtime?.sidecars || original.deployment.sidecars; - record.runtime = { deploymentId: plan.id, upgradeId: id, images: clone(from), ...(sidecars ? { sidecars } : {}) }; + record.runtime = { ...(original.runtime || {}), deploymentId: plan.id, upgradeId: id, images: clone(from), ...(sidecars ? { sidecars } : {}) }; record.upgrade = { planId: id, previousId: original.runtime?.upgradeId || '', phase: 'applying', from, to: desired, baseline, completed, observedAt: at, ...(sidecars ? { sidecars } : {}) }; record.revision++; record.updatedAt = at; record.lastRunner = 'status-platform-reset-' + id; delete record.lastError; return record; @@ -81,7 +96,9 @@ export function createResetJournal({ dirs, ctx, client }) { const candidate = join(dir(r), 'candidate.yaml'), lockPath = file(r, 'candidate-lock'); writeAtomic(candidate, yaml, 0o600); if (Object.keys(images).length) { - need(await ctx.dashnet(r, ['resolve', '--network', candidate, '--out', lockPath], { bin: join(work(r), 'dashnet'), timeoutMs: 15 * 60_000 }) === 0, 'target image resolution failed'); + const resolution = join(dir(r), 'candidate-resolve.json'); + writeAtomic(resolution, JSON.stringify(resolutionNetwork(d.n, images)), 0o600); + need(await ctx.dashnet(r, ['resolve', '--network', resolution, '--out', lockPath], { bin: join(work(r), 'dashnet'), timeoutMs: 15 * 60_000 }) === 0, 'target image resolution failed'); const lock = readJSON(lockPath); for (const t of d.plan.targets.filter((t) => t.role === 'validator')) for (const c of Object.keys(images)) { const image = lock.images.find((i) => i.component === c), platform = image?.platforms.find((p) => p.architecture === t.architecture && p.os === 'linux'); @@ -89,7 +106,7 @@ export function createResetJournal({ dirs, ctx, client }) { desired[t.name][c] = image.pinned.split('@')[0] + '@' + platform.digest; } } - r.nativePlanId = hash([r.execId || r.id, d.plan.id, snapshot.data.revision, desired]); + r.nativePlanId = hash([r.execId || r.id, d.plan.id, snapshot.data.revision, desired, r.genesisProtocolVersion ?? null]); r.nativeImages = Object.fromEntries(d.plan.targets.filter((t) => t.role === 'validator').map((t) => [t.name, Object.fromEntries(RESET_COMPONENTS.map((c) => [c, desired[t.name][c]]))])); r.nativeArchitectures = Object.fromEntries(d.plan.targets.map((t) => [t.name, t.architecture])); store(r, 'target-images', desired); @@ -153,7 +170,7 @@ export function createResetJournal({ dirs, ctx, client }) { const path = join(dirs.data, 'devnets.json'), registry = readJSON(path, {}); registry[r.network] = { ...registry[r.network], images:imagesOf(yaml), updatedAt:next.updatedAt }; writeAtomic(path, JSON.stringify(registry)); - writeAtomic(join(work(r), 'platform-reset.json'), JSON.stringify({ operation:r.id, anchor:r.anchor, verifiedAt:next.updatedAt }), 0o600); + writeAtomic(join(work(r), 'platform-reset.json'), JSON.stringify({ operation:r.id, anchor:r.anchor, ...(r.review?.platformVersion?.next != null ? { genesisProtocolVersion:r.review.platformVersion.next } : {}), verifiedAt:next.updatedAt }), 0o600); if (current.item.Owner) { const d = db(r); await d.client.send(new UpdateItemCommand({ TableName:d.TableName, Key:d.Key, UpdateExpression:'REMOVE #owner', ConditionExpression:'#owner = :owner AND #plan = :plan AND #rev = :rev', diff --git a/agent/reset-journal.test.js b/agent/reset-journal.test.js index 83bb0d1..57a8b08 100644 --- a/agent/reset-journal.test.js +++ b/agent/reset-journal.test.js @@ -8,7 +8,7 @@ import { resetSidecars } from './reset-images.js'; const pin = (repo, char='a') => `index.docker.io/dashpay/${repo}@sha256:${char.repeat(64)}`; const beforeImages = {core:pin('dashd'), drive:pin('drive'), dapi:pin('rs-dapi'), tenderdash:pin('tenderdash'), gateway:pin('envoy'), helper:pin('dashmate-helper')}; const preservation = { coreId:'a'.repeat(64),coreStarted:'2026-10-06T00:00:00Z',coreConfig:'b'.repeat(64),coreGenesis:'c'.repeat(64),containers:Object.fromEntries(['drive','dapi','gateway','tenderdash'].map((c)=>[c,'d'.repeat(64)])),restarts:{drive:0,dapi:0,gateway:0,tenderdash:0} }; -const plan = {id:'d'.repeat(64),profile:'devnet-dashmate-compose',bootstrap:{compute:{id:'e'.repeat(64),network:{metadata:{name:'devnet-test'},aws:{region:'us-west-2',accountId:'123456789012',provision:{stateTable:'networks'}}}}},targets:[{name:'validator-1',role:'validator',architecture:'arm64',images:Object.entries(beforeImages).map(([component,pinned])=>({component,pinned}))},{name:'wallet-1',role:'wallet',architecture:'amd64',images:['core','helper'].map((component)=>({component,pinned:beforeImages[component]}))}]}; +const plan = {id:'d'.repeat(64),profile:'devnet-dashmate-compose',bootstrap:{compute:{id:'e'.repeat(64),network:{nodes:[{role:'validator',architecture:'arm64'}],images:beforeImages,metadata:{name:'devnet-test'},aws:{region:'us-west-2',accountId:'123456789012',provision:{stateTable:'networks'}}}}},targets:[{name:'validator-1',role:'validator',architecture:'arm64',images:Object.entries(beforeImages).map(([component,pinned])=>({component,pinned}))},{name:'wallet-1',role:'wallet',architecture:'amd64',images:['core','helper'].map((component)=>({component,pinned:beforeImages[component]}))}]}; const observed = Object.fromEntries(plan.targets.map((t)=>[t.name,{ images:Object.fromEntries([...t.images].reverse().map((i)=>[i.component,i.pinned])),previousId:'',preservation }])); const original = {revision:4,deployment:{planId:plan.id,phase:'network-ready',sidecars:[],genesisCoreHeight:100}}; function setup(t) { @@ -110,3 +110,18 @@ test('prepare again preserves previous immutable artifacts and resume uses the s await journal.begin(r); assert.equal(JSON.parse(item().Data.S).upgrade.planId,r.nativePlanId); }); + +test('reset PV is bound into native transition identity and verified Connect receipt',async(t)=>{ + const {journal,r,work,item}=setup(t); + r.genesisProtocolVersion=15; + await journal.prepare(r,{}); + const pv15=r.nativePlanId; + r.genesisProtocolVersion=16; + await journal.prepare(r,{}); + assert.notEqual(r.nativePlanId,pv15); + journal.seal(r,observed,[]); + r.review={platformVersion:{next:16}}; + await journal.begin(r); await journal.complete(r); + assert.equal(JSON.parse(readFileSync(join(work,'platform-reset.json'),'utf8')).genesisProtocolVersion,16); + assert.equal(item().Owner,undefined); +}); diff --git a/agent/reset-native.test.js b/agent/reset-native.test.js index e607e53..2ca5ad0 100644 --- a/agent/reset-native.test.js +++ b/agent/reset-native.test.js @@ -14,6 +14,16 @@ test('dashnet reset is devnet-only and accepts Platform target versions but pres assert.throws(() => validateReset(settings, { network: 'devnet-sakura', options: { epochSeconds: 1 } }), /preserves epoch/); }); +test('reset PV is an optional uint32 for native and managed devnets, never a silently ignored value', () => { + for (const kind of ['dashnet', 'managed']) { + const settings = { networks: [{ name:'devnet-test', chainType:'devnet', kind }] }; + const q = { network:'devnet-test', images:{drive:'dashpay/drive:new',dapi:'dashpay/rs-dapi:new',tenderdash:'dashpay/tenderdash:new'} }; + for (const pv of [1, 14, 15, 4294967295]) assert.doesNotThrow(() => validateReset(settings, {...q,options:{genesisProtocolVersion:pv}})); + for (const pv of [0,-1,1.5,'15',true,4294967296]) assert.throws(() => validateReset(settings,{...q,options:{genesisProtocolVersion:pv}}), /Platform version/); + assert.doesNotThrow(() => validateReset(settings,q)); + } +}); + test('native reset binds every deployed validator, canaries all, excludes wallet, and refuses replacement hosts', async (t) => { const root = mkdtempSync(join(tmpdir(), 'native-reset-')); t.after(() => rmSync(root, { recursive: true, force: true })); @@ -33,10 +43,11 @@ test('native reset binds every deployed validator, canaries all, excludes wallet assert.equal(q.node, host.name); assert.match(script, /class Reset:/); assert.equal(q.epochSeconds, null); + assert.equal(q.genesisProtocolVersion, 15); assert.deepEqual(q.images, {}); calls.push([stage, host.name]); return JSON.stringify({ ok: fail !== `${stage}:${host.name}`, result: { - ...({ release: { sidecars:{} }, baseline: { images: { drive: 'installed@sha256:123' }, epochTime: 3600, height: 100, anchor: 10, dashmate: '5.0.0-beta.1', configFormatVersion: '5.0.0', tor: { enabled: true } }, anchor: { height: 99, hash: 'ab' }, canary: { checks: { coreSectionUnchanged: true }, rendered: [] } }[stage] || {}), + ...({ release: { sidecars:{} }, baseline: { images: { drive: 'installed@sha256:123' }, genesisProtocolVersion: 14, epochTime: 3600, height: 100, anchor: 10, dashmate: '5.0.0-beta.1', configFormatVersion: '5.0.0', tor: { enabled: true } }, anchor: { height: 99, hash: 'ab' }, canary: { checks: { coreSectionUnchanged: true, genesisProtocolVersion:15 }, rendered: [] } }[stage] || {}), } }); } }; const ctx = { step: () => () => {}, save: () => {}, write: () => {} }; @@ -47,10 +58,11 @@ test('native reset binds every deployed validator, canaries all, excludes wallet if (!checkOnly && fail === 'explorer') throw Error('Explorer not caught up'); return {installed:true,indexed:8,chain:8}; }, ctx, dirs, pool, journalImpl, getSettings: () => ({ networks: [{ name, chainType: 'devnet', coreNetwork: name, kind: 'dashnet' }] }) }); - const record = () => ({ id: 'native-reset-test', network: name, request: { network: name, action: 'platform-reset' } }); + const record = () => ({ id: 'native-reset-test', network: name, request: { network: name, action: 'platform-reset', options:{genesisProtocolVersion:15} } }); const r = record(); await reset.prepareReset(r); assert.equal(r.review.native, true); + assert.deepEqual(r.review.platformVersion,{current:[14],next:15}); assert.equal(r.review.epoch.next, 3600); assert.deepEqual(calls.filter(([s]) => s === 'canary').map(([, h]) => h), ['validators-001', 'validators-002']); assert.ok(!calls.some(([s]) => ['wipe','apply','start'].includes(s))); diff --git a/agent/reset-remote.py b/agent/reset-remote.py index 04f1bba..d243d47 100644 --- a/agent/reset-remote.py +++ b/agent/reset-remote.py @@ -34,6 +34,14 @@ def need(cond, msg): raise Fail(msg) +def genesis_protocol(genesis): + version = Q.get('genesisProtocolVersion') + if version is not None: + need(type(version) is int and 1 <= version <= 0xffffffff, 'invalid Platform version (PV)') + genesis['consensus_params']['version']['app_version'] = str(version) + return genesis + + def run(args, timeout=300, env=None, cwd=None, check=True, user=None, secret=False): if user: args = ['sudo', '-H', '-u', user, *(['env'] + [f'{k}={v}' for k, v in (env or {}).items()] if env else []), *args] @@ -176,6 +184,7 @@ def baseline(): dashmate=run(['dashmate', '--version'], user='dashmate', cwd='/home/dashmate').strip(), platform=platform_containers(), images=dict(drive=conf['platform']['drive']['abci']['docker']['image'], dapi=conf['platform']['dapi']['rsDapi']['docker']['image'], tenderdash=conf['platform']['drive']['tenderdash']['docker']['image']), + genesisProtocolVersion=int(json.loads((DM_HOME / CFG / 'platform/drive/tenderdash/genesis.json').read_text())['consensus_params']['version']['app_version']), epochTime=conf['platform']['drive']['abci'].get('epochTime'), anchor=conf['platform']['drive']['tenderdash']['genesis'].get('initial_core_chain_locked_height')) else: @@ -187,7 +196,7 @@ def baseline(): td = inspect('tenderdash') or next((x for x in containers() if 'tenderdash' in x['Config']['Image']), None) genesis = json.loads((SEED / 'tenderdash' / 'config' / 'genesis.json').read_text()) out.update(dataDir=seed_dir_meta(), compose=sha(SEED_COMPOSE), tenderdashImage=td['Config']['Image'] if td else None, tenderdashId=td['Id'] if td else None, - genesisChainId=genesis.get('chain_id'), anchor=genesis.get('initial_core_chain_locked_height'), + genesisChainId=genesis.get('chain_id'), genesisProtocolVersion=int(genesis['consensus_params']['version']['app_version']), anchor=genesis.get('initial_core_chain_locked_height'), nodeKey=sha(SEED / 'tenderdash' / 'config' / 'node_key.json')) save_json('baseline.json', out) return out @@ -245,6 +254,7 @@ def _render(base, apply_back): p['drive']['tenderdash']['docker']['image'] = Q['images']['tenderdash'] p['drive']['tenderdash']['genesis']['initial_core_chain_locked_height'] = int(Q['anchorHeight']) p['drive']['abci']['epochTime'] = int(Q['epochSeconds']) + genesis_protocol(p['drive']['tenderdash']['genesis']) (home / 'config.json').write_text(json.dumps(doc, indent=2)) os.lchown(home / 'config.json', dm.pw_uid, dm.pw_gid) run(['dashmate', 'config', 'render', f'--config={CFG}'], user='dashmate', env=env, cwd='/home/dashmate', timeout=300) @@ -270,9 +280,10 @@ def _render(base, apply_back): live_key, new_key = [json.loads((root / td / 'node_key.json').read_text()) for root in (DM_HOME, home)] need(live_key == new_key, 'rendered Tenderdash node key differs from the live node key') live_g, new_g = [json.loads((root / td / 'genesis.json').read_text()) for root in (DM_HOME, home)] + genesis_protocol(live_g) changed = sorted(k for k in set(live_g) | set(new_g) if k != 'initial_core_chain_locked_height' and live_g.get(k) != new_g.get(k)) need(not changed, f'rendered genesis changes more than the anchor: {changed}') - checks.update(nodeKeyUnchanged=True, genesisChainId=new_g.get('chain_id'), genesisOnlyAnchorChanged=True) + checks.update(nodeKeyUnchanged=True, genesisChainId=new_g.get('chain_id'), genesisOnlyAnchorChanged=Q.get('genesisProtocolVersion') is None, genesisProtocolVersion=int(new_g['consensus_params']['version']['app_version'])) rendered = [] for tpl in sorted(Path('/usr/lib/dashmate/templates/platform').rglob('*.dot')): rel = Path('platform') / tpl.relative_to('/usr/lib/dashmate/templates/platform').with_suffix('') @@ -354,6 +365,7 @@ def apply(): genesis_path = SEED / 'tenderdash' / 'config' / 'genesis.json' g = json.loads(genesis_path.read_text()) g['initial_core_chain_locked_height'] = int(Q['anchorHeight']) + genesis_protocol(g) tmp = genesis_path.with_name('.genesis.json.tmp') st = genesis_path.stat() tmp.write_text(json.dumps(g, indent=2)) @@ -402,6 +414,8 @@ def verify(): sync = core_cli(c, 'mnsync', 'status') out = dict(core=dict(unchanged=True, id=ident['id'][:12], synced=bool(sync.get('IsSynced')), height=info['blocks'])) genesis = json.loads(((DM_HOME / CFG / 'platform' / 'drive' / 'tenderdash') if ROLE == 'hpmn' else (SEED / 'tenderdash' / 'config')).joinpath('genesis.json').read_text()) + need(genesis == genesis_protocol(json.loads(json.dumps(genesis))), 'wrong reset Platform version') + out['genesisProtocolVersion'] = int(genesis['consensus_params']['version']['app_version']) out['anchor'] = genesis.get('initial_core_chain_locked_height') need(int(out['anchor'] or 0) == int(Q['anchorHeight']), f"live genesis anchor {out['anchor']}, expected {Q['anchorHeight']}") if ROLE == 'seed': diff --git a/agent/reset.js b/agent/reset.js index 230af58..766bcef 100644 --- a/agent/reset.js +++ b/agent/reset.js @@ -24,7 +24,10 @@ const IMAGE = Object.fromEntries(Object.entries(REPOS).map(([c, repo]) => [c, ne export function validateReset(settings, q) { const n = settings.networks.find((x) => x.name === q.network); if (!n || n.chainType !== 'devnet' || n.kind === 'external') throw new Error('Platform reset applies to dashmate-managed devnets'); + const pv = q.options?.genesisProtocolVersion; + if (pv != null && (!Number.isInteger(pv) || pv < 1 || pv > 0xffffffff)) throw new Error('Platform version (PV) must be an integer from 1 to 4294967295'); if (n.kind === 'dashnet') { + for (const key of ['requireUnchangedCore', 'preserveExplorer']) if (q.options?.[key] != null && typeof q.options[key] !== 'boolean') throw new Error(`${key} must be boolean`); if (q.options?.epochSeconds != null) throw new Error('native reset preserves epoch settings'); const images = q.images || {}; for (const [c, ref] of Object.entries(images)) if (!RESET_COMPONENTS.includes(c) || !IMAGE[c].test(ref)) throw Error(`${c}: invalid Platform image reference`); @@ -51,7 +54,7 @@ export function createReset({ ctx, dirs, pool, getSettings, journalImpl, explore const dir = join(dirs.private, 'resets', r.execId || r.id); mkdirSync(dir, { recursive: true, mode: 0o700 }); // A re-prepare gets a new execution id, so the baseline is retaken. - const base = { config: r.network, exec: r.execId || r.id, coreChain: r.review?.coreChain || r.coreChain, images: r.request.images, epochSeconds: r.epoch, ...extra }; + const base = { config: r.network, exec: r.execId || r.id, coreChain: r.review?.coreChain || r.coreChain, genesisProtocolVersion:r.genesisProtocolVersion ?? r.request.options?.genesisProtocolVersion, requireUnchangedCore:r.request.options?.requireUnchangedCore === true, images: r.request.images, epochSeconds: r.epoch, ...extra }; r.stages ??= {}; r.stages[name] ??= {}; const results = await mapLimit(hosts, parallel, async (h) => { @@ -83,6 +86,7 @@ export function createReset({ ctx, dirs, pool, getSettings, journalImpl, explore async function prepareReset(r) { const { network, epoch, images } = validateReset(getSettings(), r.request); r.native = network.kind === 'dashnet'; + r.genesisProtocolVersion = r.request.options?.genesisProtocolVersion; r.epoch = epoch; r.coreChain = network.coreNetwork; r.status = 'preparing'; save(r); const all = targets(r.network); @@ -123,6 +127,7 @@ export function createReset({ ctx, dirs, pool, getSettings, journalImpl, explore const canary = canaries[0]; if (r.native) { r.coreMigrations = Object.fromEntries(hpmns.map((h,i) => [h.name, canaries[i].result.checks.coreMigration || []])); + if (r.request.options?.requireUnchangedCore && Object.values(r.coreMigrations).some((c) => c.length)) throw Error('Core migration forbidden by reset preservation gate'); if (Object.values(r.coreMigrations).some((c) => c.length)) { const miners = nativePlan.targets.filter((t) => t.role === 'miner' || t.role === 'wallet'); if (miners.length !== 1) throw Error('automatic Core migration requires one identified native mining host'); @@ -134,7 +139,7 @@ export function createReset({ ctx, dirs, pool, getSettings, journalImpl, explore } if (r.native) { const wallet = nativePlan.targets.find((t) => t.role === 'wallet'); - if (wallet) { + if (wallet && !r.request.options?.preserveExplorer) { const done = step(r, 'Check managed Explorer ownership and database'); r.explorer = await explorer({ pool, target:wallet, network:r.network, chain:nativePlan.platformChainId || `dash-${r.coreChain}`, checkOnly:true }); done('ok', r.explorer?.installed ? 'Old index will be backed up and rebuilt for the new chain' : 'No managed Explorer installed'); @@ -145,7 +150,8 @@ export function createReset({ ctx, dirs, pool, getSettings, journalImpl, explore const sb = base.filter((_, i) => all[i].resetRole === 'seed').map((x) => x.result); const uniq = (xs) => [...new Set(xs.map((x) => JSON.stringify(x ?? null)))].map((x) => JSON.parse(x)); r.review = { - kind: 'platform-reset', planId: `reset-${r.id}-${r.anchor.height}`, preparedAt: new Date().toISOString(), coreChain: network.coreNetwork, + kind: 'platform-reset', genesisProtocolVersion:r.request.options?.genesisProtocolVersion, requireUnchangedCore:r.request.options?.requireUnchangedCore === true, preserveExplorer:r.request.options?.preserveExplorer === true, planId: `reset-${r.id}-${r.anchor.height}`, preparedAt: new Date().toISOString(), coreChain: network.coreNetwork, + platformVersion: { current: uniq(hb.map((x) => x.genesisProtocolVersion)), next: canary.result.checks.genesisProtocolVersion ?? r.genesisProtocolVersion ?? null }, targets: r.targets, hpmns: hpmns.length, seeds: seeds.length, anchor: r.anchor, previousAnchor: uniq(hb.map((x) => x.anchor)), explorer: r.explorer, native: r.native, coreMigrationMode: r.native ? 'parallel-v1' : undefined, coreMigrations: r.coreMigrations, targetImages: r.nativeImages, requested: r.resolvedChoices, current: uniq(hb.map((x) => x.images)), next: r.native ? r.nativeImages[hpmns[0].name] : r.request.images, epoch: { current: uniq(hb.map((x) => x.epochTime)), next: r.native ? hb[0].epochTime : epoch }, dashmate: uniq(hb.map((x) => x.dashmate)), configFormat: uniq(hb.map((x) => x.configFormatVersion)), tor: uniq(hb.map((x) => x.tor?.enabled)), @@ -204,6 +210,7 @@ export function createReset({ ctx, dirs, pool, getSettings, journalImpl, explore } async function executeReset(r) { + if (r.request.options?.requireUnchangedCore && (r.minerTarget || Object.values(r.coreMigrations || {}).some((c) => c.length))) throw Error('Core migration or miner pause forbidden by reset preservation gate'); const discovered = targets(r.network); const all = r.native ? discovered : discovered.filter((h) => r.targets.some((t) => t.name === h.name)); if (all.length !== r.targets.length || all.some((h) => !r.targets.some((t) => t.name === h.name && t.ip === h.publicIp && (!t.instanceId || t.instanceId === h.instanceId) && t.role === h.resetRole))) throw new Error(`targets changed since review: expected ${r.targets.map((t) => t.name).join(', ')}`); @@ -283,7 +290,7 @@ export function createReset({ ctx, dirs, pool, getSettings, journalImpl, explore if (r.native) { const plan = readJSON(join(dirs.private, 'devnets', r.network, 'deployment.json')); const wallet = plan.targets.find((t) => t.role === 'wallet'); - if (wallet) { + if (wallet && !r.request.options?.preserveExplorer) { const done = step(r, 'Reconcile Explorer index with the new Platform chain'); try { r.result.explorer = await explorer({ pool, target:wallet, network:r.network, chain:plan.platformChainId || `dash-${r.coreChain}`, anchor:r.anchor.height }); diff --git a/agent/test_reset_dashnet.py b/agent/test_reset_dashnet.py index a530fb3..a92ee99 100644 --- a/agent/test_reset_dashnet.py +++ b/agent/test_reset_dashnet.py @@ -23,6 +23,20 @@ def setUp(self): 'config': 'devnet-sakura', 'anchorHeight': 123}, self.root / 'host', self.root / 'state') self.r.state.mkdir(parents=True) + def test_pv_override_is_explicit_and_only_changes_genesis_app_version(self): + genesis = {'chain_id':'same','consensus_params':{'version':{'app_version':'14'},'block':{'max_bytes':'123'}}} + original = json.loads(json.dumps(genesis)) + self.assertEqual(self.r.genesis_protocol(genesis), original) + self.r.q['genesisProtocolVersion'] = 15 + result = self.r.genesis_protocol(genesis) + self.assertEqual(result['consensus_params']['version']['app_version'], '15') + original['consensus_params']['version']['app_version'] = '15' + self.assertEqual(result, original) + for pv in [0, -1, True, '15', 15.5, 4294967296]: + self.r.q['genesisProtocolVersion'] = pv + with self.assertRaisesRegex(mod.Fail, 'Platform version'): + self.r.genesis_protocol(genesis) + def containers(self): return {s: {'Id': s, 'Mounts': [{'Type': 'volume', 'Name': s+'-volume', 'Destination': d}]} for s,d in mod.DATA_MOUNTS.items()} @@ -69,7 +83,7 @@ def test_apply_keeps_core_ssl_and_writes_continuity_metadata(self): 'config.json': '{}', '.envs': 'UNCHANGED=1', '.dashnet-compose.json': '{}', 'validators-001/core/dash.conf': 'rendered salted core', 'validators-001/platform/gateway/ssl/private.key': 'not-a-real-key-staged', - 'validators-001/platform/drive/tenderdash/genesis.json': '{"initial_core_chain_locked_height":123}', + 'validators-001/platform/drive/tenderdash/genesis.json': '{"initial_core_chain_locked_height":123,"consensus_params":{"version":{"app_version":"15"}}}', 'validators-001/platform/drive/tenderdash/node_key.json': '{"test":"identity"}', } for name, data in files.items(): @@ -87,7 +101,7 @@ def test_apply_keeps_core_ssl_and_writes_continuity_metadata(self): self.r.apply() self.assertEqual(core.read_text(), 'live exact core') self.assertEqual(ssl.read_text(), 'live mock certificate key') - self.assertEqual(mod.read(self.r.root / 'platform/inputs.json'), {'genesisCoreHeight':123,'peers':['same']}) + self.assertEqual(mod.read(self.r.root / 'platform/inputs.json'), {'genesisCoreHeight':123,'initialProtocolVersion':15,'peers':['same']}) self.assertEqual(mod.read(self.r.root / 'platform/identity.json'), {n:mod.digest(self.r.td/n) for n in ['genesis.json','node_key.json']}) (stage / '.envs').write_text('tampered') with patch.object(self.r, 'baseline_record', return_value={}), patch.object(self.r, 'preserved'): diff --git a/agent/test_reset_pv.py b/agent/test_reset_pv.py new file mode 100644 index 0000000..7e00c8f --- /dev/null +++ b/agent/test_reset_pv.py @@ -0,0 +1,53 @@ +"""Managed reset PV at the filesystem boundary; no Docker or live hosts.""" +import ast +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock + + +class ManagedPVTests(unittest.TestCase): + def setUp(self): + source = Path(__file__).with_name('reset-remote.py').read_text() + tree = ast.parse(source) + tree.body = [n for n in tree.body if isinstance(n, (ast.Import, ast.ImportFrom, ast.FunctionDef, ast.ClassDef))] + self.ns = {'DM_HOME':Path('/fixture')} + exec(compile(tree, '', 'exec'), self.ns) + self.ns['Q'] = {'genesisProtocolVersion':15, 'anchorHeight':123, 'images':{'tenderdash':'dashpay/tenderdash:new'}} + + def test_optional_pv_and_invalid_values(self): + genesis = {'chain_id':'preserved','consensus_params':{'version':{'app_version':'14'}}} + self.ns['Q'].pop('genesisProtocolVersion') + self.assertEqual(self.ns['genesis_protocol'](genesis)['consensus_params']['version']['app_version'],'14') + self.ns['Q']['genesisProtocolVersion'] = 15 + self.assertEqual(self.ns['genesis_protocol'](genesis)['consensus_params']['version']['app_version'],'15') + for pv in [0, -1, True, '15', 1.5, 4294967296]: + self.ns['Q']['genesisProtocolVersion'] = pv + with self.assertRaisesRegex(self.ns['Fail'],'Platform version'): + self.ns['genesis_protocol'](genesis) + + def test_seed_apply_matches_validator_pv_preserving_identity_and_other_genesis_fields(self): + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + config = root / 'tenderdash/config' + config.mkdir(parents=True) + genesis = {'chain_id':'preserved','genesis_time':'preserved','initial_core_chain_locked_height':1, + 'consensus_params':{'version':{'app_version':'14'},'block':{'max_bytes':'123'}}} + (config/'genesis.json').write_text(json.dumps(genesis)) + (config/'node_key.json').write_text('{"fixture":"same"}') + compose = root/'docker-compose.yml' + compose.write_text('services:\n tenderdash:\n image: dashpay/tenderdash:old\n') + self.ns.update(ROLE='seed',SEED=root,SEED_COMPOSE=compose, + load_json=lambda _: {'nodeKey':self.ns['sha'](config/'node_key.json')},preserved=Mock()) + self.ns['apply']() + result = json.loads((config/'genesis.json').read_text()) + genesis['initial_core_chain_locked_height'] = 123 + genesis['consensus_params']['version']['app_version'] = '15' + self.assertEqual(result,genesis) + self.assertIn('dashpay/tenderdash:new',compose.read_text()) + self.ns['preserved'].assert_called_once() + + +if __name__ == '__main__': + unittest.main() diff --git a/deploy/deploy.sh b/deploy/deploy.sh index 058d1bf..77444dc 100755 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -12,6 +12,11 @@ rev=$(git rev-parse HEAD) dashnet_ref=${DASHNET_REF:-$(git ls-remote https://github.com/dashpay/dash-network-go refs/heads/main | cut -f1)} echo "building status ${rev} with dash-network-go ${dashnet_ref}" docker build --quiet -t "dash-status:${rev}" --build-arg "RELEASE_REVISION=${rev}" --build-arg "DASHNET_REF=${dashnet_ref}" . >/dev/null +# Fail before retagging/stopping services if an engine rebuild lost rollout support. +# This exercises actual candidate agent modules and CLI, not only the web bundle. +docker run --rm --network none --read-only \ + -v "$src/scripts/check-rollout-backend.mjs:/check-rollout-backend.mjs:ro" \ + --entrypoint node "dash-status:${rev}" /check-rollout-backend.mjs previous=$(docker image inspect dash-status:current --format '{{.Id}}' 2>/dev/null || true) install -d -o 1000 -g 1000 -m 0750 /srv/dash-status/data install -d -o 1000 -g 1000 -m 0700 /srv/dash-status/agent /srv/dash-status/agent/devnets diff --git a/deploy/devnet-keys-compose.yml b/deploy/devnet-keys-compose.yml new file mode 100644 index 0000000..0b33ee0 --- /dev/null +++ b/deploy/devnet-keys-compose.yml @@ -0,0 +1,35 @@ +# On-demand key access. Web gets a Unix socket, never SSH or cloud credentials. +services: + web: + environment: + DEVNET_KEYS_SOCKET: /key-access/keys.sock + volumes: + - /srv/dash-status/key-access:/key-access:ro + keys: + image: dash-status:current + pull_policy: never + init: true + user: "1000:1000" + restart: unless-stopped + read_only: true + cap_drop: [ALL] + security_opt: [no-new-privileges:true] + mem_limit: 256m + command: [node, agent/devnet-keys-service.js] + environment: + STATUS_DATA_DIR: /data + AGENT_PRIVATE_DIR: /agent + DEVNET_KEYS_SOCKET: /key-access/keys.sock + volumes: + - /srv/dash-status/data:/data:ro + - /srv/dash-status/agent:/agent:ro + - /srv/dash-status/key-access:/key-access + healthcheck: + test: [CMD, node, -e, "const n=require('net').connect('/key-access/keys.sock');n.on('connect',()=>{n.end();process.exit(0)});n.on('error',()=>process.exit(1));setTimeout(()=>process.exit(1),3000)"] + interval: 30s + timeout: 5s + start_period: 10s + retries: 3 + logging: + driver: json-file + options: { max-size: 10m, max-file: "3" } diff --git a/docs/platform-reset.md b/docs/platform-reset.md new file mode 100644 index 0000000..7a34a96 --- /dev/null +++ b/docs/platform-reset.md @@ -0,0 +1,31 @@ +# Platform reset: initial protocol version + +On `/n//reset`, **Initial Platform version (PV)** selects the initial +protocol version for the new Platform genesis. It is independent of the Drive, +DAPI and Tenderdash image tags; choose images supporting the requested PV. +Blank preserves the installed genesis PV (which can differ from current +consensus PV after protocol activation). + +The API accepts `options.genesisProtocolVersion`, an optional integer in +`1..4294967295`. This applies to native dashnet and imported dashmate devnets, +including imported Tenderdash seeds. Preparation renders the choice without +wiping; review shows previous and selected genesis PV. Confirmation remains +required before the existing reset executor runs. + +The only admitted genesis deltas are the reviewed ChainLock anchor and explicit +PV (`consensus_params.version.app_version`). Core, node keys and all other +genesis fields retain their existing preservation checks. Native transition +identity binds PV, and verified reset receipts update Connect's initial PV. +Original deployment plans and pinned executors stay immutable. + +Focused checks: + +``` +node --test agent/reset-native.test.js agent/reset-journal.test.js agent/devnet-config.test.js agent/agent.test.js +python3 -m unittest agent/test_reset_dashnet.py agent/test_reset_pv.py +npm run build +node scripts/browser-reset-pv-check.mjs +``` + +Browser checks need the environment's cached Chromium dependencies. They use +local fixtures and submit to the real web handler; no cloud reset runs. diff --git a/docs/rollout-options.md b/docs/rollout-options.md new file mode 100644 index 0000000..3eca36b --- /dev/null +++ b/docs/rollout-options.md @@ -0,0 +1,34 @@ +# Upgrade rollout controls + +Both Deploy and the network's Upgrade now panel provide a maximum number of +nodes to replace together (1–16), plus an optional **Stop mining before upgrade** +toggle. The toggle stages a policy; it does not stop anything while editing or +reviewing a plan. Review shows the plan-bound maximum and exact mining hosts. +Mining automatically resumes on success, failure and cancellation. + +Legacy Testnet controls the two discovered, tagged, instance-pinned `miner-1` +and `miner-2` services. Native devnets use the mining host in their deployment +plan; Core handles it last, on its own. An unsafe validator batch is reduced to +fit the observed quorum. Ordinary masternodes use the requested concurrency. + +New plans use readiness checks, not fixed four-minute waits between nodes. +Regular managed masternode batches check affected targets, without repeatedly +scanning unrelated fleet services; selected-target progression is checked once +at the end. Startup/database migration time remains real work and is displayed. + +Request options: `{ "concurrency": 3, "pauseMining": true }`. An omitted policy +retains old API behavior. Each native phase and managed plan must return matching +`rollout` fields or preparation fails; older executors cannot silently ignore the +options. Upgrade binaries are immutable per operation. Native adoption retains +existing recipe compatibility checks, including the optional mining recipe. +Configuration/schema migrations are separate and cannot combine these controls. + +This change does not modify live nodes, running plans or deployed executors. +Deploy the matching engine and console together while operation runners are idle. +The new UI controls require an executor that supports both flags; older/incompatible +native pins produce an explicit compatibility error rather than unsafe adoption. + +Focused UI verification: build the frontend, then run +`node scripts/browser-rollout-check.mjs` with Playwright available. It submits +Testnet/native options through the real web handler at desktop and mobile sizes, +using local fixtures, without an agent or cloud operation. diff --git a/monitoring/websites/README.md b/monitoring/websites/README.md new file mode 100644 index 0000000..f448da9 --- /dev/null +++ b/monitoring/websites/README.md @@ -0,0 +1,61 @@ +# Website performance + +The public `/websites` tab and `/api/websites` expose synthetic HTTPS homepage +checks of **dash.dev** and **dash.org**, collected on the existing AWS status host +(us-west-2). No browser visitor, AI job, or API request triggers a probe. + +## Measurements and history + +- The systemd timer runs once every five minutes; one request per site plus up to + four HTTPS redirects restricted to the site's apex or www hostname. No auth, + cookies, persisted sessions, or third-party asset requests. IPv4 and normal TLS + validation; curl negotiates HTTP/2 and compression when supported. +- Fresh connections each hop. TTFB = completed redirect duration plus final-hop + first byte. Total response = all hop durations through final HTML download. + DNS/TCP/TLS/wait/download phases are summed over hops; server wait includes RTT. + Tiny request/protocol setup time may not appear in the phase totals. +- Seven days of timestamped samples persist atomically in + `/srv/dash-status/data/websites/report.json`, bounded to 2,200 samples per site. + Errors are samples, never zero-latency successes. Missed intervals are not + backfilled. Graph lines break at failed checks or gaps over ten minutes. +- Median/p95 are nearest-rank over successful checks in the last 24 hours. Check + success is successes/attempts, **not uptime**. Missing intervals do not count as + successful or failed requests. Fewer samples mean less representative stats. +- Data older than twelve minutes (or over one minute in the future) is marked + stale. The last report remains available across failed collections/restarts. +- Recommendations derive from measured timing, redirect, compression, cache and + HTML tag evidence. These are not browser render metrics or Core Web Vitals. + +## Status-host installation + +Requires Python 3, curl with `%{json}` and systemd. Keep this separate from the +public web process and privileged network agents. The shipped service runs as +the existing status-data owner (`ubuntu`) with no capabilities, read-only system/home protection, resource limits, +and only the report directory writable. Use CPU weight, not a hard CPU quota: +quota throttling can inflate TLS and first-byte timings. Web reads it using its existing `/data` +mount; no cloud credentials or additional container privileges are needed. + +1. Install this directory at `/opt/dash-status/websites` (or symlink an immutable + release). Create `/srv/dash-status/data/websites`, owner `ubuntu:ubuntu`, explicitly chmod 0755 (do not rely on umask). +2. Install the service/timer files in `/etc/systemd/system/`, verify them, then + `systemctl daemon-reload` and `systemctl start dash-status-websites.service`. +3. Verify successful real reports and the public API, then enable/start the timer. +4. Check `systemctl status dash-status-websites.timer` and subsequent sample times. + The report retains no raw HTML, cookies, credentials or server IP addresses. + +Before editing a running collector, stop its timer and wait for the oneshot to +finish. Stage/validate immutable replacement source before repointing the link. +For rollback disable the new timer and restore the prior web image, retaining +collected history. Do not restore unrelated network/CI state. + +## Focused validation + +``` +python3 -m unittest discover -s monitoring/websites -p 'test_*.py' +node --test server/websites.test.js server/web.test.js server/ci.test.js server/ci-queue.test.js +npm run build +``` + +Browser QA must cover actual graph windows, metric selection, hover/keyboard/touch +inspection, mobile layout, navigation and live measurements. Use test fixtures only +in local tests, never publish artificial history to the production collector. diff --git a/monitoring/websites/dash-status-websites.service b/monitoring/websites/dash-status-websites.service new file mode 100644 index 0000000..af99af5 --- /dev/null +++ b/monitoring/websites/dash-status-websites.service @@ -0,0 +1,26 @@ +[Unit] +Description=Dash public website performance probes (status-host vantage point) +After=network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +User=ubuntu +Group=ubuntu +ExecStart=/usr/bin/python3 /opt/dash-status/websites/probe.py --output /srv/dash-status/data/websites/report.json +TimeoutStartSec=140 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictSUIDSGID=true +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX +CapabilityBoundingSet= +ReadWritePaths=/srv/dash-status/data/websites +MemoryMax=192M +CPUWeight=10 +LimitFSIZE=16M +UMask=0022 diff --git a/monitoring/websites/dash-status-websites.timer b/monitoring/websites/dash-status-websites.timer new file mode 100644 index 0000000..f91d1dc --- /dev/null +++ b/monitoring/websites/dash-status-websites.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Collect Dash website response timing every five minutes + +[Timer] +OnBootSec=45s +OnUnitActiveSec=5min +AccuracySec=5s + +[Install] +WantedBy=timers.target diff --git a/monitoring/websites/probe.py b/monitoring/websites/probe.py new file mode 100644 index 0000000..4580876 --- /dev/null +++ b/monitoring/websites/probe.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +"""Bounded, unauthenticated homepage probes. Run only on the status host.""" +import argparse +import concurrent.futures +import datetime +import fcntl +from html.parser import HTMLParser +import json +import math +import os +from pathlib import Path +import subprocess +import tempfile +import time +from urllib.parse import urljoin, urlsplit + +SITES = ('dash.dev', 'dash.org') +INTERVAL = 300 +RETENTION = 7 * 86400 +MAX_BYTES = 4 * 1024 * 1024 + + +def stamp(): + return datetime.datetime.now(datetime.timezone.utc).isoformat() + + +def allowed(url, site): + u = urlsplit(url) + return (u.scheme == 'https' and u.hostname in (site, 'www.' + site) + and u.port in (None, 443) and not u.username and not u.password) + + +class PageHints(HTMLParser): + def __init__(self): + super().__init__() + self.counts = dict(scripts=0, blockingScripts=0, stylesheets=0, images=0, imagesWithoutDimensions=0) + + def handle_starttag(self, tag, attrs): + a = dict(attrs) + if tag == 'script' and a.get('src'): + self.counts['scripts'] += 1 + if not any(k in a for k in ('async', 'defer')) and a.get('type', '').lower() != 'module': + self.counts['blockingScripts'] += 1 + if tag == 'link' and 'stylesheet' in a.get('rel', '').lower().split(): + self.counts['stylesheets'] += 1 + if tag == 'img': + self.counts['images'] += 1 + if not a.get('width') or not a.get('height'): + self.counts['imagesWithoutDimensions'] += 1 + + +def fetch_hop(url, directory): + body, headers = Path(directory) / 'body', Path(directory) / 'headers' + p = subprocess.run(['curl', '--disable', '--silent', '--show-error', '--noproxy', '*', + '--ipv4', '--compressed', '--proto', '=https', '--max-time', '20', + '--connect-timeout', '8', '--max-filesize', str(MAX_BYTES), + '--user-agent', 'DashStatusWebsiteProbe/1.0', '--dump-header', str(headers), + '--output', str(body), '--write-out', '%{json}', url], + capture_output=True, text=True, timeout=25) + if p.returncode: + # Do not publish raw curl diagnostics, headers, addresses, or cookies. + codes = {6: 'DNS lookup failed', 7: 'Connection failed', 28: 'Request timed out', + 60: 'TLS certificate validation failed', 63: 'HTML exceeds the 4 MiB probe limit'} + raise ValueError(codes.get(p.returncode, 'HTTPS probe failed (curl %d)' % p.returncode)) + metrics = json.loads(p.stdout) + selected = {} + for line in headers.read_text(errors='replace').splitlines(): + if line.startswith('HTTP/'): + selected = {} + elif ':' in line: + key, value = line.split(':', 1) + if key.lower() in ('location', 'content-type', 'content-encoding', 'cache-control', 'age', 'cf-cache-status', 'x-cache'): + selected[key.lower()] = value.strip()[:300] + return metrics, selected, body.read_bytes()[:MAX_BYTES] + + +def probe(site, fetch=fetch_hop): + result = {'site': site, 'at': stamp(), 'ok': False} + url = 'https://' + site + '/' + hops = [] + try: + with tempfile.TemporaryDirectory() as directory: + for _ in range(5): + if not allowed(url, site): + raise ValueError('Redirect outside the approved HTTPS website') + m, h, body = fetch(url, directory) + code = int(m['http_code']) + t = lambda key: float(m.get('time_' + key, 0)) * 1000 + hop = {'status': code, 'dnsMs': t('namelookup'), + 'tcpMs': max(0, t('connect') - t('namelookup')), + 'tlsMs': max(0, t('appconnect') - t('connect')), + 'waitMs': max(0, t('starttransfer') - t('pretransfer')), + 'ttfbMs': t('starttransfer'), 'totalMs': t('total'), + 'downloadMs': max(0, t('total') - t('starttransfer'))} + hops.append(hop) + if code in (301, 302, 303, 307, 308): + if not h.get('location'): + raise ValueError('Redirect has no destination') + url = urljoin(url, h['location']) + continue + result.update(status=code, finalUrl=urlsplit(url)._replace(query='', fragment='').geturl(), + redirects=len(hops) - 1, httpVersion=str(m.get('http_version', 'unknown')), + transferBytes=int(m.get('size_download', 0)), htmlBytes=len(body), + encoding=h.get('content-encoding', 'none'), cacheControl=h.get('cache-control', 'not sent'), + cacheStatus=h.get('cf-cache-status', h.get('x-cache', 'not reported')), age=h.get('age'), + redirectMs=round(sum(x['totalMs'] for x in hops[:-1]), 1), + ttfbMs=round(sum(x['totalMs'] for x in hops[:-1]) + hop['ttfbMs'], 1), + totalMs=round(sum(x['totalMs'] for x in hops), 1), + phases={k: round(sum(x[k] for x in hops), 1) for k in ('dnsMs', 'tcpMs', 'tlsMs', 'waitMs', 'downloadMs')}) + if not 200 <= code < 300: + raise ValueError('Homepage returned HTTP %d' % code) + if 'text/html' not in h.get('content-type', '').lower(): + raise ValueError('Homepage did not return HTML') + hints = PageHints() + hints.feed(body.decode('utf-8', errors='replace')) + result.update(ok=True, hints=hints.counts) + return result + raise ValueError('Too many redirects (maximum four followed)') + except (ValueError, OSError, subprocess.TimeoutExpired) as e: + result['error'] = str(e) if isinstance(e, ValueError) else 'Probe could not complete' + return result + + +def percentile(values, q): + return sorted(values)[max(0, math.ceil(len(values) * q) - 1)] if values else None + + +def summarize(samples, now): + recent = [s for s in samples if datetime.datetime.fromisoformat(s['at']).timestamp() >= now - 86400] + good = [s for s in recent if s['ok']] + return dict(samples=len(recent), successes=len(good), + successPercent=round(100 * len(good) / len(recent), 1) if recent else None, + ttfbP50Ms=percentile([s['ttfbMs'] for s in good], .5), + ttfbP95Ms=percentile([s['ttfbMs'] for s in good], .95), + totalP50Ms=percentile([s['totalMs'] for s in good], .5)) + + +def collect(output): + output = Path(output) + output.parent.mkdir(parents=True, exist_ok=True) + with (output.parent / '.lock').open('w') as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + try: + previous = json.loads(output.read_text()) + except (OSError, ValueError): + previous = {} + now = time.time() + with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: + latest = list(pool.map(probe, SITES)) + sites = [] + for item in latest: + old = next((s.get('history', []) for s in previous.get('sites', []) if s.get('site') == item['site']), []) + history = [s for s in old if datetime.datetime.fromisoformat(s['at']).timestamp() > now - RETENTION] + history = (history + [item])[-2200:] + sites.append(dict(site=item['site'], latest=item, history=history, summary24h=summarize(history, now))) + report = dict(schemaVersion=1, generatedAt=stamp(), intervalSeconds=INTERVAL, + location='AWS us-west-2 · Oregon · status host', sites=sites) + temporary = output.with_suffix('.tmp') + temporary.write_text(json.dumps(report, separators=(',', ':'))) + temporary.chmod(0o644) + os.replace(temporary, output) + print(json.dumps({'generatedAt': report['generatedAt'], 'sites': [{'site': s['site'], 'ok': s['latest']['ok'], 'ttfbMs': s['latest'].get('ttfbMs'), 'error': s['latest'].get('error')} for s in sites]})) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('--output', required=True) + collect(parser.parse_args().output) diff --git a/monitoring/websites/test_probe.py b/monitoring/websites/test_probe.py new file mode 100644 index 0000000..f6590e1 --- /dev/null +++ b/monitoring/websites/test_probe.py @@ -0,0 +1,67 @@ +import importlib.util +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location('probe', Path(__file__).with_name('probe.py')) +p = importlib.util.module_from_spec(spec) +spec.loader.exec_module(p) + + +def response(code=200): + return dict(http_code=code, time_namelookup=.01, time_connect=.03, time_appconnect=.06, + time_pretransfer=.061, time_starttransfer=.1, time_total=.12, size_download=123, http_version='2') + + +class ProbeTests(unittest.TestCase): + def test_redirect_included_in_ttfb_and_phases(self): + calls = [] + def fetch(url, _): + calls.append(url) + return (response(301), {'location': 'https://www.dash.org/'}, b'') if len(calls) == 1 else (response(), {'content-type': 'text/html', 'content-encoding': 'br'}, b'') + s = p.probe('dash.org', fetch) + self.assertTrue(s['ok']) + self.assertEqual(s['ttfbMs'], 220) + self.assertEqual(s['totalMs'], 240) + self.assertEqual(s['redirectMs'], 120) + self.assertEqual(s['phases']['tlsMs'], 60) + self.assertEqual(s['phases']['waitMs'], 78) + + def test_redirect_cannot_probe_other_hosts_or_credentials(self): + for target in ['http://dash.org/', 'https://169.254.169.254/', 'https://dash.org.evil.test/', 'https://a:b@dash.org/', 'https://dash.org:444/']: + calls = [] + def fetch(url, _): + calls.append(url) + return response(302), {'location': target}, b'' + s = p.probe('dash.org', fetch) + self.assertFalse(s['ok']) + self.assertEqual(len(calls), 1) + + def test_failures_not_counted_as_fast_success(self): + sample = p.probe('dash.dev', lambda *_: (response(503), {'content-type': 'text/html'}, b'unavailable')) + self.assertFalse(sample['ok']) + stats = p.summarize([sample], p.time.time()) + self.assertEqual(stats['successPercent'], 0) + self.assertIsNone(stats['ttfbP50Ms']) + + def test_hints_distinguish_deferred_scripts(self): + h = p.PageHints() + h.feed('') + self.assertEqual(h.counts['scripts'], 3) + self.assertEqual(h.counts['blockingScripts'], 1) + self.assertEqual(h.counts['imagesWithoutDimensions'], 1) + + def test_non_html_not_healthy(self): + s = p.probe('dash.dev', lambda *_: (response(), {'content-type': 'application/json'}, b'{}')) + self.assertFalse(s['ok']) + + def test_redirect_loop_bounded(self): + calls = [] + def fetch(url, _): + calls.append(url) + return response(301), {'location': '/'}, b'' + self.assertFalse(p.probe('dash.dev', fetch)['ok']) + self.assertEqual(len(calls), 5) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/browser-connect-keys.mjs b/scripts/browser-connect-keys.mjs new file mode 100644 index 0000000..7d24f5a --- /dev/null +++ b/scripts/browser-connect-keys.mjs @@ -0,0 +1,48 @@ +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createWeb } from '../server/web.js'; +import { DEFAULT_SETTINGS } from '../shared/settings.js'; +import { devnetFacts } from '../agent/devnet-config.js'; +const root = mkdtempSync(join(tmpdir(), 'connect-keys-browser-')); +mkdirSync(join(root, 'devnets/devnet-sakura'), { recursive: true }); +const settings = { ...structuredClone(DEFAULT_SETTINGS), operators: [...DEFAULT_SETTINGS.operators, { id: 42, login: 'fixture', role: 'operator', networks: ['devnet-sakura'] }] }; +writeFileSync(join(root, 'settings.json'), JSON.stringify(settings)); +writeFileSync(join(root, 'devnets.json'), JSON.stringify({ 'devnet-sakura': { status: 'ready', displayName: 'Sakura', coreNetwork: 'sakura' } })); +const h = { name: 'validators-001', role: 'validator', instanceId: 'i-fixture', peerAddress: '192.0.2.1' }; +const facts = devnetFacts({ name: 'devnet-sakura', plan: { coreNetwork: 'sakura', targets: [h], platformChainId: 'sakura', miningIntervalSeconds: 10 }, record: { deployment: { nodes: {} } } }); +writeFileSync(join(root, 'devnets/devnet-sakura/config.json'), JSON.stringify(facts)); +const result = { network: 'devnet-sakura', verifiedAt: new Date().toISOString(), networkKeys: { sporkPrivateKey: 'FIXTURE-SPORK' }, validators: [{ name: h.name, proTxHash: 'a'.repeat(64), votingPrivateKey: 'FIXTURE-VOTE', ownerPrivateKey: 'FIXTURE-OWNER', operatorPrivateKey: 'FIXTURE-BLS', platformNodePrivateKey: 'FIXTURE-P2P' }] }; +let reads = 0; +const fetcher = async url => url.includes('access_token') ? Response.json({ access_token: 'fixture' }) : Response.json({ id: 42, login: 'fixture' }); +const origin = 'http://127.0.0.1:4799'; +const app = createWeb({ dataDir: root, origin, auth: { clientId: 'fixture', clientSecret: 'fixture', fetcher }, keyReader: async () => { reads++; return result; } }); +const server = app.listen(4799, '127.0.0.1'); +const browser = await chromium.launch({ args: ['--no-sandbox'] }); +try { + for (const viewport of [{ width: 1440, height: 1000 }, { width: 390, height: 844 }]) { + const page = await browser.newPage({ viewport }); const errors = []; page.on('pageerror', e => errors.push(e.message)); + const start = await page.request.get(origin + '/api/auth/github', { maxRedirects: 0 }); + const state = new URL(start.headers().location).searchParams.get('state'); + await page.goto(`${origin}/api/auth/callback?state=${state}&code=fixture`); + await page.goto(origin + '/n/devnet-sakura/connect'); + await page.getByRole('button', { name: 'Reveal private keys' }).waitFor(); + const before = reads; + assert.equal(await page.getByRole('textbox', { name: 'Voting private key (WIF)' }).count(), 0); + await page.getByRole('button', { name: 'Reveal private keys' }).click(); + await page.getByRole('button', { name: 'Hide keys' }).waitFor(); + assert.equal(reads, before + 1); + await page.locator('summary').filter({ hasText: 'validators-001' }).click(); + assert.equal(await page.getByRole('textbox', { name: 'Voting private key (WIF)' }).inputValue(), 'FIXTURE-VOTE'); + const download = page.waitForEvent('download'); await page.getByRole('button', { name: 'Download private keys (.json)' }).click(); + assert.equal((await download).suggestedFilename(), 'devnet-sakura-private-keys.json'); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), 'no viewport overflow'); + await page.screenshot({ path: `../../reports/status-connect-keys-20261007/fixture-${viewport.width}.png`, fullPage: true }); + await page.getByRole('button', { name: 'Hide keys' }).click(); + assert.equal(await page.getByRole('textbox', { name: 'Voting private key (WIF)' }).count(), 0); + assert.deepEqual(errors, []); await page.close(); + } + console.log('Desktop/mobile operator reveal, download, hide, no eager key fetch and no overflow passed (synthetic keys only).'); +} finally { await browser.close(); app.close(); server.closeAllConnections(); server.close(); await new Promise(r => setTimeout(r, 250)); rmSync(root, { recursive: true, force: true }); } diff --git a/scripts/browser-reset-pv-check.mjs b/scripts/browser-reset-pv-check.mjs new file mode 100644 index 0000000..fe00880 --- /dev/null +++ b/scripts/browser-reset-pv-check.mjs @@ -0,0 +1,83 @@ +// Renders the real frontend against fixture agent state and walks the public +// board and the operator deploy flow. No cloud, SSH or identity provider. +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createWeb } from '../server/web.js'; +import { legacyNetwork } from '../agent/fixtures/legacy-network.js'; +import { DEFAULT_SETTINGS } from '../shared/settings.js'; + +const temp = mkdtempSync(join(tmpdir(), 'dash-status-browser-')); +const at = new Date().toISOString(); +const container = (name, image, running = true) => ({ name, image, repo: image.split(/[:@]/)[0], running, state: running ? 'running' : 'exited', restarts: 0, startedAt: at, ports: [] }); +const system = { load: [0.2, 0.3, 0.3], cpus: 2, memTotal: 4e9, memAvailable: 2e9, uptime: 86400 * 30, disks: [{ mount: '/', size: 5e10, used: 2e10, avail: 3e10 }], os: 'Ubuntu 22.04', kernel: '6.8' }; +function state(name, chain, platform) { + const hosts = []; + const add = (hostName, role, data, n) => hosts.push({ name: hostName, role, state: 'running', publicIp: `192.0.2.${n}`, privateIp: `10.0.0.${n}`, instanceId: `i-PRIVATE${String(n).padStart(9, '0')}`, instanceType: 't4g.small', arch: 'arm64', az: 'us-west-2a', tagged: true, probe: { ok: true, at, ms: 900, data: { system, ...data } } }); + for (let i = 1; i <= 4; i++) add(`hp-masternode-${i}`, 'validator', { + core: { chain, blocks: 1000, headers: 1000, chainLockHeight: 1000, subversion: '/Dash Core:23.1.8/', protocol: 70240, connections: 40, synced: true, masternode: { state: 'READY', posePenalty: 0, proTxHash: 'ab'.repeat(32), type: 'Evo' } }, + tenderdash: platform ? { height: 500, network: platform, protocolApp: 13, peers: 30, version: '1.8.1', validatorSetSize: 4, blockTime: at } : null, + dapi: { ok: true, latencyMs: 25, dapiVersion: '4.2.0-beta.5', driveVersion: '4.2.0-beta.5' }, + containers: [container('dashmate-core-1', 'dashpay/dashd:23'), container('dashmate-drive_abci-1', 'dashpay/drive:4.2.0-beta.5'), container('dashmate-drive_tenderdash-1', 'dashpay/tenderdash:1.8.1'), container('dashmate-rs_dapi-1', 'dashpay/rs-dapi:4.2.0-beta.5'), container('dashmate-gateway-1', 'dashpay/envoy:1.30.2-impr.1'), container('dashmate-dashmate_helper-1', 'dashpay/dashmate-helper:4.2.0-beta.4')], + }, i); + for (let i = 1; i <= 2; i++) add(`seed-${i}`, 'seed', { core: { chain, blocks: 1000, connections: 90, connectionsIn: 80 }, tenderdash: { source: 'p2p', peers: 25, network: platform }, containers: [container('dashd', 'dashpay/dashd:23'), container('tenderdash', 'dashpay/tenderdash:1.8.1')] }, 10 + i); + add('web-1', 'web', { core: { chain, blocks: 1000, subversion: '/Dash Core:23.0.0/' }, insight: { blocks: 1000, syncStatus: 'finished', syncPercentage: 100 }, faucet: { status: 200, latencyMs: 300, title: 'Dash Faucet' }, containers: [container('insight', 'dashpay/insight:4.0.10'), container('faucet', 'dashpay/multifaucet:0.9.2')] }, 20); + add('wallet-1', 'wallet', { core: { chain, blocks: 1000, wallets: [{ name: 'dashd-wallet-1-faucet', trusted: 147078.24 }, { name: 'dashd-wallet-1-mno', trusted: 298406.03 }] }, containers: [container('dashd', 'dashpay/dashd:22.1.0')] }, 21); + hosts.push({ name: 'masternode-9', role: 'masternode', state: 'running', publicIp: '192.0.2.40', instanceId: 'i-PRIVATE000000040', tagged: true, probe: { ok: false, at, ms: 12000, error: 'Timed out while waiting for handshake' } }); + return { network: name, generatedAt: at, pollSeconds: 30, discovery: { at }, endpoints: [{ label: 'Insight', url: 'https://insight.testnet.networks.dash.org/insight/', status: 200, ok: true, ms: 40 }], hosts }; +} + +const dataDir = join(temp, 'data'); +mkdirSync(join(dataDir, 'state'), { recursive: true }); +writeFileSync(join(dataDir, 'state', 'testnet.json'), JSON.stringify(state('testnet', 'test', 'dash-testnet-51'))); +writeFileSync(join(dataDir, 'state', 'devnet-moutai.json'), JSON.stringify(state('devnet-moutai', 'devnet-moutai', 'dash-devnet-moutai'))); +const settings = structuredClone(DEFAULT_SETTINGS); +settings.networks.push(structuredClone(legacyNetwork)); +settings.operators.push({ id: 42, login: 'fixture-operator', role: 'admin', networks: ['*'] }); +writeFileSync(join(dataDir, 'settings.json'), JSON.stringify(settings)); + +const fetcher = async (url) => { + if (url.includes('access_token')) return Response.json({ access_token: 'fixture-token' }); + if (url.includes('api.github.com/users/octocat')) return Response.json({ id: 583231, login: 'octocat', name: 'The Octocat', type: 'User', avatar_url: 'data:,' }); + if (url.includes('hub.docker.com')) return Response.json({ results: [{ name: '4.2.0-beta.5', last_updated: at, images: [{ architecture: 'amd64' }, { architecture: 'arm64' }] }] }); + return Response.json({ id: 42, login: 'fixture-operator' }); +}; + +// Focused operator controls against the actual web server and compiled React UI. +writeFileSync(join(dataDir,'devnets.json'),JSON.stringify({'devnet-native':{status:'ready',platform:'ready',public:true,upgradeScopes:['core','platform','tenderdash'],dashmate:true,images:{helper:'dashpay/dashmate-helper:4.2.0-beta.4'}}})); +writeFileSync(join(dataDir,'state','devnet-native.json'),JSON.stringify(state('devnet-native','devnet-native','dash-devnet-native'))); +const origin='http://127.0.0.1:4799'; +const app=createWeb({dataDir,origin,auth:{clientId:'fixture',clientSecret:'fixture',fetcher},fetcher}); +const server=app.listen(4799,'127.0.0.1'); +let browser; +try { + browser=await chromium.launch(); + mkdirSync('artifacts',{recursive:true}); + for (const [label,viewport] of [['desktop',{width:1600,height:1000}],['mobile',{width:390,height:844}]]) { + const page=await browser.newPage({viewport});const errors=[];page.on('pageerror',e=>errors.push(e.message)); + const start=await page.request.get(origin+'/api/auth/github',{maxRedirects:0}); + const token=new URL(start.headers().location).searchParams.get('state'); + await page.goto(origin+'/api/auth/callback?state='+token+'&code=fixture'); + for (const name of ['devnet-moutai','devnet-native']) { + await page.goto(origin+'/n/'+name+'/reset'); + const pv = page.getByRole('spinbutton',{name:'Initial Platform version (PV)',exact:true}); + await pv.waitFor(); + await pv.fill('0'); + assert.equal(await page.getByRole('button',{name:'Prepare (non-destructive)',exact:true}).isDisabled(),true); + await pv.fill('15'); + await page.screenshot({path:`artifacts/reset-pv-${name}-${label}.png`,fullPage:true}); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1),false); + await page.getByRole('button',{name:'Prepare (non-destructive)',exact:true}).click(); + await page.waitForURL('**/n/'+name+'/ops/*'); + const files=readdirSync(join(dataDir,'requests'));const q=JSON.parse(readFileSync(join(dataDir,'requests',files[0]),'utf8')); + assert.equal(q.options.genesisProtocolVersion,15); + assert.equal(q.network,name);assert.equal(q.action,'platform-reset'); + assert.equal(q.options.epochSeconds,name==='devnet-native'?undefined:3600); + for(const f of files)rmSync(join(dataDir,'requests',f)); + } + assert.deepEqual(errors,[]);await page.close(); + } + console.log('PASS: managed/native devnet reset PV selection, invalid-value prevention, real API request, desktop/mobile layout; no live operations'); +} finally { await browser?.close();app.close();server.close();rmSync(temp,{recursive:true,force:true}); } diff --git a/scripts/browser-rollout-check.mjs b/scripts/browser-rollout-check.mjs new file mode 100644 index 0000000..7874250 --- /dev/null +++ b/scripts/browser-rollout-check.mjs @@ -0,0 +1,84 @@ +// Renders the real frontend against fixture agent state and walks the public +// board and the operator deploy flow. No cloud, SSH or identity provider. +import { chromium } from 'playwright'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createWeb } from '../server/web.js'; +import { legacyNetwork } from '../agent/fixtures/legacy-network.js'; +import { DEFAULT_SETTINGS } from '../shared/settings.js'; + +const temp = mkdtempSync(join(tmpdir(), 'dash-status-browser-')); +const at = new Date().toISOString(); +const container = (name, image, running = true) => ({ name, image, repo: image.split(/[:@]/)[0], running, state: running ? 'running' : 'exited', restarts: 0, startedAt: at, ports: [] }); +const system = { load: [0.2, 0.3, 0.3], cpus: 2, memTotal: 4e9, memAvailable: 2e9, uptime: 86400 * 30, disks: [{ mount: '/', size: 5e10, used: 2e10, avail: 3e10 }], os: 'Ubuntu 22.04', kernel: '6.8' }; +function state(name, chain, platform) { + const hosts = []; + const add = (hostName, role, data, n) => hosts.push({ name: hostName, role, state: 'running', publicIp: `192.0.2.${n}`, privateIp: `10.0.0.${n}`, instanceId: `i-PRIVATE${String(n).padStart(9, '0')}`, instanceType: 't4g.small', arch: 'arm64', az: 'us-west-2a', tagged: true, probe: { ok: true, at, ms: 900, data: { system, ...data } } }); + for (let i = 1; i <= 4; i++) add(`hp-masternode-${i}`, 'validator', { + core: { chain, blocks: 1000, headers: 1000, chainLockHeight: 1000, subversion: '/Dash Core:23.1.8/', protocol: 70240, connections: 40, synced: true, masternode: { state: 'READY', posePenalty: 0, proTxHash: 'ab'.repeat(32), type: 'Evo' } }, + tenderdash: platform ? { height: 500, network: platform, protocolApp: 13, peers: 30, version: '1.8.1', validatorSetSize: 4, blockTime: at } : null, + dapi: { ok: true, latencyMs: 25, dapiVersion: '4.2.0-beta.5', driveVersion: '4.2.0-beta.5' }, + containers: [container('dashmate-core-1', 'dashpay/dashd:23'), container('dashmate-drive_abci-1', 'dashpay/drive:4.2.0-beta.5'), container('dashmate-drive_tenderdash-1', 'dashpay/tenderdash:1.8.1'), container('dashmate-rs_dapi-1', 'dashpay/rs-dapi:4.2.0-beta.5'), container('dashmate-gateway-1', 'dashpay/envoy:1.30.2-impr.1'), container('dashmate-dashmate_helper-1', 'dashpay/dashmate-helper:4.2.0-beta.4')], + }, i); + for (let i = 1; i <= 2; i++) add(`seed-${i}`, 'seed', { core: { chain, blocks: 1000, connections: 90, connectionsIn: 80 }, tenderdash: { source: 'p2p', peers: 25, network: platform }, containers: [container('dashd', 'dashpay/dashd:23'), container('tenderdash', 'dashpay/tenderdash:1.8.1')] }, 10 + i); + add('web-1', 'web', { core: { chain, blocks: 1000, subversion: '/Dash Core:23.0.0/' }, insight: { blocks: 1000, syncStatus: 'finished', syncPercentage: 100 }, faucet: { status: 200, latencyMs: 300, title: 'Dash Faucet' }, containers: [container('insight', 'dashpay/insight:4.0.10'), container('faucet', 'dashpay/multifaucet:0.9.2')] }, 20); + add('wallet-1', 'wallet', { core: { chain, blocks: 1000, wallets: [{ name: 'dashd-wallet-1-faucet', trusted: 147078.24 }, { name: 'dashd-wallet-1-mno', trusted: 298406.03 }] }, containers: [container('dashd', 'dashpay/dashd:22.1.0')] }, 21); + hosts.push({ name: 'masternode-9', role: 'masternode', state: 'running', publicIp: '192.0.2.40', instanceId: 'i-PRIVATE000000040', tagged: true, probe: { ok: false, at, ms: 12000, error: 'Timed out while waiting for handshake' } }); + return { network: name, generatedAt: at, pollSeconds: 30, discovery: { at }, endpoints: [{ label: 'Insight', url: 'https://insight.testnet.networks.dash.org/insight/', status: 200, ok: true, ms: 40 }], hosts }; +} + +const dataDir = join(temp, 'data'); +mkdirSync(join(dataDir, 'state'), { recursive: true }); +writeFileSync(join(dataDir, 'state', 'testnet.json'), JSON.stringify(state('testnet', 'test', 'dash-testnet-51'))); +writeFileSync(join(dataDir, 'state', 'devnet-moutai.json'), JSON.stringify(state('devnet-moutai', 'devnet-moutai', 'dash-devnet-moutai'))); +const settings = structuredClone(DEFAULT_SETTINGS); +settings.networks.push(structuredClone(legacyNetwork)); +settings.operators.push({ id: 42, login: 'fixture-operator', role: 'admin', networks: ['*'] }); +writeFileSync(join(dataDir, 'settings.json'), JSON.stringify(settings)); + +const fetcher = async (url) => { + if (url.includes('access_token')) return Response.json({ access_token: 'fixture-token' }); + if (url.includes('api.github.com/users/octocat')) return Response.json({ id: 583231, login: 'octocat', name: 'The Octocat', type: 'User', avatar_url: 'data:,' }); + if (url.includes('hub.docker.com')) return Response.json({ results: [{ name: '4.2.0-beta.5', last_updated: at, images: [{ architecture: 'amd64' }, { architecture: 'arm64' }] }] }); + return Response.json({ id: 42, login: 'fixture-operator' }); +}; + +// Focused operator controls against the actual web server and compiled React UI. +writeFileSync(join(dataDir,'devnets.json'),JSON.stringify({'devnet-native':{status:'ready',platform:'ready',public:true,upgradeScopes:['core','platform','tenderdash'],dashmate:true,images:{helper:'dashpay/dashmate-helper:4.2.0-beta.4'}}})); +writeFileSync(join(dataDir,'state','devnet-native.json'),JSON.stringify(state('devnet-native','devnet-native','dash-devnet-native'))); +const origin='http://127.0.0.1:4799'; +const app=createWeb({dataDir,origin,auth:{clientId:'fixture',clientSecret:'fixture',fetcher},fetcher}); +const server=app.listen(4799,'127.0.0.1'); +let browser; +try { + browser=await chromium.launch(); + mkdirSync('artifacts',{recursive:true}); + for (const [label,viewport] of [['desktop',{width:1600,height:1000}],['mobile',{width:390,height:844}]]) { + const page=await browser.newPage({viewport});const errors=[];page.on('pageerror',e=>errors.push(e.message)); + const start=await page.request.get(origin+'/api/auth/github',{maxRedirects:0}); + const token=new URL(start.headers().location).searchParams.get('state'); + await page.goto(origin+'/api/auth/callback?state='+token+'&code=fixture'); + for (const name of ['testnet','devnet-native']) { + await page.goto(origin+'/n/'+name+'/deploy'); + await page.getByLabel(/^core/).check(); + await page.getByPlaceholder('dashpay/dashd:').fill('dashpay/dashd:24.0.2'); + await page.getByRole('combobox',{name:'Nodes at once',exact:true}).selectOption('3'); + const toggle=page.getByRole('button',{name:'Stop mining before upgrade: off',exact:true}); + await toggle.click(); + await page.getByRole('button',{name:'Stop mining before upgrade: on',exact:true}).waitFor(); + assert.ok(await page.getByText(/Automatically resumes after completion, failure or cancellation/).isVisible()); + await page.screenshot({path:`artifacts/rollout-${name}-${label}.png`,fullPage:true}); + const wide=await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1);assert.equal(wide,false,'usable without page overflow'); + await page.getByRole('button',{name:'Upgrade now',exact:true}).click(); + await page.waitForURL('**/n/'+name+'/ops/*'); + const files=readdirSync(join(dataDir,'requests'));const q=JSON.parse(readFileSync(join(dataDir,'requests',files[0]),'utf8')); + assert.equal(q.options.concurrency,3);assert.equal(q.options.pauseMining,true);assert.equal(q.options.autoRun,true); + assert.equal(q.network,name);assert.deepEqual(q.components,['core']); + for(const f of files)rmSync(join(dataDir,'requests',f)); + } + assert.deepEqual(errors,[]);await page.close(); + } + console.log('PASS: Testnet/native deployment controls, submitted options, desktop/mobile layout; no live operations'); +} finally { await browser?.close();app.close();server.close();rmSync(temp,{recursive:true,force:true}); } diff --git a/scripts/check-console-features.mjs b/scripts/check-console-features.mjs new file mode 100644 index 0000000..7d0ae07 --- /dev/null +++ b/scripts/check-console-features.mjs @@ -0,0 +1,13 @@ +// Production smoke gate: HTTP health alone does not prove retained console features. +import assert from 'node:assert/strict'; +const origin=process.argv[2];assert.ok(origin,'Usage: node scripts/check-console-features.mjs '); +for(const path of ['/api/remediation','/api/websites','/api/ci/queue']){ + const r=await fetch(origin+path,{signal:AbortSignal.timeout(15000)}); + assert.equal(r.status,200,`${path}: console capability missing`); + assert.match(r.headers.get('content-type')||'',/application\/json/);await r.json(); +} +const html=await (await fetch(origin,{signal:AbortSignal.timeout(15000)})).text(); +const scripts=[...html.matchAll(/src="(\/assets\/[^"\s]+\.js)"/g)].map(m=>m[1]);assert.ok(scripts.length); +const bundles=await Promise.all(scripts.map(async p=>{const r=await fetch(origin+p,{signal:AbortSignal.timeout(15000)});assert.equal(r.status,200,p);return r.text()})); +for(const feature of ['/remediation','/websites','Functional monitoring'])assert.ok(bundles.some(s=>s.includes(feature)),`frontend missing ${feature}`); +console.log(JSON.stringify({remediation:'passed',websiteMonitoring:'passed',ciQueue:'passed',frontendFeatures:'passed'})); diff --git a/scripts/check-rollout-backend.mjs b/scripts/check-rollout-backend.mjs new file mode 100644 index 0000000..87b6078 --- /dev/null +++ b/scripts/check-rollout-backend.mjs @@ -0,0 +1,20 @@ +// Run inside the candidate image, before promotion. No credentials or network required. +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; +const root=process.argv[2] || '/app'; +const { rolloutFor,rolloutArgs,reviewedRollout }=await import(pathToFileURL(`${root}/shared/rollout.js`)); +const { validateRequest }=await import(pathToFileURL(`${root}/agent/ops.js`)); +const { DEFAULT_SETTINGS }=await import(pathToFileURL(`${root}/shared/settings.js`)); +const request={id:'6c8139ad-e92f-40da-943d-1e001efaccb5',network:'testnet',action:'upgrade',nodes:['masternode-11','masternode-12','masternode-13'],components:['core'],images:{core:'dashpay/dashd:24.0.2'},options:{concurrency:3,pauseMining:false}}; +assert.equal(validateRequest(DEFAULT_SETTINGS,request).rollout.concurrency,3); +const policy=rolloutFor(request);assert.deepEqual(rolloutArgs(policy),['--concurrency','3']); +assert.throws(()=>reviewedRollout({},policy,[]),/did not bind/); +assert.equal(reviewedRollout({rollout:{concurrency:3}},policy,[]).concurrency,3); +for(const command of ['managed-plan','upgrade-plan']){ + const p=spawnSync(process.env.DASHNET_BINARY || 'dashnet',[command,'--help'],{encoding:'utf8'}); + assert.equal(p.status,0,`${command}: ${p.error || p.stderr}`); + assert.match(p.stdout+p.stderr,/-concurrency\b/,`${command} missing concurrency`); + assert.match(p.stdout+p.stderr,/-pause-mining\b/,`${command} missing mining controls`); +} +console.log('rollout backend capability gate passed'); diff --git a/server/auth.js b/server/auth.js index 80e45d0..d88a2f1 100644 --- a/server/auth.js +++ b/server/auth.js @@ -1,5 +1,6 @@ import { randomBytes, timingSafeEqual } from 'node:crypto'; import { readFileSync, renameSync, writeFileSync } from 'node:fs'; +const SESSION_TTL_MS = 7 * 24 * 60 * 60_000; const nonce = () => randomBytes(32).toString('base64url'); const equal = (a, b) => typeof a === 'string' && typeof b === 'string' && Buffer.byteLength(a) === Buffer.byteLength(b) && timingSafeEqual(Buffer.from(a), Buffer.from(b)); const cookies = (req) => Object.fromEntries((req.headers.cookie || '').split(';').map((s) => s.trim().split('='))); @@ -62,8 +63,8 @@ export function createAuth(config, { clientId = process.env.GITHUB_OAUTH_CLIENT_ if (!response.ok) throw new Error('Identity unavailable'); const u = await response.json(); if (!Number.isSafeInteger(u.id) || typeof u.login !== 'string') throw new Error('Identity invalid'); if (sessions.size >= 5000) throw new Error('Session capacity'); - const id = nonce(); sessions.set(id, { user: { id: u.id, login: u.login }, csrf: nonce(), expires: clock() + 8 * 60 * 60_000 }); persist(); - res.cookie(sessionName, id, { ...options, maxAge: 8 * 60 * 60_000 }); + const id = nonce(); sessions.set(id, { user: { id: u.id, login: u.login }, csrf: nonce(), expires: clock() + SESSION_TTL_MS }); persist(); + res.cookie(sessionName, id, { ...options, maxAge: SESSION_TTL_MS }); res.redirect('/'); } catch { res.status(502).json({ error: 'GitHub sign-in failed; retry from the sign-in button' }); } }); diff --git a/server/devnet-keys.js b/server/devnet-keys.js new file mode 100644 index 0000000..925906e --- /dev/null +++ b/server/devnet-keys.js @@ -0,0 +1,15 @@ +import { request } from 'node:http'; +export function requestDevnetKeys(socketPath, network, user) { + return new Promise((resolve, reject) => { + if (!socketPath) return reject(Error('Devnet key access is not configured')); + const req = request({ socketPath, path: '/keys', method: 'POST', headers: { 'Content-Type': 'application/json' } }, res => { + let body = ''; + res.on('data', chunk => { body += chunk; if (body.length > 1024 * 1024) req.destroy(Error('size')); }); + res.on('end', () => { try { if (res.statusCode !== 200) throw Error('unavailable'); resolve(JSON.parse(body)); } catch { reject(Error('Devnet keys unavailable; the network must be idle and its identities verified')); } }); + res.on('error', () => reject(Error('Devnet key service unavailable'))); + }); + req.setTimeout(180_000, () => req.destroy(Error('timeout'))); + req.on('error', () => reject(Error('Devnet key service unavailable'))); + req.end(JSON.stringify({ network, user })); + }); +} diff --git a/server/incidents.js b/server/incidents.js index 8387a46..0bae649 100644 --- a/server/incidents.js +++ b/server/incidents.js @@ -339,7 +339,8 @@ export function deriveIssues({ settings, states, ci, aws, operations = [], maint else if (a.state === 'ALARM') add('aws', a.region, a.name, 'aws_alarm', 'warning', 'aws:health', { state: a.state }, health.at); } } - return { issues, sources, checks, samples, suppressions, jobSuccesses }; + return { issues, sources, checks, samples, suppressions, jobSuccesses, + excludedCiHosts: (Array.isArray(settings.remediation?.excludedCiHosts) ? settings.remediation.excludedCiHosts : []).filter((id) => typeof id === 'string') }; } export function reconcile(previous, derived, now = Date.now()) { @@ -360,7 +361,8 @@ export function reconcile(previous, derived, now = Date.now()) { events.push({ schemaVersion: 1, eventId: `${issue.id}:${revision}`, occurredAt: iso(now), transition, issue: structuredClone(issue) }); }; // `exempt` marks a check the network-wide hold must not cover (a crash loop). - const suppressed = (issue, check) => check?.suppressed === true || (check?.exempt !== true && issue.domain === 'network' && derived.suppressions?.[issue.scope] === true); + const excluded = (issue) => issue?.domain === 'ci' && (derived.excludedCiHosts || []).includes(issue.scope); + const suppressed = (issue, check) => excluded(issue) || check?.suppressed === true || (check?.exempt !== true && issue.domain === 'network' && derived.suppressions?.[issue.scope] === true); const positive = (issue, check) => { const s = derived.sources?.[check?.sourceKey]; const at = Date.parse(check?.observedAt), lastFault = Date.parse(issue.lastFaultAt || issue.observedAt || issue.firstSeen); @@ -447,7 +449,16 @@ export function reconcile(previous, derived, now = Date.now()) { } } state.issues = [...existing.values()].filter((i) => i.status === 'open' || now - Date.parse(i.resolvedAt) < 30 * 86400_000); - state.outbox = [...(state.outbox || []), ...events]; + // Exclusion is not recovery. Retain observations/history and withdraw only + // undelivered remediation events; the broker rechecks suppressed live issues. + for (const issue of state.issues) { + issue.remediationExcluded = excluded(issue); + if (issue.remediationExcluded) issue.suppressed = true; + } + const pending = [...(state.outbox || []), ...events]; + state.quarantined = [...(state.quarantined || []), ...pending.filter((e) => excluded(e.issue)) + .map((event) => ({ event, at: iso(now), reason: 'owner-configured remediation exclusion' }))]; + state.outbox = pending.filter((e) => !excluded(e.issue)); state.revisionCounters = counters; const samples = { ...(state.explorerSamples || {}) }; for (const [key, sample] of Object.entries(derived.samples || {})) { diff --git a/server/incidents.test.js b/server/incidents.test.js index 875b149..b9f3971 100644 --- a/server/incidents.test.js +++ b/server/incidents.test.js @@ -441,3 +441,29 @@ test('a crash loop stays actionable while a rolling change on other hosts holds assert.equal(journal.networks.testnet.reason, 'journal'); assert.deepEqual(emitted(reconcile(null, deriveIssues({ settings, states: { testnet: claimed }, activity: journal, now }), now), 'host_health'), []); }); + +test('CI remediation exclusions retain observations, retire pending delivery, and are reversible', () => { + const settings = structuredClone(DEFAULT_SETTINGS); + const ci = { reporters: [{ id: 'strix-pasta' }, { id: 'other' }], hosts: [], runners: [], recent: [] }; + let d = deriveIssues({ settings, states: {}, ci, now }); + let s = reconcile(null, d, now); + const id = s.issues.find((i) => i.scope === 'strix-pasta').id; + settings.remediation = { excludedCiHosts: ['strix-pasta'] }; + d = deriveIssues({ settings, states: {}, ci, now: now + 60_000 }); + assert.ok(d.issues.some((i) => i.id === id), 'observations retained'); + s = reconcile(s, d, now + 60_000); + assert.equal(s.issues.find((i) => i.id === id).status, 'open'); + assert.equal(s.issues.find((i) => i.id === id).suppressed, true); + assert.equal(s.issues.find((i) => i.id === id).remediationExcluded, true); + assert.ok(!s.outbox.some((e) => e.issue.scope === 'strix-pasta')); + assert.ok(s.quarantined.some((e) => e.event.issue.id === id)); + assert.ok(s.outbox.some((e) => e.issue.scope === 'other')); + const count = s.quarantined.length; + s = reconcile(JSON.parse(JSON.stringify(s)), d, now + 120_000); + assert.equal(s.quarantined.length, count); + settings.remediation.excludedCiHosts = []; + d = deriveIssues({ settings, states: {}, ci, now: now + 180_000 }); + s = reconcile(s, d, now + 180_000); + assert.equal(s.issues.find((i) => i.id === id).remediationExcluded, false); + assert.ok(s.outbox.some((e) => e.issue.id === id)); +}); diff --git a/server/remediation.js b/server/remediation.js index dfbf0f1..d701795 100644 --- a/server/remediation.js +++ b/server/remediation.js @@ -32,7 +32,7 @@ export function remediationView(state, { full = false, visibleNetworks = [], now const workerFresh = feed?.schemaVersion === 1 && fresh(feed.generatedAt, now) && fresh(workerAt, now) && Array.isArray(feed.cases); const observations = new Map((Array.isArray(feed?.cases) ? feed.cases : []).map((c) => [c.issueId, c])); const visible = new Set(visibleNetworks); - const visibleIssues = (state?.issues || []).filter((i) => full || i.domain !== 'network' || visible.has(i.scope)); + const visibleIssues = (state?.issues || []).filter((i) => !i.remediationExcluded).filter((i) => full || i.domain !== 'network' || visible.has(i.scope)); const displayedIssues = visibleIssues.filter((i) => !activityHidden(i, observations.get(i.id), state)); const cases = displayedIssues.map((issue) => { const response = observations.get(issue.id); diff --git a/server/remediation.test.js b/server/remediation.test.js index df80d59..d556e66 100644 --- a/server/remediation.test.js +++ b/server/remediation.test.js @@ -138,3 +138,9 @@ test('maintenance is visible without claiming recovery or hiding already-running assert.deepEqual(publicView.maintenance,[{network:'testnet',operations:undefined}]); assert.ok(!JSON.stringify(publicView).includes('private')); }); + +test('excluded CI hosts stay out of public and administrator remediation views', () => { + const data = state([issue('excluded', { domain: 'ci', scope: 'strix-pasta', remediationExcluded: true }), issue('retained')], []); + for (const full of [true, false]) assert.deepEqual(remediationView(data, { ...options, full }).cases.map((c) => c.id), ['retained']); + assert.equal(data.issues.length, 2); +}); diff --git a/server/web.js b/server/web.js index 9af0455..e1f088a 100644 --- a/server/web.js +++ b/server/web.js @@ -21,6 +21,7 @@ import { publicInventory } from './aws-public.js'; import { COMPONENTS, COMPONENT_REPOS, accessFor, adminFor, loadSettings, memberOf, operatorFor, readJSON, saveSettings, validateSettings, writeAtomic } from '../shared/settings.js'; import { expectations } from '../shared/monitoring.js'; import { evaluateNetwork, projectNetwork } from '../shared/evaluate.js'; +import { requestDevnetKeys } from './devnet-keys.js'; import { devnetFiles } from '../shared/devnet-files.js'; import { validateRequest } from '../agent/ops.js'; import { validateMainnetReport } from '../shared/mainnet.js'; @@ -44,7 +45,7 @@ export function ttlCache(clock, ttl = 15_000) { return Object.assign(cached, { delete: (key) => entries.delete(key), size: () => entries.size }); } -export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, clock = Date.now, ciGithub = null, ciQueue = {}, mainnetReportToken = process.env.MAINNET_REPORT_TOKEN } = {}) { +export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, clock = Date.now, ciGithub = null, ciQueue = {}, mainnetReportToken = process.env.MAINNET_REPORT_TOKEN, keyReader = requestDevnetKeys, keySocket = process.env.DEVNET_KEYS_SOCKET } = {}) { const settingsPath = join(dataDir, 'settings.json'); const dirs = { state: join(dataDir, 'state'), requests: join(dataDir, 'requests'), ops: join(dataDir, 'ops') }; for (const d of Object.values(dirs)) mkdirSync(d, { recursive: true }); @@ -283,6 +284,23 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl if (!facts) return res.status(404).json({ error: 'No connection facts yet: they appear once the devnet has a deployment plan' }); res.json({ facts, files: devnetFiles(facts) }); }); + // Explicit, network-scoped operator action; never part of config or stream data. + 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, + 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' }); + res.set({ 'Cache-Control': 'private, no-store', 'Pragma': 'no-cache' }); res.vary('Cookie'); + try { + const result = await keyReader(keySocket, n.name, req.session.user); + reloadSettings(); + if (!operatorFor(settings, user(req), n.name)) return res.status(403).json({ error: 'Operator access required' }); + console.info(JSON.stringify({ event: 'devnet-key-access', network: n.name, actorId: req.session.user.id, at: new Date(clock()).toISOString() })); + 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) => { const n = settings.networks.find((x) => x.name === req.params.name); if (!n) return res.status(404).json({ error: 'Network not found' }); diff --git a/server/web.test.js b/server/web.test.js index 831f33f..ccbd29a 100644 --- a/server/web.test.js +++ b/server/web.test.js @@ -13,7 +13,7 @@ async function start(userId = 9920871, extraUsers = [], options = {}) { writeFileSync(join(dataDir, 'state', 'testnet.json'), JSON.stringify({ generatedAt: new Date().toISOString(), hosts: [ { name: 'seed-2', role: 'seed', state: 'running', publicIp: '192.0.2.2', instanceId: 'i-0eb19958115adb5d0', probe: { ok: true, at: new Date().toISOString(), data: { core: { chain: 'test', blocks: 10 }, containers: [] } } }, ] })); - if (extraUsers.length) writeFileSync(join(dataDir, 'settings.json'), JSON.stringify({ ...structuredClone(DEFAULT_SETTINGS), operators: [...DEFAULT_SETTINGS.operators, ...extraUsers] })); + writeFileSync(join(dataDir, 'settings.json'), JSON.stringify({ ...structuredClone(DEFAULT_SETTINGS), operators: [...DEFAULT_SETTINGS.operators, ...extraUsers] })); const github = async (url) => url.includes('access_token') ? Response.json({ access_token: 't' }) : url.includes('/users/octocat') ? Response.json({ id: 583231, login: 'octocat', name: 'The Octocat', type: 'User', avatar_url: 'https://avatars.githubusercontent.com/u/583231' }) : url.includes('/users/') ? new Response('{}', { status: 404 }) : Response.json({ id: userId, login: 'someone' }); @@ -239,51 +239,20 @@ test('CI: admins issue reporter tokens; reporters post with them; infrastructure costs: { at: 'now', month: '2026-09', monthToDate: 3270.85, monthEndEstimate: 3503.4, lastMonth: 3109.17, byService: [{ service: 'EC2 - Other', amount: 1178.9 }], daily: [] } })); assert.equal((await (await w.req('/api/aws')).json()).at, 'now'); assert.equal((await (await w.req('/api/aws')).json()).instances[0].publicIp, '192.0.2.9', 'members see the inventory'); - assert.equal((await (await w.req('/api/aws')).json()).costs.monthToDate, 3270.85, 'members retain costs'); assert.equal((await w.req(`/api/ci/reporters/${id}`, { method: 'DELETE', headers: { 'x-csrf-token': csrf } })).status, 200); - // Signed out: resource aggregates, no spend or resource identity. + // Signed out: resource breakdowns only; the live board keeps costs private. await w.req('/api/auth/logout', { method: 'POST', headers: { 'x-csrf-token': csrf } }); const pub = await (await w.req('/api/aws')).json(); assert.equal(pub.public, true); assert.deepEqual(pub.byNetwork, [{ label: 'testnet', count: 1, vcpus: 2, memoryGiB: 2 }]); assert.equal(pub.costs, undefined); const text = JSON.stringify(pub); - for (const leak of ['3270.85', '3503.4', '3109.17', '1178.9', '192.0.2.9', 'i-0123456789abcdef0', 'dn-testnet-masternode-1', 'testnet-alb', 'elb.amazonaws', 'killdate', 'rs-dapi', 'quorums.testnet', 'dash-terraform-state', 'vol-1']) + for (const leak of ['192.0.2.9', 'i-0123456789abcdef0', 'dn-testnet-masternode-1', 'testnet-alb', 'elb.amazonaws', 'killdate', 'rs-dapi', 'quorums.testnet', 'dash-terraform-state', 'vol-1']) assert.ok(!text.includes(leak), `leaked ${leak}`); assert.equal((await post(`Bearer ${token}`)).status, 401); } finally { w.close(); } }); -test('AWS costs require a valid session, including after cache warmup and logout', async () => { - const w = await start(42); // Signed-in user without inventory membership. - try { - const costs = { monthToDate: 1234.56, monthEndEstimate: 2345.67, lastMonth: 3456.78, - byService: [{ service: 'Fixture service', amount: 456.78 }], daily: [{ day: '2026-10-01', amount: 567.89 }] }; - writeFileSync(join(w.dataDir, 'aws', 'inventory.json'), JSON.stringify({ at: 'fixture', regions: [], - instances: [], volumes: [], addresses: [], natGateways: [], loadBalancers: [], lambda: [], - dynamodb: [], ecr: [], snapshots: [], cloudfront: [], s3: [], costs })); - const anonymous = async (path = '/api/aws', options) => { - const response = await w.req(path, options); - assert.equal(response.status, 200); - assert.equal(response.headers.get('cache-control'), 'no-store'); - assert.match(response.headers.get('vary'), /Cookie/i); - const body = await response.json(); - assert.equal(body.public, true); - assert.equal(Object.hasOwn(body, 'costs'), false); - for (const amount of [1234.56, 2345.67, 3456.78, 456.78, 567.89]) - assert.ok(!JSON.stringify(body).includes(String(amount))); - }; - await anonymous('/api/aws?as=9920871'); // Claimed identity never grants costs. - const csrf = await w.login(); - const signedIn = await (await w.req('/api/aws?as=public')).json(); - assert.equal(signedIn.public, true, 'sign-in does not grant detailed inventory'); - assert.deepEqual(signedIn.costs, costs, 'signed-in summaries retain all costs'); - await anonymous('/api/aws?as=42', { headers: { cookie: 'dash-session=invalid' } }); - assert.equal((await w.req('/api/auth/logout', { method: 'POST', headers: { 'x-csrf-token': csrf } })).status, 200); - await anonymous(); // Same inventory timestamp must not reuse signed-in costs. - } finally { w.close(); } -}); - test('console devnet connection files reach members only', async () => { const w = await start(); try { @@ -340,6 +309,47 @@ test('remediation board notes require administrator access', async () => { } finally { w.close(); } }); +test('private keys require network operator and CSRF, not admin; grants reload immediately', async () => { + for (const role of ['operator', 'viewer']) { + let reads = 0; + const w = await start(777, [{ id: 777, login: 'keys', role, networks: ['devnet-sakura'] }], { keyReader: async () => { reads++; return { fixturePrivateKey: 'fixture-only' }; } }); + try { + writeFileSync(join(w.dataDir, 'devnets.json'), JSON.stringify({ 'devnet-sakura': { status: 'ready' }, 'devnet-other': { status: 'ready' } })); + const path = '/api/networks/devnet-sakura/keys'; + assert.equal((await w.req(path, { method: 'POST' })).status, 401); + const csrf = await w.login(), headers = { 'x-csrf-token': csrf }; + assert.equal((await w.req(path, { method: 'POST' })).status, 403); + assert.equal((await w.req('/api/networks/devnet-other/keys', { method: 'POST', headers })).status, 403); + assert.equal((await w.req(path, { method: 'POST', headers: { ...headers, origin: 'https://evil.example' } })).status, 403); + const response = await w.req(path, { method: 'POST', headers }); + assert.equal(response.status, role === 'operator' ? 200 : 403); + assert.equal(reads, role === 'operator' ? 1 : 0); + if (role === 'operator') { + assert.equal(response.headers.get('cache-control'), 'private, no-store'); + assert.equal((await response.json()).fixturePrivateKey, 'fixture-only'); + const settings = JSON.parse(readFileSync(join(w.dataDir, 'settings.json'))); + settings.operators = settings.operators.filter(x => x.id !== 777); + writeFileSync(join(w.dataDir, 'settings.json'), JSON.stringify(settings)); + assert.equal((await w.req(path, { method: 'POST', headers })).status, 403); + assert.equal(reads, 1); + } + } finally { w.close(); } + } +}); + +test('key route excludes Mainnet/Testnet and suppresses internal errors', async () => { + let reads = 0; + const w = await start(9920871, [], { keyReader: async () => { reads++; throw Error('secret fixture must never escape'); } }); + try { + const csrf = await w.login(), headers = { 'x-csrf-token': csrf }; + for (const network of ['mainnet', 'testnet']) assert.equal((await w.req(`/api/networks/${network}/keys`, { method: 'POST', headers })).status, 404); + assert.equal(reads, 0); + writeFileSync(join(w.dataDir, 'devnets.json'), JSON.stringify({ 'devnet-sakura': { status: 'ready' } })); + const response = await w.req('/api/networks/devnet-sakura/keys', { method: 'POST', headers }); + assert.equal(response.status, 503); assert.ok(!(await response.text()).includes('secret fixture')); + } finally { w.close(); } +}); + test('remediation switch and queue clear are administrator-only, CSRF-protected and default to off', async () => { const post = (w, path, body, csrf) => w.req(path, { method: 'POST', body: body === undefined ? undefined : JSON.stringify(body), headers: { ...(body === undefined ? {} : { 'content-type': 'application/json' }), ...(csrf ? { 'x-csrf-token': csrf } : {}) } }); @@ -348,11 +358,9 @@ test('remediation switch and queue clear are administrator-only, CSRF-protected try { assert.equal((await post(w, '/api/remediation/dispatch', { enabled: true })).status, 401); assert.equal((await post(w, '/api/remediation/clear')).status, 401); - assert.equal((await post(w, '/api/remediation/activity/clear')).status, 401); const csrf = await w.login(); assert.equal((await (await w.req('/api/remediation')).json()).control.requested, 'off'); assert.equal((await post(w, '/api/remediation/dispatch', { enabled: true })).status, 403, 'a session without the CSRF token is refused'); - assert.equal((await post(w, '/api/remediation/activity/clear')).status, 403); assert.equal((await post(w, '/api/remediation/dispatch', { enabled: 'yes' }, csrf)).status, 400); assert.equal((await post(w, '/api/remediation/dispatch', { enabled: true }, csrf)).status, 200); assert.deepEqual([stored(w).seq, stored(w).dispatch, stored(w).updatedBy], [1, 'on', 'someone']); @@ -375,19 +383,12 @@ test('remediation switch and queue clear are administrator-only, CSRF-protected assert.equal((await post(w, '/api/remediation/clear', undefined, csrf)).status, 200); assert.deepEqual([stored(w).seq, stored(w).dispatch, stored(w).clearSeq], [11, 'off', 11], 'a clear after the loss is not stale either, and does not switch on'); assert.equal((await (await w.req('/api/remediation')).json()).control.reset, false); - const beforeHistoryClear = stored(w); - const beforeIssues = readFileSync(join(w.dataDir, 'incidents', 'state.json'), 'utf8'); - assert.equal((await post(w, '/api/remediation/activity/clear', undefined, csrf)).status, 200); - assert.deepEqual(stored(w), beforeHistoryClear, 'activity clear never changes dispatch or the queue'); - assert.equal(readFileSync(join(w.dataDir, 'incidents', 'state.json'), 'utf8'), beforeIssues); - assert.equal((await (await w.req('/api/remediation')).json()).activityHistory.clearedBy, 'someone'); } finally { w.close(); } const member = await start(42); try { const csrf = await member.login(); assert.equal((await post(member, '/api/remediation/dispatch', { enabled: true }, csrf)).status, 403); assert.equal((await post(member, '/api/remediation/clear', undefined, csrf)).status, 403); - assert.equal((await post(member, '/api/remediation/activity/clear', undefined, csrf)).status, 403); assert.equal((await (await member.req('/api/remediation')).json()).control.changedBy, undefined); } finally { member.close(); } }); diff --git a/shared/monitoring.js b/shared/monitoring.js index 19aa287..72a4e85 100644 --- a/shared/monitoring.js +++ b/shared/monitoring.js @@ -54,14 +54,14 @@ export function convergence(host, data, network, expected, componentOf) { const pin = pins[component]; const baseline = expected['*']?.[component]; const locked = normalize(baseline?.ref) === normalize(network.images?.[component]) ? baseline?.digests?.[host.arch] : null; - const target = pin?.to || (locked ? `${network.images[component].split(/[@:]/)[0]}@${locked}` : network.images?.[component]); + const target = pin?.to || network.hostImages?.[host.name]?.[component] || (locked ? `${network.images[component].split(/[@:]/)[0]}@${locked}` : network.images?.[component]); if (!target) { checks.push({ component, status: 'unknown' }); continue; } const match = sameImage(c, target); const status = match === null ? 'unknown' : match ? 'matched' : pin && Date.parse(host.probe?.at) < Date.parse(pin.since) ? 'awaiting-sample' : pin?.active && (!pin.from || sameImage(c, pin.from)) ? 'rolling' : 'drift'; checks.push({ component, status, expected: target }); } - for (const [component, pin] of Object.entries(pins)) if (!checks.some((c) => c.component === component)) checks.push({ component, status: !host.probe?.ok ? 'unknown' : pin.active ? 'rolling' : 'missing', expected: pin.to }); + for (const [component, pin] of Object.entries(pins)) if (!(network.dashmate && component === 'helper') && !checks.some((c) => c.component === component)) checks.push({ component, status: !host.probe?.ok ? 'unknown' : pin.active ? 'rolling' : 'missing', expected: pin.to }); return checks; } const count = (values) => ({ observed: values.filter((v) => v != null).length, total: values.length, failed: values.filter((v) => v === false).length }); diff --git a/shared/rollout.js b/shared/rollout.js new file mode 100644 index 0000000..40f4a24 --- /dev/null +++ b/shared/rollout.js @@ -0,0 +1,41 @@ +// Options are immutable plan inputs, never execution-time overrides. +export function rolloutFor(request) { + const o = request.options || {}; + if (o.concurrency === undefined && o.pauseMining === undefined) return null; + if (request.action !== 'upgrade') throw new Error('rollout options apply to upgrades only'); + const concurrency = o.concurrency === undefined ? 1 : o.concurrency, pauseMining = o.pauseMining === undefined ? false : o.pauseMining; + if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16) throw new Error('concurrency must be an integer from 1 to 16'); + if (typeof pauseMining !== 'boolean') throw new Error('pauseMining must be true or false'); + if (o.allowCoreConfigRestart) throw new Error('rollout options cannot be combined with a configuration migration'); + return { concurrency, pauseMining }; +} + +export function rolloutArgs(rollout, miners) { + if (!rollout) return []; + return ['--concurrency', String(rollout.concurrency), ...(rollout.pauseMining ? ['--pause-mining', ...(miners ? ['--miners', miners.join(',')] : [])] : [])]; +} + +export function reviewedRollout(plan, requested, miners) { + if (!requested) return null; + const actual = plan?.rollout; + // CLI emits omitempty false/empty values. Never display requested options as + // verified when an older executor silently omitted them. + if (!actual || actual.concurrency !== requested.concurrency || !!actual.pauseMining !== requested.pauseMining + || JSON.stringify(actual.miners || []) !== JSON.stringify(requested.pauseMining ? miners : [])) { + throw new Error('executor did not bind the requested rollout options; update dashnet and prepare a new plan'); + } + return { concurrency: actual.concurrency, pauseMining: !!actual.pauseMining, miners: actual.miners || [], resumeMining: 'automatic' }; +} + +export function trackRollout(progress, line, native = false) { + const m = (native ? /^upgrade (\S+) (applying|verified)(?:;.*)?$/ : /^managed target (\S+) (applying|applied)$/).exec(line); + if (!m) return; + progress.active ??= []; + if (m[2] === 'applying') { + if (!progress.active.includes(m[1])) progress.active.push(m[1]); + } else { + progress.active = progress.active.filter((n) => n !== m[1]); + if (!progress.completed.includes(m[1])) progress.completed.push(m[1]); + } + progress.current = progress.active[0] || null; +} diff --git a/shared/rollout.test.js b/shared/rollout.test.js new file mode 100644 index 0000000..ef169c8 --- /dev/null +++ b/shared/rollout.test.js @@ -0,0 +1,41 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { reviewedRollout, rolloutArgs, rolloutFor, trackRollout } from './rollout.js'; +import { manifestFor, validateRequest } from '../agent/ops.js'; +import { DEFAULT_SETTINGS } from './settings.js'; + +test('rollout input validation and exact plan binding', () => { + assert.equal(rolloutFor({ action: 'upgrade' }), null); + for (const concurrency of [0, 17, 1.5, '2', null]) assert.throws(() => rolloutFor({ action: 'upgrade', options: { concurrency } })); + assert.throws(() => rolloutFor({ action: 'doctor', options: { concurrency: 2 } })); + assert.throws(() => rolloutFor({ action: 'upgrade', options: { pauseMining: 'yes' } })); + const r = rolloutFor({ action: 'upgrade', options: { concurrency: 3, pauseMining: true } }); + assert.deepEqual(rolloutArgs(r, ['miner-1', 'miner-2']), ['--concurrency', '3', '--pause-mining', '--miners', 'miner-1,miner-2']); + const plan = { rollout: { ...r, miners: ['miner-1', 'miner-2'] } }; + assert.equal(reviewedRollout(plan, r, plan.rollout.miners).resumeMining, 'automatic'); + for (const bad of [{}, { rollout: { ...plan.rollout, concurrency: 1 } }, { rollout: { ...plan.rollout, miners: ['miner-1'] } }]) assert.throws(() => reviewedRollout(bad, r, plan.rollout.miners)); + assert.equal(reviewedRollout({ rollout: { concurrency: 1 } }, { concurrency: 1, pauseMining: false }, []).pauseMining, false); +}); + +test('progress keeps every concurrent node until its own verified completion', () => { + for (const native of [false, true]) { + const p = { completed: [] }; + const line = (name, done) => native ? `upgrade ${name} ${done ? 'verified; whole fleet healthy' : 'applying'}` : `managed target ${name} ${done ? 'applied' : 'applying'}`; + trackRollout(p, line('node-1', false), native); trackRollout(p, line('node-2', false), native); + assert.deepEqual(p.active, ['node-1', 'node-2']); + trackRollout(p, line('node-1', true), native); trackRollout(p, line('node-1', true), native); + assert.deepEqual(p.active, ['node-2']); assert.deepEqual(p.completed, ['node-1']); + trackRollout(p, line('node-2', true), native); assert.equal(p.current, null); + } +}); + +test('legacy mining inventory includes only exact owned Testnet miners', () => { + const settings = structuredClone(DEFAULT_SETTINGS), network = settings.networks.find((n) => n.name === 'testnet'); + const h = (name, extra = {}) => ({ name, role: 'miner', tagged: true, state: 'running', publicIp: '192.0.2.1', instanceId: 'i-123', arch: 'amd64', probe: { data: { containers: [{ name: 'dashd', repo: 'dashpay/dashd', running: true }] } }, ...extra }); + const state = { hosts: [h('miner-1'), h('miner-2'), h('miner-3'), h('miner-1', { duplicate: true })] }; + const { manifest } = manifestFor(settings, network, state); + assert.deepEqual(manifest.targets.map((t) => [t.name, t.role, t.miningService]), [['miner-1', 'core', 'dashd-generate-miner.service'], ['miner-2', 'core', 'dashd-generate-miner.service']]); + assert.equal(manifestFor(settings, { ...network, chainType: 'devnet' }, state).manifest.targets.length, 0); + const q = { id: '6c8139ad-e92f-40da-943d-1e001efaccb5', network: 'testnet', action: 'upgrade', nodes: ['masternode-1'], components: ['core'], images: { core: 'dashpay/dashd:24.0.2' }, options: { concurrency: 4, pauseMining: true } }; + assert.equal(validateRequest(settings, q).rollout.concurrency, 4); +}); diff --git a/shared/settings.js b/shared/settings.js index 47d5e59..1d2fa6d 100644 --- a/shared/settings.js +++ b/shared/settings.js @@ -211,7 +211,7 @@ export function devnetEntry(name, reg) { upgradeScopes: reg.upgradeScopes || ['platform', 'tenderdash'], // The images it runs now; with dashmate set, the helper is the dashmate // release that renders its services. - images: reg.images || null, dashmate: !!reg.dashmate, + images: reg.images || null, hostImages: reg.hostImages || null, minerImage: reg.minerImage || null, dashmate: !!reg.dashmate, description: '', endpoints: [ dns.insight && { label: 'Insight', url: `https://${dns.insight.host}/insight-api/status` }, diff --git a/src/RolloutOptions.jsx b/src/RolloutOptions.jsx new file mode 100644 index 0000000..54d8420 --- /dev/null +++ b/src/RolloutOptions.jsx @@ -0,0 +1,14 @@ +export default function RolloutOptions({ concurrency, setConcurrency, pauseMining, setPauseMining, native, miningEnabled = true }) { + return
+ + {miningEnabled &&
+ +
{native ? 'This devnet’s mining node' : 'miner-1 and miner-2'}. Automatically resumes after completion, failure or cancellation.
+
} +
Each batch must preserve consensus quorum and pass readiness checks before the next. {native && 'For Core, the mining host is upgraded last, separately.'} No mining is stopped until the upgrade runs.
+
; +} diff --git a/src/pages/Connect.jsx b/src/pages/Connect.jsx index 6389d19..224282a 100644 --- a/src/pages/Connect.jsx +++ b/src/pages/Connect.jsx @@ -1,6 +1,7 @@ import { useState } from 'react'; -import { span, useResource } from '../lib.js'; +import { canOperate, span, useResource, useSession } from '../lib.js'; import { Empty, Err, Section, Stat } from '../ui.jsx'; +import DevnetKeys from './DevnetKeys.jsx'; function copy(text) { navigator.clipboard?.writeText(text).catch(() => {}); } function download(name, text) { @@ -20,6 +21,7 @@ function CopyButton({ text, label = 'copy' }) { export default function Connect({ name }) { const { data, error } = useResource(`/api/networks/${name}/config`, (t, d) => t === 'network' && (d.name === name || d.name === '*')); const [file, setFile] = useState(0); + const session = useSession(); if (error) return
{error.status === 404 ? {error.message} : }
; if (!data) return
Loading…
; const { facts: f, files } = data; @@ -36,17 +38,17 @@ export default function Connect({ name }) { -
-
}> +
+
}>
-
+
{files.map((x, i) => ( ))}
{current.text}
-
Public facts only, like the legacy dash-network-configs outputs. Operator, spork and faucet private keys stay on the hosts.
+
These connection files contain no private keys. Devnet operators can reveal and download keys separately below.
@@ -67,6 +69,8 @@ export default function Connect({ name }) {
+ {canOperate(session, name) && } +
diff --git a/src/pages/Deploy.jsx b/src/pages/Deploy.jsx index ea40906..2a59913 100644 --- a/src/pages/Deploy.jsx +++ b/src/pages/Deploy.jsx @@ -1,3 +1,4 @@ +import RolloutOptions from '../RolloutOptions.jsx'; import { useEffect, useMemo, useState } from 'react'; import { api, canOperate, navigate, useResource, useSession, ROLE_LABEL, ago } from '../lib.js'; import { Dot, Empty, Err, Link, Section } from '../ui.jsx'; @@ -5,7 +6,7 @@ import { COMPONENTS, OPERABLE, REPOS, cmp, helperFor, imageTag, newestRelease, r // Plain-language actions; the dashnet command runs underneath (shown in the header). const ACTIONS = [ - { id: 'upgrade', title: 'Upgrade images', text: 'Change the version of selected components. Each image is pinned by digest and swapped one host at a time; the next host waits until the whole fleet passes the health check.' }, + { id: 'upgrade', title: 'Upgrade images', text: 'Change the version of selected components. Images are pinned by digest and replaced in the batches you choose; every batch must pass health and quorum checks.' }, { id: 'deploy', title: 'Restart stopped containers', text: 'Recovery: start containers that are stopped (crash, reboot, deliberate stop) with exactly the image and settings recorded at enrollment. No version change, not for new nodes.' }, { id: 'doctor', title: 'Health check', text: 'Read-only. Observes each host twice across the observation window: services running, Core synced and advancing with ChainLocks, masternode READY, Platform advancing in agreement, DAPI answering.' }, { id: 'enroll', title: 'Enroll hosts', text: 'One-time, changes nothing running: records each host\'s container setup (images, commands, mounts) as a root-only recovery file and in the shared dashnet journal. Upgrades and restarts need it; they enroll new hosts automatically.' }, @@ -21,6 +22,8 @@ export default function Deploy({ name }) { const [picked, setPicked] = useState(params.get('nodes') ? new Set(params.get('nodes').split(',').filter(Boolean)) : null); const [components, setComponents] = useState(new Set(params.get('components')?.split(',').filter(Boolean) || [])); const [images, setImages] = useState({}); + const [concurrency, setConcurrency] = useState(1); + const [pauseMining, setPauseMining] = useState(false); const [window, setWindow] = useState(''); const [timeout, setTimeoutValue] = useState(''); const [busy, setBusy] = useState(false); @@ -32,7 +35,7 @@ export default function Deploy({ name }) { const selected = picked ?? healthy; const setSelected = (next) => setPicked((p) => (typeof next === 'function' ? next(p ?? healthy) : next)); const hosts = useMemo(() => (n?.hosts || []).filter((h) => OPERABLE.includes(h.role) && !h.duplicate), [n]); - // dash-network-go upgrades every validator, one at a time; there is no node selection. + // This form selects the whole native validator fleet; scoped APIs remain available. const chosen = native ? hosts.filter((h) => h.role === 'validator') : hosts.filter((h) => selected.has(h.name)); const coreUpgradable = !native || (n?.upgradeScopes || []).includes('core'); // On dashmate-rendered devnets the helper never runs: it is the dashmate @@ -89,7 +92,7 @@ export default function Deploy({ name }) { async function submit() { setBusy(true); setSubmitError(null); try { - const body = { action, nodes: native ? [] : chosen.map((h) => h.name), components: needsComponents ? activeComponents : [], images: action === 'upgrade' ? Object.fromEntries(activeComponents.map((c) => [c, images[c]])) : {}, options: { ...(window ? { observationWindow: window } : {}), ...(timeout ? { timeout } : {}), ...(needsComponents ? { autoRun } : {}) } }; + const body = { action, nodes: native ? [] : chosen.map((h) => h.name), components: needsComponents ? activeComponents : [], images: action === 'upgrade' ? Object.fromEntries(activeComponents.map((c) => [c, images[c]])) : {}, options: { ...(action === 'upgrade' ? { concurrency, pauseMining } : {}), ...(window ? { observationWindow: window } : {}), ...(timeout ? { timeout } : {}), ...(needsComponents ? { autoRun } : {}) } }; const r = await api(`/api/networks/${name}/ops`, { method: 'POST', body }); navigate(`/n/${name}/ops/${r.id}`); } catch (e) { setSubmitError(e); setBusy(false); } @@ -116,7 +119,7 @@ export default function Deploy({ name }) { {native ? (
-
dash-network-go withdraws one node at a time and requires the whole fleet (advancing consensus, common block hashes, DAPI, membership) to be healthy before the next. A Core upgrade runs first on every node (validators, then the mining node); Platform images then roll across the validators. {coreUpgradable ? '' : This devnet was created with a dash-network-go that cannot upgrade Core; newer devnets can.}
+
Each batch checks affected services and current validator quorum before the next batch. There is no fixed four-minute delay per node. A Core upgrade runs first on every node (validators, then the mining node); Platform images then roll across the validators. {coreUpgradable ? '' : This devnet was created with a dash-network-go that cannot upgrade Core; newer devnets can.}
) : (
- + {action === 'upgrade' && } + {action !== 'upgrade' && } {(action === 'upgrade' || action === 'deploy') && } -
Defaults come from Settings. Upgrades withdraw one host at a time; validators additionally require the remaining quorum to be healthy before each withdrawal.
+
Timeout defaults come from Settings. Upgrades continue when the changed nodes are ready, with no fixed four-minute delay between nodes.
{needsComponents && }
diff --git a/src/pages/DevnetKeys.jsx b/src/pages/DevnetKeys.jsx new file mode 100644 index 0000000..ffce258 --- /dev/null +++ b/src/pages/DevnetKeys.jsx @@ -0,0 +1,48 @@ +import { useEffect, useState } from 'react'; +import { api } from '../lib.js'; +import { Section } from '../ui.jsx'; + +function KeyValue({ label, value }) { + const [copied, setCopied] = useState(false); + if (!value) return null; + return
{label}
; +} +function download(data) { + const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2) + '\n'], { type: 'application/json' })); + const a = Object.assign(document.createElement('a'), { href: url, download: `${data.network}-private-keys.json` }); + document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); +} +export default function DevnetKeys({ name }) { + const [data, setData] = useState(null), [busy, setBusy] = useState(false), [error, setError] = useState(''); + useEffect(() => { + if (!data) return; + const timer = setTimeout(() => setData(null), 5 * 60_000); + const hide = () => { if (document.hidden) setData(null); }; + document.addEventListener('visibilitychange', hide); + return () => { clearTimeout(timer); document.removeEventListener('visibilitychange', hide); }; + }, [data]); + async function reveal() { + setBusy(true); setError(''); + try { const result = await api(`/api/networks/${name}/keys`, { method: 'POST', body: {} }); if (!document.hidden) setData(result); } + catch (e) { setError(e.message); } + finally { setBusy(false); } + } + return
Devnet operators}> +
+

Voting, owner, collateral, BLS operator and Platform node keys for this devnet. Loaded on demand and cleared from this view after five minutes or when you switch tabs.

+
{!data ? : <>Verified {data.verifiedAt}}
+ {error &&

{error}

} + {data &&
+
{['spork', 'payout', 'faucet'].map(k => )}
+ {data.validators.map(h =>
{h.name} · {h.proTxHash.slice(0, 16)}…
+ + + + + + +
)} +
} +
+
; +} diff --git a/src/pages/Network.jsx b/src/pages/Network.jsx index c8b4a60..30f1a5d 100644 --- a/src/pages/Network.jsx +++ b/src/pages/Network.jsx @@ -1,3 +1,4 @@ +import RolloutOptions from '../RolloutOptions.jsx'; import { Fragment, useEffect, useMemo, useState } from 'react'; import { ago, api, bytes, canOperate, canSee, clock, dash, duration, navigate, num, short, span, useNow, useResource, useSession, ROLE_LABEL } from '../lib.js'; import { Delta, Dot, Empty, EndpointDot, Err, Level, Link, Meter, Section, Stat } from '../ui.jsx'; @@ -419,6 +420,8 @@ function Updates({ n }) { const [state, setState] = useState({ network: null, updates: [] }); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); + const [concurrency, setConcurrency] = useState(1); + const [pauseMining, setPauseMining] = useState(false); const native = n.kind === 'dashnet'; const hosts = n.hosts.filter((h) => OPERABLE.includes(h.role) && !h.duplicate && h.state === 'running' && h.level !== 'unreachable'); const key = hosts.map((h) => h.name + COMPONENTS.map((c) => reported(h, c)).join()).join('|'); @@ -445,7 +448,7 @@ function Updates({ n }) { const upgrade = async () => { setBusy(true); setError(null); try { - const r = await api(`/api/networks/${n.name}/ops`, { method: 'POST', body: { action: 'upgrade', nodes, components: updates.map((u) => u.c), images: Object.fromEntries(updates.map((u) => [u.c, `${REPOS[u.c]}:${u.to}`])), options: { autoRun: true } } }); + const r = await api(`/api/networks/${n.name}/ops`, { method: 'POST', body: { action: 'upgrade', nodes, components: updates.map((u) => u.c), images: Object.fromEntries(updates.map((u) => [u.c, `${REPOS[u.c]}:${u.to}`])), options: { autoRun: true, concurrency, pauseMining } } }); navigate(`/n/${n.name}/ops/${r.id}`); } catch (e) { setError(e); setBusy(false); } }; @@ -453,7 +456,8 @@ function Updates({ n }) {
updates available {updates.map((u) => {u.c} {u.from} → {u.to})} - {native ? 'every node, Core first, then Platform' : `${nodes.length} healthy node(s), one at a time`} + {native ? 'every node, Core first, then Platform' : `${nodes.length} healthy node(s), up to ${concurrency} at once`} + Review first… diff --git a/src/pages/Operation.jsx b/src/pages/Operation.jsx index f1ed51c..b82b15c 100644 --- a/src/pages/Operation.jsx +++ b/src/pages/Operation.jsx @@ -70,7 +70,7 @@ export default function Operation({ name, id }) {
phase {op.progress.phase} - {op.progress.current && withdrawn {op.progress.current}} + {(op.progress.active?.length || op.progress.current) && in flight {op.progress.active?.length ? op.progress.active.join(', ') : op.progress.current}} applied {op.progress.completed.length}/{review?.targets?.length ?? '?'} {op.progress.completed.length ? ({op.progress.completed.join(', ')}) : null} {op.progress.starting && waiting for node to start: {op.progress.starting}} {op.progress.waiting && waiting for fleet health: {op.progress.waiting}} @@ -95,6 +95,10 @@ export default function Operation({ name, id }) { {review?.kind === 'delete-devnet' && } {review && !review.kind && (
confirmed automatically for {op.confirmedBy?.login} (run as soon as ready) : op.status === 'review' && expires in {Math.max(0, Math.round(expiresIn / 60))} min}> + {review.rollout &&
+ Up to {review.rollout.concurrency} nodes at once · readiness-driven health checks. + {review.rollout.pauseMining ? <> Stop mining on {review.rollout.miners.join(', ')} before replacement; automatically resume on completion, failure or cancellation. : ' Mining remains enabled (native Core upgrades retain their DKG safety pauses).'} +
}
@@ -268,8 +272,9 @@ function ResetReview({ op, review, operator, pending, act }) {
Images now {review.current.map(img).join(' | ')}
Images after {img(review.next)} · seed Tenderdash now {review.seedImages.join(', ')}
{review.native &&
Immutable pins for every target{Object.entries(review.targetImages || {}).map(([name, pins]) =>
{name}: {img(pins)}
)}
} + {review.platformVersion &&
Initial Platform version (PV) {review.platformVersion.current.filter((v) => v != null).join(', ') || 'installed'} → {review.platformVersion.next ?? 'preserved'}
}
Epoch {review.epoch.current.join(', ')} → {review.epoch.next} s · dashmate {review.dashmate.join(', ')} · config format {review.configFormat.join(', ')} · Tor enabled {review.tor.map(String).join(', ')}
-
Canary {`epochTime ${review.canary.epochTime}, env ${review.canary.epochEnv}, ${review.canary.coreMigration?.length ? 'Core configuration migration included' : `Core config unchanged ${review.canary.coreSectionUnchanged}`} , anchor ${review.canary.anchor}${review.canary.nodeKeyUnchanged ? `, node key preserved, genesis ${review.canary.genesisChainId} (only anchor changes)` : ''}`}
+
Canary {`epochTime ${review.canary.epochTime}, env ${review.canary.epochEnv}, ${review.canary.coreMigration?.length ? 'Core configuration migration included' : `Core config unchanged ${review.canary.coreSectionUnchanged}`} , anchor ${review.canary.anchor}${review.canary.nodeKeyUnchanged ? `, node key preserved, genesis ${review.canary.genesisChainId} (${review.canary.genesisOnlyAnchorChanged === false ? `anchor and PV ${review.canary.genesisProtocolVersion} selected` : 'only anchor changes'})` : ''}`}
Renders only: {review.rendered.join(', ')}
diff --git a/src/pages/ResetPlatform.jsx b/src/pages/ResetPlatform.jsx index 1a21419..90c24a2 100644 --- a/src/pages/ResetPlatform.jsx +++ b/src/pages/ResetPlatform.jsx @@ -8,6 +8,7 @@ export default function ResetPlatform({ name }) { const session = useSession(); const { data: n, error } = useResource(`/api/networks/${name}`); const [images, setImages] = useState(null); + const [pv, setPv] = useState(''); const [epoch, setEpoch] = useState(3600); const [busy, setBusy] = useState(false); const [submitError, setSubmitError] = useState(null); @@ -30,7 +31,7 @@ export default function ResetPlatform({ name }) { async function submit() { setBusy(true); setSubmitError(null); try { - const r = await api(`/api/networks/${name}/ops`, { method: 'POST', body: { action: 'platform-reset', images: Object.fromEntries(Object.entries(value).filter(([,v]) => v)), ...(!native ? { options: { epochSeconds: epoch } } : {}) } }); + const r = await api(`/api/networks/${name}/ops`, { method: 'POST', body: { action: 'platform-reset', images: Object.fromEntries(Object.entries(value).filter(([,v]) => v)), options: { ...(!native ? { epochSeconds: epoch } : {}), ...(pv !== '' ? { genesisProtocolVersion: Number(pv) } : {}) } } }); navigate(`/n/${name}/ops/${r.id}`); } catch (e) { setSubmitError(e); setBusy(false); } } @@ -52,6 +53,9 @@ export default function ResetPlatform({ name }) { ))} + {!native && } @@ -62,13 +66,13 @@ export default function ResetPlatform({ name }) {
  • Review the version set, anchor and canary, then confirm.
  • Wipe Platform on all HPMNs {native ? '(only the Drive and Tenderdash chain-data volumes)' : <>(dashmate reset --platform --force), then reset only the seed’s Tenderdash data directory}.
  • {native &&
  • Migrate Core automatically when required by the release, with private backups, parallel restarts (up to 32 validators per batch) and fleet health checks. Core chain and wallets are never wiped.
  • } -
  • Apply the images, anchor and epoch; render only Platform files; start the seed, then every HPMN.
  • +
  • Apply the images, PV, anchor and epoch; render only Platform files; start the seed, then every HPMN.
  • {native &&
  • Rebuild Explorer for the new chain, keeping the previous index and a private backup. Installed Explorer images are preserved.
  • }
  • Verify READY, containers and images, consensus, epochs at config/env/parsed layers, DAPI TLS, Core unchanged.
  • - + Nothing is wiped until you confirm the prepared review.
    {submitError &&
    }
    nodecomponentfromto (pinned)