Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-agent): require a token for the approval server (#5503)

Francesco Bonacci77b1f6047705
diff --git a/blog/human-in-the-loop.md b/blog/human-in-the-loop.md
index c9fe3451d0..b6b624705e 100644
--- a/blog/human-in-the-loop.md
+++ b/blog/human-in-the-loop.md
@@ -34,11 +34,15 @@ This approach bridges the gap between fully automated systems and pure manual co
Launch the human agent interface:
```bash
-python -m agent.human_tool
+python -m cua_agent.human_tool
```
The web UI will show pending completions. Click any completion to take control of the agent and see exactly what it sees.
+The server only accepts connections from your own machine, and it protects every request with a random token. It saves the token to `~/.cua/human_tool/token`, so the agent and the web page on the same machine find it on their own. The web page asks for a password the first time you open it: enter the contents of that file.
+
+To use it from another machine, start the server with `--host 0.0.0.0` and set `CUA_HUMAN_TOOL_TOKEN` to the same secret on both sides. Only do this on a network you trust.
+
## Usage Examples
### Direct Human Control
diff --git a/libs/python/agent/cua_agent/adapters/human_adapter.py b/libs/python/agent/cua_agent/adapters/human_adapter.py
index e5452acd46..4fe9ed0b6e 100644
--- a/libs/python/agent/cua_agent/adapters/human_adapter.py
+++ b/libs/python/agent/cua_agent/adapters/human_adapter.py
@@ -7,6 +7,8 @@ from litellm import acompletion, completion
from litellm.llms.custom_llm import CustomLLM
from litellm.types.utils import GenericStreamingChunk, ModelResponse
+from ..human_auth import auth_headers
+
class HumanAdapter(CustomLLM):
"""Human Adapter for human-in-the-loop completions.
@@ -15,22 +17,36 @@ class HumanAdapter(CustomLLM):
where humans can review and respond to AI requests.
"""
- def __init__(self, base_url: str | None = None, timeout: float = 300.0, **kwargs):
+ def __init__(
+ self,
+ base_url: str | None = None,
+ timeout: float = 300.0,
+ token: str | None = None,
+ **kwargs,
+ ):
"""Initialize the human adapter.
Args:
base_url: Base URL for the human completion server.
Defaults to HUMAN_BASE_URL environment variable or http://localhost:8002
timeout: Timeout in seconds for waiting for human response
+ token: Bearer token for the server. Defaults to the
+ CUA_HUMAN_TOOL_TOKEN environment variable, then the token file the
+ server writes on this machine (~/.cua/human_tool/token)
**kwargs: Additional arguments
"""
super().__init__()
self.base_url = base_url or os.getenv("HUMAN_BASE_URL", "http://localhost:8002")
self.timeout = timeout
+ self.token = token
# Ensure base_url doesn't end with slash
self.base_url = self.base_url.rstrip("/")
+ def _headers(self) -> Dict[str, str]:
+ """Bearer token header, read fresh so a restarted server's new token is picked up."""
+ return auth_headers(self.token)
+
def _queue_completion(self, messages: List[Dict[str, Any]], model: str) -> str:
"""Queue a completion request and return the call ID.
@@ -46,8 +62,17 @@ class HumanAdapter(CustomLLM):
"""
try:
response = requests.post(
- f"{self.base_url}/queue", json={"messages": messages, "model": model}, timeout=10
+ f"{self.base_url}/queue",
+ json={"messages": messages, "model": model},
+ headers=self._headers(),
+ timeout=10,
)
+ if response.status_code == 401:
+ raise Exception(
+ "The human tool server rejected the token. Set CUA_HUMAN_TOOL_TOKEN to "
+ "the server's token, or run the server on this machine so the token "
+ "file can be read."
+ )
response.raise_for_status()
return response.json()["id"]
except requests.RequestException as e:
@@ -73,7 +98,9 @@ class HumanAdapter(CustomLLM):
while True:
try:
# Check status
- status_response = requests.get(f"{self.base_url}/status/{call_id}")
+ status_response = requests.get(
+ f"{self.base_url}/status/{call_id}", headers=self._headers()
+ )
status_response.raise_for_status()
status_data = status_response.json()
@@ -122,7 +149,7 @@ class HumanAdapter(CustomLLM):
start_time = time.time()
- async with aiohttp.ClientSession() as session:
+ async with aiohttp.ClientSession(headers=self._headers()) as session:
while True:
try:
# Check status
diff --git a/libs/python/agent/cua_agent/human_auth.py b/libs/python/agent/cua_agent/human_auth.py
new file mode 100644
index 0000000000..675ae072ee
--- /dev/null
+++ b/libs/python/agent/cua_agent/human_auth.py
@@ -0,0 +1,138 @@
+"""Shared-secret authentication and bind-address helpers for the human tool.
+
+Stdlib only, so the adapter can use it without the server or UI extras.
+
+The human tool decides whether an agent may go ahead with an action, so only
+the person running it (and the agent they start) may talk to it. Every API
+route needs ``Authorization: Bearer <token>``.
+
+Where the token comes from:
+
+* ``CUA_HUMAN_TOOL_TOKEN`` if it is set. Use this to share the token with a
+ client on another machine, or to pick your own.
+* Otherwise the server makes a random token each time it starts and writes it
+ to ``$CUA_HOME/human_tool/token`` (default ``~/.cua/human_tool/token``) with
+ owner-only permissions. The adapter and the Gradio UI on the same machine
+ read that file, so nothing needs to be configured.
+
+The server listens on 127.0.0.1 unless you pass ``--host`` or set
+``CUA_HUMAN_TOOL_HOST``.
+"""
+
+import hmac
+import os
+import secrets
+import sys
+from pathlib import Path
+from typing import Callable, Optional
+
+TOKEN_ENV = "CUA_HUMAN_TOOL_TOKEN"
+HOST_ENV = "CUA_HUMAN_TOOL_HOST"
+DEFAULT_HOST = "127.0.0.1"
+
+# Token generated by this process, cached so every request sees the same one.
+_generated_token: Optional[str] = None
+
+
+def token_file() -> Path:
+ """Where a generated token is stored (``$CUA_HOME`` else ``~/.cua``)."""
+ base = os.environ.get("CUA_HOME") or ""
+ root = Path(base) if base else Path.home() / ".cua"
+ return root / "human_tool" / "token"
+
+
+def resolve_host(host: Optional[str] = None) -> str:
+ """Address to listen on: explicit value, else ``CUA_HUMAN_TOOL_HOST``, else loopback."""
+ return host or os.environ.get(HOST_ENV) or DEFAULT_HOST
+
+
+def is_loopback(host: str) -> bool:
+ return host in ("127.0.0.1", "localhost", "::1")
+
+
+def _write_private(path: Path, value: str) -> None:
+ """Write ``value`` to ``path`` readable by the current user only."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ os.chmod(path.parent, 0o700)
+ except OSError:
+ pass
+ # Drop any older file first so the new one is created with 0600 from the start.
+ try:
+ path.unlink()
+ except FileNotFoundError:
+ pass
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(fd, "w") as fh:
+ fh.write(value)
+
+
+def server_token() -> str:
+ """Token the server expects. Generates and stores one the first time if needed."""
+ global _generated_token
+ env_token = os.environ.get(TOKEN_ENV)
+ if env_token:
+ return env_token
+ if _generated_token is None:
+ token = secrets.token_urlsafe(32)
+ _write_private(token_file(), token)
+ _generated_token = token
+ return _generated_token
+
+
+def client_token(explicit: Optional[str] = None) -> Optional[str]:
+ """Token a client should send: explicit value, else env var, else the token file."""
+ if explicit:
+ return explicit
+ env_token = os.environ.get(TOKEN_ENV)
+ if env_token:
+ return env_token
+ try:
+ return token_file().read_text().strip() or None
+ except OSError:
+ return None
+
+
+def auth_headers(explicit: Optional[str] = None) -> dict:
+ """Headers carrying the bearer token, or an empty dict if none is known."""
+ token = client_token(explicit)
+ return {"Authorization": f"Bearer {token}"} if token else {}
+
+
+def token_matches(candidate: Optional[str], expected: str) -> bool:
+ """Constant-time comparison."""
+ if not candidate:
+ return False
+ return hmac.compare_digest(candidate.encode("utf-8"), expected.encode("utf-8"))
+
+
+def gradio_auth(get_token: Callable[[], Optional[str]]):
+ """Login check for the Gradio page: any username, the token as the password.
+
+ Without it, anyone who can open the page could answer approvals, because
+ the page calls the API with the token itself.
+ """
+
+ def check(username: str, password: str) -> bool:
+ token = get_token()
+ return bool(token) and token_matches(password, token)
+
+ return check
+
+
+def announce(host: str, port: int) -> None:
+ """Tell the operator where the token lives (never the token itself)."""
+ if os.environ.get(TOKEN_ENV):
+ print(f"Auth: using the token from ${TOKEN_ENV}", file=sys.stderr)
+ else:
+ print(f"Auth: token saved to {token_file()}", file=sys.stderr)
+ print(
+ f" to use a client on another machine, set ${TOKEN_ENV} on both sides",
+ file=sys.stderr,
+ )
+ if not is_loopback(host):
+ print(
+ f"WARNING: listening on {host}:{port}, reachable from other machines. "
+ "Anyone with the token can approve agent actions.",
+ file=sys.stderr,
+ )
diff --git a/libs/python/agent/cua_agent/human_tool/__init__.py b/libs/python/agent/cua_agent/human_tool/__init__.py
index 9006433226..cb7d0632b8 100644
--- a/libs/python/agent/cua_agent/human_tool/__init__.py
+++ b/libs/python/agent/cua_agent/human_tool/__init__.py
@@ -11,11 +11,22 @@ Components:
Usage:
# Run the server and UI
- python -m agent.human_tool
+ python -m cua_agent.human_tool
# Or run components separately
- python -m agent.human_tool.server # API server only
- python -m agent.human_tool.ui # UI only
+ python -m cua_agent.human_tool.server # API server only
+ python -m cua_agent.human_tool.ui # UI only
+
+Security:
+ The server listens on 127.0.0.1 only. To accept connections from other
+ machines pass ``--host 0.0.0.0`` (or set CUA_HUMAN_TOOL_HOST).
+
+ Every API route needs ``Authorization: Bearer <token>``, and the web page
+ asks for the same token as its password. The server makes a random token
+ at each start and saves it to ~/.cua/human_tool/token (owner-only), where
+ the agent adapter and UI on the same machine pick it up automatically.
+ To use a client on another machine, set CUA_HUMAN_TOOL_TOKEN to the same
+ value on both sides.
"""
from .server import CompletionQueue, completion_queue
diff --git a/libs/python/agent/cua_agent/human_tool/__main__.py b/libs/python/agent/cua_agent/human_tool/__main__.py
index bca0b3f2dd..9cca152142 100644
--- a/libs/python/agent/cua_agent/human_tool/__main__.py
+++ b/libs/python/agent/cua_agent/human_tool/__main__.py
@@ -4,20 +4,33 @@ Human-in-the-Loop Completion Server and UI
This module combines the FastAPI server for handling completion requests
with a Gradio UI for human interaction.
+
+The server listens on 127.0.0.1 by default and every API route needs a bearer
+token (see ``auth.py``). The web page asks for the same token as its password.
"""
+import argparse
+from typing import List, Optional
+
import gradio as gr
-from fastapi import FastAPI
+from ..human_auth import announce, gradio_auth, resolve_host, server_token
from .server import app as fastapi_app
from .ui import create_ui
+DEFAULT_PORT = 8002
+
# Create the Gradio demo
gradio_demo = create_ui()
-# Mount Gradio on FastAPI
+# Mount Gradio on FastAPI. The page asks for the server token as its password.
CUSTOM_PATH = "/gradio"
-app = gr.mount_gradio_app(fastapi_app, gradio_demo, path=CUSTOM_PATH)
+app = gr.mount_gradio_app(
+ fastapi_app,
+ gradio_demo,
+ path=CUSTOM_PATH,
+ auth=gradio_auth(server_token),
+)
# Add a redirect from root to Gradio UI
@@ -31,12 +44,29 @@ async def redirect_to_ui():
}
-if __name__ == "__main__":
+def main(argv: Optional[List[str]] = None) -> None:
import uvicorn
+ parser = argparse.ArgumentParser(description="Human-in-the-loop server and UI")
+ parser.add_argument(
+ "--host",
+ default=None,
+ help="Address to listen on (default: 127.0.0.1, or $CUA_HUMAN_TOOL_HOST). "
+ "Use 0.0.0.0 to allow other machines to connect.",
+ )
+ args = parser.parse_args(argv)
+
+ host = resolve_host(args.host)
+ server_token() # create the token (and its file) before accepting requests
+
print("πŸš€ Starting Human-in-the-Loop Completion Server...")
- print("πŸ“Š API Server: http://localhost:8002")
- print("🎨 Gradio UI: http://localhost:8002/gradio")
- print("πŸ“š API Docs: http://localhost:8002/docs")
+ print(f"πŸ“Š API Server: http://{host}:{DEFAULT_PORT}")
+ print(f"🎨 Gradio UI: http://{host}:{DEFAULT_PORT}{CUSTOM_PATH} (password: the token)")
+ print(f"πŸ“š API Docs: http://{host}:{DEFAULT_PORT}/docs")
+ announce(host, DEFAULT_PORT)
+
+ uvicorn.run(app, host=host, port=DEFAULT_PORT)
- uvicorn.run(app, host="0.0.0.0", port=8002)
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/python/agent/cua_agent/human_tool/server.py b/libs/python/agent/cua_agent/human_tool/server.py
index 8c67f95a5d..375b293976 100644
--- a/libs/python/agent/cua_agent/human_tool/server.py
+++ b/libs/python/agent/cua_agent/human_tool/server.py
@@ -5,9 +5,11 @@ from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional
-from fastapi import FastAPI, HTTPException
+from fastapi import APIRouter, Depends, FastAPI, HTTPException, Request
from pydantic import BaseModel
+from ..human_auth import announce, resolve_host, server_token, token_matches
+
class CompletionStatus(str, Enum):
PENDING = "pending"
@@ -183,25 +185,38 @@ class CompletionQueue:
# Global queue instance
completion_queue = CompletionQueue()
-# FastAPI app
+
+async def require_token(request: Request) -> None:
+ """Reject requests that do not carry the correct ``Authorization: Bearer`` token."""
+ scheme, _, supplied = request.headers.get("authorization", "").partition(" ")
+ if scheme.lower() != "bearer" or not token_matches(supplied.strip(), server_token()):
+ raise HTTPException(
+ status_code=401,
+ detail="Missing or invalid token",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+
+# FastAPI app. Every API route sits on a router that requires the bearer token.
app = FastAPI(title="Human Completion Server", version="1.0.0")
+router = APIRouter(dependencies=[Depends(require_token)])
[email protected]("/queue", response_model=Dict[str, str])
[email protected]("/queue", response_model=Dict[str, str])
async def queue_completion(request: CompletionRequest):
"""Add a completion request to the queue."""
call_id = await completion_queue.add_completion(request.messages, request.model)
return {"id": call_id, "status": "queued"}
[email protected]("/pending")
[email protected]("/pending")
async def list_pending():
"""List all pending completion calls."""
pending_calls = await completion_queue.get_pending_calls()
return {"pending_calls": pending_calls}
[email protected]("/status/{call_id}")
[email protected]("/status/{call_id}")
async def get_status(call_id: str):
"""Get the status of a specific completion call."""
status = await completion_queue.get_call_status(call_id)
@@ -210,7 +225,7 @@ async def get_status(call_id: str):
return status
[email protected]("/complete/{call_id}")
[email protected]("/complete/{call_id}")
async def complete_call(call_id: str, response: CompletionResponse):
"""Complete a call with a human response."""
success = await completion_queue.complete_call(
@@ -222,7 +237,7 @@ async def complete_call(call_id: str, response: CompletionResponse):
raise HTTPException(status_code=404, detail="Call not found or already completed")
[email protected]("/fail/{call_id}")
[email protected]("/fail/{call_id}")
async def fail_call(call_id: str, error: Dict[str, str]):
"""Mark a call as failed."""
success = await completion_queue.fail_call(call_id, error.get("error", "Unknown error"))
@@ -233,13 +248,37 @@ async def fail_call(call_id: str, error: Dict[str, str]):
return {"status": "failed"}
+app.include_router(router)
+
+
@app.get("/")
async def root():
"""Root endpoint."""
return {"message": "Human Completion Server is running"}
-if __name__ == "__main__":
+PORT = 8002
+
+
+def main(argv: Optional[List[str]] = None) -> None:
+ """Run the API server (no UI). Listens on 127.0.0.1 unless --host is given."""
+ import argparse
+
import uvicorn
- uvicorn.run(app, host="0.0.0.0", port=8002)
+ parser = argparse.ArgumentParser(description="Human completion server")
+ parser.add_argument(
+ "--host",
+ default=None,
+ help="Address to listen on (default: 127.0.0.1, or $CUA_HUMAN_TOOL_HOST)",
+ )
+ args = parser.parse_args(argv)
+
+ host = resolve_host(args.host)
+ server_token() # create the token (and its file) before accepting requests
+ announce(host, PORT)
+ uvicorn.run(app, host=host, port=PORT)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/python/agent/cua_agent/human_tool/ui.py b/libs/python/agent/cua_agent/human_tool/ui.py
index e7d0b7605d..4a3d6bc87f 100644
--- a/libs/python/agent/cua_agent/human_tool/ui.py
+++ b/libs/python/agent/cua_agent/human_tool/ui.py
@@ -9,10 +9,19 @@ import gradio as gr
import requests
from PIL import Image
+from ..human_auth import (
+ auth_headers,
+ client_token,
+ gradio_auth,
+ is_loopback,
+ resolve_host,
+)
+
class HumanCompletionUI:
- def __init__(self, server_url: str = "http://localhost:8002"):
+ def __init__(self, server_url: str = "http://localhost:8002", token: Optional[str] = None):
self.server_url = server_url
+ self.token = token # else $CUA_HUMAN_TOOL_TOKEN, else the saved token file
self.current_call_id: Optional[str] = None
self.refresh_interval = 2.0 # seconds
self.last_image = None # Store the last image for display
@@ -107,12 +116,20 @@ class HumanCompletionUI:
return formatted
+ def _headers(self) -> Dict[str, str]:
+ """Bearer token header, read fresh so a restarted server's new token is picked up."""
+ return auth_headers(self.token)
+
def get_pending_calls(self) -> List[Dict[str, Any]]:
"""Get pending calls from the server."""
try:
- response = requests.get(f"{self.server_url}/pending", timeout=5)
+ response = requests.get(
+ f"{self.server_url}/pending", headers=self._headers(), timeout=5
+ )
if response.status_code == 200:
return response.json().get("pending_calls", [])
+ if response.status_code == 401:
+ print("Error fetching pending calls: the server rejected the token")
except Exception as e:
print(f"Error fetching pending calls: {e}")
return []
@@ -122,7 +139,10 @@ class HumanCompletionUI:
try:
response_data = {"response": response}
response_obj = requests.post(
- f"{self.server_url}/complete/{call_id}", json=response_data, timeout=10
+ f"{self.server_url}/complete/{call_id}",
+ json=response_data,
+ headers=self._headers(),
+ timeout=10,
)
response_obj.raise_for_status()
return True
@@ -135,7 +155,10 @@ class HumanCompletionUI:
try:
response_data = {"tool_calls": tool_calls}
response_obj = requests.post(
- f"{self.server_url}/complete/{call_id}", json=response_data, timeout=10
+ f"{self.server_url}/complete/{call_id}",
+ json=response_data,
+ headers=self._headers(),
+ timeout=10,
)
response_obj.raise_for_status()
return True
@@ -158,7 +181,10 @@ class HumanCompletionUI:
response_data["tool_calls"] = tool_calls
response_obj = requests.post(
- f"{self.server_url}/complete/{call_id}", json=response_data, timeout=10
+ f"{self.server_url}/complete/{call_id}",
+ json=response_data,
+ headers=self._headers(),
+ timeout=10,
)
response_obj.raise_for_status()
return True
@@ -426,9 +452,9 @@ class HumanCompletionUI:
return self.refresh_pending_calls()
-def create_ui():
+def create_ui(server_url: str = "http://localhost:8002", token: Optional[str] = None):
"""Create the Gradio interface."""
- ui_handler = HumanCompletionUI()
+ ui_handler = HumanCompletionUI(server_url=server_url, token=token)
with gr.Blocks(title="Human-in-the-Loop Agent Tool", fill_width=True) as demo:
gr.Markdown("# πŸ€– Human-in-the-Loop Agent Tool")
@@ -745,7 +771,26 @@ def create_ui():
return demo
-if __name__ == "__main__":
+def main(argv: Optional[List[str]] = None) -> None:
+ """Run the UI on its own. Listens on 127.0.0.1 unless --host is given."""
+ import argparse
+
+ parser = argparse.ArgumentParser(description="Human-in-the-loop UI")
+ parser.add_argument(
+ "--host",
+ default=None,
+ help="Address to listen on (default: 127.0.0.1, or $CUA_HUMAN_TOOL_HOST)",
+ )
+ args = parser.parse_args(argv)
+
+ host = resolve_host(args.host)
+ if not is_loopback(host):
+ print(f"WARNING: listening on {host}, reachable from other machines.")
demo = create_ui()
demo.queue()
- demo.launch(server_name="0.0.0.0", server_port=7860)
+ # The page asks for the server token as its password.
+ demo.launch(server_name=host, server_port=7860, auth=gradio_auth(client_token))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/libs/python/agent/tests/test_human_tool_auth.py b/libs/python/agent/tests/test_human_tool_auth.py
new file mode 100644
index 0000000000..470edf5bce
--- /dev/null
+++ b/libs/python/agent/tests/test_human_tool_auth.py
@@ -0,0 +1,356 @@
+"""The human tool listens on loopback and requires a bearer token on every API route."""
+
+import importlib
+import os
+import stat
+from unittest.mock import MagicMock
+
+import pytest
+
+pytest.importorskip("fastapi")
+pytest.importorskip("httpx")
+
+from cua_agent import human_auth # noqa: E402
+from cua_agent.human_tool import server # noqa: E402
+from fastapi.testclient import TestClient # noqa: E402
+
+TOKEN = "test-token-for-human-tool"
+QUEUE_BODY = {"messages": [{"role": "user", "content": "delete it?"}], "model": "human"}
+
+
[email protected](autouse=True)
+def isolated_auth(tmp_path, monkeypatch):
+ """Keep token files in a temp dir and start every test with no cached token."""
+ monkeypatch.setenv("CUA_HOME", str(tmp_path))
+ monkeypatch.delenv(human_auth.TOKEN_ENV, raising=False)
+ monkeypatch.delenv(human_auth.HOST_ENV, raising=False)
+ monkeypatch.setattr(human_auth, "_generated_token", None)
+
+
+def client(monkeypatch):
+ monkeypatch.setenv(human_auth.TOKEN_ENV, TOKEN)
+ return TestClient(server.app)
+
+
+def bearer(token=TOKEN):
+ return {"Authorization": f"Bearer {token}"}
+
+
+# ---- every API route rejects requests without the token ----------------------
+
+
+ "method, path, body",
+ [
+ ("post", "/queue", QUEUE_BODY),
+ ("get", "/pending", None),
+ ("get", "/status/some-id", None),
+ ("post", "/complete/some-id", {"response": "Yes, delete it"}),
+ ("post", "/fail/some-id", {"error": "x"}),
+ ],
+)
+class TestRoutesRequireToken:
+ def test_no_token_is_401(self, client, method, path, body):
+ resp = getattr(client, method)(path, **({"json": body} if body is not None else {}))
+ assert resp.status_code == 401
+
+ def test_wrong_token_is_401(self, client, method, path, body):
+ kwargs = {"headers": bearer("not-the-token")}
+ if body is not None:
+ kwargs["json"] = body
+ assert getattr(client, method)(path, **kwargs).status_code == 401
+
+ def test_wrong_scheme_is_401(self, client, method, path, body):
+ kwargs = {"headers": {"Authorization": f"Basic {TOKEN}"}}
+ if body is not None:
+ kwargs["json"] = body
+ assert getattr(client, method)(path, **kwargs).status_code == 401
+
+
+def test_empty_bearer_is_401(client):
+ assert client.get("/pending", headers={"Authorization": "Bearer "}).status_code == 401
+
+
+def test_root_does_not_need_token(client):
+ assert client.get("/").status_code == 200
+
+
+# ---- with the token the normal flow works ------------------------------------
+
+
+def test_full_flow_with_token(client):
+ queued = client.post("/queue", json=QUEUE_BODY, headers=bearer())
+ assert queued.status_code == 200
+ call_id = queued.json()["id"]
+
+ pending = client.get("/pending", headers=bearer()).json()["pending_calls"]
+ assert call_id in [c["id"] for c in pending]
+
+ done = client.post(f"/complete/{call_id}", json={"response": "no"}, headers=bearer())
+ assert done.status_code == 200
+
+ status = client.get(f"/status/{call_id}", headers=bearer()).json()
+ assert status["status"] == "completed"
+ assert status["response"] == "no"
+
+
+def test_completion_without_token_leaves_call_pending(client):
+ call_id = client.post("/queue", json=QUEUE_BODY, headers=bearer()).json()["id"]
+
+ resp = client.post(f"/complete/{call_id}", json={"response": "Yes, delete it"})
+ assert resp.status_code == 401
+
+ status = client.get(f"/status/{call_id}", headers=bearer()).json()
+ assert status["status"] == "pending"
+ assert "response" not in status
+
+
+# ---- generated token ---------------------------------------------------------
+
+
+def test_generated_token_is_saved_private_and_accepted(tmp_path):
+ token = human_auth.server_token()
+ path = human_auth.token_file()
+
+ assert path == tmp_path / "human_tool" / "token"
+ assert path.read_text() == token
+ assert len(token) >= 32
+ if os.name == "posix":
+ assert stat.S_IMODE(path.stat().st_mode) == 0o600
+
+ api = TestClient(server.app)
+ assert api.get("/pending").status_code == 401
+ assert api.get("/pending", headers=bearer(token)).status_code == 200
+
+
+def test_generated_token_differs_per_launch(monkeypatch):
+ first = human_auth.server_token()
+ monkeypatch.setattr(human_auth, "_generated_token", None) # simulate a restart
+ second = human_auth.server_token()
+
+ assert first != second
+ assert human_auth.token_file().read_text() == second
+
+
+def test_env_token_wins_and_is_not_written(monkeypatch):
+ monkeypatch.setenv(human_auth.TOKEN_ENV, TOKEN)
+ assert human_auth.server_token() == TOKEN
+ assert not human_auth.token_file().exists()
+
+
+def test_client_token_order(monkeypatch):
+ assert human_auth.client_token() is None # nothing configured
+
+ token = human_auth.server_token() # writes the file
+ assert human_auth.client_token() == token
+
+ monkeypatch.setenv(human_auth.TOKEN_ENV, "from-env")
+ assert human_auth.client_token() == "from-env"
+ assert human_auth.client_token("explicit") == "explicit"
+
+
+def test_token_compare_is_constant_time(monkeypatch):
+ calls = []
+ real = human_auth.hmac.compare_digest
+
+ def spy(a, b):
+ calls.append((a, b))
+ return real(a, b)
+
+ monkeypatch.setattr(human_auth.hmac, "compare_digest", spy)
+
+ assert human_auth.token_matches("abc", "abc")
+ assert not human_auth.token_matches("abd", "abc")
+ assert not human_auth.token_matches(None, "abc")
+ assert len(calls) == 2
+
+
+# ---- default bind address ----------------------------------------------------
+
+
+def test_default_host_is_loopback(monkeypatch):
+ assert human_auth.resolve_host() == "127.0.0.1"
+ assert human_auth.is_loopback(human_auth.resolve_host())
+
+
+def test_host_can_be_exposed_only_explicitly(monkeypatch):
+ assert human_auth.resolve_host("0.0.0.0") == "0.0.0.0"
+ monkeypatch.setenv(human_auth.HOST_ENV, "0.0.0.0")
+ assert human_auth.resolve_host() == "0.0.0.0"
+ assert not human_auth.is_loopback("0.0.0.0")
+
+
+def test_server_main_binds_loopback_by_default(monkeypatch):
+ uvicorn = pytest.importorskip("uvicorn")
+ run = MagicMock()
+ monkeypatch.setattr(uvicorn, "run", run)
+
+ server.main([])
+ assert run.call_args.kwargs["host"] == "127.0.0.1"
+
+ server.main(["--host", "0.0.0.0"])
+ assert run.call_args.kwargs["host"] == "0.0.0.0"
+
+
+# ---- clients send the token --------------------------------------------------
+
+
+def _route_requests_to(client, monkeypatch, module):
+ """Make ``module.requests.get/post`` call the in-process app instead of the network."""
+ seen = []
+
+ def fake(method):
+ def call(url, json=None, headers=None, timeout=None):
+ path = "/" + url.split("//", 1)[1].split("/", 1)[1]
+ seen.append((method, path, dict(headers or {})))
+ return getattr(client, method)(path, json=json, headers=headers)
+
+ return call
+
+ fake_requests = MagicMock()
+ fake_requests.get = fake("get")
+ fake_requests.post = fake("post")
+ fake_requests.RequestException = Exception
+ monkeypatch.setattr(module, "requests", fake_requests)
+ return seen
+
+
+def test_adapter_authenticates_with_the_token_file(monkeypatch):
+ from cua_agent.adapters import human_adapter
+
+ api = TestClient(server.app)
+ human_auth.server_token() # server side: generated token written to the file
+ seen = _route_requests_to(api, monkeypatch, human_adapter)
+
+ adapter = human_adapter.HumanAdapter() # no token passed, no env var set
+ call_id = adapter._queue_completion(QUEUE_BODY["messages"], "human")
+
+ assert call_id
+ assert seen[0][2]["Authorization"] == f"Bearer {human_auth.client_token()}"
+
+
+def test_adapter_token_argument_and_env(client, monkeypatch):
+ from cua_agent.adapters import human_adapter
+
+ seen = _route_requests_to(client, monkeypatch, human_adapter)
+ assert human_adapter.HumanAdapter()._queue_completion([], "human") # env var
+ assert human_adapter.HumanAdapter(token=TOKEN)._queue_completion([], "human") # argument
+ assert [s[2]["Authorization"] for s in seen] == [f"Bearer {TOKEN}"] * 2
+
+
+def test_adapter_reports_rejected_token(client, monkeypatch):
+ from cua_agent.adapters import human_adapter
+
+ _route_requests_to(client, monkeypatch, human_adapter)
+ with pytest.raises(Exception, match="rejected the token"):
+ human_adapter.HumanAdapter(token="wrong")._queue_completion([], "human")
+
+
+def test_adapter_async_poll_sends_token(client, monkeypatch):
+ import asyncio
+
+ from cua_agent.adapters import human_adapter
+
+ adapter = human_adapter.HumanAdapter(token=TOKEN)
+ assert adapter._headers() == bearer()
+
+ # the async poller builds its aiohttp session from the same headers
+ captured = {}
+
+ class FakeSession:
+ def __init__(self, headers=None):
+ captured["headers"] = headers
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ def get(self, url):
+ class Resp:
+ async def __aenter__(s):
+ return s
+
+ async def __aexit__(s, *exc):
+ return False
+
+ def raise_for_status(s):
+ pass
+
+ async def json(s):
+ return {"status": "completed", "response": "ok"}
+
+ return Resp()
+
+ import aiohttp
+
+ monkeypatch.setattr(aiohttp, "ClientSession", FakeSession)
+ result = asyncio.run(adapter._async_wait_for_completion("some-id"))
+ assert result == {"response": "ok"}
+ assert captured["headers"] == bearer()
+
+
+def test_ui_authenticates_with_the_token_file(monkeypatch):
+ pytest.importorskip("gradio")
+ from cua_agent.human_tool import ui
+
+ api = TestClient(server.app)
+ human_auth.server_token()
+ seen = _route_requests_to(api, monkeypatch, ui)
+
+ handler = ui.HumanCompletionUI()
+ assert handler.get_pending_calls() == [] or isinstance(handler.get_pending_calls(), list)
+ assert seen[0][1] == "/pending"
+ assert seen[0][2]["Authorization"] == f"Bearer {human_auth.client_token()}"
+
+ call_id = api.post("/queue", json=QUEUE_BODY, headers=bearer(human_auth.client_token())).json()[
+ "id"
+ ]
+ assert handler.complete_call_with_response(call_id, "approved") is True
+ assert seen[-1][2]["Authorization"] == f"Bearer {human_auth.client_token()}"
+
+
+def test_ui_main_binds_loopback_and_asks_for_password(monkeypatch):
+ pytest.importorskip("gradio")
+ from cua_agent.human_tool import ui
+
+ demo = MagicMock()
+ monkeypatch.setattr(ui, "create_ui", lambda *a, **k: demo)
+
+ ui.main([])
+ kwargs = demo.launch.call_args.kwargs
+ assert kwargs["server_name"] == "127.0.0.1"
+ # the page's login only lets in whoever knows the token
+ token = human_auth.server_token()
+ assert kwargs["auth"]("anyone", token) is True
+ assert kwargs["auth"]("anyone", "wrong") is False
+
+
+# ---- combined server + UI ----------------------------------------------------
+
+
+def test_combined_app_binds_loopback_and_protects_the_page(monkeypatch):
+ pytest.importorskip("gradio")
+ uvicorn = pytest.importorskip("uvicorn")
+ combined = importlib.import_module("cua_agent.human_tool.__main__")
+
+ run = MagicMock()
+ monkeypatch.setattr(uvicorn, "run", run)
+ combined.main([])
+ assert run.call_args.kwargs["host"] == "127.0.0.1"
+
+ token = human_auth.server_token()
+ api = TestClient(combined.app)
+
+ # API routes still need the bearer token ...
+ assert api.get("/pending").status_code == 401
+ assert api.get("/pending", headers=bearer(token)).status_code == 200
+
+ # ... and the web page needs the token as its password
+ assert api.post("/gradio/login", data={"username": "u", "password": "wrong"}).status_code in (
+ 400,
+ 401,
+ )
+ assert api.post("/gradio/login", data={"username": "u", "password": token}).status_code == 200