Files
kevinveenbirkenbachandClaude Opus 5.5 9bc93b14d7 fix(sys-ctl-hlth-runtime): serialize image exports across swarm nodes
CI run 43828138456 aborted its swarm jobs with DISK EXHAUSTION IMMINENT
right after sys-service-terminator started the hlth-runtime unit. Every
lab node is a container on the same runner disk, and each node ran its
own Syft docker: export. One export costs up to three times the image:
the daemon stages it, the engine saves image.tar, and Syft copies every
layer uncompressed. EXPORT_SLOTS was a per-process semaphore, so the
nodes exported side by side. The thesis that the check downloads per-node
databases is refuted: the databases are one host directory, bind-mounted
read-only into every node.

ExportSlot replaces the semaphore with a flock on the database
directory. Every lab node and every local worktree stack bind-mounts
that directory from INFINITO_VULNERABILITY_DB_HOST_PATH, so exports now
take turns per host disk, while a production node keeps its own
directory. Each engine container gets a unique name. On a timeout or
crash the container is force-removed before the slot and the scratch
directory are given up. A database directory that cannot be locked
fails only its own lanes, with one error line. run_lanes takes the
Layout; the CLI scan and utils/security/database.py callers follow.

The trivy host-scan timeout behind PR 2009 odoo#1 has a separate cause
and is not part of this change.

Evidence:
- test_script.py of sys-ctl-hlth-runtime: 169 passed.
- utils/security: test_database 21, test_pipeline 4, test_deploy 7,
  test_engine 8, test_suppressions 20 passed.
- cli/contributing/security: test_scan 15, test_database 3 passed.
- Negative controls fail as expected: the old database.py caller (2
  failures), no container removal (2), no SlotError conversion (1), one
  lock above the per-node directories (5, barrier broken), a fixed
  container name (1).
- An independent review found a stale database.py caller, a missing
  container cleanup, an unhandled OSError, a timing-based test and
  overstated README wording; all are fixed.
- make quality-high is green: /tmp/make-quality-high-c4-swarm-disk-3.log

Security acceptance: MEDUSA-INF-SCAN-2056, MEDUSA-INF-SCAN-2447 and
MEDUSA-INF-SCAN-2744 on roles/sys-ctl-hlth-runtime/files/python/script.py
line 1734 are accepted by design after an independent skeptic returned
ACCEPT. The line is the rmtree of the run's own scratch directory
(work/tmp-<engine>-<subject>, under a mkdtemp 0700 work directory in the
root-only cache), unchanged from the base and only re-indented by this
change; leftovers fall to the strict rmtree(work) and the next stale
sweep.

🎯 Fix: 90 %
💥 Break: 5 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: 100 %
🏆 Score: 86
🚦 Gate: ✅ 90/5, tokens and velocity <= 100, security 100 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:27:04 +00:00

154 lines
5.1 KiB
Python

"""Download the vulnerability databases into one shared directory."""
from __future__ import annotations
import fcntl
import http.client
import os
import shutil
import time
import urllib.parse
import urllib.request
from typing import TYPE_CHECKING
from utils.security.pipeline import engine_image, pipeline, role_services, user_runtime
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from pathlib import Path
from types import ModuleType
OSV_BUCKET = "https://osv-vulnerabilities.storage.googleapis.com"
DOWNLOAD_TIMEOUT_SECONDS = 600
MAX_AGE_SECONDS = 24 * 3600
LOCK_NAME = ".lock"
def osv_url(ecosystem: str) -> str:
return f"{OSV_BUCKET}/{urllib.parse.quote(ecosystem)}/all.zip"
def fetch_url(url: str, destination: Path) -> None:
request = urllib.request.Request( # noqa: S310 - https download from the OSV bucket
url, headers={"User-Agent": "infinito-nexus-vulnerability-db"}
)
with (
urllib.request.urlopen(request, timeout=DOWNLOAD_TIMEOUT_SECONDS) as response, # noqa: S310 - https download from the OSV bucket
destination.open("wb") as target,
):
shutil.copyfileobj(response, target)
def osv_zips(p: ModuleType, root: Path) -> list[Path]:
"""Return the OSV offline database file of every listed ecosystem."""
return [
root / "osv" / p.OSV_DB_LAYOUT / ecosystem / "all.zip"
for ecosystem in role_services()["osv"]["ecosystems"]
]
def fetch_databases(
p: ModuleType,
root: Path,
engines: Sequence[str],
runner,
fetch: Callable[[str, Path], None],
) -> list[str]:
"""Download the databases of *engines* into *root*.
Args:
p: the vulnerability pipeline.
root: the database root, one directory per engine.
engines: the engines whose database to download.
runner: runs one engine command.
fetch: ``(url, destination)`` downloader.
Returns:
The error lines of the engines whose download failed.
"""
layout = p.Layout(
runtime=user_runtime(), databases=root, sbom=root, work=root, excludes=()
)
lanes = []
for engine in engines:
(root / engine).mkdir(parents=True, exist_ok=True)
if engine != "osv":
lanes.append(p.db_steps(engine, layout, engine_image(engine)))
errors = p._flat(p.run_lanes(lanes, runner, len(lanes) or 1, layout))
if "osv" in engines:
for zip_file in osv_zips(p, root):
zip_file.parent.mkdir(parents=True, exist_ok=True)
partial = zip_file.with_name(f"{zip_file.name}.part")
try:
fetch(osv_url(zip_file.parent.name), partial)
except (OSError, http.client.HTTPException) as exc:
partial.unlink(missing_ok=True)
errors.append(f"osv {zip_file.parent.name}: {exc}")
continue
partial.replace(zip_file)
for engine in engines:
errors += p.missing_databases(engine, root)
return errors
def database_files(p: ModuleType, root: Path, engine: str) -> list[Path]:
"""Return the files that make up one engine's database."""
if engine == "osv":
return osv_zips(p, root)
return [root / engine / marker for marker in p.DB_MARKERS[engine]]
def stale(p: ModuleType, root: Path, engine: str, now: float) -> bool:
"""Whether one engine's database is missing or older than a day."""
files = database_files(p, root, engine)
return not all(
path.is_file() and now - path.stat().st_mtime < MAX_AGE_SECONDS
for path in files
)
def hand_over(root: Path, paths: Sequence[Path]) -> None:
"""Give *paths* and everything below them to the owner of *root*.
Args:
root: the shared database directory.
paths: what this process may have written below *root*; a missing
path or a symlink is skipped.
"""
if os.geteuid() != 0:
return
owner = root.stat()
for path in (path for path in paths if path.exists() and not path.is_symlink()):
os.chown(path, owner.st_uid, owner.st_gid, follow_symlinks=False)
for _directory, dirs, files, parent in os.fwalk(path, follow_symlinks=False):
for name in (*dirs, *files):
os.chown(
name,
owner.st_uid,
owner.st_gid,
dir_fd=parent,
follow_symlinks=False,
)
def refresh(
root: Path,
engines: Sequence[str],
runner,
fetch: Callable[[str, Path], None],
) -> list[str]:
"""Download every database of *engines* that is missing or stale.
Returns:
The error lines of the downloads that failed.
"""
p = pipeline()
root.mkdir(parents=True, exist_ok=True)
lock_path = root / LOCK_NAME
with lock_path.open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
outdated = [engine for engine in engines if stale(p, root, engine, time.time())]
errors = fetch_databases(p, root, outdated, runner, fetch) if outdated else []
hand_over(root, [lock_path, *(root / engine for engine in outdated)])
return errors