pakem-cli 0.0.0-stage → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +280 -0
- package/LICENSE +21 -0
- package/README-ID.md +666 -0
- package/README.md +665 -2
- package/SKILL.md +264 -0
- package/adapters/git-worktree/v1/README.md +17 -0
- package/adapters/identity/v1/README.md +26 -0
- package/adapters/mcp/v1/README.md +56 -0
- package/adapters/storage-sqlite/v1/README.md +5 -0
- package/assets/banner.svg +275 -0
- package/assets/divider.svg +82 -0
- package/assets/footer.svg +174 -0
- package/assets/templates/BUG-HISTORY.md +18 -0
- package/assets/templates/CONTEXT.md +26 -0
- package/assets/templates/DECISIONS.md +8 -0
- package/assets/templates/MODULE-MAP.md +14 -0
- package/assets/templates/POLICY.json +15 -0
- package/assets/templates/PROJECT.md +42 -0
- package/conformance/v1/README.md +15 -0
- package/coordination/v1/README.md +14 -0
- package/coordination/v1/board.schema.json +59 -0
- package/coordination/v1/event.schema.json +26 -0
- package/coordination/v1/status.schema.json +49 -0
- package/evals/README.md +63 -0
- package/evals/evals.json +276 -0
- package/identity/v1/README.md +14 -0
- package/identity/v1/agent-identity.schema.json +95 -0
- package/identity/v1/identity-registry.schema.json +29 -0
- package/identity/v1/signed-payload.schema.json +42 -0
- package/intelligence/v1/README.md +19 -0
- package/intelligence/v1/dependency-graph.schema.json +82 -0
- package/intelligence/v1/impact-analysis.schema.json +51 -0
- package/intelligence/v1/reconciliation.schema.json +156 -0
- package/npm/bin/pakem.js +272 -0
- package/npm/check-version.js +26 -0
- package/package.json +58 -4
- package/policy/v1/README.md +15 -0
- package/policy/v1/policy.schema.json +20 -0
- package/protocol/v1/README.md +68 -0
- package/protocol/v1/capabilities.schema.json +17 -0
- package/protocol/v1/event.schema.json +114 -0
- package/protocol/v1/session.schema.json +51 -0
- package/references/artifacts.md +96 -0
- package/references/conventions.md +83 -0
- package/references/reviews.md +44 -0
- package/runtime/v1/README.md +21 -0
- package/runtime/v1/approval.schema.json +100 -0
- package/runtime/v1/checkpoint.schema.json +17 -0
- package/runtime/v1/hook-decision.schema.json +34 -0
- package/runtime/v1/hook-payload.schema.json +12 -0
- package/runtime/v1/task-evidence.schema.json +38 -0
- package/runtime/v1/work-report.schema.json +123 -0
- package/runtime/v1/workflow.schema.json +21 -0
- package/scripts/__pycache__/pakem.cpython-312.pyc +0 -0
- package/scripts/pakem.py +4911 -0
- package/scripts/pakem_core/__init__.py +3 -0
- package/scripts/pakem_core/__pycache__/__init__.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/coordination.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/git_worktree.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/identity.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/intelligence.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/mcp_server.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/protocol.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/reconcile.cpython-312.pyc +0 -0
- package/scripts/pakem_core/__pycache__/runtime.cpython-312.pyc +0 -0
- package/scripts/pakem_core/coordination.py +977 -0
- package/scripts/pakem_core/git_worktree.py +265 -0
- package/scripts/pakem_core/identity.py +494 -0
- package/scripts/pakem_core/intelligence.py +684 -0
- package/scripts/pakem_core/mcp_server.py +308 -0
- package/scripts/pakem_core/protocol.py +61 -0
- package/scripts/pakem_core/reconcile.py +119 -0
- package/scripts/pakem_core/runtime.py +457 -0
- package/scripts/run_evals.py +289 -0
- package/storage/v1/README.md +14 -0
- package/storage/v1/team-storage.schema.json +27 -0
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
"""Ed25519 identities and signed Pakem attestations.
|
|
2
|
+
|
|
3
|
+
Private keys live outside the project in the user's config directory. The
|
|
4
|
+
project stores only public keys and revocation metadata. This module does not
|
|
5
|
+
provide transport authentication by itself; a trusted host must bind verified
|
|
6
|
+
identity claims to the actual caller.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import contextlib
|
|
12
|
+
import functools
|
|
13
|
+
import hashlib
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import tempfile
|
|
18
|
+
import time
|
|
19
|
+
import uuid
|
|
20
|
+
from datetime import datetime, timedelta, timezone
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
FORMAT = "pakem.signed-payload.v1"
|
|
25
|
+
ALGORITHM = "Ed25519"
|
|
26
|
+
_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _crypto():
|
|
30
|
+
try:
|
|
31
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
|
32
|
+
from cryptography.hazmat.primitives import serialization
|
|
33
|
+
except ImportError as exc: # pragma: no cover - environment dependent
|
|
34
|
+
raise RuntimeError("Ed25519 requires the 'cryptography' package; install it with: python -m pip install cryptography") from exc
|
|
35
|
+
return Ed25519PrivateKey, Ed25519PublicKey, serialization
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _safe_id(value: str) -> str:
|
|
39
|
+
if not isinstance(value, str) or not _ID_RE.fullmatch(value) or value in {".", ".."}:
|
|
40
|
+
raise ValueError("agent ID is not valid")
|
|
41
|
+
return value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _b64(data: bytes) -> str:
|
|
45
|
+
return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _unb64(value: str) -> bytes:
|
|
49
|
+
if not isinstance(value, str) or len(value) > 16384:
|
|
50
|
+
raise ValueError("base64 value is not valid")
|
|
51
|
+
try:
|
|
52
|
+
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
|
53
|
+
except Exception as exc:
|
|
54
|
+
raise ValueError("base64 value is not valid") from exc
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _canonical(value: Any) -> bytes:
|
|
58
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _stamp() -> str:
|
|
62
|
+
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@contextlib.contextmanager
|
|
66
|
+
def _registry_lock(root: str | Path):
|
|
67
|
+
directory = Path(root).resolve() / ".pakem" / "identity"
|
|
68
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
lock_path = directory / ".registry.lock"
|
|
70
|
+
if lock_path.is_symlink():
|
|
71
|
+
raise ValueError("identity registry lock must not be a symlink")
|
|
72
|
+
fd = os.open(lock_path, os.O_CREAT | os.O_RDWR, 0o600)
|
|
73
|
+
stream = os.fdopen(fd, "r+b", buffering=0)
|
|
74
|
+
try:
|
|
75
|
+
try:
|
|
76
|
+
os.chmod(lock_path, 0o600)
|
|
77
|
+
except OSError:
|
|
78
|
+
pass
|
|
79
|
+
if os.name == "nt":
|
|
80
|
+
import msvcrt
|
|
81
|
+
stream.seek(0)
|
|
82
|
+
if stream.read(1) == b"":
|
|
83
|
+
stream.seek(0)
|
|
84
|
+
stream.write(b"0")
|
|
85
|
+
stream.flush()
|
|
86
|
+
stream.seek(0)
|
|
87
|
+
while True:
|
|
88
|
+
try:
|
|
89
|
+
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
|
|
90
|
+
break
|
|
91
|
+
except OSError:
|
|
92
|
+
time.sleep(0.05)
|
|
93
|
+
try:
|
|
94
|
+
yield
|
|
95
|
+
finally:
|
|
96
|
+
stream.seek(0)
|
|
97
|
+
msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
|
|
98
|
+
else:
|
|
99
|
+
import fcntl
|
|
100
|
+
fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
|
|
101
|
+
try:
|
|
102
|
+
yield
|
|
103
|
+
finally:
|
|
104
|
+
fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
|
|
105
|
+
finally:
|
|
106
|
+
stream.close()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _locked_registry(function):
|
|
110
|
+
@functools.wraps(function)
|
|
111
|
+
def wrapped(root, *args, **kwargs):
|
|
112
|
+
with _registry_lock(root):
|
|
113
|
+
return function(root, *args, **kwargs)
|
|
114
|
+
return wrapped
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def registry_path(root: str | Path) -> Path:
|
|
118
|
+
return Path(root).resolve() / ".pakem" / "identity" / "registry.json"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _project_key_namespace(root: str | Path) -> str:
|
|
122
|
+
canonical = str(Path(root).resolve()).encode("utf-8", errors="surrogatepass")
|
|
123
|
+
return hashlib.sha256(canonical).hexdigest()[:24]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def private_key_path(root: str | Path, agent_id: str, key_id: str | None = None) -> Path:
|
|
127
|
+
agent_id = _safe_id(agent_id)
|
|
128
|
+
if key_id is not None and (not isinstance(key_id, str) or not re.fullmatch(r"[a-f0-9]{16}", key_id)):
|
|
129
|
+
raise ValueError("key ID is not valid")
|
|
130
|
+
if os.name == "nt":
|
|
131
|
+
base = Path(os.environ.get("APPDATA") or (Path.home() / "AppData" / "Roaming")) / "Pakem"
|
|
132
|
+
else:
|
|
133
|
+
base = Path(os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config")) / "pakem"
|
|
134
|
+
suffix = f".{key_id}" if key_id else ""
|
|
135
|
+
return base / "identities" / _project_key_namespace(root) / f"{agent_id}{suffix}.ed25519"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _atomic_write(path: Path, data: bytes, mode: int = 0o600) -> None:
|
|
139
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
try:
|
|
141
|
+
os.chmod(path.parent, 0o700)
|
|
142
|
+
except OSError:
|
|
143
|
+
pass
|
|
144
|
+
fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=str(path.parent))
|
|
145
|
+
try:
|
|
146
|
+
try:
|
|
147
|
+
os.fchmod(fd, mode)
|
|
148
|
+
except OSError:
|
|
149
|
+
pass
|
|
150
|
+
with os.fdopen(fd, "wb") as stream:
|
|
151
|
+
stream.write(data)
|
|
152
|
+
stream.flush()
|
|
153
|
+
os.fsync(stream.fileno())
|
|
154
|
+
os.replace(tmp, path)
|
|
155
|
+
try:
|
|
156
|
+
os.chmod(path, mode)
|
|
157
|
+
except OSError:
|
|
158
|
+
pass
|
|
159
|
+
finally:
|
|
160
|
+
if os.path.exists(tmp):
|
|
161
|
+
os.unlink(tmp)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _load_registry(root: str | Path, create: bool = False) -> dict:
|
|
165
|
+
path = registry_path(root)
|
|
166
|
+
if path.is_symlink():
|
|
167
|
+
raise ValueError("identity registry must not be a symlink")
|
|
168
|
+
if not path.exists():
|
|
169
|
+
if not create:
|
|
170
|
+
return {"schemaVersion": 1, "agents": {}}
|
|
171
|
+
registry = {"schemaVersion": 1, "updatedAt": _stamp(), "agents": {}}
|
|
172
|
+
_save_registry(root, registry)
|
|
173
|
+
return registry
|
|
174
|
+
try:
|
|
175
|
+
registry = json.loads(path.read_text(encoding="utf-8"))
|
|
176
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
177
|
+
raise ValueError(f"identity registry is invalid: {exc}") from exc
|
|
178
|
+
if not isinstance(registry, dict) or registry.get("schemaVersion") != 1 or not isinstance(registry.get("agents"), dict):
|
|
179
|
+
raise ValueError("identity registry does not match schema v1")
|
|
180
|
+
for agent_id, item in registry["agents"].items():
|
|
181
|
+
_safe_id(agent_id)
|
|
182
|
+
if not isinstance(item, dict) or item.get("agentId") != agent_id or item.get("algorithm") != ALGORITHM:
|
|
183
|
+
raise ValueError(f"registry entry {agent_id} is not valid")
|
|
184
|
+
try:
|
|
185
|
+
public_raw = _unb64(item.get("publicKey"))
|
|
186
|
+
except ValueError as exc:
|
|
187
|
+
raise ValueError(f"registry public key for {agent_id} is not valid") from exc
|
|
188
|
+
if len(public_raw) != 32 or hashlib.sha256(public_raw).hexdigest() != item.get("fingerprint"):
|
|
189
|
+
raise ValueError(f"registry public key/fingerprint for {agent_id} does not match")
|
|
190
|
+
key_id = item.get("keyId")
|
|
191
|
+
if key_id is not None and (not isinstance(key_id, str) or not re.fullmatch(r"[a-f0-9]{16}", key_id)
|
|
192
|
+
or key_id != item.get("fingerprint", "")[:16]):
|
|
193
|
+
raise ValueError(f"registry keyId for {agent_id} is not valid")
|
|
194
|
+
if item.get("revokedAt") is not None and not isinstance(item.get("revokedAt"), str):
|
|
195
|
+
raise ValueError(f"registry revokedAt for {agent_id} is not valid")
|
|
196
|
+
previous = item.get("previousKeys", [])
|
|
197
|
+
if not isinstance(previous, list):
|
|
198
|
+
raise ValueError(f"registry previousKeys for {agent_id} must be an array")
|
|
199
|
+
for retired in previous:
|
|
200
|
+
if not isinstance(retired, dict):
|
|
201
|
+
raise ValueError(f"registry previous key for {agent_id} is not valid")
|
|
202
|
+
retired_public = _unb64(retired.get("publicKey"))
|
|
203
|
+
if len(retired_public) != 32 or hashlib.sha256(retired_public).hexdigest() != retired.get("fingerprint"):
|
|
204
|
+
raise ValueError(f"registry previous public key for {agent_id} does not match")
|
|
205
|
+
return registry
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _save_registry(root: str | Path, registry: dict) -> None:
|
|
209
|
+
registry["updatedAt"] = _stamp()
|
|
210
|
+
path = registry_path(root)
|
|
211
|
+
# Public keys/revocations are intentionally readable and may be committed
|
|
212
|
+
# so peers can verify signed payloads. Private keys never live here.
|
|
213
|
+
_atomic_write(path, (_canonical(registry) + b"\n"), 0o644)
|
|
214
|
+
try:
|
|
215
|
+
os.chmod(path.parent, 0o755)
|
|
216
|
+
os.chmod(path, 0o644)
|
|
217
|
+
except OSError:
|
|
218
|
+
pass
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@_locked_registry
|
|
222
|
+
def create(root: str | Path, agent_id: str, replace: bool = False,
|
|
223
|
+
key_out: str | Path | None = None) -> dict:
|
|
224
|
+
agent_id = _safe_id(agent_id)
|
|
225
|
+
Private, _, serialization = _crypto()
|
|
226
|
+
registry = _load_registry(root, create=True)
|
|
227
|
+
existing = registry["agents"].get(agent_id)
|
|
228
|
+
if existing and not replace:
|
|
229
|
+
raise ValueError(f"identity for agent {agent_id} already exists")
|
|
230
|
+
private = Private.generate()
|
|
231
|
+
public_raw = private.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
|
|
232
|
+
fingerprint = hashlib.sha256(public_raw).hexdigest()
|
|
233
|
+
key_id = fingerprint[:16]
|
|
234
|
+
key_path = Path(key_out).expanduser() if key_out else private_key_path(root, agent_id, key_id)
|
|
235
|
+
if key_path.exists() and not replace:
|
|
236
|
+
raise ValueError(f"private key already exists: {key_path}; use a deliberate backup/rotate")
|
|
237
|
+
private_raw = private.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw,
|
|
238
|
+
serialization.NoEncryption())
|
|
239
|
+
_atomic_write(key_path, private_raw, 0o600)
|
|
240
|
+
registry["agents"][agent_id] = {
|
|
241
|
+
"agentId": agent_id, "algorithm": ALGORITHM, "publicKey": _b64(public_raw),
|
|
242
|
+
"fingerprint": fingerprint, "keyId": key_id, "createdAt": _stamp(), "revokedAt": None,
|
|
243
|
+
"previousKeys": [],
|
|
244
|
+
}
|
|
245
|
+
_save_registry(root, registry)
|
|
246
|
+
return {"agentId": agent_id, "algorithm": ALGORITHM, "fingerprint": fingerprint,
|
|
247
|
+
"publicKey": _b64(public_raw), "privateKeyPath": str(key_path),
|
|
248
|
+
"privateKeyPermissions": "0600", "registryPath": str(registry_path(root)),
|
|
249
|
+
"warning": "Store a backup of the private key securely. The private key is not stored in the project."}
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
@_locked_registry
|
|
253
|
+
def import_public(root: str | Path, agent_id: str, public_key: str,
|
|
254
|
+
replace: bool = False) -> dict:
|
|
255
|
+
"""Register a public key owned by another host (e.g. a seal key in CI).
|
|
256
|
+
|
|
257
|
+
Private keys never enter the repo: the registry stores only public keys, so
|
|
258
|
+
verification still works anywhere while signing is possible only for the
|
|
259
|
+
holder of the original key.
|
|
260
|
+
"""
|
|
261
|
+
agent_id = _safe_id(agent_id)
|
|
262
|
+
_, Public, _ = _crypto()
|
|
263
|
+
try:
|
|
264
|
+
public_raw = _unb64(public_key.strip())
|
|
265
|
+
except Exception as exc:
|
|
266
|
+
raise ValueError("public key must be 32-byte Ed25519 base64") from exc
|
|
267
|
+
if len(public_raw) != 32:
|
|
268
|
+
raise ValueError("Ed25519 public key must be exactly 32 bytes")
|
|
269
|
+
try:
|
|
270
|
+
Public.from_public_bytes(public_raw)
|
|
271
|
+
except Exception as exc:
|
|
272
|
+
raise ValueError(f"public key is not valid: {exc}") from exc
|
|
273
|
+
registry = _load_registry(root, create=True)
|
|
274
|
+
if agent_id in registry["agents"] and not replace:
|
|
275
|
+
raise ValueError(f"identity for agent {agent_id} already exists; use rotate or replace")
|
|
276
|
+
fingerprint = hashlib.sha256(public_raw).hexdigest()
|
|
277
|
+
registry["agents"][agent_id] = {
|
|
278
|
+
"agentId": agent_id, "algorithm": ALGORITHM, "publicKey": _b64(public_raw),
|
|
279
|
+
"fingerprint": fingerprint, "keyId": fingerprint[:16], "createdAt": _stamp(),
|
|
280
|
+
"revokedAt": None, "previousKeys": [], "privateKeyOnThisHost": False,
|
|
281
|
+
}
|
|
282
|
+
_save_registry(root, registry)
|
|
283
|
+
return {"agentId": agent_id, "fingerprint": fingerprint, "publicKey": _b64(public_raw),
|
|
284
|
+
"registryPath": str(registry_path(root)),
|
|
285
|
+
"note": "private key was not imported; signing must use --key on the host that owns the key"}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
@_locked_registry
|
|
289
|
+
def rotate(root: str | Path, agent_id: str, reason: str = "") -> dict:
|
|
290
|
+
"""Rotate an agent's signing key while retaining retired public-key metadata."""
|
|
291
|
+
agent_id = _safe_id(agent_id)
|
|
292
|
+
Private, _, serialization = _crypto()
|
|
293
|
+
registry = _load_registry(root)
|
|
294
|
+
item = registry["agents"].get(agent_id)
|
|
295
|
+
if not item:
|
|
296
|
+
raise ValueError(f"identity for agent {agent_id} has not been created")
|
|
297
|
+
if item.get("revokedAt"):
|
|
298
|
+
raise ValueError(f"identity for agent {agent_id} is revoked; recreate it through the provisioning procedure")
|
|
299
|
+
old_key_path = private_key_path(root, agent_id, item.get("keyId"))
|
|
300
|
+
if not old_key_path.is_file():
|
|
301
|
+
raise ValueError(f"active private key for agent {agent_id} is not available on this host")
|
|
302
|
+
old_raw = old_key_path.read_bytes()
|
|
303
|
+
if len(old_raw) != 32:
|
|
304
|
+
raise ValueError("old Ed25519 private key is not valid")
|
|
305
|
+
old_private = Private.from_private_bytes(old_raw)
|
|
306
|
+
old_public = old_private.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
|
|
307
|
+
old_fingerprint = hashlib.sha256(old_public).hexdigest()
|
|
308
|
+
if old_fingerprint != item.get("fingerprint"):
|
|
309
|
+
raise ValueError("active private key does not match the public registry; rotation aborted")
|
|
310
|
+
|
|
311
|
+
new_private = Private.generate()
|
|
312
|
+
new_private_raw = new_private.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw,
|
|
313
|
+
serialization.NoEncryption())
|
|
314
|
+
new_public = new_private.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
|
|
315
|
+
new_fingerprint = hashlib.sha256(new_public).hexdigest()
|
|
316
|
+
new_key_id = new_fingerprint[:16]
|
|
317
|
+
new_key_path = private_key_path(root, agent_id, new_key_id)
|
|
318
|
+
if new_key_path.exists():
|
|
319
|
+
raise ValueError("rotation target key file already exists; not overwritten")
|
|
320
|
+
_atomic_write(new_key_path, new_private_raw, 0o600)
|
|
321
|
+
retired = {"fingerprint": item["fingerprint"], "publicKey": item["publicKey"],
|
|
322
|
+
"keyId": item.get("keyId"), "retiredAt": _stamp(), "reason": str(reason)[:300]}
|
|
323
|
+
item.setdefault("previousKeys", []).append(retired)
|
|
324
|
+
item.update({"publicKey": _b64(new_public), "fingerprint": new_fingerprint,
|
|
325
|
+
"keyId": new_key_id, "rotatedAt": _stamp()})
|
|
326
|
+
_save_registry(root, registry)
|
|
327
|
+
return {"agentId": agent_id, "oldFingerprint": old_fingerprint,
|
|
328
|
+
"newFingerprint": new_fingerprint, "newPrivateKeyPath": str(new_key_path),
|
|
329
|
+
"retiredPublicKeys": len(item["previousKeys"]),
|
|
330
|
+
"warning": "The old private key was not deleted automatically; delete or archive it securely per organizational policy."}
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
@_locked_registry
|
|
334
|
+
def list_identities(root: str | Path) -> dict:
|
|
335
|
+
registry = _load_registry(root)
|
|
336
|
+
agents = []
|
|
337
|
+
for agent_id, item in sorted(registry["agents"].items()):
|
|
338
|
+
agents.append({"agentId": agent_id, "algorithm": item.get("algorithm"),
|
|
339
|
+
"fingerprint": item.get("fingerprint"), "createdAt": item.get("createdAt"),
|
|
340
|
+
"rotatedAt": item.get("rotatedAt"), "retiredKeyCount": len(item.get("previousKeys", [])),
|
|
341
|
+
"revokedAt": item.get("revokedAt"), "active": not bool(item.get("revokedAt"))})
|
|
342
|
+
return {"schemaVersion": 1, "agents": agents, "count": len(agents)}
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
@_locked_registry
|
|
346
|
+
def revoke(root: str | Path, agent_id: str, reason: str = "") -> dict:
|
|
347
|
+
agent_id = _safe_id(agent_id)
|
|
348
|
+
registry = _load_registry(root)
|
|
349
|
+
item = registry["agents"].get(agent_id)
|
|
350
|
+
if not item:
|
|
351
|
+
raise ValueError(f"identity for agent {agent_id} not found")
|
|
352
|
+
if not item.get("revokedAt"):
|
|
353
|
+
item["revokedAt"] = _stamp()
|
|
354
|
+
item["revocationReason"] = str(reason)[:300]
|
|
355
|
+
_save_registry(root, registry)
|
|
356
|
+
return {"agentId": agent_id, "revokedAt": item["revokedAt"], "revoked": True}
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def _load_private_key(path: Path, Private, serialization):
|
|
360
|
+
"""The key may be 32 raw bytes (Pakem format) or PEM PKCS8."""
|
|
361
|
+
raw = path.read_bytes()
|
|
362
|
+
if raw.lstrip().startswith(b"-----BEGIN"):
|
|
363
|
+
from cryptography.hazmat.primitives.serialization import load_pem_private_key
|
|
364
|
+
try:
|
|
365
|
+
key = load_pem_private_key(raw, password=None)
|
|
366
|
+
except Exception as exc:
|
|
367
|
+
raise ValueError(f"PEM private key cannot be read: {exc}") from exc
|
|
368
|
+
if not hasattr(key, "public_key") or key.public_key().__class__.__name__ != "Ed25519PublicKey":
|
|
369
|
+
raise ValueError("PEM private key is not Ed25519")
|
|
370
|
+
return key
|
|
371
|
+
if len(raw) != 32:
|
|
372
|
+
raise ValueError("Ed25519 private key must be exactly 32 bytes (raw) or PEM PKCS8")
|
|
373
|
+
return Private.from_private_bytes(raw)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
@_locked_registry
|
|
377
|
+
def sign(root: str | Path, agent_id: str, payload: Any,
|
|
378
|
+
key_path: str | Path | None = None) -> dict:
|
|
379
|
+
"""Sign a payload as agent_id.
|
|
380
|
+
|
|
381
|
+
`key_path` lets the private key live outside the host config directory (e.g. a
|
|
382
|
+
mounted CI secret): the registry still holds the public key, so the signature
|
|
383
|
+
can still be verified elsewhere without carrying the private key.
|
|
384
|
+
"""
|
|
385
|
+
agent_id = _safe_id(agent_id)
|
|
386
|
+
Private, _, serialization = _crypto()
|
|
387
|
+
registry = _load_registry(root)
|
|
388
|
+
item = registry["agents"].get(agent_id)
|
|
389
|
+
if not item:
|
|
390
|
+
raise ValueError(f"identity for agent {agent_id} has not been created")
|
|
391
|
+
if item.get("revokedAt"):
|
|
392
|
+
raise ValueError(f"identity for agent {agent_id} is revoked")
|
|
393
|
+
source = Path(key_path).expanduser() if key_path else private_key_path(root, agent_id, item.get("keyId"))
|
|
394
|
+
if not source.is_file():
|
|
395
|
+
raise ValueError(f"private key for agent {agent_id} is not available: {source}")
|
|
396
|
+
private = _load_private_key(source, Private, serialization)
|
|
397
|
+
public_raw = private.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
|
|
398
|
+
fingerprint = hashlib.sha256(public_raw).hexdigest()
|
|
399
|
+
if fingerprint != item.get("fingerprint") or _b64(public_raw) != item.get("publicKey"):
|
|
400
|
+
raise ValueError("private key does not match the public key in the registry")
|
|
401
|
+
payload_bytes = _canonical(payload)
|
|
402
|
+
unsigned = {"format": FORMAT, "algorithm": ALGORITHM, "agentId": agent_id,
|
|
403
|
+
"fingerprint": fingerprint, "payload": payload,
|
|
404
|
+
"payloadSha256": hashlib.sha256(payload_bytes).hexdigest()}
|
|
405
|
+
signature = private.sign(_canonical(unsigned))
|
|
406
|
+
return {**unsigned, "signature": _b64(signature)}
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
@_locked_registry
|
|
410
|
+
def verify(root: str | Path, envelope: dict, audience: str | None = None,
|
|
411
|
+
action: str | None = None, check_expiry: bool = True) -> dict:
|
|
412
|
+
_, Public, _ = _crypto()
|
|
413
|
+
if not isinstance(envelope, dict) or envelope.get("format") != FORMAT or envelope.get("algorithm") != ALGORITHM:
|
|
414
|
+
raise ValueError("unknown signed envelope format/algorithm")
|
|
415
|
+
agent_id = _safe_id(envelope.get("agentId"))
|
|
416
|
+
registry = _load_registry(root)
|
|
417
|
+
item = registry["agents"].get(agent_id)
|
|
418
|
+
if not item:
|
|
419
|
+
raise ValueError(f"public identity for {agent_id} is not known")
|
|
420
|
+
if item.get("revokedAt"):
|
|
421
|
+
raise ValueError(f"identity {agent_id} is revoked")
|
|
422
|
+
if envelope.get("fingerprint") != item.get("fingerprint"):
|
|
423
|
+
raise ValueError("signed envelope fingerprint does not match the registry")
|
|
424
|
+
payload = envelope.get("payload")
|
|
425
|
+
payload_hash = hashlib.sha256(_canonical(payload)).hexdigest()
|
|
426
|
+
if payload_hash != envelope.get("payloadSha256"):
|
|
427
|
+
raise ValueError("payload digest does not match")
|
|
428
|
+
unsigned = {key: envelope.get(key) for key in
|
|
429
|
+
("format", "algorithm", "agentId", "fingerprint", "payload", "payloadSha256")}
|
|
430
|
+
try:
|
|
431
|
+
public = Public.from_public_bytes(_unb64(item["publicKey"]))
|
|
432
|
+
public.verify(_unb64(envelope.get("signature")), _canonical(unsigned))
|
|
433
|
+
except Exception as exc:
|
|
434
|
+
raise ValueError("invalid Ed25519 signature") from exc
|
|
435
|
+
|
|
436
|
+
# Token claims are optional for ordinary attestations. If present, enforce
|
|
437
|
+
# expiry and optional audience/action constraints after signature checks.
|
|
438
|
+
claims = payload if isinstance(payload, dict) else {}
|
|
439
|
+
if claims.get("type") == "pakem.delegation.v1":
|
|
440
|
+
if claims.get("subject") != agent_id:
|
|
441
|
+
raise ValueError("delegation subject differs from the signing identity")
|
|
442
|
+
if not isinstance(claims.get("actions"), list) or not claims["actions"] or any(not isinstance(x, str) for x in claims["actions"]):
|
|
443
|
+
raise ValueError("delegation actions are not valid")
|
|
444
|
+
try:
|
|
445
|
+
issued_at = datetime.fromisoformat(str(claims["issuedAt"]).replace("Z", "+00:00"))
|
|
446
|
+
expires_at = datetime.fromisoformat(str(claims["expiresAt"]).replace("Z", "+00:00"))
|
|
447
|
+
if issued_at.tzinfo is None:
|
|
448
|
+
issued_at = issued_at.replace(tzinfo=timezone.utc)
|
|
449
|
+
if expires_at.tzinfo is None:
|
|
450
|
+
expires_at = expires_at.replace(tzinfo=timezone.utc)
|
|
451
|
+
except (KeyError, ValueError) as exc:
|
|
452
|
+
raise ValueError("delegation timestamps are not valid") from exc
|
|
453
|
+
if expires_at <= issued_at or expires_at - issued_at > timedelta(days=1):
|
|
454
|
+
raise ValueError("delegation lifetime is not valid (maximum 24 hours)")
|
|
455
|
+
if issued_at > datetime.now(timezone.utc) + timedelta(minutes=2):
|
|
456
|
+
raise ValueError("delegation is not yet valid (issuedAt is in the future)")
|
|
457
|
+
if check_expiry and claims.get("expiresAt"):
|
|
458
|
+
try:
|
|
459
|
+
expiry = datetime.fromisoformat(str(claims["expiresAt"]).replace("Z", "+00:00"))
|
|
460
|
+
if expiry.tzinfo is None:
|
|
461
|
+
expiry = expiry.replace(tzinfo=timezone.utc)
|
|
462
|
+
except ValueError as exc:
|
|
463
|
+
raise ValueError("token expiresAt is not valid") from exc
|
|
464
|
+
if expiry <= datetime.now(timezone.utc):
|
|
465
|
+
raise ValueError("signed token has expired")
|
|
466
|
+
if audience is not None and claims.get("audience") != audience:
|
|
467
|
+
raise ValueError("token audience does not match")
|
|
468
|
+
if action is not None and action not in claims.get("actions", []):
|
|
469
|
+
raise ValueError("token does not allow the requested action")
|
|
470
|
+
return {"valid": True, "agentId": agent_id, "fingerprint": item["fingerprint"],
|
|
471
|
+
"payload": payload, "token": bool(claims.get("expiresAt"))}
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def issue_token(root: str | Path, agent_id: str, audience: str,
|
|
475
|
+
actions: list[str], ttl_seconds: int = 900) -> dict:
|
|
476
|
+
if not isinstance(audience, str) or not audience.strip() or len(audience) > 200:
|
|
477
|
+
raise ValueError("audience must be a non-empty string of at most 200 characters")
|
|
478
|
+
if isinstance(ttl_seconds, bool) or not isinstance(ttl_seconds, int) or not 30 <= ttl_seconds <= 86400:
|
|
479
|
+
raise ValueError("ttl_seconds must be 30-86400")
|
|
480
|
+
clean_actions = []
|
|
481
|
+
if not isinstance(actions, list) or not actions or len(actions) > 50:
|
|
482
|
+
raise ValueError("actions must be an array of 1-50 items")
|
|
483
|
+
for value in actions:
|
|
484
|
+
if not isinstance(value, str) or not value.strip() or len(value.strip()) > 100:
|
|
485
|
+
raise ValueError("each action must be non-empty text of at most 100 characters")
|
|
486
|
+
if value.strip() not in clean_actions:
|
|
487
|
+
clean_actions.append(value.strip())
|
|
488
|
+
issued = datetime.now(timezone.utc)
|
|
489
|
+
payload = {"type": "pakem.delegation.v1", "subject": _safe_id(agent_id),
|
|
490
|
+
"audience": audience.strip(), "actions": clean_actions,
|
|
491
|
+
"issuedAt": issued.isoformat(timespec="seconds"),
|
|
492
|
+
"expiresAt": (issued + timedelta(seconds=ttl_seconds)).isoformat(timespec="seconds"),
|
|
493
|
+
"tokenId": str(uuid.uuid4())}
|
|
494
|
+
return sign(root, agent_id, payload)
|