feat: bundle agent executables + web-driven claude login

Two changes so an operator can stand up and authenticate Handler entirely
from the browser, with a self-contained control image.

Bundle executables in the control image (Dockerfile.control)
- Node.js (NodeSource) + the Claude Code CLI, mise (official apt repo), and
  forge (git-pkgs/forge, built in a Go stage) join the existing git/tmux/ssh.
  No more bring-your-own binaries: live agent spawning, the verification gate,
  CI resolution, and the login flow all work out of the box. Installed under
  /usr so the /var/lib/handler VOLUME never masks them; mise apt source pinned
  to $TARGETARCH for the multi-arch (amd64/arm64) build.

Claude login from the web UI
- New login_start / login_submit command types (migration 0005) drive the
  interactive `claude /login` through the same enqueue→worker handoff every
  other control action uses — the API container has no claude binary.
- control/login.py opens `claude` in a dedicated tmux session, sends /login,
  selects the subscription account, and scrapes the claude.com authorization
  URL (tmux.capture_pane, -pJ so a wrapped URL rejoins); a second command feeds
  back the pasted code. Fully mockable via the tmux seam.
- API: POST /login/start, POST /login/submit (admin-gated).
- Dashboard: a "Claude Login" pane — a button that starts the flow, embeds the
  URL in an iframe (with a new-tab fallback, since claude.com may refuse
  framing), and takes the code to finish.

Also un-ignores frontend/lib/ (a broad Python `lib/` rule was swallowing the
UI's own api client + formatters, breaking rebuilds from a fresh clone) and
reconstructs those two source files; rebuilt static export committed.

Tests: control/login unit tests (tmux faked), worker dispatch, and API route
tests. Full suite green (195 tests), ruff clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YKVyBmKvWDVgrFC9WER2f2
This commit is contained in:
Claude
2026-07-13 17:45:52 +00:00
parent 5c68c8d47b
commit fa2e97130d
27 changed files with 1145 additions and 24 deletions
+49
View File
@@ -0,0 +1,49 @@
"""The web-login API surface: enqueue login_start / login_submit, admin-gated."""
from __future__ import annotations
def _admin(env):
# ADMIN_TOKEN is unset in the test env, so the admin gate falls back to AUTH_TOKEN.
return {"Authorization": f"Bearer {env['token']}"}
def test_login_start_enqueues_command(client, env):
r = client.post("/login/start", headers=_admin(env))
assert r.status_code == 202
body = r.json()
assert body["type"] == "login_start"
assert body["status"] == "queued"
assert body["requested_by"] == "operator:web"
def test_login_submit_enqueues_command_with_code(client, env):
r = client.post("/login/submit", headers=_admin(env), json={"code": "auth-xyz"})
assert r.status_code == 202
body = r.json()
assert body["type"] == "login_submit"
assert body["payload"] == {"code": "auth-xyz"}
def test_login_submit_rejects_blank_code(client, env):
r = client.post("/login/submit", headers=_admin(env), json={"code": ""})
assert r.status_code == 422
def test_login_start_requires_auth(client):
assert client.post("/login/start").status_code in (401, 403)
def test_login_endpoints_require_admin_token(client, env, monkeypatch):
# With a distinct admin token set, the plain auth token must be refused.
monkeypatch.setenv("ADMIN_TOKEN", "admin-secret")
from handler import config
config.get_settings.cache_clear()
try:
r = client.post("/login/start", headers={"Authorization": f"Bearer {env['token']}"})
assert r.status_code == 403
ok = client.post("/login/start", headers={"Authorization": "Bearer admin-secret"})
assert ok.status_code == 202
finally:
config.get_settings.cache_clear()
+117
View File
@@ -0,0 +1,117 @@
"""The claude web-login seam: driving ``claude /login`` through tmux and scraping the URL.
Uses the shared ``fake_tmux`` fixture (extended here with a scripted ``capture_pane``) and
patches out the real sleeps, so no live claude/tmux is touched — the same approach as the
spawn tests.
"""
from __future__ import annotations
import pytest
from handler.control import login, tmux
@pytest.fixture
def no_sleep(monkeypatch):
monkeypatch.setattr(login, "_sleep", lambda *_a, **_k: None)
def _pane(monkeypatch, *frames):
"""Make ``capture_pane`` return each frame in turn, then repeat the last one."""
seq = list(frames)
def capture(_name):
return seq[0] if len(seq) == 1 else seq.pop(0)
monkeypatch.setattr(tmux, "capture_pane", capture)
AUTH_URL = "https://claude.ai/oauth/authorize?code=true&client_id=abc&state=xyz"
def test_extract_url_prefers_oauth_link():
pane = f"Visit https://example.com/help or\n{AUTH_URL}\nand paste the code."
assert login._extract_url(pane) == AUTH_URL
def test_extract_url_strips_trailing_punctuation():
assert login._extract_url(f"Open ({AUTH_URL}).") == AUTH_URL
def test_extract_url_none_when_no_link():
assert login._extract_url("no link here") is None
def test_start_launches_claude_selects_subscription_and_returns_url(
env, fake_tmux, no_sleep, monkeypatch
):
_pane(monkeypatch, "booting…", f"Open this URL to log in:\n{AUTH_URL}")
result = login.start(url_timeout=1.0)
assert result == {"session": login.LOGIN_SESSION, "url": AUTH_URL}
# A fresh claude session was launched…
launched = fake_tmux["calls"]["new_session"]
assert len(launched) == 1
assert launched[0]["name"] == login.LOGIN_SESSION
assert launched[0]["command"] == "claude"
# …then /login was sent, followed by a bare Enter selecting the subscription option.
sent = [c["keys"] for c in fake_tmux["calls"]["send_keys"]]
assert sent[:2] == ["/login", ""]
# The session is left alive for submit_code.
assert login.LOGIN_SESSION in fake_tmux["live"]
def test_start_kills_a_stale_session_first(env, fake_tmux, no_sleep, monkeypatch):
fake_tmux["live"].add(login.LOGIN_SESSION) # a leftover from an abandoned attempt
_pane(monkeypatch, f"{AUTH_URL}")
login.start(url_timeout=1.0)
assert login.LOGIN_SESSION in fake_tmux["calls"]["kill_session"]
def test_start_times_out_and_cleans_up_when_no_url(env, fake_tmux, no_sleep, monkeypatch):
_pane(monkeypatch, "still thinking, no url yet")
with pytest.raises(login.LoginError, match="timed out"):
login.start(url_timeout=0.05, poll_interval=0.0)
# It shouldn't leave a half-driven session lying around.
assert login.LOGIN_SESSION not in fake_tmux["live"]
def test_submit_code_sends_code_and_reports_success(env, fake_tmux, no_sleep, monkeypatch):
fake_tmux["live"].add(login.LOGIN_SESSION)
_pane(monkeypatch, "Login successful. Welcome back!")
result = login.submit_code("my-auth-code")
assert result["success"] is True
assert "Login successful" in result["output"]
assert {"name": login.LOGIN_SESSION, "keys": "my-auth-code"} in fake_tmux["calls"]["send_keys"]
# A confirmed login tears the session down.
assert login.LOGIN_SESSION not in fake_tmux["live"]
def test_submit_code_reports_failure_without_killing_session(
env, fake_tmux, no_sleep, monkeypatch
):
fake_tmux["live"].add(login.LOGIN_SESSION)
_pane(monkeypatch, "Invalid code, please try again")
result = login.submit_code("wrong")
assert result["success"] is False
assert login.LOGIN_SESSION in fake_tmux["live"] # left up for a retry
def test_submit_code_without_session_raises(env, fake_tmux, no_sleep):
with pytest.raises(login.LoginError, match="no active"):
login.submit_code("code")
def test_submit_code_rejects_blank(env, fake_tmux, no_sleep):
with pytest.raises(login.LoginError, match="no authorization code"):
login.submit_code(" ")
+48 -1
View File
@@ -6,7 +6,7 @@ machinery (already covered by test_control_spawn)."""
from __future__ import annotations
from handler.control import poller, spawn, worker
from handler.control import login, poller, spawn, worker
from handler.db import repository as repo
from handler.db.engine import get_engine
@@ -107,6 +107,53 @@ def test_poll_ci_command_returns_summary(env, monkeypatch):
assert done["result"] == {"checked": 0, "resolved": 0, "pending": 0}
def test_login_start_command_returns_url(env, monkeypatch):
monkeypatch.setattr(
login, "start", lambda: {"session": "handler__login", "url": "https://claude.ai/oauth"}
)
cmd = _enqueue(type="login_start")
worker.drain("w")
done = _get(cmd["id"])
assert done["status"] == "done"
assert done["result"]["url"] == "https://claude.ai/oauth"
def test_login_submit_command_feeds_code(env, monkeypatch):
seen = {}
def fake_submit(code):
seen["code"] = code
return {"success": True, "output": "Login successful"}
monkeypatch.setattr(login, "submit_code", fake_submit)
cmd = _enqueue(type="login_submit", payload={"code": "auth-123"})
worker.drain("w")
done = _get(cmd["id"])
assert done["status"] == "done"
assert done["result"]["success"] is True
assert seen["code"] == "auth-123"
def test_login_submit_failure_is_recorded_failed(env, monkeypatch):
monkeypatch.setattr(
login, "submit_code", lambda code: {"success": False, "output": "Invalid code"}
)
cmd = _enqueue(type="login_submit", payload={"code": "bad"})
worker.drain("w")
failed = _get(cmd["id"])
assert failed["status"] == "failed"
assert "Invalid code" in failed["error"]
def test_login_submit_without_code_is_failed(env):
cmd = _enqueue(type="login_submit", payload={})
assert worker.drain("w") == 1
assert _get(cmd["id"])["status"] == "failed"
def test_bad_command_is_recorded_failed_not_raised(env):
# spawn with no agent name -> CommandError -> the worker records 'failed', keeps going.
_seed_project()