authority-runtime 0.3.0__py3-none-any.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.
- authority_runtime/__init__.py +139 -0
- authority_runtime/approvals.py +267 -0
- authority_runtime/backends/__init__.py +16 -0
- authority_runtime/backends/memory.py +296 -0
- authority_runtime/backends/slos.py +555 -0
- authority_runtime/cli.py +1405 -0
- authority_runtime/compiler.py +719 -0
- authority_runtime/compliance.py +572 -0
- authority_runtime/constraints.py +124 -0
- authority_runtime/crypto.py +212 -0
- authority_runtime/enforce.py +590 -0
- authority_runtime/envelope.py +575 -0
- authority_runtime/keys.py +212 -0
- authority_runtime/langgraph.py +407 -0
- authority_runtime/logging_config.py +71 -0
- authority_runtime/mcp_server.py +1431 -0
- authority_runtime/policy.py +245 -0
- authority_runtime/roles.py +539 -0
- authority_runtime/shell.py +489 -0
- authority_runtime/storage.py +970 -0
- authority_runtime/types.py +281 -0
- authority_runtime/validation.py +428 -0
- authority_runtime/vault_scope.py +175 -0
- authority_runtime-0.3.0.dist-info/METADATA +220 -0
- authority_runtime-0.3.0.dist-info/RECORD +29 -0
- authority_runtime-0.3.0.dist-info/WHEEL +5 -0
- authority_runtime-0.3.0.dist-info/entry_points.txt +2 -0
- authority_runtime-0.3.0.dist-info/licenses/LICENSE +89 -0
- authority_runtime-0.3.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Authority Runtime - Constraint Enforcement
|
|
3
|
+
|
|
4
|
+
Pure-function constraint checkers that evaluate an envelope's constraints dict
|
|
5
|
+
against the current action, resource, and context. Called by enforce.py after
|
|
6
|
+
scope validation passes.
|
|
7
|
+
|
|
8
|
+
Supported constraint keys:
|
|
9
|
+
- require_purpose: bool — access must include a non-empty purpose string in context
|
|
10
|
+
- denied_resources: list[str] — explicit deny list with glob matching (fnmatch)
|
|
11
|
+
- max_records_per_request: int — limits returned record count (context must include "record_count")
|
|
12
|
+
- write_requires_approval: bool — write actions return REQUIRE_APPROVAL instead of allowing
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from fnmatch import fnmatch
|
|
17
|
+
from typing import Any, Dict, List, Optional
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class ConstraintResult:
|
|
22
|
+
"""Result of constraint evaluation."""
|
|
23
|
+
|
|
24
|
+
allowed: bool
|
|
25
|
+
violated: List[str] = field(default_factory=list)
|
|
26
|
+
warnings: List[str] = field(default_factory=list)
|
|
27
|
+
require_approval: bool = False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check_constraints(
|
|
31
|
+
constraints: Dict[str, Any],
|
|
32
|
+
action: str,
|
|
33
|
+
resource: Optional[str] = None,
|
|
34
|
+
context: Optional[Dict[str, Any]] = None,
|
|
35
|
+
) -> ConstraintResult:
|
|
36
|
+
"""
|
|
37
|
+
Evaluate all constraints against the current request.
|
|
38
|
+
|
|
39
|
+
Returns a ConstraintResult. If any constraint is violated, allowed=False
|
|
40
|
+
and violated contains human-readable descriptions of each violation.
|
|
41
|
+
|
|
42
|
+
Empty constraints dict always returns allowed=True (backward compat).
|
|
43
|
+
"""
|
|
44
|
+
if not constraints:
|
|
45
|
+
return ConstraintResult(allowed=True)
|
|
46
|
+
|
|
47
|
+
ctx = context or {}
|
|
48
|
+
violations: List[str] = []
|
|
49
|
+
warnings: List[str] = []
|
|
50
|
+
require_approval = False
|
|
51
|
+
|
|
52
|
+
# Check each constraint
|
|
53
|
+
if constraints.get("require_purpose"):
|
|
54
|
+
v = _check_require_purpose(ctx)
|
|
55
|
+
if v:
|
|
56
|
+
violations.append(v)
|
|
57
|
+
|
|
58
|
+
if "denied_resources" in constraints and resource:
|
|
59
|
+
v = _check_denied_resources(constraints["denied_resources"], resource)
|
|
60
|
+
if v:
|
|
61
|
+
violations.append(v)
|
|
62
|
+
|
|
63
|
+
if "max_records_per_request" in constraints:
|
|
64
|
+
v = _check_max_records(constraints["max_records_per_request"], ctx)
|
|
65
|
+
if v:
|
|
66
|
+
violations.append(v)
|
|
67
|
+
|
|
68
|
+
if constraints.get("write_requires_approval"):
|
|
69
|
+
result = _check_write_requires_approval(action)
|
|
70
|
+
if result == "require_approval":
|
|
71
|
+
require_approval = True
|
|
72
|
+
elif result:
|
|
73
|
+
violations.append(result)
|
|
74
|
+
|
|
75
|
+
if violations:
|
|
76
|
+
return ConstraintResult(allowed=False, violated=violations, warnings=warnings)
|
|
77
|
+
|
|
78
|
+
if require_approval:
|
|
79
|
+
return ConstraintResult(
|
|
80
|
+
allowed=False,
|
|
81
|
+
require_approval=True,
|
|
82
|
+
warnings=["Write action requires human approval"],
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
return ConstraintResult(allowed=True, warnings=warnings)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _check_require_purpose(context: Dict[str, Any]) -> Optional[str]:
|
|
89
|
+
"""Access must include a non-empty purpose string."""
|
|
90
|
+
purpose = context.get("purpose")
|
|
91
|
+
if not purpose or (isinstance(purpose, str) and not purpose.strip()):
|
|
92
|
+
return "Constraint 'require_purpose': access must include a non-empty purpose"
|
|
93
|
+
return None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _check_denied_resources(
|
|
97
|
+
denied_patterns: List[str], resource: str
|
|
98
|
+
) -> Optional[str]:
|
|
99
|
+
"""Resource must not match any denied pattern (fnmatch glob)."""
|
|
100
|
+
for pattern in denied_patterns:
|
|
101
|
+
if fnmatch(resource, pattern):
|
|
102
|
+
return (
|
|
103
|
+
f"Constraint 'denied_resources': resource '{resource}' "
|
|
104
|
+
f"matches denied pattern '{pattern}'"
|
|
105
|
+
)
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _check_max_records(max_records: int, context: Dict[str, Any]) -> Optional[str]:
|
|
110
|
+
"""If context includes record_count, it must not exceed the limit."""
|
|
111
|
+
record_count = context.get("record_count")
|
|
112
|
+
if record_count is not None and record_count > max_records:
|
|
113
|
+
return (
|
|
114
|
+
f"Constraint 'max_records_per_request': requested {record_count} records "
|
|
115
|
+
f"but limit is {max_records}"
|
|
116
|
+
)
|
|
117
|
+
return None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _check_write_requires_approval(action: str) -> Optional[str]:
|
|
121
|
+
"""Write actions require human approval."""
|
|
122
|
+
if action in ("write", "create", "update", "delete"):
|
|
123
|
+
return "require_approval"
|
|
124
|
+
return None
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Carryall Vault Encryption — age-x25519 encryption at rest for SLOS documents.
|
|
3
|
+
|
|
4
|
+
Encrypts document bodies before they hit disk, decrypts on read.
|
|
5
|
+
Frontmatter stays plaintext so metadata queries continue to work.
|
|
6
|
+
|
|
7
|
+
Encryption is applied based on vault sensitivity:
|
|
8
|
+
- restricted (health, meta) → always encrypted
|
|
9
|
+
- confidential (finance, family) → always encrypted
|
|
10
|
+
- internal (community, personal, startup) → plaintext
|
|
11
|
+
|
|
12
|
+
Key management:
|
|
13
|
+
- One age x25519 keypair per vault domain
|
|
14
|
+
- Keys stored in {keys_dir}/vault-encryption/{domain}.key (identity)
|
|
15
|
+
- Public keys stored in {keys_dir}/vault-encryption/{domain}.pub
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import logging
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Optional
|
|
21
|
+
|
|
22
|
+
import pyrage
|
|
23
|
+
from pyrage import x25519
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
# Sensitivity levels that require encryption
|
|
28
|
+
ENCRYPTED_SENSITIVITIES = {"restricted", "confidential"}
|
|
29
|
+
|
|
30
|
+
# Default sensitivity per vault domain
|
|
31
|
+
VAULT_SENSITIVITY = {
|
|
32
|
+
"health": "restricted",
|
|
33
|
+
"meta": "restricted",
|
|
34
|
+
"finance": "confidential",
|
|
35
|
+
"family": "confidential",
|
|
36
|
+
"personal": "internal",
|
|
37
|
+
"community": "internal",
|
|
38
|
+
"startup": "internal",
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
AGE_HEADER = "-----BEGIN AGE ENCRYPTED FILE-----"
|
|
42
|
+
AGE_ARMOR_PREFIX = "age-encryption.org/v1"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _encryption_keys_dir(keys_dir: Path) -> Path:
|
|
46
|
+
"""Return the vault-encryption subdirectory within the keys directory."""
|
|
47
|
+
return keys_dir / "vault-encryption"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def generate_vault_keypair(keys_dir: Path, domain: str) -> tuple[str, str]:
|
|
51
|
+
"""
|
|
52
|
+
Generate an age x25519 keypair for a vault domain.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
keys_dir: Base keys directory (e.g. ~/slos/config/carryall/keys/)
|
|
56
|
+
domain: Vault domain name (e.g. "health", "finance")
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
Tuple of (public_key_str, identity_str)
|
|
60
|
+
"""
|
|
61
|
+
enc_dir = _encryption_keys_dir(keys_dir)
|
|
62
|
+
enc_dir.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
|
|
64
|
+
identity = x25519.Identity.generate()
|
|
65
|
+
recipient = identity.to_public()
|
|
66
|
+
|
|
67
|
+
identity_str = str(identity)
|
|
68
|
+
public_str = str(recipient)
|
|
69
|
+
|
|
70
|
+
# Write identity (secret key)
|
|
71
|
+
key_path = enc_dir / f"{domain}.key"
|
|
72
|
+
key_path.write_text(identity_str + "\n")
|
|
73
|
+
key_path.chmod(0o600)
|
|
74
|
+
|
|
75
|
+
# Write public key
|
|
76
|
+
pub_path = enc_dir / f"{domain}.pub"
|
|
77
|
+
pub_path.write_text(public_str + "\n")
|
|
78
|
+
pub_path.chmod(0o644)
|
|
79
|
+
|
|
80
|
+
logger.info(f"Generated vault encryption keypair for {domain}: {public_str}")
|
|
81
|
+
return public_str, identity_str
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _load_recipient(keys_dir: Path, domain: str) -> x25519.Recipient:
|
|
85
|
+
"""Load the age public key (recipient) for a vault domain."""
|
|
86
|
+
pub_path = _encryption_keys_dir(keys_dir) / f"{domain}.pub"
|
|
87
|
+
if not pub_path.exists():
|
|
88
|
+
raise FileNotFoundError(
|
|
89
|
+
f"No encryption public key for vault '{domain}' at {pub_path}. "
|
|
90
|
+
f"Generate one with: carryall vault generate-encryption-key {domain}"
|
|
91
|
+
)
|
|
92
|
+
public_str = pub_path.read_text().strip()
|
|
93
|
+
return x25519.Recipient.from_str(public_str)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _load_identity(keys_dir: Path, domain: str) -> x25519.Identity:
|
|
97
|
+
"""Load the age secret key (identity) for a vault domain."""
|
|
98
|
+
key_path = _encryption_keys_dir(keys_dir) / f"{domain}.key"
|
|
99
|
+
if not key_path.exists():
|
|
100
|
+
raise FileNotFoundError(
|
|
101
|
+
f"No encryption secret key for vault '{domain}' at {key_path}. "
|
|
102
|
+
f"Generate one with: carryall vault generate-encryption-key {domain}"
|
|
103
|
+
)
|
|
104
|
+
identity_str = key_path.read_text().strip()
|
|
105
|
+
return x25519.Identity.from_str(identity_str)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def is_encrypted(content: str) -> bool:
|
|
109
|
+
"""Check if document content is age-encrypted."""
|
|
110
|
+
stripped = content.strip()
|
|
111
|
+
return stripped.startswith(AGE_HEADER) or stripped.startswith(AGE_ARMOR_PREFIX)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def should_encrypt(domain: str, sensitivity: Optional[str] = None) -> bool:
|
|
115
|
+
"""
|
|
116
|
+
Determine if a document should be encrypted based on domain and sensitivity.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
domain: Vault domain name
|
|
120
|
+
sensitivity: Document sensitivity level (falls back to domain default)
|
|
121
|
+
"""
|
|
122
|
+
effective_sensitivity = sensitivity or VAULT_SENSITIVITY.get(domain, "internal")
|
|
123
|
+
return effective_sensitivity in ENCRYPTED_SENSITIVITIES
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def encrypt_body(plaintext: str, domain: str, keys_dir: Path) -> str:
|
|
127
|
+
"""
|
|
128
|
+
Encrypt a document body using the vault's age public key.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
plaintext: Document body content (markdown)
|
|
132
|
+
domain: Vault domain name
|
|
133
|
+
keys_dir: Base keys directory
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
Age-encrypted ciphertext (binary, to be stored as-is)
|
|
137
|
+
"""
|
|
138
|
+
recipient = _load_recipient(keys_dir, domain)
|
|
139
|
+
encrypted = pyrage.encrypt(plaintext.encode("utf-8"), [recipient])
|
|
140
|
+
# Return as latin-1 string so it can be stored in the markdown body
|
|
141
|
+
# The SLOS runtime writes it as bytes in the document
|
|
142
|
+
return encrypted.decode("latin-1")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def decrypt_body(ciphertext: str, domain: str, keys_dir: Path) -> str:
|
|
146
|
+
"""
|
|
147
|
+
Decrypt a document body using the vault's age secret key.
|
|
148
|
+
|
|
149
|
+
Args:
|
|
150
|
+
ciphertext: Age-encrypted content
|
|
151
|
+
domain: Vault domain name
|
|
152
|
+
keys_dir: Base keys directory
|
|
153
|
+
|
|
154
|
+
Returns:
|
|
155
|
+
Decrypted plaintext (utf-8 string)
|
|
156
|
+
"""
|
|
157
|
+
identity = _load_identity(keys_dir, domain)
|
|
158
|
+
# Convert back from latin-1 string to bytes for decryption
|
|
159
|
+
decrypted = pyrage.decrypt(ciphertext.encode("latin-1"), [identity])
|
|
160
|
+
return decrypted.decode("utf-8")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def encrypt_document(content: str, domain: str, sensitivity: str, keys_dir: Path) -> tuple[str, bool]:
|
|
164
|
+
"""
|
|
165
|
+
Conditionally encrypt a full document body.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
content: Document body (after frontmatter)
|
|
169
|
+
domain: Vault domain name
|
|
170
|
+
sensitivity: Document sensitivity level
|
|
171
|
+
keys_dir: Base keys directory
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
Tuple of (content, was_encrypted). Content is encrypted if sensitivity warrants it.
|
|
175
|
+
"""
|
|
176
|
+
if not should_encrypt(domain, sensitivity):
|
|
177
|
+
return content, False
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
encrypted = encrypt_body(content, domain, keys_dir)
|
|
181
|
+
return encrypted, True
|
|
182
|
+
except FileNotFoundError:
|
|
183
|
+
logger.warning(
|
|
184
|
+
f"No encryption key for vault '{domain}' — writing plaintext. "
|
|
185
|
+
f"Generate keys with: carryall vault generate-encryption-key {domain}"
|
|
186
|
+
)
|
|
187
|
+
return content, False
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def decrypt_document(content: str, domain: str, keys_dir: Path) -> str:
|
|
191
|
+
"""
|
|
192
|
+
Conditionally decrypt a document body. Returns plaintext as-is.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
content: Document content (may or may not be encrypted)
|
|
196
|
+
domain: Vault domain name
|
|
197
|
+
keys_dir: Base keys directory
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
Decrypted content (or original if not encrypted)
|
|
201
|
+
"""
|
|
202
|
+
if not is_encrypted(content):
|
|
203
|
+
return content
|
|
204
|
+
|
|
205
|
+
try:
|
|
206
|
+
return decrypt_body(content, domain, keys_dir)
|
|
207
|
+
except FileNotFoundError:
|
|
208
|
+
logger.error(f"Cannot decrypt document from vault '{domain}' — missing key")
|
|
209
|
+
raise
|
|
210
|
+
except Exception as e:
|
|
211
|
+
logger.error(f"Decryption failed for vault '{domain}': {e}")
|
|
212
|
+
raise
|