fix(docker): validate and atomically save first-boot configuration
This commit is contained in:
1 parent
ef2cd0c8c7
commit
e20737a509
8 files changed
+314
-168
No files matched your search
+65
-64
@@ -1,72 +1,73 @@
|
||||
"""The committed Docker deploy template must always bake into a startable config.
|
||||
|
||||
`entrypoint.sh` initializes `~/.nanobot/config.json` from `docker-config.json`
|
||||
on first boot (see docker-compose.yml). A template that drifts out of sync with
|
||||
the config schema would crash-loop every container on a fresh `docker compose
|
||||
up`, so pin the contract here: the baked config validates, and its wildcard
|
||||
binds carry the secrets their security validators require.
|
||||
"""
|
||||
"""Exercise the Docker initializer that the container entrypoint invokes."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||
from nanobot.config.schema import Config
|
||||
|
||||
repo_root = Path(__file__).resolve().parents[1]
|
||||
|
||||
WEB_TOKEN_PLACEHOLDER = "${NANOBOT_WEB_TOKEN}"
|
||||
API_KEY_PLACEHOLDER = "${NANOBOT_API_KEY}"
|
||||
from nanobot.config.loader import load_config, resolve_config_env_vars
|
||||
|
||||
|
||||
def _template() -> dict:
|
||||
return json.loads((repo_root / "docker-config.json").read_text())
|
||||
|
||||
|
||||
def _baked() -> dict:
|
||||
"""The template as the entrypoint writes it, with both secrets substituted."""
|
||||
raw = (repo_root / "docker-config.json").read_text()
|
||||
raw = raw.replace(WEB_TOKEN_PLACEHOLDER, "test-web-token")
|
||||
raw = raw.replace(API_KEY_PLACEHOLDER, "test-api-key")
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def test_docker_template_bakes_to_a_valid_container_config():
|
||||
config = Config.model_validate(_baked())
|
||||
|
||||
# Binds must survive the container boundary: a loopback bind inside the
|
||||
# container is unreachable through the ports docker-compose.yml publishes.
|
||||
assert config.gateway.host == "0.0.0.0"
|
||||
assert config.api.host == "0.0.0.0"
|
||||
assert config.api.api_key == "test-api-key"
|
||||
|
||||
|
||||
def test_docker_template_websocket_satisfies_wildcard_host_auth():
|
||||
ws = WebSocketConfig.model_validate(_baked()["channels"]["websocket"])
|
||||
|
||||
assert ws.enabled is True
|
||||
assert ws.host == "0.0.0.0"
|
||||
assert ws.port == 8765
|
||||
assert ws.token_issue_secret
|
||||
assert ws.websocket_requires_token is True
|
||||
|
||||
|
||||
def test_docker_template_secrets_are_wired_for_entrypoint_substitution():
|
||||
# entrypoint.sh substitutes exactly these placeholders when writing
|
||||
# config.json (env value if provided, generated otherwise). A renamed
|
||||
# placeholder would survive substitution and reach the runtime as a
|
||||
# literal string, breaking every client that needs the real secret.
|
||||
template = _template()
|
||||
|
||||
assert template["channels"]["websocket"]["tokenIssueSecret"] == WEB_TOKEN_PLACEHOLDER
|
||||
assert template["api"]["api_key"] == API_KEY_PLACEHOLDER
|
||||
assert "${" not in json.dumps(_baked())
|
||||
|
||||
|
||||
def test_docker_template_uses_the_same_shape_as_the_render_template():
|
||||
docker_template = _template()
|
||||
render_template = json.loads((repo_root / "render-config.json").read_text())
|
||||
|
||||
assert set(docker_template["channels"]["websocket"]) == set(
|
||||
render_template["channels"]["websocket"]
|
||||
def _initialize(path: Path, web_token: str = "", api_key: str = "") -> subprocess.CompletedProcess[str]:
|
||||
env = dict(os.environ, NANOBOT_WEB_TOKEN=web_token, NANOBOT_API_KEY=api_key)
|
||||
return subprocess.run(
|
||||
[sys.executable, "-m", "nanobot.cli.docker_bootstrap", str(path)],
|
||||
env=env, capture_output=True, text=True,
|
||||
)
|
||||
|
||||
|
||||
def test_first_boot_generates_valid_container_config(tmp_path):
|
||||
path = tmp_path / "instance" / "config.json"
|
||||
result = _initialize(path)
|
||||
assert result.returncode == 0, result.stderr
|
||||
config = resolve_config_env_vars(load_config(path))
|
||||
ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"])
|
||||
assert config.gateway.host == ws.host == config.api.host == "0.0.0.0"
|
||||
assert ws.enabled and ws.websocket_requires_token
|
||||
assert len(ws.token_issue_secret) == len(config.api.api_key) == 32
|
||||
assert ws.token_issue_secret != config.api.api_key
|
||||
assert ws.token_issue_secret in result.stdout
|
||||
assert config.api.api_key in result.stdout
|
||||
|
||||
|
||||
@pytest.mark.parametrize("secret", ['review&secret', 'review|secret', 'review"secret', r'review\secret'])
|
||||
def test_custom_secrets_survive_json_serialization(tmp_path, secret):
|
||||
path = tmp_path / "config.json"
|
||||
result = _initialize(path, secret, secret)
|
||||
assert result.returncode == 0, result.stderr
|
||||
config = resolve_config_env_vars(load_config(path))
|
||||
ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"])
|
||||
assert ws.token_issue_secret == config.api.api_key == secret
|
||||
|
||||
|
||||
def test_restart_preserves_user_settings_and_credentials(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
assert _initialize(path, "original-web", "original-api").returncode == 0
|
||||
data = json.loads(path.read_text())
|
||||
data["providers"]["custom"] = {"apiKey": "provider-key", "apiBase": "http://model:8000/v1"}
|
||||
path.write_text(json.dumps(data))
|
||||
previous = path.read_bytes()
|
||||
result = _initialize(path, "replacement-web", "replacement-api")
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert path.read_bytes() == previous
|
||||
assert "replacement-web" not in result.stdout
|
||||
assert "replacement-api" not in result.stdout
|
||||
|
||||
|
||||
def test_failed_write_does_not_leave_an_existing_config(tmp_path):
|
||||
# A bind mount can be unwritable. Force failure at the actual atomic
|
||||
# replacement boundary rather than only validating the input template.
|
||||
from unittest.mock import patch
|
||||
|
||||
from nanobot.cli.docker_bootstrap import initialize_config
|
||||
|
||||
path = tmp_path / "config.json"
|
||||
with patch.object(Path, "replace", side_effect=PermissionError("read-only mount")):
|
||||
with pytest.raises(PermissionError, match="read-only mount"):
|
||||
initialize_config(path)
|
||||
assert not path.exists()
|
||||
assert list(tmp_path.iterdir()) == []
|
||||
Reference in new issue
Block a user