Host Agent: - One-time local operator account bootstrap (PBKDF2-HMAC-SHA256, atomic 0600-permission write) gating the daemon's first unattended start via a new `setup` CLI subcommand. - Default control-plane URL now https://amcp.home.jerryyan.top (env var override unchanged). - Enrollment no longer requires a pre-issued token; falls back to zero-token self-service enrollment when none is configured. Cloud control plane: - CLOUD_SELF_SERVICE_ENROLLMENT_ENABLED (default false) opt-in flag. - SelfServiceEnrollmentAuthProvider + ChainedEnrollmentAuthProvider: configured tokens still take priority; self-service only applies when no token matches, preserving edge-host-enrollment's token-bound path. - Fixed a latent bug in sql_repository.py::enroll_host: the token-conflict lookup used `== enrollment_token_digest`, which SQLAlchemy compiles to `IS NULL` when the value is None, so every self-service enrollment after the first would have falsely collided with an existing NULL-digest host. Skipped that lookup entirely when the digest is None. Docs/deploy: .env.example, compose.yaml, compose.deploy.yaml, CLOUD_DEPLOYMENT.md, MACOS_IPHONE_SETUP.md updated for the new flag, URL default, and required `device-host-agent setup` step. Verification: 494 non-integration tests pass; openspec validate --strict passes. PostgreSQL-backed contract tests and full manual end-to-end verification were not run (no Postgres/Docker or reachable cloud-api in this environment); noted as unchecked in tasks.md 7.2/7.4.
This commit is contained in:
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from host_agent import cli
|
||||
from host_agent.local_account import LocalAccountStore
|
||||
|
||||
|
||||
class _RecordingApplication:
|
||||
def __init__(self) -> None:
|
||||
self.ran = False
|
||||
|
||||
def run(self) -> None:
|
||||
self.ran = True
|
||||
|
||||
|
||||
def _base_env(tmp_path) -> dict[str, str]:
|
||||
return {
|
||||
"HOST_AGENT_CONTROL_PLANE_URL": "https://cloud.example",
|
||||
"HOST_AGENT_LOCAL_ACCOUNT_PATH": str(tmp_path / "account.json"),
|
||||
"HOST_AGENT_IDENTITY_PATH": str(tmp_path / "identity.json"),
|
||||
}
|
||||
|
||||
|
||||
def _set_env(monkeypatch, tmp_path) -> None:
|
||||
for key, value in _base_env(tmp_path).items():
|
||||
monkeypatch.setenv(key, value)
|
||||
|
||||
|
||||
def _patch_create_application(monkeypatch) -> dict:
|
||||
captured: dict = {}
|
||||
|
||||
def fake_create_application(*, config=None, **kwargs):
|
||||
captured["config"] = config
|
||||
app = _RecordingApplication()
|
||||
captured["app"] = app
|
||||
return app
|
||||
|
||||
monkeypatch.setattr(cli, "create_application", fake_create_application)
|
||||
return captured
|
||||
|
||||
|
||||
def test_existing_account_fast_path_skips_prompting(monkeypatch, tmp_path) -> None:
|
||||
_set_env(monkeypatch, tmp_path)
|
||||
LocalAccountStore(tmp_path / "account.json").create(
|
||||
"operator", "correct horse battery staple"
|
||||
)
|
||||
|
||||
def fail_input(prompt: str = "") -> str:
|
||||
raise AssertionError("must not prompt when a local account already exists")
|
||||
|
||||
monkeypatch.setattr("builtins.input", fail_input)
|
||||
captured = _patch_create_application(monkeypatch)
|
||||
|
||||
cli.main([])
|
||||
|
||||
assert captured["app"].ran is True
|
||||
assert captured["config"].display_name == "operator"
|
||||
|
||||
|
||||
def test_interactive_first_run_prompts_and_creates_account(monkeypatch, tmp_path) -> None:
|
||||
_set_env(monkeypatch, tmp_path)
|
||||
monkeypatch.setattr(sys.stdin, "isatty", lambda: True)
|
||||
inputs = iter(["operator"])
|
||||
monkeypatch.setattr("builtins.input", lambda prompt="": next(inputs))
|
||||
passwords = iter(["hunter2", "hunter2"])
|
||||
monkeypatch.setattr("getpass.getpass", lambda prompt="": next(passwords))
|
||||
captured = _patch_create_application(monkeypatch)
|
||||
|
||||
cli.main([])
|
||||
|
||||
assert captured["app"].ran is True
|
||||
account = LocalAccountStore(tmp_path / "account.json").load()
|
||||
assert account is not None
|
||||
assert account.username == "operator"
|
||||
|
||||
|
||||
def test_non_interactive_without_account_exits_with_clear_error(
|
||||
monkeypatch, tmp_path, capsys
|
||||
) -> None:
|
||||
_set_env(monkeypatch, tmp_path)
|
||||
monkeypatch.setattr(sys.stdin, "isatty", lambda: False)
|
||||
captured = _patch_create_application(monkeypatch)
|
||||
|
||||
with pytest.raises(SystemExit) as exc_info:
|
||||
cli.main([])
|
||||
|
||||
assert exc_info.value.code == 1
|
||||
assert "setup" in capsys.readouterr().err
|
||||
assert "app" not in captured
|
||||
assert LocalAccountStore(tmp_path / "account.json").load() is None
|
||||
|
||||
|
||||
def test_setup_subcommand_creates_account(monkeypatch, tmp_path) -> None:
|
||||
_set_env(monkeypatch, tmp_path)
|
||||
inputs = iter(["operator"])
|
||||
monkeypatch.setattr("builtins.input", lambda prompt="": next(inputs))
|
||||
passwords = iter(["hunter2", "hunter2"])
|
||||
monkeypatch.setattr("getpass.getpass", lambda prompt="": next(passwords))
|
||||
captured = _patch_create_application(monkeypatch)
|
||||
|
||||
cli.main(["setup"])
|
||||
|
||||
assert "app" not in captured
|
||||
account = LocalAccountStore(tmp_path / "account.json").load()
|
||||
assert account is not None
|
||||
assert account.username == "operator"
|
||||
|
||||
|
||||
def test_setup_subcommand_refuses_overwrite_without_confirmation(
|
||||
monkeypatch, tmp_path
|
||||
) -> None:
|
||||
_set_env(monkeypatch, tmp_path)
|
||||
store = LocalAccountStore(tmp_path / "account.json")
|
||||
original = store.create("operator", "original-password")
|
||||
monkeypatch.setattr("builtins.input", lambda prompt="": "n")
|
||||
|
||||
cli.main(["setup"])
|
||||
|
||||
assert store.load() == original
|
||||
@@ -225,3 +225,36 @@ def test_bootstrap_client_retries_identical_enrollment_and_enrolls_device() -> N
|
||||
assert requests[0].content == requests[1].content
|
||||
assert requests[0].headers["authorization"] == "Bearer one-time-token"
|
||||
assert requests[2].headers["authorization"] == ("Bearer host-token-" + ("x" * 40))
|
||||
|
||||
|
||||
def test_self_service_enrollment_sends_no_authorization_header() -> None:
|
||||
requests: list[httpx.Request] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
return httpx.Response(201, json={"host_id": "host-cloud-a"})
|
||||
|
||||
config = _config(
|
||||
host_id="",
|
||||
token="",
|
||||
enrollment_token="",
|
||||
enrollment_managed=True,
|
||||
)
|
||||
with httpx.Client(
|
||||
transport=httpx.MockTransport(handler),
|
||||
base_url="https://control.example",
|
||||
) as http_client:
|
||||
client = HostAgentEnrollmentClient(
|
||||
config,
|
||||
http_client=http_client,
|
||||
sleep=lambda _delay: None,
|
||||
)
|
||||
host = client.enroll_host(
|
||||
agent_instance_id="agent-instance-a",
|
||||
host_token="host-token-" + ("x" * 40),
|
||||
display_name="operator",
|
||||
)
|
||||
|
||||
assert host.host_id == "host-cloud-a"
|
||||
assert len(requests) == 1
|
||||
assert "authorization" not in requests[0].headers
|
||||
|
||||
@@ -17,9 +17,9 @@ BASE_ENV = {
|
||||
}
|
||||
|
||||
|
||||
def test_load_host_agent_config_uses_local_network_defaults() -> None:
|
||||
def test_load_host_agent_config_uses_managed_cloud_default() -> None:
|
||||
assert load_host_agent_config(BASE_ENV) == HostAgentConfig(
|
||||
control_plane_url="http://127.0.0.1:8001",
|
||||
control_plane_url="https://amcp.home.jerryyan.top",
|
||||
host_id="host-a",
|
||||
token="secret",
|
||||
)
|
||||
@@ -74,6 +74,27 @@ def test_existing_identity_state_allows_restart_without_enrollment_token(
|
||||
assert config.enrollment_managed is True
|
||||
|
||||
|
||||
def test_fresh_install_with_no_token_is_valid_and_defaults_local_account_path() -> None:
|
||||
config = load_host_agent_config({"HOST_AGENT_CONTROL_PLANE_URL": "https://cloud.example"})
|
||||
|
||||
assert config.host_id == ""
|
||||
assert config.enrollment_token == ""
|
||||
assert config.enrollment_managed is True
|
||||
assert config.local_account_path == Path("tasks/host_local_account.json")
|
||||
|
||||
|
||||
def test_local_account_path_can_be_overridden(tmp_path) -> None:
|
||||
account_path = tmp_path / "account.json"
|
||||
config = load_host_agent_config(
|
||||
{
|
||||
"HOST_AGENT_CONTROL_PLANE_URL": "https://cloud.example",
|
||||
"HOST_AGENT_LOCAL_ACCOUNT_PATH": str(account_path),
|
||||
}
|
||||
)
|
||||
|
||||
assert config.local_account_path == account_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"overrides",
|
||||
[
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from host_agent.client import HostAgentAPIError
|
||||
from host_agent.config import HostAgentConfig
|
||||
from host_agent.enrollment import resolve_host_identity
|
||||
from host_agent.identity import HostIdentityStore
|
||||
|
||||
|
||||
def _config(**overrides) -> HostAgentConfig:
|
||||
values = {
|
||||
"control_plane_url": "https://control.example",
|
||||
}
|
||||
values.update(overrides)
|
||||
return HostAgentConfig(**values)
|
||||
|
||||
|
||||
class _RecordingEnrollmentClient:
|
||||
def __init__(self, *, host_id: str = "host-cloud-a") -> None:
|
||||
self.host_id = host_id
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def enroll_host(self, **payload):
|
||||
from cloud.internal_api.models import HostEnrollmentResponse
|
||||
|
||||
self.calls.append(payload)
|
||||
return HostEnrollmentResponse(host_id=self.host_id)
|
||||
|
||||
|
||||
class _RejectingEnrollmentClient:
|
||||
def enroll_host(self, **payload):
|
||||
raise HostAgentAPIError(401, "unauthorized")
|
||||
|
||||
|
||||
def test_fresh_install_with_no_token_self_enrolls(tmp_path) -> None:
|
||||
identity_store = HostIdentityStore(tmp_path / "identity.json")
|
||||
client = _RecordingEnrollmentClient()
|
||||
|
||||
resolved = resolve_host_identity(
|
||||
_config(enrollment_token=""),
|
||||
identity_store=identity_store,
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert resolved.host_id == "host-cloud-a"
|
||||
assert len(client.calls) == 1
|
||||
assert identity_store.load().host_id == "host-cloud-a"
|
||||
|
||||
|
||||
def test_self_service_rejection_propagates_as_api_error(tmp_path) -> None:
|
||||
identity_store = HostIdentityStore(tmp_path / "identity.json")
|
||||
client = _RejectingEnrollmentClient()
|
||||
|
||||
try:
|
||||
resolve_host_identity(
|
||||
_config(enrollment_token=""),
|
||||
identity_store=identity_store,
|
||||
client=client,
|
||||
)
|
||||
except HostAgentAPIError as exc:
|
||||
assert exc.status_code == 401
|
||||
else:
|
||||
raise AssertionError("expected HostAgentAPIError to propagate")
|
||||
assert identity_store.load().host_id is None
|
||||
|
||||
|
||||
def test_configured_enrollment_token_still_used_when_present(tmp_path) -> None:
|
||||
identity_store = HostIdentityStore(tmp_path / "identity.json")
|
||||
client = _RecordingEnrollmentClient()
|
||||
|
||||
resolve_host_identity(
|
||||
_config(enrollment_token="one-time-token"),
|
||||
identity_store=identity_store,
|
||||
client=client,
|
||||
)
|
||||
|
||||
assert client.calls[0]["agent_instance_id"]
|
||||
|
||||
|
||||
def test_existing_cached_identity_skips_enrollment(tmp_path) -> None:
|
||||
identity_store = HostIdentityStore(tmp_path / "identity.json")
|
||||
identity_store.complete(identity_store.load_or_create(), "host-cloud-a")
|
||||
|
||||
class ExplodingClient:
|
||||
def enroll_host(self, **payload):
|
||||
raise AssertionError("cached identity must skip enrollment")
|
||||
|
||||
resolved = resolve_host_identity(
|
||||
_config(enrollment_token=""),
|
||||
identity_store=identity_store,
|
||||
client=ExplodingClient(), # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
assert resolved.host_id == "host-cloud-a"
|
||||
@@ -0,0 +1,62 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from host_agent.local_account import LocalAccountStateError, LocalAccountStore
|
||||
|
||||
|
||||
def test_local_account_store_creates_and_verifies_password(tmp_path) -> None:
|
||||
path = tmp_path / "state" / "host_local_account.json"
|
||||
store = LocalAccountStore(path)
|
||||
|
||||
assert store.load() is None
|
||||
|
||||
created = store.create("operator", "correct horse battery staple")
|
||||
assert created.username == "operator"
|
||||
assert store.load() == created
|
||||
assert store.verify(created, "correct horse battery staple") is True
|
||||
assert store.verify(created, "wrong password") is False
|
||||
|
||||
raw = path.read_text(encoding="utf-8")
|
||||
assert "correct horse battery staple" not in raw
|
||||
assert "password" not in raw.lower() or "password_hash" in raw
|
||||
if os.name != "nt":
|
||||
assert path.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_local_account_state_never_exposes_password_via_repr(tmp_path) -> None:
|
||||
store = LocalAccountStore(tmp_path / "host_local_account.json")
|
||||
created = store.create("operator", "hunter2")
|
||||
|
||||
assert "hunter2" not in repr(created)
|
||||
assert "salt=" not in repr(created)
|
||||
assert "password_hash=" not in repr(created)
|
||||
|
||||
|
||||
def test_local_account_store_rejects_corrupted_file(tmp_path) -> None:
|
||||
path = tmp_path / "host_local_account.json"
|
||||
path.write_text('{"username": "operator"}', encoding="utf-8")
|
||||
store = LocalAccountStore(path)
|
||||
|
||||
with pytest.raises(LocalAccountStateError):
|
||||
store.load()
|
||||
|
||||
|
||||
def test_local_account_store_rejects_invalid_json(tmp_path) -> None:
|
||||
path = tmp_path / "host_local_account.json"
|
||||
path.write_text("not json", encoding="utf-8")
|
||||
store = LocalAccountStore(path)
|
||||
|
||||
with pytest.raises(LocalAccountStateError):
|
||||
store.load()
|
||||
|
||||
|
||||
def test_local_account_store_rejects_empty_credentials(tmp_path) -> None:
|
||||
store = LocalAccountStore(tmp_path / "host_local_account.json")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
store.create("", "password")
|
||||
with pytest.raises(ValueError):
|
||||
store.create("operator", "")
|
||||
Reference in New Issue
Block a user