"""The two credential planes: a console key governs the API, an agent token only governs its own agent.""" from __future__ import annotations import pytest from fastapi.testclient import TestClient from starlette.websockets import WebSocketDisconnect from agenthub.config import get_settings, reset_settings_cache BASE = "/api/v1" @pytest.fixture() def vault(tmp_path, monkeypatch) -> TestClient: """Auth on: nothing under /api/v1 answers without a credential.""" monkeypatch.setenv("AGENTHUB_DATABASE_URL", f"sqlite+aiosqlite:///{tmp_path / 'vault.db'}") monkeypatch.setenv("AGENTHUB_DATA_DIR", str(tmp_path)) monkeypatch.setenv("AGENTHUB_AUTH_ENABLED", "true") monkeypatch.setenv("AGENTHUB_PRESENCE_ENABLED", "false") monkeypatch.setenv("AGENTHUB_HUB_PUBLIC_URL", "http://127.0.0.1:8100") reset_settings_cache() from agenthub.app import create_app with TestClient(create_app()) as client: yield client reset_settings_cache() @pytest.fixture() def root() -> str: return get_settings().bootstrap_credentials()[0] def keyed(client: TestClient, key: str): return {"X-API-Key": key} def test_a_sealed_credential_only_opens_with_the_hubs_own_secret(): """库里那份可读副本只为「回看凭证」存在:换掉 secret_key 就读不出来了。""" from agenthub import security sealed = security.seal("secret-a", "ag_lovesagenthub") assert sealed != "ag_lovesagenthub" and sealed.startswith("sey_") assert security.unseal("secret-a", sealed) == "ag_lovesagenthub" assert security.unseal("secret-b", sealed) == "", "换 secret 要读不出来,但不能抛" assert security.unseal("secret-a", "sey_truncated") == "" assert security.seal("", "ag_lovesagenthub") == "" and security.seal("secret-a", "") == "" def test_healthz_stays_open(vault): assert vault.get("/healthz").status_code == 200 assert vault.get(f"{BASE}/meta").status_code == 401 def test_bootstrap_key_works_on_both_headers(vault, root): assert vault.get(f"{BASE}/meta").json()["detail"].startswith("missing credentials") via_header = vault.get(f"{BASE}/meta", headers=keyed(vault, root)) assert via_header.status_code == 200 assert via_header.json()["auth_required"] is True assert vault.get(f"{BASE}/meta", headers={"Authorization": f"Bearer {root}"}).status_code == 200 assert vault.get(f"{BASE}/meta", headers=keyed(vault, "ah_nope")).status_code == 403 def test_read_only_key_can_look_but_not_touch(vault, root): created = vault.post(f"{BASE}/keys", json={"name": "viewer", "scope": "read"}, headers=keyed(vault, root)) assert created.status_code == 201, created.text body = created.json() assert body["scopes"] == {"scope": "read"} and body["token"].startswith("ah_") assert [row["id"] for row in vault.get(f"{BASE}/keys", headers=keyed(vault, root)).json()] == [body["id"]] read_only = keyed(vault, body["token"]) assert vault.get(f"{BASE}/agents", headers=read_only).status_code == 200 assert vault.get(f"{BASE}/stats", headers=read_only).status_code == 200 assert vault.post(f"{BASE}/agents", json={"name": "sneaky", "driver": "mock"}, headers=read_only).status_code == 403 assert vault.post(f"{BASE}/keys", json={"name": "escalate"}, headers=read_only).status_code == 403 assert vault.delete(f"{BASE}/keys/{body['id']}", headers=keyed(vault, root)).status_code == 200 assert vault.get(f"{BASE}/agents", headers=read_only).status_code == 403 def test_an_agent_token_does_not_open_the_console(vault, root): offer = vault.post( f"{BASE}/agents", json={"name": "worker", "driver": "mock", "connection_mode": "connector", "issue_credential": True}, headers=keyed(vault, root), ) assert offer.status_code == 201 agent_token = offer.json()["agent_token"] assert agent_token.startswith("ag_") # the agent plane accepts it, for itself only assert vault.post(f"{BASE}/gateway/heartbeat", json={"status": "online"}, headers={"Authorization": f"Bearer {agent_token}"}).status_code == 200 # the console plane rejects it, and vice versa assert vault.get(f"{BASE}/agents", headers={"Authorization": f"Bearer {agent_token}"}).status_code == 403 # ...and the agent plane never reads a console key: X-API-Key is not its # header at all (401), and a console key as Bearer is not an agent token (403) assert vault.post(f"{BASE}/gateway/heartbeat", json={"status": "online"}, headers=keyed(vault, root)).status_code == 401 assert vault.post(f"{BASE}/gateway/heartbeat", json={"status": "online"}, headers={"Authorization": f"Bearer {root}"}).status_code == 403 # the plaintext agent token is never returned: the hub keeps a hash + hint agent = vault.get(f"{BASE}/agents/worker", headers=keyed(vault, root)).json() assert agent["connector"]["token_preview"] and agent_token not in agent["connector"]["token_preview"] assert vault.get(f"{BASE}/presence", headers=keyed(vault, root)).json()[0]["status"] == "online" def test_console_socket_needs_the_same_key(vault, root): with pytest.raises(WebSocketDisconnect) as refused: with vault.websocket_connect(f"{BASE}/stream?api_key=wrong") as ws: ws.receive_json() assert refused.value.code == 4403 with vault.websocket_connect(f"{BASE}/stream?api_key={root}") as ws: hello = ws.receive_json() assert hello["kind"] == "hub.hello" and hello["payload"]["topics"] == ["*.>"]