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:
@@ -1,12 +1,76 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import replace
|
||||
|
||||
from host_agent.app import create_application
|
||||
from host_agent.config import load_host_agent_config
|
||||
from host_agent.local_account import LocalAccountStore
|
||||
|
||||
|
||||
class LocalAccountSetupError(RuntimeError):
|
||||
"""Raised when local account bootstrap cannot proceed."""
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> None:
|
||||
parser = argparse.ArgumentParser(description="Run the Device Host Agent")
|
||||
parser.parse_args(argv)
|
||||
create_application().run()
|
||||
subparsers = parser.add_subparsers(dest="command")
|
||||
subparsers.add_parser("setup", help="Create the local operator account")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
try:
|
||||
if args.command == "setup":
|
||||
_run_setup()
|
||||
return
|
||||
config = _resolve_config_with_local_account()
|
||||
except LocalAccountSetupError as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1) from exc
|
||||
|
||||
create_application(config=config).run()
|
||||
|
||||
|
||||
def _run_setup() -> None:
|
||||
config = load_host_agent_config()
|
||||
store = LocalAccountStore(config.local_account_path)
|
||||
if store.load() is not None:
|
||||
confirm = input(
|
||||
"A local account already exists. Overwrite it? [y/N] "
|
||||
).strip().lower()
|
||||
if confirm != "y":
|
||||
print("Setup cancelled; existing account left unchanged.")
|
||||
return
|
||||
account = _prompt_and_create(store)
|
||||
print(f"Local account '{account.username}' created.")
|
||||
|
||||
|
||||
def _resolve_config_with_local_account():
|
||||
config = load_host_agent_config()
|
||||
store = LocalAccountStore(config.local_account_path)
|
||||
account = store.load()
|
||||
if account is None:
|
||||
if not sys.stdin.isatty():
|
||||
raise LocalAccountSetupError(
|
||||
"no local account configured; run `device-host-agent setup` "
|
||||
"on an interactive terminal to create one"
|
||||
)
|
||||
account = _prompt_and_create(store)
|
||||
if not config.display_name:
|
||||
config = replace(config, display_name=account.username)
|
||||
return config
|
||||
|
||||
|
||||
def _prompt_and_create(store: LocalAccountStore):
|
||||
username = input("Username: ").strip()
|
||||
if not username:
|
||||
raise LocalAccountSetupError("username must not be empty")
|
||||
password = getpass.getpass("Password: ")
|
||||
confirm = getpass.getpass("Confirm password: ")
|
||||
if not password:
|
||||
raise LocalAccountSetupError("password must not be empty")
|
||||
if password != confirm:
|
||||
raise LocalAccountSetupError("passwords do not match")
|
||||
return store.create(username, password)
|
||||
|
||||
@@ -53,12 +53,10 @@ class HostAgentEnrollmentClient:
|
||||
host_token: str,
|
||||
display_name: str | None,
|
||||
) -> HostEnrollmentResponse:
|
||||
if not self.config.enrollment_token:
|
||||
raise HostAgentAPIError(0, "Host enrollment token is unavailable")
|
||||
response = self._request(
|
||||
"POST",
|
||||
"/internal/v1/enrollments",
|
||||
token=self.config.enrollment_token,
|
||||
token=self.config.enrollment_token or None,
|
||||
json={
|
||||
"agent_instance_id": agent_instance_id,
|
||||
"host_token": host_token,
|
||||
@@ -99,9 +97,10 @@ class HostAgentEnrollmentClient:
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
token: str,
|
||||
token: str | None,
|
||||
json: dict[str, Any],
|
||||
) -> httpx.Response:
|
||||
headers = {"Authorization": f"Bearer {token}"} if token else {}
|
||||
backoff = self.config.retry_backoff_seconds
|
||||
for attempt in range(1, self.config.max_retry_attempts + 1):
|
||||
try:
|
||||
@@ -109,7 +108,7 @@ class HostAgentEnrollmentClient:
|
||||
method,
|
||||
path,
|
||||
json=json,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
headers=headers,
|
||||
)
|
||||
except httpx.TransportError:
|
||||
if attempt == self.config.max_retry_attempts:
|
||||
|
||||
@@ -18,6 +18,7 @@ class HostAgentConfig:
|
||||
token: str = field(default="", repr=False)
|
||||
enrollment_token: str = field(default="", repr=False)
|
||||
identity_path: Path = Path("tasks/host_identity.json")
|
||||
local_account_path: Path = Path("tasks/host_local_account.json")
|
||||
enrollment_managed: bool = False
|
||||
display_name: str | None = None
|
||||
heartbeat_interval_seconds: float = 30.0
|
||||
@@ -34,7 +35,7 @@ def load_host_agent_config(
|
||||
control_plane_url = (
|
||||
values.get(
|
||||
"HOST_AGENT_CONTROL_PLANE_URL",
|
||||
"http://127.0.0.1:8001",
|
||||
"https://amcp.home.jerryyan.top",
|
||||
)
|
||||
.strip()
|
||||
.rstrip("/")
|
||||
@@ -55,11 +56,11 @@ def load_host_agent_config(
|
||||
identity_path = Path(
|
||||
values.get("HOST_AGENT_IDENTITY_PATH", "tasks/host_identity.json").strip()
|
||||
)
|
||||
if not host_id and not enrollment_token and not identity_path.is_file():
|
||||
raise HostAgentConfigurationError(
|
||||
"explicit Host credentials, an enrollment token, or existing identity state "
|
||||
"is required"
|
||||
)
|
||||
local_account_path = Path(
|
||||
values.get(
|
||||
"HOST_AGENT_LOCAL_ACCOUNT_PATH", "tasks/host_local_account.json"
|
||||
).strip()
|
||||
)
|
||||
|
||||
config = HostAgentConfig(
|
||||
control_plane_url=control_plane_url,
|
||||
@@ -67,6 +68,7 @@ def load_host_agent_config(
|
||||
token=token,
|
||||
enrollment_token=enrollment_token,
|
||||
identity_path=identity_path,
|
||||
local_account_path=local_account_path,
|
||||
enrollment_managed=not bool(host_id),
|
||||
display_name=values.get("HOST_AGENT_DISPLAY_NAME") or None,
|
||||
heartbeat_interval_seconds=_positive_float(
|
||||
|
||||
@@ -3,7 +3,7 @@ from __future__ import annotations
|
||||
from dataclasses import replace
|
||||
|
||||
from host_agent.client import HostAgentEnrollmentClient
|
||||
from host_agent.config import HostAgentConfig, HostAgentConfigurationError
|
||||
from host_agent.config import HostAgentConfig
|
||||
from host_agent.identity import HostIdentityStore
|
||||
|
||||
|
||||
@@ -17,10 +17,6 @@ def resolve_host_identity(
|
||||
return config
|
||||
state = identity_store.load_or_create()
|
||||
if state.host_id is None:
|
||||
if not config.enrollment_token:
|
||||
raise HostAgentConfigurationError(
|
||||
"HOST_AGENT_ENROLLMENT_TOKEN is required to complete enrollment"
|
||||
)
|
||||
response = client.enroll_host(
|
||||
agent_instance_id=state.agent_instance_id,
|
||||
host_token=state.token,
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from hashlib import pbkdf2_hmac
|
||||
from pathlib import Path
|
||||
from secrets import token_bytes
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
PBKDF2_ITERATIONS = 600_000
|
||||
SALT_BYTES = 16
|
||||
|
||||
|
||||
class LocalAccountStateError(RuntimeError):
|
||||
"""Raised when persisted local account state is missing or invalid."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LocalAccountState:
|
||||
username: str
|
||||
salt: bytes = field(repr=False)
|
||||
iterations: int
|
||||
password_hash: bytes = field(repr=False)
|
||||
|
||||
|
||||
class LocalAccountStore:
|
||||
def __init__(self, path: str | Path) -> None:
|
||||
self.path = Path(path)
|
||||
|
||||
def load(self) -> LocalAccountState | None:
|
||||
if not self.path.exists():
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError, json.JSONDecodeError) as exc:
|
||||
raise LocalAccountStateError("local account state is unreadable") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise LocalAccountStateError("local account state must be an object")
|
||||
username = payload.get("username")
|
||||
salt_hex = payload.get("salt")
|
||||
iterations = payload.get("iterations")
|
||||
password_hash_hex = payload.get("password_hash")
|
||||
if (
|
||||
not isinstance(username, str)
|
||||
or not username
|
||||
or not isinstance(salt_hex, str)
|
||||
or not isinstance(iterations, int)
|
||||
or iterations <= 0
|
||||
or not isinstance(password_hash_hex, str)
|
||||
):
|
||||
raise LocalAccountStateError("local account state is invalid")
|
||||
try:
|
||||
salt = bytes.fromhex(salt_hex)
|
||||
password_hash = bytes.fromhex(password_hash_hex)
|
||||
except ValueError as exc:
|
||||
raise LocalAccountStateError("local account state is invalid") from exc
|
||||
return LocalAccountState(
|
||||
username=username,
|
||||
salt=salt,
|
||||
iterations=iterations,
|
||||
password_hash=password_hash,
|
||||
)
|
||||
|
||||
def create(self, username: str, password: str) -> LocalAccountState:
|
||||
if not username.strip():
|
||||
raise ValueError("username must not be empty")
|
||||
if not password:
|
||||
raise ValueError("password must not be empty")
|
||||
salt = token_bytes(SALT_BYTES)
|
||||
state = LocalAccountState(
|
||||
username=username,
|
||||
salt=salt,
|
||||
iterations=PBKDF2_ITERATIONS,
|
||||
password_hash=_derive_hash(password, salt, PBKDF2_ITERATIONS),
|
||||
)
|
||||
self._write(state)
|
||||
return state
|
||||
|
||||
def verify(self, state: LocalAccountState, password: str) -> bool:
|
||||
candidate = _derive_hash(password, state.salt, state.iterations)
|
||||
return hmac.compare_digest(candidate, state.password_hash)
|
||||
|
||||
def _write(self, state: LocalAccountState) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = self.path.with_name(f".{self.path.name}.{uuid4().hex}.tmp")
|
||||
payload = {
|
||||
"username": state.username,
|
||||
"salt": state.salt.hex(),
|
||||
"iterations": state.iterations,
|
||||
"password_hash": state.password_hash.hex(),
|
||||
}
|
||||
try:
|
||||
temporary.write_text(
|
||||
json.dumps(payload, ensure_ascii=True, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
_restrict_permissions(temporary)
|
||||
os.replace(temporary, self.path)
|
||||
_restrict_permissions(self.path)
|
||||
finally:
|
||||
if temporary.exists():
|
||||
temporary.unlink()
|
||||
|
||||
|
||||
def _derive_hash(password: str, salt: bytes, iterations: int) -> bytes:
|
||||
return pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
||||
|
||||
|
||||
def _restrict_permissions(path: Path) -> None:
|
||||
try:
|
||||
path.chmod(0o600)
|
||||
except OSError:
|
||||
return
|
||||
Reference in New Issue
Block a user