repopact 3.1.0__py3-none-win_amd64.whl
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.
- repopact/AGENTS.md +37 -0
- repopact/__init__.py +36 -0
- repopact/_audit/README.md +4 -0
- repopact/_audit/alignment-report.md +305 -0
- repopact/_audit/inventory.md +38 -0
- repopact/adapters.py +129 -0
- repopact/admission.py +804 -0
- repopact/admission_conformance.py +39 -0
- repopact/adopt_repo.py +501 -0
- repopact/check_frozen_surface.py +136 -0
- repopact/cli.py +564 -0
- repopact/dev_fixtures.py +234 -0
- repopact/doctor.py +430 -0
- repopact/enforcement.py +218 -0
- repopact/engine_client.py +278 -0
- repopact/fleet_verify.py +702 -0
- repopact/frontmatter.py +48 -0
- repopact/generate_dashboard.py +131 -0
- repopact/generate_spec.py +101 -0
- repopact/graph_cli.py +462 -0
- repopact/guard.py +262 -0
- repopact/guard_ipc.py +385 -0
- repopact/init_repo.py +183 -0
- repopact/legacy_validate.py +48 -0
- repopact/new.py +115 -0
- repopact/package_version.py +69 -0
- repopact/plan_import.py +409 -0
- repopact/platform_backends.py +800 -0
- repopact/release_build.py +418 -0
- repopact/release_local.py +437 -0
- repopact/repo_model.py +245 -0
- repopact/run_admission_platform_conformance.py +86 -0
- repopact/run_conformance.py +203 -0
- repopact/schemas/adapter-capabilities.schema.json +57 -0
- repopact/schemas/admission-policy.schema.json +58 -0
- repopact/schemas/adopter-fleet.schema.json +108 -0
- repopact/schemas/assurance-mapping.schema.json +252 -0
- repopact/schemas/audit-finding.schema.json +15 -0
- repopact/schemas/authorization-receipt.schema.json +24 -0
- repopact/schemas/authorization-request.schema.json +41 -0
- repopact/schemas/conformance-manifest.schema.json +53 -0
- repopact/schemas/evidence-run.schema.json +17 -0
- repopact/schemas/frozen-surface.schema.json +21 -0
- repopact/schemas/invariants.schema.json +27 -0
- repopact/schemas/operator-authority.schema.json +76 -0
- repopact/schemas/record-frontmatter.schema.json +29 -0
- repopact/schemas/repository-registration.schema.json +35 -0
- repopact/schemas/rog-capability.schema.json +21 -0
- repopact/schemas/verification-profile.schema.json +76 -0
- repopact/schemas/work-item.schema.json +41 -0
- repopact/takeover.py +438 -0
- repopact/templates/README.md +14 -0
- repopact/templates/admission-policy.json +22 -0
- repopact/templates/decision.md +25 -0
- repopact/templates/evidence-run.json +12 -0
- repopact/templates/policy.md +20 -0
- repopact/templates/work-item.README.md +24 -0
- repopact/templates/work-item.json +14 -0
- repopact/track_import.py +204 -0
- repopact/validate_repo.py +1889 -0
- repopact/validate_research.py +463 -0
- repopact/validate_verification.py +25 -0
- repopact/verification.py +817 -0
- repopact/verify_cli.py +69 -0
- repopact/verify_status.py +266 -0
- repopact/windows_guard_service.py +106 -0
- repopact-3.1.0.data/scripts/repopact-engine.exe +0 -0
- repopact-3.1.0.data/scripts/repopact.exe +0 -0
- repopact-3.1.0.dist-info/METADATA +219 -0
- repopact-3.1.0.dist-info/RECORD +72 -0
- repopact-3.1.0.dist-info/WHEEL +4 -0
- repopact-3.1.0.dist-info/sboms/repopact-engine.cyclonedx.json +4044 -0
repopact/admission.py
ADDED
|
@@ -0,0 +1,804 @@
|
|
|
1
|
+
"""Vendor-neutral pre-execution admission policy and authorization primitives.
|
|
2
|
+
|
|
3
|
+
This module intentionally keeps policy decisions deterministic and independent
|
|
4
|
+
of a host or agent vendor. The protected guard and adapters are thin callers
|
|
5
|
+
around these functions; a receipt is proof, while a lease is the short-lived
|
|
6
|
+
runtime capability derived from that proof.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import hashlib
|
|
12
|
+
import hmac
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import secrets
|
|
16
|
+
import subprocess
|
|
17
|
+
import uuid
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from datetime import datetime, timedelta, timezone
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any, Callable, Iterable, Mapping
|
|
22
|
+
|
|
23
|
+
try: # optional until a signer is actually used
|
|
24
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
25
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
26
|
+
Ed25519PrivateKey, Ed25519PublicKey,
|
|
27
|
+
)
|
|
28
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
29
|
+
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
|
30
|
+
except ImportError: # pragma: no cover - exercised by dependency/install tests
|
|
31
|
+
Ed25519PrivateKey = Ed25519PublicKey = AESGCM = PBKDF2HMAC = None # type: ignore
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
DENIAL_CODES = (
|
|
35
|
+
"UNREGISTERED_REPO", "GUARD_UNHEALTHY", "NO_WORK_ITEM", "PROPOSED_WORK",
|
|
36
|
+
"INVALID_PREFLIGHT", "WRONG_LIFECYCLE", "DEPENDENCY_AUTHORITY",
|
|
37
|
+
"DEVELOPMENT_IDENTITY", "SCOPE_VIOLATION", "PATH_VIOLATION",
|
|
38
|
+
"FROZEN_APPROVAL_REQUIRED", "WRONG_REPOSITORY", "WRONG_WORK_ITEM",
|
|
39
|
+
"WRONG_SESSION", "EXPIRED_AUTHORIZATION", "REVOKED_AUTHORIZATION",
|
|
40
|
+
"STATE_DRIFT", "AUTHORITY_DRIFT", "STALE_POLICY", "DELEGATION_ESCALATION",
|
|
41
|
+
"PROFILE_ESCALATION", "BOOTSTRAP_SCOPE", "RECEIPT_INVALID",
|
|
42
|
+
"RECEIPT_REPLAY", "NO_OPERATOR_PROOF", "NOT_COVERED",
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def canonical_json(value: Any) -> bytes:
|
|
47
|
+
"""Return deterministic UTF-8 JSON bytes (no whitespace or NaN)."""
|
|
48
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
|
|
49
|
+
allow_nan=False).encode("utf-8")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
canonicalize = canonical_json
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def digest(value: Any) -> str:
|
|
56
|
+
return hashlib.sha256(canonical_json(value)).hexdigest()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _utc(value: str | datetime) -> datetime:
|
|
60
|
+
if isinstance(value, datetime):
|
|
61
|
+
dt = value
|
|
62
|
+
else:
|
|
63
|
+
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
64
|
+
if dt.tzinfo is None:
|
|
65
|
+
dt = dt.replace(tzinfo=timezone.utc)
|
|
66
|
+
return dt.astimezone(timezone.utc)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def iso(value: datetime | None = None) -> str:
|
|
70
|
+
return (value or datetime.now(timezone.utc)).astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _git(root: Path, *args: str) -> str:
|
|
74
|
+
cp = subprocess.run(["git", "-C", str(root), *args], text=True, capture_output=True, check=False)
|
|
75
|
+
if cp.returncode:
|
|
76
|
+
return ""
|
|
77
|
+
return cp.stdout.strip()
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def normalize_path(path: str | Path) -> str:
|
|
81
|
+
p = Path(path).expanduser().resolve(strict=False)
|
|
82
|
+
text = os.path.normcase(str(p)).replace("\\", "/")
|
|
83
|
+
if len(text) > 1 and text.endswith("/"):
|
|
84
|
+
text = text.rstrip("/")
|
|
85
|
+
return text
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def canonical_identity(root: Path) -> dict[str, Any]:
|
|
89
|
+
root = root.resolve()
|
|
90
|
+
top = _git(root, "rev-parse", "--show-toplevel") or str(root)
|
|
91
|
+
common = _git(root, "rev-parse", "--git-common-dir") or str(root / ".git")
|
|
92
|
+
head = _git(root, "rev-parse", "HEAD")
|
|
93
|
+
tree = _git(root, "rev-parse", "HEAD^{tree}")
|
|
94
|
+
contract_parts = []
|
|
95
|
+
for rel in ("AGENTS.md", "governance/owners.json", "governance/invariants.json", "governance/charter.md"):
|
|
96
|
+
p = root / rel
|
|
97
|
+
if p.is_file():
|
|
98
|
+
contract_parts.append((rel, hashlib.sha256(p.read_bytes()).hexdigest()))
|
|
99
|
+
return {
|
|
100
|
+
"repository_root": normalize_path(top),
|
|
101
|
+
"git_common_dir": normalize_path((root / common).resolve() if not Path(common).is_absolute() else common),
|
|
102
|
+
"repopact_root": normalize_path(root), "head": head, "tree": tree,
|
|
103
|
+
"contract_digest": digest(contract_parts),
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class SignerError(RuntimeError):
|
|
108
|
+
pass
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class UserPresence:
|
|
112
|
+
"""Small host/UI-neutral user-presence seam used by approval front ends."""
|
|
113
|
+
def confirm(self, prompt: str) -> bool:
|
|
114
|
+
import sys
|
|
115
|
+
if not sys.stdin.isatty():
|
|
116
|
+
raise SignerError("user presence requires an interactive terminal")
|
|
117
|
+
return input(prompt + " [y/N] ").strip().lower() in {"y", "yes"}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Ed25519Signer:
|
|
121
|
+
"""Ed25519 signer. Private keys are deliberately external to repositories."""
|
|
122
|
+
algorithm = "ed25519"
|
|
123
|
+
|
|
124
|
+
def __init__(self, private_key: Any, key_id: str = "operator-key", operator_id: str = "operator"):
|
|
125
|
+
if Ed25519PrivateKey is None:
|
|
126
|
+
raise SignerError("cryptography is required for Ed25519 signing")
|
|
127
|
+
self.private_key, self.key_id, self.operator_id = private_key, key_id, operator_id
|
|
128
|
+
|
|
129
|
+
@classmethod
|
|
130
|
+
def generate(cls, key_id: str = "operator-key", operator_id: str = "operator") -> "Ed25519Signer":
|
|
131
|
+
if Ed25519PrivateKey is None:
|
|
132
|
+
raise SignerError("cryptography is required for Ed25519 signing")
|
|
133
|
+
return cls(Ed25519PrivateKey.generate(), key_id, operator_id)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def public_key_bytes(self) -> bytes:
|
|
137
|
+
return self.private_key.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
|
|
138
|
+
|
|
139
|
+
@property
|
|
140
|
+
def public_key(self) -> str:
|
|
141
|
+
return base64.b64encode(self.public_key_bytes).decode("ascii")
|
|
142
|
+
|
|
143
|
+
def sign(self, value: Any) -> str:
|
|
144
|
+
return base64.b64encode(self.private_key.sign(canonical_json(value))).decode("ascii")
|
|
145
|
+
|
|
146
|
+
def save(self, path: Path, passphrase: str) -> None:
|
|
147
|
+
if AESGCM is None or PBKDF2HMAC is None:
|
|
148
|
+
raise SignerError("cryptography is required for encrypted key storage")
|
|
149
|
+
salt, nonce = os.urandom(16), os.urandom(12)
|
|
150
|
+
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=310000)
|
|
151
|
+
key = kdf.derive(passphrase.encode("utf-8"))
|
|
152
|
+
raw = self.private_key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption())
|
|
153
|
+
ciphertext = AESGCM(key).encrypt(nonce, raw, self.key_id.encode())
|
|
154
|
+
record = {"format": 1, "key_id": self.key_id, "operator_id": self.operator_id,
|
|
155
|
+
"salt": base64.b64encode(salt).decode(), "nonce": base64.b64encode(nonce).decode(),
|
|
156
|
+
"ciphertext": base64.b64encode(ciphertext).decode()}
|
|
157
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
158
|
+
path.write_bytes(canonical_json(record));
|
|
159
|
+
try: os.chmod(path, 0o600)
|
|
160
|
+
except OSError: pass
|
|
161
|
+
|
|
162
|
+
@classmethod
|
|
163
|
+
def load(cls, path: Path, passphrase: str) -> "Ed25519Signer":
|
|
164
|
+
if AESGCM is None or PBKDF2HMAC is None:
|
|
165
|
+
raise SignerError("cryptography is required for encrypted key storage")
|
|
166
|
+
rec = json.loads(path.read_bytes())
|
|
167
|
+
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=base64.b64decode(rec["salt"]), iterations=310000)
|
|
168
|
+
key = kdf.derive(passphrase.encode("utf-8"))
|
|
169
|
+
try: raw = AESGCM(key).decrypt(base64.b64decode(rec["nonce"]), base64.b64decode(rec["ciphertext"]), rec["key_id"].encode())
|
|
170
|
+
except Exception as exc: raise SignerError("invalid signing key or passphrase") from exc
|
|
171
|
+
return cls(Ed25519PrivateKey.from_private_bytes(raw), rec["key_id"], rec["operator_id"])
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def verify_signature(public_key: str, signature: str, value: Any) -> bool:
|
|
175
|
+
if Ed25519PublicKey is None: return False
|
|
176
|
+
try:
|
|
177
|
+
Ed25519PublicKey.from_public_bytes(base64.b64decode(public_key)).verify(base64.b64decode(signature), canonical_json(value))
|
|
178
|
+
return True
|
|
179
|
+
except Exception:
|
|
180
|
+
return False
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@dataclass(frozen=True)
|
|
184
|
+
class AdmissionDecision:
|
|
185
|
+
allowed: bool
|
|
186
|
+
code: str = ""
|
|
187
|
+
reason: str = ""
|
|
188
|
+
enforcement: str = "pre-action"
|
|
189
|
+
details: Mapping[str, Any] = field(default_factory=dict)
|
|
190
|
+
|
|
191
|
+
@classmethod
|
|
192
|
+
def allow(cls, enforcement: str = "pre-action", **details: Any) -> "AdmissionDecision":
|
|
193
|
+
return cls(True, "", "allowed", enforcement, details)
|
|
194
|
+
|
|
195
|
+
@classmethod
|
|
196
|
+
def deny(cls, code: str, reason: str = "", **details: Any) -> "AdmissionDecision":
|
|
197
|
+
if code not in DENIAL_CODES: code = "NOT_COVERED"
|
|
198
|
+
return cls(False, code, reason or code.lower().replace("_", " "), "not-covered", details)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@dataclass(frozen=True)
|
|
202
|
+
class AdmissionRequest:
|
|
203
|
+
"""Typed wrapper used by API clients; fields remain JSON-contract compatible."""
|
|
204
|
+
value: Mapping[str, Any]
|
|
205
|
+
def to_dict(self) -> dict[str, Any]: return dict(self.value)
|
|
206
|
+
@property
|
|
207
|
+
def digest(self) -> str: return digest(self.value)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@dataclass(frozen=True)
|
|
211
|
+
class AuthorizationReceipt:
|
|
212
|
+
value: Mapping[str, Any]
|
|
213
|
+
def to_dict(self) -> dict[str, Any]: return dict(self.value)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@dataclass(frozen=True)
|
|
217
|
+
class Lease:
|
|
218
|
+
value: Mapping[str, Any]
|
|
219
|
+
def to_dict(self) -> dict[str, Any]: return dict(self.value)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@dataclass(frozen=True)
|
|
223
|
+
class Principal:
|
|
224
|
+
principal_id: str
|
|
225
|
+
kind: str = "session"
|
|
226
|
+
parent: str | None = None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
@dataclass(frozen=True)
|
|
230
|
+
class GuardHealth:
|
|
231
|
+
healthy: bool
|
|
232
|
+
security_level: str = "pre-action"
|
|
233
|
+
reason: str = ""
|
|
234
|
+
protected: bool = False
|
|
235
|
+
integrity_checked: bool = False
|
|
236
|
+
protected_from_gated_principal: bool = False
|
|
237
|
+
process_confined: bool = False
|
|
238
|
+
path_confined: bool = False
|
|
239
|
+
service_identity_verified: bool = False
|
|
240
|
+
host_configuration_protected: bool = False
|
|
241
|
+
installed_code_path: str = ""
|
|
242
|
+
protected_state_path: str = ""
|
|
243
|
+
ipc_endpoint: str = ""
|
|
244
|
+
backend_id: str = ""
|
|
245
|
+
testing_only: bool = False
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def default_policy() -> dict[str, Any]:
|
|
249
|
+
profile = {"readable_scopes": ["*"], "writable_scopes": ["work", "src", "tests"], "writable_paths": ["work/**", "src/**", "tests/**"],
|
|
250
|
+
"capabilities": {"process": False, "shell": False, "network": False, "frozen_surface": False}, "max_duration_seconds": 1800,
|
|
251
|
+
"repair_allowed": False, "delegation_allowed": False, "max_delegation_depth": 0, "max_profile": "bounded"}
|
|
252
|
+
repair = {**profile, "writable_scopes": ["governance", "work", "evidence"], "writable_paths": ["governance/**", "work/**", "evidence/**"], "max_duration_seconds": 900, "repair_allowed": True, "max_profile": "repair"}
|
|
253
|
+
return {"version": 1, "policy_version": "1", "enabled": True, "minimum_enforcement": "pre-action", "failure_mode": "fail-closed",
|
|
254
|
+
"approval_cadence": "per-session", "default_profile": "bounded", "profiles": {"observe": {**profile, "writable_scopes": [], "writable_paths": [], "max_duration_seconds": 3600, "max_profile": "observe"}, "bounded": profile, "repair": repair}, "protected_scopes": ["governance", "repopact/schemas"]}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def default_authority(public_key: str = "", operator_id: str = "operator", key_id: str = "operator-key") -> dict[str, Any]:
|
|
258
|
+
return {"authority_version": "1", "operators": [{"operator_id": operator_id, "key_id": key_id, "algorithm": "ed25519", "public_key": public_key, "roles": ["operator"]}],
|
|
259
|
+
"approval_classes": ["activate", "repair", "frozen", "scope", "revoke", "recovery"], "profiles": {"observe": {"approval_classes": ["activate"], "max_delegation_depth": 0}, "bounded": {"approval_classes": ["activate", "repair", "frozen", "scope"], "max_delegation_depth": 0}, "repair": {"approval_classes": ["repair"], "max_delegation_depth": 0}},
|
|
260
|
+
"delegation": {"allowed": False, "max_depth": 0, "operator_approval_required": True}, "rotation": {"requires_existing_trust": True, "overlap_seconds": 86400}, "recovery": {"requires_existing_trust": True, "separate_approval_class": "recovery"}}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _record(path: Path) -> dict[str, Any]:
|
|
264
|
+
return json.loads(path.read_text(encoding="utf-8"))
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _public_paths(root: Path) -> tuple[Path, Path, Path]:
|
|
268
|
+
return root / "governance" / "admission-policy.json", root / "governance" / "operator-authority.json", root / "governance" / "repository-registration.json"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def admission_policy(root: Path) -> dict[str, Any] | None:
|
|
272
|
+
"""Read the adopter-owned policy, if this repository opted in.
|
|
273
|
+
|
|
274
|
+
Absence is meaningful: standalone RepoPact has no hidden guard or lease
|
|
275
|
+
prerequisite. Callers that need strict registration verification should
|
|
276
|
+
continue to use :func:`verify_registration` after this opt-in check.
|
|
277
|
+
"""
|
|
278
|
+
path = root / "governance" / "admission-policy.json"
|
|
279
|
+
if not path.is_file():
|
|
280
|
+
return None
|
|
281
|
+
try:
|
|
282
|
+
value = _record(path)
|
|
283
|
+
except Exception as exc:
|
|
284
|
+
raise ValueError("admission policy is invalid JSON") from exc
|
|
285
|
+
if not isinstance(value, dict):
|
|
286
|
+
raise ValueError("admission policy must be an object")
|
|
287
|
+
return value
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def admission_requirement(root: Path):
|
|
291
|
+
"""Return the canonical opt-in requirement without touching guard state."""
|
|
292
|
+
from .enforcement import policy_requirement
|
|
293
|
+
try:
|
|
294
|
+
return policy_requirement(admission_policy(root))
|
|
295
|
+
except ValueError:
|
|
296
|
+
return policy_requirement({"enabled": True, "minimum_enforcement": "pre-action", "failure_mode": "fail-closed"})
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def frozen_surface_digest(root: Path) -> str:
|
|
300
|
+
"""Digest the repository's declared frozen surface, not caller assertions."""
|
|
301
|
+
path = root / "governance" / "frozen-surface.json"
|
|
302
|
+
if path.is_file():
|
|
303
|
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
304
|
+
return digest({"frozen_surface": []})
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def setup_admission(root: Path, protected_dir: Path | None = None, signer: Ed25519Signer | None = None,
|
|
308
|
+
*, registry_key: str = "root") -> dict[str, Any]:
|
|
309
|
+
"""Explicit opt-in setup. Existing protected registration is never replaced."""
|
|
310
|
+
root = root.resolve(); policy_path, authority_path, registration_path = _public_paths(root)
|
|
311
|
+
base = protected_dir or (Path.home() / ".repopact" / "registrations")
|
|
312
|
+
# Testing/reference installations historically use a root digest. A
|
|
313
|
+
# host-managed global guard uses the adoption id as the registry key so a
|
|
314
|
+
# single service can hold independent registrations for many repositories.
|
|
315
|
+
protected = base / digest(normalize_path(root)) if registry_key == "root" else base / "_pending"
|
|
316
|
+
if protected.exists() and (protected / "registration.json").exists():
|
|
317
|
+
raise RuntimeError("protected registration already exists; explicit rotation required")
|
|
318
|
+
if signer is None:
|
|
319
|
+
raise SignerError("explicit operator signer required; unattended setup cannot establish trust")
|
|
320
|
+
policy, authority = default_policy(), default_authority(signer.public_key, signer.operator_id, signer.key_id)
|
|
321
|
+
ident = canonical_identity(root)
|
|
322
|
+
registration = {"registration_version": 1, "adoption_id": str(uuid.uuid4()), "repository_identity": {"root_digest": digest(ident["repository_root"]), "common_dir_digest": digest(ident["git_common_dir"]), "assurance": "git-common-dir"}, "repopact_root_digest": digest(ident["repopact_root"]), "git": {"common_dir_hint": ident["git_common_dir"], "worktree_hint": ident["repository_root"]}, "policy_version": policy["policy_version"], "authority_version": authority["authority_version"]}
|
|
323
|
+
if registry_key != "root":
|
|
324
|
+
protected = base / registration["adoption_id"]
|
|
325
|
+
if protected.exists():
|
|
326
|
+
raise RuntimeError("protected registration adoption id already exists")
|
|
327
|
+
for p, data in ((policy_path, policy), (authority_path, authority), (registration_path, registration)):
|
|
328
|
+
p.parent.mkdir(parents=True, exist_ok=True); p.write_bytes(canonical_json(data) + b"\n")
|
|
329
|
+
protected.mkdir(parents=True, exist_ok=True)
|
|
330
|
+
state = {"registration": registration, "registration_digest": digest(registration), "authority_digest": digest(authority), "policy_digest": digest(policy), "revocation_epoch": 0, "guard_version": "1", "guard_id": secrets.token_hex(8), "adoption_id": registration["adoption_id"], "common_dir_digest": digest(ident["git_common_dir"]), "registered_root_digest": digest(ident["repopact_root"]), "registered_root": ident["repopact_root"], "registry_key": registry_key}
|
|
331
|
+
state_key = os.urandom(32)
|
|
332
|
+
(protected / "registration.key").write_bytes(state_key)
|
|
333
|
+
try: os.chmod(protected / "registration.key", 0o600)
|
|
334
|
+
except OSError: pass
|
|
335
|
+
state["state_mac"] = hmac.new(state_key, canonical_json(state), hashlib.sha256).hexdigest()
|
|
336
|
+
(protected / "registration.json").write_bytes(canonical_json(state) + b"\n")
|
|
337
|
+
return {"policy": policy_path, "authority": authority_path, "registration": registration_path, "protected": protected, "signer": signer}
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def _read_protected_state(p: Path) -> dict[str, Any] | None:
|
|
341
|
+
try:
|
|
342
|
+
state = _record(p)
|
|
343
|
+
key_path = p.with_name("registration.key")
|
|
344
|
+
key = key_path.read_bytes() if key_path.is_file() else b""
|
|
345
|
+
supplied = state.pop("state_mac", None)
|
|
346
|
+
expected = hmac.new(key, canonical_json(state), hashlib.sha256).hexdigest() if key else None
|
|
347
|
+
if not supplied or not expected or not hmac.compare_digest(str(supplied), expected): return None
|
|
348
|
+
state["state_mac"] = supplied
|
|
349
|
+
return state
|
|
350
|
+
except (OSError, ValueError, json.JSONDecodeError): return None
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _protected_state(root: Path, protected_dir: Path | None) -> tuple[dict[str, Any] | None, Path]:
|
|
354
|
+
base = protected_dir or (Path.home() / ".repopact" / "registrations")
|
|
355
|
+
preferred = base / digest(normalize_path(root)) / "registration.json"
|
|
356
|
+
if preferred.is_file():
|
|
357
|
+
state = _read_protected_state(preferred)
|
|
358
|
+
if state is not None:
|
|
359
|
+
return state, preferred
|
|
360
|
+
# Linked worktrees have a different checkout root but share git-common-dir.
|
|
361
|
+
# Locate an authenticated registration by its common-dir binding.
|
|
362
|
+
ident = canonical_identity(root)
|
|
363
|
+
common_digest = digest(ident["git_common_dir"])
|
|
364
|
+
if base.is_dir():
|
|
365
|
+
# Global host guards keep registrations below ``state/registrations``;
|
|
366
|
+
# reference backends keep them directly below the supplied base.
|
|
367
|
+
for candidate in base.rglob("registration.json"):
|
|
368
|
+
state = _read_protected_state(candidate)
|
|
369
|
+
if state is not None and state.get("common_dir_digest") == common_digest:
|
|
370
|
+
return state, candidate
|
|
371
|
+
return None, preferred
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _known_worktree(root: Path, common_dir: str) -> bool:
|
|
375
|
+
listing = _git(root, "worktree", "list", "--porcelain")
|
|
376
|
+
if not listing:
|
|
377
|
+
return False
|
|
378
|
+
wanted = normalize_path(root)
|
|
379
|
+
paths: list[str] = []
|
|
380
|
+
for line in listing.splitlines():
|
|
381
|
+
if line.startswith("worktree "):
|
|
382
|
+
paths.append(normalize_path(line[9:]))
|
|
383
|
+
return wanted in paths
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _save_protected_state(path: Path, state: dict[str, Any]) -> None:
|
|
387
|
+
key = path.with_name("registration.key").read_bytes()
|
|
388
|
+
state.pop("state_mac", None)
|
|
389
|
+
state["state_mac"] = hmac.new(key, canonical_json(state), hashlib.sha256).hexdigest()
|
|
390
|
+
path.write_bytes(canonical_json(state) + b"\n")
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def verify_registration(root: Path, protected_dir: Path | None = None) -> AdmissionDecision:
|
|
394
|
+
policy_path, authority_path, registration_path = _public_paths(root)
|
|
395
|
+
state, p = _protected_state(root, protected_dir)
|
|
396
|
+
if state is None:
|
|
397
|
+
return AdmissionDecision.deny("AUTHORITY_DRIFT" if p.exists() else "UNREGISTERED_REPO", "protected registration is missing, tampered, or unreadable")
|
|
398
|
+
if not registration_path.is_file(): return AdmissionDecision.deny("UNREGISTERED_REPO", "public registration is missing")
|
|
399
|
+
try:
|
|
400
|
+
reg, policy, authority = _record(registration_path), _record(policy_path), _record(authority_path)
|
|
401
|
+
except Exception: return AdmissionDecision.deny("UNREGISTERED_REPO", "public admission records are invalid")
|
|
402
|
+
if state.get("registration_digest") != digest(reg) or state.get("policy_digest") != digest(policy) or state.get("authority_digest") != digest(authority): return AdmissionDecision.deny("AUTHORITY_DRIFT", "protected trust pin does not match public records")
|
|
403
|
+
ident = canonical_identity(root)
|
|
404
|
+
same_checkout = reg.get("repopact_root_digest") == digest(ident["repopact_root"])
|
|
405
|
+
linked_checkout = (state.get("common_dir_digest") == digest(ident["git_common_dir"])
|
|
406
|
+
and reg.get("repository_identity", {}).get("common_dir_digest") == digest(ident["git_common_dir"])
|
|
407
|
+
and _known_worktree(root, ident["git_common_dir"]))
|
|
408
|
+
if not same_checkout and not linked_checkout:
|
|
409
|
+
return AdmissionDecision.deny("WRONG_REPOSITORY", "repository root identity changed")
|
|
410
|
+
if not linked_checkout and reg.get("repository_identity", {}).get("root_digest") != digest(ident["repository_root"]):
|
|
411
|
+
return AdmissionDecision.deny("WRONG_REPOSITORY", "canonical repository identity changed")
|
|
412
|
+
return AdmissionDecision.allow("pre-action", revocation_epoch=state.get("revocation_epoch", 0), policy=policy,
|
|
413
|
+
authority=authority, registration=reg, protected_path=str(p),
|
|
414
|
+
integrity_checked=True, protected_from_gated_principal=False)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _find_work(root: Path, work_id: str) -> tuple[dict[str, Any] | None, Path | None]:
|
|
418
|
+
for p in root.glob(f"work/*/{work_id}*/work-item.json"):
|
|
419
|
+
try: return _record(p), p
|
|
420
|
+
except Exception: return None, p
|
|
421
|
+
return None, None
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
_NO_LEASE_KINDS = {"read/orient", "bootstrap-propose", "bootstrap-amend", "approval-request"}
|
|
425
|
+
_FROZEN_PREFIXES = ("governance/", "repopact/schemas/", ".github/workflows/")
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def _action_kind(action: Mapping[str, Any]) -> str:
|
|
429
|
+
value = str(action.get("kind", "mutation")).strip().lower().replace("_", "-")
|
|
430
|
+
return "read/orient" if value in {"read", "read-only", "orient", "orientation"} else value
|
|
431
|
+
|
|
432
|
+
|
|
433
|
+
def _capability_names(value: Any) -> set[str]:
|
|
434
|
+
if isinstance(value, Mapping):
|
|
435
|
+
return {str(k) for k, enabled in value.items() if enabled}
|
|
436
|
+
return {str(x) for x in (value or [])}
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _lease_path_allowed(path: str, lease_paths: Iterable[Any]) -> bool:
|
|
440
|
+
return any(_match_path(path, str(pattern).replace("\\", "/")) for pattern in lease_paths)
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _frozen_path(path: str) -> bool:
|
|
444
|
+
return path.startswith(_FROZEN_PREFIXES)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _profile_rank(name: Any) -> int:
|
|
448
|
+
return {"observe": 0, "bounded": 1, "repair": 2}.get(str(name), -1)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
def evaluate_action(root: Path, action: Mapping[str, Any], lease: Mapping[str, Any] | None = None,
|
|
452
|
+
guard_health: GuardHealth | None = None, protected_dir: Path | None = None,
|
|
453
|
+
now: datetime | None = None) -> AdmissionDecision:
|
|
454
|
+
# Admission is an opt-in capability. Keep the ordinary RepoPact policy
|
|
455
|
+
# core usable for adopters that have no policy, and make an explicitly
|
|
456
|
+
# disabled policy equally non-blocking. This check must precede health,
|
|
457
|
+
# lease, and registration checks so consulting the API cannot accidentally
|
|
458
|
+
# turn a standalone repository into a fail-closed protected repository.
|
|
459
|
+
try:
|
|
460
|
+
policy = admission_policy(root)
|
|
461
|
+
except ValueError as exc:
|
|
462
|
+
return AdmissionDecision.deny("UNREGISTERED_REPO", str(exc))
|
|
463
|
+
if policy is None:
|
|
464
|
+
return AdmissionDecision.allow("instruction-only", enforcement_required=False,
|
|
465
|
+
provider="none", effective_class="instruction-only",
|
|
466
|
+
reason_code="not-required")
|
|
467
|
+
if policy.get("enabled") is False:
|
|
468
|
+
return AdmissionDecision.allow("instruction-only", enforcement_required=False,
|
|
469
|
+
provider="none", effective_class="instruction-only",
|
|
470
|
+
reason_code="not-required")
|
|
471
|
+
if policy.get("enabled") is not True:
|
|
472
|
+
return AdmissionDecision.deny("UNREGISTERED_REPO", "admission policy must explicitly set enabled=true or false")
|
|
473
|
+
from .enforcement import enforcement_rank, policy_requirement
|
|
474
|
+
requirement = policy_requirement(policy)
|
|
475
|
+
# An enabled policy is an explicit adopter choice. Registration is checked
|
|
476
|
+
# before runtime lease/health checks so missing provider state fails closed
|
|
477
|
+
# with a truthful registration diagnostic.
|
|
478
|
+
identity = verify_registration(root, protected_dir)
|
|
479
|
+
if not identity.allowed:
|
|
480
|
+
return identity
|
|
481
|
+
health = guard_health or GuardHealth(True, protected=False, backend_id="policy-core-unbound")
|
|
482
|
+
# A bare GuardHealth object is not an attestation. Only a backend-owned
|
|
483
|
+
# identity (or an explicitly marked testing backend) may assert protection.
|
|
484
|
+
if not health.backend_id:
|
|
485
|
+
health = GuardHealth(health.healthy, health.security_level, health.reason, False,
|
|
486
|
+
health.integrity_checked, False, health.process_confined,
|
|
487
|
+
health.path_confined, health.service_identity_verified,
|
|
488
|
+
health.host_configuration_protected, health.installed_code_path,
|
|
489
|
+
health.protected_state_path, health.ipc_endpoint, "unbound", False)
|
|
490
|
+
elif not health.testing_only and health.backend_id != "policy-core-unbound":
|
|
491
|
+
# A caller-supplied health structure is not trusted merely because it
|
|
492
|
+
# contains a familiar backend id. Re-attest the selected host backend
|
|
493
|
+
# and fail closed if the claims do not match its current facts.
|
|
494
|
+
from .platform_backends import current_backend
|
|
495
|
+
actual = current_backend(root, protected_dir).attest(root, protected_dir)
|
|
496
|
+
if (health.backend_id != actual.backend_id
|
|
497
|
+
or health.protected != actual.protected_from_gated_principal
|
|
498
|
+
or health.host_configuration_protected != actual.host_configuration_protected):
|
|
499
|
+
health = GuardHealth(health.healthy, "not-covered", "backend attestation mismatch", False,
|
|
500
|
+
health.integrity_checked, False, False, False, False, False,
|
|
501
|
+
actual.installed_code_path, actual.protected_state_path,
|
|
502
|
+
actual.ipc_endpoint, actual.backend_id, False)
|
|
503
|
+
action_kind = _action_kind(action)
|
|
504
|
+
# The explicit in-process TestingBackend is a semantic fixture used by the
|
|
505
|
+
# legacy corpus; it is allowed to exercise policy checks without claiming
|
|
506
|
+
# host/process protection. Production/provider health remains subject to
|
|
507
|
+
# the required-class comparison below.
|
|
508
|
+
if (requirement.required and not health.testing_only
|
|
509
|
+
and enforcement_rank(health.security_level) < enforcement_rank(requirement.minimum_class)):
|
|
510
|
+
return AdmissionDecision.deny(
|
|
511
|
+
"NOT_COVERED",
|
|
512
|
+
f"required {requirement.minimum_class} enforcement is unavailable",
|
|
513
|
+
enforcement_required=True, required_class=requirement.minimum_class,
|
|
514
|
+
effective_class=health.security_level, failure_mode=requirement.failure_mode,
|
|
515
|
+
)
|
|
516
|
+
if lease is None and action_kind not in _NO_LEASE_KINDS:
|
|
517
|
+
# Make the missing operator proof explicit even when the host guard is
|
|
518
|
+
# also unavailable. Both paths fail closed; this stable code helps an
|
|
519
|
+
# adapter request the correct operator workflow.
|
|
520
|
+
return AdmissionDecision.deny("NO_OPERATOR_PROOF", "mutating actions require an operator-derived lease")
|
|
521
|
+
if not health.healthy or (not health.protected and action_kind not in _NO_LEASE_KINDS):
|
|
522
|
+
return AdmissionDecision.deny("GUARD_UNHEALTHY", health.reason or "protected guard is unhealthy")
|
|
523
|
+
# ``identity.details["policy"]`` is the protected, digest-pinned copy of
|
|
524
|
+
# the same opt-in policy. Use it for all authorization decisions below.
|
|
525
|
+
policy = identity.details["policy"]
|
|
526
|
+
# Orientation and bounded bootstrap are intentionally non-mutating and do not
|
|
527
|
+
# need a work item. They can never be used as a source-code write escape.
|
|
528
|
+
if lease is None:
|
|
529
|
+
paths = [str(x).replace("\\", "/") for x in action.get("paths", [])]
|
|
530
|
+
if action_kind == "approval-request" and paths:
|
|
531
|
+
return AdmissionDecision.deny("BOOTSTRAP_SCOPE", "approval requests do not authorize mutation paths")
|
|
532
|
+
if action_kind in {"bootstrap-propose", "bootstrap-amend"}:
|
|
533
|
+
if any(_frozen_path(p) or not _match_path(p, "work/**") for p in paths):
|
|
534
|
+
return AdmissionDecision.deny("BOOTSTRAP_SCOPE", "bootstrap is limited to proposed work records")
|
|
535
|
+
return AdmissionDecision.allow(health.security_level, kind=action_kind)
|
|
536
|
+
|
|
537
|
+
work_id = str(action.get("work_item", "")); item, path = _find_work(root, work_id)
|
|
538
|
+
if not item:
|
|
539
|
+
return AdmissionDecision.deny("NO_WORK_ITEM", "no governed work item")
|
|
540
|
+
if item.get("status") == "proposed":
|
|
541
|
+
return AdmissionDecision.deny("PROPOSED_WORK", "proposed work has no implementation authority")
|
|
542
|
+
if item.get("status") != "active":
|
|
543
|
+
return AdmissionDecision.deny("WRONG_LIFECYCLE", f"work item is {item.get('status')}")
|
|
544
|
+
if not isinstance(item.get("preflight"), dict) or item["preflight"].get("created_before_work_started") is not True:
|
|
545
|
+
return AdmissionDecision.deny("INVALID_PREFLIGHT", "mandatory preflight is missing or invalid")
|
|
546
|
+
|
|
547
|
+
current_ident = canonical_identity(root)
|
|
548
|
+
supplied_identity = action.get("repository_identity")
|
|
549
|
+
actual_digest = digest(current_ident)
|
|
550
|
+
if supplied_identity and supplied_identity != actual_digest and supplied_identity != current_ident:
|
|
551
|
+
return AdmissionDecision.deny("WRONG_REPOSITORY", "request repository identity mismatch")
|
|
552
|
+
if lease.get("repository_identity") != actual_digest:
|
|
553
|
+
return AdmissionDecision.deny("WRONG_REPOSITORY", "lease repository identity mismatch")
|
|
554
|
+
if lease.get("work_item") != work_id:
|
|
555
|
+
return AdmissionDecision.deny("WRONG_WORK_ITEM", "lease work item mismatch")
|
|
556
|
+
if action.get("principal") and lease.get("principal") != action.get("principal"):
|
|
557
|
+
return AdmissionDecision.deny("NO_OPERATOR_PROOF", "lease principal mismatch")
|
|
558
|
+
action_session = action.get("session_id", action.get("adapter_session"))
|
|
559
|
+
if action_session and lease.get("session_id") != action_session:
|
|
560
|
+
return AdmissionDecision.deny("WRONG_SESSION", "lease session mismatch")
|
|
561
|
+
|
|
562
|
+
profile_name = str(action.get("profile") or policy.get("default_profile") or "bounded")
|
|
563
|
+
profile = policy.get("profiles", {}).get(profile_name)
|
|
564
|
+
if not profile:
|
|
565
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", "unknown authorization profile")
|
|
566
|
+
if _profile_rank(profile_name) < 0 or _profile_rank(profile_name) > _profile_rank(lease.get("profile")):
|
|
567
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", "action profile exceeds lease profile")
|
|
568
|
+
if lease.get("approval_class") == "repair" and profile_name != "repair":
|
|
569
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", "repair approval cannot authorize normal actions")
|
|
570
|
+
if profile_name == "observe" and action_kind not in {"read/orient", "approval-request"}:
|
|
571
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", "observe profile is read-only")
|
|
572
|
+
action_mode = str(action.get("mode", "normal"))
|
|
573
|
+
if lease.get("mode", "normal") != action_mode:
|
|
574
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", "action mode exceeds lease mode")
|
|
575
|
+
action_scopes = set(str(x) for x in action.get("scopes", []))
|
|
576
|
+
if action_scopes - set(str(x) for x in lease.get("scopes", [])):
|
|
577
|
+
return AdmissionDecision.deny("SCOPE_VIOLATION", "requested scope exceeds lease")
|
|
578
|
+
action_caps = _capability_names(action.get("capabilities", []))
|
|
579
|
+
if action_caps - _capability_names(lease.get("capabilities", [])):
|
|
580
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", "requested capability exceeds lease")
|
|
581
|
+
required_capability = {"process": "process", "shell": "shell", "network": "network"}.get(action_kind)
|
|
582
|
+
if required_capability and required_capability not in _capability_names(lease.get("capabilities", [])):
|
|
583
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", f"{action_kind} capability is not in lease")
|
|
584
|
+
if required_capability and not profile.get("capabilities", {}).get(required_capability):
|
|
585
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", f"{action_kind} capability is disabled by policy")
|
|
586
|
+
action_lineage = action.get("delegation_lineage")
|
|
587
|
+
if action_lineage is not None and action_lineage != lease.get("delegation_lineage", []):
|
|
588
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "delegation lineage was changed")
|
|
589
|
+
paths = [str(x).replace("\\", "/") for x in action.get("paths", [])]
|
|
590
|
+
if any(not _lease_path_allowed(rel, lease.get("paths", [])) for rel in paths):
|
|
591
|
+
return AdmissionDecision.deny("PATH_VIOLATION", "path exceeds lease allowlist")
|
|
592
|
+
try:
|
|
593
|
+
current = now or datetime.now(timezone.utc)
|
|
594
|
+
if _utc(lease["expires_at"]) <= current.astimezone(timezone.utc):
|
|
595
|
+
return AdmissionDecision.deny("EXPIRED_AUTHORIZATION", "lease expired")
|
|
596
|
+
except Exception:
|
|
597
|
+
return AdmissionDecision.deny("RECEIPT_INVALID", "lease expiry is invalid")
|
|
598
|
+
if lease.get("revocation_epoch") != identity.details.get("revocation_epoch"):
|
|
599
|
+
return AdmissionDecision.deny("REVOKED_AUTHORIZATION", "lease was revoked")
|
|
600
|
+
base = lease.get("base", {})
|
|
601
|
+
if base and (base.get("head") != current_ident.get("head") or base.get("tree") != current_ident.get("tree")):
|
|
602
|
+
return AdmissionDecision.deny("STATE_DRIFT", "repository base changed since authorization")
|
|
603
|
+
if lease.get("authority_state_digest") != digest(identity.details["authority"]) or lease.get("admission_policy_digest") != digest(identity.details["policy"]):
|
|
604
|
+
return AdmissionDecision.deny("AUTHORITY_DRIFT", "authority or policy changed since authorization")
|
|
605
|
+
|
|
606
|
+
repair = action_kind == "repair" or bool(action.get("repair"))
|
|
607
|
+
frozen_approval = lease.get("approval_class") == "frozen" and lease.get("frozen_surface_digest") == frozen_surface_digest(root)
|
|
608
|
+
allowed_scopes = set(profile.get("writable_scopes", []))
|
|
609
|
+
if action_scopes and not (action_scopes <= allowed_scopes or "*" in allowed_scopes or frozen_approval):
|
|
610
|
+
return AdmissionDecision.deny("SCOPE_VIOLATION", "requested scope exceeds profile")
|
|
611
|
+
if repair:
|
|
612
|
+
if profile_name != "repair" or lease.get("approval_class") != "repair" or lease.get("mode") != "repair" or lease.get("delegation_lineage"):
|
|
613
|
+
return AdmissionDecision.deny("BOOTSTRAP_SCOPE", "repair requires a direct repair approval and lease")
|
|
614
|
+
if not profile.get("repair_allowed"):
|
|
615
|
+
return AdmissionDecision.deny("BOOTSTRAP_SCOPE", "repair requires explicit repair profile")
|
|
616
|
+
diagnosed_raw = action.get("diagnosed_paths")
|
|
617
|
+
if not isinstance(diagnosed_raw, (list, tuple, set)):
|
|
618
|
+
return AdmissionDecision.deny("PATH_VIOLATION", "repair requires explicitly diagnosed paths")
|
|
619
|
+
diagnosed = set(str(x).replace("\\", "/") for x in diagnosed_raw)
|
|
620
|
+
if not diagnosed or not diagnosed.issubset(set(paths)):
|
|
621
|
+
return AdmissionDecision.deny("PATH_VIOLATION", "repair paths must be diagnosed")
|
|
622
|
+
return AdmissionDecision.allow(health.security_level, work_item=work_id, profile="repair", repair=True)
|
|
623
|
+
|
|
624
|
+
if any(_frozen_path(rel) for rel in paths) and not frozen_approval and not profile.get("capabilities", {}).get("frozen_surface"):
|
|
625
|
+
return AdmissionDecision.deny("FROZEN_APPROVAL_REQUIRED", "frozen/protected path requires approval")
|
|
626
|
+
if (action.get("frozen") or action_kind == "frozen") and not frozen_approval:
|
|
627
|
+
return AdmissionDecision.deny("FROZEN_APPROVAL_REQUIRED", "operator frozen receipt and matching lease required")
|
|
628
|
+
for rel in paths:
|
|
629
|
+
if rel.startswith("../") or "/../" in rel or rel.startswith("/"):
|
|
630
|
+
return AdmissionDecision.deny("PATH_VIOLATION", "path escapes repository")
|
|
631
|
+
if _frozen_path(rel) and not frozen_approval and not profile.get("capabilities", {}).get("frozen_surface"):
|
|
632
|
+
return AdmissionDecision.deny("FROZEN_APPROVAL_REQUIRED", "frozen/protected path requires approval")
|
|
633
|
+
patterns = profile.get("writable_paths", [])
|
|
634
|
+
if patterns and not any(_match_path(rel, pat) for pat in patterns) and not frozen_approval:
|
|
635
|
+
return AdmissionDecision.deny("PATH_VIOLATION", f"path is outside profile: {rel}")
|
|
636
|
+
return AdmissionDecision.allow(health.security_level, work_item=work_id, profile=profile_name, work_path=str(path) if path else "")
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
def _match_path(path: str, pattern: str) -> bool:
|
|
640
|
+
import fnmatch
|
|
641
|
+
return fnmatch.fnmatch(path, pattern) or (pattern.endswith("/**") and path.startswith(pattern[:-3]))
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def make_request(root: Path, work_item: str, session_id: str, principal: str = "agent", profile: str = "bounded", scopes: Iterable[str] = (), paths: Iterable[str] = (), capabilities: Mapping[str, bool] | None = None, approval_class: str = "activate", mode: str = "normal", expires_at: datetime | None = None, protected_dir: Path | None = None) -> dict[str, Any]:
|
|
645
|
+
policy = admission_policy(root)
|
|
646
|
+
if policy is None or policy.get("enabled") is False:
|
|
647
|
+
raise RuntimeError("protected admission is not required; enable an adopter-owned admission policy before creating a lease request")
|
|
648
|
+
check = verify_registration(root, protected_dir)
|
|
649
|
+
if not check.allowed: raise RuntimeError(check.reason)
|
|
650
|
+
ident = canonical_identity(root); policy, authority = check.details["policy"], check.details["authority"]
|
|
651
|
+
frozen = frozen_surface_digest(root)
|
|
652
|
+
return {"protocol_version": "1", "request_id": str(uuid.uuid4()), "nonce": secrets.token_urlsafe(24), "repository_identity": digest(ident), "repopact_root": ident["repopact_root"], "work_item": work_item, "principal": principal, "adapter_session": session_id, "base": {"head": ident["head"], "tree": ident["tree"]}, "authority_state_digest": digest(authority), "admission_policy_digest": digest(policy), "frozen_surface_digest": frozen, "approval_class": approval_class, "profile": profile, "scopes": sorted(scopes), "paths": sorted(paths), "capabilities": sorted(k for k, v in (capabilities or {}).items() if v), "delegation_ceiling": 0, "mode": mode, "issued_at": iso(), "expires_at": iso(expires_at or (datetime.now(timezone.utc) + timedelta(minutes=30))), "revocation_epoch": check.details.get("revocation_epoch", 0)}
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
def issue_receipt(request: Mapping[str, Any], signer: Ed25519Signer, approval_class: str | None = None) -> dict[str, Any]:
|
|
656
|
+
req = dict(request); req_digest = digest(req)
|
|
657
|
+
return {"receipt_version": "1", "request_digest": req_digest, "operator_id": signer.operator_id, "key_id": signer.key_id, "signature_algorithm": "ed25519", "signature": signer.sign(req), "approval_class": approval_class or req.get("approval_class", "activate"), "issued_at": iso(), "expires_at": req.get("expires_at"), "authority_version": "1", "revocation_epoch": req.get("revocation_epoch", 0)}
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
def verify_receipt(request: Mapping[str, Any], receipt: Mapping[str, Any], authority: Mapping[str, Any], now: datetime | None = None) -> AdmissionDecision:
|
|
661
|
+
if receipt.get("signature_algorithm") != "ed25519": return AdmissionDecision.deny("RECEIPT_INVALID", "unsupported receipt signature algorithm")
|
|
662
|
+
if receipt.get("request_digest") != digest(request): return AdmissionDecision.deny("RECEIPT_INVALID", "receipt is not bound to this request")
|
|
663
|
+
if receipt.get("approval_class") != request.get("approval_class"):
|
|
664
|
+
return AdmissionDecision.deny("RECEIPT_INVALID", "receipt approval class does not match request")
|
|
665
|
+
if receipt.get("expires_at") != request.get("expires_at"):
|
|
666
|
+
return AdmissionDecision.deny("RECEIPT_INVALID", "receipt expiry does not match request")
|
|
667
|
+
if receipt.get("revocation_epoch") != request.get("revocation_epoch"):
|
|
668
|
+
return AdmissionDecision.deny("RECEIPT_INVALID", "receipt revocation epoch does not match request")
|
|
669
|
+
op = next((x for x in authority.get("operators", []) if x.get("operator_id") == receipt.get("operator_id") and x.get("key_id") == receipt.get("key_id")), None)
|
|
670
|
+
if not op or not verify_signature(op.get("public_key", ""), receipt.get("signature", ""), request): return AdmissionDecision.deny("RECEIPT_INVALID", "operator signature is invalid")
|
|
671
|
+
n = now or datetime.now(timezone.utc)
|
|
672
|
+
try:
|
|
673
|
+
if _utc(request["expires_at"]) <= n.astimezone(timezone.utc): return AdmissionDecision.deny("EXPIRED_AUTHORIZATION", "request has expired")
|
|
674
|
+
except Exception: return AdmissionDecision.deny("RECEIPT_INVALID", "invalid receipt expiry")
|
|
675
|
+
allowed = set(authority.get("approval_classes", []))
|
|
676
|
+
if receipt.get("approval_class") not in allowed: return AdmissionDecision.deny("NO_OPERATOR_PROOF", "approval class is not trusted")
|
|
677
|
+
if receipt.get("authority_version") != authority.get("authority_version"):
|
|
678
|
+
return AdmissionDecision.deny("RECEIPT_INVALID", "receipt authority version is stale")
|
|
679
|
+
return AdmissionDecision.allow("pre-action", operator_id=receipt.get("operator_id"))
|
|
680
|
+
|
|
681
|
+
|
|
682
|
+
def issue_lease(request: Mapping[str, Any], receipt: Mapping[str, Any], root: Path, protected_dir: Path | None = None, now: datetime | None = None) -> tuple[AdmissionDecision, dict[str, Any] | None]:
|
|
683
|
+
check = verify_registration(root, protected_dir)
|
|
684
|
+
if not check.allowed: return check, None
|
|
685
|
+
vr = verify_receipt(request, receipt, check.details["authority"], now)
|
|
686
|
+
if not vr.allowed: return vr, None
|
|
687
|
+
state, state_path = _protected_state(root, protected_dir)
|
|
688
|
+
request_digest = digest(request)
|
|
689
|
+
if state is None: return AdmissionDecision.deny("GUARD_UNHEALTHY", "protected state unavailable"), None
|
|
690
|
+
if request_digest in set(state.get("used_request_digests", [])):
|
|
691
|
+
return AdmissionDecision.deny("RECEIPT_REPLAY", "authorization request has already been consumed"), None
|
|
692
|
+
state.setdefault("used_request_digests", []).append(request_digest)
|
|
693
|
+
_save_protected_state(state_path, state)
|
|
694
|
+
lease = {"lease_version": 1, "lease_id": str(uuid.uuid4()), "request_digest": request_digest,
|
|
695
|
+
"repository_identity": request["repository_identity"], "repopact_root": request.get("repopact_root"),
|
|
696
|
+
"work_item": request["work_item"], "principal": request["principal"], "session_id": request["adapter_session"],
|
|
697
|
+
"approval_class": request.get("approval_class"), "profile": request["profile"], "mode": request.get("mode", "normal"),
|
|
698
|
+
"scopes": request["scopes"], "paths": request["paths"], "capabilities": request.get("capabilities", []),
|
|
699
|
+
"frozen_surface_digest": request.get("frozen_surface_digest"), "delegation_lineage": request.get("delegation_lineage", []),
|
|
700
|
+
"delegation_ceiling": request.get("delegation_ceiling", 0), "base": request["base"],
|
|
701
|
+
"authority_state_digest": request["authority_state_digest"], "admission_policy_digest": request["admission_policy_digest"],
|
|
702
|
+
"issued_at": iso(now), "expires_at": request["expires_at"], "revocation_epoch": check.details.get("revocation_epoch", 0)}
|
|
703
|
+
return AdmissionDecision.allow("pre-action"), lease
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def revoke(root: Path, protected_dir: Path | None = None, *, request: Mapping[str, Any] | None = None,
|
|
707
|
+
receipt: Mapping[str, Any] | None = None) -> int:
|
|
708
|
+
"""Apply a revocation transition only after a signed revoke receipt."""
|
|
709
|
+
if request is None or receipt is None:
|
|
710
|
+
raise SignerError("operator receipt required for revocation")
|
|
711
|
+
identity = verify_registration(root, protected_dir)
|
|
712
|
+
if not identity.allowed:
|
|
713
|
+
raise RuntimeError(identity.reason)
|
|
714
|
+
if request.get("approval_class") != "revoke" or receipt.get("approval_class") != "revoke":
|
|
715
|
+
raise SignerError("revocation requires the revoke approval class")
|
|
716
|
+
proof = verify_receipt(request, receipt, identity.details["authority"])
|
|
717
|
+
if not proof.allowed:
|
|
718
|
+
raise SignerError(proof.reason)
|
|
719
|
+
state, p = _protected_state(root, protected_dir)
|
|
720
|
+
if state is None: raise RuntimeError("protected registration missing")
|
|
721
|
+
state["revocation_epoch"] = int(state.get("revocation_epoch", 0)) + 1
|
|
722
|
+
_save_protected_state(p, state); return state["revocation_epoch"]
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
def operator_revoke(root: Path, signer: Ed25519Signer, protected_dir: Path | None = None) -> int:
|
|
726
|
+
"""Create and consume a direct operator-controlled revocation approval."""
|
|
727
|
+
request = make_request(root, "000", "operator-revocation", principal=signer.operator_id,
|
|
728
|
+
profile="observe", scopes=(), paths=(), capabilities={},
|
|
729
|
+
approval_class="revoke", mode="normal", protected_dir=protected_dir)
|
|
730
|
+
receipt = issue_receipt(request, signer, "revoke")
|
|
731
|
+
return revoke(root, protected_dir, request=request, receipt=receipt)
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def delegation_subset(parent: Mapping[str, Any], child: Mapping[str, Any]) -> AdmissionDecision:
|
|
735
|
+
if child.get("repository_identity") != parent.get("repository_identity") or child.get("work_item") != parent.get("work_item"):
|
|
736
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "delegation changed repository or work item")
|
|
737
|
+
if child.get("principal") in {None, ""} or child.get("principal") == parent.get("principal"):
|
|
738
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "child principal must be distinct")
|
|
739
|
+
if parent.get("approval_class") in {"frozen", "revoke", "recovery"} or child.get("approval_class") in {"frozen", "revoke", "recovery"}:
|
|
740
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "sensitive approval classes cannot be delegated")
|
|
741
|
+
if child.get("approval_class") != parent.get("approval_class") or child.get("mode", "normal") != parent.get("mode", "normal"):
|
|
742
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "delegation changed approval semantics")
|
|
743
|
+
if int(child.get("delegation_ceiling", 0)) >= int(parent.get("delegation_ceiling", 1)):
|
|
744
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "delegation depth is not reduced")
|
|
745
|
+
if set(child.get("scopes", [])) - set(parent.get("scopes", [])):
|
|
746
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "scope exceeds parent")
|
|
747
|
+
if set(child.get("paths", [])) - set(parent.get("paths", [])):
|
|
748
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "paths exceed parent")
|
|
749
|
+
if _capability_names(child.get("capabilities", [])) - _capability_names(parent.get("capabilities", [])):
|
|
750
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "capability exceeds parent")
|
|
751
|
+
if _profile_rank(child.get("profile")) < 0 or _profile_rank(child.get("profile")) > _profile_rank(parent.get("profile")):
|
|
752
|
+
return AdmissionDecision.deny("PROFILE_ESCALATION", "delegation changed profile")
|
|
753
|
+
if _utc(child.get("expires_at")) > _utc(parent.get("expires_at")):
|
|
754
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "expiry exceeds parent")
|
|
755
|
+
parent_lineage = list(parent.get("delegation_lineage", []))
|
|
756
|
+
expected_lineage = parent_lineage + [parent.get("lease_id")]
|
|
757
|
+
if child.get("parent_lease_id") != parent.get("lease_id") or child.get("delegation_lineage") != expected_lineage:
|
|
758
|
+
return AdmissionDecision.deny("DELEGATION_ESCALATION", "delegation lineage is missing or altered")
|
|
759
|
+
return AdmissionDecision.allow("pre-action")
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def issue_child_lease(parent: Mapping[str, Any], child: Mapping[str, Any]) -> tuple[AdmissionDecision, dict[str, Any] | None]:
|
|
763
|
+
"""Derive a child lease as a strict, lineage-preserving subset of a parent."""
|
|
764
|
+
check = delegation_subset(parent, child)
|
|
765
|
+
if not check.allowed:
|
|
766
|
+
return check, None
|
|
767
|
+
lease = dict(child)
|
|
768
|
+
lease.setdefault("lease_version", 1)
|
|
769
|
+
lease.setdefault("lease_id", str(uuid.uuid4()))
|
|
770
|
+
lease.setdefault("request_digest", digest(child))
|
|
771
|
+
lease["parent_lease_id"] = parent.get("lease_id")
|
|
772
|
+
lease["delegation_lineage"] = list(parent.get("delegation_lineage", [])) + [parent.get("lease_id")]
|
|
773
|
+
lease["revocation_epoch"] = parent.get("revocation_epoch")
|
|
774
|
+
return AdmissionDecision.allow("pre-action"), lease
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def safe_audit(decision: AdmissionDecision, request: Mapping[str, Any] | None = None) -> dict[str, Any]:
|
|
778
|
+
return {"event": "admission", "allowed": decision.allowed, "code": decision.code, "reason": decision.reason, "enforcement": decision.enforcement, "request_digest": digest(request) if request else None}
|
|
779
|
+
|
|
780
|
+
|
|
781
|
+
def diagnose(root: Path, protected_dir: Path | None = None) -> list[dict[str, Any]]:
|
|
782
|
+
try:
|
|
783
|
+
policy = admission_policy(root)
|
|
784
|
+
except ValueError as exc:
|
|
785
|
+
return [{"severity": "warn", "code": "UNREGISTERED_REPO", "message": str(exc),
|
|
786
|
+
"enforcement_required": True, "provider": "none", "effective_class": "not-covered"}]
|
|
787
|
+
if policy is None or policy.get("enabled") is False:
|
|
788
|
+
return [{"severity": "info", "code": "ADMISSION_NOT_REQUIRED",
|
|
789
|
+
"message": "protected admission is opt-in; standalone RepoPact mode is valid",
|
|
790
|
+
"enforcement_required": False, "provider": "none", "effective_class": "instruction-only",
|
|
791
|
+
"valid": True}]
|
|
792
|
+
result = verify_registration(root, protected_dir)
|
|
793
|
+
from .enforcement import resolve_enforcement_requirement
|
|
794
|
+
if result.allowed:
|
|
795
|
+
resolution = resolve_enforcement_requirement(policy, None, adapter_class="pre-action", root=root)
|
|
796
|
+
if resolution.satisfied:
|
|
797
|
+
return [{"severity": "info", "code": "ADMISSION_READY", "message": "protected admission registration and provider coverage are healthy",
|
|
798
|
+
"enforcement_required": True, "provider": "registered", "effective_class": resolution.effective_class,
|
|
799
|
+
"valid": True}]
|
|
800
|
+
return [{"severity": "warn", "code": "ADMISSION_PROVIDER_REQUIRED", "message": resolution.reason,
|
|
801
|
+
"enforcement_required": True, "provider": "none", "effective_class": resolution.effective_class,
|
|
802
|
+
"valid": False}]
|
|
803
|
+
return [{"severity": "warn", "code": result.code, "message": result.reason,
|
|
804
|
+
"enforcement_required": True, "provider": "none", "effective_class": "not-covered", "valid": False}]
|