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,281 @@
1
+ """
2
+ Core types for Authority Runtime - Python port of TypeScript types
3
+ """
4
+
5
+ from typing import Any, Dict, List, Literal, Optional
6
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
7
+ from datetime import datetime
8
+ import re
9
+
10
+
11
+ class Authority(BaseModel):
12
+ """Permission scopes granted to an agent"""
13
+
14
+ scopes: List[str] = Field(
15
+ description="Allowed actions (e.g., 'read:user', 'write:user')"
16
+ )
17
+ resources: List[str] = Field(
18
+ default=["*"], description="Allowed resources (e.g., 'user:123', '*')"
19
+ )
20
+ constraints: Dict[str, Any] = Field(
21
+ default_factory=dict,
22
+ description=(
23
+ "Enforced constraints on envelope usage. Supported keys: "
24
+ "require_purpose (bool), denied_resources (list[str] with glob patterns), "
25
+ "max_records_per_request (int), write_requires_approval (bool)"
26
+ ),
27
+ )
28
+
29
+ @field_validator('scopes')
30
+ @classmethod
31
+ def validate_scope_format(cls, v: List[str]) -> List[str]:
32
+ """Validate that scopes follow valid scope patterns.
33
+
34
+ Supported patterns:
35
+ - action:resource (e.g., 'read:user', 'write:files')
36
+ - namespace:resource:action (e.g., 'vault:finance:read', 'wallet:transfer')
37
+ - wildcard support (e.g., 'vault:*:read', 'read:*')
38
+ """
39
+ # Allow alphanumeric, underscore, hyphen, asterisk, dot, slash, separated by colons
40
+ scope_pattern = re.compile(r'^[a-zA-Z0-9_./*-]+(?::[a-zA-Z0-9_./*-]+)+$')
41
+ for scope in v:
42
+ if not scope_pattern.match(scope):
43
+ raise ValueError(
44
+ f"Invalid scope format: '{scope}'. "
45
+ f"Scopes must use colon-separated segments (e.g., 'read:user', 'vault:finance:read')"
46
+ )
47
+ return v
48
+
49
+
50
+ class Context(BaseModel):
51
+ """Agent context fields available at each step"""
52
+
53
+ included: List[str] = Field(
54
+ description="Context fields included in this envelope (e.g., 'email', 'name')"
55
+ )
56
+ excluded: List[str] = Field(
57
+ default_factory=list, description="Context fields explicitly excluded"
58
+ )
59
+ max_size_bytes: int = Field(
60
+ default=10000, description="Maximum context size to prevent DoS"
61
+ )
62
+
63
+
64
+ class SkillParameters(BaseModel):
65
+ """Parameters that a skill accepts"""
66
+
67
+ allowed: List[str] = Field(description="Allowed parameter names")
68
+ constraints: Dict[str, str] = Field(
69
+ description="Parameter type constraints (e.g., {'user_id': 'string'})"
70
+ )
71
+
72
+
73
+ class Skill(BaseModel):
74
+ """A skill/tool that an agent can use"""
75
+
76
+ id: str = Field(description="Unique skill identifier")
77
+ name: str = Field(description="Human-readable skill name (e.g., 'getUserByEmail')")
78
+ tool: str = Field(description="Tool description for the agent")
79
+ parameters: SkillParameters = Field(description="Skill parameters")
80
+
81
+
82
+ class DecisionContext(BaseModel):
83
+ """
84
+ Decision-time context - captures WHY a decision was made, not just WHAT happened.
85
+
86
+ This bridges the gap between records and understanding:
87
+ - Records say "User deleted"
88
+ - Decision context says "User requested GDPR Article 17 deletion,
89
+ alternatives (soft delete, anonymization) were considered but rejected
90
+ because user explicitly requested permanent deletion"
91
+ """
92
+
93
+ intent: str = Field(
94
+ description="What was the agent trying to accomplish? (e.g., 'User requested account deletion')"
95
+ )
96
+
97
+ inputs: Dict[str, Any] = Field(
98
+ default_factory=dict,
99
+ description="What data was available at decision time (e.g., {'user_request': 'delete my account', 'user_tier': 'premium'})"
100
+ )
101
+
102
+ constraints_applied: List[str] = Field(
103
+ default_factory=list,
104
+ description="What rules/policies limited the decision? (e.g., ['GDPR Article 17', '30-day retention policy'])"
105
+ )
106
+
107
+ alternatives_considered: List[str] = Field(
108
+ default_factory=list,
109
+ description="What other options were evaluated? (e.g., ['soft delete', 'anonymization', 'account suspension'])"
110
+ )
111
+
112
+ selected_because: str = Field(
113
+ description="Why was this specific action chosen? (e.g., 'User explicitly requested permanent deletion in support ticket #12345')"
114
+ )
115
+
116
+ policy_references: List[str] = Field(
117
+ default_factory=list,
118
+ description="Which policies governed this decision? (e.g., ['privacy-policy-v2.1', 'gdpr-compliance-guide'])"
119
+ )
120
+
121
+ confidence: float = Field(
122
+ default=1.0,
123
+ ge=0.0,
124
+ le=1.0,
125
+ description="How certain was the decision? (0.0 = uncertain, 1.0 = certain)"
126
+ )
127
+
128
+ escalation_reason: Optional[str] = Field(
129
+ default=None,
130
+ description="If this required human review, why? (e.g., 'High-value account detected')"
131
+ )
132
+
133
+ risk_factors: List[str] = Field(
134
+ default_factory=list,
135
+ description="What risks were identified? (e.g., ['irreversible action', 'affects 3 linked accounts'])"
136
+ )
137
+
138
+
139
+ class ExecutionConfig(BaseModel):
140
+ """Provider-specific execution configuration"""
141
+
142
+ provider_config: Dict[str, Dict[str, Any]] = Field(
143
+ description="Provider-specific settings (e.g., {'claude': {'skill_name': 'root'}})"
144
+ )
145
+
146
+
147
+ class AuthorityEnvelope(BaseModel):
148
+ """
149
+ Core envelope structure - cryptographically signed permission bundle.
150
+
151
+ This is the Python port of the TypeScript AuthorityEnvelope interface.
152
+ """
153
+
154
+ # Identity & versioning
155
+ envelope_id: str = Field(description="Unique envelope identifier (UUID)")
156
+ version: str = Field(default="1.0.0", description="Envelope format version")
157
+ created_at: str = Field(
158
+ description="ISO 8601 timestamp of envelope creation"
159
+ )
160
+ expires_at: str = Field(description="ISO 8601 timestamp when envelope expires")
161
+
162
+ # Agent context
163
+ agent_id: str = Field(description="Unique agent identifier")
164
+ provider: Literal["claude", "openai", "gemini", "custom"] = Field(
165
+ description="LLM provider for this agent"
166
+ )
167
+
168
+ # Envelope chain (for authority narrowing)
169
+ step_number: int = Field(description="Step in the agent's execution (1-indexed)")
170
+ parent_envelope_id: Optional[str] = Field(
171
+ default=None, description="Parent envelope ID (None for root)"
172
+ )
173
+ root_policy_id: str = Field(
174
+ description="Root policy that started this chain"
175
+ )
176
+
177
+ # Core authorization
178
+ skill: Skill = Field(description="The skill being authorized for this step")
179
+ authority: Authority = Field(description="Permissions granted for this step")
180
+ context: Context = Field(description="Context fields available for this step")
181
+
182
+ # Decision-time context (optional but recommended)
183
+ decision_context: Optional[DecisionContext] = Field(
184
+ default=None,
185
+ description="WHY this decision was made - captures intent, constraints, alternatives, and reasoning"
186
+ )
187
+
188
+ # Execution metadata
189
+ execution: ExecutionConfig = Field(
190
+ description="Provider-specific execution configuration"
191
+ )
192
+
193
+ # Cryptographic security
194
+ signature: str = Field(
195
+ description="Ed25519 signature of the canonical envelope (hex-encoded)"
196
+ )
197
+
198
+ ttl_seconds: int = Field(
199
+ default=300,
200
+ ge=60, # Minimum 1 minute
201
+ le=86400, # Maximum 24 hours
202
+ description="Time-to-live in seconds (default: 5 minutes, max: 24 hours)"
203
+ )
204
+
205
+ model_config = ConfigDict(
206
+ json_schema_extra={
207
+ "example": {
208
+ "envelope_id": "env-123abc",
209
+ "version": "1.0.0",
210
+ "created_at": "2024-12-26T10:00:00Z",
211
+ "expires_at": "2024-12-26T10:05:00Z",
212
+ "agent_id": "agent-001",
213
+ "provider": "claude",
214
+ "step_number": 1,
215
+ "parent_envelope_id": None,
216
+ "root_policy_id": "policy-root-001",
217
+ "skill": {
218
+ "id": "skill-001",
219
+ "name": "getUserByEmail",
220
+ "tool": "Searches for a user by email",
221
+ "parameters": {
222
+ "allowed": ["email"],
223
+ "constraints": {"email": "string"},
224
+ },
225
+ },
226
+ "authority": {
227
+ "scopes": ["read:user"],
228
+ "resources": ["*"],
229
+ "constraints": {},
230
+ },
231
+ "context": {
232
+ "included": ["email"],
233
+ "excluded": [],
234
+ "max_size_bytes": 10000,
235
+ },
236
+ "execution": {
237
+ "provider_config": {"claude": {"skill_name": "getUserByEmail"}}
238
+ },
239
+ "signature": "abcd1234...",
240
+ "ttl_seconds": 300,
241
+ }
242
+ }
243
+ )
244
+
245
+
246
+ class SkillSelection(BaseModel):
247
+ """Result of LLM skill selection"""
248
+
249
+ selected_skill: Skill = Field(description="The skill chosen by the LLM")
250
+ required_scopes: List[str] = Field(
251
+ description="Minimal scopes needed for this skill"
252
+ )
253
+ required_context_fields: List[str] = Field(
254
+ description="Minimal context fields needed"
255
+ )
256
+ reasoning: str = Field(description="LLM's reasoning for this selection")
257
+ confidence: float = Field(
258
+ ge=0.0, le=1.0, description="LLM confidence score (0-1)"
259
+ )
260
+
261
+
262
+ class NarrowingResult(BaseModel):
263
+ """Result of authority narrowing operation"""
264
+
265
+ narrowed_authority: Authority = Field(description="Narrowed authority scopes")
266
+ narrowed_context: Context = Field(description="Narrowed context fields")
267
+ authority_reduction_ratio: float = Field(
268
+ description="Ratio of authority reduction (0-1)"
269
+ )
270
+ context_reduction_ratio: float = Field(
271
+ description="Ratio of context reduction (0-1)"
272
+ )
273
+
274
+
275
+ class TokenMetrics(BaseModel):
276
+ """Metrics for LLM token usage and cost"""
277
+
278
+ input_tokens: int = Field(description="Input tokens used")
279
+ output_tokens: int = Field(description="Output tokens used")
280
+ total_cost_usd: float = Field(description="Total cost in USD")
281
+ latency_ms: int = Field(description="Latency in milliseconds")
@@ -0,0 +1,428 @@
1
+ """
2
+ Authority Runtime - Input Validation and Error Handling
3
+
4
+ This module provides comprehensive validation for envelope creation,
5
+ better error messages, and input sanitization.
6
+ """
7
+
8
+ from typing import List, Optional, Dict, Any
9
+ import re
10
+ from .types import Authority, AuthorityEnvelope
11
+
12
+
13
+ class ValidationError(Exception):
14
+ """Raised when validation fails with detailed error information."""
15
+
16
+ def __init__(self, message: str, field: Optional[str] = None, value: Any = None):
17
+ self.field = field
18
+ self.value = value
19
+ super().__init__(message)
20
+
21
+
22
+ def validate_agent_id(agent_id: str) -> None:
23
+ """
24
+ Validate agent ID format.
25
+
26
+ Rules:
27
+ - Not empty
28
+ - Alphanumeric, hyphens, underscores only
29
+ - Max 100 characters
30
+
31
+ Raises:
32
+ ValidationError: If agent_id is invalid
33
+ """
34
+ if not agent_id:
35
+ raise ValidationError(
36
+ "agent_id cannot be empty",
37
+ field="agent_id",
38
+ value=agent_id
39
+ )
40
+
41
+ if not isinstance(agent_id, str):
42
+ raise ValidationError(
43
+ f"agent_id must be a string, got {type(agent_id).__name__}",
44
+ field="agent_id",
45
+ value=agent_id
46
+ )
47
+
48
+ if len(agent_id) > 100:
49
+ raise ValidationError(
50
+ f"agent_id must be <= 100 characters, got {len(agent_id)}",
51
+ field="agent_id",
52
+ value=agent_id
53
+ )
54
+
55
+ if not re.match(r'^[a-zA-Z0-9_-]+$', agent_id):
56
+ raise ValidationError(
57
+ "agent_id must contain only alphanumeric characters, hyphens, and underscores",
58
+ field="agent_id",
59
+ value=agent_id
60
+ )
61
+
62
+
63
+ def validate_provider(provider: str) -> None:
64
+ """
65
+ Validate provider name.
66
+
67
+ Args:
68
+ provider: LLM provider name
69
+
70
+ Raises:
71
+ ValidationError: If provider is invalid
72
+ """
73
+ if not provider:
74
+ raise ValidationError(
75
+ "provider cannot be empty",
76
+ field="provider",
77
+ value=provider
78
+ )
79
+
80
+ if not isinstance(provider, str):
81
+ raise ValidationError(
82
+ f"provider must be a string, got {type(provider).__name__}",
83
+ field="provider",
84
+ value=provider
85
+ )
86
+
87
+ # Match Pydantic's Literal type constraint in types.py
88
+ valid_providers = {'openai', 'claude', 'gemini', 'custom'}
89
+ if provider.lower() not in valid_providers:
90
+ raise ValidationError(
91
+ f"Unknown provider '{provider}'. Valid providers: {', '.join(sorted(valid_providers))}. "
92
+ f"Use 'custom' for other providers (e.g., Anthropic, Bedrock, Azure).",
93
+ field="provider",
94
+ value=provider
95
+ )
96
+
97
+
98
+ def validate_step_number(step_number: int) -> None:
99
+ """
100
+ Validate step number.
101
+
102
+ Args:
103
+ step_number: Step number in execution chain
104
+
105
+ Raises:
106
+ ValidationError: If step_number is invalid
107
+ """
108
+ if not isinstance(step_number, int):
109
+ raise ValidationError(
110
+ f"step_number must be an integer, got {type(step_number).__name__}",
111
+ field="step_number",
112
+ value=step_number
113
+ )
114
+
115
+ if step_number < 0:
116
+ raise ValidationError(
117
+ f"step_number must be >= 0, got {step_number}",
118
+ field="step_number",
119
+ value=step_number
120
+ )
121
+
122
+ if step_number > 10000:
123
+ raise ValidationError(
124
+ f"step_number must be <= 10000, got {step_number}. "
125
+ "This likely indicates an infinite loop.",
126
+ field="step_number",
127
+ value=step_number
128
+ )
129
+
130
+
131
+ def validate_scopes(scopes: List[str]) -> None:
132
+ """
133
+ Validate permission scopes.
134
+
135
+ Args:
136
+ scopes: List of permission scopes
137
+
138
+ Raises:
139
+ ValidationError: If scopes are invalid
140
+ """
141
+ if not isinstance(scopes, list):
142
+ raise ValidationError(
143
+ f"scopes must be a list, got {type(scopes).__name__}",
144
+ field="scopes",
145
+ value=scopes
146
+ )
147
+
148
+ if not scopes:
149
+ raise ValidationError(
150
+ "scopes cannot be empty. Every envelope must grant at least one permission.",
151
+ field="scopes",
152
+ value=scopes
153
+ )
154
+
155
+ for i, scope in enumerate(scopes):
156
+ if not isinstance(scope, str):
157
+ raise ValidationError(
158
+ f"scope at index {i} must be a string, got {type(scope).__name__}",
159
+ field=f"scopes[{i}]",
160
+ value=scope
161
+ )
162
+
163
+ if not scope:
164
+ raise ValidationError(
165
+ f"scope at index {i} cannot be empty",
166
+ field=f"scopes[{i}]",
167
+ value=scope
168
+ )
169
+
170
+ # Validate scope format - allow multiple colon-separated segments
171
+ # Supported patterns:
172
+ # - action:resource (e.g., 'read:users', 'write:data')
173
+ # - namespace:resource:action (e.g., 'vault:finance:read', 'wallet:transfer')
174
+ if ':' in scope:
175
+ parts = scope.split(':')
176
+ if len(parts) < 2:
177
+ raise ValidationError(
178
+ f"Scope '{scope}' has invalid format. Expected 'action:resource' or 'namespace:resource:action'",
179
+ field=f"scopes[{i}]",
180
+ value=scope
181
+ )
182
+
183
+ # Check that no part is empty
184
+ for j, part in enumerate(parts):
185
+ if not part:
186
+ raise ValidationError(
187
+ f"Scope '{scope}' has empty segment at position {j}",
188
+ field=f"scopes[{i}]",
189
+ value=scope
190
+ )
191
+
192
+
193
+ def validate_resources(resources: List[str]) -> None:
194
+ """
195
+ Validate resource patterns.
196
+
197
+ Args:
198
+ resources: List of resource patterns
199
+
200
+ Raises:
201
+ ValidationError: If resources are invalid
202
+ """
203
+ if not isinstance(resources, list):
204
+ raise ValidationError(
205
+ f"resources must be a list, got {type(resources).__name__}",
206
+ field="resources",
207
+ value=resources
208
+ )
209
+
210
+ if not resources:
211
+ raise ValidationError(
212
+ "resources cannot be empty. Use ['*'] to grant access to all resources.",
213
+ field="resources",
214
+ value=resources
215
+ )
216
+
217
+ for i, resource in enumerate(resources):
218
+ if not isinstance(resource, str):
219
+ raise ValidationError(
220
+ f"resource at index {i} must be a string, got {type(resource).__name__}",
221
+ field=f"resources[{i}]",
222
+ value=resource
223
+ )
224
+
225
+ if not resource:
226
+ raise ValidationError(
227
+ f"resource at index {i} cannot be empty",
228
+ field=f"resources[{i}]",
229
+ value=resource
230
+ )
231
+
232
+
233
+ def validate_ttl_seconds(ttl_seconds: int, parent_ttl: Optional[int] = None) -> None:
234
+ """
235
+ Validate TTL (time-to-live).
236
+
237
+ Args:
238
+ ttl_seconds: TTL in seconds
239
+ parent_ttl: Parent envelope TTL (if this is a child envelope)
240
+
241
+ Raises:
242
+ ValidationError: If TTL is invalid
243
+ """
244
+ if not isinstance(ttl_seconds, int):
245
+ raise ValidationError(
246
+ f"ttl_seconds must be an integer, got {type(ttl_seconds).__name__}",
247
+ field="ttl_seconds",
248
+ value=ttl_seconds
249
+ )
250
+
251
+ if ttl_seconds < 60:
252
+ raise ValidationError(
253
+ f"ttl_seconds must be >= 60 (1 minute), got {ttl_seconds}. "
254
+ "Short-lived envelopes are a security risk.",
255
+ field="ttl_seconds",
256
+ value=ttl_seconds
257
+ )
258
+
259
+ if ttl_seconds > 86400:
260
+ raise ValidationError(
261
+ f"ttl_seconds must be <= 86400 (24 hours), got {ttl_seconds}. "
262
+ "Long-lived envelopes are a security risk.",
263
+ field="ttl_seconds",
264
+ value=ttl_seconds
265
+ )
266
+
267
+ # Validate child TTL <= parent TTL
268
+ if parent_ttl is not None:
269
+ if ttl_seconds > parent_ttl:
270
+ raise ValidationError(
271
+ f"Child envelope TTL ({ttl_seconds}s) cannot exceed parent TTL ({parent_ttl}s). "
272
+ "Children must have equal or shorter lifetimes than their parents.",
273
+ field="ttl_seconds",
274
+ value=ttl_seconds
275
+ )
276
+
277
+
278
+ def validate_private_key(private_key: str) -> None:
279
+ """
280
+ Validate Ed25519 private key format.
281
+
282
+ Args:
283
+ private_key: Hex-encoded Ed25519 private key
284
+
285
+ Raises:
286
+ ValidationError: If private key is invalid
287
+ """
288
+ if not isinstance(private_key, str):
289
+ raise ValidationError(
290
+ f"private_key must be a string, got {type(private_key).__name__}",
291
+ field="private_key",
292
+ value="<redacted>"
293
+ )
294
+
295
+ if not private_key:
296
+ raise ValidationError(
297
+ "private_key cannot be empty",
298
+ field="private_key",
299
+ value="<redacted>"
300
+ )
301
+
302
+ # Ed25519 private key is 32 bytes = 64 hex characters
303
+ if len(private_key) != 64:
304
+ raise ValidationError(
305
+ f"private_key must be 64 hex characters (32 bytes), got {len(private_key)}. "
306
+ "Use generate_key_pair() to create valid keys.",
307
+ field="private_key",
308
+ value="<redacted>"
309
+ )
310
+
311
+ # Validate hex encoding
312
+ try:
313
+ int(private_key, 16)
314
+ except ValueError:
315
+ raise ValidationError(
316
+ "private_key must be hex-encoded (0-9, a-f). "
317
+ "Use generate_key_pair() to create valid keys.",
318
+ field="private_key",
319
+ value="<redacted>"
320
+ )
321
+
322
+
323
+ def validate_authority_narrowing(
324
+ parent_authority: Authority,
325
+ child_scopes: List[str],
326
+ child_resources: List[str]
327
+ ) -> None:
328
+ """
329
+ Validate that child authority is a proper subset of parent authority.
330
+
331
+ This enforces the core security invariant: children cannot have MORE permissions than parents.
332
+
333
+ Args:
334
+ parent_authority: Parent envelope's authority
335
+ child_scopes: Child envelope's requested scopes
336
+ child_resources: Child envelope's requested resources
337
+
338
+ Raises:
339
+ ValidationError: If child authority exceeds parent authority
340
+ """
341
+ # Validate scopes: child ⊆ parent
342
+ parent_scopes_set = set(parent_authority.scopes)
343
+ child_scopes_set = set(child_scopes)
344
+
345
+ if not child_scopes_set.issubset(parent_scopes_set):
346
+ invalid_scopes = child_scopes_set - parent_scopes_set
347
+ raise ValidationError(
348
+ f"Child envelope has scopes not granted by parent: {sorted(invalid_scopes)}. "
349
+ f"Parent grants: {sorted(parent_authority.scopes)}. "
350
+ f"Child requested: {sorted(child_scopes)}. "
351
+ "Children can only narrow permissions, not expand them.",
352
+ field="authority.scopes",
353
+ value=child_scopes
354
+ )
355
+
356
+ # Validate resources: For now, we allow any subset
357
+ # More sophisticated validation could check resource patterns
358
+ if '*' not in parent_authority.resources:
359
+ # Parent has specific resources, validate child doesn't exceed
360
+ parent_resources_set = set(parent_authority.resources)
361
+ child_resources_set = set(child_resources)
362
+
363
+ # If child requests specific resources, they must be in parent's list
364
+ if '*' not in child_resources:
365
+ if not child_resources_set.issubset(parent_resources_set):
366
+ invalid_resources = child_resources_set - parent_resources_set
367
+ raise ValidationError(
368
+ f"Child envelope has resources not granted by parent: {sorted(invalid_resources)}. "
369
+ f"Parent grants: {sorted(parent_authority.resources)}. "
370
+ f"Child requested: {sorted(child_resources)}.",
371
+ field="authority.resources",
372
+ value=child_resources
373
+ )
374
+
375
+
376
+ def validate_envelope_for_execution(
377
+ envelope: AuthorityEnvelope,
378
+ required_scope: str
379
+ ) -> List[str]:
380
+ """
381
+ Validate that an envelope is suitable for executing an action.
382
+
383
+ Returns list of validation warnings (non-fatal issues).
384
+
385
+ Args:
386
+ envelope: Envelope to validate
387
+ required_scope: Required scope for the action
388
+
389
+ Returns:
390
+ List of warning messages (empty if no warnings)
391
+
392
+ Raises:
393
+ ValidationError: If envelope is invalid for execution
394
+ """
395
+ warnings = []
396
+
397
+ # Check if envelope is expiring soon (within 5% of TTL)
398
+ from datetime import datetime, timezone
399
+ import dateutil.parser
400
+
401
+ expires_at = dateutil.parser.isoparse(envelope.expires_at)
402
+ now = datetime.now(timezone.utc)
403
+ time_remaining = (expires_at - now).total_seconds()
404
+
405
+ if time_remaining < 0:
406
+ raise ValidationError(
407
+ f"Envelope {envelope.envelope_id} has expired. "
408
+ f"Expired at: {envelope.expires_at}, Current time: {now.isoformat()}",
409
+ field="expires_at",
410
+ value=envelope.expires_at
411
+ )
412
+
413
+ if time_remaining < envelope.ttl_seconds * 0.05: # Less than 5% remaining
414
+ warnings.append(
415
+ f"Envelope {envelope.envelope_id} is expiring soon "
416
+ f"({time_remaining:.0f}s remaining)"
417
+ )
418
+
419
+ # Check if required scope is granted
420
+ if required_scope not in envelope.authority.scopes:
421
+ raise ValidationError(
422
+ f"Envelope {envelope.envelope_id} does not grant required scope '{required_scope}'. "
423
+ f"Granted scopes: {envelope.authority.scopes}",
424
+ field="authority.scopes",
425
+ value=envelope.authority.scopes
426
+ )
427
+
428
+ return warnings