From d781e5beb87fccbd917d5ee80ed4385e3ff878ed Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:04:22 +0100 Subject: [PATCH 001/114] fix(auth): an unreachable database no longer switches logins off has_any_users() answered False on any database error and the dashboard cached that as 'no accounts' for the life of the worker: a dashboard that started before Postgres accepted connections served every anonymous request as root admin, also after Postgres was back. The answer is now True, False or unknown. While unknown, logins stay required and the question is repeated (at most every 5 s) until the database answers; the start-up bootstrap that was skipped (users table, admin from .env) runs first, so a first start that raced Postgres does not conclude there are no accounts. --- dashboard/app.py | 37 +++++++++++-- dashboard/user_db.py | 10 ++-- tests/test_auth_fail_closed.py | 97 ++++++++++++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 7 deletions(-) create mode 100644 tests/test_auth_fail_closed.py diff --git a/dashboard/app.py b/dashboard/app.py index 9c0a432..63d2242 100644 --- a/dashboard/app.py +++ b/dashboard/app.py @@ -121,9 +121,39 @@ def theme_inline(): except Exception as _exc: # noqa: BLE001 — before migration 046, or the database is not up yet app.logger.info('email address check skipped: %s', _exc) -# auth is enabled iff at least one user row exists. Cached at startup — restart -# is required if the table goes from empty to populated outside of the UI -_AUTH_ENABLED = user_db.has_any_users() +# auth is enabled iff at least one user row exists. Cached once the database has answered — restart +# is required if the table goes from empty to populated outside of the UI. Until it has answered +# (Postgres still starting, or down) authentication stays ON: an unreachable database is not "no users". +_AUTH_ENABLED = True +_auth_known = False +_auth_checked_at = 0.0 +_auth_lock = threading.Lock() + + +def _refresh_auth_enabled(min_interval: float = 5.0) -> None: + """Ask the database whether accounts exist, until it has answered once. While the answer is unknown + every request is treated as needing a login; the question is repeated at most every few seconds.""" + global _AUTH_ENABLED, _auth_known, _auth_checked_at + if _auth_known: + return + with _auth_lock: + if _auth_known or time.monotonic() - _auth_checked_at < min_interval: + return + first = _auth_checked_at == 0.0 + _auth_checked_at = time.monotonic() + if not first: + # the start-up bootstrap ran against a database that was not there: do it now, before + # concluding that there are no accounts + user_db.ensure_table() + user_db.seed_admin_from_env() + state = user_db.has_any_users() + if state is None: + app.logger.warning('user store unreachable: logins stay required until it answers') + return + _AUTH_ENABLED, _auth_known = bool(state), True + + +_refresh_auth_enabled() class AccessDenied(Exception): @@ -232,6 +262,7 @@ def deco(f): @app.before_request def _access_fresh(): + _refresh_auth_enabled() access_db.begin_request() diff --git a/dashboard/user_db.py b/dashboard/user_db.py index 10cebc9..71efdf9 100644 --- a/dashboard/user_db.py +++ b/dashboard/user_db.py @@ -122,8 +122,10 @@ def seed_admin_from_env() -> None: # public API # --------------------------------------------------------------------------- -def has_any_users() -> bool: - """Return True if at least one user row exists (auth is enabled).""" +def has_any_users() -> bool | None: + """True when at least one user row exists (auth is enabled), False when the table is empty, + None when the database could not be asked. Unknown is not "no users": the caller keeps + authentication on until the database answers.""" try: conn = _connect() try: @@ -133,8 +135,8 @@ def has_any_users() -> bool: finally: conn.close() except Exception as exc: - logger.warning('user_db: has_any_users() DB error, assuming no users: %s', exc) - return False + logger.warning('user_db: has_any_users() DB error, answer unknown: %s', exc) + return None def get_by_username(username: str) -> dict | None: diff --git a/tests/test_auth_fail_closed.py b/tests/test_auth_fail_closed.py new file mode 100644 index 0000000..bceb512 --- /dev/null +++ b/tests/test_auth_fail_closed.py @@ -0,0 +1,97 @@ +""" +Authentication must not switch off because the database could not be asked. + +Before 1.8.1 `user_db.has_any_users()` answered False on any database error and the dashboard cached +that as "no accounts, no login needed" for the life of the worker: a dashboard that started before +Postgres accepted connections served every anonymous request as root admin. +""" +from __future__ import annotations + +import logging +import re +import sys +import threading +import time +import types + +for _name in ('pyotp', 'qrcode', 'qrcode.image', 'qrcode.image.pil'): # user_db imports them; the gate does not use them + sys.modules.setdefault(_name, types.ModuleType(_name)) + +import user_db # noqa: E402 + + +def test_an_unreachable_database_is_not_no_users(monkeypatch): + def boom(): + raise RuntimeError('connection refused') + monkeypatch.setattr(user_db, '_connect', boom) + assert user_db.has_any_users() is None + + +class _Cur: + def __init__(self, row): self.row = row + def __enter__(self): return self + def __exit__(self, *a): return False + def execute(self, *a): pass + def fetchone(self): return self.row + + +class _Conn: + def __init__(self, row): self.row = row + def cursor(self): return _Cur(self.row) + def close(self): pass + + +def test_an_answering_database_is_believed(monkeypatch): + monkeypatch.setattr(user_db, '_connect', lambda: _Conn({'?column?': 1})) + assert user_db.has_any_users() is True + monkeypatch.setattr(user_db, '_connect', lambda: _Conn(None)) + assert user_db.has_any_users() is False + + +def _gate(repo, answers): + """The start-up block of app.py that decides whether logins are required, run against a fake user store + that gives `answers` in order (None = database unreachable).""" + src = (repo / 'dashboard' / 'app.py').read_text() + m = re.search(r'^_AUTH_ENABLED = True\n.*?^_refresh_auth_enabled\(\)\n', src, re.S | re.M) + assert m, 'the auth gate block moved: update this test' + calls = {'bootstrap': 0} + seq = iter(answers) + store = types.SimpleNamespace( + has_any_users=lambda: next(seq), + ensure_table=lambda: calls.__setitem__('bootstrap', calls['bootstrap'] + 1), + seed_admin_from_env=lambda: None) + ns = {'threading': threading, 'time': time, 'user_db': store, + 'app': types.SimpleNamespace(logger=logging.getLogger('test'))} + exec(m.group(0), ns) # noqa: S102 — our own source + return ns, calls + + +def test_logins_stay_required_while_the_database_is_down(repo): + ns, calls = _gate(repo, [None, None, True]) + assert ns['_AUTH_ENABLED'] is True and ns['_auth_known'] is False + ns['_refresh_auth_enabled'](min_interval=0) + assert ns['_AUTH_ENABLED'] is True and ns['_auth_known'] is False + ns['_refresh_auth_enabled'](min_interval=0) + assert ns['_AUTH_ENABLED'] is True and ns['_auth_known'] is True + assert calls['bootstrap'] == 2, 'the skipped start-up bootstrap is repeated before the question' + + +def test_a_database_that_comes_back_empty_is_bootstrapped_before_auth_goes_off(repo): + # a first start that raced Postgres: the admin from .env was never seeded, so "no rows" would be wrong + ns, calls = _gate(repo, [None, False]) + ns['_refresh_auth_enabled'](min_interval=0) + assert calls['bootstrap'] == 1 + assert ns['_AUTH_ENABLED'] is False and ns['_auth_known'] is True # truly no accounts: first-run mode + + +def test_the_question_is_not_repeated_on_every_request(repo): + ns, _ = _gate(repo, [None, True]) + ns['_refresh_auth_enabled']() # default interval: too soon, not asked again + assert ns['_auth_known'] is False + + +def test_a_known_answer_is_final(repo): + ns, _ = _gate(repo, [True]) + assert ns['_auth_known'] is True + ns['_refresh_auth_enabled'](min_interval=0) # would raise StopIteration if it asked again + assert ns['_AUTH_ENABLED'] is True From 2f98b04919773294c1c7b7572d2deed7d0e53453 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:06:56 +0100 Subject: [PATCH 002/114] fix(infraviewer): a migrated VM is listed on the node it runs on now The VM list took a VM's node (and name, tag, VLAN) from the first vm_metrics series in the range. Node is a tag, so a VM that live-migrated inside the range has a series per node, and the lowest node won for as long as the old series stayed in range: on a cluster where VMs move, 'group by node' showed the newest node empty or missing. A VM is now described as of its newest sample (vm_rows.py) and its history is one series, oldest first. The allocated-vCPU figure on the node cards had the same cause and counted a migrated VM on every node it ran on in the last hour: only a VM's newest inventory row counts, and only while the VM still reports. --- dashboard/Dockerfile | 1 + dashboard/app.py | 45 +++++++++++---------------------- dashboard/vm_rows.py | 41 ++++++++++++++++++++++++++++++ tests/test_vm_rows.py | 58 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 114 insertions(+), 31 deletions(-) create mode 100644 dashboard/vm_rows.py create mode 100644 tests/test_vm_rows.py diff --git a/dashboard/Dockerfile b/dashboard/Dockerfile index 9c6d048..2c952da 100644 --- a/dashboard/Dockerfile +++ b/dashboard/Dockerfile @@ -24,6 +24,7 @@ COPY dashboard/verify_mail.py . COPY dashboard/forwarding.py . COPY dashboard/alerts.py . COPY dashboard/storage_summary.py . +COPY dashboard/vm_rows.py . COPY dashboard/manual.py . COPY dashboard/cluster_registry.py . COPY dashboard/hypercore_tasks.py . diff --git a/dashboard/app.py b/dashboard/app.py index 63d2242..a035623 100644 --- a/dashboard/app.py +++ b/dashboard/app.py @@ -61,6 +61,7 @@ import config_db import user_db import backup_scope +import vm_rows import rbac import access_db import cluster_registry @@ -531,15 +532,22 @@ def get_nodes(): if 'num_threads' not in nodes[node_uuid]: nodes[node_uuid]['num_threads'] = int(record.values.get('num_threads') or 0) - # fetch latest allocated vCPUs per node from vm_inventory + # fetch latest allocated vCPUs per node from vm_inventory. Node and state are tags, so a VM that + # migrated or stopped inside the hour has several series: only its newest one counts, or it would be + # added to every node it ran on + # (and only the last polls are read, as in _vm_sizes: a deleted VM stops counting when it stops reporting) + fresh = max(60, int(_stale_seconds())) vcpu_query = f''' from(bucket: "{INFLUX_BUCKET}") - |> range(start: -1h) + |> range(start: -{fresh}s) {_flux_cluster()} |> filter(fn: (r) => r["_measurement"] == "vm_inventory") |> filter(fn: (r) => r["_field"] == "num_vcpu") - |> filter(fn: (r) => r["vm_state"] == "RUNNING") |> last() + |> group(columns: ["vm_uuid"]) + |> sort(columns: ["_time"]) + |> last() + |> filter(fn: (r) => r["vm_state"] == "RUNNING") |> group(columns: ["node_uuid"]) |> sum() ''' @@ -657,35 +665,10 @@ def get_vms(): ''' result = client.query_api().query(org=INFLUX_ORG, query=query) - vms = {} - for table in result: - for record in table.records: - vm_uuid = record.values.get('vm_uuid', 'unknown') - vm_name = record.values.get('vm_name', 'Unknown') - node_uuid = record.values.get('node_uuid', 'unknown') - - # skip records from in-flight migration state (no node assignment yet) - if node_uuid == 'unknown': - continue - - if vm_uuid not in vms: - vms[vm_uuid] = { - 'uuid': vm_uuid, - 'name': vm_name, - 'node_uuid': node_uuid, - 'node_peer_id': record.values.get('node_peer_id', 'unknown'), - 'tag': record.values.get('vm_tag', ''), - 'vlan': record.values.get('vm_vlan', '0'), - 'history': [] - } + # one row per VM, described as of its newest sample: a VM that migrated inside the range has a + # series per node and belongs to the node it is on now (vm_rows.py) + vms = vm_rows.fold((record.get_time(), record.values) for table in result for record in table.records) - vms[vm_uuid]['history'].append({ - 'time': record.get_time().isoformat(), - 'cpu_usage': record.values.get('cpu_usage'), - 'rx_bit_rate': record.values.get('rx_bit_rate'), - 'tx_bit_rate': record.values.get('tx_bit_rate') - }) - # fetch true current CPU per VM (last measurement, independent of time range) current_query = f''' from(bucket: "{INFLUX_BUCKET}") diff --git a/dashboard/vm_rows.py b/dashboard/vm_rows.py new file mode 100644 index 0000000..fb8c7a7 --- /dev/null +++ b/dashboard/vm_rows.py @@ -0,0 +1,41 @@ +""" +vm_rows.py — one row per VM from vm_metrics records, pure. + +vm_metrics carries the node a VM runs on as tags (node_uuid, node_peer_id), next to its name, first +tag and VLAN. A VM that live-migrates inside the queried range therefore has one series per node it +ran on. The row describes the VM as of its NEWEST sample: taking the first series seen (the lowest +node in tag order) kept a migrated VM under its old node for as long as that series stayed in range, +which emptied the newest node in the "group by node" view. +""" +from __future__ import annotations + +from datetime import datetime +from typing import Any, Iterable + +# tags that describe the VM at the time of a sample +_AS_OF = (('name', 'vm_name', 'Unknown'), ('node_uuid', 'node_uuid', 'unknown'), + ('node_peer_id', 'node_peer_id', 'unknown'), ('tag', 'vm_tag', ''), ('vlan', 'vm_vlan', '0')) + + +def fold(records: Iterable[tuple[datetime, dict[str, Any]]]) -> dict[str, dict[str, Any]]: + """{vm_uuid: row} from (time, values) pairs in any order. Each row has uuid, name, node_uuid, + node_peer_id, tag, vlan (all as of the newest sample) and history, oldest first. Samples taken + while a VM had no node (mid-migration) are left out.""" + vms: dict[str, dict[str, Any]] = {} + newest: dict[str, datetime] = {} + for when, values in records: + if values.get('node_uuid', 'unknown') == 'unknown': + continue + uuid = values.get('vm_uuid', 'unknown') + vm = vms.get(uuid) + if vm is None: + vm = vms[uuid] = {'uuid': uuid, 'history': []} + if uuid not in newest or when >= newest[uuid]: + newest[uuid] = when + for key, tag, default in _AS_OF: + vm[key] = values.get(tag, default) + vm['history'].append({'time': when.isoformat(), 'cpu_usage': values.get('cpu_usage'), + 'rx_bit_rate': values.get('rx_bit_rate'), 'tx_bit_rate': values.get('tx_bit_rate')}) + for vm in vms.values(): + vm['history'].sort(key=lambda h: h['time']) + return vms diff --git a/tests/test_vm_rows.py b/tests/test_vm_rows.py new file mode 100644 index 0000000..9b2df7a --- /dev/null +++ b/tests/test_vm_rows.py @@ -0,0 +1,58 @@ +"""dashboard/vm_rows.py — a VM belongs to the node of its newest sample, not of the first series found.""" +import os +import sys +from datetime import datetime, timedelta, timezone + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'dashboard')) +import vm_rows # noqa: E402 + +NOW = datetime(2026, 11, 22, 16, 0, tzinfo=timezone.utc) + + +def _rec(minutes_ago, vm='vm-a', node='node-1', peer='1', cpu=10.0, **tags): + values = {'vm_uuid': vm, 'vm_name': tags.get('name', 'alpha'), 'node_uuid': node, 'node_peer_id': peer, + 'vm_tag': tags.get('tag', 'prod'), 'vm_vlan': tags.get('vlan', '102'), + 'cpu_usage': cpu, 'rx_bit_rate': 1.0, 'tx_bit_rate': 2.0} + return NOW - timedelta(minutes=minutes_ago), values + + +def test_a_migrated_vm_is_listed_on_the_node_it_runs_on_now(): + # Influx returns one table per series, the old node's (tag '1') before the new node's (tag '3') + recs = [_rec(120), _rec(90), _rec(60), _rec(30, node='node-3', peer='3'), _rec(5, node='node-3', peer='3')] + vm = vm_rows.fold(recs)['vm-a'] + assert (vm['node_uuid'], vm['node_peer_id']) == ('node-3', '3') + + +def test_the_order_of_the_series_does_not_matter(): + recs = [_rec(5, node='node-3', peer='3'), _rec(30, node='node-3', peer='3'), _rec(120), _rec(60)] + vm = vm_rows.fold(recs)['vm-a'] + assert vm['node_peer_id'] == '3' + times = [h['time'] for h in vm['history']] + assert times == sorted(times) and len(times) == 4, 'history is one series, oldest first' + + +def test_name_tag_and_vlan_follow_the_newest_sample_too(): + recs = [_rec(60, name='old-name', tag='test', vlan='0'), _rec(5, name='new-name', tag='prod', vlan='201')] + vm = vm_rows.fold(recs)['vm-a'] + assert (vm['name'], vm['tag'], vm['vlan']) == ('new-name', 'prod', '201') + + +def test_samples_without_a_node_are_left_out(): + recs = [_rec(60), _rec(5, node='unknown', peer='unknown')] + vm = vm_rows.fold(recs)['vm-a'] + assert vm['node_peer_id'] == '1' and len(vm['history']) == 1 + assert vm_rows.fold([_rec(5, vm='vm-b', node='unknown', peer='unknown')]) == {} + + +def test_every_node_with_a_vm_gets_its_group(): + # the reported case: three nodes, the VMs on node 3 all arrived there by migration + recs = [_rec(600, vm='a'), _rec(5, vm='a', node='node-3', peer='3'), + _rec(600, vm='b', node='node-2', peer='2'), _rec(5, vm='b', node='node-3', peer='3'), + _rec(5, vm='c'), _rec(5, vm='d', node='node-2', peer='2')] + peers = sorted({v['node_peer_id'] for v in vm_rows.fold(recs).values()}) + assert peers == ['1', '2', '3'] + + +def test_defaults_when_tags_are_missing(): + vm = vm_rows.fold([(NOW, {'vm_uuid': 'x', 'node_uuid': 'n'})])['x'] + assert (vm['name'], vm['node_peer_id'], vm['tag'], vm['vlan']) == ('Unknown', 'unknown', '', '0') From cd35e732b54908836dd7eef86836dd732ba6e0d2 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:13:37 +0100 Subject: [PATCH 003/114] fix(proxy): retention leaves checksums that verify (proxy 0.6.3) A prune folds the oldest delta into the base (qemu-img commit) and rebases the next delta onto it. Both files change, but the manifests kept the checksums taken when the points were written: after the first prune every verification reported 'checksum differs' for the base and the next point, and a restore with verification (the default) refused the chain with 'chain integrity check failed, nothing restored'. The data was intact. run_prune now hashes the files it rewrote once the chain has its final shape and writes the new checksums into the two manifests. A chain pruned by an older proxy heals on its next prune, which commits into every base file again. --- proxy/identity.py | 2 +- proxy/jobs.py | 32 ++++++++++++++++++++++++++++++ tests/test_proxy.py | 47 ++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 79 insertions(+), 2 deletions(-) diff --git a/proxy/identity.py b/proxy/identity.py index 0fac1da..8c78b6b 100644 --- a/proxy/identity.py +++ b/proxy/identity.py @@ -9,7 +9,7 @@ import socket import subprocess -VERSION = '0.6.2' +VERSION = '0.6.3' _SKIP_PREFIXES = ('lo', 'docker', 'veth', 'br-', 'virbr', 'cni', 'flannel', 'tun', 'tap', 'wg') diff --git a/proxy/jobs.py b/proxy/jobs.py index 28bf4f8..a9fe530 100644 --- a/proxy/jobs.py +++ b/proxy/jobs.py @@ -422,6 +422,11 @@ def run_prune(self, job: Job) -> dict: points = sorted(chain['points'], key=lambda p: p['seq']) keep_min = int(req['keep_min_seq']) job.progress = {'dropped': 0, 'to_drop': len([p for p in points if p['seq'] < keep_min])} + # a commit rewrites the base file and a rebase rewrites the next delta's header: the checksums in + # their manifests are of files that no longer exist in that form. Remember what changed and hash + # it again once the chain has its final shape (once per file, not once per dropped point). + base_changed: set[str] = set() + rebased: tuple[str, set[str]] | None = None while points and points[0]['seq'] < keep_min: oldest, nxt = points[0], points[1] if len(points) > 1 else None base_dir = os.path.join(chain_dir, oldest['dir']) @@ -429,19 +434,26 @@ def run_prune(self, job: Job) -> dict: break nxt_dir = os.path.join(chain_dir, nxt['dir']) nxt_m = manifest.read_json(os.path.join(nxt_dir, manifest.POINT_FILE)) or {} + rebased = None # the point rebased last time is the one folded in now for d in nxt_m.get('devices', []): delta_file = os.path.join(nxt_dir, d['file']); base_file = os.path.join(base_dir, d['file']) if self.backend.name == 'file': shutil.copyfile(delta_file, base_file) # raw files: the delta is complete + base_changed.discard(d['file']) # ... and so is its checksum elif os.path.exists(base_file) and not d.get('full'): self.backend.commit(delta_file) # fold the delta into its base + base_changed.add(d['file']) else: shutil.move(delta_file, base_file) # device that got a full inside this delta + base_changed.discard(d['file']) # the same file under another name after = points[2] if len(points) > 2 else None if after and self.backend.name != 'file': after_file = os.path.join(chain_dir, after['dir'], d['file']) if os.path.exists(after_file): self.backend.rebase(after_file, base_file) + if rebased is None: + rebased = (after['dir'], set()) + rebased[1].add(d['file']) # the base directory now holds nxt's state: move nxt's manifest in, drop nxt's dir nxt_m['dir'] = oldest['dir'] nxt_m['note'] = f"committed from {nxt['dir']} on {_now()}" @@ -451,12 +463,32 @@ def run_prune(self, job: Job) -> dict: points.pop(0) job.progress['dropped'] += 1 self._persist(job) + stale = [(points[0]['dir'], base_changed)] if points and base_changed else [] + if rebased and any(p['dir'] == rebased[0] for p in points): + stale.append(rebased) + if stale: + job.progress['phase'] = 'checksum' + self._persist(job) + for point_dir, files in stale: + self._rehash(os.path.join(chain_dir, point_dir), files) chain['points'] = points manifest.save_chain(chain_dir, chain) return {'dirs': {str(p['seq']): p['dir'] for p in points}, 'dropped': job.progress['dropped']} finally: self._release_target(req) + @staticmethod + def _rehash(point_dir: str, files: set[str]) -> None: + """Write the current sha256 of `files` into the point's manifest (after a commit or rebase changed them).""" + path = os.path.join(point_dir, manifest.POINT_FILE) + m = manifest.read_json(path) + if not m: + return + for d in m.get('devices', []): + if d.get('file') in files and os.path.exists(os.path.join(point_dir, d['file'])): + d['sha256'] = manifest.sha256_file(os.path.join(point_dir, d['file'])) + manifest.write_json(path, m) + def run_delete_chain(self, job: Job) -> dict: req = job.request root = self._with_target(req) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index c403d6c..be8f65e 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -320,6 +320,51 @@ def test_prune_commits_forward_and_delete_chain(stack): assert d['result'] == {'removed': True} and not os.path.exists(chain) +@pytest.mark.skipif(not (__import__('shutil').which('qemu-img') and __import__('shutil').which('qemu-io')), reason='qemu-img / qemu-io not installed') +def test_prune_on_qcow2_leaves_checksums_that_verify(tmp_path): + """Retention on the real backend: the commit rewrites the base and the rebase rewrites the next delta's + header, so both manifests need fresh checksums. With the old ones every later verification reported + 'checksum differs' and a restore with verification refused the chain.""" + import subprocess + be = P.images.NbdBackend(P.images.NbdPool(0, str(tmp_path))) + root = tmp_path / 'target'; chain_dir = root / 'F' / 'v.chain' + fname = 'disk.qcow2' + + def qemu_io(path, *cmds, readonly=False): + args = ['qemu-io'] + (['-r'] if readonly else []) + ['-f', 'qcow2'] + [x for c in cmds for x in ('-c', c)] + r = subprocess.run(args + [str(path)], capture_output=True, text=True, timeout=120) + assert r.returncode == 0, r.stdout + r.stderr + + points, prev = [], None + for seq, (name, write) in enumerate((('base', 'write -P 0xaa 0 4M'), ('delta-0001', 'write -P 0xbb 1M 1M'), + ('delta-0002', 'write -P 0xcc 2M 1M'), ('delta-0003', 'write -P 0xdd 3M 1M'))): + d = chain_dir / name; d.mkdir(parents=True) + be.create(str(d / fname), 4 * MiB, backing=str(prev) if prev else None) + qemu_io(d / fname, write) + prev = d / fname + points.append({'kind': 'delta' if seq else 'full', 'seq': seq, 'dir': name, 'previous_seq': seq - 1 if seq else None, 'created_at': 't'}) + for pt in points: # checksums as the backup job leaves them: of the finished files + d = chain_dir / pt['dir'] + P.manifest.write_json(str(d / P.manifest.POINT_FILE), dict(pt, devices=[ + {'uuid': 'u', 'type': 'VIRTIO_DISK', 'file': fname, 'size': 4 * MiB, 'full': False, 'sha256': P.manifest.sha256_file(str(d / fname))}])) + P.manifest.save_chain(str(chain_dir), {'vm': {'uuid': 'vm'}, 'points': points}) + for pt in points: + assert P.manifest.verify_point(str(chain_dir / pt['dir']))['ok'] + + engine = types.SimpleNamespace(backend=be, _with_target=lambda req: str(root), _release_target=lambda req: None, + _persist=lambda job: None, _rehash=getattr(P.jobs.Engine, '_rehash', None)) + job = P.jobs.Job('prune', {'target': {}, 'chain_dir': 'F/v.chain', 'keep_min_seq': 2}) + out = P.jobs.Engine.run_prune(engine, job) + assert out == {'dirs': {'2': 'base', '3': 'delta-0003'}, 'dropped': 2} + assert sorted(os.listdir(chain_dir)) == ['base', 'chain.json', 'delta-0003'] + for name in ('base', 'delta-0003'): + v = P.manifest.verify_point(str(chain_dir / name)) + assert v['ok'], f'{name}: {v["mismatches"]}' + # and the content is still each point's own + qemu_io(chain_dir / 'base' / fname, 'read -P 0xaa 0 1M', 'read -P 0xbb 1M 1M', 'read -P 0xcc 2M 1M', 'read -P 0xaa 3M 1M', readonly=True) + qemu_io(chain_dir / 'delta-0003' / fname, 'read -P 0xbb 1M 1M', 'read -P 0xcc 2M 1M', 'read -P 0xdd 3M 1M', readonly=True) + + def test_synthesize_builds_a_new_chain_from_a_point_without_touching_the_old_one(stack): """A synthetic full: point 1 (a delta) becomes the base of a new chain with the same files, devices and definition and fresh checksums; the source chain is left as it was.""" @@ -1254,7 +1299,7 @@ def test_support_bundle_route_needs_the_token(tmp_path): r = c.get('/support/bundle', headers={'Authorization': 'Bearer t0k'}) assert r.status_code == 200 and r.mimetype == 'application/zip' and 'attachment; filename="hcm-proxy-' in r.headers['Content-Disposition'] assert r.data[:2] == b'PK' - assert P.identity.VERSION == '0.6.2' + assert P.identity.VERSION == '0.6.3' def test_the_proxy_keeps_a_rotating_log_file(tmp_path): From f73ebd2bc24fb439cd973acc9b5d04184d6f6a76 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:16:37 +0100 Subject: [PATCH 004/114] fix(proxy): links in a backed-up filesystem never lead into the proxy (proxy 0.6.4) File-level recovery opened what a symbolic link pointed at with the kernel's resolver, and the proxy's root is the root: a link in the guest to /proc/self/environ, to the proxy's TLS key or to its mount directory (every tenant's images) was browsable and downloadable by anyone who may browse that VM's backups. Ordinary guests showed the same fault harmlessly: /var/run and /var/lock of a restore point listed the proxy's own /run. Links are now resolved inside the filesystem they are on, as the guest would: a relative target from the link's directory, an absolute target from that filesystem's root, '..' never above it. Links that stay inside the guest therefore work (they were 404 before); links are left out of zip downloads. --- proxy/identity.py | 2 +- proxy/mounts.py | 39 ++++++++++++++++++++++++++++++++++----- tests/test_proxy.py | 34 +++++++++++++++++++++++++++++++++- 3 files changed, 68 insertions(+), 7 deletions(-) diff --git a/proxy/identity.py b/proxy/identity.py index 8c78b6b..f3dca19 100644 --- a/proxy/identity.py +++ b/proxy/identity.py @@ -9,7 +9,7 @@ import socket import subprocess -VERSION = '0.6.3' +VERSION = '0.6.4' _SKIP_PREFIXES = ('lo', 'docker', 'veth', 'br-', 'virbr', 'cni', 'flannel', 'tun', 'tap', 'wg') diff --git a/proxy/mounts.py b/proxy/mounts.py index a45d56a..e68a2dd 100644 --- a/proxy/mounts.py +++ b/proxy/mounts.py @@ -201,6 +201,37 @@ def no_filesystem_error(skipped: list[dict], limit: int = 900) -> str: return msg +def _resolve_in_root(root: str, parts: list[str], max_links: int = 40) -> str: + """root/parts with every symbolic link resolved the way the guest would resolve it: a relative target + from the link's own directory, an absolute target from the filesystem's own root, and '..' never above + that root. The files are a guest's: a link to /etc/shadow, /proc/self/environ or the proxy's mount + directory must lead into the backup, never into the proxy (which is what following it with the + kernel's resolver does, since the proxy's root is the root).""" + cur: list[str] = [] + todo = [p for p in parts] + links = 0 + while todo: + p = todo.pop(0) + if p in ('', '.'): + continue + if p == '..': + if cur: + cur.pop() + continue + full = os.path.join(root, *cur, p) + if os.path.islink(full): + links += 1 + if links > max_links: + raise FileNotFoundError('too many levels of symbolic links') + target = os.readlink(full) + if target.startswith('/'): + cur = [] + todo = [x for x in target.split('/') if x] + todo + continue + cur.append(p) + return os.path.join(root, *cur) if cur else root + + class MountManager: def __init__(self, cfg, backend, mounter, run=subprocess.run, idle_seconds: int = 1800): self.cfg, self.backend, self.mounter, self.run = cfg, backend, mounter, run @@ -450,10 +481,7 @@ def _resolve(self, m: Mount, path: str) -> tuple[dict | None, str]: fs = next((f for f in m.filesystems if f['name'] == parts[0]), None) if not fs: raise FileNotFoundError(path) - abs_path = os.path.normpath(os.path.join(fs['mountpoint'], *parts[1:])) - if not abs_path.startswith(fs['mountpoint']): - raise FileNotFoundError(path) - return fs, abs_path + return fs, _resolve_in_root(fs['mountpoint'], parts[1:]) def ls(self, mid: str, path: str) -> dict: m = self.get(mid) @@ -494,7 +522,8 @@ def iter_zip(self, mid: str, paths: list[str], chunk: int = 1 << 20): for dirpath, _, files in os.walk(abs_path): for f in files: full = os.path.join(dirpath, f) - if os.path.isfile(full): + # links are left out of a zip: os.path.isfile would follow one out of the backup + if not os.path.islink(full) and os.path.isfile(full): zf.write(full, os.path.join(arc_root, os.path.relpath(full, abs_path))) yield from buf.drain() elif os.path.isfile(abs_path): diff --git a/tests/test_proxy.py b/tests/test_proxy.py index be8f65e..0ec51b9 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -570,6 +570,38 @@ def test_mount_browse_zip_and_unmount(flr): assert not os.path.exists(m.root) and m.id not in flr.mm.mounts +def test_links_in_the_guest_never_lead_out_of_the_backup(flr, tmp_path): + """Symbolic links are the guest's: followed with the kernel's resolver they lead into the proxy (its + token, its TLS key, every tenant's images under the mount directory). They are resolved inside the + filesystem they are on, as the guest itself would.""" + outside = tmp_path / 'proxy-secret'; outside.mkdir(); (outside / 'token').write_text('s3cret') + m = flr.mm.mount({'uri': 'smb://nas/share/hcm'}, 'F/v_vm-1.chain', 0) + root = m.filesystems[1]['mountpoint'] + os.makedirs(os.path.join(root, 'usr', 'share')); open(os.path.join(root, 'usr', 'share', 'zone'), 'w').write('UTC') + os.symlink(str(outside / 'token'), os.path.join(root, 'etc', 'abs-file')) # absolute, to a proxy file + os.symlink(str(outside), os.path.join(root, 'etc', 'abs-dir')) # absolute, to a proxy directory + os.symlink('../../../../../../..' + str(outside / 'token'), os.path.join(root, 'etc', 'rel-up')) + os.symlink('/usr/share/zone', os.path.join(root, 'etc', 'localtime')) # absolute, exists in the guest + os.symlink('../usr/share', os.path.join(root, 'etc', 'rel-dir')) # relative, inside the guest + os.symlink('loop-b', os.path.join(root, 'etc', 'loop-a')); os.symlink('loop-a', os.path.join(root, 'etc', 'loop-b')) + + for p in ('/disk1-p2/etc/abs-file', '/disk1-p2/etc/rel-up', '/disk1-p2/etc/abs-dir/token', '/disk1-p2/etc/loop-a'): + with pytest.raises(FileNotFoundError): + flr.mm.open_file(m.id, p) + with pytest.raises(FileNotFoundError): + flr.mm.ls(m.id, '/disk1-p2/etc/abs-dir') + # a link that stays inside the guest works, absolute or relative + fh, size, name = flr.mm.open_file(m.id, '/disk1-p2/etc/localtime'); assert fh.read() == b'UTC' and name == 'zone'; fh.close() + assert [e['name'] for e in flr.mm.ls(m.id, '/disk1-p2/etc/rel-dir')['entries']] == ['zone'] + kinds = {e['name']: e['kind'] for e in flr.mm.ls(m.id, '/disk1-p2/etc')['entries']} + assert kinds['abs-file'] == 'link' and kinds['hostname'] == 'file', 'a link is listed as a link, not as its target' + import zipfile, io + names = zipfile.ZipFile(io.BytesIO(b''.join(flr.mm.iter_zip(m.id, ['/disk1-p2/etc'])))).namelist() + assert sorted(names) == ['disk1-p2/etc/hostname', 'disk1-p2/etc/hosts'], 'a zip holds files, never what a link points at' + assert not any(x.endswith(str(outside / 'token')) for x in flr.mm.iso_command(m.id, ['/disk1-p2/etc/abs-file', '/disk1-p2/etc/hosts'])) + flr.mm.unmount(m.id) + + def test_nothing_mountable_names_the_reason_per_partition(flr): """The proxy's log is out of reach for most admins: the error itself says why each partition was left out.""" @@ -1299,7 +1331,7 @@ def test_support_bundle_route_needs_the_token(tmp_path): r = c.get('/support/bundle', headers={'Authorization': 'Bearer t0k'}) assert r.status_code == 200 and r.mimetype == 'application/zip' and 'attachment; filename="hcm-proxy-' in r.headers['Content-Disposition'] assert r.data[:2] == b'PK' - assert P.identity.VERSION == '0.6.3' + assert P.identity.VERSION == '0.6.4' def test_the_proxy_keeps_a_rotating_log_file(tmp_path): From 953daccdb78db911d5122c25ee056813fe75ef6b Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:18:03 +0100 Subject: [PATCH 005/114] fix(migrations): a fresh install can run its migrations again On an install whose database was created by initdb the dashboard's runner starts with nothing recorded and applies every file again. 021 then recreated the unique index on folder names that 044 drops, and failed on the two nodes named 'Default' that 044 seeds. The runner stops at the first failure and retries it forever: no later migration was ever applied, and every in-app update aborted at its migration step. Installs upgraded from before 1.3.0 were not affected (021 was recorded before 044 existed), which is why it went unseen. The index is gone from 021 (044 dropped it anyway). An install that is already stuck passes on the next retry once it has this file. 020 had the same pattern with the install-wide cluster-name index that 051 replaces; on a stuck install that brought install-wide cluster names back. A test refuses a migration that creates an index a later one drops. --- postgres/init/020_cluster_registry.sql | 5 +++-- postgres/init/021_folders_rbac.sql | 5 ++++- tests/test_migrations.py | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/postgres/init/020_cluster_registry.sql b/postgres/init/020_cluster_registry.sql index a3cd646..7c88c77 100644 --- a/postgres/init/020_cluster_registry.sql +++ b/postgres/init/020_cluster_registry.sql @@ -37,8 +37,9 @@ INSERT INTO config.clusters (cluster_id, cluster_name, is_template, enabled) VALUES ('00000000-0000-0000-0000-000000000001', 'Defaults', TRUE, FALSE) ON CONFLICT (cluster_id) DO NOTHING; -CREATE UNIQUE INDEX IF NOT EXISTS ux_clusters_name - ON config.clusters (lower(cluster_name)); +-- (an install-wide unique index on the cluster name lived here until 1.8.0. Migration 051 replaces it with +-- one per folder; like the folder index in 021 it must not be recreated when the runner applies this file +-- again, or an install that stops between here and 051 has install-wide names back.) -- sharing_prefs: TEXT 'default' -> UUID per cluster DO $$ diff --git a/postgres/init/021_folders_rbac.sql b/postgres/init/021_folders_rbac.sql index 21e5046..7fca3c9 100644 --- a/postgres/init/021_folders_rbac.sql +++ b/postgres/init/021_folders_rbac.sql @@ -14,7 +14,10 @@ CREATE TABLE IF NOT EXISTS config.folders ( updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -CREATE UNIQUE INDEX IF NOT EXISTS ux_folders_name ON config.folders (lower(name)); +-- (a unique index on lower(name) lived here until 1.8.0. Migration 044 drops it: folder names are unique +-- per parent since then. It must not come back: the dashboard's runner applies this file again on an +-- install whose database was created by initdb, after 044 has seeded two nodes named 'Default', and +-- failed here for good, which blocked every later migration and every in-app update.) ALTER TABLE config.clusters ADD COLUMN IF NOT EXISTS folder_id UUID REFERENCES config.folders (folder_id) ON DELETE SET NULL; diff --git a/tests/test_migrations.py b/tests/test_migrations.py index fbe436e..227022c 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -159,3 +159,21 @@ def sleep(s): applied = migrations.apply_until_done(Ctx, str(init_dir), sleep=sleep, fast_attempts=4, slow_interval=300) assert applied == ['002_second.sql', '010_tenth.sql'] assert waits[:3] == [2.0, 4.0, 8.0] and waits[3:] == [300] * 7 + + +def test_no_migration_recreates_what_a_later_one_drops(repo): + """The runner applies every file again on an install whose database was created by initdb (nothing is + recorded yet). A file that creates an index or constraint which a later file drops then runs against + the later file's data: 021's unique index on folder names failed on the two 'Default' nodes 044 seeds, + and with it every later migration and every in-app update of a fresh install.""" + import re + files = sorted((repo / 'postgres' / 'init').glob('*.sql')) + strip = lambda sql: re.sub(r'--[^\n]*', '', sql) # noqa: E731 — comments may name what was removed + created: dict[str, str] = {} + for f in files: + sql = strip(f.read_text()) + for name in re.findall(r'DROP\s+INDEX\s+(?:IF\s+EXISTS\s+)?(?:\w+\.)?(\w+)', sql, re.I): + assert name not in created or created[name] == f.name, \ + f'{created[name]} creates index {name}, which {f.name} drops: remove it from {created[name]}' + for name in re.findall(r'CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(\w+)', sql, re.I): + created.setdefault(name, f.name) From e8493a8c01e12e26456234dd933531bf678d5080 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:23:58 +0100 Subject: [PATCH 006/114] fix(collector): a database outage no longer stops collection for good The registry's bookkeeping functions (mark_seen, set_active_host, upsert_nodes, record_tasks, settle_stale_tasks, mark_error) promise never to break a poll loop, but opened their connection outside the try. With Postgres unreachable the collector's worker raised in its poll, then again in its own error handler (mark_error), and the thread ended. The main loop only started a worker for a cluster it had none for, so that cluster got no metrics until the container was restarted: an 80-second outage did this to both real clusters in the lab. The connection is now opened inside the try in all six, and the collector starts a worker again when it finds one that is no longer alive (as the balancer already did). --- Balancer/cluster_registry.py | 36 +++++++++++++++++++++++------------ Collector/cluster_registry.py | 36 +++++++++++++++++++++++------------ Collector/collector.py | 5 +++++ backup/cluster_registry.py | 36 +++++++++++++++++++++++------------ console/cluster_registry.py | 36 +++++++++++++++++++++++------------ dashboard/cluster_registry.py | 36 +++++++++++++++++++++++------------ sentinel/cluster_registry.py | 36 +++++++++++++++++++++++------------ shared/cluster_registry.py | 36 +++++++++++++++++++++++------------ tests/test_shared_modules.py | 25 ++++++++++++++++++++++++ 9 files changed, 198 insertions(+), 84 deletions(-) diff --git a/Balancer/cluster_registry.py b/Balancer/cluster_registry.py index 2157c49..5ea5c9d 100644 --- a/Balancer/cluster_registry.py +++ b/Balancer/cluster_registry.py @@ -413,15 +413,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +537,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +547,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +557,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +597,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +677,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +696,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +716,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +743,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +753,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- diff --git a/Collector/cluster_registry.py b/Collector/cluster_registry.py index 2157c49..5ea5c9d 100644 --- a/Collector/cluster_registry.py +++ b/Collector/cluster_registry.py @@ -413,15 +413,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +537,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +547,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +557,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +597,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +677,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +696,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +716,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +743,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +753,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- diff --git a/Collector/collector.py b/Collector/collector.py index 4ac5776..96d6e3c 100644 --- a/Collector/collector.py +++ b/Collector/collector.py @@ -544,6 +544,11 @@ def main(): ev.set() del workers[cid] for cid, c in clusters.items(): + # a worker that ended on its own (an exception nothing caught) is replaced, as the + # balancer does: without this its cluster stays without metrics until a restart + if cid in workers and not workers[cid][0].is_alive(): + print(f"[{_ts()}] Collector for {c.name} stopped unexpectedly; starting it again.") + del workers[cid] if cid not in workers: ev = threading.Event() w = ClusterWorker(c, write_api, ev) diff --git a/backup/cluster_registry.py b/backup/cluster_registry.py index 2157c49..5ea5c9d 100644 --- a/backup/cluster_registry.py +++ b/backup/cluster_registry.py @@ -413,15 +413,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +537,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +547,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +557,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +597,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +677,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +696,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +716,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +743,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +753,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- diff --git a/console/cluster_registry.py b/console/cluster_registry.py index 2157c49..5ea5c9d 100644 --- a/console/cluster_registry.py +++ b/console/cluster_registry.py @@ -413,15 +413,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +537,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +547,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +557,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +597,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +677,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +696,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +716,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +743,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +753,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- diff --git a/dashboard/cluster_registry.py b/dashboard/cluster_registry.py index 2157c49..5ea5c9d 100644 --- a/dashboard/cluster_registry.py +++ b/dashboard/cluster_registry.py @@ -413,15 +413,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +537,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +547,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +557,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +597,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +677,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +696,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +716,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +743,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +753,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- diff --git a/sentinel/cluster_registry.py b/sentinel/cluster_registry.py index 2157c49..5ea5c9d 100644 --- a/sentinel/cluster_registry.py +++ b/sentinel/cluster_registry.py @@ -413,15 +413,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +537,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +547,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +557,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +597,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +677,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +696,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +716,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +743,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +753,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- diff --git a/shared/cluster_registry.py b/shared/cluster_registry.py index 2157c49..5ea5c9d 100644 --- a/shared/cluster_registry.py +++ b/shared/cluster_registry.py @@ -413,15 +413,17 @@ def mark_seen(cluster_id: str, hc_cluster_uuid: Optional[str] = None, *, api_v2_ if timezone and zone_is_valid(timezone): # what the cluster reports, unless an admin typed a zone (timezone_override) sets.append('timezone = CASE WHEN timezone_override THEN timezone ELSE %s END'); params.append(timezone) - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute(f'UPDATE config.clusters SET {", ".join(sets)} WHERE cluster_id = %s', params + [cluster_id]) conn.commit() except Exception as exc: # never let bookkeeping break a poll loop log.warning('cluster_registry.mark_seen(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() if hc_cluster_uuid: try: me = get(cluster_id) @@ -535,8 +537,9 @@ def candidate_hosts(cluster_id: str, current: Optional[str] = None) -> list[str] def set_active_host(cluster_id: str, host: str) -> None: """Record the node the cluster is currently reached on (written on every switch).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET active_host = %s WHERE cluster_id = %s', (normalize_host(host), cluster_id)) @@ -544,7 +547,8 @@ def set_active_host(cluster_id: str, host: str) -> None: except Exception as exc: log.warning('cluster_registry.set_active_host(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str] = None) -> None: @@ -553,8 +557,9 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str or per changed LAN IP, never per poll. Never raises.""" rows = [dict(n) if 'node_uuid' in n else node_from_api(n) for n in api_nodes or []] # raw API or slim rows = [r for r in rows if r.get('node_uuid')] - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: if seed_host is None: cur.execute('SELECT hc_host FROM config.clusters WHERE cluster_id = %s', (cluster_id,)) @@ -592,7 +597,8 @@ def upsert_nodes(cluster_id: str, api_nodes: list[dict], seed_host: Optional[str except Exception as exc: # bookkeeping must never break a poll loop log.warning('cluster_registry.upsert_nodes(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() _NODE_COLUMNS = '''cluster_id::text AS cluster_id, node_uuid, peer_id, lan_ip, backplane_ip, address, network_status, @@ -671,8 +677,9 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: """Upsert normalised task rows (see hypercore_tasks.normalise) for one cluster.""" if not rows: return - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: psycopg2.extras.execute_batch(cur, ''' INSERT INTO config.cluster_tasks (cluster_id, task_tag, kind, description, vm_name, object_uuid, state, progress, @@ -689,14 +696,16 @@ def record_tasks(cluster_id: str, rows: list[dict]) -> None: except Exception as exc: # the feed is informational; never break a poll loop log.warning('cluster_registry.record_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_seconds: int = 180) -> None: """A task that was active but is no longer listed as active and has not been seen for a while is marked COMPLETE (the v2 feed drops finished tasks from the active list).""" - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('''UPDATE config.cluster_tasks SET state = 'COMPLETE', progress = 100, completed_at = COALESCE(completed_at, NOW()) WHERE cluster_id = %s AND state IN ('QUEUED', 'RUNNING') AND NOT (task_tag = ANY(%s)) @@ -707,7 +716,8 @@ def settle_stale_tasks(cluster_id: str, active_tags: set[str], older_than_second except Exception as exc: log.warning('cluster_registry.settle_stale_tasks(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: @@ -733,8 +743,9 @@ def list_tasks(cluster_id: str, limit: int = 40) -> list[dict[str, Any]]: def mark_error(cluster_id: str, message: str) -> None: - conn = _connect() + conn = None try: + conn = _connect() # inside the try: an unreachable database is one more thing bookkeeping survives with conn.cursor() as cur: cur.execute('UPDATE config.clusters SET last_error = %s WHERE cluster_id = %s', ((message or '')[:500], cluster_id)) @@ -742,7 +753,8 @@ def mark_error(cluster_id: str, message: str) -> None: except Exception as exc: log.warning('cluster_registry.mark_error(%s): %s', cluster_id, exc) finally: - conn.close() + if conn is not None: + conn.close() # --------------------------------------------------------------------------- diff --git a/tests/test_shared_modules.py b/tests/test_shared_modules.py index 251242a..8895de6 100644 --- a/tests/test_shared_modules.py +++ b/tests/test_shared_modules.py @@ -193,3 +193,28 @@ def test_timezone_helpers(): assert c.effective_timezone == 'Europe/Amsterdam' c.timezone = 'US/Eastern' assert c.effective_timezone == 'US/Eastern' + + +def test_bookkeeping_survives_an_unreachable_database(monkeypatch): + """These six are called from poll loops and from their except handlers, and promise never to raise. + They opened their connection outside the try: with Postgres unreachable for a minute the collector's + worker died in its own error handler (2026-11-22, both real clusters) and nothing started it again.""" + import cluster_registry as cr + if not hasattr(cr, '_connect'): + pytest.skip('the registry is stubbed in this run') + + def down(*a, **k): + raise RuntimeError('could not translate host name "postgres" to address') + monkeypatch.setattr(cr, '_connect', down) + cid = '11111111-1111-4111-8111-111111111111' + cr.mark_seen(cid, active_host='10.0.0.1') + cr.set_active_host(cid, '10.0.0.1') + cr.upsert_nodes(cid, [{'uuid': 'n1', 'lanIP': '10.0.0.1', 'peerID': 1}]) + cr.record_tasks(cid, [{'task_tag': '1', 'state': 'RUNNING'}]) + cr.settle_stale_tasks(cid, set()) + cr.mark_error(cid, 'login failed') + + +def test_the_collector_replaces_a_worker_that_died(repo): + src = (repo / 'Collector' / 'collector.py').read_text() + assert 'not workers[cid][0].is_alive()' in src, 'a dead worker must be started again' From 869d9e79e9c23539da75673bdadaea188ea3bc50 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:25:57 +0100 Subject: [PATCH 007/114] fix(ui): unapplied settings no longer follow you to another cluster Edits staged in a settings form were only cleared after a successful Apply of their group. Flip 'Dry run' off on cluster A without applying, switch to cluster B: B's form showed its own values and no unsaved badge, but the next Apply of that group on B also sent DRY_RUN=false, so B went live with a value its form never showed. The same held between a cluster and the defaults, and for the Foresight settings. A settings form that is rendered again now drops the edits staged on the previous one. --- dashboard/static/index.html | 11 +++++++++++ tests/test_dashboard_markup.py | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/dashboard/static/index.html b/dashboard/static/index.html index d1fd266..0fa62f8 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -3642,6 +3642,14 @@ if (btn) btn.classList.add('dirty'); } +// A settings form that is rendered again shows the server's values for whatever is selected now. Edits +// staged on the previous form (another cluster, or the defaults) are dropped with it: left in place they +// were sent with the next Apply of that group, to a cluster whose form never showed them (an unapplied +// "Dry run off" on cluster A went live on cluster B). +function _dropStaged(groups) { + groups.forEach(g => { delete _staged[g.id]; }); +} + function _clearDirty(groupId) { const badge = document.getElementById(`dirty-${groupId}`); const btn = document.getElementById(`apply-${groupId}`); @@ -4590,6 +4598,7 @@ const vals = {}; data.forEach(item => { vals[item.key] = item.value; }); const groups = CTRL_GROUPS.filter(g => g.tab === 'general'); + _dropStaged(groups); _accSet(me); const isAdmin = can('cluster.settings', currentCluster) || (_settingsTarget === 'defaults' && can('install.manage')); @@ -5499,6 +5508,7 @@ const el = document.getElementById('sentSettingsContent'); try { const data = await apiFetch('/api/sentinel/tunables'); + Object.keys(_sStagedSent).forEach(k => { delete _sStagedSent[k]; }); // as _dropStaged: the form is rendered anew if (!data) { el.innerHTML = `
${t('empty.sentinel_settings_unavail')}
`; return; } // index by key @@ -5544,6 +5554,7 @@ const vals = {}; data.forEach(item => { vals[item.key] = item.value; }); const groups = CTRL_GROUPS.filter(g => g.tab === 'balancer'); + _dropStaged(groups); const isAdmin = can('cluster.settings', currentCluster) || (_settingsTarget === 'defaults' && can('install.manage')); document.getElementById('balancerSettingsContent').innerHTML = _settingsTargetBar(isAdmin) + _renderGroups(groups, vals, isAdmin); } diff --git a/tests/test_dashboard_markup.py b/tests/test_dashboard_markup.py index 7ab09ee..ff074a2 100644 --- a/tests/test_dashboard_markup.py +++ b/tests/test_dashboard_markup.py @@ -32,3 +32,14 @@ def test_tab_containers_are_not_nested(): assert len(p.tabs) >= 6, p.tabs nested = {tab: above for tab, above in p.tabs.items() if above} assert not nested, f'tab containers nested inside another tab: {nested}' + + +def test_staged_settings_do_not_outlive_their_form(repo): + """An unapplied 'Dry run off' on cluster A was posted to cluster B by the next Apply of that group there: + the staged edits were only cleared after a successful Apply. Every settings loader drops them.""" + src = (repo / 'dashboard' / 'static' / 'index.html').read_text() + for loader, marker in (('async function loadSettings()', '_dropStaged(groups);'), + ('async function loadBalancerSettings()', '_dropStaged(groups);'), + ('async function loadSentinelSettings()', 'delete _sStagedSent[k]')): + body = src[src.index(loader):][:1600] + assert marker in body, f'{loader} must drop the edits staged on the previous form' From 13f1f5a1b527c879777a31e6aaf54638db32be03 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:25:57 +0100 Subject: [PATCH 008/114] fix(foresight): report, What-If, settings and 'Run analysis now' use the selected cluster Six Foresight calls used a bare fetch without ?cluster=: the report PDF, the VM list and the simulation of What-If, saving the Foresight settings, saving the report branding and 'Run analysis now'. The server then takes the first cluster the user may see. With cluster B selected the settings form showed B's values and Apply wrote them to A; the report and the simulation were A's. They go through _withCluster() like every other data call. --- dashboard/static/index.html | 12 ++++++------ tests/test_dashboard_markup.py | 10 ++++++++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 0fa62f8..072475b 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -4319,7 +4319,7 @@ const msg = document.getElementById('brandingSaveMsg'); try { - const resp = await fetch('/api/sentinel/branding', { + const resp = await fetch(_withCluster('/api/sentinel/branding'), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ @@ -4358,7 +4358,7 @@ if (msg) msg.textContent = t('reports.building'); try { - const resp = await fetch('/api/sentinel/report.pdf'); + const resp = await fetch(_withCluster('/api/sentinel/report.pdf')); if (!resp.ok) { let detail = `HTTP ${resp.status}`; try { const j = await resp.json(); detail = j.error || detail; } catch (_) {} @@ -4399,7 +4399,7 @@ async function _loadWhatifVmList() { try { - const resp = await fetch('/api/sentinel/vms'); + const resp = await fetch(_withCluster('/api/sentinel/vms')); if (!resp.ok) return; _whatifVmData = await resp.json(); const dl = document.getElementById('whatifVmList'); @@ -4477,7 +4477,7 @@ loadingEl.style.display = 'block'; try { - const resp = await fetch('/api/sentinel/whatif', { + const resp = await fetch(_withCluster('/api/sentinel/whatif'), { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), @@ -5471,7 +5471,7 @@ const updates = _sStagedSent[gid]; if (!updates || !Object.keys(updates).length) return; try { - const r = await fetch(`${API_BASE}/api/sentinel/tunables`, { + const r = await fetch(_withCluster('/api/sentinel/tunables'), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(updates), @@ -5491,7 +5491,7 @@ const originalLabel = btnEl ? btnEl.innerHTML : ''; if (btnEl) { btnEl.disabled = true; btnEl.innerHTML = `${t('sentinel.analysis_triggering')}`; } try { - const r = await fetch(`${API_BASE}/api/sentinel/trend/run`, { method: 'POST' }); + const r = await fetch(_withCluster('/api/sentinel/trend/run'), { method: 'POST' }); if (!r.ok) { const err = await r.json().catch(() => ({})); throw new Error(err.error || `HTTP ${r.status}`); diff --git a/tests/test_dashboard_markup.py b/tests/test_dashboard_markup.py index ff074a2..c51574c 100644 --- a/tests/test_dashboard_markup.py +++ b/tests/test_dashboard_markup.py @@ -34,6 +34,16 @@ def test_tab_containers_are_not_nested(): assert not nested, f'tab containers nested inside another tab: {nested}' +def test_foresight_calls_name_the_selected_cluster(repo): + """Report, VM list, What-If, saving the Foresight settings, the branding and 'Run analysis now' used a bare + fetch: without ?cluster= the server takes the first cluster the user may see, so with cluster B selected + the settings were saved to A and the report was A's.""" + import re + src = (repo / 'dashboard' / 'static' / 'index.html').read_text() + bare = re.findall(r"fetch\(\s*(?:`\$\{API_BASE\}|'|`)/api/sentinel/[^)\n]*", src) + assert not bare, f'route these through _withCluster(): {bare}' + + def test_staged_settings_do_not_outlive_their_form(repo): """An unapplied 'Dry run off' on cluster A was posted to cluster B by the next Apply of that group there: the staged edits were only cleared after a successful Apply. Every settings loader drops them.""" From e67d6fadaea331ff66ded35b2c650e9c95523cec Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:29:00 +0100 Subject: [PATCH 009/114] fix(access): handing out access needs user management on that scope The assignment, invitation and group-member routes asked for users.manage 'anywhere' and then only checked that the giver holds the role's permissions on the scope. Someone who is Admin at customer A and a Viewer at customer B holds Viewer's permissions at B, so they could assign or invite people as Viewer at B, a tenant whose people are not theirs to manage. grant_check now also requires the managing permission on the scope itself: users.manage for assignments, invitations and copied VM access, groups.manage when the access comes with a group. Invitations are re-checked with the same rule when they are accepted. --- dashboard/access_api.py | 11 +++++++++-- dashboard/access_db.py | 10 +++++----- tests/test_integration_rbac.py | 26 ++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/dashboard/access_api.py b/dashboard/access_api.py index 2676495..8e466d3 100644 --- a/dashboard/access_api.py +++ b/dashboard/access_api.py @@ -124,10 +124,17 @@ def parse_scope(b: dict, tree: rbac.Tree) -> dict: out['vm_name'] = name or str(s.get('vm_name') or '')[:200] or None return out - def grant_check(acc: rbac.Access, r: dict, scope: dict) -> None: + def grant_check(acc: rbac.Access, r: dict, scope: dict, perm: str = 'users.manage') -> None: + """May `acc` hand role `r` to someone on `scope`? Two conditions: they manage people there (`perm` on + the scope: users.manage, or groups.manage when the access comes with a group), and they hold every + permission of the role there themselves. The second alone is not enough: an Admin of customer A who + is a Viewer at customer B holds Viewer's permissions at B, but B's people are not theirs to manage.""" tree = acc.tree if not role_usable_at(r, scope, tree): raise AccessError('that role is not defined for this part of the tree', 403) + if not access_db.assignment_in_reach(acc, {'scope_kind': scope['kind'], 'node_id': scope.get('node_id'), + 'cluster_id': scope.get('cluster_id')}, perm): + raise AccessError('you do not manage access on that scope', 403) tags = [] if scope['kind'] == 'vm': tags = next((v.get('tags') or [] for v in vm_index_rows(scope['cluster_id']) if v.get('uuid') == scope['vm_uuid']), []) @@ -528,7 +535,7 @@ def access_group_member(group_id): for a in access_db.assignments(group_id=g['group_id']): scope = {'kind': a['scope_kind'], 'node_id': a['node_id'], 'cluster_id': a['cluster_id'], 'tag': a['tag'], 'vm_uuid': a['vm_uuid']} - grant_check(acc, access_db.role(a['role_id']), scope) + grant_check(acc, access_db.role(a['role_id']), scope, 'groups.manage') access_db.set_group_member(g['group_id'], u['user_id'], bool(b.get('member', True)), actor()) return jsonify({'ok': True}) diff --git a/dashboard/access_db.py b/dashboard/access_db.py index 4483a69..81ac023 100644 --- a/dashboard/access_db.py +++ b/dashboard/access_db.py @@ -940,14 +940,14 @@ def node_label(node_id, tree: rbac.Tree, visible: set | None = None) -> str: return ' / '.join(tree.name.get(n, n) for n in chain) or str(node_id) -def assignment_in_reach(acc: rbac.Access, a: dict) -> bool: - """May this reader manage people on the scope of assignment `a` (users.manage there)?""" +def assignment_in_reach(acc: rbac.Access, a: dict, perm: str = 'users.manage') -> bool: + """May this reader manage people on the scope of assignment `a` (`perm` there, users.manage by default)?""" k = a['scope_kind'] if k == 'node': - return acc.can('users.manage', node_id=a['node_id']) + return acc.can(perm, node_id=a['node_id']) if k in ('cluster', 'tag', 'vm'): - return acc.can('users.manage', a['cluster_id']) - return acc.can('users.manage') # root: the whole installation + return acc.can(perm, a['cluster_id']) + return acc.can(perm) # root: the whole installation def manageable_user_ids(acc: rbac.Access) -> set | None: diff --git a/tests/test_integration_rbac.py b/tests/test_integration_rbac.py index dc54c83..aab0a75 100644 --- a/tests/test_integration_rbac.py +++ b/tests/test_integration_rbac.py @@ -265,6 +265,32 @@ def test_customer_admin_cannot_escalate(admin, clusters): assert st == 404 +def test_handing_out_access_needs_user_management_on_that_scope(admin): + """Holding a role's permissions somewhere is not the right to hand them out there. contoso-admin, made a + Viewer at Fabrikam, could assign and invite people as Viewer at Fabrikam (2026-11-22).""" + o = admin.call('GET', '/api/access/overview')[1] + fabrikam = next(n['id'] for n in o['nodes'] if n['name'] == 'Fabrikam') + viewer = next(r['role_id'] for r in o['roles'] if r['builtin_key'] == 'viewer') + scope = {'kind': 'node', 'node_id': fabrikam} + st, d = admin.call('POST', '/api/access/assignments', {'user_id': _uid(admin, 'contoso-admin'), 'role_id': viewer, 'scope': scope}) + assert st == 201, d + try: + _sessions.pop('contoso-admin', None) + c = as_user('contoso-admin') + st, d = c.call('POST', '/api/access/assignments', {'user_id': _uid(admin, 'contoso-viewer'), 'role_id': viewer, 'scope': scope}) + assert st == 403 and 'manage' in d['error'], (st, d) + st, d = c.call('POST', '/api/access/invitations', {'email': 'someone@invited.example', 'role_id': viewer, 'scope': scope}) + assert st in (403, 404), (st, d) + assert 'Fabrikam-Main' not in visible('contoso-viewer') + finally: + admin.call('DELETE', f"/api/access/assignments/{d.get('assignment_id')}") if isinstance(d, dict) and d.get('assignment_id') else None + uid = _uid(admin, 'contoso-admin') + for a in admin.call('GET', f'/api/access/users/{uid}')[1]['assignments']: + if a.get('node_id') == fabrikam: + admin.call('DELETE', f"/api/access/assignments/{a['assignment_id']}") + _sessions.pop('contoso-admin', None) + + def test_engineer_cannot_manage_users(admin): c = as_user('contoso-eng') st, _ = c.call('POST', '/api/access/assignments', {'user_id': _uid(admin, 'contoso-viewer'), 'role_id': _role(admin, 'viewer'), From 95d1e1ddbf32e11aab8ec0339bb898241a683084 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:32:54 +0100 Subject: [PATCH 010/114] test: the stack integration tests follow HCM_BASE and skip without a stack test_integration_stack.py hardcoded http://localhost:5000, so it could not run from the test container next to the stack (test_integration_rbac.py already reads HCM_BASE), and two of its tests used no fixture and failed, instead of being skipped, when nothing was listening. --- tests/test_integration_stack.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tests/test_integration_stack.py b/tests/test_integration_stack.py index c6c5a3d..b8084ef 100644 --- a/tests/test_integration_stack.py +++ b/tests/test_integration_stack.py @@ -6,6 +6,7 @@ """ import http.cookiejar import json +import os import urllib.error import urllib.parse import urllib.request @@ -16,7 +17,7 @@ import sys sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'dashboard')) -BASE = 'http://localhost:5000' +BASE = os.environ.get('HCM_BASE', 'http://localhost:5000') # as test_integration_rbac: the stack from inside a container pytestmark = pytest.mark.integration @@ -64,6 +65,16 @@ def get(path, method='GET', body=None): return get +@pytest.fixture(autouse=True) +def _stack_up(): + """Every test here needs the stack: two of them used no fixture and failed, instead of being skipped, + when it was not reachable.""" + try: + urllib.request.urlopen(BASE + '/login', timeout=3) + except Exception: # noqa: BLE001 + pytest.skip('dashboard not reachable on ' + BASE) + + def test_root_requires_login(): req = urllib.request.Request(BASE + '/') opener = urllib.request.build_opener(urllib.request.HTTPRedirectHandler) From 6b8f8f8a6530ada24a6acc7b2296ef362972aa5d Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:32:54 +0100 Subject: [PATCH 011/114] fix(infraviewer): a cluster where every VM is off still lists its VMs The stopped VMs are added to the list from the inventory, in a helper that returned early when no VM had performance samples. On a cluster with nothing running (a passive DR cluster, or a new one) the list was therefore empty and no VM could be opened or started from it. --- dashboard/app.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/dashboard/app.py b/dashboard/app.py index a035623..5acc1fc 100644 --- a/dashboard/app.py +++ b/dashboard/app.py @@ -597,9 +597,8 @@ def _vm_sizes(client, vms: dict) -> None: """Adds mem_bytes, num_vcpu, os, state and disk_bytes to each VM of the list, and the VMs that are not running (from vm_inventory, which lists every VM). Memory and vCPUs come from vm_inventory; a VM's disks from its per-disk I/O samples (vsd_metrics carry vm_uuid and vsd_uuid), - their sizes from block_device_metrics by vsd_uuid. CD-ROMs (mounted ISOs) do not count.""" - if not vms: - return + their sizes from block_device_metrics by vsd_uuid. CD-ROMs (mounted ISOs) do not count. + Also when no VM is running (a passive DR cluster): the stopped ones are still listed.""" q = client.query_api() # the inventory as of the last polls only: a deleted VM drops out as fast as a stopped one shows up fresh = max(60, int(_stale_seconds())) From cd40b1f5b32a3768365d560b1d1c4d48d6463735 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:32:54 +0100 Subject: [PATCH 012/114] fix(clusters): colour, name and address are checked on every write A cluster's or tree node's colour was stored as sent and written into style attributes on every viewer's page: 'red;background:url(//x)' made each browser fetch //x, and the two places that print a cluster's colour did not escape it at all, so markup in it was script, for anyone who may edit a cluster. A colour is now '#rrggbb' or nothing, checked where it is stored (cluster create and update, folder and tree-node create and update), and the page ignores a stored value that is not one. Updating a cluster skipped what creating one checks: an empty name, a 300-character name and an empty address (https:///rest/v1) were stored. Create and update now refuse them (400). --- Balancer/cluster_registry.py | 28 +++++++++++++++++++++++++--- Collector/cluster_registry.py | 28 +++++++++++++++++++++++++--- backup/cluster_registry.py | 28 +++++++++++++++++++++++++--- console/cluster_registry.py | 28 +++++++++++++++++++++++++--- dashboard/access_db.py | 13 +++++++++++-- dashboard/app.py | 4 ++++ dashboard/cluster_registry.py | 28 +++++++++++++++++++++++++--- dashboard/static/index.html | 14 +++++++++----- sentinel/cluster_registry.py | 28 +++++++++++++++++++++++++--- shared/cluster_registry.py | 28 +++++++++++++++++++++++++--- tests/test_shared_modules.py | 34 ++++++++++++++++++++++++++++++++++ 11 files changed, 233 insertions(+), 28 deletions(-) diff --git a/Balancer/cluster_registry.py b/Balancer/cluster_registry.py index 5ea5c9d..de4d9ec 100644 --- a/Balancer/cluster_registry.py +++ b/Balancer/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -238,7 +253,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -287,8 +305,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,7 +319,7 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: @@ -848,7 +870,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -863,7 +885,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/Collector/cluster_registry.py b/Collector/cluster_registry.py index 5ea5c9d..de4d9ec 100644 --- a/Collector/cluster_registry.py +++ b/Collector/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -238,7 +253,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -287,8 +305,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,7 +319,7 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: @@ -848,7 +870,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -863,7 +885,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/backup/cluster_registry.py b/backup/cluster_registry.py index 5ea5c9d..de4d9ec 100644 --- a/backup/cluster_registry.py +++ b/backup/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -238,7 +253,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -287,8 +305,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,7 +319,7 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: @@ -848,7 +870,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -863,7 +885,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/console/cluster_registry.py b/console/cluster_registry.py index 5ea5c9d..de4d9ec 100644 --- a/console/cluster_registry.py +++ b/console/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -238,7 +253,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -287,8 +305,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,7 +319,7 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: @@ -848,7 +870,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -863,7 +885,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/dashboard/access_db.py b/dashboard/access_db.py index 81ac023..98d70da 100644 --- a/dashboard/access_db.py +++ b/dashboard/access_db.py @@ -15,6 +15,7 @@ import threading import time +import cluster_registry import rbac log = logging.getLogger(__name__) @@ -316,6 +317,14 @@ def nodes() -> list[dict]: conn.close() +def _colour(value): + """cluster_registry.clean_colour, as an AccessError (400).""" + try: + return cluster_registry.clean_colour(value) + except ValueError as e: + raise AccessError(str(e), 400) from None + + def create_node(name: str, level: str, parent_id: str | None, colour: str | None, actor: str) -> str: name = (name or '').strip() if not name or len(name) > 80: @@ -331,7 +340,7 @@ def create_node(name: str, level: str, parent_id: str | None, colour: str | None with conn.cursor() as cur: try: cur.execute('''INSERT INTO config.folders (name, level, parent_id, colour) VALUES (%s, %s, %s, %s) - RETURNING folder_id::text AS id''', (name, level, parent_id, colour or None)) + RETURNING folder_id::text AS id''', (name, level, parent_id, _colour(colour))) except Exception as exc: # noqa: BLE001 if 'ux_folders_parent_name' in str(exc) or 'duplicate key' in str(exc): raise AccessError(f'there already is a {level} called {name!r} here', 409) from exc @@ -365,7 +374,7 @@ def rename_node(node_id: str, name: str | None, colour, actor: str) -> None: raise audit(cur, actor, f"{row['level']}.rename", f"{row['name']} → {name}", node_id=node_id) if colour is not ...: - cur.execute('UPDATE config.folders SET colour = %s, updated_at = NOW() WHERE folder_id = %s', (colour or None, node_id)) + cur.execute('UPDATE config.folders SET colour = %s, updated_at = NOW() WHERE folder_id = %s', (_colour(colour), node_id)) conn.commit() finally: conn.close() diff --git a/dashboard/app.py b/dashboard/app.py index 5acc1fc..eaeea71 100644 --- a/dashboard/app.py +++ b/dashboard/app.py @@ -1401,6 +1401,8 @@ def api_clusters_create(): verify_tls=f['verify_tls'], colour=f['colour'], hc_cluster_uuid=hc_uuid, api_version=f['api_version'], api_v2_available=probe.get('api_v2') if probe.get('ok') else None, hc_version=probe.get('version') or None, folder_id=target_folder) + except ValueError as e: + return jsonify({'error': str(e)}), 400 except Exception as e: msg = str(e) if 'ux_clusters_folder_name' in msg or 'duplicate key' in msg: @@ -1641,6 +1643,8 @@ def api_folders_update(folder_id): try: cluster_registry.update_folder(folder_id, name=body.get('name'), colour=body.get('colour'), share_id=body['share_id'] if 'share_id' in body else ...) + except ValueError as e: + return jsonify({'error': str(e)}), 400 except Exception as e: if 'ux_folders_name' in str(e) or 'duplicate key' in str(e): return jsonify({'error': 'a folder with that name already exists'}), 409 diff --git a/dashboard/cluster_registry.py b/dashboard/cluster_registry.py index 5ea5c9d..de4d9ec 100644 --- a/dashboard/cluster_registry.py +++ b/dashboard/cluster_registry.py @@ -86,6 +86,21 @@ def to_dict(self) -> dict[str, Any]: # helpers # --------------------------------------------------------------------------- +NAME_MAX = 100 +_COLOUR_RE = re.compile(r'#[0-9a-fA-F]{6}') + + +def clean_colour(value) -> Optional[str]: + """A cluster's or tree node's colour as the picker gives it ('#rrggbb'), None for no colour. Anything + else is refused: the value is written into style attributes of every viewer's page, where + 'red;background:url(//x)' is a request to someone else's server and markup is script.""" + if value is None or (isinstance(value, str) and not value.strip()): + return None + if not isinstance(value, str) or not _COLOUR_RE.fullmatch(value.strip()): + raise ValueError("a colour is written as '#rrggbb'") + return value.strip().lower() + + def is_uuid(value: str) -> bool: return bool(value) and bool(_UUID_RE.match(str(value))) @@ -238,7 +253,10 @@ def create(name: str, host: str, username: str, password: str, host = normalize_host(host) if not name or not host or not username: raise ValueError('name, host and username are required') + if len(name) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') enc = hcm_crypto.encrypt(password or '') + colour = clean_colour(colour) conn = _connect() try: with conn.cursor() as cur: @@ -287,8 +305,12 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if folder_id is not ...: sets.append('folder_id = %s'); params.append(folder_id if folder_id and is_uuid(folder_id) else None) if name is not None: + if not isinstance(name, str) or not name.strip() or len(name.strip()) > NAME_MAX: + raise ValueError(f'a cluster needs a name of at most {NAME_MAX} characters') sets.append('cluster_name = %s'); params.append(name.strip()) if host is not None: + if not isinstance(host, str) or not normalize_host(host): + raise ValueError('a cluster needs an address') sets.append('hc_host = %s'); params.append(normalize_host(host)) if username is not None: sets.append('hc_username = %s'); params.append(username.strip()) @@ -297,7 +319,7 @@ def update(cluster_id: str, *, name: Optional[str] = None, host: Optional[str] = if verify_tls is not None: sets.append('verify_tls = %s'); params.append(bool(verify_tls)) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if enabled is not None: sets.append('enabled = %s'); params.append(bool(enabled)) if api_version is not None: @@ -848,7 +870,7 @@ def create_folder(name: str, colour: Optional[str] = None) -> str: try: with conn.cursor() as cur: cur.execute('INSERT INTO config.folders (name, colour) VALUES (%s, %s) RETURNING folder_id::text AS folder_id', - (name, colour or None)) + (name, clean_colour(colour))) fid = cur.fetchone()['folder_id'] conn.commit() return fid @@ -863,7 +885,7 @@ def update_folder(folder_id: str, name: Optional[str] = None, colour: Optional[s if name is not None: sets.append('name = %s'); params.append(name.strip()) if colour is not None: - sets.append('colour = %s'); params.append(colour or None) + sets.append('colour = %s'); params.append(clean_colour(colour)) if share_id is not ...: sets.append('share_id = %s'); params.append(int(share_id) if share_id not in (None, '', 0) else None) if not sets: diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 072475b..bfaaa6b 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -5583,9 +5583,12 @@ if (s < 5400) return t('clusters.status_seen', {ago: Math.round(s / 60) + 'm'}); return t('clusters.status_seen', {ago: Math.round(s / 3600) + 'h'}); } +// a colour as the picker gives it; anything else stored (from before the server checked) is not used: +// these values go into style attributes +function _safeColour(v) { return /^#[0-9a-fA-F]{6}$/.test(v || '') ? v : ''; } function _clColour(c, i) { // a cluster without a colour of its own takes the next chart colour of the theme - return c.colour || CHART_COLORS[i % CHART_COLORS.length]; + return _safeColour(c.colour) || CHART_COLORS[i % CHART_COLORS.length]; } async function loadClusters() { @@ -5633,7 +5636,8 @@ const group = (key, name, colour, members, adminMenu) => { const collapsed = !(_railQuery || '').trim() && _collapsedFolders.has(key); - const vars = colour ? `--fc:${_clEsc(colour)};--fc-tint:${_tint(colour, 0.16)}` : ''; + colour = _safeColour(colour); + const vars = colour ? `--fc:${colour};--fc-tint:${_tint(colour, 0.16)}` : ''; return `
▾ @@ -5719,7 +5723,7 @@ const clusterScoped = !['settings', 'modules', 'account'].includes(activeTab); if (cur && clusterScoped) { const f = FOLDERS.find(x => x.folder_id === cur.folder_id); - if (f) parts.push(`${_clEsc(f.name)}`); + if (f) parts.push(`${_clEsc(f.name)}`); parts.push(`${_clEsc(cur.name)}`); } const tabEl = document.querySelector(`.nav-tab[data-tab="${activeTab}"], .rail-nav[data-tab="${activeTab}"]`); @@ -5795,7 +5799,7 @@ if (!list.length) return `
${t('folders.no_match')}
`; return list.map(f => `
- ${_clEsc(f.name)}${c && c.folder_id === f.folder_id ? '✓' : ''} + ${_clEsc(f.name)}${c && c.folder_id === f.folder_id ? '✓' : ''}
`).join(''); } function clusterMenuSearch(clusterId, q) { const box = document.getElementById('clusterMenuRows'); if (box) box.innerHTML = _clusterMenuRows(clusterId, q); } @@ -5937,7 +5941,7 @@
-
+
${scopeOptions(u)} - + `; window._pendingList = pending; @@ -724,7 +724,7 @@ async function _acGroupRender(gid, g) { }).join('') : `
${_esc(t('acc.members_none'))}
`} ${invited.map(i => `
${_acIcon('user')}
${_esc(i.email)}
${_esc(t('acc.tb_invited'))} · ${_esc(_acInviteState(i))}
-
`).join('')} +
`).join('')}
${_esc(t('acc.assignments'))} ${_esc(t('acc.group_access_hint'))} @@ -1059,7 +1059,7 @@ async function _acTbPane() { if (box2 && here.length) box2.innerHTML = `
${_esc(t('acc.tb_invited'))} ${here.length}
${here.map(i => `
${_acIcon('user')}
${_esc(i.email)}
${_esc(_acInviteState(i))}
${_esc(i.builtin_key ? t('acc.role_' + i.builtin_key) : (i.role_name || i.group_name || ''))} -
`).join('')}`; +
`).join('')}`; } /** The visible chain from the reader's top down to a node (ids), or null when the node is not theirs to see. */ @@ -1151,8 +1151,8 @@ async function _acRenderInvites() { ${_esc(i.kind === 'activate' ? '' : i.scope_label || '')} ${i.invited_by ? _esc(i.invited_by) : _esc(t('acc.actor_above'))} ${_esc(_acInviteState(i))} - - `).join('')} + + `).join('')} ` : ''; } diff --git a/dashboard/static/index.html b/dashboard/static/index.html index 3bbc759..99a9856 100644 --- a/dashboard/static/index.html +++ b/dashboard/static/index.html @@ -2447,7 +2447,7 @@ for (const k of keys) { const label = `${labels[currentVmGroup]}: ${currentVmGroup === 'node' ? t('vm.group_label.peer') + ' ' + k : k}`; const gk = `${currentVmGroup}:${k}`, folded = vmCollapsed.has(gk) && !vmQuery; // a search opens every group with a match - body += `▾${_clEsc(label)}${groups[k].length}` + body += `▾${_clEsc(label)}${groups[k].length}` + (folded ? '' : groups[k].sort(cmp).map(row).join('')); } } @@ -3357,9 +3357,9 @@ if (!data||!data.measurements||!data.measurements.length) { container.innerHTML=`
${t('empty.no_measurements')}
`; return; } container.innerHTML = data.measurements.map(name => { const m = getModuleMeta(name); - return `
+ return `
${m.icon}
-
${name}
${m.desc}
+
${_clEsc(name)}
${m.desc}
`; }).join(''); } @@ -4764,7 +4764,7 @@ - +
`).join(''); @@ -4819,7 +4819,7 @@
${t('proxies.bench')}
${t('proxies.logs')}
-
${t('clusters.remove')}
`); +
${t('clusters.remove')}
`); } function pxAddOpen() { hcmModal({ @@ -6322,9 +6322,9 @@ ${canVm('vm.console', cid, it.vm_uuid) ? `` : ''} ${can('console_check.manage', cid) ? `` : ''}` : ''; const muteCtl = it.muted_until - ? `` - : `${t('notice.mute_for')}${t('notice.days')} - `; + ? `` + : `${t('notice.mute_for')}${t('notice.days')} + `; return `
${ALERT_ICON[it.severity]}
${_alertText(it)}
${meta.join(' · ')}
${consoleBtns}${muteCtl}
`; @@ -6508,7 +6508,7 @@ ` : ''} - ${admin ? `` : ''} + ${admin ? `` : ''} `).join('')}
`; } @@ -6670,10 +6670,10 @@ ${p.members.length ? `` : ''} - + - +
@@ -6874,7 +6874,7 @@ ${!m.prediction ? '—' : m.prediction.learned ? `~${_polDur(m.prediction.seconds)}` : `${t('ex.pol_tl_learning', {n: m.prediction.samples, of: m.prediction.needed || 5})}`} ${m.last_run ? `${_exStatusBadge(m.last_run.status, m.last_run.message)}${m.last_run.notice ? ' ' + _exNoticeBadge(m.last_run.notice) : ''}
${_exFmt(m.last_run.started_at)}
` : `${t('ex.never')}`} ${m.cluster_id === currentCluster ? `` : ''} - `).join('')} + `).join('')} ` : `
${t('ex.pol_no_members')}
`}
${t('ex.pol_add_hint')}
@@ -7238,7 +7238,7 @@ -
+
${t('tr.rule', {n: p.interval_days, fixed: fixed.length, random: p.random_count, weeks: p.rest_weeks})} ${_trTargetLine(p)}
${opts.join(' · ')}${p.last_run_at ? ` · ${t('tr.last_round', {when: _exFmt(p.last_run_at)})}` : ''}
${fixed.map(member).join('')}${excl.map(member).join('')}
@@ -7349,7 +7349,7 @@ ${r.detail ? `
${_exEsc(r.detail)}
` : ''} ${(r.checks || []).length ? `
${r.checks.map(c => `${_exEsc(c.ip)}: ${t(c.ping ? 'tr.ping_ok' : 'tr.ping_no')}${Object.entries(c.ports || {}).map(([pt, ok]) => ` · ${pt} ${ok ? '✓' : '✕'}`).join('')}`).join('
')}
` : ''} ${r.keep_until && !r.cleaned_at ? `
${t('tr.kept_until', {when: _exFmt(r.keep_until)})}
` : ''} - ${r.has_screenshot ? `` : ''}`).join('')}` + ${r.has_screenshot ? `` : ''}`).join('')}` : `
${t('tr.history_none')}
`}`; } function trScreenshot(id, vm) { @@ -7386,9 +7386,9 @@ ${_vfChainCell(c)} ${_trChainCell(c)} - + ${admin ? ` - ` : ''} + ` : ''}
`).join('')}`; @@ -7413,7 +7413,7 @@ ${p.seq}${t(p.kind === 'full' ? 'ex.point_full' : 'ex.point_delta')} ${_exEsc(p.dir)}${p.synthetic ? ` ${t('ex.synthetic')}` : ''}${(p.short_disks || []).length ? ` ${t('ex.short_disk')}` : ''}${p.quiesced === true ? ` ${t('ex.quiesced')}` : p.quiesced === false ? ` ${t('ex.crash_consistent')}` : ''} ${_exFmt(p.created_at)}${_exMiB(p.blocks)}${_exMiB(p.bytes_written ? Math.round(p.bytes_written / 1048576) : null)} ${p.verify_error ? `${t('ex.point_corrupt')}` : p.verified_at ? _exFmt(p.verified_at) : '—'} - `).join('')}` : `
${t('ex.no_points')}
`; + `).join('')}` : `
${t('ex.no_points')}
`; } catch (e) { body.innerHTML = `
${_exEsc(e.message)}
`; } } let _exChains = {}; @@ -7539,13 +7539,13 @@ const crumbs = ['/'].concat(st.path.split('/').filter(Boolean)); let acc = ''; const back = _pts ? `← ${t('ex.tab.points')} · ` : ''; - const crumbHtml = back + crumbs.map((c, i) => { if (i > 0) acc += '/' + c; const p = i === 0 ? '/' : acc; return `${_exEsc(i === 0 ? t('ex.flr_root') : c)}`; }).join(' / '); + const crumbHtml = back + crumbs.map((c, i) => { if (i > 0) acc += '/' + c; const p = i === 0 ? '/' : acc; return `${_exEsc(i === 0 ? t('ex.flr_root') : c)}`; }).join(' / '); const rows = st.entries.map(e => { const full = _flrJoin(st.path, e.name); const sel = st.selected.has(full); const icon = e.kind === 'dir' ? '📁' : e.kind === 'link' ? '🔗' : '📄'; - const name = e.kind === 'dir' ? `${_exEsc(e.name)}` : _exEsc(e.name); + const name = e.kind === 'dir' ? `${_exEsc(e.name)}` : _exEsc(e.name); const size = e.size != null ? (e.size >= 1048576 ? (e.size / 1048576).toFixed(1) + ' MiB' : e.size >= 1024 ? (e.size / 1024).toFixed(0) + ' KiB' : e.size + ' B') : (e.fstype ? `${_exEsc(e.fstype)} · ${(e.size || 0) / 1073741824 | 0} GiB` : ''); - return ` + return ` ${icon} ${name}${size} ${e.mtime ? _exFmt(new Date(e.mtime * 1000).toISOString()) : ''} ${e.kind === 'file' ? `${t('ex.flr_download')}` : ''}`; diff --git a/tests/test_dashboard_escaping.py b/tests/test_dashboard_escaping.py new file mode 100644 index 0000000..43e7337 --- /dev/null +++ b/tests/test_dashboard_escaping.py @@ -0,0 +1,76 @@ +"""Server strings in the dashboard's HTML templates: escaped, and never compiled as code. + +The HTML parser decodes an attribute before the browser compiles an inline handler, so +`onclick="f('${_clEsc(name)}')"` runs a VM tag or file name such as `')-alert(1)-('` as script: +`'` is a quote again by the time the handler is compiled. Server strings go into a +`data-*` attribute and the handler reads them from `this.dataset`.""" +import re + +import pytest + +FILES = ('dashboard/static/index.html', 'dashboard/static/access.js', 'dashboard/static/mail.js') + +# ids the server generates (UUIDs, serial numbers), optionally escaped or defaulted to '' +_ID = re.compile(r"^(?:_clEsc|_exEsc)?\(?(?:[a-z]+\.)?(?:id|seq|uuid|vm_uuid|node_uuid|cluster_id|user_id|group_id|role_id" + r"|assignment_id|invitation_id|folder_id|node_id)(?:\s*\|\|\s*'')?\)?$") +# a choice between two literals: p.enabled ? 'false' : 'true' +_CHOICE = re.compile(r"^[\w.]+(?:\s*===\s*'\w+')?\s*\?\s*'\w*'\s*:\s*'\w*'$") +# names that only ever hold a number, an id or a constant of the page's own code +_CODE = { + 'i', 'id', 'uid', 'gid', 'cid', 'clusterId', 'folderId', 'definedAt', 'cur ? cur.id : 0', + 'key', # a folder id / '__unfiled__', or a tunable's key from CTRL_INFO / SENT_INFO + 'k', # a sub-tab name of Settings > Access + 'kind', # 'vm' / 'folder' in the new-policy button + 'prefix', 'activeTab', 'addLevel', 'it.kind', 'def.key', 'meta.key', 'group.id', + 'v', # a segment value of a CTRL_GROUPS control + 'open', # acOpenGroup('') / acOpenUser('') built from ids + 'c.parent', "c.parent ? `'${c.parent}'` : 'null'", +} + + +def _interpolations(value): + out, i = [], 0 + while (j := value.find('${', i)) >= 0: + k, depth = j + 2, 1 + while depth and k < len(value): + depth += {'{': 1, '}': -1}.get(value[k], 0) + k += 1 + out.append(value[j + 2:k - 1].strip()) + i = k + return out + + +def _inline_handlers(src): + """(line, attribute value) of every inline handler that holds a ${...}.""" + for m in re.finditer(r'\bon[a-z]+="', src): + i, depth = m.end(), 0 + while i < len(src): + if src.startswith('${', i): + depth, i = depth + 1, i + 2 + continue + ch = src[i] + if depth and ch in '{}': + depth += 1 if ch == '{' else -1 + elif not depth and ch == '"': + break + i += 1 + value = src[m.end():i] + if '${' in value: + yield src.count('\n', 0, m.start()) + 1, value + + +@pytest.mark.parametrize('rel', FILES) +def test_inline_handlers_interpolate_only_ids_and_constants(repo, rel): + src = (repo / rel).read_text(encoding='utf-8') + bad = [f'{rel}:{line}: ${{{e}}}' for line, value in _inline_handlers(src) for e in _interpolations(value) + if not (_ID.match(e) or _CHOICE.match(e) or e in _CODE)] + assert not bad, 'put these in a data-* attribute and read this.dataset in the handler:\n' + '\n'.join(bad) + + +def test_the_scanner_sees_the_old_sinks(): + """The guard itself: the 1.8.0 VM group header and restore-point file links are found.""" + old = ("" + "") + found = [e for _, v in _inline_handlers(old) for e in _interpolations(v)] + assert found == ['encodeURIComponent(gk)', '_exEsc(full)'] + assert not any(_ID.match(e) or _CHOICE.match(e) or e in _CODE for e in found) From b54cbca2da0dbc64c422ba44fb755ef287906f89 Mon Sep 17 00:00:00 2001 From: William David van Collenburg Date: Sun, 22 Nov 2026 17:56:19 +0100 Subject: [PATCH 072/114] fix(ui): VM names, IPs and reasons from the server are escaped in every table Several screens built HTML from server text as it came: the migration log (VM name, source and target IP, engine, mode, reason, also in a title attribute), the forecast runs (error in a title attribute that only escaped double quotes, peak node IP), the queued predictions (VM name, IPs, reason), Foresight forecasts (entity label) and right-sizing (VM name), the What-If VM list (