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,575 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Authority Envelope implementation with Ed25519 signing
|
|
3
|
+
|
|
4
|
+
Port of the TypeScript envelope system to Python.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import uuid
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
from typing import Optional, Dict, Any, List
|
|
11
|
+
|
|
12
|
+
import nacl.signing
|
|
13
|
+
import nacl.encoding
|
|
14
|
+
|
|
15
|
+
from .types import (
|
|
16
|
+
AuthorityEnvelope,
|
|
17
|
+
Authority,
|
|
18
|
+
Context,
|
|
19
|
+
Skill,
|
|
20
|
+
SkillParameters,
|
|
21
|
+
ExecutionConfig,
|
|
22
|
+
NarrowingResult,
|
|
23
|
+
DecisionContext,
|
|
24
|
+
)
|
|
25
|
+
from .validation import ValidationError
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def generate_key_pair() -> tuple[str, str]:
|
|
29
|
+
"""
|
|
30
|
+
Generate an Ed25519 key pair for envelope signing.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
Tuple of (private_key_hex, public_key_hex)
|
|
34
|
+
"""
|
|
35
|
+
signing_key = nacl.signing.SigningKey.generate()
|
|
36
|
+
verify_key = signing_key.verify_key
|
|
37
|
+
|
|
38
|
+
private_key = signing_key.encode(encoder=nacl.encoding.HexEncoder).decode("utf-8")
|
|
39
|
+
public_key = verify_key.encode(encoder=nacl.encoding.HexEncoder).decode("utf-8")
|
|
40
|
+
|
|
41
|
+
return (private_key, public_key)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _canonical_json(data: Dict[str, Any]) -> str:
|
|
45
|
+
"""
|
|
46
|
+
Create canonical JSON string for deterministic signing.
|
|
47
|
+
|
|
48
|
+
Ensures:
|
|
49
|
+
- Keys are sorted alphabetically
|
|
50
|
+
- No whitespace
|
|
51
|
+
- Consistent serialization
|
|
52
|
+
"""
|
|
53
|
+
return json.dumps(data, sort_keys=True, separators=(",", ":"))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _sign_envelope(envelope_data: Dict[str, Any], private_key: str) -> str:
|
|
57
|
+
"""
|
|
58
|
+
Sign envelope data with Ed25519 private key.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
envelope_data: Envelope dict (signature field will be removed if present)
|
|
62
|
+
private_key: Hex-encoded Ed25519 private key
|
|
63
|
+
|
|
64
|
+
Returns:
|
|
65
|
+
Hex-encoded signature
|
|
66
|
+
"""
|
|
67
|
+
# Remove signature field if present
|
|
68
|
+
data_to_sign = {k: v for k, v in envelope_data.items() if k != "signature"}
|
|
69
|
+
|
|
70
|
+
# Create canonical JSON
|
|
71
|
+
canonical = _canonical_json(data_to_sign)
|
|
72
|
+
|
|
73
|
+
# Sign with Ed25519
|
|
74
|
+
signing_key = nacl.signing.SigningKey(
|
|
75
|
+
private_key, encoder=nacl.encoding.HexEncoder
|
|
76
|
+
)
|
|
77
|
+
signed = signing_key.sign(canonical.encode("utf-8"))
|
|
78
|
+
|
|
79
|
+
# Return signature as hex string
|
|
80
|
+
return signed.signature.hex()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def verify_signature(
|
|
84
|
+
envelope: AuthorityEnvelope, public_key: str
|
|
85
|
+
) -> bool:
|
|
86
|
+
"""
|
|
87
|
+
Verify envelope signature with Ed25519 public key.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
envelope: Complete envelope with signature
|
|
91
|
+
public_key: Hex-encoded Ed25519 public key
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
True if signature is valid
|
|
95
|
+
"""
|
|
96
|
+
# Extract signature and remove from envelope
|
|
97
|
+
signature = envelope.signature
|
|
98
|
+
envelope_dict = envelope.model_dump()
|
|
99
|
+
del envelope_dict["signature"]
|
|
100
|
+
|
|
101
|
+
# Create canonical JSON
|
|
102
|
+
canonical = _canonical_json(envelope_dict)
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
# Verify signature
|
|
106
|
+
verify_key = nacl.signing.VerifyKey(
|
|
107
|
+
public_key, encoder=nacl.encoding.HexEncoder
|
|
108
|
+
)
|
|
109
|
+
verify_key.verify(
|
|
110
|
+
canonical.encode("utf-8"),
|
|
111
|
+
bytes.fromhex(signature),
|
|
112
|
+
)
|
|
113
|
+
return True
|
|
114
|
+
except nacl.exceptions.BadSignatureError:
|
|
115
|
+
return False
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def create_envelope(
|
|
119
|
+
agent_id: str,
|
|
120
|
+
provider: str,
|
|
121
|
+
step_number: int,
|
|
122
|
+
root_policy_id: str,
|
|
123
|
+
skill: Skill,
|
|
124
|
+
authority: Authority,
|
|
125
|
+
context: Context,
|
|
126
|
+
execution: ExecutionConfig,
|
|
127
|
+
private_key: str,
|
|
128
|
+
parent_envelope_id: Optional[str] = None,
|
|
129
|
+
ttl_seconds: int = 300,
|
|
130
|
+
decision_context: Optional["DecisionContext"] = None,
|
|
131
|
+
) -> AuthorityEnvelope:
|
|
132
|
+
"""
|
|
133
|
+
Create a new authority envelope with cryptographic signature.
|
|
134
|
+
|
|
135
|
+
Args:
|
|
136
|
+
agent_id: Unique agent identifier
|
|
137
|
+
provider: LLM provider ('claude', 'openai', 'gemini', 'custom')
|
|
138
|
+
step_number: Step number in execution chain (1-indexed)
|
|
139
|
+
root_policy_id: Root policy ID
|
|
140
|
+
skill: Skill being authorized
|
|
141
|
+
authority: Permission scopes
|
|
142
|
+
context: Available context fields
|
|
143
|
+
execution: Provider-specific execution config
|
|
144
|
+
private_key: Hex-encoded Ed25519 private key for signing
|
|
145
|
+
parent_envelope_id: Parent envelope ID (None for root)
|
|
146
|
+
ttl_seconds: Time-to-live in seconds
|
|
147
|
+
decision_context: Optional decision-time context explaining WHY this action was chosen
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Signed AuthorityEnvelope
|
|
151
|
+
|
|
152
|
+
Raises:
|
|
153
|
+
ValidationError: If input validation fails
|
|
154
|
+
"""
|
|
155
|
+
# Import validation functions
|
|
156
|
+
from .validation import (
|
|
157
|
+
validate_agent_id,
|
|
158
|
+
validate_provider,
|
|
159
|
+
validate_step_number,
|
|
160
|
+
validate_scopes,
|
|
161
|
+
validate_resources,
|
|
162
|
+
validate_ttl_seconds,
|
|
163
|
+
validate_private_key,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
# Validate inputs
|
|
167
|
+
validate_agent_id(agent_id)
|
|
168
|
+
validate_provider(provider)
|
|
169
|
+
validate_step_number(step_number)
|
|
170
|
+
validate_scopes(authority.scopes)
|
|
171
|
+
validate_resources(authority.resources)
|
|
172
|
+
validate_ttl_seconds(ttl_seconds)
|
|
173
|
+
validate_private_key(private_key)
|
|
174
|
+
|
|
175
|
+
now = datetime.now(timezone.utc)
|
|
176
|
+
expires = now + timedelta(seconds=ttl_seconds)
|
|
177
|
+
|
|
178
|
+
# Create envelope without signature
|
|
179
|
+
# Format timestamps without timezone offset, then add Z suffix
|
|
180
|
+
created_at_str = now.replace(tzinfo=None).isoformat() + "Z"
|
|
181
|
+
expires_at_str = expires.replace(tzinfo=None).isoformat() + "Z"
|
|
182
|
+
|
|
183
|
+
envelope_data = {
|
|
184
|
+
"envelope_id": f"env-{uuid.uuid4().hex[:12]}",
|
|
185
|
+
"version": "1.0.0",
|
|
186
|
+
"created_at": created_at_str,
|
|
187
|
+
"expires_at": expires_at_str,
|
|
188
|
+
"agent_id": agent_id,
|
|
189
|
+
"provider": provider,
|
|
190
|
+
"step_number": step_number,
|
|
191
|
+
"parent_envelope_id": parent_envelope_id,
|
|
192
|
+
"root_policy_id": root_policy_id,
|
|
193
|
+
"skill": skill.model_dump(),
|
|
194
|
+
"authority": authority.model_dump(),
|
|
195
|
+
"context": context.model_dump(),
|
|
196
|
+
"decision_context": decision_context.model_dump() if decision_context else None,
|
|
197
|
+
"execution": execution.model_dump(),
|
|
198
|
+
"ttl_seconds": ttl_seconds,
|
|
199
|
+
"signature": "", # Placeholder
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
# Sign envelope
|
|
203
|
+
signature = _sign_envelope(envelope_data, private_key)
|
|
204
|
+
envelope_data["signature"] = signature
|
|
205
|
+
|
|
206
|
+
# Return as Pydantic model
|
|
207
|
+
return AuthorityEnvelope(**envelope_data)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def narrow_authority(
|
|
211
|
+
parent_envelope: AuthorityEnvelope,
|
|
212
|
+
required_scopes: List[str],
|
|
213
|
+
required_context_fields: List[str],
|
|
214
|
+
required_resources: Optional[List[str]] = None,
|
|
215
|
+
) -> NarrowingResult:
|
|
216
|
+
"""
|
|
217
|
+
Narrow authority from parent envelope to minimal required scopes and context.
|
|
218
|
+
|
|
219
|
+
Enforces the core invariant: child authority ⊆ parent authority
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
parent_envelope: Parent envelope with broader authority
|
|
223
|
+
required_scopes: Minimal scopes needed for next step
|
|
224
|
+
required_context_fields: Minimal context fields needed
|
|
225
|
+
required_resources: Minimal resources needed (defaults to parent's resources)
|
|
226
|
+
|
|
227
|
+
Returns:
|
|
228
|
+
NarrowingResult with narrowed authority and metrics
|
|
229
|
+
|
|
230
|
+
Raises:
|
|
231
|
+
ValueError: If required scopes/context/resources exceed parent authority
|
|
232
|
+
"""
|
|
233
|
+
# Validate child ⊆ parent for scopes
|
|
234
|
+
parent_scopes = set(parent_envelope.authority.scopes)
|
|
235
|
+
required_scopes_set = set(required_scopes)
|
|
236
|
+
|
|
237
|
+
if not required_scopes_set.issubset(parent_scopes):
|
|
238
|
+
invalid = required_scopes_set - parent_scopes
|
|
239
|
+
raise ValidationError(
|
|
240
|
+
f"Authority narrowing failed: Required scopes {invalid} not in parent. "
|
|
241
|
+
f"(Security violation - attempting privilege escalation)",
|
|
242
|
+
field="required_scopes",
|
|
243
|
+
value=list(invalid)
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# Validate child ⊆ parent for context
|
|
247
|
+
parent_context = set(parent_envelope.context.included)
|
|
248
|
+
required_context_set = set(required_context_fields)
|
|
249
|
+
|
|
250
|
+
if not required_context_set.issubset(parent_context):
|
|
251
|
+
invalid = required_context_set - parent_context
|
|
252
|
+
raise ValidationError(
|
|
253
|
+
f"Authority narrowing failed: Required context fields {invalid} not in parent. "
|
|
254
|
+
f"(Security violation - attempting to access unauthorized data)",
|
|
255
|
+
field="required_context_fields",
|
|
256
|
+
value=list(invalid)
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
# Validate child ⊆ parent for resources (CRITICAL SECURITY FIX)
|
|
260
|
+
if required_resources is None:
|
|
261
|
+
required_resources = parent_envelope.authority.resources
|
|
262
|
+
else:
|
|
263
|
+
parent_resources = set(parent_envelope.authority.resources)
|
|
264
|
+
required_resources_set = set(required_resources)
|
|
265
|
+
|
|
266
|
+
# Special case: parent has ["*"] means allow any specific resources
|
|
267
|
+
if "*" not in parent_resources:
|
|
268
|
+
if not required_resources_set.issubset(parent_resources):
|
|
269
|
+
invalid = required_resources_set - parent_resources
|
|
270
|
+
raise ValidationError(
|
|
271
|
+
f"Authority narrowing failed: Required resources {invalid} not in parent. "
|
|
272
|
+
f"(Security violation - attempting resource bypass)",
|
|
273
|
+
field="required_resources",
|
|
274
|
+
value=list(invalid)
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
# Calculate narrowed authority
|
|
278
|
+
narrowed_authority = Authority(
|
|
279
|
+
scopes=required_scopes,
|
|
280
|
+
resources=required_resources,
|
|
281
|
+
constraints=parent_envelope.authority.constraints, # Inherit constraints
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
# Calculate narrowed context
|
|
285
|
+
narrowed_context = Context(
|
|
286
|
+
included=required_context_fields,
|
|
287
|
+
excluded=parent_envelope.context.excluded,
|
|
288
|
+
max_size_bytes=parent_envelope.context.max_size_bytes,
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
# Calculate reduction ratios
|
|
292
|
+
authority_reduction = 1.0 - (
|
|
293
|
+
len(required_scopes) / len(parent_envelope.authority.scopes)
|
|
294
|
+
if len(parent_envelope.authority.scopes) > 0
|
|
295
|
+
else 0.0
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
context_reduction = 1.0 - (
|
|
299
|
+
len(required_context_fields) / len(parent_envelope.context.included)
|
|
300
|
+
if len(parent_envelope.context.included) > 0
|
|
301
|
+
else 0.0
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
return NarrowingResult(
|
|
305
|
+
narrowed_authority=narrowed_authority,
|
|
306
|
+
narrowed_context=narrowed_context,
|
|
307
|
+
authority_reduction_ratio=authority_reduction,
|
|
308
|
+
context_reduction_ratio=context_reduction,
|
|
309
|
+
)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def create_simple_envelope(
|
|
313
|
+
agent_id: str,
|
|
314
|
+
scopes: List[str],
|
|
315
|
+
private_key: str,
|
|
316
|
+
skill_name: str = "default",
|
|
317
|
+
resources: Optional[List[str]] = None,
|
|
318
|
+
context_fields: Optional[List[str]] = None,
|
|
319
|
+
provider: str = "claude",
|
|
320
|
+
ttl_seconds: int = 300,
|
|
321
|
+
root_policy_id: Optional[str] = None,
|
|
322
|
+
) -> AuthorityEnvelope:
|
|
323
|
+
"""
|
|
324
|
+
Create an envelope with sensible defaults for common use cases.
|
|
325
|
+
|
|
326
|
+
This is the recommended way to create root envelopes. It reduces boilerplate
|
|
327
|
+
by providing defaults for skill, context, and execution configuration.
|
|
328
|
+
|
|
329
|
+
Args:
|
|
330
|
+
agent_id: Unique agent identifier (e.g., "devops-assistant-001")
|
|
331
|
+
scopes: Permission scopes (e.g., ["read:logs", "execute:kubectl"])
|
|
332
|
+
private_key: Hex-encoded Ed25519 private key for signing
|
|
333
|
+
skill_name: Name of the skill (default: "default")
|
|
334
|
+
resources: Resource patterns (default: ["*"] - all resources)
|
|
335
|
+
context_fields: Context fields to include (default: ["user_id", "session_id"])
|
|
336
|
+
provider: LLM provider (default: "claude")
|
|
337
|
+
ttl_seconds: Time-to-live in seconds (default: 300)
|
|
338
|
+
root_policy_id: Policy ID (default: auto-generated from agent_id)
|
|
339
|
+
|
|
340
|
+
Returns:
|
|
341
|
+
Signed AuthorityEnvelope ready for use
|
|
342
|
+
|
|
343
|
+
Example:
|
|
344
|
+
```python
|
|
345
|
+
private_key, public_key = generate_key_pair()
|
|
346
|
+
|
|
347
|
+
envelope = create_simple_envelope(
|
|
348
|
+
agent_id="my-agent",
|
|
349
|
+
scopes=["read:files", "write:files"],
|
|
350
|
+
private_key=private_key,
|
|
351
|
+
)
|
|
352
|
+
```
|
|
353
|
+
"""
|
|
354
|
+
# Apply defaults
|
|
355
|
+
if resources is None:
|
|
356
|
+
resources = ["*"]
|
|
357
|
+
if context_fields is None:
|
|
358
|
+
context_fields = ["user_id", "session_id"]
|
|
359
|
+
if root_policy_id is None:
|
|
360
|
+
root_policy_id = f"policy-{agent_id}"
|
|
361
|
+
|
|
362
|
+
# Create the envelope with full API
|
|
363
|
+
return create_envelope(
|
|
364
|
+
agent_id=agent_id,
|
|
365
|
+
provider=provider,
|
|
366
|
+
step_number=1,
|
|
367
|
+
root_policy_id=root_policy_id,
|
|
368
|
+
skill=Skill(
|
|
369
|
+
id=f"skill-{skill_name}",
|
|
370
|
+
name=skill_name,
|
|
371
|
+
tool=f"Tool for {skill_name}",
|
|
372
|
+
parameters=SkillParameters(
|
|
373
|
+
allowed=[],
|
|
374
|
+
constraints={},
|
|
375
|
+
),
|
|
376
|
+
),
|
|
377
|
+
authority=Authority(
|
|
378
|
+
scopes=scopes,
|
|
379
|
+
resources=resources,
|
|
380
|
+
constraints={},
|
|
381
|
+
),
|
|
382
|
+
context=Context(
|
|
383
|
+
included=context_fields,
|
|
384
|
+
excluded=[],
|
|
385
|
+
max_size_bytes=10000,
|
|
386
|
+
),
|
|
387
|
+
execution=ExecutionConfig(
|
|
388
|
+
provider_config={
|
|
389
|
+
provider: {"skill_name": skill_name}
|
|
390
|
+
}
|
|
391
|
+
),
|
|
392
|
+
private_key=private_key,
|
|
393
|
+
ttl_seconds=ttl_seconds,
|
|
394
|
+
)
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def create_child_envelope(
|
|
398
|
+
parent_envelope: AuthorityEnvelope,
|
|
399
|
+
scopes: List[str],
|
|
400
|
+
private_key: str,
|
|
401
|
+
context_fields: Optional[List[str]] = None,
|
|
402
|
+
resources: Optional[List[str]] = None,
|
|
403
|
+
ttl_seconds: Optional[int] = None,
|
|
404
|
+
skill_name: Optional[str] = None,
|
|
405
|
+
decision_context: Optional[DecisionContext] = None,
|
|
406
|
+
) -> AuthorityEnvelope:
|
|
407
|
+
"""
|
|
408
|
+
Create a child envelope with enforced authority narrowing.
|
|
409
|
+
|
|
410
|
+
This function ALWAYS validates that child authority ⊆ parent authority.
|
|
411
|
+
Unlike create_envelope(), validation is not optional - it's built in.
|
|
412
|
+
|
|
413
|
+
Args:
|
|
414
|
+
parent_envelope: Parent envelope to derive from
|
|
415
|
+
scopes: Required scopes (must be subset of parent's scopes)
|
|
416
|
+
private_key: Hex-encoded Ed25519 private key for signing
|
|
417
|
+
context_fields: Context fields (must be subset of parent's; default: same as parent)
|
|
418
|
+
resources: Resources (must be subset of parent's; default: same as parent)
|
|
419
|
+
ttl_seconds: TTL in seconds (default: remaining parent TTL, never exceeds parent)
|
|
420
|
+
skill_name: Skill name (default: parent's skill name)
|
|
421
|
+
decision_context: Optional context explaining why this action was chosen
|
|
422
|
+
|
|
423
|
+
Returns:
|
|
424
|
+
Signed child AuthorityEnvelope
|
|
425
|
+
|
|
426
|
+
Raises:
|
|
427
|
+
ValidationError: If child authority would exceed parent authority
|
|
428
|
+
|
|
429
|
+
Example:
|
|
430
|
+
```python
|
|
431
|
+
# Parent has ["read:files", "write:files", "delete:files"]
|
|
432
|
+
# Child only needs read access
|
|
433
|
+
child = create_child_envelope(
|
|
434
|
+
parent_envelope=parent,
|
|
435
|
+
scopes=["read:files"],
|
|
436
|
+
private_key=private_key,
|
|
437
|
+
)
|
|
438
|
+
```
|
|
439
|
+
"""
|
|
440
|
+
from datetime import datetime, timezone
|
|
441
|
+
|
|
442
|
+
# Use narrow_authority to validate and compute narrowed values
|
|
443
|
+
# This enforces child ⊆ parent invariant
|
|
444
|
+
narrowing_result = narrow_authority(
|
|
445
|
+
parent_envelope=parent_envelope,
|
|
446
|
+
required_scopes=scopes,
|
|
447
|
+
required_context_fields=context_fields if context_fields else parent_envelope.context.included,
|
|
448
|
+
required_resources=resources,
|
|
449
|
+
)
|
|
450
|
+
|
|
451
|
+
# Calculate TTL - child cannot outlive parent
|
|
452
|
+
now = datetime.now(timezone.utc)
|
|
453
|
+
parent_expires_str = parent_envelope.expires_at.replace("Z", "+00:00") if parent_envelope.expires_at.endswith("Z") else parent_envelope.expires_at
|
|
454
|
+
parent_expires = datetime.fromisoformat(parent_expires_str)
|
|
455
|
+
remaining_seconds = int((parent_expires - now).total_seconds())
|
|
456
|
+
|
|
457
|
+
if remaining_seconds <= 0:
|
|
458
|
+
raise ValidationError(
|
|
459
|
+
"Parent envelope has expired - cannot create child",
|
|
460
|
+
field="parent_envelope",
|
|
461
|
+
value=parent_envelope.envelope_id,
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
# Use provided TTL or remaining parent TTL, whichever is smaller
|
|
465
|
+
if ttl_seconds is None:
|
|
466
|
+
effective_ttl = remaining_seconds
|
|
467
|
+
else:
|
|
468
|
+
effective_ttl = min(ttl_seconds, remaining_seconds)
|
|
469
|
+
|
|
470
|
+
# Create child envelope - use parent skill or override name
|
|
471
|
+
child_skill = Skill(
|
|
472
|
+
id=parent_envelope.skill.id,
|
|
473
|
+
name=skill_name if skill_name else parent_envelope.skill.name,
|
|
474
|
+
tool=parent_envelope.skill.tool,
|
|
475
|
+
parameters=parent_envelope.skill.parameters,
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
return create_envelope(
|
|
479
|
+
agent_id=parent_envelope.agent_id,
|
|
480
|
+
provider=parent_envelope.provider,
|
|
481
|
+
step_number=parent_envelope.step_number + 1,
|
|
482
|
+
root_policy_id=parent_envelope.root_policy_id,
|
|
483
|
+
skill=child_skill,
|
|
484
|
+
authority=narrowing_result.narrowed_authority,
|
|
485
|
+
context=narrowing_result.narrowed_context,
|
|
486
|
+
execution=parent_envelope.execution,
|
|
487
|
+
private_key=private_key,
|
|
488
|
+
parent_envelope_id=parent_envelope.envelope_id,
|
|
489
|
+
ttl_seconds=effective_ttl,
|
|
490
|
+
decision_context=decision_context,
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def validate_envelope(
|
|
495
|
+
envelope: AuthorityEnvelope,
|
|
496
|
+
parent_envelope: Optional[AuthorityEnvelope] = None,
|
|
497
|
+
public_key: Optional[str] = None,
|
|
498
|
+
) -> Dict[str, Any]:
|
|
499
|
+
"""
|
|
500
|
+
Validate an authority envelope.
|
|
501
|
+
|
|
502
|
+
Checks:
|
|
503
|
+
1. Signature validity (if public_key provided)
|
|
504
|
+
2. TTL not expired
|
|
505
|
+
3. Child ⊆ parent authority (if parent provided)
|
|
506
|
+
4. Child ⊆ parent context (if parent provided)
|
|
507
|
+
|
|
508
|
+
Args:
|
|
509
|
+
envelope: Envelope to validate
|
|
510
|
+
parent_envelope: Parent envelope (if validating child)
|
|
511
|
+
public_key: Public key for signature verification
|
|
512
|
+
|
|
513
|
+
Returns:
|
|
514
|
+
Dict with validation result:
|
|
515
|
+
{
|
|
516
|
+
"valid": bool,
|
|
517
|
+
"errors": List[str]
|
|
518
|
+
}
|
|
519
|
+
"""
|
|
520
|
+
errors: List[str] = []
|
|
521
|
+
|
|
522
|
+
# Check signature if public key provided
|
|
523
|
+
if public_key:
|
|
524
|
+
if not verify_signature(envelope, public_key):
|
|
525
|
+
errors.append("Invalid signature - envelope may have been tampered with")
|
|
526
|
+
|
|
527
|
+
# Check TTL
|
|
528
|
+
now = datetime.now(timezone.utc)
|
|
529
|
+
# Handle both 'Z' suffix and explicit timezone
|
|
530
|
+
expires_str = envelope.expires_at.replace("Z", "+00:00") if envelope.expires_at.endswith("Z") else envelope.expires_at
|
|
531
|
+
expires = datetime.fromisoformat(expires_str)
|
|
532
|
+
if now > expires:
|
|
533
|
+
errors.append(f"Envelope expired at {envelope.expires_at}")
|
|
534
|
+
|
|
535
|
+
# Check authority narrowing if parent provided
|
|
536
|
+
if parent_envelope:
|
|
537
|
+
# Check scopes
|
|
538
|
+
child_scopes = set(envelope.authority.scopes)
|
|
539
|
+
parent_scopes = set(parent_envelope.authority.scopes)
|
|
540
|
+
if not child_scopes.issubset(parent_scopes):
|
|
541
|
+
invalid = child_scopes - parent_scopes
|
|
542
|
+
errors.append(
|
|
543
|
+
f"Child has scopes not in parent: {invalid}. "
|
|
544
|
+
f"This violates the authority narrowing invariant."
|
|
545
|
+
)
|
|
546
|
+
|
|
547
|
+
# Check context
|
|
548
|
+
child_context = set(envelope.context.included)
|
|
549
|
+
parent_context = set(parent_envelope.context.included)
|
|
550
|
+
if not child_context.issubset(parent_context):
|
|
551
|
+
invalid = child_context - parent_context
|
|
552
|
+
errors.append(
|
|
553
|
+
f"Child has context fields not in parent: {invalid}. "
|
|
554
|
+
f"This violates the context narrowing invariant."
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
# Check TTL - MUST check absolute expiration times, not just ttl_seconds
|
|
558
|
+
# Critical: A child created late could outlive parent with same TTL value
|
|
559
|
+
child_expires_str = envelope.expires_at.replace("Z", "+00:00") if envelope.expires_at.endswith("Z") else envelope.expires_at
|
|
560
|
+
parent_expires_str = parent_envelope.expires_at.replace("Z", "+00:00") if parent_envelope.expires_at.endswith("Z") else parent_envelope.expires_at
|
|
561
|
+
|
|
562
|
+
child_expires = datetime.fromisoformat(child_expires_str)
|
|
563
|
+
parent_expires = datetime.fromisoformat(parent_expires_str)
|
|
564
|
+
|
|
565
|
+
if child_expires > parent_expires:
|
|
566
|
+
errors.append(
|
|
567
|
+
f"Child expires after parent "
|
|
568
|
+
f"(child: {envelope.expires_at}, parent: {parent_envelope.expires_at}). "
|
|
569
|
+
f"Child cannot outlive its parent."
|
|
570
|
+
)
|
|
571
|
+
|
|
572
|
+
return {
|
|
573
|
+
"valid": len(errors) == 0,
|
|
574
|
+
"errors": errors,
|
|
575
|
+
}
|