from __future__ import annotations import os import pytest from host_agent.identity import ( HostIdentityStateError, HostIdentityStore, ) def test_identity_store_persists_pending_and_completed_state(tmp_path) -> None: path = tmp_path / "state" / "host_identity.json" store = HostIdentityStore(path) pending = store.load_or_create() assert pending.host_id is None assert len(pending.token) >= 32 assert "token=" not in repr(pending) assert store.load() == pending completed = store.complete(pending, "host-cloud-a") assert completed.host_id == "host-cloud-a" assert store.load() == completed assert "host-cloud-a" in path.read_text(encoding="utf-8") if os.name != "nt": assert path.stat().st_mode & 0o777 == 0o600 def test_identity_store_rejects_invalid_or_changed_state(tmp_path) -> None: path = tmp_path / "host_identity.json" path.write_text('{"agent_instance_id":"a"}', encoding="utf-8") store = HostIdentityStore(path) with pytest.raises(HostIdentityStateError): store.load() path.unlink() pending = store.load_or_create() path.write_text( '{"agent_instance_id":"other","token":"' + ("x" * 40) + '"}', encoding="utf-8", ) with pytest.raises(HostIdentityStateError, match="changed"): store.complete(pending, "host-a")