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.
@@ -0,0 +1,590 @@
1
+ """
2
+ Authority Runtime - Enforcement Layer
3
+
4
+ This module provides ACTUAL permission enforcement, not just bookkeeping.
5
+ Tools wrapped with EnforcedTool will refuse to execute without valid envelopes.
6
+ """
7
+
8
+ import logging
9
+ from datetime import datetime, timezone
10
+ from typing import Any, Callable, Dict, List, Optional
11
+ from functools import wraps
12
+
13
+ from .constraints import check_constraints, ConstraintResult
14
+ from .envelope import verify_signature
15
+ from .types import AuthorityEnvelope
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class PermissionDenied(Exception):
21
+ """Raised when an action is blocked due to insufficient permissions."""
22
+ pass
23
+
24
+
25
+ class EnvelopeExpired(Exception):
26
+ """Raised when an envelope's TTL has passed."""
27
+ pass
28
+
29
+
30
+ class InvalidSignature(Exception):
31
+ """Raised when an envelope's signature doesn't verify."""
32
+ pass
33
+
34
+
35
+ def _scope_matches(granted: str, required: str) -> bool:
36
+ """
37
+ Check if a granted scope pattern matches a required scope.
38
+
39
+ Supports per-segment wildcard matching:
40
+ - "vault:finance:read" matches "vault:finance:read" (exact)
41
+ - "vault:*:read" matches "vault:finance:read" (segment wildcard)
42
+ - "vault:finance:*" matches "vault:finance:read" and "vault:finance:write"
43
+ - "*:*:*" matches any 3-segment scope
44
+
45
+ Segments must match in count — "vault:*" does NOT match "vault:finance:read".
46
+ """
47
+ g_parts = granted.split(":")
48
+ r_parts = required.split(":")
49
+ if len(g_parts) != len(r_parts):
50
+ return False
51
+ return all(g == "*" or g == r for g, r in zip(g_parts, r_parts))
52
+
53
+
54
+ class ConstraintViolation(Exception):
55
+ """Raised when an envelope's constraints are violated."""
56
+ pass
57
+
58
+
59
+ class ApprovalRequired(Exception):
60
+ """Raised when an action requires human approval per envelope constraints."""
61
+ pass
62
+
63
+
64
+ def check_envelope(
65
+ envelope: AuthorityEnvelope,
66
+ public_key: str,
67
+ required_scope: str,
68
+ action: Optional[str] = None,
69
+ resource: Optional[str] = None,
70
+ context: Optional[Dict[str, Any]] = None,
71
+ ) -> None:
72
+ """
73
+ Validate an envelope before allowing an action.
74
+
75
+ Checks signature, expiration, scope (with wildcards), and constraints.
76
+
77
+ Args:
78
+ envelope: The authority envelope to validate
79
+ public_key: Agent's Ed25519 public key for signature verification
80
+ required_scope: Scope string required for this action
81
+ action: Action being performed (e.g., "read", "write") — for constraint checking
82
+ resource: Resource URI being accessed — for constraint checking
83
+ context: Additional context dict — for constraint checking
84
+
85
+ Raises:
86
+ InvalidSignature: If the envelope signature doesn't verify
87
+ EnvelopeExpired: If the envelope TTL has passed
88
+ PermissionDenied: If the required scope isn't in the envelope
89
+ ConstraintViolation: If envelope constraints are violated
90
+ ApprovalRequired: If action requires human approval per constraints
91
+ """
92
+ logger.debug("Checking envelope",
93
+ extra={"envelope_id": envelope.envelope_id,
94
+ "agent_id": envelope.agent_id,
95
+ "required_scope": required_scope})
96
+
97
+ # 1. Verify signature - tamper detection
98
+ if not verify_signature(envelope, public_key):
99
+ raise InvalidSignature(
100
+ f"Envelope {envelope.envelope_id} has invalid signature. "
101
+ "The envelope may have been tampered with."
102
+ )
103
+
104
+ # 2. Check expiration
105
+ expires_at = datetime.fromisoformat(envelope.expires_at.replace('Z', '+00:00'))
106
+ now = datetime.now(timezone.utc)
107
+ if expires_at < now:
108
+ raise EnvelopeExpired(
109
+ f"Envelope {envelope.envelope_id} expired at {envelope.expires_at}. "
110
+ f"Current time: {now.isoformat()}"
111
+ )
112
+
113
+ # 3. Check scope (with wildcard support)
114
+ if not any(_scope_matches(s, required_scope) for s in envelope.authority.scopes):
115
+ raise PermissionDenied(
116
+ f"Action requires scope '{required_scope}' but envelope only grants: "
117
+ f"{envelope.authority.scopes}"
118
+ )
119
+
120
+ # 4. Check constraints (if any)
121
+ if envelope.authority.constraints:
122
+ result = check_constraints(
123
+ constraints=envelope.authority.constraints,
124
+ action=action or _infer_action(required_scope),
125
+ resource=resource,
126
+ context=context,
127
+ )
128
+ if result.require_approval:
129
+ raise ApprovalRequired(
130
+ f"Action requires human approval: {'; '.join(result.warnings)}"
131
+ )
132
+ if not result.allowed:
133
+ raise ConstraintViolation(
134
+ f"Constraint violation: {'; '.join(result.violated)}"
135
+ )
136
+
137
+ logger.info("Envelope check passed",
138
+ extra={"envelope_id": envelope.envelope_id,
139
+ "agent_id": envelope.agent_id,
140
+ "scope": required_scope})
141
+
142
+
143
+ def _infer_action(scope: str) -> str:
144
+ """Infer action from scope string (last segment). Fallback for when action not explicitly passed."""
145
+ parts = scope.split(":")
146
+ return parts[-1] if parts else "unknown"
147
+
148
+
149
+ def check_context_field(envelope: AuthorityEnvelope, field: str) -> None:
150
+ """
151
+ Validate that a context field is allowed by the envelope.
152
+
153
+ Raises:
154
+ PermissionDenied: If the field isn't in the envelope's included context
155
+ """
156
+ if field not in envelope.context.included:
157
+ raise PermissionDenied(
158
+ f"Access to context field '{field}' denied. "
159
+ f"Envelope only allows: {envelope.context.included}"
160
+ )
161
+
162
+
163
+ class EnforcedTool:
164
+ """
165
+ A tool wrapper that enforces Authority Runtime permissions.
166
+
167
+ The tool will refuse to execute without a valid envelope that grants
168
+ the required scope.
169
+
170
+ Example:
171
+ ```python
172
+ def read_file(path: str) -> str:
173
+ return open(path).read()
174
+
175
+ # Wrap with enforcement
176
+ secure_read = EnforcedTool(
177
+ name="read_file",
178
+ func=read_file,
179
+ required_scope="read:filesystem",
180
+ public_key=public_key
181
+ )
182
+
183
+ # This will FAIL without valid envelope
184
+ secure_read(path="/etc/passwd") # Raises PermissionDenied
185
+
186
+ # This works with valid envelope
187
+ secure_read(path="/etc/passwd", _envelope=valid_envelope)
188
+ ```
189
+ """
190
+
191
+ def __init__(
192
+ self,
193
+ name: str,
194
+ func: Callable,
195
+ required_scope: str,
196
+ public_key: str,
197
+ description: Optional[str] = None,
198
+ ):
199
+ self.name = name
200
+ self.func = func
201
+ self.required_scope = required_scope
202
+ self.public_key = public_key
203
+ self.description = description or func.__doc__ or f"Tool: {name}"
204
+
205
+ def __call__(self, *args, _envelope: Optional[AuthorityEnvelope] = None, **kwargs) -> Any:
206
+ """
207
+ Execute the tool, but only if a valid envelope is provided.
208
+
209
+ Args:
210
+ *args: Positional arguments for the underlying function
211
+ _envelope: The AuthorityEnvelope granting permission (REQUIRED)
212
+ **kwargs: Keyword arguments for the underlying function
213
+
214
+ Returns:
215
+ The result of the underlying function
216
+
217
+ Raises:
218
+ PermissionDenied: If no envelope provided or scope not granted
219
+ InvalidSignature: If envelope signature doesn't verify
220
+ EnvelopeExpired: If envelope has expired
221
+ """
222
+ if _envelope is None:
223
+ raise PermissionDenied(
224
+ f"Tool '{self.name}' requires an AuthorityEnvelope. "
225
+ f"Pass _envelope=your_envelope to execute."
226
+ )
227
+
228
+ # Validate the envelope
229
+ check_envelope(_envelope, self.public_key, self.required_scope)
230
+
231
+ # Envelope is valid - execute the function
232
+ # Pass _envelope to the function if it accepts it (for constraint checking)
233
+ import inspect
234
+ sig = inspect.signature(self.func)
235
+ if '_envelope' in sig.parameters:
236
+ return self.func(*args, _envelope=_envelope, **kwargs)
237
+ else:
238
+ return self.func(*args, **kwargs)
239
+
240
+ def to_langchain_tool(self):
241
+ """
242
+ Convert EnforcedTool to a LangChain StructuredTool.
243
+
244
+ This allows EnforcedTool to work with LangGraph's ToolNode and
245
+ standard LangChain tool infrastructure.
246
+
247
+ Returns:
248
+ langchain_core.tools.StructuredTool compatible with LangGraph
249
+
250
+ Example:
251
+ ```python
252
+ from langchain_core.tools import StructuredTool
253
+
254
+ secure_tool = EnforcedTool(
255
+ name="read_file",
256
+ func=read_file,
257
+ required_scope="read:filesystem",
258
+ public_key=public_key
259
+ )
260
+
261
+ # Convert to LangChain tool
262
+ lc_tool = secure_tool.to_langchain_tool()
263
+
264
+ # Use with LangGraph ToolNode
265
+ from langgraph.prebuilt import ToolNode
266
+ tool_node = ToolNode([lc_tool])
267
+ ```
268
+ """
269
+ from langchain_core.tools import StructuredTool
270
+ import inspect
271
+
272
+ # Get function signature
273
+ sig = inspect.signature(self.func)
274
+
275
+ # Create wrapper that doesn't require _envelope parameter
276
+ # (envelope should be bound in execution context)
277
+ @wraps(self.func)
278
+ def langchain_wrapper(*args, **kwargs):
279
+ # Note: LangChain tools don't support _envelope parameter
280
+ # The envelope should be managed by the LangGraph integration layer
281
+ # For now, return a helpful error if called without proper context
282
+ return self.func(*args, **kwargs)
283
+
284
+ return StructuredTool(
285
+ name=self.name,
286
+ description=self.description,
287
+ func=langchain_wrapper,
288
+ )
289
+
290
+
291
+ class EnforcedToolkit:
292
+ """
293
+ A collection of tools with shared enforcement settings.
294
+
295
+ Example:
296
+ ```python
297
+ toolkit = EnforcedToolkit(public_key=public_key)
298
+
299
+ @toolkit.tool(scope="read:filesystem")
300
+ def read_file(path: str) -> str:
301
+ return open(path).read()
302
+
303
+ @toolkit.tool(scope="write:filesystem")
304
+ def write_file(path: str, content: str) -> None:
305
+ open(path, 'w').write(content)
306
+
307
+ # Execute with envelope
308
+ result = toolkit.execute("read_file", path="/tmp/test.txt", envelope=envelope)
309
+ ```
310
+ """
311
+
312
+ def __init__(self, public_key: str):
313
+ self.public_key = public_key
314
+ self.tools: Dict[str, EnforcedTool] = {}
315
+
316
+ def tool(self, scope: str, name: Optional[str] = None):
317
+ """Decorator to register a tool with required scope."""
318
+ def decorator(func: Callable) -> Callable:
319
+ tool_name = name or func.__name__
320
+ enforced = EnforcedTool(
321
+ name=tool_name,
322
+ func=func,
323
+ required_scope=scope,
324
+ public_key=self.public_key,
325
+ )
326
+ self.tools[tool_name] = enforced
327
+ return func # Return original for direct use
328
+ return decorator
329
+
330
+ def execute(
331
+ self,
332
+ tool_name: str,
333
+ envelope: AuthorityEnvelope,
334
+ **kwargs
335
+ ) -> Any:
336
+ """
337
+ Execute a tool by name with envelope enforcement.
338
+
339
+ Raises:
340
+ KeyError: If tool doesn't exist
341
+ PermissionDenied: If envelope doesn't grant required scope
342
+ """
343
+ if tool_name not in self.tools:
344
+ raise KeyError(f"Tool '{tool_name}' not found. Available: {list(self.tools.keys())}")
345
+
346
+ return self.tools[tool_name](_envelope=envelope, **kwargs)
347
+
348
+ def get_required_scope(self, tool_name: str) -> str:
349
+ """Get the required scope for a tool."""
350
+ if tool_name not in self.tools:
351
+ raise KeyError(f"Tool '{tool_name}' not found")
352
+ return self.tools[tool_name].required_scope
353
+
354
+
355
+ def enforce(scope: str, public_key: str):
356
+ """
357
+ Decorator to add enforcement to any function.
358
+
359
+ Example:
360
+ ```python
361
+ @enforce(scope="delete:users", public_key=PUBLIC_KEY)
362
+ def delete_user(user_id: str) -> None:
363
+ db.delete(user_id)
364
+
365
+ # Fails without envelope
366
+ delete_user("123") # PermissionDenied
367
+
368
+ # Works with valid envelope
369
+ delete_user("123", _envelope=admin_envelope)
370
+ ```
371
+ """
372
+ def decorator(func: Callable) -> Callable:
373
+ @wraps(func)
374
+ def wrapper(*args, _envelope: Optional[AuthorityEnvelope] = None, **kwargs):
375
+ if _envelope is None:
376
+ raise PermissionDenied(
377
+ f"Function '{func.__name__}' requires scope '{scope}'. "
378
+ f"Pass _envelope=your_envelope to execute."
379
+ )
380
+ check_envelope(_envelope, public_key, scope)
381
+ return func(*args, **kwargs)
382
+ return wrapper
383
+ return decorator
384
+
385
+
386
+ # =============================================================================
387
+ # Audit Trail - Enterprise Compliance
388
+ # =============================================================================
389
+
390
+ class AuditEntry:
391
+ """A single auditable action with its authorization proof."""
392
+
393
+ def __init__(
394
+ self,
395
+ action: str,
396
+ envelope: AuthorityEnvelope,
397
+ public_key: str,
398
+ result: str = "success",
399
+ error: Optional[str] = None,
400
+ metadata: Optional[Dict[str, Any]] = None,
401
+ resource: Optional[str] = None,
402
+ ):
403
+ self.timestamp = datetime.now(timezone.utc).isoformat()
404
+ self.action = action
405
+ self.envelope = envelope
406
+ self.public_key = public_key
407
+ self.result = result
408
+ self.error = error
409
+ self.metadata = metadata or {}
410
+ self.resource = resource
411
+
412
+ # Verify signature at audit time
413
+ self.signature_valid = verify_signature(envelope, public_key)
414
+
415
+ def to_dict(self) -> Dict[str, Any]:
416
+ """Export as compliance-ready dictionary."""
417
+ envelope_dict = {
418
+ "envelope_id": self.envelope.envelope_id,
419
+ "agent_id": self.envelope.agent_id,
420
+ "parent_envelope_id": self.envelope.parent_envelope_id,
421
+ "root_policy_id": self.envelope.root_policy_id,
422
+ "scopes": self.envelope.authority.scopes,
423
+ "resources": self.envelope.authority.resources,
424
+ "constraints": self.envelope.authority.constraints,
425
+ "created_at": self.envelope.created_at,
426
+ "expires_at": self.envelope.expires_at,
427
+ "ttl_seconds": self.envelope.ttl_seconds,
428
+ }
429
+
430
+ # Include decision context if present - this is the "why" behind the "what"
431
+ if self.envelope.decision_context:
432
+ envelope_dict["decision_context"] = {
433
+ "intent": self.envelope.decision_context.intent,
434
+ "inputs": self.envelope.decision_context.inputs,
435
+ "constraints_applied": self.envelope.decision_context.constraints_applied,
436
+ "alternatives_considered": self.envelope.decision_context.alternatives_considered,
437
+ "selected_because": self.envelope.decision_context.selected_because,
438
+ "policy_references": self.envelope.decision_context.policy_references,
439
+ "confidence": self.envelope.decision_context.confidence,
440
+ "escalation_reason": self.envelope.decision_context.escalation_reason,
441
+ "risk_factors": self.envelope.decision_context.risk_factors,
442
+ }
443
+
444
+ return {
445
+ "timestamp": self.timestamp,
446
+ "action": self.action,
447
+ "resource": self.resource,
448
+ "result": self.result,
449
+ "error": self.error,
450
+ "envelope": envelope_dict,
451
+ "verification": {
452
+ "signature_valid": self.signature_valid,
453
+ "public_key_fingerprint": self.public_key[:16] + "...",
454
+ },
455
+ "metadata": self.metadata,
456
+ }
457
+
458
+
459
+ def export_audit_trail(
460
+ entries: List[AuditEntry],
461
+ include_envelope_chain: bool = True,
462
+ ) -> Dict[str, Any]:
463
+ """
464
+ Export an audit trail for compliance review.
465
+
466
+ This produces a compliance-ready report showing:
467
+ - What actions were taken
468
+ - What permissions authorized each action
469
+ - Cryptographic proof that permissions were valid
470
+ - The delegation chain (if include_envelope_chain=True)
471
+
472
+ Example:
473
+ ```python
474
+ audit_log = []
475
+
476
+ # During execution, record each action
477
+ envelope = create_envelope(...)
478
+ result = secure_delete(user_id="123", _envelope=envelope)
479
+ audit_log.append(AuditEntry(
480
+ action="delete_user",
481
+ envelope=envelope,
482
+ public_key=public_key,
483
+ metadata={"user_id": "123"}
484
+ ))
485
+
486
+ # Export for compliance
487
+ report = export_audit_trail(audit_log)
488
+ print(json.dumps(report, indent=2))
489
+ ```
490
+
491
+ Returns:
492
+ Dict with:
493
+ - summary: High-level stats
494
+ - entries: List of auditable actions
495
+ - envelope_chain: Delegation hierarchy (if requested)
496
+ """
497
+ if not entries:
498
+ return {
499
+ "summary": {
500
+ "total_actions": 0,
501
+ "successful": 0,
502
+ "failed": 0,
503
+ "signature_failures": 0,
504
+ },
505
+ "entries": [],
506
+ }
507
+
508
+ # Build summary
509
+ successful = sum(1 for e in entries if e.result == "success")
510
+ failed = sum(1 for e in entries if e.result != "success")
511
+ sig_failures = sum(1 for e in entries if not e.signature_valid)
512
+
513
+ result: Dict[str, Any] = {
514
+ "generated_at": datetime.now(timezone.utc).isoformat(),
515
+ "summary": {
516
+ "total_actions": len(entries),
517
+ "successful": successful,
518
+ "failed": failed,
519
+ "signature_failures": sig_failures,
520
+ "unique_agents": len(set(e.envelope.agent_id for e in entries)),
521
+ "unique_policies": len(set(e.envelope.root_policy_id for e in entries)),
522
+ },
523
+ "entries": [e.to_dict() for e in entries],
524
+ }
525
+
526
+ # Build envelope chain if requested
527
+ if include_envelope_chain:
528
+ chain: Dict[str, Dict[str, Any]] = {}
529
+ for entry in entries:
530
+ env = entry.envelope
531
+ if env.envelope_id not in chain:
532
+ chain[env.envelope_id] = {
533
+ "envelope_id": env.envelope_id,
534
+ "agent_id": env.agent_id,
535
+ "parent_envelope_id": env.parent_envelope_id,
536
+ "scopes": env.authority.scopes,
537
+ "created_at": env.created_at,
538
+ "children": [],
539
+ }
540
+
541
+ # Link children to parents
542
+ for env_id, node in chain.items():
543
+ parent_id = node["parent_envelope_id"]
544
+ if parent_id and parent_id in chain:
545
+ chain[parent_id]["children"].append(env_id)
546
+
547
+ # Find roots (no parent)
548
+ roots = [eid for eid, node in chain.items() if node["parent_envelope_id"] is None]
549
+
550
+ result["envelope_chain"] = {
551
+ "roots": roots,
552
+ "nodes": chain,
553
+ }
554
+
555
+ return result
556
+
557
+
558
+ def create_audit_entry(
559
+ action: str,
560
+ envelope: AuthorityEnvelope,
561
+ public_key: str,
562
+ result: str = "success",
563
+ error: Optional[str] = None,
564
+ resource: Optional[str] = None,
565
+ **metadata
566
+ ) -> AuditEntry:
567
+ """
568
+ Convenience function to create an audit entry.
569
+
570
+ Example:
571
+ ```python
572
+ entry = create_audit_entry(
573
+ action="transfer_funds",
574
+ envelope=envelope,
575
+ public_key=public_key,
576
+ resource="slos://vaults/finance/budget-2026",
577
+ amount="0.1 ETH",
578
+ recipient="0x123..."
579
+ )
580
+ ```
581
+ """
582
+ return AuditEntry(
583
+ action=action,
584
+ envelope=envelope,
585
+ public_key=public_key,
586
+ result=result,
587
+ error=error,
588
+ metadata=metadata,
589
+ resource=resource,
590
+ )