vectorguard-agentproof 1.1.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.
- agentproof/__init__.py +1 -0
- agentproof/agent_builder.py +388 -0
- agentproof/agent_chain.py +304 -0
- agentproof/agent_client.py +106 -0
- agentproof/agent_package.py +129 -0
- agentproof/agent_registry.py +242 -0
- agentproof/agent_remote.py +261 -0
- agentproof/agent_runtime.py +404 -0
- agentproof/agent_verifier.py +591 -0
- agentproof/api.py +1019 -0
- agentproof/api_keys.py +167 -0
- agentproof/assurance.py +46 -0
- agentproof/audit.py +306 -0
- agentproof/billing.py +392 -0
- agentproof/chain/__init__.py +17 -0
- agentproof/chain/anchor_gateway.py +314 -0
- agentproof/chain/circuit_breaker.py +93 -0
- agentproof/chain/evm.py +342 -0
- agentproof/chain/evm_lite.py +448 -0
- agentproof/chain/file_registry.py +80 -0
- agentproof/chain/protocol.py +97 -0
- agentproof/chain/registry.py +112 -0
- agentproof/chain_checkpoint.py +310 -0
- agentproof/challenge.py +284 -0
- agentproof/cli.py +1051 -0
- agentproof/credential_jwt.py +52 -0
- agentproof/credential_store.py +142 -0
- agentproof/crypto/__init__.py +1 -0
- agentproof/crypto/encryption.py +60 -0
- agentproof/crypto/hashing.py +21 -0
- agentproof/crypto/jwt.py +165 -0
- agentproof/crypto/keys.py +129 -0
- agentproof/crypto/sd_jwt.py +244 -0
- agentproof/did/__init__.py +1 -0
- agentproof/did/cache.py +115 -0
- agentproof/did/did_ethr.py +144 -0
- agentproof/did/did_key.py +80 -0
- agentproof/did/did_web.py +118 -0
- agentproof/did/governance.py +291 -0
- agentproof/did/resolver.py +67 -0
- agentproof/did/rotation.py +229 -0
- agentproof/dispute.py +197 -0
- agentproof/distributed_lock.py +171 -0
- agentproof/domain_link.py +211 -0
- agentproof/dpop.py +170 -0
- agentproof/events.py +358 -0
- agentproof/fees.py +127 -0
- agentproof/holder.py +64 -0
- agentproof/hosted_did.py +132 -0
- agentproof/hsm_signer.py +90 -0
- agentproof/http_signatures.py +458 -0
- agentproof/issuer.py +268 -0
- agentproof/key_store.py +384 -0
- agentproof/ledger_mirror.py +278 -0
- agentproof/mcp.py +51 -0
- agentproof/merchant.py +181 -0
- agentproof/metrics.py +68 -0
- agentproof/models/__init__.py +1 -0
- agentproof/models/agent.py +256 -0
- agentproof/models/agent_api.py +355 -0
- agentproof/models/agent_registry.py +51 -0
- agentproof/models/api.py +916 -0
- agentproof/models/api_key.py +33 -0
- agentproof/models/billing.py +165 -0
- agentproof/models/credential.py +137 -0
- agentproof/models/did_document.py +60 -0
- agentproof/models/dispute.py +31 -0
- agentproof/models/fee.py +40 -0
- agentproof/models/policy.py +15 -0
- agentproof/models/presentation.py +40 -0
- agentproof/models/rbac.py +108 -0
- agentproof/models/reputation.py +59 -0
- agentproof/models/schemas.py +246 -0
- agentproof/models/status.py +39 -0
- agentproof/models/status_list.py +120 -0
- agentproof/models/tenant.py +127 -0
- agentproof/models/trust.py +99 -0
- agentproof/models/webhook.py +28 -0
- agentproof/net_safety.py +181 -0
- agentproof/oauth_as.py +582 -0
- agentproof/oauth_client.py +153 -0
- agentproof/oauth_rs.py +276 -0
- agentproof/pg/__init__.py +36 -0
- agentproof/pg/agent_registry.py +167 -0
- agentproof/pg/api_keys.py +109 -0
- agentproof/pg/attestation.py +208 -0
- agentproof/pg/audit.py +310 -0
- agentproof/pg/credential_store.py +104 -0
- agentproof/pg/dispute.py +197 -0
- agentproof/pg/fees.py +97 -0
- agentproof/pg/key_store.py +159 -0
- agentproof/pg/pool.py +613 -0
- agentproof/pg/rbac.py +139 -0
- agentproof/pg/reputation.py +67 -0
- agentproof/pg/retry.py +71 -0
- agentproof/pg/spend.py +311 -0
- agentproof/pg/status_list.py +138 -0
- agentproof/pg/tenant.py +157 -0
- agentproof/pg/trust.py +230 -0
- agentproof/pg/webhook.py +163 -0
- agentproof/platform.py +112 -0
- agentproof/policy.py +89 -0
- agentproof/rate_limit.py +381 -0
- agentproof/rbac.py +192 -0
- agentproof/receipts.py +122 -0
- agentproof/reputation.py +101 -0
- agentproof/routes/__init__.py +1 -0
- agentproof/routes/_deps.py +297 -0
- agentproof/routes/agent.py +339 -0
- agentproof/routes/agent_builder.py +335 -0
- agentproof/routes/agents.py +540 -0
- agentproof/routes/api_keys.py +228 -0
- agentproof/routes/audit.py +82 -0
- agentproof/routes/billing.py +287 -0
- agentproof/routes/chain_auth.py +314 -0
- agentproof/routes/credentials.py +529 -0
- agentproof/routes/dev.py +76 -0
- agentproof/routes/disputes.py +193 -0
- agentproof/routes/events.py +77 -0
- agentproof/routes/fees.py +91 -0
- agentproof/routes/health.py +88 -0
- agentproof/routes/issuers.py +417 -0
- agentproof/routes/merchants.py +53 -0
- agentproof/routes/oauth.py +167 -0
- agentproof/routes/onboarding.py +217 -0
- agentproof/routes/platform.py +70 -0
- agentproof/routes/portal.py +373 -0
- agentproof/routes/principals.py +91 -0
- agentproof/routes/reputation.py +102 -0
- agentproof/routes/spend.py +135 -0
- agentproof/routes/tenants.py +312 -0
- agentproof/routes/usage.py +89 -0
- agentproof/routes/verification.py +253 -0
- agentproof/routes/webhooks.py +109 -0
- agentproof/routes/workloads.py +53 -0
- agentproof/secret_rotation.py +94 -0
- agentproof/secrets.py +93 -0
- agentproof/security/__init__.py +1 -0
- agentproof/security/pentest.py +351 -0
- agentproof/security/run_pentest.py +99 -0
- agentproof/security/threat_model.py +282 -0
- agentproof/signing_delegation.py +602 -0
- agentproof/spend.py +967 -0
- agentproof/status_list.py +150 -0
- agentproof/tenant.py +156 -0
- agentproof/tracing.py +62 -0
- agentproof/trust.py +256 -0
- agentproof/verifier.py +632 -0
- agentproof/webhook.py +320 -0
- agentproof/workers.py +123 -0
- agentproof/workload.py +137 -0
- vectorguard_agentproof-1.1.0.dist-info/METADATA +493 -0
- vectorguard_agentproof-1.1.0.dist-info/RECORD +156 -0
- vectorguard_agentproof-1.1.0.dist-info/WHEEL +4 -0
- vectorguard_agentproof-1.1.0.dist-info/entry_points.txt +3 -0
- vectorguard_agentproof-1.1.0.dist-info/licenses/LICENSE +21 -0
agentproof/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Credential issuance and verification infrastructure with on-chain attestation anchoring."""
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""Agent builder: blueprints, one-time enrollments, and their storage.
|
|
2
|
+
|
|
3
|
+
A company designs an agent in AgentProof as a *blueprint*: what it is for, its
|
|
4
|
+
instructions, which AI model it uses, which tools it may call, and the spending rules
|
|
5
|
+
of the delegation it will receive. AgentProof then produces a package that the company
|
|
6
|
+
runs on its own infrastructure (``agentproof.agent_package``).
|
|
7
|
+
|
|
8
|
+
Keys never leave the company. AgentProof does not generate or store the agent's key,
|
|
9
|
+
and it does not hold the company's AI-provider API key. On its first start the agent
|
|
10
|
+
generates its key where it runs and *enrolls*: it proves possession of the key with a
|
|
11
|
+
one-time enrollment token the company issued from the blueprint. Enrollment registers
|
|
12
|
+
the agent (a hosted DID whose first key is the agent's) and issues its delegation from
|
|
13
|
+
the blueprint's rules.
|
|
14
|
+
|
|
15
|
+
Enrollment tokens:
|
|
16
|
+
|
|
17
|
+
* 256 bits of randomness, shown once, stored only as a SHA-256 hash;
|
|
18
|
+
* single use (claimed atomically, so two concurrent enrollments cannot both succeed);
|
|
19
|
+
* short-lived (24 hours by default, at most 7 days) and revocable before use;
|
|
20
|
+
* scoped to one blueprint and one owner. They grant nothing else: no API access, no
|
|
21
|
+
other agents, no changes to the blueprint.
|
|
22
|
+
|
|
23
|
+
Each enrollment keeps a copy of the blueprint as it was when the token was issued, so
|
|
24
|
+
the limits the owner approved are the limits the agent receives, even if the
|
|
25
|
+
blueprint is edited before the agent starts.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import asyncio
|
|
31
|
+
import hashlib
|
|
32
|
+
import json
|
|
33
|
+
import secrets
|
|
34
|
+
from abc import ABC, abstractmethod
|
|
35
|
+
from dataclasses import dataclass, replace
|
|
36
|
+
from datetime import UTC, datetime
|
|
37
|
+
from enum import StrEnum
|
|
38
|
+
from typing import Any, Literal
|
|
39
|
+
|
|
40
|
+
from pydantic import Field, field_validator, model_validator
|
|
41
|
+
|
|
42
|
+
from agentproof.models.agent_api import DelegateRequest, _CamelModel
|
|
43
|
+
|
|
44
|
+
TOOLS = ("purchase", "fetch")
|
|
45
|
+
TOKEN_PREFIX = "apenr_"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ModelChoice(_CamelModel):
|
|
49
|
+
"""The AI model the agent uses. The company's own provider account pays for it;
|
|
50
|
+
its API key stays in the company's environment."""
|
|
51
|
+
|
|
52
|
+
provider: Literal["openai", "anthropic"]
|
|
53
|
+
name: str = Field(min_length=1, max_length=100, pattern=r"^[A-Za-z0-9._:\-]+$",
|
|
54
|
+
examples=["gpt-4.1", "claude-sonnet-4-5"])
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class BlueprintSpec(_CamelModel):
|
|
58
|
+
"""What the company configures. Request body of create and update."""
|
|
59
|
+
|
|
60
|
+
name: str = Field(min_length=1, max_length=128)
|
|
61
|
+
purpose: str | None = Field(default=None, max_length=256)
|
|
62
|
+
instructions: str = Field(min_length=1, max_length=8000,
|
|
63
|
+
description="System instructions for the agent.")
|
|
64
|
+
model: ModelChoice
|
|
65
|
+
tools: list[Literal["purchase", "fetch"]] = Field(
|
|
66
|
+
min_length=1, max_length=len(TOOLS),
|
|
67
|
+
description="purchase: a signed POST to a merchant checkout. fetch: a signed GET.")
|
|
68
|
+
delegation: DelegateRequest = Field(
|
|
69
|
+
description="Authority the agent receives on enrollment.")
|
|
70
|
+
max_steps: int = Field(default=8, ge=1, le=20,
|
|
71
|
+
description="Model and tool round trips per task.")
|
|
72
|
+
credential_ttl_days: int = Field(default=90, ge=1, le=365)
|
|
73
|
+
|
|
74
|
+
@field_validator("tools")
|
|
75
|
+
@classmethod
|
|
76
|
+
def _unique(cls, v: list[str]) -> list[str]:
|
|
77
|
+
if len(set(v)) != len(v):
|
|
78
|
+
msg = "tools must not repeat"
|
|
79
|
+
raise ValueError(msg)
|
|
80
|
+
return v
|
|
81
|
+
|
|
82
|
+
@model_validator(mode="after")
|
|
83
|
+
def _bounded(self) -> BlueprintSpec:
|
|
84
|
+
# A builder agent acts on its own, so where it may act must be explicit.
|
|
85
|
+
if not self.delegation.audiences:
|
|
86
|
+
msg = "delegation.audiences must list the merchants or services the agent may call"
|
|
87
|
+
raise ValueError(msg)
|
|
88
|
+
if "purchase" in self.tools and self.delegation.spend_limit is None:
|
|
89
|
+
msg = "an agent with the purchase tool needs delegation.spendLimit"
|
|
90
|
+
raise ValueError(msg)
|
|
91
|
+
return self
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class EnrollmentStatus(StrEnum):
|
|
95
|
+
PENDING = "pending"
|
|
96
|
+
CLAIMED = "claimed" # an enrollment is in progress with this token
|
|
97
|
+
COMPLETED = "completed"
|
|
98
|
+
REVOKED = "revoked"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class Blueprint:
|
|
103
|
+
id: str
|
|
104
|
+
owner_did: str
|
|
105
|
+
spec: BlueprintSpec
|
|
106
|
+
created_at: datetime
|
|
107
|
+
updated_at: datetime
|
|
108
|
+
archived: bool = False
|
|
109
|
+
|
|
110
|
+
def to_public(self) -> dict[str, Any]:
|
|
111
|
+
return {"id": self.id, "ownerDid": self.owner_did,
|
|
112
|
+
"createdAt": self.created_at.isoformat(),
|
|
113
|
+
"updatedAt": self.updated_at.isoformat(), "archived": self.archived,
|
|
114
|
+
**self.spec.model_dump(by_alias=True, mode="json", exclude_none=True)}
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass(frozen=True)
|
|
118
|
+
class Enrollment:
|
|
119
|
+
id: str
|
|
120
|
+
blueprint_id: str
|
|
121
|
+
owner_did: str
|
|
122
|
+
token_hash: str
|
|
123
|
+
spec: BlueprintSpec # the blueprint as approved when the token was issued
|
|
124
|
+
agent_id: str | None
|
|
125
|
+
created_at: datetime
|
|
126
|
+
expires_at: datetime
|
|
127
|
+
created_by: str
|
|
128
|
+
status: EnrollmentStatus = EnrollmentStatus.PENDING
|
|
129
|
+
agent_did: str | None = None
|
|
130
|
+
|
|
131
|
+
def usable(self, now: datetime) -> bool:
|
|
132
|
+
return self.status == EnrollmentStatus.PENDING and now < self.expires_at
|
|
133
|
+
|
|
134
|
+
def to_public(self) -> dict[str, Any]:
|
|
135
|
+
return {"id": self.id, "blueprintId": self.blueprint_id, "agentId": self.agent_id,
|
|
136
|
+
"status": self.status.value, "createdAt": self.created_at.isoformat(),
|
|
137
|
+
"expiresAt": self.expires_at.isoformat(), "agentDid": self.agent_did}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def new_token() -> str:
|
|
141
|
+
return TOKEN_PREFIX + secrets.token_urlsafe(32)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def hash_token(token: str) -> str:
|
|
145
|
+
return hashlib.sha256(token.encode()).hexdigest()
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def new_id(prefix: str) -> str:
|
|
149
|
+
return f"{prefix}_{secrets.token_hex(12)}"
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class BuilderStore(ABC):
|
|
153
|
+
"""Blueprints and enrollments. Every blueprint read and write is scoped by owner."""
|
|
154
|
+
|
|
155
|
+
@abstractmethod
|
|
156
|
+
async def create_blueprint(self, bp: Blueprint) -> None: ...
|
|
157
|
+
|
|
158
|
+
@abstractmethod
|
|
159
|
+
async def get_blueprint(self, owner_did: str, blueprint_id: str) -> Blueprint | None: ...
|
|
160
|
+
|
|
161
|
+
@abstractmethod
|
|
162
|
+
async def list_blueprints(self, owner_did: str) -> list[Blueprint]: ...
|
|
163
|
+
|
|
164
|
+
@abstractmethod
|
|
165
|
+
async def update_blueprint(self, owner_did: str, blueprint_id: str, spec: BlueprintSpec,
|
|
166
|
+
now: datetime) -> Blueprint | None: ...
|
|
167
|
+
|
|
168
|
+
@abstractmethod
|
|
169
|
+
async def archive_blueprint(self, owner_did: str, blueprint_id: str,
|
|
170
|
+
now: datetime) -> bool: ...
|
|
171
|
+
|
|
172
|
+
@abstractmethod
|
|
173
|
+
async def create_enrollment(self, e: Enrollment) -> None: ...
|
|
174
|
+
|
|
175
|
+
@abstractmethod
|
|
176
|
+
async def find_enrollment(self, token_hash: str) -> Enrollment | None: ...
|
|
177
|
+
|
|
178
|
+
@abstractmethod
|
|
179
|
+
async def claim_enrollment(self, enrollment_id: str, now: datetime) -> bool:
|
|
180
|
+
"""pending and unexpired -> claimed, atomically. False if anything else."""
|
|
181
|
+
|
|
182
|
+
@abstractmethod
|
|
183
|
+
async def release_enrollment(self, enrollment_id: str) -> None:
|
|
184
|
+
"""claimed -> pending (the enrollment failed after claiming)."""
|
|
185
|
+
|
|
186
|
+
@abstractmethod
|
|
187
|
+
async def complete_enrollment(self, enrollment_id: str, agent_did: str) -> None: ...
|
|
188
|
+
|
|
189
|
+
@abstractmethod
|
|
190
|
+
async def revoke_enrollment(self, owner_did: str, enrollment_id: str) -> bool:
|
|
191
|
+
"""pending -> revoked. False if not found, not the owner's, or already used."""
|
|
192
|
+
|
|
193
|
+
@abstractmethod
|
|
194
|
+
async def list_enrollments(self, owner_did: str, blueprint_id: str) -> list[Enrollment]: ...
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
class InMemoryBuilderStore(BuilderStore):
|
|
198
|
+
def __init__(self) -> None:
|
|
199
|
+
self._blueprints: dict[str, Blueprint] = {}
|
|
200
|
+
self._enrollments: dict[str, Enrollment] = {}
|
|
201
|
+
self._lock = asyncio.Lock()
|
|
202
|
+
|
|
203
|
+
async def create_blueprint(self, bp: Blueprint) -> None:
|
|
204
|
+
self._blueprints[bp.id] = bp
|
|
205
|
+
|
|
206
|
+
async def get_blueprint(self, owner_did: str, blueprint_id: str) -> Blueprint | None:
|
|
207
|
+
bp = self._blueprints.get(blueprint_id)
|
|
208
|
+
return bp if bp is not None and bp.owner_did == owner_did else None
|
|
209
|
+
|
|
210
|
+
async def list_blueprints(self, owner_did: str) -> list[Blueprint]:
|
|
211
|
+
return sorted((b for b in self._blueprints.values() if b.owner_did == owner_did),
|
|
212
|
+
key=lambda b: b.created_at)
|
|
213
|
+
|
|
214
|
+
async def update_blueprint(self, owner_did, blueprint_id, spec, now):
|
|
215
|
+
async with self._lock:
|
|
216
|
+
bp = await self.get_blueprint(owner_did, blueprint_id)
|
|
217
|
+
if bp is None or bp.archived:
|
|
218
|
+
return None
|
|
219
|
+
bp = replace(bp, spec=spec, updated_at=now)
|
|
220
|
+
self._blueprints[bp.id] = bp
|
|
221
|
+
return bp
|
|
222
|
+
|
|
223
|
+
async def archive_blueprint(self, owner_did, blueprint_id, now):
|
|
224
|
+
async with self._lock:
|
|
225
|
+
bp = await self.get_blueprint(owner_did, blueprint_id)
|
|
226
|
+
if bp is None:
|
|
227
|
+
return False
|
|
228
|
+
self._blueprints[bp.id] = replace(bp, archived=True, updated_at=now)
|
|
229
|
+
for e in list(self._enrollments.values()):
|
|
230
|
+
if e.blueprint_id == bp.id and e.status == EnrollmentStatus.PENDING:
|
|
231
|
+
self._enrollments[e.id] = replace(e, status=EnrollmentStatus.REVOKED)
|
|
232
|
+
return True
|
|
233
|
+
|
|
234
|
+
async def create_enrollment(self, e: Enrollment) -> None:
|
|
235
|
+
self._enrollments[e.id] = e
|
|
236
|
+
|
|
237
|
+
async def find_enrollment(self, token_hash: str) -> Enrollment | None:
|
|
238
|
+
return next((e for e in self._enrollments.values() if e.token_hash == token_hash), None)
|
|
239
|
+
|
|
240
|
+
async def claim_enrollment(self, enrollment_id, now):
|
|
241
|
+
async with self._lock:
|
|
242
|
+
e = self._enrollments.get(enrollment_id)
|
|
243
|
+
if e is None or not e.usable(now):
|
|
244
|
+
return False
|
|
245
|
+
self._enrollments[e.id] = replace(e, status=EnrollmentStatus.CLAIMED)
|
|
246
|
+
return True
|
|
247
|
+
|
|
248
|
+
async def release_enrollment(self, enrollment_id):
|
|
249
|
+
async with self._lock:
|
|
250
|
+
e = self._enrollments.get(enrollment_id)
|
|
251
|
+
if e is not None and e.status == EnrollmentStatus.CLAIMED:
|
|
252
|
+
self._enrollments[e.id] = replace(e, status=EnrollmentStatus.PENDING)
|
|
253
|
+
|
|
254
|
+
async def complete_enrollment(self, enrollment_id, agent_did):
|
|
255
|
+
async with self._lock:
|
|
256
|
+
e = self._enrollments[enrollment_id]
|
|
257
|
+
self._enrollments[e.id] = replace(e, status=EnrollmentStatus.COMPLETED,
|
|
258
|
+
agent_did=agent_did)
|
|
259
|
+
|
|
260
|
+
async def revoke_enrollment(self, owner_did, enrollment_id):
|
|
261
|
+
async with self._lock:
|
|
262
|
+
e = self._enrollments.get(enrollment_id)
|
|
263
|
+
if e is None or e.owner_did != owner_did or e.status != EnrollmentStatus.PENDING:
|
|
264
|
+
return False
|
|
265
|
+
self._enrollments[e.id] = replace(e, status=EnrollmentStatus.REVOKED)
|
|
266
|
+
return True
|
|
267
|
+
|
|
268
|
+
async def list_enrollments(self, owner_did, blueprint_id):
|
|
269
|
+
return sorted((e for e in self._enrollments.values()
|
|
270
|
+
if e.owner_did == owner_did and e.blueprint_id == blueprint_id),
|
|
271
|
+
key=lambda e: e.created_at)
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
class PostgresBuilderStore(BuilderStore):
|
|
275
|
+
"""Tables ``agent_blueprints`` and ``agent_enrollments`` (migration 018)."""
|
|
276
|
+
|
|
277
|
+
def __init__(self, pool: Any) -> None:
|
|
278
|
+
self._pool = pool
|
|
279
|
+
|
|
280
|
+
@staticmethod
|
|
281
|
+
def _bp(row: dict) -> Blueprint:
|
|
282
|
+
return Blueprint(id=row["id"], owner_did=row["owner_did"],
|
|
283
|
+
spec=BlueprintSpec.model_validate(_json(row["spec"])),
|
|
284
|
+
created_at=row["created_at"], updated_at=row["updated_at"],
|
|
285
|
+
archived=row["archived"])
|
|
286
|
+
|
|
287
|
+
@staticmethod
|
|
288
|
+
def _en(row: dict) -> Enrollment:
|
|
289
|
+
return Enrollment(id=row["id"], blueprint_id=row["blueprint_id"],
|
|
290
|
+
owner_did=row["owner_did"], token_hash=row["token_hash"],
|
|
291
|
+
spec=BlueprintSpec.model_validate(_json(row["spec"])),
|
|
292
|
+
agent_id=row["agent_id"], created_at=row["created_at"],
|
|
293
|
+
expires_at=row["expires_at"], created_by=row["created_by"],
|
|
294
|
+
status=EnrollmentStatus(row["status"]), agent_did=row["agent_did"])
|
|
295
|
+
|
|
296
|
+
async def _one(self, sql: str, params: tuple) -> dict | None:
|
|
297
|
+
async with self._pool.connection() as conn:
|
|
298
|
+
return await (await conn.execute(sql, params)).fetchone()
|
|
299
|
+
|
|
300
|
+
async def _all(self, sql: str, params: tuple) -> list[dict]:
|
|
301
|
+
async with self._pool.connection() as conn:
|
|
302
|
+
return await (await conn.execute(sql, params)).fetchall()
|
|
303
|
+
|
|
304
|
+
async def create_blueprint(self, bp: Blueprint) -> None:
|
|
305
|
+
await self._one(
|
|
306
|
+
"INSERT INTO agent_blueprints (id, owner_did, spec, created_at, updated_at, "
|
|
307
|
+
"archived) VALUES (%s, %s, %s, %s, %s, %s) RETURNING id",
|
|
308
|
+
(bp.id, bp.owner_did, _dump(bp.spec), bp.created_at, bp.updated_at, bp.archived))
|
|
309
|
+
|
|
310
|
+
async def get_blueprint(self, owner_did, blueprint_id):
|
|
311
|
+
row = await self._one("SELECT * FROM agent_blueprints WHERE id = %s AND owner_did = %s",
|
|
312
|
+
(blueprint_id, owner_did))
|
|
313
|
+
return self._bp(row) if row else None
|
|
314
|
+
|
|
315
|
+
async def list_blueprints(self, owner_did):
|
|
316
|
+
rows = await self._all("SELECT * FROM agent_blueprints WHERE owner_did = %s "
|
|
317
|
+
"ORDER BY created_at", (owner_did,))
|
|
318
|
+
return [self._bp(r) for r in rows]
|
|
319
|
+
|
|
320
|
+
async def update_blueprint(self, owner_did, blueprint_id, spec, now):
|
|
321
|
+
row = await self._one(
|
|
322
|
+
"UPDATE agent_blueprints SET spec = %s, updated_at = %s WHERE id = %s "
|
|
323
|
+
"AND owner_did = %s AND NOT archived RETURNING *",
|
|
324
|
+
(_dump(spec), now, blueprint_id, owner_did))
|
|
325
|
+
return self._bp(row) if row else None
|
|
326
|
+
|
|
327
|
+
async def archive_blueprint(self, owner_did, blueprint_id, now):
|
|
328
|
+
async with self._pool.connection() as conn, conn.transaction():
|
|
329
|
+
row = await (await conn.execute(
|
|
330
|
+
"UPDATE agent_blueprints SET archived = true, updated_at = %s WHERE id = %s "
|
|
331
|
+
"AND owner_did = %s RETURNING id", (now, blueprint_id, owner_did))).fetchone()
|
|
332
|
+
if row is None:
|
|
333
|
+
return False
|
|
334
|
+
await conn.execute(
|
|
335
|
+
"UPDATE agent_enrollments SET status = 'revoked' WHERE blueprint_id = %s "
|
|
336
|
+
"AND status = 'pending'", (blueprint_id,))
|
|
337
|
+
return True
|
|
338
|
+
|
|
339
|
+
async def create_enrollment(self, e: Enrollment) -> None:
|
|
340
|
+
await self._one(
|
|
341
|
+
"INSERT INTO agent_enrollments (id, blueprint_id, owner_did, token_hash, spec, "
|
|
342
|
+
"agent_id, created_at, expires_at, created_by, status) "
|
|
343
|
+
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id",
|
|
344
|
+
(e.id, e.blueprint_id, e.owner_did, e.token_hash, _dump(e.spec), e.agent_id,
|
|
345
|
+
e.created_at, e.expires_at, e.created_by, e.status.value))
|
|
346
|
+
|
|
347
|
+
async def find_enrollment(self, token_hash):
|
|
348
|
+
row = await self._one("SELECT * FROM agent_enrollments WHERE token_hash = %s",
|
|
349
|
+
(token_hash,))
|
|
350
|
+
return self._en(row) if row else None
|
|
351
|
+
|
|
352
|
+
async def claim_enrollment(self, enrollment_id, now):
|
|
353
|
+
row = await self._one(
|
|
354
|
+
"UPDATE agent_enrollments SET status = 'claimed' WHERE id = %s "
|
|
355
|
+
"AND status = 'pending' AND expires_at > %s RETURNING id", (enrollment_id, now))
|
|
356
|
+
return row is not None
|
|
357
|
+
|
|
358
|
+
async def release_enrollment(self, enrollment_id):
|
|
359
|
+
await self._one("UPDATE agent_enrollments SET status = 'pending' WHERE id = %s "
|
|
360
|
+
"AND status = 'claimed' RETURNING id", (enrollment_id,))
|
|
361
|
+
|
|
362
|
+
async def complete_enrollment(self, enrollment_id, agent_did):
|
|
363
|
+
await self._one("UPDATE agent_enrollments SET status = 'completed', agent_did = %s "
|
|
364
|
+
"WHERE id = %s RETURNING id", (agent_did, enrollment_id))
|
|
365
|
+
|
|
366
|
+
async def revoke_enrollment(self, owner_did, enrollment_id):
|
|
367
|
+
row = await self._one(
|
|
368
|
+
"UPDATE agent_enrollments SET status = 'revoked' WHERE id = %s AND owner_did = %s "
|
|
369
|
+
"AND status = 'pending' RETURNING id", (enrollment_id, owner_did))
|
|
370
|
+
return row is not None
|
|
371
|
+
|
|
372
|
+
async def list_enrollments(self, owner_did, blueprint_id):
|
|
373
|
+
rows = await self._all("SELECT * FROM agent_enrollments WHERE owner_did = %s "
|
|
374
|
+
"AND blueprint_id = %s ORDER BY created_at",
|
|
375
|
+
(owner_did, blueprint_id))
|
|
376
|
+
return [self._en(r) for r in rows]
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _dump(spec: BlueprintSpec) -> str:
|
|
380
|
+
return json.dumps(spec.model_dump(by_alias=True, mode="json", exclude_none=True))
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _json(value: Any) -> Any:
|
|
384
|
+
return json.loads(value) if isinstance(value, str) else value
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
def now_utc() -> datetime:
|
|
388
|
+
return datetime.now(UTC)
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Delegation-chain verification for agent identity.
|
|
2
|
+
|
|
3
|
+
A chain runs from a root principal (a human or business) to the calling agent::
|
|
4
|
+
|
|
5
|
+
principal ──delegates──▶ agent A ──delegates──▶ agent B (the caller)
|
|
6
|
+
|
|
7
|
+
Each link is an ``AgentDelegationCredential`` issued by the delegator to the
|
|
8
|
+
delegatee. The verifier checks every credential (signature, payload binding,
|
|
9
|
+
expiry, revocation) and then the chain rules:
|
|
10
|
+
|
|
11
|
+
* links connect: link[i].subject == link[i+1].issuer, and the last subject is
|
|
12
|
+
the calling agent
|
|
13
|
+
* the first issuer is the root principal named in every link
|
|
14
|
+
* ``delegatorDid`` equals the issuer of its own credential
|
|
15
|
+
* each link may only narrow its parent: scopes, spend limit, audiences
|
|
16
|
+
* ``maxDepth`` limits how many further hops each agent may create
|
|
17
|
+
* no DID appears twice, and the chain is bounded in length
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from datetime import UTC, datetime
|
|
24
|
+
from typing import TYPE_CHECKING
|
|
25
|
+
|
|
26
|
+
from pydantic import ValidationError
|
|
27
|
+
|
|
28
|
+
from agentproof.models.agent import (
|
|
29
|
+
AGENT_DELEGATION_TYPE,
|
|
30
|
+
MAX_DELEGATION_DEPTH,
|
|
31
|
+
AgentDelegationClaims,
|
|
32
|
+
SpendLimit,
|
|
33
|
+
schema_supported,
|
|
34
|
+
scope_covers,
|
|
35
|
+
)
|
|
36
|
+
from agentproof.models.credential import VerifiableCredential
|
|
37
|
+
|
|
38
|
+
if TYPE_CHECKING:
|
|
39
|
+
from collections.abc import Collection, Sequence
|
|
40
|
+
|
|
41
|
+
from agentproof.verifier import CredentialVerifier
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class DelegationLink:
|
|
46
|
+
"""One verified link, kept so spending and later re-checks can use it."""
|
|
47
|
+
|
|
48
|
+
delegation_id: str
|
|
49
|
+
issuer: str
|
|
50
|
+
subject: str
|
|
51
|
+
spend_limit: SpendLimit | None
|
|
52
|
+
status_ref: tuple[str, int] | None # (issuer DID, StatusList2021 index)
|
|
53
|
+
expires_at: datetime
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def delegation_id_of(vc: VerifiableCredential) -> str:
|
|
57
|
+
"""Stable identifier of a delegation credential."""
|
|
58
|
+
if vc.id:
|
|
59
|
+
return vc.id
|
|
60
|
+
return "jws:" + (vc.proof.jwt.rsplit(".", 1)[-1][:43] if vc.proof else "none")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _status_ref(vc: VerifiableCredential) -> tuple[str, int] | None:
|
|
64
|
+
if vc.credential_status is None:
|
|
65
|
+
return None
|
|
66
|
+
try:
|
|
67
|
+
return vc.issuer, int(vc.credential_status.id.rsplit("#", 1)[-1])
|
|
68
|
+
except (ValueError, IndexError):
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class DelegationChainResult:
|
|
74
|
+
"""Outcome of delegation-chain verification."""
|
|
75
|
+
|
|
76
|
+
valid: bool
|
|
77
|
+
error: str | None = None
|
|
78
|
+
agent_did: str | None = None
|
|
79
|
+
principal_did: str | None = None
|
|
80
|
+
principal_domain: str | None = None
|
|
81
|
+
depth: int = 0
|
|
82
|
+
scopes: list[str] = field(default_factory=list)
|
|
83
|
+
spend_limit: SpendLimit | None = None
|
|
84
|
+
audiences: list[str] | None = None
|
|
85
|
+
expires_at: datetime | None = None
|
|
86
|
+
principal_trust_tier: str | None = None
|
|
87
|
+
principal_reputation: int | None = None
|
|
88
|
+
links: list[DelegationLink] = field(default_factory=list)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _fail(error: str, **kwargs) -> DelegationChainResult:
|
|
92
|
+
return DelegationChainResult(valid=False, error=error, **kwargs)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def check_narrowing(parent: AgentDelegationClaims, child: AgentDelegationClaims) -> str | None:
|
|
96
|
+
"""Return an error message if ``child`` widens ``parent``, else None."""
|
|
97
|
+
for scope in child.scopes:
|
|
98
|
+
if not scope_covers(parent.scopes, scope):
|
|
99
|
+
return f"Scope '{scope}' is not covered by the delegating credential"
|
|
100
|
+
|
|
101
|
+
if child.max_depth > max(parent.max_depth - 1, 0):
|
|
102
|
+
return "maxDepth must be smaller than the parent's"
|
|
103
|
+
|
|
104
|
+
if parent.spend_limit is not None:
|
|
105
|
+
if child.spend_limit is None:
|
|
106
|
+
return "Delegation drops the parent's spend limit"
|
|
107
|
+
p, c = parent.spend_limit, child.spend_limit
|
|
108
|
+
if p.currency != c.currency or p.period != c.period:
|
|
109
|
+
return "Spend limit currency or period differs from the parent's"
|
|
110
|
+
if c.amount > p.amount:
|
|
111
|
+
return "Spend limit exceeds the parent's"
|
|
112
|
+
if c.per_transaction_cap > p.per_transaction_cap:
|
|
113
|
+
return "Per-transaction cap exceeds the parent's"
|
|
114
|
+
# A parent's merchant budget is enforced on every descendant purchase anyway
|
|
115
|
+
# (each link is charged), but a child may not claim more at that merchant.
|
|
116
|
+
for m in c.merchant_limits:
|
|
117
|
+
parent_m = p.merchant_limit(m.merchant_did)
|
|
118
|
+
if parent_m is not None and m.amount > parent_m.amount:
|
|
119
|
+
return f"Merchant limit for {m.merchant_did} exceeds the parent's"
|
|
120
|
+
|
|
121
|
+
if parent.audiences is not None:
|
|
122
|
+
if child.audiences is None:
|
|
123
|
+
return "Delegation drops the parent's audience restriction"
|
|
124
|
+
if not set(child.audiences) <= set(parent.audiences):
|
|
125
|
+
return "Audiences are not a subset of the parent's"
|
|
126
|
+
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class DelegationChainVerifier:
|
|
131
|
+
"""Verifies a principal-to-agent delegation chain.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
credential_verifier: Used to verify each credential's signature, expiry
|
|
135
|
+
and revocation status.
|
|
136
|
+
max_chain_length: Upper bound on links, in addition to the schema's
|
|
137
|
+
``maxDepth`` limit.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def __init__(
|
|
141
|
+
self,
|
|
142
|
+
credential_verifier: CredentialVerifier,
|
|
143
|
+
max_chain_length: int = MAX_DELEGATION_DEPTH + 1,
|
|
144
|
+
) -> None:
|
|
145
|
+
self._verifier = credential_verifier
|
|
146
|
+
self._max_len = max_chain_length
|
|
147
|
+
|
|
148
|
+
async def verify(
|
|
149
|
+
self,
|
|
150
|
+
chain: Sequence[VerifiableCredential],
|
|
151
|
+
agent_did: str,
|
|
152
|
+
*,
|
|
153
|
+
required_scopes: Collection[str] = (),
|
|
154
|
+
audience: str | None = None,
|
|
155
|
+
trusted_principals: Collection[str] | None = None,
|
|
156
|
+
require_revocation_status: bool = True,
|
|
157
|
+
check_chain: bool = False,
|
|
158
|
+
) -> DelegationChainResult:
|
|
159
|
+
"""Verify ``chain`` (root first) authorizes ``agent_did``.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
chain: Delegation credentials ordered from the root principal to the
|
|
163
|
+
calling agent.
|
|
164
|
+
agent_did: The DID of the agent making the call.
|
|
165
|
+
required_scopes: Scopes the leaf must grant.
|
|
166
|
+
audience: Merchant hostname the call targets. Checked against the
|
|
167
|
+
leaf's audience restriction.
|
|
168
|
+
trusted_principals: If given, the root principal must be in this set.
|
|
169
|
+
require_revocation_status: Require every link to carry a
|
|
170
|
+
``credentialStatus`` and the verifier to enforce it. A
|
|
171
|
+
delegation that cannot be revoked is rejected.
|
|
172
|
+
check_chain: Also check on-chain attestation for each link.
|
|
173
|
+
"""
|
|
174
|
+
if not chain:
|
|
175
|
+
return _fail("Delegation chain is empty", agent_did=agent_did)
|
|
176
|
+
if len(chain) > self._max_len:
|
|
177
|
+
return _fail("Delegation chain is too long", agent_did=agent_did)
|
|
178
|
+
if require_revocation_status and not self._verifier.has_status_list:
|
|
179
|
+
return _fail(
|
|
180
|
+
"Revocation cannot be enforced: no status list is configured",
|
|
181
|
+
agent_did=agent_did,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
claims_list: list[AgentDelegationClaims] = []
|
|
185
|
+
expiries: list[datetime] = []
|
|
186
|
+
root_tier: str | None = None
|
|
187
|
+
root_reputation: int | None = None
|
|
188
|
+
|
|
189
|
+
for i, vc in enumerate(chain):
|
|
190
|
+
where = f"Link {i}"
|
|
191
|
+
if AGENT_DELEGATION_TYPE not in vc.type:
|
|
192
|
+
return _fail(f"{where} is not an {AGENT_DELEGATION_TYPE}", agent_did=agent_did)
|
|
193
|
+
if vc.expiration_date is None:
|
|
194
|
+
return _fail(f"{where} has no expiration", agent_did=agent_did)
|
|
195
|
+
if not schema_supported(vc.schema_version):
|
|
196
|
+
return _fail(f"{where} has unsupported schemaVersion {vc.schema_version}",
|
|
197
|
+
agent_did=agent_did)
|
|
198
|
+
if require_revocation_status and vc.credential_status is None:
|
|
199
|
+
return _fail(f"{where} has no credentialStatus", agent_did=agent_did)
|
|
200
|
+
|
|
201
|
+
try:
|
|
202
|
+
claims = AgentDelegationClaims.model_validate(vc.credential_subject.claims)
|
|
203
|
+
except ValidationError as exc:
|
|
204
|
+
return _fail(f"{where} has invalid claims: {exc.error_count()} error(s)",
|
|
205
|
+
agent_did=agent_did)
|
|
206
|
+
|
|
207
|
+
if claims.delegator_did != vc.issuer:
|
|
208
|
+
return _fail(f"{where}: delegatorDid does not match issuer", agent_did=agent_did)
|
|
209
|
+
if vc.issuer == vc.credential_subject.id:
|
|
210
|
+
return _fail(f"{where}: self-delegation is not allowed", agent_did=agent_did)
|
|
211
|
+
|
|
212
|
+
result = await self._verifier.verify(vc, check_chain=check_chain)
|
|
213
|
+
if not result.valid:
|
|
214
|
+
return _fail(f"{where} is invalid: {result.error}", agent_did=agent_did)
|
|
215
|
+
if i == 0:
|
|
216
|
+
root_tier = result.issuer_trust_tier
|
|
217
|
+
root_reputation = result.issuer_reputation
|
|
218
|
+
|
|
219
|
+
# Connectivity and uniqueness
|
|
220
|
+
if i > 0 and chain[i - 1].credential_subject.id != vc.issuer:
|
|
221
|
+
return _fail(f"{where}: issuer is not the previous link's subject",
|
|
222
|
+
agent_did=agent_did)
|
|
223
|
+
|
|
224
|
+
if claims_list:
|
|
225
|
+
parent = claims_list[-1]
|
|
226
|
+
if claims.principal_did != parent.principal_did:
|
|
227
|
+
return _fail(f"{where}: principalDid differs from the parent link",
|
|
228
|
+
agent_did=agent_did)
|
|
229
|
+
if claims.principal_domain != parent.principal_domain:
|
|
230
|
+
return _fail(f"{where}: principalDomain differs from the parent link",
|
|
231
|
+
agent_did=agent_did)
|
|
232
|
+
narrowing_error = check_narrowing(parent, claims)
|
|
233
|
+
if narrowing_error:
|
|
234
|
+
return _fail(f"{where}: {narrowing_error}", agent_did=agent_did)
|
|
235
|
+
if vc.expiration_date > expiries[-1]:
|
|
236
|
+
return _fail(f"{where}: expires after the parent link", agent_did=agent_did)
|
|
237
|
+
|
|
238
|
+
claims_list.append(claims)
|
|
239
|
+
expiries.append(vc.expiration_date)
|
|
240
|
+
|
|
241
|
+
path = [chain[0].issuer, *(vc.credential_subject.id for vc in chain)]
|
|
242
|
+
if len(set(path)) != len(path):
|
|
243
|
+
return _fail("A DID appears twice in the chain (cycle)", agent_did=agent_did)
|
|
244
|
+
|
|
245
|
+
root = chain[0]
|
|
246
|
+
principal = claims_list[0].principal_did
|
|
247
|
+
if root.issuer != principal:
|
|
248
|
+
return _fail("Root issuer does not match principalDid", agent_did=agent_did)
|
|
249
|
+
if chain[-1].credential_subject.id != agent_did:
|
|
250
|
+
return _fail("Chain does not end at the calling agent", agent_did=agent_did,
|
|
251
|
+
principal_did=principal)
|
|
252
|
+
if trusted_principals is not None and principal not in trusted_principals:
|
|
253
|
+
return _fail("Principal is not trusted", agent_did=agent_did, principal_did=principal)
|
|
254
|
+
|
|
255
|
+
# Depth: a link's agent may create at most maxDepth further hops.
|
|
256
|
+
for i, claims in enumerate(claims_list):
|
|
257
|
+
remaining = len(chain) - 1 - i
|
|
258
|
+
if remaining > claims.max_depth:
|
|
259
|
+
return _fail(
|
|
260
|
+
f"Link {i} allows {claims.max_depth} further hop(s) "
|
|
261
|
+
f"but the chain has {remaining}",
|
|
262
|
+
agent_did=agent_did,
|
|
263
|
+
principal_did=principal,
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
leaf = claims_list[-1]
|
|
267
|
+
for scope in required_scopes:
|
|
268
|
+
if not scope_covers(leaf.scopes, scope):
|
|
269
|
+
return _fail(f"Scope '{scope}' is not granted", agent_did=agent_did,
|
|
270
|
+
principal_did=principal)
|
|
271
|
+
if (audience is not None and leaf.audiences is not None
|
|
272
|
+
and audience.lower() not in leaf.audiences):
|
|
273
|
+
return _fail("Audience is not permitted by the delegation", agent_did=agent_did,
|
|
274
|
+
principal_did=principal)
|
|
275
|
+
|
|
276
|
+
now = datetime.now(UTC)
|
|
277
|
+
expires_at = min(expiries)
|
|
278
|
+
if expires_at <= now: # defensive: each link was already checked
|
|
279
|
+
return _fail("Delegation has expired", agent_did=agent_did, principal_did=principal)
|
|
280
|
+
|
|
281
|
+
return DelegationChainResult(
|
|
282
|
+
valid=True,
|
|
283
|
+
agent_did=agent_did,
|
|
284
|
+
principal_did=principal,
|
|
285
|
+
principal_domain=claims_list[0].principal_domain,
|
|
286
|
+
depth=len(chain),
|
|
287
|
+
scopes=list(leaf.scopes),
|
|
288
|
+
spend_limit=leaf.spend_limit,
|
|
289
|
+
audiences=leaf.audiences,
|
|
290
|
+
expires_at=expires_at,
|
|
291
|
+
principal_trust_tier=root_tier,
|
|
292
|
+
principal_reputation=root_reputation,
|
|
293
|
+
links=[
|
|
294
|
+
DelegationLink(
|
|
295
|
+
delegation_id=delegation_id_of(vc),
|
|
296
|
+
issuer=vc.issuer,
|
|
297
|
+
subject=vc.credential_subject.id,
|
|
298
|
+
spend_limit=c.spend_limit,
|
|
299
|
+
status_ref=_status_ref(vc),
|
|
300
|
+
expires_at=vc.expiration_date,
|
|
301
|
+
)
|
|
302
|
+
for vc, c in zip(chain, claims_list, strict=True)
|
|
303
|
+
],
|
|
304
|
+
)
|