Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(docker): validate and atomically save first-boot configuration
chengyongrue20737a509f2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e67767e71..ea8897a36 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -423,6 +423,9 @@ jobs:- name: Build image with default channel dependenciesrun: docker build -t nanobot:test .+ - name: Verify first-boot WebUI and optional API+ run: python scripts/docker_compose_smoke.py --image nanobot:test+- name: Verify Docker Compose startup and privilege boundaryenv:HOME: ${{ runner.temp }}diff --git a/Dockerfile b/Dockerfileindex 5fc777116..c1f4bd36c 100644--- a/Dockerfile+++ b/Dockerfile@@ -54,11 +54,6 @@ RUN for channel in $(printf '%s' "$NANOBOT_CHANNELS" | tr ',' ' '); do \# won't shadow it. Only used when RENDER=true; ignored by local runs.COPY render-config.json ./-# Local Docker deploy template (see docker-compose.yml): container-appropriate-# binds with the WebUI token and API key baked in by the entrypoint at first-# boot. Same /app location so a mounted data dir can't shadow it.-COPY docker-config.json ./-# Create the non-root user and hand ownership of the writable virtualenv to it.RUN useradd -m -u 1000 -s /bin/bash nanobot && \mkdir -p /home/nanobot/.nanobot && \diff --git a/docker-config.json b/docker-config.jsondeleted file mode 100644index 5e6ee0346..000000000--- a/docker-config.json+++ /dev/null@@ -1,19 +0,0 @@-{- "gateway": {- "host": "0.0.0.0",- "port": 18790- },- "channels": {- "websocket": {- "enabled": true,- "host": "0.0.0.0",- "port": 8765,- "tokenIssueSecret": "${NANOBOT_WEB_TOKEN}",- "websocketRequiresToken": true- }- },- "api": {- "host": "0.0.0.0",- "api_key": "${NANOBOT_API_KEY}"- }-}diff --git a/docs/deployment.md b/docs/deployment.mdindex cdd9dea55..be4c2b098 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -65,7 +65,7 @@ If deployment fails, open the service **Logs** page first. A missing model key f> Official Docker usage currently means building from this repository with the included `Dockerfile`. Docker Hub images under third-party namespaces are not maintained or verified by HKUDS/nanobot; do not mount API keys or bot tokens into them unless you trust the publisher.> [!IMPORTANT]-> The gateway and WebSocket channel default to `host: "127.0.0.1"` in `config.json` (set in `nanobot/config/schema.py`). Docker `-p` port forwarding cannot reach a container's loopback interface, so for the host or LAN to reach the exposed ports you must set both binds to `0.0.0.0` in `~/.nanobot/config.json` before starting the container. To serve the bundled WebUI from Docker, bind the WebSocket channel externally and protect bootstrap with `tokenIssueSecret`:+> The gateway and WebSocket channel default to `host: "127.0.0.1"` in `config.json` (set in `nanobot/config/schema.py`). Docker `-p` port forwarding cannot reach a container's loopback interface, so for the host or LAN to reach the exposed ports existing configurations and manual Docker runs must set both binds to `0.0.0.0` in `~/.nanobot/config.json` before starting the container. The Compose first-boot setup below sets these automatically. To serve the bundled WebUI from Docker, bind the WebSocket channel externally and protect bootstrap with `tokenIssueSecret`:>> ```json> {@@ -82,31 +82,6 @@ If deployment fails, open the service **Logs** page first. A missing model key f>> When the WebSocket `host` is `0.0.0.0`, the channel refuses to start unless `token`, `tokenIssueSecret`, or a fully configured `trustedProxyAuth` is also configured. See [`webui.md#lan-access`](./webui.md#lan-access) for details. The gateway health route itself is intentionally minimal and unauthenticated. When the container binds it to `0.0.0.0`, publish port `18790` to host loopback only; place any remotely monitored health endpoint behind a firewall or reverse proxy. If another host must probe it directly, replace `127.0.0.1` in the port mapping with a trusted host interface and restrict inbound traffic to the monitoring system.-### Cloudflare Tunnel + Cloudflare Access--For a local `cloudflared` process in front of nanobot, Cloudflare Access can authenticate the user before forwarding the request and add `Cf-Access-Jwt-Assertion`. Opt in to trusted-proxy no-token mode only when the direct TCP peer is the tunnel process and the assertion is non-empty:--```json-{- "gateway": { "host": "127.0.0.1" },- "channels": {- "websocket": {- "host": "127.0.0.1",- "port": 8765,- "publicWsUrl": "wss://nanobot.example.com/",- "trustedProxyAuth": {- "trustedPeerCidrs": ["127.0.0.1/32", "::1/128"],- "assertionHeader": "Cf-Access-Jwt-Assertion"- }- }- }-}-```--This is two-part authorization: a trusted direct loopback peer **and** a non-empty Cloudflare Access assertion. A trusted CIDR alone is not a bypass. For this flow `/webui/bootstrap` returns connection metadata without a bootstrap token or REST API token; the proxy assertion authorizes the WebSocket handshake and REST requests directly.--Set `publicWsUrl` to the browser-facing `wss://` endpoint when the tunnel sends the origin host header (such as `127.0.0.1:8765`); otherwise the WebUI could attempt to open its WebSocket directly against the loopback address. The assertion header must be generated by Cloudflare Access after authentication; routing/client metadata headers such as `Host`, `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, and `CF-Connecting-IP` are rejected as `assertionHeader` values. Nanobot trusts the assertion but does not cryptographically validate the JWT, so configure the tunnel and Access policy carefully and do not expose the nanobot listener directly to untrusted clients. Forwarded client headers do not establish proxy trust.-### Docker ComposeOn a new Linux host, install Git and Docker with the Compose plugin, then get the repository. You do not need to install Python or nanobot on the host:@@ -114,43 +89,35 @@ On a new Linux host, install Git and Docker with the Compose plugin, then get th```bashgit clone https://github.com/HKUDS/nanobot.gitcd nanobot-docker compose build-docker compose run --rm nanobot-cli onboard+docker compose up -d+docker compose logs nanobot-gateway```-The last command initializes `~/.nanobot/config.json` and the workspace in the bind mount. Skip it when reusing an existing configuration. Edit that file on the host and merge your provider settings from [provider setup](./providers.md); select the provider/model you can access, either through the documented model preset or direct `agents.defaults.provider` and `agents.defaults.model` settings. Keep `agents.defaults.workspace` as a container path, normally `~/.nanobot/workspace` (resolved inside the container), rather than a host home-directory path.+On first boot, Compose initializes `~/.nanobot/config.json` with container bind addresses and random WebUI/API credentials. Open `http://HOST:8765`, enter the WebUI password printed in the first-boot logs, then configure your provider and model in **Settings → Models**. Send a message to verify the setup. No provider is required just to open the WebUI.-Also merge the Docker bind and authentication settings [above](#docker): `gateway.host` and `channels.websocket.host` must be `0.0.0.0`, and `tokenIssueSecret` must be a private random value. These snippets are partial configuration, not replacements for your provider settings. Config `${VAR}` references require those variables inside every CLI and gateway container; Compose does not forward arbitrary host variables automatically. Either add the necessary `environment` entries to the services or keep credentials in the protected config file.+Export `NANOBOT_WEB_TOKEN` or `NANOBOT_API_KEY` before the first startup to supply your own credentials. Compose forwards these variables into the containers. Existing configuration is left untouched, including credentials and bind addresses; changing these variables later does not rotate persisted credentials. If you reuse an existing configuration, check the [Docker bind and authentication settings](#docker) above.+The configuration and workspace persist in the `~/.nanobot` bind mount. Keep `agents.defaults.workspace` as a container path, normally `~/.nanobot/workspace`, rather than a host home-directory path. Other config `${VAR}` references require explicit `environment` entries in the CLI and gateway services; Compose does not forward arbitrary host variables.-The default image preinstalls WhatsApp dependencies. To bake other enabled channels into an image (recommended for deployments without PyPI access), pass a comma-separated `NANOBOT_CHANNELS` build argument:+The OpenAI-compatible API is optional and requires a configured provider. After completing model setup, enable it with:```bash-NANOBOT_CHANNELS=telegram,slack docker compose build+docker compose --profile api up -d```-The image keeps nanobot in a virtual environment owned by its built-in non-root runtime user (UID 1000). If an enabled channel was not preinstalled, gateway startup can therefore install its manifest-declared dependencies. Rebuilding with `NANOBOT_CHANNELS` keeps that installation reproducible instead of relying on the container's writable layer. If you override the container with a different `--user`, bake every enabled channel into the image because that UID is not guaranteed write access to the virtual environment.+Its endpoint is `http://127.0.0.1:8900/v1`; use the API key from the first-boot logs or `api.apiKey` in the persisted config. It is published to host loopback only.-The first `docker compose up` bootstraps `~/.nanobot/config.json` with container-appropriate binds and generated secrets: the WebUI password (`NANOBOT_WEB_TOKEN`) and the OpenAI-compatible API key (`NANOBOT_API_KEY`). Export either variable before `up` to pin your own; otherwise the entrypoint generates one and prints it to the container log. An existing `config.json` is left untouched. Add provider keys afterwards in the WebUI settings or with `onboard`:+For terminal setup, run `docker compose run --rm nanobot-cli onboard --wizard` and preserve existing settings. Verify it with `docker compose run --rm nanobot-cli agent -m "Hello!"` before starting the persistent gateway.-```bash-docker compose up -d nanobot-gateway # first boot writes ~/.nanobot/config.json-docker compose logs nanobot-gateway # shows the generated WebUI password and API key-```--The `nanobot-api` service (OpenAI-compatible endpoint on `127.0.0.1:8900`) needs a configured provider before it can serve, so it is opt-in via the `api` profile:+The default image preinstalls WhatsApp dependencies. To bake other enabled channels into an image (recommended for deployments without PyPI access), pass a comma-separated `NANOBOT_CHANNELS` build argument:```bash-docker compose --profile api up -d # also start the API once a provider is configured+NANOBOT_CHANNELS=telegram,slack docker compose build```-For a fully pre-configured setup, keep using first-time onboarding:+The image keeps nanobot in a virtual environment owned by its built-in non-root runtime user (UID 1000). If an enabled channel was not preinstalled, gateway startup can therefore install its manifest-declared dependencies. Rebuilding with `NANOBOT_CHANNELS` keeps that installation reproducible instead of relying on the container's writable layer. If you override the container with a different `--user`, bake every enabled channel into the image because that UID is not guaranteed write access to the virtual environment.```bash-docker compose run --rm nanobot-cli status-docker compose run --rm nanobot-cli agent -m "Hello!"-# Continue only after a normal reply.-docker compose up -d nanobot-gatewaycurl --fail http://127.0.0.1:18790/health```@@ -222,6 +189,31 @@ docker run -v ~/.nanobot:/home/nanobot/.nanobot --rm nanobot agent -m "Hello!"docker run -v ~/.nanobot:/home/nanobot/.nanobot --rm nanobot status```+### Cloudflare Tunnel + Cloudflare Access++For a local `cloudflared` process in front of nanobot, Cloudflare Access can authenticate the user before forwarding the request and add `Cf-Access-Jwt-Assertion`. Opt in to trusted-proxy no-token mode only when the direct TCP peer is the tunnel process and the assertion is non-empty:++```json+{+ "gateway": { "host": "127.0.0.1" },+ "channels": {+ "websocket": {+ "host": "127.0.0.1",+ "port": 8765,+ "publicWsUrl": "wss://nanobot.example.com/",+ "trustedProxyAuth": {+ "trustedPeerCidrs": ["127.0.0.1/32", "::1/128"],+ "assertionHeader": "Cf-Access-Jwt-Assertion"+ }+ }+ }+}+```++This is two-part authorization: a trusted direct loopback peer **and** a non-empty Cloudflare Access assertion. A trusted CIDR alone is not a bypass. For this flow `/webui/bootstrap` returns connection metadata without a bootstrap token or REST API token; the proxy assertion authorizes the WebSocket handshake and REST requests directly.++Set `publicWsUrl` to the browser-facing `wss://` endpoint when the tunnel sends the origin host header (such as `127.0.0.1:8765`); otherwise the WebUI could attempt to open its WebSocket directly against the loopback address. The assertion header must be generated by Cloudflare Access after authentication; routing/client metadata headers such as `Host`, `Forwarded`, `X-Forwarded-*`, `X-Real-IP`, and `CF-Connecting-IP` are rejected as `assertionHeader` values. Nanobot trusts the assertion but does not cryptographically validate the JWT, so configure the tunnel and Access policy carefully and do not expose the nanobot listener directly to untrusted clients. Forwarded client headers do not establish proxy trust.+## Switch an Existing Gateway to a ServiceBefore installing an OS service, finish active work and close WebUI/TUI launchers that could start another gateway. Stop the existing instance: use `nanobot gateway stop` for a recorded background gateway (including one retained by `/detach`), or Ctrl+C in the terminal running a foreground gateway. Pass the same `--config` and `--workspace` selectors to stop, status, and service-install commands for a custom instance.diff --git a/entrypoint.sh b/entrypoint.shindex 80f199956..62a98309c 100755--- a/entrypoint.sh+++ b/entrypoint.sh@@ -1,43 +1,22 @@#!/bin/shdir="$HOME/.nanobot"-# Container config bootstrap. Two deploy paths share the init-once logic:-# - Render (RENDER=true): template wires secrets via ${VAR} env vars, resolved-# at startup by the config loader.-# - Local Docker (NANOBOT_DOCKER_BOOTSTRAP=1, set by docker-compose.yml): a-# template with binds that work across the container boundary, and secrets-# baked in at first boot (env value if provided, otherwise generated) so a-# missing env var can never crash-loop the containers.-# Initializes the on-disk config only when it does not already exist, so-# WebUI/provider settings edited at runtime survive restarts.-# Logs each decision so a failed start is diagnosable in the container logs.-# Privilege dropping is handled below, for every root start (not just here).-if [ "$RENDER" = "true" ] || [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ]; then- echo "[entrypoint] container deploy — starting as $(id)"- mkdir -p "$dir" || echo "[entrypoint] warning: mkdir $dir failed"+# Render keeps environment references in its deployment template. Local+# Compose generates and validates its initial config through Python instead.+if [ "$RENDER" = "true" ]; thenconfig="$dir/config.json"+ mkdir -p "$dir" || exit 1if [ ! -f "$config" ]; then- if [ "$RENDER" = "true" ]; then- echo "[entrypoint] initializing $config from render-config.json"- cp /app/render-config.json "$config" || echo "[entrypoint] warning: cp config failed"- else- web_token="${NANOBOT_WEB_TOKEN:-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')}"- api_key="${NANOBOT_API_KEY:-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')}"- echo "[entrypoint] initializing $config from docker-config.json"- sed -e "s|\${NANOBOT_WEB_TOKEN}|$web_token|" \- -e "s|\${NANOBOT_API_KEY}|$api_key|" \- /app/docker-config.json > "$config" \- || echo "[entrypoint] warning: config bootstrap failed"- echo "[entrypoint] WebUI: http://localhost:8765 — password: $web_token"- echo "[entrypoint] OpenAI-compatible API: http://127.0.0.1:8900/v1 — api key: $api_key"- fi+ echo "[entrypoint] initializing $config from render-config.json"+ cp /app/render-config.json "$config" || exit 1elseecho "[entrypoint] existing $config found — leaving it in place"- if [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ]; then- echo "[entrypoint] WebUI password lives in $config (channels.websocket.tokenIssueSecret)"- fifiset -- "$@" --config "$config"+elif [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ]; then+ config="$dir/config.json"+ python -m nanobot.cli.docker_bootstrap "$config" || exit 1+ set -- "$@" --config "$config"fi# Drop privileges whenever the container starts as root. Render mounts thediff --git a/nanobot/cli/docker_bootstrap.py b/nanobot/cli/docker_bootstrap.pynew file mode 100644index 000000000..af1898242--- /dev/null+++ b/nanobot/cli/docker_bootstrap.py@@ -0,0 +1,37 @@+"""Initialize a local Docker instance without replacing existing settings."""++import os+import secrets+import sys+from pathlib import Path++from nanobot.channels.websocket.runtime import WebSocketConfig+from nanobot.config.loader import save_config+from nanobot.config.schema import Config+++def initialize_config(path: Path) -> None:+ if path.exists():+ print(f"[entrypoint] existing {path} found — leaving it in place")+ print(f"[entrypoint] WebUI password: {path} (channels.websocket.tokenIssueSecret)")+ return++ web_token = os.environ.get("NANOBOT_WEB_TOKEN") or secrets.token_hex(16)+ api_key = os.environ.get("NANOBOT_API_KEY") or secrets.token_hex(16)+ websocket = WebSocketConfig(+ enabled=True, host="0.0.0.0", token_issue_secret=web_token,+ websocket_requires_token=True,+ )+ config = Config.model_validate({+ "gateway": {"host": "0.0.0.0"},+ "channels": {"websocket": websocket.model_dump(by_alias=True)},+ "api": {"host": "0.0.0.0", "api_key": api_key},+ })+ save_config(config, path)+ print(f"[entrypoint] initialized {path}")+ print(f"[entrypoint] WebUI: http://localhost:8765 — password: {web_token}")+ print(f"[entrypoint] OpenAI-compatible API key: {api_key}")+++if __name__ == "__main__":+ initialize_config(Path(sys.argv[1]))diff --git a/scripts/docker_compose_smoke.py b/scripts/docker_compose_smoke.pynew file mode 100644index 000000000..cfcd51537--- /dev/null+++ b/scripts/docker_compose_smoke.py@@ -0,0 +1,158 @@+"""Verify Compose first boot, WebUI authentication, restart, and optional API."""++import argparse+import json+import os+import subprocess+import tempfile+import time+from pathlib import Path+from urllib.error import HTTPError, URLError+from urllib.request import Request, urlopen+++def request(url: str, secret: str = "") -> tuple[int, bytes]:+ headers = {"Authorization": f"Bearer {secret}"} if secret else {}+ try:+ with urlopen(Request(url, headers=headers), timeout=3) as response:+ return response.status, response.read()+ except HTTPError as exc:+ return exc.code, exc.read()+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--image", required=True, help="Already-built Docker image")+ args = parser.parse_args()+ repo = Path(__file__).resolve().parents[1]+ config = json.loads(subprocess.check_output(+ ["docker", "compose", "-f", str(repo / "docker-compose.yml"),+ "--profile", "cli", "--profile", "api", "config", "--format", "json"],+ text=True,+ ))+ with tempfile.TemporaryDirectory(prefix="nanobot-compose-smoke-") as temporary:+ root = Path(temporary)+ config.pop("name", None)+ for network in config.get("networks", {}).values():+ network.pop("name", None)+ for service in config["services"].values():+ service.pop("build", None)+ service.pop("container_name", None)+ service["image"] = args.image+ for port in service.get("ports", []):+ port.update(host_ip="127.0.0.1", published="0")+ compose_path = root / "compose.json"+ compose = ["docker", "compose", "-p", root.name, "-f", str(compose_path)]++ def run(*arguments: str) -> str:+ return subprocess.check_output([*compose, *arguments], text=True)++ def endpoint(service: str, port: int) -> str:+ return "http://" + run("port", service, str(port)).strip()++ def wait_for(url: str) -> None:+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ try:+ if request(url)[0] == 200:+ return+ except (URLError, ConnectionError, TimeoutError):+ pass+ time.sleep(1)+ raise RuntimeError(f"Endpoint did not become ready: {url}")++ for label, secret in (("generated", ""), ("custom", 'review&|"\\secret')):+ data = root / label+ data.mkdir()+ for service in config["services"].values():+ service["volumes"] = [{+ "type": "bind", "source": str(data),+ "target": "/home/nanobot/.nanobot",+ }]+ service["environment"].update(+ NANOBOT_WEB_TOKEN=secret, NANOBOT_API_KEY=secret,+ )+ compose_path.write_text(json.dumps(config))+ try:+ run("up", "-d")+ health = endpoint("nanobot-gateway", 18790)+ webui = endpoint("nanobot-gateway", 8765)+ wait_for(health + "/health")+ wait_for(webui + "/")+ assert run("ps", "--services").split() == ["nanobot-gateway"]+ path = data / "config.json"+ saved = json.loads(path.read_text())+ password = saved["channels"]["websocket"]["tokenIssueSecret"]+ api_key = saved["api"]["apiKey"]+ if secret:+ assert password == api_key == secret+ else:+ assert len(password) == len(api_key) == 32 and password != api_key+ assert request(webui + "/webui/bootstrap", "wrong-password")[0] == 401+ status, body = request(webui + "/webui/bootstrap", password)+ assert status == 200 and json.loads(body)["token"]+ print(f"PASS {label}: default gateway only, health, WebUI, password authentication")++ # Configure a provider without making external model requests.+ saved["providers"]["custom"] = {+ "apiKey": "smoke-provider-key", "apiBase": "http://127.0.0.1:9/v1",+ }+ saved["agents"]["defaults"].update(provider="custom", model="smoke-model")+ path.write_text(json.dumps(saved))+ previous = path.read_bytes()+ for service in config["services"].values():+ service["environment"].update(+ NANOBOT_WEB_TOKEN="changed-env", NANOBOT_API_KEY="changed-env",+ )+ compose_path.write_text(json.dumps(config))+ run("up", "-d", "--force-recreate", "nanobot-gateway")+ webui = endpoint("nanobot-gateway", 8765)+ wait_for(webui + "/")+ assert path.read_bytes() == previous+ assert request(webui + "/webui/bootstrap", password)[0] == 200+ assert request(webui + "/webui/bootstrap", "changed-env")[0] == 401+ print(f"PASS {label}: recreate preserves provider settings and credentials")++ run("--profile", "api", "up", "-d")+ api = endpoint("nanobot-api", 8900)+ deadline = time.monotonic() + 60+ while True:+ try:+ status, _body = request(api + "/v1/models", api_key)+ if status == 200:+ break+ except (URLError, ConnectionError, TimeoutError):+ pass+ if time.monotonic() >= deadline:+ raise RuntimeError("Configured API did not start")+ time.sleep(1)+ assert request(api + "/v1/models")[0] == 401+ print(f"PASS {label}: opt-in API starts and requires its persisted key")+ except Exception:+ print(run("logs", "--no-color", "--tail", "80"), flush=True)+ raise+ finally:+ subprocess.run([*compose, "--profile", "api", "down", "--volumes"], check=True)+ # The non-root container owns the bind mount on Linux.+ if os.name != "nt":+ subprocess.run([+ "docker", "run", "--rm", "--entrypoint", "chown",+ "-v", f"{data}:/data", args.image,+ "-R", f"{os.getuid()}:{os.getgid()}", "/data",+ ], check=True)++ readonly = root / "readonly"+ readonly.mkdir()+ result = subprocess.run([+ "docker", "run", "--rm", "--read-only",+ "-e", "NANOBOT_DOCKER_BOOTSTRAP=1",+ "-v", f"{readonly}:/home/nanobot/.nanobot:ro", args.image, "status",+ ], capture_output=True, text=True)+ assert result.returncode == 1, result.stdout + result.stderr+ assert not (readonly / "config.json").exists()+ assert "password:" not in result.stdout+ print("PASS read-only mount: initialization fails without a partial config or success message")+++if __name__ == "__main__":+ main()diff --git a/tests/test_docker_config.py b/tests/test_docker_config.pyindex e8f30bf16..ec7309b8e 100644--- a/tests/test_docker_config.py+++ b/tests/test_docker_config.py@@ -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 sysfrom pathlib import Path-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}"---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)-+import pytest-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()+from nanobot.channels.websocket.runtime import WebSocketConfig+from nanobot.config.loader import load_config, resolve_config_env_vars- assert template["channels"]["websocket"]["tokenIssueSecret"] == WEB_TOKEN_PLACEHOLDER- assert template["api"]["api_key"] == API_KEY_PLACEHOLDER- assert "${" not in json.dumps(_baked())+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_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 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++[email protected]("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()) == []