diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 7832afe..d92632b 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -27,6 +27,8 @@ jobs: run: python3 -m unittest discover -s agent -p 'test_reset_dashnet.py' - name: Explorer chain reset and retained deployment contracts run: python3 -m unittest discover -s agent -p 'test_explorer_chain.py' + - name: Devnet key export from legacy and descriptor wallets + run: python3 -m unittest discover -s agent -p 'test_devnet_keys.py' - name: Incident receiver replay, authentication and worker safeguards run: python3 -m unittest discover -s deploy/incident-broker -p 'test_*.py' - run: npm run lint diff --git a/README.md b/README.md index 08c9667..ac57806 100644 --- a/README.md +++ b/README.md @@ -382,7 +382,12 @@ 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` +Create `/srv/dash-status/key-access` owned by uid1000, mode0700; `deploy/deploy.sh` +adds that compose file, and rolls `keys` together with web, on every host where +the directory exists. A hand-run `docker compose` must name the file too: without +it the recreated web has no socket, and a full `up --remove-orphans` removes the +helper. Reveal then answers "the key service is not running on the status host", +and web logs `devnet-key-service-down`. 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 @@ -392,10 +397,26 @@ 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. +Legacy wallets use `dumpprivkey`. For descriptor wallets the collector matches +the owned address to an existing private P2PKH descriptor, derives its test/devnet +WIF in target-process memory, and asks Core to verify that it resolves to the +registered address. OpenSSL supplies secp256k1 public-key operations over stdin; +neither private descriptors nor scalars enter command arguments or files. The +spork key may instead be held in the managed node's secret store; its address is +verified in the same way. Unsupported scripts or ambiguous/mismatched identities +fail closed. These paths do not convert wallets or change registrations. + 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. +For a wallet-side RPC -18, compare `listwallets` with `listwalletdir`: a wallet on +disk need not be loaded. An authorized operator can load the existing wallet with +`loadwallet "dashnet" true` to persist autoload, then recheck exports; the read-only +key service does not load wallets itself. Core can keep processing a timed-out +load request, so reconcile `listwallets`, `getrpcinfo` and wallet scan state before +retrying. Verify the wallet entry in Core's startup settings without restarting +the node solely to test persistence. ### CI host remediation exclusions diff --git a/agent/devnet-keys.py b/agent/devnet-keys.py index 36950bb..2963558 100644 --- a/agent/devnet-keys.py +++ b/agent/devnet-keys.py @@ -1,13 +1,133 @@ #!/usr/bin/env python3 """Read-only, identity-checked devnet key export; stdout is private transport only.""" import base64 +import hashlib +import hmac import json from pathlib import Path +import re import subprocess import sys import urllib.request +ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' +ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 + + +def b58encode(raw): + data = raw + hashlib.sha256(hashlib.sha256(raw).digest()).digest()[:4] + value, out = int.from_bytes(data, 'big'), '' + while value: + value, digit = divmod(value, 58) + out = ALPHABET[digit] + out + return '1' * (len(data) - len(data.lstrip(b'\0'))) + out + + +def b58decode(text): + assert 0 < len(text) < 120 + value = 0 + for char in text: + value = value * 58 + ALPHABET.index(char) + data = b'\0' * (len(text) - len(text.lstrip('1'))) + value.to_bytes((value.bit_length() + 7) // 8, 'big') + raw, checksum = data[:-4], data[-4:] + assert hashlib.sha256(hashlib.sha256(raw).digest()).digest()[:4] == checksum + return raw + + +def public_key(key): + assert 0 < key < ORDER + # OpenSSL handles secp256k1; the scalar is stdin only, never argv/files/errors. + der = bytes.fromhex('302e0201010420') + key.to_bytes(32, 'big') + bytes.fromhex('a00706052b8104000a') + result = subprocess.run(['openssl', 'ec', '-inform', 'DER', '-pubout', '-outform', 'DER', '-conv_form', 'compressed'], + input=der, capture_output=True, timeout=10) + assert result.returncode == 0 and len(result.stdout) == 56 + pub = result.stdout[-33:] + assert pub[0] in (2, 3) + return pub + + +def child_key(key, chain_code, index): + assert 0 <= index < 2 ** 32 and 0 < key < ORDER and len(chain_code) == 32 + data = b'\0' + key.to_bytes(32, 'big') if index >= 2 ** 31 else public_key(key) + digest = hmac.new(chain_code, data + index.to_bytes(4, 'big'), hashlib.sha512).digest() + left = int.from_bytes(digest[:32], 'big') + child = (left + key) % ORDER + assert left < ORDER and child != 0 + return child, digest[32:] + + +def path_parts(path): + parts = [] + for item in path.split('/'): + assert re.fullmatch(r"[0-9]+['hH]?", item) + hardened = item[-1] in "'hH" + value = int(item[:-1] if hardened else item) + assert value < 2 ** 31 + parts.append(value + (2 ** 31 if hardened else 0)) + return parts + + +def descriptor_key(descriptor, hd_path): + # Managed wallets use single-key P2PKH descriptors, not arbitrary scripts. + match = re.fullmatch(r"pkh\((?:\[([0-9a-fA-F]{8})((?:/[0-9]+['hH]?)*?)\])?([1-9A-HJ-NP-Za-km-z]+)((?:/(?:[0-9]+['hH]?|\*))+?)\)(?:#[a-z0-9]{8})?", descriptor) + assert match and hd_path.startswith('m/') + origin = path_parts(match[2][1:]) if match[2] else [] + actual = path_parts(hd_path[2:]) + suffix = match[4][1:].split('/') + assert suffix[-1] == '*' and suffix.count('*') == 1 + relative = path_parts('/'.join(suffix[:-1])) if len(suffix) > 1 else [] + assert actual == origin + relative + [actual[-1]] and actual[-1] < 2 ** 31 + raw = b58decode(match[3]) + # Test/devnet extended private key, exact depth/origin, never Mainnet. + assert len(raw) == 78 and raw[:4] == bytes.fromhex('04358394') and raw[4] == len(origin) and raw[45] == 0 + key, code = int.from_bytes(raw[46:], 'big'), raw[13:45] + for index in relative + [actual[-1]]: + key, code = child_key(key, code, index) + return b58encode(b'\xef' + key.to_bytes(32, 'big') + b'\x01') + + +def verified_address(rpc, key, address): + info = rpc('getdescriptorinfo', ['pkh(' + key + ')']) + assert info.get('hasprivatekeys') is True and info.get('isrange') is False + assert key not in info['descriptor'] + assert rpc('deriveaddresses', [info['descriptor']]) == [address] + return key + + +def wallet_exporter(rpc): + wallets, descriptors, exported = {}, {}, {} + + def export(address, wallet): + cache_key = (wallet, address) + if cache_key in exported: + return exported[cache_key] + if wallet not in wallets: + wallets[wallet] = rpc('getwalletinfo', wallet=wallet) + if not wallets[wallet].get('descriptors', False): + key = rpc('dumpprivkey', [address], wallet) + else: + info = rpc('getaddressinfo', [address], wallet) + assert info.get('ismine') is True and not info.get('iswatchonly', False) + if wallet not in descriptors: + entries = rpc('listdescriptors', [True], wallet)['descriptors'] + # Ranged only: Core refuses a range for a fixed descriptor (RPC -8), + # which would end the export before the HD parent is compared. + descriptors[wallet] = [e['desc'] for e in entries if e['desc'].startswith('pkh(') and '*' in e['desc']] + index = path_parts(info['hdkeypath'][2:])[-1] + assert index < 2 ** 31 + # Core's normalized parent descriptor may move hardened derivation + # into the extended key. Match the actual address, not its spelling. + matching = [d for d in descriptors[wallet] + if rpc('deriveaddresses', [d, [index, index]]) == [address]] + assert len(matching) == 1 + private = matching[0] + key = descriptor_key(private, info['hdkeypath']) + exported[cache_key] = verified_address(rpc, key, address) + return key + return export + + 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() @@ -36,6 +156,7 @@ def rpc(method, params=None, wallet=None): return {'operatorPrivateKey': secret['operatorPrivateKey'], 'platformNodePrivateKey': secret['nodePrivateKey']} assert q['host']['role'] == 'wallet' + export = wallet_exporter(rpc) keys = {} for h in q['validators']: info = rpc('protx', ['info', h['proTxHash']]) @@ -46,13 +167,14 @@ def rpc(method, params=None, wallet=None): row = {} for kind, address in fields.items(): row[kind + 'Address'] = address - row[kind + 'PrivateKey'] = rpc('dumpprivkey', [address], 'dashnet') + row[kind + 'PrivateKey'] = export(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) + network[kind + 'PrivateKey'] = (verified_address(rpc, secret['sporkKey'], address) + if kind == 'spork' and secret.get('sporkKey') else export(address, wallet)) return {'validators': keys, 'networkKeys': network} diff --git a/agent/test_devnet_keys.py b/agent/test_devnet_keys.py new file mode 100644 index 0000000..ba5a673 --- /dev/null +++ b/agent/test_devnet_keys.py @@ -0,0 +1,139 @@ +"""Public BIP32 vectors and fail-closed export tests; no live private material.""" +import importlib.util +from pathlib import Path +import unittest + +spec = importlib.util.spec_from_file_location('devnet_keys', Path(__file__).with_name('devnet-keys.py')) +keys = importlib.util.module_from_spec(spec) +spec.loader.exec_module(keys) + +# https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#test-vector-1 +VECTORS = [ + 'xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi', + 'xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7', + 'xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs', + 'xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM', + 'xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334', + 'xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76', +] + + +def testnet_extended(vector): + raw = keys.b58decode(vector) + return keys.b58encode(bytes.fromhex('04358394') + raw[4:]) + + +class Derivation(unittest.TestCase): + def test_bip32_hardened_and_normal_children(self): + raw = keys.b58decode(VECTORS[0]) + key, code = int.from_bytes(raw[46:], 'big'), raw[13:45] + for index, expected in zip([2**31, 1, 2**31 + 2, 2, 1000000000], VECTORS[1:]): + key, code = keys.child_key(key, code, index) + expected = keys.b58decode(expected) + self.assertEqual(key.to_bytes(32, 'big'), expected[46:]) + self.assertEqual(code, expected[13:45]) + + def test_descriptor_from_master_and_account_roots(self): + full_path = 'm/0h/1/2h/2/1000000000' + master = 'pkh(' + testnet_extended(VECTORS[0]) + '/0h/1/2h/2/*)' + account = 'pkh([3442193e/0h/1/2h]' + testnet_extended(VECTORS[3]) + '/2/*)' + expected = b'\xef' + keys.b58decode(VECTORS[-1])[46:] + b'\x01' + self.assertEqual(keys.b58decode(keys.descriptor_key(master, full_path)), expected) + self.assertEqual(keys.b58decode(keys.descriptor_key(account, full_path)), expected) + self.assertEqual(keys.descriptor_key(account, full_path.replace('h', "'")), keys.descriptor_key(master, full_path)) + + def test_reject_wrong_chain_path_depth_and_script(self): + root = testnet_extended(VECTORS[0]) + cases = [ + ('pkh(' + VECTORS[0] + '/0/*)', 'm/0/1'), + ('pkh(' + root + '/0/*)', 'm/1/1'), + ('pkh([3442193e/0h]' + root + '/0/*)', 'm/0h/0/1'), + ('wpkh(' + root + '/0/*)', 'm/0/1'), + ('pkh(' + root + '/0/*/*)', 'm/0/1/1'), + ] + for desc, path in cases: + with self.assertRaises(AssertionError): + keys.descriptor_key(desc, path) + + def test_base58_checksum_and_scalar_checks(self): + with self.assertRaises(AssertionError): + keys.b58decode(VECTORS[0][:-1] + '1') + for scalar in [0, keys.ORDER]: + with self.assertRaises(AssertionError): + keys.public_key(scalar) + + +class Exports(unittest.TestCase): + def rpc(self, method, params=None, wallet=None): + self.calls.append((method, wallet)) + if method == 'getwalletinfo': + return {'descriptors': self.descriptors} + if method == 'dumpprivkey': + return 'synthetic-private' + if method == 'getaddressinfo': + return {'ismine': self.owned, 'iswatchonly': False, 'hdkeypath': 'm/0h/1/2h/2/1000000000'} + if method == 'listdescriptors': + return {'descriptors': [{'desc': self.desc}] * self.match_count + [{'desc': d} for d in self.fixed]} + if method == 'deriveaddresses': + if len(params) == 2: # Core independently identifies the parent. + # Core: "Range should not be specified for an un-ranged descriptor" (-8). + assert '*' in params[0], 'range given for a fixed descriptor' + return ['synthetic-address'] + return [self.derived_address] + if method == 'getdescriptorinfo': + return {'hasprivatekeys': True, 'isrange': False, 'descriptor': 'pkh(synthetic-public)'} + raise AssertionError('unexpected RPC') + + def setUp(self): + self.calls = [] + self.descriptors = True + self.owned = True + self.match_count = 1 + self.fixed = [] + self.derived_address = 'synthetic-address' + self.desc = 'pkh([3442193e/0h/1/2h]' + testnet_extended(VECTORS[3]) + '/2/*)' + + def test_descriptor_export_verifies_address_and_caches(self): + export = keys.wallet_exporter(self.rpc) + result = export('synthetic-address', 'dashnet') + before = len(self.calls) + self.assertEqual(export('synthetic-address', 'dashnet'), result) + self.assertEqual(len(self.calls), before) + self.assertEqual(keys.b58decode(result)[1:-1], keys.b58decode(VECTORS[-1])[46:]) + self.assertNotIn(('dumpprivkey', 'dashnet'), self.calls) + + def test_fixed_descriptor_beside_the_hd_parent_does_not_end_the_export(self): + # An imported single key sits next to the ranged parent; it must never be probed with a range. + self.fixed = ['pkh(synthetic-imported-key)#abcdefgh', 'pkh([3442193e/0h]' + testnet_extended(VECTORS[1]) + '/1)'] + result = keys.wallet_exporter(self.rpc)('synthetic-address', 'dashnet') + self.assertEqual(keys.b58decode(result)[1:-1], keys.b58decode(VECTORS[-1])[46:]) + + def test_legacy_wallet_remains_supported(self): + self.descriptors = False + self.assertEqual(keys.wallet_exporter(self.rpc)('synthetic-address', 'faucet'), 'synthetic-private') + self.assertIn(('dumpprivkey', 'faucet'), self.calls) + self.assertNotIn(('listdescriptors', 'faucet'), self.calls) + + def test_wrong_derived_address_rejected(self): + self.derived_address = 'wrong-address' + with self.assertRaises(AssertionError): + keys.wallet_exporter(self.rpc)('synthetic-address', 'dashnet') + + def test_unowned_or_ambiguous_descriptor_rejected(self): + self.owned = False + with self.assertRaises(AssertionError): + keys.wallet_exporter(self.rpc)('synthetic-address', 'dashnet') + self.owned = True + for count in [0, 2]: + self.match_count = count + with self.assertRaises(AssertionError): + keys.wallet_exporter(self.rpc)('synthetic-address', 'dashnet') + + def test_spork_must_match_registered_address(self): + self.derived_address = 'different-spork' + with self.assertRaises(AssertionError): + keys.verified_address(self.rpc, 'synthetic-spork', 'synthetic-address') + + +if __name__ == '__main__': + unittest.main() diff --git a/deploy/deploy.sh b/deploy/deploy.sh index 77444dc..9472ec6 100755 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -20,25 +20,42 @@ docker run --rm --network none --read-only \ 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 -# Preserve the optional incident sidecar on future rollouts. Loading the small -# compose env file only supplies a non-secret receiver URL; never source it. +# Preserve the optional incident and devnet key sidecars on future rollouts. +# Loading the small compose env file only supplies a non-secret receiver URL; +# never source it. The key sidecar is on wherever its socket directory exists +# (README, "Devnet operator keys"). Leaving its file out would drop web's socket +# and, on a full rollout, remove the helper as an orphan. +web_services=web +if [ -d /srv/dash-status/key-access ]; then web_services="web keys"; fi compose() { + files="-f deploy/compose.yml"; env_file= if [ -f /etc/dash-status/incidents/compose.env ]; then install -d -o 1000 -g 1000 -m 0700 /srv/dash-status/data/incidents - docker compose --env-file /etc/dash-status/incidents/compose.env -f deploy/compose.yml -f deploy/incident-compose.yml "$@" - else - docker compose -f deploy/compose.yml "$@" + env_file="--env-file /etc/dash-status/incidents/compose.env"; files="$files -f deploy/incident-compose.yml" fi + if [ -d /srv/dash-status/key-access ]; then files="$files -f deploy/devnet-keys-compose.yml"; fi + # shellcheck disable=SC2086 # deliberate word splitting of fixed option lists + docker compose $env_file $files "$@" } docker tag "dash-status:${rev}" dash-status:current +# The key helper serves one read per request and runs no operation, so a +# web-only rollout may replace it together with web. case "${DEPLOY_ONLY:-}" in "") compose up -d --remove-orphans ;; - web) compose up -d --no-deps web ;; + web) compose up -d --no-deps $web_services ;; *) echo "DEPLOY_ONLY must be empty or web" >&2; exit 2 ;; esac +# Web's health endpoint does not consult the key socket, so a rollout that also +# replaced the key helper is healthy only when the helper's own check passes. +healthy() { + curl -fsS -m 3 http://127.0.0.1:3006/api/health >/dev/null 2>&1 || return 1 + if [ "$web_services" = web ]; then return 0; fi + keys_id=$(compose ps -q keys 2>/dev/null) || return 1 + [ -n "$keys_id" ] && [ "$(docker inspect --format '{{.State.Health.Status}}' "$keys_id" 2>/dev/null)" = healthy ] +} for i in $(seq 1 30); do - if curl -fsS -m 3 http://127.0.0.1:3006/api/health >/dev/null 2>&1; then - echo "web healthy on ${rev}"; compose ps --format '{{.Service}} {{.Status}}' + if healthy; then + echo "$web_services healthy on ${rev}"; compose ps --format '{{.Service}} {{.Status}}' # Each deploy leaves a ~370 MB image: keep the running one and the two # newest others for rollback, so the root disk never fills (a full disk # fails the next build mid-download). @@ -53,9 +70,9 @@ for i in $(seq 1 30); do fi sleep 2 done -echo "web did not become healthy; rolling back" >&2 +echo "$web_services did not become healthy; rolling back" >&2 if [ -n "$previous" ]; then docker tag "$previous" dash-status:current - if [ "${DEPLOY_ONLY:-}" = web ]; then compose up -d --no-deps web; else compose up -d; fi + if [ "${DEPLOY_ONLY:-}" = web ]; then compose up -d --no-deps $web_services; else compose up -d; fi fi exit 1 diff --git a/server/devnet-keys.js b/server/devnet-keys.js index 925906e..7930884 100644 --- a/server/devnet-keys.js +++ b/server/devnet-keys.js @@ -1,7 +1,11 @@ import { request } from 'node:http'; +// A key service that is not deployed or not listening is a deployment fault, not a +// refused request. The code lets web say so; the message never carries internals. +const down = message => Object.assign(Error(message), { code: 'key-service-down' }); +const NOT_LISTENING = new Set(['ENOENT', 'ECONNREFUSED', 'EACCES', 'ENOTSOCK']); export function requestDevnetKeys(socketPath, network, user) { return new Promise((resolve, reject) => { - if (!socketPath) return reject(Error('Devnet key access is not configured')); + if (!socketPath) return reject(down('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')); }); @@ -9,7 +13,7 @@ export function requestDevnetKeys(socketPath, network, user) { 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.on('error', e => reject(NOT_LISTENING.has(e?.code) ? down('Devnet key service is not running') : Error('Devnet key service unavailable'))); req.end(JSON.stringify({ network, user })); }); } diff --git a/server/web.js b/server/web.js index 2e92924..a306b1b 100644 --- a/server/web.js +++ b/server/web.js @@ -348,7 +348,14 @@ export function createWeb({ dataDir, origin, auth: authDeps, fetcher = fetch, cl 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' }); } + } catch (e) { + // A missing key service is a deployment fault; do not blame the devnet for it. + if (e?.code === 'key-service-down') { + console.warn(JSON.stringify({ event: 'devnet-key-service-down', network: n.name, at: new Date(clock()).toISOString() })); + return res.status(503).json({ error: 'Keys unavailable: the key service is not running on the status host' }); + } + 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, csrf, (req, res) => { const n = settings.networks.find((x) => x.name === req.params.name); diff --git a/server/web.test.js b/server/web.test.js index 8fef6c5..b48bd5f 100644 --- a/server/web.test.js +++ b/server/web.test.js @@ -5,6 +5,7 @@ import { mkdtempSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSyn import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { createWeb, ttlCache } from './web.js'; +import { requestDevnetKeys } from './devnet-keys.js'; import { DEFAULT_SETTINGS } from '../shared/settings.js'; async function start(userId = 9920871, extraUsers = [], options = {}) { @@ -350,6 +351,24 @@ test('key route excludes Mainnet/Testnet and suppresses internal errors', async } finally { w.close(); } }); +test('key route names a missing key service instead of blaming the devnet', async () => { + // Default reader, no socket configured: what a web container rolled without the keys overlay sees. + const w = await start(9920871, [], { keySocket: '' }); + try { + const csrf = await w.login(), headers = { 'x-csrf-token': csrf }; + 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); + const { error } = await response.json(); + assert.match(error, /key service is not running/); assert.doesNotMatch(error, /must be idle/); + } finally { w.close(); } +}); + +test('key reader marks an absent or unreachable socket, and only that, as a service fault', async () => { + await assert.rejects(requestDevnetKeys('', 'devnet-sakura', { id: 1 }), { code: 'key-service-down' }); + await assert.rejects(requestDevnetKeys(join(tmpdir(), `absent-${process.pid}-keys.sock`), 'devnet-sakura', { id: 1 }), { code: 'key-service-down' }); +}); + 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 } : {}) } });