diff --git a/backend/packages/harness/deerflow/community/aio_sandbox/remote_backend.py b/backend/packages/harness/deerflow/community/aio_sandbox/remote_backend.py index f3ae9b15b0..5ab17dddd0 100644 --- a/backend/packages/harness/deerflow/community/aio_sandbox/remote_backend.py +++ b/backend/packages/harness/deerflow/community/aio_sandbox/remote_backend.py @@ -25,6 +25,7 @@ from pathlib import PurePosixPath import requests +from deerflow.community.provider_credentials import REDACTION_MARKER, redact_secret from deerflow.constants import DEFAULT_SKILLS_CONTAINER_PATH from deerflow.integrations.lark_cli import ( PROVISIONER_CAPABILITY_REFRESH_HEADER, @@ -214,7 +215,16 @@ class RemoteSandboxBackend(SandboxBackend): request is sent. """ self._provisioner_url = provisioner_url.rstrip("/") - self._api_key = api_key + # The provisioner is a standalone service whose image carries only + # app.py, so it cannot import provider_credentials: a shared rule that + # only one side can run would compare asymmetric values. Both sides + # therefore strip this symmetric secret inline. resolve_api_key would + # also read the .env.example placeholder as unset, breaking a + # deployment that configures the same placeholder on both sides. + # A Secret mounted through envFrom keeps its trailing newline; the raw + # value would make requests refuse the header with an error that quotes + # the whole key. + self._api_key = (api_key or "").strip() self._max_shell_sessions = max_shell_sessions self._max_bash_sessions = max_bash_sessions self._required_shell_sessions = max(required_shell_sessions, max_shell_sessions or 0) @@ -228,6 +238,19 @@ class RemoteSandboxBackend(SandboxBackend): def _auth_headers(self) -> dict[str, str]: return {"X-API-Key": self._api_key} if self._api_key else {} + def _safe_error_text(self, exc: object) -> str: + """Error text with the configured key scrubbed out. + + Transport refusals quote the offending header value, and these + messages reach the error log and the model-visible tool result. The + quoted value is repr-escaped, so a key with interior control characters + appears in escaped form; scrub both spellings. + """ + text = redact_secret(exc, self._api_key) + if self._api_key: + text = text.replace(repr(self._api_key)[1:-1], REDACTION_MARKER) + return text + def _requires_shell_capacity_replacement(self, payload: dict[str, object]) -> bool: if self._required_shell_sessions == 0: return False @@ -319,7 +342,9 @@ class RemoteSandboxBackend(SandboxBackend): return None return SandboxInfo(sandbox_id, "", container_id=generation, lark_cli_broker=None) except (requests.RequestException, ValueError) as exc: - raise RuntimeError(f"Could not inspect runtime for sandbox {sandbox_id}: {exc}") from exc + # from None: the cause keeps the unredacted transport text, and + # upstream logger.exception calls print the whole chain. + raise RuntimeError(f"Could not inspect runtime for sandbox {sandbox_id}: {self._safe_error_text(exc)}") from None def discover(self, sandbox_id: str) -> SandboxInfo | None: """Discover an existing sandbox via the provisioner. @@ -372,7 +397,7 @@ class RemoteSandboxBackend(SandboxBackend): logger.info("Provisioner list_running: %d sandbox(es) found", len(infos)) return infos except requests.RequestException as exc: - logger.warning("Provisioner list_running failed: %s", exc) + logger.warning("Provisioner list_running failed: %s", self._safe_error_text(exc)) return [] def _provisioner_create( @@ -443,8 +468,8 @@ class RemoteSandboxBackend(SandboxBackend): return info except requests.RequestException as exc: self._drop_cached_lark_broker_mode_on_conflict(exc) - logger.error(f"Provisioner create failed for {sandbox_id}: {exc}") - raise RuntimeError(f"Provisioner create failed: {exc}") from exc + logger.error(f"Provisioner create failed for {sandbox_id}: {self._safe_error_text(exc)}") + raise RuntimeError(f"Provisioner create failed: {self._safe_error_text(exc)}") from None def _drop_cached_lark_broker_mode_on_conflict(self, exc: requests.RequestException) -> None: """Honor the provisioner's capability-refresh marker on create conflicts. @@ -480,7 +505,7 @@ class RemoteSandboxBackend(SandboxBackend): resp.raise_for_status() logger.info(f"Provisioner destroyed sandbox {sandbox_id}") except requests.RequestException as exc: - raise RuntimeError(f"Provisioner destroy failed for {sandbox_id}: {exc}") from exc + raise RuntimeError(f"Provisioner destroy failed for {sandbox_id}: {self._safe_error_text(exc)}") from None def _provisioner_is_alive(self, sandbox_id: str) -> bool: """GET /api/sandboxes/{sandbox_id} → check Pod phase.""" @@ -491,12 +516,15 @@ class RemoteSandboxBackend(SandboxBackend): timeout=10, ) except requests.RequestException as exc: - raise RuntimeError(f"Provisioner health check failed for {sandbox_id}: {exc}") from exc + raise RuntimeError(f"Provisioner health check failed for {sandbox_id}: {self._safe_error_text(exc)}") from None if resp.status_code == 404: return False if not resp.ok: - raise RuntimeError(f"Provisioner health check failed for {sandbox_id}: HTTP {resp.status_code} {resp.text}") + # The upstream body can echo request headers or proxy diagnostics, + # and this error is logged by _check_tracked_sandbox_alive; report + # the operation and status without copying it. + raise RuntimeError(f"Provisioner health check failed for {sandbox_id}: HTTP {resp.status_code}") data = resp.json() return data.get("status") == "Running" @@ -515,5 +543,5 @@ class RemoteSandboxBackend(SandboxBackend): data = resp.json() return self._sandbox_info(data, sandbox_id) except requests.RequestException as exc: - logger.debug(f"Provisioner discover failed for {sandbox_id}: {exc}") + logger.debug(f"Provisioner discover failed for {sandbox_id}: {self._safe_error_text(exc)}") return None diff --git a/backend/packages/harness/deerflow/config/sandbox_config.py b/backend/packages/harness/deerflow/config/sandbox_config.py index baeb46b750..11bc5db5ba 100644 --- a/backend/packages/harness/deerflow/config/sandbox_config.py +++ b/backend/packages/harness/deerflow/config/sandbox_config.py @@ -452,8 +452,10 @@ class SandboxConfig(BaseModel): description=( "API key sent as X-API-Key header to the provisioner service. " "Must match PROVISIONER_API_KEY on the provisioner container. " - "Both sides must be set to the same value; " - "the provisioner rejects all /api/* requests when the key is unset or mismatched." + "Both sides must be set to the same value; surrounding whitespace is " + "stripped on each side before comparing, so a Secret-mounted key with " + "a trailing newline still authenticates. " + "The provisioner rejects all /api/* requests when the key is unset or mismatched." ), ) diff --git a/backend/tests/test_provisioner_request_threading.py b/backend/tests/test_provisioner_request_threading.py index b27aaafb02..d4342832e9 100644 --- a/backend/tests/test_provisioner_request_threading.py +++ b/backend/tests/test_provisioner_request_threading.py @@ -929,3 +929,41 @@ async def test_auth_middleware_unset_key(monkeypatch: pytest.MonkeyPatch, provis r = await client.get("/api/sandboxes", headers={"X-API-Key": "anything"}) assert r.status_code == 401 + + +@pytest.mark.asyncio +async def test_auth_middleware_strips_configured_key(monkeypatch: pytest.MonkeyPatch, provisioner_module) -> None: + """A Secret mounted through envFrom keeps its trailing newline; the clean key must still authenticate.""" + monkeypatch.setattr(provisioner_module, "PROVISIONER_API_KEY", "test-secret\r\n") + fake_core_v1 = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", fake_core_v1) + + transport = httpx.ASGITransport(app=provisioner_module.app) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: + r = await client.get("/api/sandboxes", headers={"X-API-Key": "test-secret"}) + assert r.status_code != 401 + + # Stripping must not turn the comparison into a prefix or substring match. + r = await client.get("/api/sandboxes", headers={"X-API-Key": "test-secret\r\n"}) + assert r.status_code == 401 + r = await client.get("/api/sandboxes", headers={"X-API-Key": "wrong-key"}) + assert r.status_code == 401 + + +@pytest.mark.asyncio +async def test_auth_middleware_whitespace_only_key_stays_unset(monkeypatch: pytest.MonkeyPatch, provisioner_module) -> None: + """A whitespace-only PROVISIONER_API_KEY reads as unset: every /api/* route stays 401.""" + monkeypatch.setattr(provisioner_module, "PROVISIONER_API_KEY", " \r\n") + fake_core_v1 = _RecordingCoreV1(event_loop_thread_id=-1) + monkeypatch.setattr(provisioner_module, "core_v1", fake_core_v1) + + transport = httpx.ASGITransport(app=provisioner_module.app) + async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client: + r = await client.get("/health") + assert r.status_code == 200 + + r = await client.get("/api/sandboxes") + assert r.status_code == 401 + + r = await client.get("/api/sandboxes", headers={"X-API-Key": "anything"}) + assert r.status_code == 401 diff --git a/backend/tests/test_remote_sandbox_backend.py b/backend/tests/test_remote_sandbox_backend.py index 309160fd1b..625b9b360f 100644 --- a/backend/tests/test_remote_sandbox_backend.py +++ b/backend/tests/test_remote_sandbox_backend.py @@ -1,6 +1,10 @@ from __future__ import annotations +import logging import time +import traceback +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from threading import Thread from unittest.mock import Mock import pytest @@ -230,6 +234,212 @@ def test_provisioner_list_sends_auth_header_when_api_key_set(monkeypatch): assert captured[0]["headers"] == {"X-API-Key": "secret"} +def test_provisioner_list_sends_stripped_key_when_configured_key_has_whitespace(monkeypatch): + # A Secret mounted through envFrom keeps its trailing newline; the raw + # value would make requests refuse the header before anything is sent. + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret\r\n") + captured: list[dict] = [] + + def mock_get(url: str, timeout: int, headers=None): + captured.append({"headers": headers}) + return _StubResponse(payload={"sandboxes": []}) + + monkeypatch.setattr(requests, "get", mock_get) + + backend._provisioner_list() + assert captured[0]["headers"] == {"X-API-Key": "secret"} + + +def test_provisioner_list_sends_no_header_for_whitespace_only_key(monkeypatch): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key=" \r\n") + captured: list[dict] = [] + + def mock_get(url: str, timeout: int, headers=None): + captured.append({"headers": headers}) + return _StubResponse(payload={"sandboxes": []}) + + monkeypatch.setattr(requests, "get", mock_get) + + backend._provisioner_list() + assert captured[0]["headers"] == {} + + +def test_provisioner_list_redacts_key_from_transport_refusal(monkeypatch, caplog): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'secret\\r\\n'") + + def mock_get(url: str, timeout: int, headers=None): + raise refusal + + monkeypatch.setattr(requests, "get", mock_get) + + with caplog.at_level(logging.WARNING): + assert backend._provisioner_list() == [] + assert "secret" not in caplog.text + assert "[REDACTED]" in caplog.text + + +def test_create_failure_redacts_key_from_error_and_log(monkeypatch, caplog): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + monkeypatch.setattr(remote_backend_mod, "user_should_see_legacy_skills", lambda _user_id: False) + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'secret\\r\\n'") + + def mock_post(url: str, json=None, timeout: int = 0, headers=None): + raise refusal + + monkeypatch.setattr(requests, "post", mock_post) + + with caplog.at_level(logging.ERROR): + with pytest.raises(RuntimeError, match="Provisioner create failed") as excinfo: + backend.create("thread-1", "abc123", user_id="user-1") + assert "secret" not in str(excinfo.value) + assert "[REDACTED]" in str(excinfo.value) + assert "secret" not in caplog.text + + +def test_inspect_runtime_failure_redacts_key_from_error(monkeypatch): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'secret\\r\\n'") + + def mock_get(url: str, timeout: int, headers=None): + raise refusal + + monkeypatch.setattr(requests, "get", mock_get) + + with pytest.raises(RuntimeError, match="Could not inspect runtime") as excinfo: + backend.inspect_runtime("abc123") + assert "secret" not in str(excinfo.value) + assert "[REDACTED]" in str(excinfo.value) + + +def test_transport_refusal_chain_never_carries_the_key(monkeypatch): + # Upstream logger.exception / exc_info=True callers print the whole cause + # chain; the unredacted transport exception must not survive in it. + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'secret\\r\\n'") + + def mock_get(url: str, timeout: int, headers=None): + raise refusal + + monkeypatch.setattr(requests, "get", mock_get) + + with pytest.raises(RuntimeError) as excinfo: + backend.inspect_runtime("abc123") + rendered = "".join(traceback.format_exception(type(excinfo.value), excinfo.value, excinfo.value.__traceback__)) + assert "secret" not in rendered + assert "[REDACTED]" in rendered + + +def test_redaction_scrubs_repr_escaped_interior_whitespace(monkeypatch): + # A multi-line Secret value keeps interior newlines after strip; the + # transport quotes it repr-escaped, so the raw substring never matches. + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="sec\nret") + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'sec\\nret'") + + def mock_get(url: str, timeout: int, headers=None): + raise refusal + + monkeypatch.setattr(requests, "get", mock_get) + + with pytest.raises(RuntimeError) as excinfo: + backend.inspect_runtime("abc123") + message = str(excinfo.value) + assert "sec\\nret" not in message + assert "sec\nret" not in message + assert "[REDACTED]" in message + + +def test_destroy_failure_redacts_key_from_error(monkeypatch): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'secret\\r\\n'") + + def mock_delete(url: str, timeout: int, headers=None): + raise refusal + + monkeypatch.setattr(requests, "delete", mock_delete) + + with pytest.raises(RuntimeError, match="Provisioner destroy failed") as excinfo: + backend.destroy(SandboxInfo(sandbox_id="abc123", sandbox_url="http://k3s:31001")) + assert "secret" not in str(excinfo.value) + assert "[REDACTED]" in str(excinfo.value) + + +def test_health_check_failure_redacts_key_from_error(monkeypatch): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'secret\\r\\n'") + + def mock_get(url: str, timeout: int, headers=None): + raise refusal + + monkeypatch.setattr(requests, "get", mock_get) + + with pytest.raises(RuntimeError, match="Provisioner health check failed") as excinfo: + backend.is_alive(SandboxInfo(sandbox_id="abc123", sandbox_url="http://k3s:31001")) + assert "secret" not in str(excinfo.value) + assert "[REDACTED]" in str(excinfo.value) + + +def test_discover_failure_redacts_key_from_log(monkeypatch, caplog): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + refusal = requests.exceptions.InvalidHeader("Invalid leading whitespace, reserved character(s), or return character(s) in header value: 'secret\\r\\n'") + + def mock_get(url: str, timeout: int, headers=None): + raise refusal + + monkeypatch.setattr(requests, "get", mock_get) + + with caplog.at_level(logging.DEBUG, logger="deerflow.community.aio_sandbox.remote_backend"): + assert backend.discover("abc123") is None + assert "secret" not in caplog.text + assert "[REDACTED]" in caplog.text + + +def test_none_api_key_reads_as_unconfigured(monkeypatch): + backend = RemoteSandboxBackend("http://provisioner:8002", api_key=None) + captured: list[dict] = [] + + def mock_get(url: str, timeout: int, headers=None): + captured.append({"headers": headers}) + return _StubResponse(payload={"sandboxes": []}) + + monkeypatch.setattr(requests, "get", mock_get) + + backend._provisioner_list() + assert captured[0]["headers"] == {} + + +def test_stripped_key_survives_real_transport_header_validation(): + # The transport's own header validation stays in the loop: requests must + # accept the header and the server must receive the stripped key. + key = "sk-provisioner-test-4f7c2a91" + received: list[dict[str, str]] = [] + + class Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + received.append({name.lower(): value for name, value in self.headers.items()}) + body = b'{"sandboxes": []}' + self.send_response(200) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args) -> None: + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + backend = RemoteSandboxBackend(f"http://127.0.0.1:{server.server_port}", api_key=f"{key}\r\n") + assert backend.list_running() == [] + finally: + server.shutdown() + server.server_close() + thread.join() + assert received and received[0]["x-api-key"] == key + + def test_provisioner_list_returns_empty_on_request_exception(monkeypatch): backend = RemoteSandboxBackend("http://provisioner:8002") @@ -706,17 +916,22 @@ def test_provisioner_is_alive_raises_on_request_exception(monkeypatch): backend._provisioner_is_alive("abc123") -def test_provisioner_is_alive_raises_on_server_error(monkeypatch): - backend = RemoteSandboxBackend("http://provisioner:8002") +def test_provisioner_is_alive_raises_on_server_error_without_upstream_body(monkeypatch): + # _check_tracked_sandbox_alive logs this error, so an upstream body that + # echoes headers or proxy diagnostics would bypass the transport redaction. + backend = RemoteSandboxBackend("http://provisioner:8002", api_key="secret") + upstream_body = "unavailable; X-API-Key: secret" def mock_get(url: str, timeout: int, headers=None): response = _StubResponse(status_code=503) - response.text = "unavailable" + response.text = upstream_body return response monkeypatch.setattr(requests, "get", mock_get) - with pytest.raises(RuntimeError, match="HTTP 503 unavailable"): + with pytest.raises(RuntimeError, match="Provisioner health check failed for abc123: HTTP 503") as excinfo: backend._provisioner_is_alive("abc123") + assert upstream_body not in str(excinfo.value) + assert "secret" not in str(excinfo.value) def test_discover_delegates_to_provisioner_discover(monkeypatch): diff --git a/config.example.yaml b/config.example.yaml index b86eb7eb68..1427bab5ff 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -2004,7 +2004,9 @@ sandbox: # provisioner_url: http://provisioner:8002 # # API key for provisioner authentication. Must match PROVISIONER_API_KEY # # set on the provisioner container. Both sides must have the same value set; -# # the provisioner rejects all /api/* requests when PROVISIONER_API_KEY is unset. +# # surrounding whitespace is stripped on each side before comparing (a +# # Secret-mounted key with a trailing newline still authenticates). +# # The provisioner rejects all /api/* requests when PROVISIONER_API_KEY is unset. # # Generate a strong key: openssl rand -hex 32 # # provisioner_api_key: $PROVISIONER_API_KEY # # Note: provisioner-created Pods use the provisioner's SANDBOX_IMAGE diff --git a/deploy/helm/deer-flow/README.md b/deploy/helm/deer-flow/README.md index f1187ab61e..de9da56c2a 100644 --- a/deploy/helm/deer-flow/README.md +++ b/deploy/helm/deer-flow/README.md @@ -397,7 +397,10 @@ kubectl -n deer-flow exec deploy/deer-flow-provisioner -- curl -s localhost:8002 `PROVISIONER_API_KEY`: the provisioner's `verify_api_key` middleware answers 401 to every `/api/*` request while its key is empty or differs from the one the gateway sends, so a deployment without it cannot create a - single sandbox. The chart injects the same Secret value into both Pods and + single sandbox. Each side strips surrounding whitespace from its + configured value before comparing, so a key that arrives with a trailing + newline (for example from `kubectl create secret --from-file`) still + authenticates. The chart injects the same Secret value into both Pods and the default `config` references it as `sandbox.provisioner_api_key: $PROVISIONER_API_KEY` (keep that line when you override `config:`; the harness refuses to start when a referenced variable is unset). With diff --git a/docker/provisioner/app.py b/docker/provisioner/app.py index a541276cf6..7cae4aa45b 100644 --- a/docker/provisioner/app.py +++ b/docker/provisioner/app.py @@ -581,7 +581,10 @@ async def verify_api_key(request: Request, call_next): # Compare bytes: compare_digest raises TypeError for non-ASCII str, # and header values are client-controlled (decoded as latin-1). key = request.headers.get("X-API-Key", "").encode("utf-8", "surrogatepass") - if not PROVISIONER_API_KEY or not secrets.compare_digest(key, PROVISIONER_API_KEY.encode("utf-8", "surrogatepass")): + # A Secret mounted through envFrom keeps its trailing newline; strip + # it so the shared secret compares equal to the Gateway's stripped key. + configured = PROVISIONER_API_KEY.strip() + if not configured or not secrets.compare_digest(key, configured.encode("utf-8", "surrogatepass")): logger.warning("provisioner auth rejected: %s %s", request.method, request.url.path) return Response(status_code=401, content="Unauthorized") return await call_next(request) diff --git a/docs/guide/deployment.md b/docs/guide/deployment.md index 05d7558458..e822487b67 100644 --- a/docs/guide/deployment.md +++ b/docs/guide/deployment.md @@ -29,6 +29,7 @@ make docker-logs # View logs ``` `make docker-start` starts `provisioner` only when `config.yaml` uses provisioner mode (`sandbox.use: deerflow.community.aio_sandbox:AioSandboxProvider` with `provisioner_url`). Direct Compose users can add `--profile provisioner` to the dev command for the same mode; the default stack does not require Kubernetes. +The Gateway and the provisioner compare `PROVISIONER_API_KEY` after stripping surrounding whitespace from the configured value on each side, so a key that arrives with a trailing newline (for example from a Kubernetes Secret created with `kubectl create secret --from-file`) still authenticates; see the [Helm architecture notes](../../deploy/helm/deer-flow/README.md#architecture-notes). With `USERDATA_PVC_NAME`, sandbox data, extra mounts and Lark broker credentials share one `user-data` volume with separate `subPath` mounts, avoiding duplicate references to the same claim on NFS CSI drivers. Docker builds use the upstream `uv` registry by default. The gateway image installs with `uv sync --locked`, and `uv.lock` pins `https://pypi.org/simple`, so `UV_INDEX_URL` has to keep that value: exporting a mirror such as `https://pypi.tuna.tsinghua.edu.cn/simple` fails the build with ``The lockfile at `uv.lock` needs to be updated, but `--locked` was provided`` (reproduce in an already-synced environment with `cd backend && UV_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple uv sync --locked --check`; if the environment itself is stale, `--check` reports that instead for either index, so use `uv lock --check` to see it without syncing). Installing from a mirror requires regenerating the lock or dropping `--locked`, and both change what the image installs, so keep the default index for a checkout you intend to contribute back. `NPM_REGISTRY=https://registry.npmmirror.com` is independent of this: it applies to the frontend image's `pnpm` install and to the gateway image's Lark CLI install (`@larksuite/cli`, which `backend/Dockerfile` installs with npm).