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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -474,9 +474,21 @@ CI-only (native ARM64 GitHub Actions, up to 2 hours, `workflow_dispatch`);
and signing is, by this project's unbroken precedent
([ADR-0006](docs/adrs/0006-production-signing-key-custody.md)), a manual
step the maintainer performs offline with a key the assistant never
handles. Compose-template validation for llama.cpp's and SearXNG's own
templates (the way Pi-hole's already is) also remains unextended — a
smaller, separately scoped follow-up.
handles.

**Compose-template validation is now extended to all three images.**
`validate_appliance_configuration` previously rendered and ran `docker
compose config --quiet` against Pi-hole's Compose template only; a
malformed `llama/compose.yaml.in` or `searxng/compose.yaml.in` would have
passed release validation silently and only failed later, at real
Compose-up time on a device. Generalized into the same `COMPOSE_TEMPLATES`
data-driven loop shape `IMAGE_COMPONENTS` already established, handling
llama's second (`@LLAMA_MODEL_FILENAME@`, substituted at deploy time, not
release-validation time) placeholder and SearXNG's `SEARXNG_SECRET`
env-var reference along the way. Verified against real `docker` (not the
fake stub the rest of this suite uses) that all three real templates pass
and a structurally broken one is rejected
(`tests/test_appliance_compose_validation.py`).

**Conversation Service:** implemented — `sovereign_conversation.py`
(RFC-0003/0004's bounded propose→execute→narrate loop: max 3 rounds per
Expand Down
17 changes: 12 additions & 5 deletions docs/research/searxng-signed-release-qualification-assessment.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ pass tests real gaps, not ones already known and fixable from a desk.

## Limitations

- Compose-template rendering and `nginx -t`-style deep validation
- ~~Compose-template rendering and `nginx -t`-style deep validation
(`validate_appliance_configuration`'s existing behavior for Pi-hole) was
**not** extended to llama.cpp's or SearXNG's own compose templates —
only the image-import/digest-matching half of activation was
Expand All @@ -149,7 +149,14 @@ pass tests real gaps, not ones already known and fixable from a desk.
`validate_release_payload` and only fail later, at Compose-up time. This
is a smaller, contained follow-up, not attempted here to keep this
change's scope to what the image-import generalization actually
required.
required.~~ **Closed 2026-08-22**: `validate_appliance_configuration`
now renders and runs `docker compose config --quiet` against all three
templates (`COMPOSE_TEMPLATES`, generalizing the same loop shape
`IMAGE_COMPONENTS` already established), not just Pi-hole's. Verified
against real `docker` (not the fake stub the rest of this test suite
uses elsewhere) that all three real templates pass, and that a
structurally invalid one is rejected — see
`tests/test_appliance_compose_validation.py`.
- Finding 1 (systemd units require a base-OS update, not an appliance
update) remains completely open — nothing in this change set attempts a
base-OS update mechanism change, since none is needed: the mechanism
Expand Down Expand Up @@ -183,10 +190,10 @@ logic that the fake-tool unit-test harness can't surface.

## Unresolved Questions

- Should `validate_appliance_configuration` be extended to render and
- ~~Should `validate_appliance_configuration` be extended to render and
validate llama.cpp's and SearXNG's own Compose templates the way it
already does for Pi-hole's? (Flagged above as a Limitation, not decided
here.)
already does for Pi-hole's?~~ **Resolved 2026-08-22: yes, done** — see
the Limitations entry above.
- Does a three-image sequential `docker load` (each up to 900s) fit
comfortably inside whatever end-to-end time budget a real update
transaction is expected to complete in? Untested.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,12 @@ IMAGE_COMPONENTS = (
("llama", "llama-image.env", "llama-arm64.oci.tar", "LLAMA_IMAGE_REPOSITORY", "LLAMA_IMAGE_DIGEST", "LLAMA_IMAGE_PLATFORM"),
("searxng", "searxng-image.env", "searxng-arm64.oci.tar", "SEARXNG_IMAGE_REPOSITORY", "SEARXNG_IMAGE_DIGEST", "SEARXNG_IMAGE_PLATFORM"),
)
# key, Compose template path (relative to appliance/), image placeholder token
COMPOSE_TEMPLATES = (
("pihole", "pihole/compose.yaml.in", "PIHOLE_IMAGE_REFERENCE"),
("llama", "llama/compose.yaml.in", "LLAMA_IMAGE_REFERENCE"),
("searxng", "searxng/compose.yaml.in", "SEARXNG_IMAGE_REFERENCE"),
)
RELEASE_FILES = {
**APPLIANCE_FILES,
"pihole-arm64.oci.tar": 0o644,
Expand Down Expand Up @@ -1086,14 +1092,15 @@ def prepare_update(args):
return snapshot["transaction_id"]


def run_checked(command, code, message, timeout=120):
def run_checked(command, code, message, timeout=120, env=None):
try:
subprocess.run(
command,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=timeout,
env=env,
)
except (OSError, subprocess.SubprocessError) as error:
raise UpdateError(code, message) from error
Expand Down Expand Up @@ -1401,10 +1408,34 @@ def validate_release_payload(release, manifest):
fail(image_env.get(repository_key) == target["repository"], "COMPONENT_MISMATCH", f"{key} repository does not match")
fail(image_env.get(digest_key) == target["digest"], "COMPONENT_MISMATCH", f"Invalid {key} digest")
fail(image_env.get(platform_key) == "linux/arm64", "COMPONENT_MISMATCH", f"{key} platform does not match")
validate_appliance_configuration(release, manifest["components"]["pihole"])
validate_appliance_configuration(release, manifest["components"])


def render_compose_template(key, template, placeholder, image_reference):
fail(
template.count(f"@{placeholder}@") == 1,
"INVALID_COMPOSE_TEMPLATE",
f"{key} Compose template has an invalid image placeholder",
)
rendered = template.replace(f"@{placeholder}@", image_reference)
if key == "llama":
# @LLAMA_MODEL_FILENAME@ is substituted by start-llama-server at
# deploy time, not at release validation time -- a real filename
# here would tie this check to ADR-0013's specific model choice,
# so a syntactically valid stand-in is substituted instead to
# validate the template's real rendered shape.
fail(
rendered.count("@LLAMA_MODEL_FILENAME@") == 1,
"INVALID_COMPOSE_TEMPLATE",
"llama Compose template has an invalid model placeholder",
)
rendered = rendered.replace(
"@LLAMA_MODEL_FILENAME@", "validation-placeholder.gguf"
)
return rendered


def validate_appliance_configuration(release, pihole):
def validate_appliance_configuration(release, components):
appliance = release / "appliance"
for script in sorted((appliance / "bin").iterdir()):
# Classify by shebang, not a hardcoded name set: this updater is
Expand Down Expand Up @@ -1470,37 +1501,39 @@ def validate_appliance_configuration(release, pihole):
"Console release identity does not match the target release",
)

image_reference = (
f"{pihole['repository'].removeprefix('docker.io/')}@{pihole['digest']}"
)
with tempfile.TemporaryDirectory(
prefix="appliance-validation-", dir=release.parent
) as temporary_directory:
temporary = pathlib.Path(temporary_directory)
compose = temporary / "compose.yaml"
try:
template = (appliance / "pihole/compose.yaml.in").read_text(
encoding="utf-8"
for key, template_path, placeholder in COMPOSE_TEMPLATES:
image_reference = (
f"{components[key]['repository'].removeprefix('docker.io/')}"
f"@{components[key]['digest']}"
)
fail(
template.count("@PIHOLE_IMAGE_REFERENCE@") == 1,
try:
template = (appliance / template_path).read_text(encoding="utf-8")
rendered = render_compose_template(key, template, placeholder, image_reference)
except (OSError, UnicodeError) as error:
raise UpdateError(
"INVALID_COMPOSE_TEMPLATE",
f"{key} Compose template could not be rendered",
) from error
compose = temporary / f"{key}-compose.yaml"
compose.write_text(rendered, encoding="utf-8")
env = None
if key == "searxng":
# SEARXNG_SECRET is only ever exported for the single real
# `docker compose up` invocation (start-searxng), never
# persisted -- a dummy value here exists only so `compose
# config` doesn't warn about an unset variable, the same
# shape start-searxng itself provides at deploy time.
env = {**os.environ, "SEARXNG_SECRET": "0" * 64}
run_checked(
[DOCKER, "compose", "--file", str(compose), "config", "--quiet"],
"INVALID_COMPOSE_TEMPLATE",
"Pi-hole Compose template has an invalid image placeholder",
f"{key} Compose template failed validation",
env=env,
)
compose.write_text(
template.replace("@PIHOLE_IMAGE_REFERENCE@", image_reference),
encoding="utf-8",
)
except (OSError, UnicodeError) as error:
raise UpdateError(
"INVALID_COMPOSE_TEMPLATE",
"Pi-hole Compose template could not be rendered",
) from error
run_checked(
[DOCKER, "compose", "--file", str(compose), "config", "--quiet"],
"INVALID_COMPOSE_TEMPLATE",
"Pi-hole Compose template failed validation",
)

nginx_include = str(appliance / "nginx/sovereign.conf").replace(
"\\", "\\\\"
Expand Down
179 changes: 179 additions & 0 deletions tests/test_appliance_compose_validation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import importlib.util
import os
import shutil
import subprocess
import tempfile
import unittest
from importlib.machinery import SourceFileLoader
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
CLIENT = (
ROOT
/ "image-builder/sovereign/layer/sovereign-proof.rootfs-overlay/usr/sbin/sovereign-update"
)
APPLIANCE = ROOT / "image-builder/sovereign/appliance"
DOCKER = shutil.which("docker")

_TEMP_FOR_IMPORT = tempfile.TemporaryDirectory()
os.environ.setdefault("SOVEREIGN_UPDATE_TEST_MODE", "1")
os.environ.setdefault("SOVEREIGN_BASE_OS_RELEASE_PATH", str(Path(_TEMP_FOR_IMPORT.name) / "base-os-release"))
Path(os.environ["SOVEREIGN_BASE_OS_RELEASE_PATH"]).write_text('VERSION="0.1.0-proof.1"\n')
SPEC = importlib.util.spec_from_loader("sovereign_update", SourceFileLoader("sovereign_update", str(CLIENT)))
MODULE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(MODULE)

FAKE_DIGEST = f"sha256:{'0' * 64}"


class ComposeTemplatesRegistryTests(unittest.TestCase):
"""RFC-0017/0019's IMAGE_COMPONENTS already covers all three embedded
images (Pi-hole, llama.cpp, SearXNG) -- COMPOSE_TEMPLATES must name the
same set, or a component silently gets no Compose-template validation
at release time (the exact gap this change closes for llama/SearXNG)."""

def test_every_image_component_has_a_compose_template_entry(self):
image_keys = {key for key, *_ in MODULE.IMAGE_COMPONENTS}
template_keys = {key for key, *_ in MODULE.COMPOSE_TEMPLATES}
self.assertEqual(image_keys, template_keys)

def test_every_referenced_template_file_exists(self):
for _, template_path, _ in MODULE.COMPOSE_TEMPLATES:
self.assertTrue(
(APPLIANCE / template_path).is_file(),
f"missing Compose template: {template_path}",
)


class RenderComposeTemplateTests(unittest.TestCase):
"""render_compose_template is the pure-logic half of the release-time
Compose validation (RFC-0017/RFC-0019's searxng-signed-release
qualification assessment named this exact gap: a malformed llama or
SearXNG template previously passed validate_release_payload silently
and only failed later, at real `docker compose up` time)."""

def _real_template(self, key):
template_path = dict((k, t) for k, t, _ in MODULE.COMPOSE_TEMPLATES)[key]
return (APPLIANCE / template_path).read_text(encoding="utf-8")

def test_renders_the_real_pihole_template(self):
rendered = MODULE.render_compose_template(
"pihole", self._real_template("pihole"), "PIHOLE_IMAGE_REFERENCE",
f"ghcr.io/example/pihole@{FAKE_DIGEST}",
)
self.assertNotIn("@PIHOLE_IMAGE_REFERENCE@", rendered)
self.assertIn(f"ghcr.io/example/pihole@{FAKE_DIGEST}", rendered)

def test_renders_the_real_llama_template_substituting_both_placeholders(self):
# llama's template is the only one with a second placeholder
# (@LLAMA_MODEL_FILENAME@), substituted by start-llama-server at
# deploy time rather than release-validation time -- the real
# regression this guards is a stray, un-substituted @...@ token
# reaching `docker compose config` silently as a literal string.
rendered = MODULE.render_compose_template(
"llama", self._real_template("llama"), "LLAMA_IMAGE_REFERENCE",
f"ghcr.io/example/llama@{FAKE_DIGEST}",
)
self.assertNotIn("@LLAMA_IMAGE_REFERENCE@", rendered)
self.assertNotIn("@LLAMA_MODEL_FILENAME@", rendered)
self.assertIn("validation-placeholder.gguf", rendered)

def test_renders_the_real_searxng_template(self):
rendered = MODULE.render_compose_template(
"searxng", self._real_template("searxng"), "SEARXNG_IMAGE_REFERENCE",
f"ghcr.io/example/searxng@{FAKE_DIGEST}",
)
self.assertNotIn("@SEARXNG_IMAGE_REFERENCE@", rendered)
self.assertIn(f"ghcr.io/example/searxng@{FAKE_DIGEST}", rendered)

def test_rejects_a_missing_image_placeholder(self):
with self.assertRaises(MODULE.UpdateError) as caught:
MODULE.render_compose_template(
"pihole", "services:\n pihole:\n image: pinned\n",
"PIHOLE_IMAGE_REFERENCE", f"ghcr.io/example/pihole@{FAKE_DIGEST}",
)
self.assertEqual("INVALID_COMPOSE_TEMPLATE", caught.exception.code)

def test_rejects_a_duplicated_image_placeholder(self):
template = "services:\n a:\n image: @PIHOLE_IMAGE_REFERENCE@\n b:\n image: @PIHOLE_IMAGE_REFERENCE@\n"
with self.assertRaises(MODULE.UpdateError) as caught:
MODULE.render_compose_template(
"pihole", template, "PIHOLE_IMAGE_REFERENCE",
f"ghcr.io/example/pihole@{FAKE_DIGEST}",
)
self.assertEqual("INVALID_COMPOSE_TEMPLATE", caught.exception.code)

def test_rejects_a_llama_template_missing_the_model_placeholder(self):
template = "services:\n llama-server:\n image: @LLAMA_IMAGE_REFERENCE@\n"
with self.assertRaises(MODULE.UpdateError) as caught:
MODULE.render_compose_template(
"llama", template, "LLAMA_IMAGE_REFERENCE",
f"ghcr.io/example/llama@{FAKE_DIGEST}",
)
self.assertEqual("INVALID_COMPOSE_TEMPLATE", caught.exception.code)


@unittest.skipIf(DOCKER is None, "docker is unavailable")
class RealDockerComposeValidationTests(unittest.TestCase):
"""The actual defect this change closes: llama's and SearXNG's own
Compose templates were never run through `docker compose config`
before activation, unlike Pi-hole's. These tests use the real docker
binary (not a fake stub), since a fake stub that always exits 0 cannot
tell a syntactically valid template from a broken one -- that
distinction is the entire point of this check."""

def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.directory = Path(self.temporary.name)

def _render(self, key):
template_path = dict((k, t) for k, t, _ in MODULE.COMPOSE_TEMPLATES)[key]
placeholder = dict((k, p) for k, _, p in MODULE.COMPOSE_TEMPLATES)[key]
template = (APPLIANCE / template_path).read_text(encoding="utf-8")
return MODULE.render_compose_template(
key, template, placeholder, f"ghcr.io/example/{key}@{FAKE_DIGEST}"
)

def _validate(self, compose_text, extra_env=None):
compose = self.directory / "compose.yaml"
compose.write_text(compose_text, encoding="utf-8")
env = {**os.environ, **(extra_env or {})}
return subprocess.run(
[DOCKER, "compose", "--file", str(compose), "config", "--quiet"],
env=env, capture_output=True, timeout=30,
)

def test_the_real_pihole_template_passes(self):
result = self._validate(self._render("pihole"))
self.assertEqual(0, result.returncode, result.stderr.decode())

def test_the_real_llama_template_passes(self):
result = self._validate(self._render("llama"))
self.assertEqual(0, result.returncode, result.stderr.decode())

def test_the_real_searxng_template_passes(self):
# Mirrors start-searxng's own real invocation shape: SEARXNG_SECRET
# is exported for this one `docker compose` call, never persisted.
result = self._validate(self._render("searxng"), {"SEARXNG_SECRET": "0" * 64})
self.assertEqual(0, result.returncode, result.stderr.decode())

def test_a_structurally_broken_template_is_rejected(self):
# The real regression this check exists to catch: a template edit
# that is well-formed YAML but not a valid Compose document (here,
# `ports` given a scalar instead of a list) previously would have
# passed validate_release_payload for llama/SearXNG and only
# failed later, at real `docker compose up` time on a device.
broken = (
"services:\n"
" broken:\n"
f" image: ghcr.io/example/broken@{FAKE_DIGEST}\n"
" ports: \"not-a-list\"\n"
)
result = self._validate(broken)
self.assertNotEqual(0, result.returncode)


if __name__ == "__main__":
unittest.main()
Loading