fix(claude): implement official Python hook contract

This commit is contained in:
ZacharyZhang-NY committed 2026-07-20 06:54:51 -04:00
1 parent a5a250ac94
commit 202aa1dff7
14 files changed
+2162 -198

No files matched your search

+234
View File
@@ -0,0 +1,234 @@
from __future__ import annotations
from dataclasses import dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
import subprocess # nosec B404
import sys
from threading import Thread
from typing import Any, Mapping
import pytest
from elydora.plugins.claudecode import ClaudeCodePlugin
from elydora.utils import base64url_encode
AGENT_ID = "agent-1"
MISSING = object()
VALID_PRIVATE_KEY = base64url_encode(bytes(range(32)))
@dataclass
class ClaudeFixture:
root_dir: Path
home_dir: Path
project_dir: Path
config_path: Path
agent_dir: Path
guard_path: Path
hook_path: Path
runtime_config_path: Path
private_key_path: Path
plugin: ClaudeCodePlugin
config: dict[str, str]
def install(self) -> None:
self.plugin.install(self.config)
def settings(self) -> dict[str, Any]:
return json.loads(self.config_path.read_text(encoding="utf-8"))
class ElydoraApiHandler(BaseHTTPRequestHandler):
agent_status: Any = "active"
operation_status = 201
requests: list[dict[str, Any]] = []
@classmethod
def reset(cls, status: Any, operation_status: int) -> None:
cls.agent_status = status
cls.operation_status = operation_status
cls.requests = []
def _respond(self, status: int, value: object) -> None:
body = json.dumps(value).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self) -> None:
type(self).requests.append({
"method": "GET",
"path": self.path,
"authorization": self.headers.get("Authorization"),
})
self._respond(200, {"agent": {"status": type(self).agent_status}})
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length)
type(self).requests.append({
"method": "POST",
"path": self.path,
"authorization": self.headers.get("Authorization"),
"raw": raw,
"json": json.loads(raw),
})
self._respond(
type(self).operation_status,
{"operation": {"accepted": True}},
)
def log_message(self, _format: str, *_args: object) -> None:
return
def start_api_server(
*, status: Any = "active", operation_status: int = 201
) -> ThreadingHTTPServer:
ElydoraApiHandler.reset(status, operation_status)
server = ThreadingHTTPServer(("127.0.0.1", 0), ElydoraApiHandler)
Thread(target=server.serve_forever, daemon=True).start()
return server
def server_base_url(server: ThreadingHTTPServer) -> str:
return f"http://127.0.0.1:{server.server_port}"
def write_text(path: Path, source: str, mode: int = 0o600) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(source, encoding="utf-8")
os.chmod(path, mode)
def write_json(path: Path, value: object, mode: int = 0o600) -> None:
source = value if isinstance(value, str) else json.dumps(value, indent=2) + "\n"
write_text(path, source, mode)
def prepare_fixture(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
*,
existing_settings: object = MISSING,
base_url: str = "http://127.0.0.1:9",
config_override: object = None,
) -> ClaudeFixture:
home_dir = tmp_path / "home with spaces and 'quote %CLAUDE_HOOK_EVENT%"
project_dir = tmp_path / "project with spaces"
project_dir.mkdir(parents=True)
monkeypatch.setenv("HOME", str(home_dir))
monkeypatch.setenv("USERPROFILE", str(home_dir))
monkeypatch.chdir(project_dir)
if config_override is MISSING:
monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
config_directory = home_dir / ".claude"
else:
configured = (
str(home_dir / "custom claude")
if config_override is None
else str(config_override)
)
monkeypatch.setenv("CLAUDE_CONFIG_DIR", configured)
config_directory = Path(os.path.abspath(configured))
config_path = config_directory / "settings.json"
agent_dir = home_dir / ".elydora" / AGENT_ID
guard_path = agent_dir / "guard.py"
hook_path = agent_dir / "hook.py"
runtime_config_path = agent_dir / "config.json"
private_key_path = agent_dir / "private.key"
if existing_settings is not MISSING:
write_json(config_path, existing_settings)
return ClaudeFixture(
root_dir=tmp_path,
home_dir=home_dir,
project_dir=project_dir,
config_path=config_path,
agent_dir=agent_dir,
guard_path=guard_path,
hook_path=hook_path,
runtime_config_path=runtime_config_path,
private_key_path=private_key_path,
plugin=ClaudeCodePlugin(),
config={
"org_id": "org-1",
"agent_id": AGENT_ID,
"agent_name": "claudecode",
"private_key": VALID_PRIVATE_KEY,
"kid": "key-1",
"token": "token-1",
"base_url": base_url,
"guard_script_path": str(guard_path),
},
)
def managed_handler(
settings: Mapping[str, Any], event: str
) -> dict[str, Any]:
for group in settings["hooks"][event]:
if set(group) != {"hooks"}:
continue
for handler in group["hooks"]:
if (
set(handler)
== {"type", "command", "args", "timeout", "statusMessage"}
and handler.get("type") == "command"
and handler.get("timeout") == 10
):
return handler
raise AssertionError(f"managed handler for {event!r} not found")
def assert_native_handler(
handler: Mapping[str, Any], script_path: Path, status_message: str
) -> None:
assert set(handler) == {
"type", "command", "args", "timeout", "statusMessage",
}
assert handler["type"] == "command"
assert handler["command"] == sys.executable
assert handler["args"] == [str(script_path)]
assert handler["timeout"] == 10
assert handler["statusMessage"] == status_message
def run_handler(
handler: Mapping[str, Any], payload: bytes, fixture: ClaudeFixture
) -> subprocess.CompletedProcess[bytes]:
return subprocess.run(
[str(handler["command"]), *map(str, handler["args"])],
input=payload,
capture_output=True,
check=False,
cwd=fixture.project_dir,
env={
**os.environ,
"HOME": str(fixture.home_dir),
"USERPROFILE": str(fixture.home_dir),
},
)
def legacy_handler(script_path: Path) -> dict[str, str]:
command = (
f'"{sys.executable}" {script_path}'
if script_path.name == "guard.py"
else str(script_path)
)
return {"type": "command", "command": command}
def symlink_or_skip(
target: Path, link: Path, *, directory: bool = False
) -> None:
try:
link.symlink_to(target, target_is_directory=directory)
except OSError as error:
pytest.skip(f"Symbolic links unavailable: {error}")
+56
View File
@@ -0,0 +1,56 @@
from __future__ import annotations
import os
from pathlib import Path
import subprocess # nosec B404
import pytest
from claudecode_support import prepare_fixture
CLAUDE_BINARY = os.environ.get("ELYDORA_CLAUDE_BINARY")
@pytest.mark.skipif(
not CLAUDE_BINARY,
reason="set ELYDORA_CLAUDE_BINARY to the official Claude Code executable",
)
def test_official_claude_code_accepts_installed_settings(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
environment = {
**os.environ,
"HOME": str(fixture.home_dir),
"USERPROFILE": str(fixture.home_dir),
"CLAUDE_CONFIG_DIR": str(fixture.config_path.parent),
"DISABLE_AUTOUPDATER": "1",
"DISABLE_TELEMETRY": "1",
}
version = subprocess.run(
[str(CLAUDE_BINARY), "--version"],
capture_output=True,
check=False,
cwd=fixture.project_dir,
env=environment,
text=True,
)
doctor = subprocess.run(
[str(CLAUDE_BINARY), "doctor"],
capture_output=True,
check=False,
cwd=fixture.project_dir,
env=environment,
text=True,
)
assert version.returncode == 0, version.stderr
assert "Claude Code" in version.stdout
assert doctor.returncode == 0, doctor.stderr
output = (doctor.stdout + "\n" + doctor.stderr).lower()
assert "invalid settings" not in output
assert "settings validation" not in output
assert "failed to parse" not in output
+451
View File
@@ -0,0 +1,451 @@
from __future__ import annotations
import json
import os
from pathlib import Path
import subprocess # nosec B404
import sys
import pytest
from claudecode_support import (
AGENT_ID,
MISSING,
VALID_PRIVATE_KEY,
assert_native_handler,
legacy_handler,
managed_handler,
prepare_fixture,
write_json,
write_text,
)
from elydora.plugins.claudecode_contract import AUDIT_STATUS, GUARD_STATUS
from elydora.plugins.registry import SUPPORTED_AGENTS
def assert_managed_triple(settings: dict, fixture: object) -> None:
assert_native_handler(
managed_handler(settings, "PreToolUse"),
fixture.guard_path,
GUARD_STATUS,
)
assert_native_handler(
managed_handler(settings, "PostToolUse"),
fixture.hook_path,
AUDIT_STATUS,
)
assert_native_handler(
managed_handler(settings, "PostToolUseFailure"),
fixture.hook_path,
AUDIT_STATUS,
)
def test_claude_code_is_registered_with_the_official_contract() -> None:
assert SUPPORTED_AGENTS["claudecode"] == {
"name": "Claude Code",
"hook_event": "PreToolUse/PostToolUse/PostToolUseFailure",
"config_path": "$CLAUDE_CONFIG_DIR/settings.json",
}
def test_install_preserves_settings_and_writes_one_exact_triple(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
capsys: pytest.CaptureFixture[str],
) -> None:
existing = {
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"model": "sonnet",
"disableAllHooks": False,
"hooks": {
"Notification": [{
"matcher": "permission_prompt",
"hooks": [{
"type": "http",
"url": "https://example.test/hook",
"timeout": 1,
}],
}],
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "existing-command",
"timeout": 5,
}],
}],
},
}
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings=existing
)
fixture.install()
output = capsys.readouterr().out
assert "run /hooks and claude doctor" in output
installed = fixture.settings()
assert installed["model"] == "sonnet"
assert installed["hooks"]["Notification"] == existing["hooks"]["Notification"]
assert installed["hooks"]["PreToolUse"][0] == existing["hooks"]["PreToolUse"][0]
assert_managed_triple(installed, fixture)
first_source = fixture.config_path.read_text(encoding="utf-8")
fixture.install()
assert fixture.config_path.read_text(encoding="utf-8") == first_source
@pytest.mark.parametrize(
("config_override", "expected_kind"),
[
(None, "custom"),
(MISSING, "default"),
("relative claude", "relative"),
("", "cwd"),
("~", "literal_tilde"),
],
)
def test_claude_config_dir_matches_native_path_resolution(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
config_override: object,
expected_kind: str,
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, config_override=config_override
)
fixture.install()
expected = {
"custom": fixture.home_dir / "custom claude" / "settings.json",
"default": fixture.home_dir / ".claude" / "settings.json",
"relative": fixture.project_dir / "relative claude" / "settings.json",
"cwd": fixture.project_dir / "settings.json",
"literal_tilde": fixture.project_dir / "~" / "settings.json",
}[expected_kind]
assert fixture.config_path == expected
assert expected.is_file()
def test_malformed_settings_fail_before_runtime_creation(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings="{ malformed"
)
with pytest.raises(ValueError, match="parse Claude Code user settings"):
fixture.install()
assert fixture.config_path.read_text(encoding="utf-8") == "{ malformed"
assert not fixture.agent_dir.exists()
def test_documented_handler_types_and_fields_are_preserved(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
user_hooks = {
"SessionStart": [{"hooks": [{
"type": "prompt",
"prompt": "Review context",
"model": "haiku",
"continueOnBlock": True,
"if": "always",
"once": False,
"statusMessage": "Reviewing",
"timeout": 0.5,
}]}],
"PreToolUse": [{"matcher": "Bash", "hooks": [{
"type": "command",
"command": "user-command",
"args": ["--safe"],
"async": False,
"asyncRewake": True,
"shell": "powershell",
}]}],
"Stop": [{"hooks": [{
"type": "agent", "prompt": "Verify completion", "model": "sonnet",
}]}],
"Notification": [{"hooks": [{
"type": "http",
"url": "https://example.test/hook",
"headers": {"Authorization": "Bearer ${TOKEN}"},
"allowedEnvVars": ["TOKEN"],
}]}],
"PostToolUse": [{"hooks": [{
"type": "mcp_tool",
"server": "audit",
"tool": "record",
"input": {"source": "claude"},
}]}],
}
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings={"hooks": user_hooks}
)
fixture.install()
installed = fixture.settings()["hooks"]
for event, groups in user_hooks.items():
assert installed[event][0] == groups[0]
INVALID_SETTINGS = [
('{"hooks":{},"hooks":{}}', 'duplicate field "hooks"'),
(json.dumps({"disableAllHooks": "yes"}), "must be a boolean"),
(json.dumps({"hooks": None}), 'field "hooks" must be an object'),
(json.dumps({"hooks": {"MadeUp": []}}), "unsupported hook event"),
(json.dumps({"hooks": {"PreToolUse": None}}), "must be an array"),
(json.dumps({"hooks": {"PreToolUse": [None]}}), "must be an object"),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [], "label": "x"}]}}),
'unsupported field "label"',
),
(
json.dumps({"hooks": {"PreToolUse": [{"matcher": 1, "hooks": []}]}}),
"matcher must be a string",
),
(json.dumps({"hooks": {"PreToolUse": [{}]}}), "hooks array"),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [None]}]}}),
"handler",
),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [{"type": "file"}]}]}}),
"unsupported type",
),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [{
"type": "command", "command": "x", "invented": True,
}]}]}}),
'unsupported field "invented"',
),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [{
"type": "command", "command": "",
}]}]}}),
"non-empty string",
),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [{
"type": "command", "command": "x", "args": [1],
}]}]}}),
"array of strings",
),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [{
"type": "command", "command": "x", "timeout": 0,
}]}]}}),
"positive finite number",
),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [{
"type": "http", "url": "https://example.test", "headers": {"A": 1},
}]}]}}),
"map names to strings",
),
(
json.dumps({"hooks": {"PreToolUse": [{"hooks": [{
"type": "mcp_tool", "server": "s", "tool": "t", "input": [],
}]}]}}),
"must be an object",
),
]
@pytest.mark.parametrize(("source", "pattern"), INVALID_SETTINGS)
def test_invalid_official_hook_shapes_fail_before_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
source: str,
pattern: str,
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings=source
)
with pytest.raises(ValueError, match=pattern):
fixture.install()
assert fixture.config_path.read_text(encoding="utf-8") == source
assert not fixture.agent_dir.exists()
def test_disabled_user_hooks_block_installation(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings={"disableAllHooks": True}
)
with pytest.raises(ValueError, match="disabled by disableAllHooks"):
fixture.install()
assert not fixture.agent_dir.exists()
assert fixture.settings() == {"disableAllHooks": True}
def test_exact_legacy_hooks_migrate_and_lookalikes_survive_uninstall(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
lookalike = legacy_handler(fixture.guard_path)
lookalike["command"] += " --inspect"
write_json(fixture.config_path, {
"hooks": {
"PreToolUse": [
{"hooks": [legacy_handler(fixture.guard_path)]},
{"hooks": [lookalike]},
],
"PostToolUse": [{"hooks": [legacy_handler(fixture.hook_path)]}],
}
})
fixture.install()
settings = fixture.settings()
assert_managed_triple(settings, fixture)
assert any(
group["hooks"][0].get("command") == lookalike["command"]
for group in settings["hooks"]["PreToolUse"]
)
settings["hooks"]["PreToolUse"][-1]["hooks"].append({
"type": "command", "command": "user-command", "timeout": 5,
})
write_json(fixture.config_path, settings)
fixture.plugin.uninstall(AGENT_ID)
remaining = fixture.settings()["hooks"]
assert remaining["PreToolUse"] == [
{"hooks": [lookalike]},
{"hooks": [{"type": "command", "command": "user-command", "timeout": 5}]},
]
assert "PostToolUse" not in remaining
assert "PostToolUseFailure" not in remaining
def test_uninstall_preserves_user_settings_and_removes_managed_file(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
user = prepare_fixture(
monkeypatch,
tmp_path / "user",
existing_settings={"model": "sonnet", "hooks": {"Notification": []}},
)
user.install()
user.plugin.uninstall(AGENT_ID)
assert user.settings() == {
"model": "sonnet", "hooks": {"Notification": []},
}
managed = prepare_fixture(monkeypatch, tmp_path / "managed")
managed.install()
managed.plugin.uninstall(AGENT_ID)
assert not managed.config_path.exists()
def test_status_requires_enabled_unique_triple_and_strict_runtime(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
assert fixture.plugin.status()["installed"] is True
settings = fixture.settings()
del settings["hooks"]["PostToolUseFailure"]
write_json(fixture.config_path, settings)
assert fixture.plugin.status()["installed"] is False
fixture.install()
settings = fixture.settings()
settings["hooks"]["PostToolUseFailure"].append(
settings["hooks"]["PostToolUseFailure"][-1]
)
write_json(fixture.config_path, settings)
assert fixture.plugin.status()["installed"] is False
fixture.install()
settings = fixture.settings()
settings["disableAllHooks"] = True
write_json(fixture.config_path, settings)
assert fixture.plugin.status()["installed"] is False
settings["disableAllHooks"] = False
write_json(fixture.config_path, settings)
write_text(fixture.private_key_path, "invalid")
with pytest.raises(ValueError, match="canonical 32-byte"):
fixture.plugin.status()
def test_project_and_local_settings_remain_unchanged(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
project_settings = fixture.project_dir / ".claude" / "settings.json"
local_settings = fixture.project_dir / ".claude" / "settings.local.json"
project_source = '{"hooks":{"PreToolUse":[]}}\n'
local_source = '{"model":"haiku"}\n'
write_text(project_settings, project_source)
write_text(local_settings, local_source)
fixture.install()
assert project_settings.read_text(encoding="utf-8") == project_source
assert local_settings.read_text(encoding="utf-8") == local_source
def test_cli_install_status_and_uninstall_end_to_end(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
key_path = tmp_path / "install-private.key"
token_path = tmp_path / "install-token.txt"
write_text(key_path, VALID_PRIVATE_KEY + "\n")
write_text(token_path, "token-1\n")
environment = {
**os.environ,
"HOME": str(fixture.home_dir),
"USERPROFILE": str(fixture.home_dir),
"CLAUDE_CONFIG_DIR": str(fixture.config_path.parent),
}
root = Path(__file__).parents[1]
base = [sys.executable, "-m", "elydora.cli"]
install = subprocess.run(
[
*base, "install", "--agent", "claudecode",
"--org_id", "org-1", "--agent_id", AGENT_ID,
"--private_key_file", str(key_path), "--token_file", str(token_path),
"--kid", "key-1", "--base_url", "http://127.0.0.1:9",
],
capture_output=True,
check=False,
cwd=root,
env=environment,
text=True,
)
assert install.returncode == 0, install.stderr
assert "PostToolUseFailure hooks installed" in install.stdout
assert_managed_triple(fixture.settings(), fixture)
status = subprocess.run(
[*base, "status"], capture_output=True, check=False,
cwd=root, env=environment, text=True,
)
assert status.returncode == 0, status.stderr
assert "Claude Code" in status.stdout
assert "[installed]" in status.stdout
uninstall = subprocess.run(
[*base, "uninstall", "--agent", "claudecode", "--agent_id", AGENT_ID],
capture_output=True,
check=False,
cwd=root,
env=environment,
text=True,
)
assert uninstall.returncode == 0, uninstall.stderr
assert not fixture.config_path.exists()
assert not fixture.agent_dir.exists()
+146
View File
@@ -0,0 +1,146 @@
from __future__ import annotations
import json
from pathlib import Path
import pytest
from claudecode_support import (
ElydoraApiHandler,
managed_handler,
prepare_fixture,
run_handler,
server_base_url,
start_api_server,
)
def official_payload(event: str, **overrides: object) -> dict[str, object]:
value: dict[str, object] = {
"session_id": "session-1",
"prompt_id": "302d811d-0d17-41ad-a359-d2cb618fd42b",
"transcript_path": "/tmp/session-1.jsonl",
"cwd": "/tmp/project",
"permission_mode": "default",
"effort": {"level": "high"},
"hook_event_name": event,
"tool_name": "Bash",
"tool_input": {"command": "pytest", "description": "Run tests"},
"tool_use_id": "toolu_01ABC123",
}
value.update(overrides)
return value
def encoded(value: object) -> bytes:
return json.dumps(value, separators=(",", ":")).encode()
def test_runtimes_preserve_success_and_failure_payloads(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
server = start_api_server()
try:
fixture = prepare_fixture(
monkeypatch, tmp_path, base_url=server_base_url(server)
)
fixture.install()
settings = fixture.settings()
guard = managed_handler(settings, "PreToolUse")
success_audit = managed_handler(settings, "PostToolUse")
failure_audit = managed_handler(settings, "PostToolUseFailure")
pre = official_payload("PreToolUse")
guard_result = run_handler(guard, encoded(pre), fixture)
success = official_payload(
"PostToolUse",
tool_response={
"stdout": "tests passed",
"stderr": "",
"interrupted": False,
"isImage": False,
},
)
success_result = run_handler(success_audit, encoded(success), fixture)
failure = official_payload(
"PostToolUseFailure",
error="Command exited with non-zero status code 1",
is_interrupt=False,
duration_ms=4187,
)
failure_result = run_handler(failure_audit, encoded(failure), fixture)
finally:
server.shutdown()
server.server_close()
assert guard_result.returncode == 0
assert guard_result.stdout == b""
assert guard_result.stderr == b""
assert success_result.returncode == 0
assert failure_result.returncode == 0
assert [request["method"] for request in ElydoraApiHandler.requests] == [
"GET", "POST", "POST",
]
success_operation = ElydoraApiHandler.requests[1]["json"]
failure_operation = ElydoraApiHandler.requests[2]["json"]
assert success_operation["payload"] == success
assert failure_operation["payload"] == failure
assert success_operation["subject"] == {"session_id": "session-1"}
assert success_operation["action"] == {"tool": "Bash"}
assert ElydoraApiHandler.requests[1]["authorization"] == "Bearer token-1"
assert failure_operation["prev_chain_hash"] == success_operation["chain_hash"]
@pytest.mark.parametrize("status", ["frozen", "revoked"])
def test_guard_returns_official_exit_code_two(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
status: str,
) -> None:
server = start_api_server(status=status)
try:
fixture = prepare_fixture(
monkeypatch, tmp_path, base_url=server_base_url(server)
)
fixture.install()
result = run_handler(
managed_handler(fixture.settings(), "PreToolUse"),
encoded(official_payload("PreToolUse")),
fixture,
)
finally:
server.shutdown()
server.server_close()
assert result.returncode == 2
assert result.stdout == b""
assert status.encode() in result.stderr.lower()
assert b"Tool execution blocked" in result.stderr
def test_runtime_failures_are_observable_and_fail_open(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
settings = fixture.settings()
guard = managed_handler(settings, "PreToolUse")
audit = managed_handler(settings, "PostToolUse")
guard_result = run_handler(
guard, encoded(official_payload("PreToolUse")), fixture
)
audit_result = run_handler(
audit,
encoded(official_payload("PostToolUse", tool_response={"stdout": ""})),
fixture,
)
malformed = run_handler(audit, b"{ malformed", fixture)
assert guard_result.returncode == 0
assert b"Failed to resolve agent status" in guard_result.stderr
assert audit_result.returncode == 0
assert malformed.returncode == 0
log = (fixture.agent_dir / "error.log").read_text(encoding="utf-8")
assert "invalid JSON" in log
assert "refused" in log.lower() or "urlopen" in log.lower()
+283
View File
@@ -0,0 +1,283 @@
from __future__ import annotations
import os
from pathlib import Path
import shutil
import subprocess # nosec B404
import sys
import pytest
from claudecode_support import (
AGENT_ID,
VALID_PRIVATE_KEY,
prepare_fixture,
symlink_or_skip,
write_json,
write_text,
)
from elydora.plugins import _transaction, claudecode_installation
from elydora.plugins.claudecode_contract import (
AUDIT_STATUS,
GUARD_STATUS,
build_claude_group,
remove_managed_claude_hooks,
render_claude_document,
)
from elydora.plugins.claudecode_io import read_claude_document
from elydora.utils import base64url_encode
RUNTIME_NAMES = ("guard.py", "config.json", "private.key", "hook.py")
def prepare_installation(fixture: object) -> list[_transaction.FileChange]:
document = read_claude_document()
paths = claudecode_installation.preflight_claude_installation(
fixture.config, document
)
cleaned = remove_managed_claude_hooks(document.hooks)
hooks = {
**cleaned,
"PreToolUse": [
*cleaned.get("PreToolUse", []),
build_claude_group(paths.guard_path, GUARD_STATUS),
],
"PostToolUse": [
*cleaned.get("PostToolUse", []),
build_claude_group(paths.audit_path, AUDIT_STATUS),
],
"PostToolUseFailure": [
*cleaned.get("PostToolUseFailure", []),
build_claude_group(paths.audit_path, AUDIT_STATUS),
],
}
return claudecode_installation.prepare_claude_installation(
fixture.config, paths, render_claude_document(document, hooks)
)
def assert_no_transaction_files(root: Path) -> None:
assert not list(root.rglob("*.tmp"))
assert not list(root.rglob("*.rollback"))
def test_transaction_rolls_back_all_five_files(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
original = '{"model":"sonnet"}\n'
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings=original
)
real_replace = _transaction.os.replace
failed = False
def fail_settings_once(source: str, destination: str) -> None:
nonlocal failed
if os.path.abspath(destination) == str(fixture.config_path) and not failed:
failed = True
raise OSError("injected Claude settings failure")
real_replace(source, destination)
monkeypatch.setattr(_transaction.os, "replace", fail_settings_once)
with pytest.raises(OSError, match="injected Claude settings failure"):
fixture.install()
assert fixture.config_path.read_text(encoding="utf-8") == original
for name in RUNTIME_NAMES:
assert not (fixture.agent_dir / name).exists()
assert_no_transaction_files(fixture.home_dir)
def test_concurrent_settings_change_is_detected_before_runtime_commits(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(
monkeypatch, tmp_path, existing_settings={"model": "sonnet"}
)
changes = prepare_installation(fixture)
concurrent = '{"model":"opus"}\n'
fixture.config_path.write_text(concurrent, encoding="utf-8")
with pytest.raises(OSError, match="changed during installation"):
claudecode_installation.commit_claude_installation(changes)
assert fixture.config_path.read_text(encoding="utf-8") == concurrent
for name in RUNTIME_NAMES:
assert not (fixture.agent_dir / name).exists()
assert_no_transaction_files(fixture.home_dir)
def test_recovery_preserves_original_after_committed_runtime_changes(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
original = fixture.runtime_config_path.read_text(encoding="utf-8")
fixture.config["org_id"] = "org-updated"
fixture.config["private_key"] = base64url_encode(bytes(range(31, -1, -1)))
changes = prepare_installation(fixture)
real_replace = _transaction.os.replace
calls = 0
def change_first_then_fail(source: str, destination: str) -> None:
nonlocal calls
calls += 1
if calls == 1:
real_replace(source, destination)
write_text(Path(destination), "external change\n")
return
raise OSError("injected later commit failure")
monkeypatch.setattr(_transaction.os, "replace", change_first_then_fail)
with pytest.raises(OSError, match="original content preserved at"):
claudecode_installation.commit_claude_installation(changes)
assert fixture.runtime_config_path.read_text(encoding="utf-8") == "external change\n"
rollbacks = list(fixture.agent_dir.glob(".config.json.*.rollback"))
assert len(rollbacks) == 1
assert rollbacks[0].read_text(encoding="utf-8") == original
@pytest.mark.parametrize("runtime_name", [
"private.key", "guard.py", "hook.py", "chain-state.json",
"status-cache.json", "error.log",
])
def test_orphan_runtime_artifacts_fail_before_settings_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
runtime_name: str,
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
artifact = fixture.agent_dir / runtime_name
write_text(artifact, "orphan\n")
with pytest.raises(ValueError, match="identity cannot be verified"):
fixture.install()
assert artifact.read_text(encoding="utf-8") == "orphan\n"
assert not fixture.config_path.exists()
def test_mismatched_runtime_identity_fails_before_writes(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
write_json(fixture.runtime_config_path, {
"agent_id": "another-agent", "agent_name": "claudecode",
})
original = fixture.runtime_config_path.read_text(encoding="utf-8")
with pytest.raises(ValueError, match="identity does not match"):
fixture.install()
assert fixture.runtime_config_path.read_text(encoding="utf-8") == original
assert not fixture.config_path.exists()
@pytest.mark.parametrize("kind", ["configuration", "settings", "runtime"])
def test_linked_configuration_and_runtime_paths_are_rejected(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
kind: str,
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
target = tmp_path / f"{kind}-target"
if kind == "settings":
write_text(target, "{}\n")
fixture.config_path.parent.mkdir(parents=True)
symlink_or_skip(target, fixture.config_path)
else:
target.mkdir()
link = (
fixture.config_path.parent
if kind == "configuration"
else fixture.agent_dir.parent
)
if kind == "runtime" and link.exists():
shutil.rmtree(link)
link.parent.mkdir(parents=True, exist_ok=True)
symlink_or_skip(target, link, directory=True)
with pytest.raises(OSError, match="physical (file|directory)"):
fixture.install()
@pytest.mark.parametrize(
("field", "value", "pattern"),
[
("agent_name", "codex", "requires agent_name claudecode"),
("agent_id", "../escape", "Invalid agent ID"),
("private_key", "invalid", "canonical 32-byte"),
("token", "", "non-empty string"),
("base_url", "https://api.elydora.com?q=1", "query parameters"),
("guard_script_path", "outside", "managed agent directory"),
],
)
def test_install_validates_runtime_inputs_before_writes(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
field: str,
value: str,
pattern: str,
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.config[field] = value
with pytest.raises(ValueError, match=pattern):
fixture.install()
assert not fixture.config_path.exists()
assert not fixture.agent_dir.exists()
def test_status_surfaces_malformed_runtime_metadata(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
fixture.runtime_config_path.write_text("{ malformed", encoding="utf-8")
with pytest.raises(ValueError, match="parse Elydora runtime config"):
fixture.plugin.status()
def test_installation_leaves_no_transaction_artifacts(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
fixture = prepare_fixture(monkeypatch, tmp_path)
fixture.install()
assert_no_transaction_files(fixture.home_dir)
def test_cli_preflight_preserves_malformed_settings(
tmp_path: Path,
) -> None:
home_dir = tmp_path / "cli-home"
settings_path = home_dir / ".claude" / "settings.json"
key_path = tmp_path / "private.key"
write_text(settings_path, "{ malformed")
write_text(key_path, VALID_PRIVATE_KEY)
environment = {**os.environ, "HOME": str(home_dir), "USERPROFILE": str(home_dir)}
environment.pop("CLAUDE_CONFIG_DIR", None)
result = subprocess.run(
[
sys.executable, "-m", "elydora.cli", "install",
"--agent", "claudecode", "--org_id", "org-1",
"--agent_id", AGENT_ID, "--private_key_file", str(key_path),
"--kid", "key-1", "--base_url", "https://api.elydora.com",
],
capture_output=True,
check=False,
cwd=Path(__file__).parents[1],
env=environment,
text=True,
)
assert result.returncode == 1
assert "parse Claude Code user settings" in result.stderr
assert settings_path.read_text(encoding="utf-8") == "{ malformed"
assert not (home_dir / ".elydora").exists()
-2
View File
@@ -15,7 +15,6 @@ from elydora._cli_secrets import (
)
from elydora.plugins._file_io import write_text_atomic
from elydora.plugins import (
claudecode,
copilot,
cursor,
gemini,
@@ -374,7 +373,6 @@ def test_atomic_secret_write_preserves_existing_file_on_replace_failure(
@pytest.mark.parametrize(
"module, plugin_type, agent_name",
[
(claudecode, claudecode.ClaudeCodePlugin, "claudecode"),
(copilot, copilot.CopilotPlugin, "copilot"),
(cursor, cursor.CursorPlugin, "cursor"),
(gemini, gemini.GeminiPlugin, "gemini"),
+1 -2
View File
@@ -4,7 +4,6 @@ from collections.abc import Callable
import pytest
from elydora.plugins.claudecode import _is_elydora_hook as is_claude_hook
from elydora.plugins.gemini import _is_elydora_hook as is_gemini_hook
from elydora.plugins.letta import _is_elydora_hook as is_letta_hook
@@ -12,7 +11,7 @@ from elydora.plugins.letta import _is_elydora_hook as is_letta_hook
HookDetector = Callable[[dict, str], bool]
@pytest.mark.parametrize("detector", [is_claude_hook, is_gemini_hook, is_letta_hook])
@pytest.mark.parametrize("detector", [is_gemini_hook, is_letta_hook])
def test_hook_detection_handles_only_string_commands(detector: HookDetector) -> None:
assert detector({"command": 42}, "") is False
assert detector({"hooks": [{"command": None}]}, "") is False