Merged
merge develop into main #295
maoqimingAdd on Sep 4
merge develop into main #295
Merged
maoqimingAdd on Sep 4
Merged fromdevelopintomain
Total: 125 files changed+13001-351
@@ -607,16 +607,20 @@ void LibcurlConn::CheckMultiInfo()
607 continue;607 continue;
608 }608 }
609 609 
610- // Process response based on result610+ // CURLMsg lives inside the easy handle on some libcurl builds; copy result
611- if (msg->data.result == CURLE_OK) {611+ // before cleanup. Free the handle before business callbacks so exceptions /
612- HandleFinishedResponse(request);612+ // early returns cannot skip curl_easy_cleanup (ASAN leak).
613- } else {613+ CURLcode result = msg->data.result;
614- HandleErrorResponse(request, curl_easy_strerror(msg->data.result));
615- }
616- 
617- // Cleanup resources
618 curl_multi_remove_handle(multiHandle_, easyHandle);614 curl_multi_remove_handle(multiHandle_, easyHandle);
619 curl_easy_cleanup(easyHandle);615 curl_easy_cleanup(easyHandle);
616+ request->easyHandle = nullptr;
617+ 
618+ // Process response based on result (statusCode already set in HeaderCallback)
619+ if (result == CURLE_OK) {
620+ HandleFinishedResponse(request);
621+ } else {
622+ HandleErrorResponse(request, curl_easy_strerror(result));
623+ }
620 }624 }
621}625}
622 626 
@@ -1060,8 +1064,10 @@ void LibcurlConn::CancelRequest(const std::shared_ptr<RequestContext>& request)
1060 }1064 }
1061 1065 
1062 if (request->easyHandle != nullptr) {1066 if (request->easyHandle != nullptr) {
1063- // Remove from multi handle1067+ // Remove and free easy handle before callback (exception-safe; avoids ASAN leak)
1064 curl_multi_remove_handle(multiHandle_, request->easyHandle);1068 curl_multi_remove_handle(multiHandle_, request->easyHandle);
1069+ curl_easy_cleanup(request->easyHandle);
1070+ request->easyHandle = nullptr;
1065 1071 
1066 HttpResponse response;1072 HttpResponse response;
1067 response.success = false;1073 response.success = false;
@@ -1070,10 +1076,6 @@ void LibcurlConn::CancelRequest(const std::shared_ptr<RequestContext>& request)
1070 response.userData = request->userData;1076 response.userData = request->userData;
1071 ExecuteCallback(request, response);1077 ExecuteCallback(request, response);
1072 1078 
1073- // Cleanup CURL handle
1074- curl_easy_cleanup(request->easyHandle);
1075- request->easyHandle = nullptr;
1076- 
1077 A2A_LOG(A2A_LOG_LEVEL::INFO, std::string("Request ") + request->userData.requestId +1079 A2A_LOG(A2A_LOG_LEVEL::INFO, std::string("Request ") + request->userData.requestId +
1078 " cancelled successfully");1080 " cancelled successfully");
1079 }1081 }
@@ -84,8 +84,13 @@ struct RequestContext {
84 84 
85 ~RequestContext()85 ~RequestContext()
86 {86 {
87+ // Cleanup CURL easy handle if still owned (e.g. exception before explicit cleanup)
88+ if (easyHandle != nullptr) {
89+ curl_easy_cleanup(easyHandle);
90+ easyHandle = nullptr;
91+ }
87 // Cleanup headers to prevent memory leak92 // Cleanup headers to prevent memory leak
88- if (headers) {93+ if (headers != nullptr) {
89 curl_slist_free_all(headers);94 curl_slist_free_all(headers);
90 headers = nullptr;95 headers = nullptr;
91 }96 }
@@ -20,12 +20,12 @@ HttpServerManager::~HttpServerManager()
20 20 
21void HttpServerManager::Start()21void HttpServerManager::Start()
22{22{
23- if (running_.exchange(true)) {23+ std::lock_guard<std::mutex> lock(mutex_);
24+ if (running_) {
24 return;25 return;
25 }26 }
26 27 
27 if (config_.ioThreadNum == 0) {28 if (config_.ioThreadNum == 0) {
28- running_ = false;
29 return;29 return;
30 }30 }
31 31 
@@ -34,7 +34,7 @@ void HttpServerManager::Start()
34 34 
35 for (size_t i = 0; i < config_.ioThreadNum; ++i) {35 for (size_t i = 0; i < config_.ioThreadNum; ++i) {
36 servers_.push_back(36 servers_.push_back(
37- std::make_unique<HttpServer>(config_.host, config_.port, config_.tlsConfig, config_.routeMap));37+ std::make_unique<HttpServer>(config_.host, config_.port, config_.tlsConfig, config_.routeMap, i));
38 }38 }
39 39 
40 for (auto& server : servers_) {40 for (auto& server : servers_) {
@@ -42,20 +42,29 @@ void HttpServerManager::Start()
42 server->Run();42 server->Run();
43 }43 }
44 }44 }
45+ 
46+ // Mark running only after servers_ is fully populated and Run() has returned,
47+ // so concurrent Stop() cannot clear a half-built vector.
48+ running_ = true;
45}49}
46 50 
47void HttpServerManager::Stop()51void HttpServerManager::Stop()
48{52{
49- if (!running_.exchange(false)) {53+ std::vector<std::unique_ptr<HttpServer>> serversToStop;
50- return;54+ {
55+ std::lock_guard<std::mutex> lock(mutex_);
56+ if (!running_) {
57+ return;
58+ }
59+ running_ = false;
60+ serversToStop.swap(servers_);
51 }61 }
52 62 
53- for (auto& server : servers_) {63+ for (auto& server : serversToStop) {
54 if (server != nullptr) {64 if (server != nullptr) {
55 server->Stop();65 server->Stop();
56 }66 }
57 }67 }
58- 68+ serversToStop.clear();
59- servers_.clear();
60}69}
61-} // namespace A2A::Server70+} // namespace A2A::Server
@@ -5,8 +5,8 @@
5#ifndef A2A_HTTP_SERVER_MANAGER_H_5#ifndef A2A_HTTP_SERVER_MANAGER_H_
6#define A2A_HTTP_SERVER_MANAGER_H_6#define A2A_HTTP_SERVER_MANAGER_H_
7 7 
8-#include <atomic>
9#include <memory>8#include <memory>
9+#include <mutex>
10#include <string>10#include <string>
11#include <unordered_map>11#include <unordered_map>
12#include <vector>12#include <vector>
@@ -54,8 +54,9 @@ public:
54private:54private:
55 HttpServerManagerConfig config_; // Configuration.55 HttpServerManagerConfig config_; // Configuration.
56 56 
57+ std::mutex mutex_;
57 std::vector<std::unique_ptr<HttpServer>> servers_;58 std::vector<std::unique_ptr<HttpServer>> servers_;
58- std::atomic<bool> running_{false};59+ bool running_{false};
59};60};
60 61 
61} // namespace A2A::Server62} // namespace A2A::Server
@@ -5,6 +5,7 @@
5#include <nlohmann/json.hpp>5#include <nlohmann/json.hpp>
6#include <thread>6#include <thread>
7#include <mutex>7#include <mutex>
8+#include <future>
8#include <algorithm>9#include <algorithm>
9 10 
10#include "stream_server_emitter.h"11#include "stream_server_emitter.h"
@@ -66,10 +67,19 @@ int HttpServerTransport::Start()
66 // Create and start the server manager67 // Create and start the server manager
67 httpServerMgr_ = std::make_unique<Server::HttpServerManager>(config);68 httpServerMgr_ = std::make_unique<Server::HttpServerManager>(config);
68 69 
69- // Start server in background thread70+ // Start server in background thread; wait until Start() finishes so Stop()
70- listenThread_ = std::thread([this]() {71+ // cannot race with servers_ construction (ASAN SEGV in unique_ptr clear).
71- httpServerMgr_->Start();72+ auto started = std::make_shared<std::promise<void>>();
73+ auto startedFuture = started->get_future();
74+ listenThread_ = std::thread([this, started]() {
75+ try {
76+ httpServerMgr_->Start();
77+ started->set_value();
78+ } catch (...) {
79+ started->set_exception(std::current_exception());
80+ }
72 });81 });
82+ startedFuture.get();
73 83 
74 return 0;84 return 0;
75}85}
@@ -82,4 +82,8 @@ endif()
82 82 
83add_dependencies(a2a_ut_test a2a)83add_dependencies(a2a_ut_test a2a)
84 84 
85-gtest_discover_tests(a2a_ut_test)85+# DISCOVERY_TIMEOUT: ASAN builds are slow to start; default 5s often fails discovery.
86+gtest_discover_tests(a2a_ut_test
87+ DISCOVERY_TIMEOUT 60
88+ PROPERTIES TIMEOUT 300
89+)
@@ -33,18 +33,18 @@ TEST_F(HttpServerManagerCoverageTest, ConstructorInitializesFields)
33 EXPECT_EQ(mgr.config_.host, "127.0.0.1");33 EXPECT_EQ(mgr.config_.host, "127.0.0.1");
34 EXPECT_EQ(mgr.config_.port, 0);34 EXPECT_EQ(mgr.config_.port, 0);
35 EXPECT_EQ(mgr.config_.ioThreadNum, 2u);35 EXPECT_EQ(mgr.config_.ioThreadNum, 2u);
36- EXPECT_FALSE(mgr.running_.load());36+ EXPECT_FALSE(mgr.running_);
37 EXPECT_TRUE(mgr.servers_.empty());37 EXPECT_TRUE(mgr.servers_.empty());
38}38}
39 39 
40TEST_F(HttpServerManagerCoverageTest, StartWhenAlreadyRunningReturnsImmediately)40TEST_F(HttpServerManagerCoverageTest, StartWhenAlreadyRunningReturnsImmediately)
41{41{
42 HttpServerManager mgr(MakeConfig(2));42 HttpServerManager mgr(MakeConfig(2));
43- mgr.running_.store(true);43+ mgr.running_ = true;
44 44 
45 mgr.Start();45 mgr.Start();
46 46 
47- EXPECT_TRUE(mgr.running_.load());47+ EXPECT_TRUE(mgr.running_);
48 EXPECT_TRUE(mgr.servers_.empty());48 EXPECT_TRUE(mgr.servers_.empty());
49}49}
50 50 
@@ -54,7 +54,7 @@ TEST_F(HttpServerManagerCoverageTest, StartWithZeroIoThreadReturnsWithoutCreatin
54 54 
55 mgr.Start();55 mgr.Start();
56 56 
57- EXPECT_FALSE(mgr.running_.load());57+ EXPECT_FALSE(mgr.running_);
58 EXPECT_TRUE(mgr.servers_.empty());58 EXPECT_TRUE(mgr.servers_.empty());
59}59}
60 60 
@@ -64,14 +64,14 @@ TEST_F(HttpServerManagerCoverageTest, StopWhenNotRunningReturnsImmediately)
64 64 
65 mgr.Stop();65 mgr.Stop();
66 66 
67- EXPECT_FALSE(mgr.running_.load());67+ EXPECT_FALSE(mgr.running_);
68 EXPECT_TRUE(mgr.servers_.empty());68 EXPECT_TRUE(mgr.servers_.empty());
69}69}
70 70 
71TEST_F(HttpServerManagerCoverageTest, StopWhenRunningAndServersExistClearsAllServers)71TEST_F(HttpServerManagerCoverageTest, StopWhenRunningAndServersExistClearsAllServers)
72{72{
73 HttpServerManager mgr(MakeConfig(2));73 HttpServerManager mgr(MakeConfig(2));
74- mgr.running_.store(true);74+ mgr.running_ = true;
75 75 
76 mgr.servers_.push_back(nullptr);76 mgr.servers_.push_back(nullptr);
77 mgr.servers_.push_back(nullptr);77 mgr.servers_.push_back(nullptr);
@@ -79,27 +79,27 @@ TEST_F(HttpServerManagerCoverageTest, StopWhenRunningAndServersExistClearsAllSer
79 79 
80 mgr.Stop();80 mgr.Stop();
81 81 
82- EXPECT_FALSE(mgr.running_.load());82+ EXPECT_FALSE(mgr.running_);
83 EXPECT_TRUE(mgr.servers_.empty());83 EXPECT_TRUE(mgr.servers_.empty());
84}84}
85 85 
86TEST_F(HttpServerManagerCoverageTest, StopTwiceIsSafe)86TEST_F(HttpServerManagerCoverageTest, StopTwiceIsSafe)
87{87{
88 HttpServerManager mgr(MakeConfig(1));88 HttpServerManager mgr(MakeConfig(1));
89- mgr.running_.store(true);89+ mgr.running_ = true;
90 mgr.servers_.push_back(nullptr);90 mgr.servers_.push_back(nullptr);
91 91 
92 mgr.Stop();92 mgr.Stop();
93 mgr.Stop();93 mgr.Stop();
94 94 
95- EXPECT_FALSE(mgr.running_.load());95+ EXPECT_FALSE(mgr.running_);
96 EXPECT_TRUE(mgr.servers_.empty());96 EXPECT_TRUE(mgr.servers_.empty());
97}97}
98 98 
99TEST_F(HttpServerManagerCoverageTest, DestructorCallsStopSafely)99TEST_F(HttpServerManagerCoverageTest, DestructorCallsStopSafely)
100{100{
101 auto mgr = std::make_unique<HttpServerManager>(MakeConfig(1));101 auto mgr = std::make_unique<HttpServerManager>(MakeConfig(1));
102- mgr->running_.store(true);102+ mgr->running_ = true;
103 mgr->servers_.push_back(nullptr);103 mgr->servers_.push_back(nullptr);
104 mgr->servers_.push_back(nullptr);104 mgr->servers_.push_back(nullptr);
105 105 
@@ -108,4 +108,4 @@ TEST_F(HttpServerManagerCoverageTest, DestructorCallsStopSafely)
108 SUCCEED();108 SUCCEED();
109}109}
110 110 
111-} // namespace111+} // namespace
@@ -0,0 +1,15 @@
1+__pycache__/
2+*.py[cod]
3+ 
4+.venv/
5+.pytest_cache/
6+.mypy_cache/
7+.ruff_cache/
8+.a4p/
9+ 
10+.coverage
11+htmlcov/
12+ 
13+build/
14+dist/
15+*.egg-info/
@@ -0,0 +1,245 @@
1+# A4P 协议
2+ 
3+本文定义 A4P 的角色、授权对象、流程和安全验证规则。安装与运行见 [README.md](README.md),Python SDK 实现边界见 [A4P_SDK_DESIGN.md](A4P_SDK_DESIGN.md)。
4+ 
5+## 1. 协议模型
6+ 
7+A4P 在 Agent 执行敏感操作前建立用户授权边界:
8+ 
9+- **Operation Authorization**:一次批准一个精确的 `action` + `params`,成功 complete 后消费 pending。
10+- **Intent Authorization**:一次批准一组 `action` 和参数约束,成功 complete 后签发可复用的 intent token。
11+ 
12+## 2. 协议角色
13+ 
14+### Agent
15+ 
16+Agent 发起工具调用,并编排 Intent 授权流程。它同时负责在各组件之间转发授权消息。
17+ 
18+### A4P Server
19+ 
20+A4P Server 是统一的授权服务。它生成 Mandate,验证用户批准,并根据授权类型完成一次性 Operation 授权或签发/验证 Intent Token。
21+ 
22+### User Authorizer
23+ 
24+User Authorizer 是用户设备上的本地授权组件。它验证 A4P Server 签署的 Mandate,向用户展示授权内容,并在用户同意后完成本地签名。
25+ 
26+### Tool Server / MCP Server
27+ 
28+Tool Server 执行实际业务操作。Operation 模式下,它根据当前调用申请并完成授权;Intent 模式下,它在每次执行前请求 A4P Server 验证 Token。只有 A4P Server 返回授权有效时,Tool Server 才执行业务。
29+ 
30+## 3. 操作授权(Operation Authorization)
31+ 
32+操作授权使用精确操作对象:
33+ 
34+```json
35+{"action":"delete_note","params":{"note_id":"note-1"}}
36+```
37+ 
38+### 流程
39+ 
40+```mermaid
41+sequenceDiagram
42+ participant Agent
43+ participant Tool as Tool Server
44+ participant A4P as A4P Server
45+ participant User as Local User Authorizer
46+ 
47+ Agent->>Tool: action(params)
48+ Tool->>A4P: prepare(agentId, userId, operation)
49+ A4P->>A4P: 创建 mandate 并签名
50+ A4P->>A4P: 当前 signature method 生成 signingOptions
51+ A4P-->>Tool: mandate + signingOptions
52+ Tool-->>Agent: authorization_required + mandate + signingOptions
53+ Agent->>User: 转发 mandate + signingOptions
54+ User->>User: 验 Server 签名和有效期,重算 challenge
55+ User->>User: 展示已验证内容,用户批准并调用认证器
56+ User-->>Agent: signedMandate 或拒绝
57+ Agent->>Tool: 重试 action(params) + signedMandate
58+ Tool->>Tool: 从当前请求重新构造 operation
59+ Tool->>A4P: complete(signedMandate, operation)
60+ A4P->>A4P: 按 operationId 路由、严格比对并消费 pending
61+ A4P-->>Tool: approved + operationId
62+ Tool->>Tool: 以 operationId 幂等执行业务
63+ Tool-->>Agent: 业务结果
64+```
65+ 
66+Prepare 请求包含 `agentId`、`userId`、`operation`,以及可选的 `validitySeconds`、`agentPublicKey` 和外部 `metadata`。响应一次返回:
67+ 
68+```json
69+{
70+ "mandate": {
71+ "type": "a4p/v1/operation-mandate",
72+ "operationId": "op_<32-byte-random>",
73+ "server": "local://a4p",
74+ "subject": {"type": "agent", "id": "agent:demo-agent"},
75+ "operation": {"action": "delete_note", "params": {"note_id": "note-1"}},
76+ "validTime": {"until": "2026-07-22T04:00:00Z"},
77+ "userAuthorization": {
78+ "required": true,
79+ "signatureMethod": "webauthn",
80+ "methodPolicy": {"userVerification": "required"}
81+ },
82+ "displayText": "授权执行 delete_note(note_id=\"note-1\")(有效期至 ...)",
83+ "signatures": {
84+ "server": {"alg": "EdDSA", "keyId": "server#operation-mandate-k1", "signature": "..."},
85+ "user": {}
86+ }
87+ },
88+ "signingOptions": {
89+ "signatureMethod": "webauthn",
90+ "methodOptions": {
91+ "challenge": "...",
92+ "rpId": "localhost",
93+ "allowCredentials": [{"id": "...", "type": "public-key"}],
94+ "userVerification": "required"
95+ }
96+ }
97+}
98+```
99+ 
100+Complete 请求为 `{"signedMandate": {...}, "operation": {...}}`。
101+ 
102+A4P Server 从 submitted mandate 提取 `operationId` 用于 pending 路由,然后必须验证:当前 operation 等于 prepare operation;submitted mandate 等于 pending 中的 Server-signed mandate,仅允许新增 `signatures.user`;用户签名、Server 签名和有效期均合法。成功后先消费 pending,再返回 `operationId`。业务系统仍须用该 ID 实现持久化幂等。
103+ 
104+## 4. 意图授权(Intent Authorization)
105+ 
106+Intent 使用 action 白名单、参数约束和可选执行策略:
107+ 
108+```json
109+{
110+ "actions": [
111+ {"name": "delete_note", "params": {"note_id": "note-*"}, "allowExtraParams": false}
112+ ],
113+ "executionPolicy": {"maxExecutions": 10}
114+}
115+```
116+ 
117+参数约束中,`"*"` 允许任意参数;`{}` 不允许参数;对象字段值可为精确值、`"*"` 或大小写敏感 glob。对象默认拒绝未声明字段,除非设置 `allowExtraParams: true`。多个同名 action 按 OR 匹配。
118+ 
119+### 流程
120+ 
121+```mermaid
122+sequenceDiagram
123+ participant Agent
124+ participant A4P as A4P Server
125+ participant User as Local User Authorizer
126+ participant Tool as Tool Server
127+ 
128+ Agent->>A4P: prepare(agentId, userId, intent)
129+ A4P->>A4P: 创建并签署 mandate
130+ A4P->>A4P: 当前 signature method 生成 signingOptions
131+ A4P-->>Agent: mandate + signingOptions
132+ Agent->>User: 转发 mandate + signingOptions
133+ User->>User: 验 Server 签名和有效期,重算并覆盖 challenge
134+ User->>User: 展示已验证内容,用户批准并调用认证器
135+ User-->>Agent: signedMandate 或拒绝
136+ Agent->>A4P: complete(signedMandate)
137+ A4P->>A4P: 按 mandateId 严格比对并消费 pending
138+ A4P-->>Agent: approved + intentToken
139+ 
140+ loop 每次工具调用
141+ Agent->>Tool: action(params) + intentToken
142+ Tool->>A4P: verify(token, expected action/params/identity)
143+ A4P->>A4P: 验签、匹配 scope、原子消费可选额度
144+ A4P-->>Tool: valid + matchedScope
145+ Tool-->>Agent: 业务结果或拒绝
146+ end
147+```
148+ 
149+Prepare 响应与 Operation 一样一次返回 `mandate + signingOptions`。Intent mandate 使用高熵 `mandateId`,完整 `intent`、有效期、用户授权策略和最终 `displayText` 都进入 Server 签名。
150+ 
151+Complete 请求仅为 `{"signedMandate": {...}}`。
152+ 
153+成功 complete 后签发的 token 通过 `mandateId` 引用来源授权,并复制 subject、user、intent、有效期和执行策略。Tool Server 提交 token 及当前 `action + params`;A4P Server 验证 token 签名、有效期、身份绑定和范围。若存在 `maxExecutions`,所有无状态检查成功后必须原子消费一次额度;存储不可用时 fail closed。
154+ 
155+## 5. 签名与 Challenge 规范
156+ 
157+A4P 的授权证明分为两层:
158+ 
159+- **Server 签名**:A4P Server 使用 Ed25519 签署 Mandate,证明其来源并防止内容被篡改。
160+- **用户确认**:证明用户批准了这份 Mandate,可使用 WebAuthn、Ed25519,或在明确配置后不使用加密签名。
161+ 
162+### 5.1 Server 签名
163+ 
164+Server 签名覆盖 Mandate 的全部授权内容,包括:
165+ 
166+- Mandate 类型和 `mandateId` / `operationId`;
167+- Server、Agent、完整 Intent 或 Operation;
168+- 有效期和用户签名策略;
169+- 最终展示给用户的 `displayText`。
170+ 
171+签名前,JSON 必须先规范化:对象键按字典序排列、移除无意义空白、使用 UTF-8,并拒绝 `NaN` 和无穷值。`signatures` 不进入 Server 签名输入。
172+ 
173+### 5.2 用户确认方式
174+ 
175+| 方式 | 用户设备上的操作 | A4P Server 的验证 |
176+| --- | --- | --- |
177+| WebAuthn | 使用 WebAuthn 签名载体完成用户验证并产生 assertion。 | 验证 challenge、RP ID、origin、credential 归属、用户验证和签名。 |
178+| Ed25519 | 使用调用方管理的 Ed25519 私钥签署 canonical payload。 | 按 `credentialId` 读取已注册的 OKP JWK 并验签。 |
179+| 无需加密签名 | `signatures.user` 保持为空。 | 仅在 Server 显式配置 `require_user_signature=false` 时接受。 |
180+ 
181+无论采用哪种方式,User Authorizer 都必须先验证 Server 签名,再向用户展示授权内容。无需加密签名只表示没有用户私钥证明,不会跳过 Server 签名或 Mandate 校验。
182+ 
183+### 5.3 WebAuthn Challenge
184+ 
185+当使用 WebAuthn 作为签名方式时,签名的对象是一个 Challenge,即 Server-signed Mandate 的 SHA-256 摘要:
186+ 
187+```text
188+webauthnChallenge = SHA256(
189+ UTF8(canonical_json({
190+ "scope": "a4p/v1/user-authorization",
191+ "mandate": serverSignedMandateWithoutUserSignature
192+ }))
193+)
194+```
195+ 
196+其中 `serverSignedMandateWithoutUserSignature` 包含完整 Mandate 和 `signatures.server`,但不包含 `signatures.user`。
197+ 
198+这样可以保证:
199+ 
200+- 修改授权内容、展示文本、授权 ID 或 Server 签名,challenge 都会改变;
201+- 用户签名不参与自身 challenge 的计算,避免循环依赖。
202+ 
203+SHA-256 的原始 32 字节直接交给 WebAuthn。通过 JSON 传递时,使用无填充 base64url 编码。
204+ 
205+### 5.4 验证职责
206+ 
207+User Authorizer 在用户确认前:
208+ 
209+1. 使用本地信任公钥验证 Server 签名;
210+2. 检查 Mandate 有效期和签名策略;
211+3. 从 Mandate 派生 challenge,并写入 WebAuthn options;
212+4. 展示已验证的内容,用户同意后才调用认证器。
213+ 
214+A4P Server 在 complete 时从 pending Mandate 重新派生同一个 challenge,并用它验证 WebAuthn assertion。Ed25519 对同一 canonical JSON 直接签名。
215+ 
216+### 5.5 签名载体与凭据注册
217+ 
218+一个 `A4PServer` 实例只配置一个 `A4PUserSignatureMethod`,当前内置 `ed25519` 和 `webauthn` 两种签名方法。Mandate 使用 `signatureMethod` 和 `methodPolicy`,用户签名统一使用:
219+ 
220+```json
221+{
222+ "signatureMethod": "ed25519",
223+ "credentialId": "cred_xxx",
224+ "proof": {"alg": "EdDSA", "signature": "..."}
225+}
226+```
227+ 
228+凭据注册时,Ed25519 使用一次注册接口提交 `userId + OKP JWK + metadata`;Server 生成随机 credential ID,同用户同公钥幂等,跨用户冲突返回 `CREDENTIAL_KEY_CONFLICT`。WebAuthn 保留 options/verify 两阶段注册。注册接口的认证、登录态、CSRF 和防滥用应由额外的部署层负责。
229+ 
230+## 6. HTTP 端点
231+ 
232+所有端点使用 JSON `POST`:
233+ 
234+| 端点 | 调用方 | 作用 |
235+| --- | --- | --- |
236+| `/a4p/v1/operation-authorizations/prepare` | Tool Server | 创建 Operation pending,返回 mandate 和 signing options。 |
237+| `/a4p/v1/operation-authorizations/complete` | Tool Server | 验证并消费 Operation pending。 |
238+| `/a4p/v1/intent-authorizations/prepare` | Agent | 创建 Intent pending,返回 mandate 和 signing options。 |
239+| `/a4p/v1/intent-authorizations/complete` | Agent | 验证并消费 Intent pending,签发 token。 |
240+| `/a4p/v1/intent-tokens/verify` | Tool Server | 验证 token 与当前调用。 |
241+| `/a4p/v1/user-credentials/ed25519/register` | 凭据注册客户端 | 一次注册 Ed25519 OKP JWK。 |
242+| `/a4p/v1/user-credentials/webauthn/register/options` | 凭据注册客户端 | 获取注册 options 并转发给 User Authorizer。 |
243+| `/a4p/v1/user-credentials/webauthn/register/verify` | 凭据注册客户端 | 转发 registration credential,由 Server 验证并保存。 |
244+ 
245+调用与当前实例载体不匹配的注册接口返回 HTTP 409、`SIGNATURE_METHOD_NOT_ENABLED`。当前用户没有已注册凭据时,prepare 返回 `USER_CREDENTIAL_NOT_REGISTERED` 且不创建 pending。JSON credential store 使用 `schemaVersion: 2`。
@@ -0,0 +1,177 @@
1+# A4P Python SDK
2+ 
3+## 摘要
4+ 
5+A4P(Agentic Authentication, Authorization, and Audit Protocol)是一套面向 AI Agent 的授权协议,具有授权细粒度、可追溯、抗篡改的安全特性。
6+ 
7+本仓库是 A4P 协议的 Python SDK,用于在 Agent 执行敏感操作前获取用户授权,并通过可验证的 mandate(授权对象)和 token(令牌)传递授权范围。
8+ 
9+当前版本:`0.2.0`
10+ 
11+## 主要特性
12+ 
13+- 两类授权模型
14+ - 操作授权(Operation Mandate)精确授权一次具体操作及参数。
15+ - 意图授权(Intent Mandate/Token)授权一组可复用的 action 范围。
16+- 清晰的角色分工
17+ - Agent 发起授权并负责消息转发,不参与授权安全判断。
18+ - A4P Server 创建并验证 Mandate 和 Token,维护服务端授权状态。
19+ - User Authorizer 运行在用户设备本地,验证授权内容并收集用户确认。
20+ - Tool Server 保护实际业务操作,只在 A4P 授权验证通过后执行工具调用。
21+- 可验证的授权链路
22+ - A4P Server 使用 Ed25519 签署 Mandate 和 Intent Token,保护授权内容及授权范围不被篡改。
23+ - 本地 User Authorizer 使用预置信任公钥验证 Mandate 的 Server 签名,只向用户展示经过验证的授权内容。
24+ - 使用 WebAuthn/passkey 时,User Authorizer 从经过验证的 Server-signed Mandate 派生 challenge,将用户验证和设备签名绑定到本次授权内容。
25+- 细粒度范围与额度控制
26+ - 支持参数精确匹配、通配符和额外参数控制。
27+ - 支持最大执行次数,并通过 SQLite 持久化、原子消费执行额度。
28+- 可插拔的用户签名载体
29+ - 每个 A4P Server 实例显式配置一个 signature method,内置 `ed25519` 和 `webauthn`。
30+ - 通用 credential registry 与方法专属注册解耦;Ed25519 一次注册,WebAuthn 两阶段注册。
31+- 轻量集成方式
32+ - Intent 和 Operation 统一采用 prepare/complete 两阶段接口,支持授权服务与用户确认异步完成。
33+ - Operation 授权由受保护的 Tool Server 发起和完成;Intent 授权由 Agent 发起,授权结果在后续工具调用中验证。
34+ - SDK 内置异步 HTTP 客户端、轻量 HTTP 服务端和可定制的授权展示文本,便于嵌入现有 Agent 与工具服务。
35+ 
36+ 
37+## 快速开始
38+ 
39+环境要求:Python 3.10 或更高版本。安装命令:
40+ 
41+```bash
42+uv sync
43+```
44+ 
45+| 运行环境 | 可运行示例 | 环境与交互要求 |
46+| --- | --- | --- |
47+| Windows | Ed25519 非交互示例;WebAuthn 笔记 demo;无 UI 冒烟测试 | WebAuthn 笔记 demo 需要配置 Windows Hello,并使用支持 WebAuthn 的浏览器(Chrome, Edge 等均支持) |
48+| macOS | Ed25519 非交互示例;WebAuthn 笔记 demo;无 UI 冒烟测试 | WebAuthn 笔记 demo 需要浏览器能够调用 passkey 或兼容的安全密钥 |
49+| Linux | Ed25519 非交互示例;无 UI 冒烟测试 | 示例不需要浏览器;由于无浏览器,暂时无法运行交互式 WebAuthn demo |
50+ 
51+三个示例的用途如下:
52+ 
53+- `examples/ed25519_authorization.py`:最小 Ed25519 注册与 operation 授权全链路,
54+ 只需基础依赖;
55+- `examples/note_mcp_a4p`:带浏览器确认的 WebAuthn/passkey 桌面 demo,需要安装
56+ `demo` 额外依赖;
57+- `examples/note_mcp_a4p/smoke_test.py`:使用测试签名器覆盖笔记 MCP 的
58+ prepare/complete 流程,不启动 Web UI,需要安装 `demo` 额外依赖。
59+ 
60+ 
61+### 最小 Ed25519 注册与授权全链路示例
62+ 
63+运行最小 Ed25519 注册与授权全链路:
64+ 
65+```bash
66+uv run python examples/ed25519_authorization.py
67+```
68+ 
69+这是一条非交互链路,不需要桌面环境、浏览器或硬件认证器。
70+脚本会在本机回环地址启动临时 A4P HTTP Server,生成临时
71+Ed25519 私钥,依次完成凭据注册、operation mandate 准备、用户签名和授权完成,
72+然后输出类似:
73+ 
74+```json
75+{
76+ "credentialId": "cred_xxx",
77+ "approved": true,
78+ "operationId": "op_xxx"
79+}
80+```
81+ 
82+进程执行完毕后会停止临时 HTTP Server。示例使用内存凭据存储且只生成临时私钥;
83+生产私钥应由调用方自己的密钥系统管理,SDK 不负责持久化或解锁。
84+ 
85+ 
86+### 笔记 MCP 服务器示例(基于 WebAuthn 的签名)
87+ 
88+在 Windows 上运行本示例前,请进入“设置 > 账户 > 登录选项”,至少配置一种
89+Windows Hello 登录方式(PIN、面部识别或指纹识别)。浏览器认证器会使用该登录方式
90+在调用用户私钥签名前确认用户身份。
91+ 
92+仅有终端的 Linux 环境无法完成需要用户确认的浏览器 WebAuthn 签名过程。
93+ 
94+运行 `examples/note_mcp_a4p` 中的笔记 MCP 服务器示例前,需要额外安装 demo 依赖:
95+ 
96+```bash
97+uv sync --extra demo
98+```
99+ 
100+运行示例需要三个终端。
101+ 
102+终端 1,启动 A4P Server:
103+ 
104+```bash
105+uv run python examples/note_mcp_a4p/run_authorization_server.py
106+```
107+ 
108+终端 2,启动基于 WebAuthn 的 User Authorizer:
109+ 
110+```bash
111+uv run python examples/note_mcp_a4p/run_user_authorizer.py
112+```
113+ 
114+首次运行时,在终端 3 显式注册 WebAuthn/passkey 凭据:
115+ 
116+```bash
117+uv run python examples/note_mcp_a4p/register_browser_key.py
118+```
119+ 
120+脚本从 A4P Server 获取 registration options,交给本地 User Authorizer 调用浏览器认证器生成公钥/私钥,再把公钥返回 A4P Server 保存。
121+ 
122+终端 3,启动模拟 Agent(意图授权模式):
123+ 
124+```bash
125+uv run python examples/note_mcp_a4p/agent_simulator.py --mode intent
126+```
127+ 
128+模拟的 Agent 会申请一个允许删除笔记的 Intent Mandate。请在浏览器页面审核其 action 和参数范围;批准后,A4P Server 会签发可验证的 Intent Token。Agent 随后复用该 token 删除已列出的多条笔记,每次执行前都会校验授权范围并原子消费执行额度。
129+ 
130+如需体验针对单次具体操作的精确授权,可将启动参数改为 `--mode operation`。
131+ 
132+> 示例和内置默认密钥仅用于本地开发。生产环境必须使用 HTTPS、匹配的 WebAuthn RP ID/origin、独立签名密钥、受保护的本地信任配置。
133+ 
134+### 笔记 MCP 服务器无 UI 冒烟测试
135+ 
136+该示例用于快速验证笔记 MCP Server 与 A4P 的 prepare/complete 集成,无需启动浏览器
137+Web UI,不需要 passkey、硬件认证器或人工确认。脚本使用临时 Ed25519 测试凭据和
138+本机 A4P HTTP Server,依次验证:
139+ 
140+- Operation Mandate 可以授权删除指定笔记;
141+- 当前操作与已签名 mandate 参数不一致时拒绝删除;
142+- 一个 Intent Token 可以按授权范围删除多条笔记;
143+- Intent Token 缺少参数、包含额外参数或 action 不匹配时验证失败;
144+- 未完成授权前不会执行删除。
145+ 
146+先安装 demo 额外依赖:
147+ 
148+```bash
149+uv sync --extra demo
150+```
151+ 
152+然后在仓库根目录运行:
153+ 
154+```bash
155+uv run python examples/note_mcp_a4p/smoke_test.py
156+```
157+ 
158+脚本会在 `127.0.0.1` 的 `18960` 至 `18962` 端口依次启动并停止临时服务,因此不依赖
159+外部 A4P Server,但运行时这些端口需要可用。全部检查通过时,最后一行输出:
160+ 
161+```text
162+note_mcp_a4p smoke tests passed
163+```
164+ 
165+该示例可在 Windows、macOS、Linux 环境中运行。
166+ 
167+### 运行测试
168+ 
169+```bash
170+uv run python -m pytest -q
171+```
172+ 
173+## 更多文档
174+ 
175+- [A4P 协议说明](A4P_PROTOCOL.md)
176+- [SDK 设计说明](A4P_SDK_DESIGN.md)
177+- [A4P + MCP 示例](examples/note_mcp_a4p/README.md)
@@ -0,0 +1,102 @@
1+"""Run a complete one-request Ed25519 enrollment and authorization flow."""
2+ 
3+from __future__ import annotations
4+ 
5+import asyncio
6+import json
7+import sys
8+ 
9+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
10+ 
11+from a4p import (
12+ A4PClient,
13+ A4PServer,
14+ InMemoryCredentialStore,
15+ sign_user_mandate_with_signer,
16+)
17+from a4p.user_signature.ed25519 import (
18+ Ed25519UserSigner,
19+ RegisteredEd25519Method,
20+ ed25519_public_jwk,
21+)
22+from a4p.http_server import A4PHTTPServer
23+ 
24+ 
25+async def main() -> int:
26+ signature_method = RegisteredEd25519Method(InMemoryCredentialStore())
27+ http_server = A4PHTTPServer(
28+ A4PServer(
29+ server_id="local://ed25519-example",
30+ user_signature_method=signature_method,
31+ ),
32+ host="127.0.0.1",
33+ port=0,
34+ )
35+ exit_code = 0
36+ try:
37+ await http_server.start()
38+ client = A4PClient(base_url=f"http://127.0.0.1:{http_server.port}")
39+ 
40+ # The caller owns this private key. The SDK neither persists nor unlocks it.
41+ private_key = Ed25519PrivateKey.generate()
42+ registration = await client.register_ed25519_credential(
43+ {
44+ "userId": "user-1",
45+ "publicKey": ed25519_public_jwk(private_key),
46+ "metadata": {"label": "temporary CLI example key"},
47+ }
48+ )
49+ signer = Ed25519UserSigner(
50+ credential_id=registration["credential"]["credentialId"],
51+ private_key=private_key,
52+ )
53+ 
54+ operation = {
55+ "action": "delete_note",
56+ "params": {"note_id": "note-1"},
57+ }
58+ prepared = await client.prepare_operation_authorization(
59+ {
60+ "agentId": "agent-1",
61+ "userId": "user-1",
62+ "operation": operation,
63+ "validitySeconds": 60,
64+ }
65+ )
66+ if prepared.mandate is None:
67+ raise RuntimeError(prepared.rejectReason or "prepare failed")
68+ signed_mandate = sign_user_mandate_with_signer(
69+ prepared.mandate,
70+ user_signer=signer,
71+ )
72+ completed = await client.complete_operation_authorization(
73+ {
74+ "signedMandate": signed_mandate,
75+ "operation": operation,
76+ }
77+ )
78+ print(
79+ json.dumps(
80+ {
81+ "credentialId": signer.credential_id,
82+ "approved": completed.approved,
83+ "operationId": completed.operationId,
84+ },
85+ ensure_ascii=False,
86+ indent=2,
87+ )
88+ )
89+ except (OSError, RuntimeError, ValueError) as exc:
90+ print(f"Ed25519 authorization example failed: {exc}", file=sys.stderr)
91+ exit_code = 1
92+ finally:
93+ try:
94+ await http_server.stop()
95+ except (OSError, RuntimeError) as exc:
96+ print(f"Failed to stop the local A4P server: {exc}", file=sys.stderr)
97+ exit_code = 1
98+ return exit_code
99+ 
100+ 
101+if __name__ == "__main__":
102+ raise SystemExit(asyncio.run(main()))
@@ -0,0 +1,251 @@
1+# A4P + MCP 笔记管理示例
2+ 
3+本示例展示了一个受 A4P 授权保护的笔记管理 MCP Server。
4+ 
5+MCP Server 提供四个工具:
6+ 
7+- `list_notes`
8+- `get_note`
9+- `add_note`
10+- `delete_note`
11+ 
12+`delete_note` 被视为高风险操作,只有通过以下任一授权后才会执行删除:
13+ 
14+- 精确授权本次笔记删除操作的 A4P Operation Mandate;或
15+- 允许删除笔记的 A4P Intent Token。
16+ 
17+## 示例组件
18+ 
19+| 组件 | 文件 | 职责 |
20+| --- | --- | --- |
21+| A4P Server | `run_authorization_server.py` | 生成和验证 Mandate、管理 WebAuthn credential、签发并验证 Intent Token |
22+| Note MCP Server | `note_mcp_server.py` | 提供笔记工具;在执行 `delete_note` 前调用 A4P |
23+| User Authorizer | `run_user_authorizer.py` | 本地验证 Server-signed Mandate、展示授权内容并调用浏览器 WebAuthn |
24+| 凭据注册客户端 | `register_browser_key.py` | 在 A4P Server 与 User Authorizer 之间转发一次 WebAuthn 注册流程 |
25+| 模拟 Agent | `agent_simulator.py` | 调用 MCP 工具并转发授权请求与用户签名结果 |
26+ 
27+授权组件之间的主要关系是:
28+ 
29+```text
30+Agent <-> Note MCP Server <-> A4P Server
31+ |
32+ +---- mandate + signingOptions ----> User Authorizer
33+ <----------- signedMandate ---------+
34+```
35+ 
36+User Authorizer 不直接连接 A4P Server。Agent 转发给它的授权请求只包含
37+`mandate` 和 `signingOptions`;授权展示以 Server-signed Mandate 中的
38+`displayText` 和结构化授权字段为准。
39+ 
40+## 安装
41+ 
42+在 A4P SDK 根目录运行:
43+ 
44+```bash
45+uv sync --locked --extra demo
46+```
47+ 
48+## 运行前约定
49+ 
50+示例默认使用以下地址:
51+ 
52+| 配置 | 默认值 | 覆盖方式 |
53+| --- | --- | --- |
54+| A4P Server | `http://127.0.0.1:8961` | `A4P_SERVER_BASE_URL` |
55+| User Authorizer | `http://localhost:8970` | `A4P_USER_AUTHORIZER_BASE_URL` |
56+| Intent Token 用量数据库 | `.a4p/intent_token_usage.sqlite3` | `A4P_USAGE_DB_PATH` |
57+ 
58+WebAuthn RP ID 为 `localhost`,预期 origin 为 `http://localhost:8970`。如果修改
59+User Authorizer 的地址,必须同步修改 A4P Server 中的 `expected_origin`;如果连
60+hostname 也发生变化,还必须同步修改 RP ID。
61+ 
62+### Windows 环境
63+ 
64+在 Windows 上运行本示例前,请进入“设置 > 账户 > 登录选项”,至少配置一种
65+Windows Hello 登录方式(PIN、面部识别或指纹识别)。浏览器认证器会使用该登录方式在调用用户私钥签名前确认用户身份。
66+ 
67+### Linux 环境
68+ 
69+仅有终端的 Linux 环境无法完成需要用户确认的浏览器 WebAuthn 签名过程,可在仓库根目录改为运行 Ed25519 非交互示例或 MCP 笔记服务器的无 UI 冒烟测试:
70+ 
71+```bash
72+uv run python examples/ed25519_authorization.py
73+uv run python examples/note_mcp_a4p/smoke_test.py
74+```
75+ 
76+## 启动 A4P Server 和 User Authorizer
77+ 
78+终端 1,启动 A4P Server:
79+ 
80+```bash
81+uv run python examples/note_mcp_a4p/run_authorization_server.py
82+```
83+ 
84+该示例从 `a4p.user_signature.webauthn` 导入并显式配置
85+`WebAuthnSignatureMethod`。一个 Server 实例只启用一种用户签名方法,不会同时
86+接受 WebAuthn 和 Ed25519。
87+ 
88+Server 启动时还会把公开验签配置写入 `.a4p/trusted_server_keys.json`,供本地 User Authorizer 固定信任当前 `serverId + keyId`。该文件不包含私钥。
89+ 
90+未配置 `INTENT_SERVER_ED25519_PRIVATE_KEY` 和
91+`OPERATION_SERVER_ED25519_PRIVATE_KEY` 时,示例使用 SDK 内置的开发签名密钥并输出
92+高风险告警。内置密钥只能用于本地演示,不能用于生产部署。
93+ 
94+终端 2,启动 A4P User Authorizer:
95+ 
96+```bash
97+uv run python examples/note_mcp_a4p/run_user_authorizer.py
98+```
99+ 
100+打开终端输出的本地 Web UI 地址,通常为:
101+ 
102+```text
103+http://localhost:8970/
104+```
105+ 
106+User Authorizer 不连接 A4P Server。它只接收 Agent 转发的 mandate 和 WebAuthn options,并在打开浏览器前使用 `.a4p/trusted_server_keys.json` 验证 Server 签名、challenge 内容绑定和 options 一致性。
107+ 
108+浏览器页面模板、样式和 WebAuthn JavaScript 位于 `user_authorizer_assets/`,由本地 User Authorizer 通过固定资源白名单提供;Python service 不再内嵌前端代码。
109+ 
110+如果只希望在终端输出 URL,而不自动打开浏览器,可运行:
111+ 
112+```bash
113+uv run python examples/note_mcp_a4p/run_user_authorizer.py --no-open-browser
114+```
115+ 
116+## 注册浏览器凭据
117+ 
118+演示注册的浏览器凭据由 A4P Server 保存到:
119+ 
120+```text
121+.a4p/webauthn_credentials.json
122+```
123+ 
124+Intent Token 的执行次数通过 SQLite 原子持久化到:
125+ 
126+```text
127+.a4p/intent_token_usage.sqlite3
128+```
129+ 
130+可通过 `A4P_USAGE_DB_PATH` 指定其他 SQLite 文件路径。
131+ 
132+Web UI 使用 `http://localhost:8970`,因为浏览器会将 localhost 视为可用于 WebAuthn 开发的安全上下文。生产部署必须使用 HTTPS,并配置匹配的 RP ID 和 origin。授权期间由 Agent 转发 mandate、signing options 和 assertion;注册期间由独立 enrollment 脚本转发 registration options 和公开 credential。私钥操作始终留在浏览器认证器中。注册 options 返回的 `registrationRequestId` 会随 credential 一起回传,确保同一用户的并发注册 challenge 彼此隔离。
133+ 
134+首次运行时,在独立终端显式执行 enrollment:
135+ 
136+```bash
137+uv run python examples/note_mcp_a4p/register_browser_key.py
138+```
139+ 
140+该命令仅演示转发结构。生产环境必须使用强登录态保护凭据注册接口,
141+并处理 CSRF、防滥用和审计;脚本中配置的 `userId` 本身不构成身份证明。
142+ 
143+## 使用单次操作授权运行
144+ 
145+确保 A4P Server、User Authorizer 已启动且浏览器凭据已注册,然后启动模拟 Agent:
146+ 
147+```bash
148+uv run python examples/note_mcp_a4p/agent_simulator.py --mode operation
149+```
150+ 
151+模拟 Agent 会先列出全部笔记,然后首次调用 `delete_note`。MCP Server 根据当前 `note_id` 生成 operation,向 A4P Server prepare,再返回 `authorization_required`、mandate 和 signing options。Agent 取得 User Authorizer 签名后,以 `operation_authorization: {signedMandate}` 重新调用 `delete_note`。MCP Server 会再次从当前 `note_id` 生成 operation 并调用 A4P complete,验证通过后才删除笔记。
152+ 
153+Prepare 会一次返回 Server-signed mandate 和 assertion options。Agent 将二者转发到本地;User Authorizer 先验 Server 签名和有效期,再从 mandate 重算并覆盖 WebAuthn challenge。本地校验失败时不会打开批准页面或调用认证器。
154+ 
155+Agent 转发给 User Authorizer 的请求结构为:
156+ 
157+```json
158+{
159+ "mandate": {},
160+ "signingOptions": {
161+ "signatureMethod": "webauthn",
162+ "methodOptions": {
163+ "allowCredentials": [],
164+ "challenge": "...",
165+ "rpId": "localhost",
166+ "timeout": 60000,
167+ "userVerification": "required"
168+ }
169+ }
170+}
171+```
172+ 
173+Mandate 内签名保护的 `userAuthorization.methodPolicy.userVerification` 是安全策略,
174+`signingOptions.methodOptions.userVerification` 是传给浏览器 WebAuthn API 的执行参数。
175+User Authorizer 会重新派生 challenge,并强制 `userVerification=required`,不会直接信任
176+Agent 转发的动态 options。
177+ 
178+Operation 授权精确对应一次工具调用:
179+ 
180+```json
181+{
182+ "operation": {
183+ "action": "delete_note",
184+ "params": {
185+ "note_id": "note-1"
186+ }
187+ }
188+}
189+```
190+ 
191+Complete 成功后返回的关键字段为:
192+ 
193+```json
194+{
195+ "approved": true,
196+ "operationId": "op_xxx",
197+ "verificationResult": {
198+ "valid": true
199+ }
200+}
201+```
202+ 
203+成功结果中的 `operationId` 是业务系统的幂等键。本示例只在进程内记录成功结果;
204+生产业务系统必须在执行副作用时以 `operationId` 实现持久化幂等。
205+ 
206+## 使用 Intent 授权运行
207+ 
208+保持 A4P Server 和 User Authorizer 运行,以 Intent 模式启动模拟 Agent:
209+ 
210+```bash
211+uv run python examples/note_mcp_a4p/agent_simulator.py --mode intent
212+```
213+ 
214+模拟 Agent 会申请一个允许删除笔记的 A4P Intent Token,将 mandate 交给 User Authorizer 获取用户签名,再通过 A4P Server 完成授权。取得 token 后,Agent 会复用它删除已列出的笔记。
215+ 
216+Intent 授权使用可复用的 action 参数约束:
217+ 
218+```json
219+{
220+ "intent": {
221+ "actions": [
222+ {
223+ "name": "delete_note",
224+ "params": {
225+ "note_id": "*"
226+ }
227+ }
228+ ]
229+ }
230+}
231+```
232+ 
233+Intent complete 成功后返回 `approved + intentToken + verificationResult`。Intent Token
234+自身包含受 Server 签名保护的 `issuedAt` 和 `expireAt`;后续每次删除操作由 MCP
235+Server 调用 A4P Server 验证 token、agent、user、action 和 params。
236+ 
237+## 冒烟测试
238+ 
239+冒烟测试在 prepare 和 complete 之间使用测试签名器批准 mandate,不需要启动 Web UI:
240+ 
241+```bash
242+uv run python examples/note_mcp_a4p/smoke_test.py
243+```
244+ 
245+测试会验证:
246+ 
247+- Operation challenge 经用户签名后可以删除一条笔记;
248+- 二次请求的 operation 参数与 challenge 不一致时拒绝删除;
249+- 一个 Intent Token 可以删除多条笔记;
250+- Intent Token 缺少参数、包含额外参数或 action 不一致时验证失败;
251+- 首次调用只返回 challenge,不执行删除。
@@ -0,0 +1,212 @@
1+"""Simulate an AI agent that deletes notes through MCP after A4P authorization."""
2+ 
3+from __future__ import annotations
4+ 
5+import argparse
6+import asyncio
7+import json
8+import os
9+import sys
10+import urllib.error
11+import urllib.request
12+from pathlib import Path
13+from typing import Any
14+ 
15+from a4p import A4PClient
16+from mcp import ClientSession, StdioServerParameters
17+from mcp.client.stdio import stdio_client
18+ 
19+ 
20+AGENT_ID = "demo-agent"
21+USER_ID = "demo-user"
22+PROJECT_ROOT = Path(__file__).resolve().parents[2]
23+SERVER_SCRIPT = Path(__file__).with_name("note_mcp_server.py")
24+USER_AUTHORIZER_BASE_URL = (os.getenv("A4P_USER_AUTHORIZER_BASE_URL") or "http://localhost:8970").rstrip("/")
25+ 
26+ 
27+def _server_env() -> dict[str, str]:
28+ env = dict(os.environ)
29+ src_path = str(PROJECT_ROOT / "src")
30+ existing = env.get("PYTHONPATH")
31+ env["PYTHONPATH"] = f"{src_path}{os.pathsep}{existing}" if existing else src_path
32+ return env
33+ 
34+ 
35+def _tool_payload(result: Any) -> Any:
36+ structured = getattr(result, "structuredContent", None)
37+ if structured is None:
38+ structured = getattr(result, "structured_content", None)
39+ if isinstance(structured, dict) and set(structured) == {"result"}:
40+ return structured["result"]
41+ if structured is not None:
42+ return structured
43+ 
44+ for content in getattr(result, "content", []) or []:
45+ text = getattr(content, "text", None)
46+ if not text:
47+ continue
48+ try:
49+ return json.loads(text)
50+ except json.JSONDecodeError:
51+ return text
52+ return None
53+ 
54+ 
55+async def _call_tool(session: ClientSession, name: str, arguments: dict[str, Any] | None = None) -> Any:
56+ result = await session.call_tool(name, arguments or {})
57+ return _tool_payload(result)
58+ 
59+ 
60+async def _request_user_signature(
61+ *,
62+ mandate: dict[str, Any],
63+ signing_options: dict[str, Any],
64+) -> dict[str, Any]:
65+ payload = {
66+ "mandate": mandate,
67+ "signingOptions": signing_options,
68+ }
69+ return await asyncio.to_thread(_post_user_authorizer_sync, "/authorize", payload)
70+ 
71+ 
72+def _post_user_authorizer_sync(path: str, payload: dict[str, Any]) -> dict[str, Any]:
73+ data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
74+ req = urllib.request.Request(
75+ f"{USER_AUTHORIZER_BASE_URL}{path}",
76+ data=data,
77+ headers={"Content-Type": "application/json", "Accept": "application/json"},
78+ method="POST",
79+ )
80+ try:
81+ with urllib.request.urlopen(req, timeout=300) as resp:
82+ raw = resp.read().decode("utf-8")
83+ except urllib.error.HTTPError as exc:
84+ raw = exc.read().decode("utf-8", errors="replace")
85+ raise RuntimeError(f"User Authorizer HTTP {exc.code}: {raw}") from exc
86+ except urllib.error.URLError as exc:
87+ raise RuntimeError(f"User Authorizer HTTP request failed: {exc}") from exc
88+ parsed = json.loads(raw) if raw else {}
89+ return parsed if isinstance(parsed, dict) else {}
90+ 
91+ 
92+async def _delete_with_operation(
93+ session: ClientSession,
94+ notes: list[dict[str, Any]],
95+) -> None:
96+ for note in notes:
97+ note_id = str(note["id"])
98+ print(f"\n[agent] requesting operation authorization for {note_id}")
99+ challenged = await _call_tool(session, "delete_note", {"note_id": note_id})
100+ authorization = challenged.get("authorization") if isinstance(challenged, dict) else None
101+ if not isinstance(authorization, dict) or not isinstance(authorization.get("mandate"), dict):
102+ print(f"[agent] operation challenge failed for {note_id}: {challenged}")
103+ continue
104+ user_auth = await _request_user_signature(
105+ mandate=authorization["mandate"],
106+ signing_options=(
107+ authorization.get("signingOptions")
108+ if isinstance(authorization.get("signingOptions"), dict)
109+ else {}
110+ ),
111+ )
112+ if not user_auth.get("approved") or not isinstance(user_auth.get("signedMandate"), dict):
113+ print(f"[agent] user authorization rejected for {note_id}: {user_auth.get('rejectReason')}")
114+ continue
115+ deleted = await _call_tool(
116+ session,
117+ "delete_note",
118+ {
119+ "note_id": note_id,
120+ "operation_authorization": {
121+ "signedMandate": user_auth["signedMandate"],
122+ },
123+ },
124+ )
125+ print(f"[agent] delete result: {json.dumps(deleted, ensure_ascii=False)}")
126+ 
127+ 
128+async def _delete_with_intent(session: ClientSession, a4p_client: A4PClient, notes: list[dict[str, Any]]) -> None:
129+ print("\n[agent] requesting one intent authorization for deleting notes")
130+ prepared = await a4p_client.prepare_intent_authorization(
131+ {
132+ "agentId": AGENT_ID,
133+ "userId": USER_ID,
134+ "intent": {
135+ "actions": [
136+ {
137+ "name": "delete_note",
138+ "params": {"note_id": "*"},
139+ }
140+ ],
141+ },
142+ "validitySeconds": 600,
143+ "metadata": {"reason": "The simulated agent wants to delete all listed notes."},
144+ }
145+ )
146+ if prepared.mandate is None:
147+ print(f"[agent] intent mandate rejected: {prepared.rejectReason}")
148+ return
149+ user_auth = await _request_user_signature(
150+ mandate=prepared.mandate,
151+ signing_options=prepared.signingOptions,
152+ )
153+ if not user_auth.get("approved") or not isinstance(user_auth.get("signedMandate"), dict):
154+ print(f"[agent] user intent authorization rejected: {user_auth.get('rejectReason')}")
155+ return
156+ auth = await a4p_client.complete_intent_authorization(
157+ {"signedMandate": user_auth["signedMandate"]}
158+ )
159+ if not auth.approved or auth.intentToken is None:
160+ print(f"[agent] intent authorization rejected: {auth.rejectReason}")
161+ return
162+ 
163+ for note in notes:
164+ note_id = str(note["id"])
165+ deleted = await _call_tool(
166+ session,
167+ "delete_note",
168+ {"note_id": note_id, "intent_token": auth.intentToken},
169+ )
170+ print(f"[agent] delete result for {note_id}: {json.dumps(deleted, ensure_ascii=False)}")
171+ 
172+ 
173+async def run(mode: str) -> None:
174+ a4p_client = A4PClient()
175+ server = StdioServerParameters(
176+ command=sys.executable,
177+ args=[str(SERVER_SCRIPT)],
178+ env=_server_env(),
179+ )
180+ async with stdio_client(server) as (read_stream, write_stream):
181+ async with ClientSession(read_stream, write_stream) as session:
182+ await session.initialize()
183+ 
184+ notes = await _call_tool(session, "list_notes")
185+ print(f"[agent] listed notes: {json.dumps(notes, ensure_ascii=False)}")
186+ if not notes:
187+ print("[agent] no notes to delete")
188+ return
189+ 
190+ if mode == "operation":
191+ await _delete_with_operation(session, notes)
192+ else:
193+ await _delete_with_intent(session, a4p_client, notes)
194+ 
195+ remaining = await _call_tool(session, "list_notes")
196+ print(f"\n[agent] remaining notes: {json.dumps(remaining, ensure_ascii=False)}")
197+ 
198+ 
199+def main() -> None:
200+ parser = argparse.ArgumentParser(description=__doc__)
201+ parser.add_argument(
202+ "--mode",
203+ choices=("operation", "intent"),
204+ default="operation",
205+ help="Authorization mode used before deleting notes.",
206+ )
207+ args = parser.parse_args()
208+ asyncio.run(run(args.mode))
209+ 
210+ 
211+if __name__ == "__main__":
212+ main()
@@ -0,0 +1,177 @@
1+"""A note-management MCP server protected by A4P authorization."""
2+ 
3+from __future__ import annotations
4+ 
5+from typing import Any
6+ 
7+from a4p import A4PClient
8+from mcp.server.fastmcp import FastMCP
9+ 
10+ 
11+AGENT_ID = "demo-agent"
12+USER_ID = "demo-user"
13+ 
14+mcp = FastMCP("A4P Note MCP Server")
15+ 
16+_notes: dict[str, dict[str, str]] = {
17+ "note-1": {
18+ "id": "note-1",
19+ "title": "Project checklist",
20+ "body": "Ship the A4P package layout and examples.",
21+ },
22+ "note-2": {
23+ "id": "note-2",
24+ "title": "Meeting notes",
25+ "body": "Deletion should require explicit user authorization.",
26+ },
27+ "note-3": {
28+ "id": "note-3",
29+ "title": "Draft",
30+ "body": "This note exists so the simulated agent has another target.",
31+ },
32+}
33+_next_note_id = 4
34+_operation_results: dict[str, dict[str, Any]] = {}
35+ 
36+ 
37+def _summary(note: dict[str, str]) -> dict[str, str]:
38+ return {"id": note["id"], "title": note["title"]}
39+ 
40+ 
41+def _delete_operation(note_id: str) -> dict[str, Any]:
42+ return {
43+ "action": "delete_note",
44+ "params": {"note_id": note_id},
45+ }
46+ 
47+ 
48+async def _authorize_delete(
49+ note_id: str,
50+ *,
51+ intent_token: dict[str, Any] | None,
52+) -> tuple[bool, str]:
53+ if intent_token is not None:
54+ response = await A4PClient().verify_intent_token(
55+ {
56+ "token": intent_token,
57+ "expected": {
58+ "action": "delete_note",
59+ "params": {"note_id": note_id},
60+ "agentId": f"agent:{AGENT_ID}",
61+ "userId": USER_ID,
62+ },
63+ }
64+ )
65+ return response.valid, response.reason or ""
66+ 
67+ return False, "delete_note requires A4P authorization"
68+ 
69+ 
70+@mcp.tool()
71+def list_notes() -> list[dict[str, str]]:
72+ """List note ids and titles."""
73+ return [_summary(note) for note in _notes.values()]
74+ 
75+ 
76+@mcp.tool()
77+def get_note(note_id: str) -> dict[str, Any]:
78+ """Return one note by id."""
79+ note = _notes.get(note_id)
80+ if note is None:
81+ return {"found": False, "error": f"note not found: {note_id}"}
82+ return {"found": True, "note": dict(note)}
83+ 
84+ 
85+@mcp.tool()
86+def add_note(title: str, body: str) -> dict[str, Any]:
87+ """Add a note and return the created entry."""
88+ global _next_note_id
89+ 
90+ note_id = f"note-{_next_note_id}"
91+ _next_note_id += 1
92+ note = {"id": note_id, "title": title, "body": body}
93+ _notes[note_id] = note
94+ return {"created": True, "note": dict(note)}
95+ 
96+ 
97+@mcp.tool()
98+async def delete_note(
99+ note_id: str,
100+ operation_authorization: dict[str, Any] | None = None,
101+ intent_token: dict[str, Any] | None = None,
102+) -> dict[str, Any]:
103+ """Delete a note after A4P authorization."""
104+ note = _notes.get(note_id)
105+ if note is None:
106+ return {"deleted": False, "error": f"note not found: {note_id}"}
107+ 
108+ operation_id: str | None = None
109+ if operation_authorization is not None:
110+ signed_mandate = operation_authorization.get("signedMandate")
111+ if not isinstance(signed_mandate, dict):
112+ return {
113+ "deleted": False,
114+ "error": "A4P authorization failed: signedMandate missing",
115+ "note": _summary(note),
116+ }
117+ completed = await A4PClient().complete_operation_authorization(
118+ {
119+ "signedMandate": signed_mandate,
120+ "operation": _delete_operation(note_id),
121+ }
122+ )
123+ authorized = completed.approved and completed.operationId is not None
124+ reason = completed.rejectReason or ""
125+ operation_id = completed.operationId
126+ elif intent_token is not None:
127+ authorized, reason = await _authorize_delete(note_id, intent_token=intent_token)
128+ else:
129+ challenge = await A4PClient().prepare_operation_authorization(
130+ {
131+ "agentId": AGENT_ID,
132+ "userId": USER_ID,
133+ "operation": _delete_operation(note_id),
134+ "validitySeconds": 300,
135+ "metadata": {"noteTitle": note["title"]},
136+ }
137+ )
138+ if challenge.mandate is None:
139+ return {
140+ "deleted": False,
141+ "error": f"A4P authorization preparation failed: {challenge.rejectReason}",
142+ "note": _summary(note),
143+ }
144+ return {
145+ "deleted": False,
146+ "status": "authorization_required",
147+ "authorization": {
148+ "mandate": challenge.mandate,
149+ "signingOptions": challenge.signingOptions,
150+ },
151+ "note": _summary(note),
152+ }
153+ 
154+ if not authorized:
155+ return {
156+ "deleted": False,
157+ "error": f"A4P authorization failed: {reason}",
158+ "note": _summary(note),
159+ }
160+ 
161+ if operation_id is not None and operation_id in _operation_results:
162+ return dict(_operation_results[operation_id])
163+ 
164+ deleted = _notes.pop(note_id)
165+ result = {
166+ "deleted": True,
167+ "note": _summary(deleted),
168+ "remaining": list_notes(),
169+ }
170+ if operation_id is not None:
171+ result["operationId"] = operation_id
172+ _operation_results[operation_id] = dict(result)
173+ return result
174+ 
175+ 
176+if __name__ == "__main__":
177+ mcp.run()
@@ -0,0 +1,77 @@
1+"""Register a browser WebAuthn credential for the local A4P demo."""
2+ 
3+from __future__ import annotations
4+ 
5+import asyncio
6+import json
7+import os
8+import urllib.error
9+import urllib.request
10+from typing import Any
11+ 
12+from a4p import A4PClient
13+ 
14+ 
15+USER_ID = "demo-user"
16+USER_AUTHORIZER_BASE_URL = (os.getenv("A4P_USER_AUTHORIZER_BASE_URL") or "http://localhost:8970").rstrip("/")
17+ 
18+ 
19+def _post_user_authorizer_sync(path: str, payload: dict[str, Any]) -> dict[str, Any]:
20+ data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
21+ request = urllib.request.Request(
22+ f"{USER_AUTHORIZER_BASE_URL}{path}",
23+ data=data,
24+ headers={"Content-Type": "application/json", "Accept": "application/json"},
25+ method="POST",
26+ )
27+ try:
28+ with urllib.request.urlopen(request, timeout=300) as response:
29+ raw = response.read().decode("utf-8")
30+ except urllib.error.HTTPError as exc:
31+ raw = exc.read().decode("utf-8", errors="replace")
32+ raise RuntimeError(f"User Authorizer HTTP {exc.code}: {raw}") from exc
33+ except urllib.error.URLError as exc:
34+ raise RuntimeError(f"User Authorizer HTTP request failed: {exc}") from exc
35+ parsed = json.loads(raw) if raw else {}
36+ return parsed if isinstance(parsed, dict) else {}
37+ 
38+ 
39+async def register_browser_key() -> None:
40+ """Relay one registration ceremony between A4P Server and User Authorizer."""
41+ a4p_client = A4PClient()
42+ options_payload = await a4p_client.webauthn_registration_options(
43+ {
44+ "userId": USER_ID,
45+ "userName": USER_ID,
46+ "userDisplayName": "A4P Note Demo User",
47+ }
48+ )
49+ registration_request_id = str(options_payload.get("registrationRequestId") or "").strip()
50+ creation_options = (
51+ options_payload.get("options") if isinstance(options_payload.get("options"), dict) else {}
52+ )
53+ local_result = await asyncio.to_thread(
54+ _post_user_authorizer_sync,
55+ "/register",
56+ {
57+ "registrationRequestId": registration_request_id,
58+ "userId": USER_ID,
59+ "creationOptions": creation_options,
60+ },
61+ )
62+ credential = local_result.get("credential")
63+ if not isinstance(credential, dict):
64+ raise RuntimeError(f"Local browser key registration failed: {local_result}")
65+ verified = await a4p_client.verify_webauthn_registration(
66+ {
67+ "registrationRequestId": registration_request_id,
68+ "userId": USER_ID,
69+ "credential": credential,
70+ }
71+ )
72+ registered = verified.get("credential") if isinstance(verified.get("credential"), dict) else {}
73+ print(f"[enrollment] registered browser credential: {registered.get('credentialId')}")
74+ 
75+ 
76+if __name__ == "__main__":
77+ asyncio.run(register_browser_key())
@@ -0,0 +1,61 @@
1+"""Run the standalone A4P authorization server for the note demo."""
2+ 
3+from __future__ import annotations
4+ 
5+import argparse
6+import asyncio
7+import json
8+from pathlib import Path
9+ 
10+from a4p import A4PServer, JsonFileCredentialStore
11+from a4p.user_signature.webauthn import WebAuthnSignatureMethod
12+from a4p.http_server import A4PHTTPServer
13+ 
14+ 
15+async def main() -> None:
16+ parser = argparse.ArgumentParser(description=__doc__)
17+ parser.add_argument("--host", default="127.0.0.1", help="A4P server host.")
18+ parser.add_argument("--port", type=int, default=8961, help="A4P server port.")
19+ parser.add_argument(
20+ "--trusted-keys-output",
21+ default=".a4p/trusted_server_keys.json",
22+ help="Write the demo Server's public trust configuration to this JSON file.",
23+ )
24+ args = parser.parse_args()
25+ 
26+ credential_store = JsonFileCredentialStore(".a4p/webauthn_credentials.json")
27+ signature_method = WebAuthnSignatureMethod(
28+ credential_store,
29+ rp_id="localhost",
30+ rp_name="A4P Note Demo",
31+ expected_origin="http://localhost:8970",
32+ )
33+ a4p_server = A4PServer(
34+ server_id="local://note-a4p-demo",
35+ user_signature_method=signature_method,
36+ )
37+ trusted_keys_path = Path(args.trusted_keys_output)
38+ trusted_keys_path.parent.mkdir(parents=True, exist_ok=True)
39+ trusted_keys_path.write_text(
40+ json.dumps(a4p_server.server_trust_config(), ensure_ascii=False, indent=2) + "\n",
41+ encoding="utf-8",
42+ )
43+ a4p_http = A4PHTTPServer(
44+ a4p_server,
45+ host=args.host,
46+ port=args.port,
47+ )
48+ await a4p_http.start()
49+ 
50+ print(f"[A4P Server] HTTP server: http://{a4p_http.host}:{a4p_http.port}")
51+ print(f"[A4P Server] Local trust configuration: {trusted_keys_path}")
52+ print("[A4P Server] User Authorizer is external; use prepare/complete authorization flow.")
53+ try:
54+ while True:
55+ await asyncio.sleep(3600)
56+ finally:
57+ await a4p_http.stop()
58+ 
59+ 
60+if __name__ == "__main__":
61+ asyncio.run(main())
@@ -0,0 +1,508 @@
1+"""Run the standalone A4P User Authorizer with a Browser/WebAuthn UI."""
2+ 
3+from __future__ import annotations
4+ 
5+import argparse
6+import asyncio
7+import html
8+import json
9+import webbrowser
10+from dataclasses import dataclass
11+from functools import lru_cache
12+from pathlib import Path
13+from string import Template
14+from typing import Any
15+from urllib.parse import parse_qs, urlencode, urlsplit
16+ 
17+from a4p import (
18+ MandateSecurityError,
19+ StaticA4PServerTrustStore,
20+ UserAuthorizationRequest,
21+ mandate_identifier,
22+ verify_local_user_authorization_request,
23+)
24+from a4p.user_signature.webauthn import WebAuthnUserSigner
25+from a4p.user_authorizer import sign_user_mandate_with_signer
26+from a4p.user_signature import A4PUserSigner
27+ 
28+ 
29+_ASSET_DIR = Path(__file__).with_name("user_authorizer_assets")
30+_PUBLIC_ASSETS = {
31+ "authorizer.css": "text/css; charset=utf-8",
32+ "authorizer.js": "text/javascript; charset=utf-8",
33+ "registration.js": "text/javascript; charset=utf-8",
34+ "webauthn.js": "text/javascript; charset=utf-8",
35+}
36+ 
37+ 
38+@lru_cache(maxsize=None)
39+def _asset_text(name: str) -> str:
40+ return (_ASSET_DIR / name).read_text(encoding="utf-8")
41+ 
42+ 
43+def _render_template(name: str, **values: str) -> str:
44+ return Template(_asset_text(name)).substitute(values)
45+ 
46+ 
47+@dataclass
48+class _PendingAuthorization:
49+ request: UserAuthorizationRequest
50+ future: asyncio.Future[dict[str, Any]]
51+ 
52+ 
53+@dataclass
54+class _PendingRegistration:
55+ registration_request_id: str
56+ user_id: str
57+ creation_options: dict[str, Any]
58+ future: asyncio.Future[dict[str, Any]]
59+ 
60+ 
61+class BrowserWebA4PUserAuthorizer:
62+ """Standalone Browser/WebAuthn User Authorizer service."""
63+ 
64+ def __init__(
65+ self,
66+ *,
67+ trust_store: StaticA4PServerTrustStore,
68+ user_signer: A4PUserSigner | None = None,
69+ host: str = "localhost",
70+ port: int = 8970,
71+ open_browser: bool = True,
72+ ) -> None:
73+ self.host = host
74+ self.port = port
75+ self.open_browser = open_browser
76+ self.trust_store = trust_store
77+ self.user_signer = user_signer or WebAuthnUserSigner()
78+ self._pending: dict[str, _PendingAuthorization] = {}
79+ self._registrations: dict[str, _PendingRegistration] = {}
80+ self._server: asyncio.AbstractServer | None = None
81+ 
82+ async def start(self) -> None:
83+ if self._server is not None:
84+ return
85+ self._server = await asyncio.start_server(self._handle_client, self.host, self.port)
86+ sockets = self._server.sockets or []
87+ if sockets:
88+ self.port = int(sockets[0].getsockname()[1])
89+ 
90+ async def stop(self) -> None:
91+ if self._server is None:
92+ return
93+ self._server.close()
94+ await self._server.wait_closed()
95+ self._server = None
96+ 
97+ async def _authorize(self, payload: dict[str, Any]) -> dict[str, Any]:
98+ mandate = payload.get("mandate") if isinstance(payload.get("mandate"), dict) else None
99+ signing_options = (
100+ payload.get("signingOptions") if isinstance(payload.get("signingOptions"), dict) else {}
@@ -0,0 +1,282 @@
1+"""Non-interactive smoke tests for the A4P note MCP example."""
2+ 
3+from __future__ import annotations
4+ 
5+import asyncio
6+import os
7+import sys
8+from pathlib import Path
9+ 
10+PROJECT_ROOT = Path(__file__).resolve().parents[2]
11+sys.path.insert(0, str(PROJECT_ROOT / "src"))
12+sys.path.insert(0, str(Path(__file__).resolve().parent))
13+ 
14+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402
15+ 
16+from a4p import ( # noqa: E402
17+ A4PClient,
18+ A4PServer,
19+ InMemoryCredentialStore,
20+ sign_user_mandate_with_signer,
21+)
22+from a4p.user_signature.ed25519 import ( # noqa: E402
23+ Ed25519UserSigner,
24+ RegisteredEd25519Method,
25+ ed25519_public_jwk,
26+)
27+from a4p.http_server import A4PHTTPServer # noqa: E402
28+ 
29+import note_mcp_server # noqa: E402
30+ 
31+ 
32+def _explicit_test_server() -> tuple[A4PServer, Ed25519UserSigner]:
33+ private_key = Ed25519PrivateKey.generate()
34+ signature_method = RegisteredEd25519Method(InMemoryCredentialStore())
35+ registration = signature_method.register(
36+ {
37+ "userId": "demo-user",
38+ "publicKey": ed25519_public_jwk(private_key),
39+ "metadata": {"purpose": "non-interactive smoke test"},
40+ }
41+ )
42+ return (
43+ A4PServer(
44+ server_id="local://note-a4p-demo",
45+ user_signature_method=signature_method,
46+ ),
47+ Ed25519UserSigner(
48+ credential_id=registration["credential"]["credentialId"],
49+ private_key=private_key,
50+ ),
51+ )
52+ 
53+ 
54+def _reset_notes() -> None:
55+ note_mcp_server._notes.clear()
56+ note_mcp_server._notes.update(
57+ {
58+ "note-1": {"id": "note-1", "title": "One", "body": "First"},
59+ "note-2": {"id": "note-2", "title": "Two", "body": "Second"},
60+ }
61+ )
62+ note_mcp_server._next_note_id = 3
63+ note_mcp_server._operation_results.clear()
64+ 
65+ 
66+async def _operation_delete_succeeds() -> None:
67+ _reset_notes()
68+ server, signer = _explicit_test_server()
69+ a4p_server = A4PHTTPServer(
70+ server,
71+ host="127.0.0.1",
72+ port=18960,
73+ )
74+ await a4p_server.start()
75+ old_base_url = os.environ.get("A4P_SERVER_BASE_URL")
76+ old_no_proxy = os.environ.get("NO_PROXY")
77+ os.environ["A4P_SERVER_BASE_URL"] = f"http://127.0.0.1:{a4p_server.port}"
78+ os.environ["NO_PROXY"] = "127.0.0.1,localhost"
79+ try:
80+ challenged = await note_mcp_server.delete_note("note-1")
81+ authorization = challenged["authorization"]
82+ signed = sign_user_mandate_with_signer(
83+ authorization["mandate"],
84+ user_signer=signer,
85+ )
86+ result = await note_mcp_server.delete_note(
87+ "note-1",
88+ operation_authorization={
89+ "signedMandate": signed,
90+ },
91+ )
92+ assert challenged["status"] == "authorization_required"
93+ assert result["deleted"] is True
94+ assert result["operationId"] == signed["operationId"]
95+ assert "note-1" not in note_mcp_server._notes
96+ finally:
97+ if old_base_url is None:
98+ os.environ.pop("A4P_SERVER_BASE_URL", None)
99+ else:
100+ os.environ["A4P_SERVER_BASE_URL"] = old_base_url
101+ if old_no_proxy is None:
102+ os.environ.pop("NO_PROXY", None)
103+ else:
104+ os.environ["NO_PROXY"] = old_no_proxy
105+ await a4p_server.stop()
106+ 
107+ 
108+async def _operation_params_mismatch_fails() -> None:
109+ _reset_notes()
110+ server, signer = _explicit_test_server()
111+ a4p_server = A4PHTTPServer(
112+ server,
113+ host="127.0.0.1",
114+ port=18960,
115+ )
116+ await a4p_server.start()
117+ old_base_url = os.environ.get("A4P_SERVER_BASE_URL")
118+ old_no_proxy = os.environ.get("NO_PROXY")
119+ os.environ["A4P_SERVER_BASE_URL"] = f"http://127.0.0.1:{a4p_server.port}"
120+ os.environ["NO_PROXY"] = "127.0.0.1,localhost"
121+ try:
122+ challenged = await note_mcp_server.delete_note("note-1")
123+ authorization = challenged["authorization"]
124+ signed = sign_user_mandate_with_signer(
125+ authorization["mandate"],
126+ user_signer=signer,
127+ )
128+ result = await note_mcp_server.delete_note(
129+ "note-2",
130+ operation_authorization={
131+ "signedMandate": signed,
132+ },
133+ )
134+ assert result["deleted"] is False
135+ assert "does not match pending" in result["error"]
136+ assert "note-1" in note_mcp_server._notes
137+ assert "note-2" in note_mcp_server._notes
138+ finally:
139+ if old_base_url is None:
140+ os.environ.pop("A4P_SERVER_BASE_URL", None)
141+ else:
142+ os.environ["A4P_SERVER_BASE_URL"] = old_base_url
143+ if old_no_proxy is None:
144+ os.environ.pop("NO_PROXY", None)
145+ else:
146+ os.environ["NO_PROXY"] = old_no_proxy
147+ await a4p_server.stop()
148+ 
149+ 
150+async def _intent_token_deletes_multiple_notes() -> None:
151+ _reset_notes()
152+ server, signer = _explicit_test_server()
153+ a4p_server = A4PHTTPServer(
154+ server,
155+ host="127.0.0.1",
156+ port=18961,
157+ )
158+ await a4p_server.start()
159+ old_base_url = os.environ.get("A4P_SERVER_BASE_URL")
160+ old_no_proxy = os.environ.get("NO_PROXY")
161+ os.environ["A4P_SERVER_BASE_URL"] = f"http://127.0.0.1:{a4p_server.port}"
162+ os.environ["NO_PROXY"] = "127.0.0.1,localhost"
163+ try:
164+ client = A4PClient()
165+ prepared = await client.prepare_intent_authorization(
166+ {
167+ "agentId": "demo-agent",
168+ "userId": "demo-user",
169+ "intent": {"actions": [{"name": "delete_note", "params": {"note_id": "*"}}]},
170+ "validitySeconds": 60,
171+ }
172+ )
173+ assert prepared.mandate is not None
174+ signed = sign_user_mandate_with_signer(
175+ prepared.mandate,
176+ user_signer=signer,
177+ )
178+ auth = await client.complete_intent_authorization(
179+ {"signedMandate": signed}
180+ )
181+ first = await note_mcp_server.delete_note("note-1", intent_token=auth.intentToken)
182+ second = await note_mcp_server.delete_note("note-2", intent_token=auth.intentToken)
183+ assert first["deleted"] is True
184+ assert second["deleted"] is True
185+ assert note_mcp_server._notes == {}
186+ finally:
187+ if old_base_url is None:
188+ os.environ.pop("A4P_SERVER_BASE_URL", None)
189+ else:
190+ os.environ["A4P_SERVER_BASE_URL"] = old_base_url
191+ if old_no_proxy is None:
192+ os.environ.pop("NO_PROXY", None)
193+ else:
194+ os.environ["NO_PROXY"] = old_no_proxy
195+ await a4p_server.stop()
196+ 
197+ 
198+async def _intent_constraints_reject_mismatches() -> None:
199+ _reset_notes()
200+ server, signer = _explicit_test_server()
201+ a4p_server = A4PHTTPServer(
202+ server,
203+ host="127.0.0.1",
204+ port=18962,
205+ )
206+ await a4p_server.start()
207+ old_base_url = os.environ.get("A4P_SERVER_BASE_URL")
208+ old_no_proxy = os.environ.get("NO_PROXY")
209+ os.environ["A4P_SERVER_BASE_URL"] = f"http://127.0.0.1:{a4p_server.port}"
210+ os.environ["NO_PROXY"] = "127.0.0.1,localhost"
211+ try:
212+ client = A4PClient()
213+ prepared = await client.prepare_intent_authorization(
214+ {
215+ "agentId": "demo-agent",
216+ "userId": "demo-user",
217+ "intent": {"actions": [{"name": "delete_note", "params": {"note_id": "note-1"}}]},
218+ "validitySeconds": 60,
219+ }
220+ )
221+ assert prepared.mandate is not None
222+ signed = sign_user_mandate_with_signer(
223+ prepared.mandate,
224+ user_signer=signer,
225+ )
226+ auth = await client.complete_intent_authorization(
227+ {"signedMandate": signed}
228+ )
229+ missing = await client.verify_intent_token(
230+ {
231+ "token": auth.intentToken,
232+ "expected": {"action": "delete_note", "params": {}, "agentId": "agent:demo-agent", "userId": "demo-user"},
233+ }
234+ )
235+ extra = await client.verify_intent_token(
236+ {
237+ "token": auth.intentToken,
238+ "expected": {
239+ "action": "delete_note",
240+ "params": {"note_id": "note-1", "force": True},
241+ "agentId": "agent:demo-agent",
242+ "userId": "demo-user",
243+ },
244+ }
245+ )
246+ action_mismatch = await client.verify_intent_token(
247+ {
248+ "token": auth.intentToken,
249+ "expected": {"action": "archive_note", "params": {"note_id": "note-1"}, "agentId": "agent:demo-agent", "userId": "demo-user"},
250+ }
251+ )
252+ assert missing.valid is False
253+ assert extra.valid is False
254+ assert action_mismatch.valid is False
255+ finally:
256+ if old_base_url is None:
257+ os.environ.pop("A4P_SERVER_BASE_URL", None)
258+ else:
259+ os.environ["A4P_SERVER_BASE_URL"] = old_base_url
260+ if old_no_proxy is None:
261+ os.environ.pop("NO_PROXY", None)
262+ else:
263+ os.environ["NO_PROXY"] = old_no_proxy
264+ await a4p_server.stop()
265+ 
266+ 
267+async def _delete_without_authorization_fails() -> None:
268+ # Covered by the first phase of the operation tests: no authorization executes no deletion.
269+ return None
270+ 
271+ 
272+async def main() -> None:
273+ await _operation_delete_succeeds()
274+ await _operation_params_mismatch_fails()
275+ await _intent_token_deletes_multiple_notes()
276+ await _intent_constraints_reject_mismatches()
277+ await _delete_without_authorization_fails()
278+ print("note_mcp_a4p smoke tests passed")
279+ 
280+ 
281+if __name__ == "__main__":
282+ asyncio.run(main())
@@ -0,0 +1,22 @@
1+<article data-authorization-id="$authorization_id" data-signing-options="$signing_options">
2+ <div class="field">
3+ <label>Authorization ID</label>
4+ <code>$authorization_id</code>
5+ </div>
6+ <div class="field">
7+ <label>Instruction</label>
8+ <div class="instruction">$display_text</div>
9+ </div>
10+ <details>
11+ <summary>完整授权对象</summary>
12+ <pre>$authorization_json</pre>
13+ </details>
14+ <div class="actions">
15+ <button class="approve" type="button" onclick="approveWithPasskey(this)">Approve with passkey</button>
16+ <form method="post" action="/reject">
17+ <input type="hidden" name="authorizationId" value="$authorization_id">
18+ <button class="reject" type="submit">Reject</button>
19+ </form>
20+ </div>
21+ <div class="status"></div>
22+</article>
@@ -0,0 +1,141 @@
1+:root {
2+ color-scheme: light;
3+ --bg: #f7f8fb;
4+ --panel: #ffffff;
5+ --text: #1f2328;
6+ --muted: #5f6b7a;
7+ --border: #d8dee8;
8+ --green: #1f7a4d;
9+ --red: #b42318;
10+ --blue: #315f96;
11+ --code: #f2f4f8;
12+}
13+ 
14+* { box-sizing: border-box; }
15+ 
16+body {
17+ margin: 0;
18+ background: var(--bg);
19+ color: var(--text);
20+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
21+ line-height: 1.5;
22+}
23+ 
24+main {
25+ max-width: 980px;
26+ margin: 0 auto;
27+ padding: 32px 20px 48px;
28+}
29+ 
30+header { margin-bottom: 20px; }
31+ 
32+h1 {
33+ margin: 0 0 6px;
34+ font-size: 28px;
35+ font-weight: 700;
36+}
37+ 
38+.subtitle {
39+ margin: 0;
40+ color: var(--muted);
41+ font-size: 15px;
42+}
43+ 
44+article {
45+ background: var(--panel);
46+ border: 1px solid var(--border);
47+ border-radius: 8px;
48+ padding: 22px;
49+ margin: 16px 0;
50+ box-shadow: 0 10px 24px rgba(31, 35, 40, 0.06);
51+}
52+ 
53+.field {
54+ display: grid;
55+ grid-template-columns: 170px minmax(0, 1fr);
56+ gap: 16px;
57+ padding: 14px 0;
58+ border-bottom: 1px solid var(--border);
59+}
60+ 
61+.field:first-of-type { padding-top: 0; }
62+ 
63+.field label {
64+ color: var(--muted);
65+ font-size: 13px;
66+ font-weight: 700;
67+ text-transform: uppercase;
68+}
69+ 
70+.field code {
71+ overflow-wrap: anywhere;
72+ color: var(--blue);
73+ font-size: 14px;
74+}
75+ 
76+.instruction {
77+ font-size: 18px;
78+ font-weight: 650;
79+}
80+ 
81+details {
82+ margin-top: 18px;
83+ border: 1px solid var(--border);
84+ border-radius: 8px;
85+ background: var(--code);
86+}
87+ 
88+summary {
89+ cursor: pointer;
90+ padding: 12px 14px;
91+ font-weight: 700;
92+}
93+ 
94+pre {
95+ margin: 0;
96+ border-top: 1px solid var(--border);
97+ padding: 14px;
98+ overflow: auto;
99+ font-size: 13px;
100+ line-height: 1.45;
101+}
102+ 
103+.actions {
104+ display: flex;
105+ gap: 10px;
106+ flex-wrap: wrap;
107+ margin-top: 20px;
108+}
109+ 
110+button {
111+ min-height: 40px;
112+ padding: 0 16px;
113+ border: 0;
114+ border-radius: 6px;
115+ color: white;
116+ font-weight: 700;
117+ cursor: pointer;
118+}
119+ 
120+.approve { background: var(--green); }
121+.reject { background: var(--red); }
122+.secondary { background: var(--blue); }
123+ 
124+.status {
125+ margin-top: 14px;
126+ color: var(--muted);
127+ font-size: 14px;
128+}
129+ 
130+.empty {
131+ background: var(--panel);
132+ border: 1px dashed var(--border);
133+ border-radius: 8px;
134+ padding: 24px;
135+ color: var(--muted);
136+}
137+ 
138+@media (max-width: 680px) {
139+ main { padding: 24px 14px 36px; }
140+ .field { grid-template-columns: 1fr; gap: 4px; }
141+}
@@ -0,0 +1,20 @@
1+<!doctype html>
2+<html>
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>A4P User Authorizer</title>
7+ <link rel="stylesheet" href="/assets/authorizer.css">
8+</head>
9+<body>
10+ <main>
11+ <header>
12+ <h1>A4P User Authorizer</h1>
13+ <p class="subtitle">Review the request, then approve with a browser passkey or reject.</p>
14+ </header>
15+ $body
16+ </main>
17+ <script src="/assets/webauthn.js"></script>
18+ <script src="/assets/authorizer.js"></script>
19+</body>
20+</html>
@@ -0,0 +1,37 @@
1+function decodeRequestOptions(publicKey) {
2+ publicKey.challenge = b64urlToBuffer(publicKey.challenge);
3+ for (const item of publicKey.allowCredentials || []) item.id = b64urlToBuffer(item.id);
4+ return publicKey;
5+}
6+ 
7+async function postJSON(path, payload) {
8+ const response = await fetch(path, {
9+ method: 'POST',
10+ headers: {'Content-Type': 'application/json'},
11+ body: JSON.stringify(payload),
12+ });
13+ const data = await response.json();
14+ if (!response.ok || data.ok === false) throw new Error(data.message || data.error || 'Request failed');
15+ return data;
16+}
17+ 
18+async function approveWithPasskey(button) {
19+ const article = button.closest('article');
20+ const status = article.querySelector('.status');
21+ try {
22+ status.textContent = 'Waiting for browser authentication...';
23+ const authorizationId = article.dataset.authorizationId;
24+ const options = JSON.parse(article.dataset.signingOptions);
25+ if (options.signatureMethod !== 'webauthn') throw new Error('Unsupported signature method');
26+ const assertion = await navigator.credentials.get({
27+ publicKey: decodeRequestOptions(options.methodOptions),
28+ });
29+ const result = await postJSON('/approve', {
30+ authorizationId,
31+ assertion: credentialToJSON(assertion),
32+ });
33+ status.textContent = result.message;
34+ } catch (error) {
35+ status.textContent = error.message;
36+ }
37+}
@@ -0,0 +1 @@
1+<section class="empty">$message</section>
@@ -0,0 +1,2 @@
1+<!doctype html>
2+<html><head><meta charset="utf-8"><title>Internal error</title></head><body><h1>Internal error</h1><pre>$message</pre></body></html>
@@ -0,0 +1,2 @@
1+<!doctype html>
2+<html><head><meta charset="utf-8"><title>Not Found</title></head><body><h1>Not Found</h1></body></html>
@@ -0,0 +1,21 @@
1+<!doctype html>
2+<html>
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>Register A4P browser key</title>
7+ <link rel="stylesheet" href="/assets/authorizer.css">
8+</head>
9+<body>
10+ <main>
11+ <article>
12+ <h1>Register A4P browser key</h1>
13+ <p>Register a passkey for <code>$user_id</code>. Continue only if you initiated the Agent command.</p>
14+ <button class="secondary" id="register" data-request-id="$request_id" data-options="$options">Register passkey</button>
15+ <p class="status" id="status"></p>
16+ </article>
17+ </main>
18+ <script src="/assets/webauthn.js"></script>
19+ <script src="/assets/registration.js"></script>
20+</body>
21+</html>
@@ -0,0 +1,29 @@
1+function decodeCreationOptions(publicKey) {
2+ publicKey.challenge = b64urlToBuffer(publicKey.challenge);
3+ publicKey.user.id = b64urlToBuffer(publicKey.user.id);
4+ for (const item of publicKey.excludeCredentials || []) item.id = b64urlToBuffer(item.id);
5+ return publicKey;
6+}
7+ 
8+document.getElementById('register').onclick = async function() {
9+ const status = document.getElementById('status');
10+ try {
11+ status.textContent = 'Waiting for browser authenticator...';
12+ const credential = await navigator.credentials.create({
13+ publicKey: decodeCreationOptions(JSON.parse(this.dataset.options)),
14+ });
15+ const response = await fetch('/register/complete', {
16+ method: 'POST',
17+ headers: {'Content-Type': 'application/json'},
18+ body: JSON.stringify({
19+ registrationRequestId: this.dataset.requestId,
20+ credential: credentialToJSON(credential),
21+ }),
22+ });
23+ const result = await response.json();
24+ if (!response.ok || result.ok === false) throw new Error(result.message || 'Registration failed');
25+ status.textContent = result.message;
26+ } catch (error) {
27+ status.textContent = error.message;
28+ }
29+};
@@ -0,0 +1,17 @@
1+<!doctype html>
2+<html>
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>A4P User Authorizer result</title>
7+ <link rel="stylesheet" href="/assets/authorizer.css">
8+</head>
9+<body>
10+ <main>
11+ <article>
12+ <h1>$message</h1>
13+ <p><a href="/">Back to pending requests</a></p>
14+ </article>
15+ </main>
16+</body>
17+</html>
@@ -0,0 +1,31 @@
1+function b64urlToBuffer(value) {
2+ const base64 = value.replace(/-/g, '+').replace(/_/g, '/');
3+ const padded = base64 + '='.repeat((4 - base64.length % 4) % 4);
4+ const binary = atob(padded);
5+ const bytes = new Uint8Array(binary.length);
6+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
7+ return bytes.buffer;
8+}
9+ 
10+function bufferToB64url(buffer) {
11+ const bytes = new Uint8Array(buffer);
12+ let binary = '';
13+ for (const byte of bytes) binary += String.fromCharCode(byte);
14+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
15+}
16+ 
17+function credentialToJSON(credential) {
18+ const response = credential.response;
19+ const out = {
20+ id: credential.id,
21+ rawId: bufferToB64url(credential.rawId),
22+ type: credential.type,
23+ response: {},
24+ };
25+ for (const key of ['attestationObject', 'authenticatorData', 'clientDataJSON', 'signature', 'userHandle']) {
26+ const value = response[key];
27+ if (value instanceof ArrayBuffer) out.response[key] = bufferToB64url(value);
28+ }
29+ if (typeof response.getTransports === 'function') out.response.transports = response.getTransports();
30+ return out;
31+}
@@ -0,0 +1,47 @@
1+[build-system]
2+requires = ["hatchling>=1.25"]
3+build-backend = "hatchling.build"
4+ 
5+[project]
6+name = "a4p"
7+version = "0.2.0"
8+description = "A lightweight Python SDK for A4P authorization mandates and tokens."
9+readme = "README.md"
10+requires-python = ">=3.10"
11+license = { text = "Apache-2.0" }
12+authors = [
13+ { name = "Agent Protocol Contributors" },
14+]
15+keywords = ["agent", "authorization", "a4p", "sdk"]
16+classifiers = [
17+ "Development Status :: 3 - Alpha",
18+ "Intended Audience :: Developers",
19+ "License :: OSI Approved :: Apache Software License",
20+ "Programming Language :: Python :: 3",
21+ "Programming Language :: Python :: 3.10",
22+ "Programming Language :: Python :: 3.11",
23+ "Programming Language :: Python :: 3.12",
24+ "Programming Language :: Python :: 3.13",
25+]
26+dependencies = [
27+ "cryptography>=45.0.0",
28+ "tzdata",
29+ "webauthn>=2.0.0",
30+]
31+ 
32+[project.optional-dependencies]
33+demo = [
34+ "mcp[cli]>=1.0.0",
35+]
36+ 
37+[dependency-groups]
38+dev = [
39+ "pytest>=8.0",
40+]
41+ 
42+[tool.hatch.build.targets.wheel]
43+packages = ["src/a4p"]
44+ 
45+[tool.pytest.ini_options]
46+pythonpath = ["src"]
47+testpaths = ["tests"]
@@ -0,0 +1,102 @@
1+"""Public A4P SDK exports."""
2+ 
3+from a4p.client import A4PClient
4+from a4p.credential_store import (
5+ CredentialStoreFormatError,
6+ InMemoryCredentialStore,
7+ JsonFileCredentialStore,
8+ UserCredentialRecord,
9+)
10+from a4p.errors import (
11+ A4PProtocolError,
12+ CredentialKeyConflictError,
13+ SignatureMethodNotEnabledError,
14+ UserCredentialNotRegisteredError,
15+)
16+from a4p.intent.mandate import IntentDisplayTextRenderer
17+from a4p.intent.usage_store import A4PIntentTokenUsageStore, SQLiteIntentTokenUsageStore
18+from a4p.mandate_security import (
19+ MandateSecurityError,
20+ StaticA4PServerTrustStore,
21+ derive_user_authorization_challenge,
22+ mandate_identifier,
23+ user_authorization_challenge_base64url,
24+ verify_trusted_server_mandate,
25+)
26+from a4p.operation.mandate import OperationDisplayTextRenderer
27+from a4p.server import A4PServer
28+from a4p.types import (
29+ IntentAuthorizationRequest,
30+ IntentAuthorizationResponse,
31+ IntentMandate,
32+ IntentToken,
33+ OperationAuthorizationChallenge,
34+ OperationAuthorizationCompletionRequest,
35+ OperationAuthorizationRequest,
36+ OperationAuthorizationResult,
37+ OperationMandate,
38+ TokenVerificationRequest,
39+ TokenVerificationResponse,
40+ UserAuthorizationRequest,
41+ UserAuthorizationResponse,
42+ VerificationResult,
43+)
44+from a4p.user_authorizer import (
45+ A4PUserAuthorizer,
46+ ApprovingA4PUserAuthorizer,
47+ RejectingA4PUserAuthorizer,
48+ approve_user_mandate,
49+ sign_user_mandate_with_signer,
50+ verify_local_user_authorization_request,
51+)
52+from a4p.user_signature import (
53+ A4PUserSignatureMethod,
54+ A4PUserSigner,
55+ UserSignatureContext,
56+)
57+ 
58+__all__ = [
59+ "A4PClient",
60+ "A4PProtocolError",
61+ "A4PServer",
62+ "A4PIntentTokenUsageStore",
63+ "A4PUserAuthorizer",
64+ "A4PUserSignatureMethod",
65+ "A4PUserSigner",
66+ "ApprovingA4PUserAuthorizer",
67+ "CredentialKeyConflictError",
68+ "CredentialStoreFormatError",
69+ "InMemoryCredentialStore",
70+ "IntentDisplayTextRenderer",
71+ "IntentAuthorizationRequest",
72+ "IntentAuthorizationResponse",
73+ "IntentMandate",
74+ "IntentToken",
75+ "JsonFileCredentialStore",
76+ "MandateSecurityError",
77+ "OperationAuthorizationChallenge",
78+ "OperationAuthorizationCompletionRequest",
79+ "OperationAuthorizationRequest",
80+ "OperationAuthorizationResult",
81+ "OperationDisplayTextRenderer",
82+ "OperationMandate",
83+ "RejectingA4PUserAuthorizer",
84+ "SignatureMethodNotEnabledError",
85+ "approve_user_mandate",
86+ "sign_user_mandate_with_signer",
87+ "SQLiteIntentTokenUsageStore",
88+ "StaticA4PServerTrustStore",
89+ "TokenVerificationRequest",
90+ "TokenVerificationResponse",
91+ "UserAuthorizationRequest",
92+ "UserAuthorizationResponse",
93+ "UserCredentialNotRegisteredError",
94+ "UserCredentialRecord",
95+ "UserSignatureContext",
96+ "VerificationResult",
97+ "derive_user_authorization_challenge",
98+ "mandate_identifier",
99+ "user_authorization_challenge_base64url",
100+ "verify_local_user_authorization_request",
101+ "verify_trusted_server_mandate",
102+]
@@ -0,0 +1,44 @@
1+"""Shared internal helpers for authorization services."""
2+ 
3+from __future__ import annotations
4+ 
5+from collections.abc import Callable, Mapping
6+from copy import deepcopy
7+from dataclasses import is_dataclass
8+from typing import Any
9+ 
10+from a4p.types import to_payload
11+ 
12+ 
13+def payload(value: Any) -> dict[str, Any]:
14+ converted = to_payload(value) if is_dataclass(value) else value
15+ return converted if isinstance(converted, dict) else {}
16+ 
17+ 
18+def error_code(reason: str, prefix: str) -> str:
19+ lower = reason.lower()
20+ if "expired" in lower:
21+ return f"{prefix}_EXPIRED"
22+ if "usage" in lower or "execution" in lower or "limit" in lower:
23+ return f"{prefix}_USAGE_EXCEEDED"
24+ if "signature" in lower:
25+ return f"{prefix}_SIGNATURE_INVALID"
26+ if "mismatch" in lower or "scope" in lower or "actions" in lower or "param" in lower:
27+ return f"{prefix}_SCOPE_MISMATCH"
28+ return f"{prefix}_INVALID"
29+ 
30+ 
31+def mandate_matches_pending(
32+ signed_mandate: dict[str, Any],
33+ pending_mandate: dict[str, Any],
34+ *,
35+ normalize: Callable[[Mapping[str, Any]], Mapping[str, Any]],
36+) -> bool:
37+ try:
38+ signed = deepcopy(dict(normalize(signed_mandate)))
39+ pending = deepcopy(dict(normalize(pending_mandate)))
40+ except (TypeError, ValueError):
41+ return False
42+ signed["signatures"]["user"] = {}
43+ pending["signatures"]["user"] = {}
44+ return signed == pending
@@ -0,0 +1,182 @@
1+"""HTTP A4P client."""
2+ 
3+from __future__ import annotations
4+ 
5+import asyncio
6+import json
7+import os
8+import urllib.error
9+import urllib.request
10+from dataclasses import is_dataclass
11+from typing import Any, cast
12+ 
13+from a4p.types import (
14+ IntentAuthorizationRequest,
15+ IntentAuthorizationResponse,
16+ IntentMandate,
17+ IntentToken,
18+ OperationAuthorizationChallenge,
19+ OperationAuthorizationCompletionRequest,
20+ OperationAuthorizationRequest,
21+ OperationAuthorizationResult,
22+ OperationMandate,
23+ TokenVerificationRequest,
24+ TokenVerificationResponse,
25+ VerificationResult,
26+ to_payload,
27+)
28+ 
29+ 
30+def default_a4p_base_url() -> str:
31+ return (os.getenv("A4P_SERVER_BASE_URL") or "http://127.0.0.1:8961").rstrip("/")
32+ 
33+ 
34+def default_a4p_timeout() -> float:
35+ raw = (os.getenv("A4P_HTTP_TIMEOUT_S") or "300").strip()
36+ try:
37+ return max(1.0, float(raw))
38+ except ValueError:
39+ return 300.0
40+ 
41+ 
42+def _coerce_payload(value: Any) -> dict[str, Any]:
43+ payload = to_payload(value) if is_dataclass(value) else value
44+ return payload if isinstance(payload, dict) else {}
45+ 
46+ 
47+def _verification_result_from_payload(payload: Any) -> VerificationResult | None:
48+ if not isinstance(payload, dict):
49+ return None
50+ return VerificationResult(
51+ valid=bool(payload.get("valid")),
52+ reason=payload.get("reason"),
53+ code=payload.get("code"),
54+ matchedScope=payload.get("matchedScope") if isinstance(payload.get("matchedScope"), dict) else None,
55+ )
56+ 
57+ 
58+def _intent_mandate_from_payload(payload: Any) -> IntentMandate | None:
59+ return cast(IntentMandate, payload) if isinstance(payload, dict) else None
60+ 
61+ 
62+def _intent_token_from_payload(payload: Any) -> IntentToken | None:
63+ return cast(IntentToken, payload) if isinstance(payload, dict) else None
64+ 
65+ 
66+def _operation_mandate_from_payload(payload: Any) -> OperationMandate | None:
67+ return cast(OperationMandate, payload) if isinstance(payload, dict) else None
68+ 
69+ 
70+class A4PClient:
71+ """Small async HTTP client for A4P server endpoints."""
72+ 
73+ def __init__(self, *, base_url: str | None = None, timeout: float | None = None) -> None:
74+ self.base_url = (base_url or default_a4p_base_url()).rstrip("/")
75+ self.timeout = timeout if timeout is not None else default_a4p_timeout()
76+ 
77+ async def prepare_intent_authorization(
78+ self,
79+ request: IntentAuthorizationRequest | dict[str, Any],
80+ ) -> IntentAuthorizationResponse:
81+ payload = await self._post("/a4p/v1/intent-authorizations/prepare", _coerce_payload(request))
82+ return IntentAuthorizationResponse(
83+ mandate=_intent_mandate_from_payload(payload.get("mandate")),
84+ signingOptions=(
85+ payload.get("signingOptions") if isinstance(payload.get("signingOptions"), dict) else {}
86+ ),
87+ verificationResult=_verification_result_from_payload(payload.get("verificationResult")),
88+ approved=bool(payload.get("approved")),
89+ rejectReason=payload.get("rejectReason"),
90+ )
91+ 
92+ async def complete_intent_authorization(
93+ self,
94+ request: dict[str, Any],
95+ ) -> IntentAuthorizationResponse:
96+ payload = await self._post("/a4p/v1/intent-authorizations/complete", request)
97+ return IntentAuthorizationResponse(
98+ mandate=_intent_mandate_from_payload(payload.get("mandate")),
99+ intentToken=_intent_token_from_payload(payload.get("intentToken")),
100+ verificationResult=_verification_result_from_payload(payload.get("verificationResult")),
101+ approved=bool(payload.get("approved")),
102+ rejectReason=payload.get("rejectReason"),
103+ )
104+ 
105+ async def verify_intent_token(
106+ self,
107+ request: TokenVerificationRequest | dict[str, Any],
108+ ) -> TokenVerificationResponse:
109+ payload = await self._post("/a4p/v1/intent-tokens/verify", _coerce_payload(request))
110+ return TokenVerificationResponse(
111+ valid=bool(payload.get("valid")),
112+ reason=payload.get("reason"),
113+ code=payload.get("code"),
114+ matchedScope=payload.get("matchedScope") if isinstance(payload.get("matchedScope"), dict) else None,
115+ )
116+ 
117+ async def prepare_operation_authorization(
118+ self,
119+ request: OperationAuthorizationRequest | dict[str, Any],
120+ ) -> OperationAuthorizationChallenge:
121+ payload = await self._post("/a4p/v1/operation-authorizations/prepare", _coerce_payload(request))
122+ return OperationAuthorizationChallenge(
123+ mandate=_operation_mandate_from_payload(payload.get("mandate")),
124+ signingOptions=(
125+ payload.get("signingOptions") if isinstance(payload.get("signingOptions"), dict) else {}
126+ ),
127+ verificationResult=_verification_result_from_payload(payload.get("verificationResult")),
128+ rejectReason=payload.get("rejectReason"),
129+ )
130+ 
131+ async def complete_operation_authorization(
132+ self,
133+ request: OperationAuthorizationCompletionRequest | dict[str, Any],
134+ ) -> OperationAuthorizationResult:
135+ payload = await self._post("/a4p/v1/operation-authorizations/complete", _coerce_payload(request))
136+ return OperationAuthorizationResult(
137+ operationId=str(payload.get("operationId") or "") or None,
138+ verificationResult=_verification_result_from_payload(payload.get("verificationResult")),
139+ approved=bool(payload.get("approved")),
140+ rejectReason=payload.get("rejectReason"),
141+ )
142+ 
143+ async def register_ed25519_credential(self, request: dict[str, Any]) -> dict[str, Any]:
144+ return await self._post(
145+ "/a4p/v1/user-credentials/ed25519/register",
146+ request,
147+ )
148+ 
149+ async def webauthn_registration_options(self, request: dict[str, Any]) -> dict[str, Any]:
150+ return await self._post("/a4p/v1/user-credentials/webauthn/register/options", request)
151+ 
152+ async def verify_webauthn_registration(self, request: dict[str, Any]) -> dict[str, Any]:
153+ return await self._post("/a4p/v1/user-credentials/webauthn/register/verify", request)
154+ 
155+ async def _post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
156+ return await asyncio.to_thread(self._post_sync, path, payload)
157+ 
158+ def _post_sync(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:
159+ data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
160+ req = urllib.request.Request(
161+ f"{self.base_url}{path}",
162+ data=data,
163+ headers={"Content-Type": "application/json", "Accept": "application/json"},
164+ method="POST",
165+ )
166+ try:
167+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
168+ raw = resp.read().decode("utf-8")
169+ except urllib.error.HTTPError as exc:
170+ raw = exc.read().decode("utf-8", errors="replace")
171+ try:
172+ error_payload = json.loads(raw)
173+ except json.JSONDecodeError:
174+ error_payload = {"error": raw}
175+ raise RuntimeError(f"A4P HTTP {exc.code}: {error_payload}") from exc
176+ except urllib.error.URLError as exc:
177+ raise RuntimeError(f"A4P HTTP request failed: {exc}") from exc
178+ parsed = json.loads(raw) if raw else {}
179+ return parsed if isinstance(parsed, dict) else {}
180+ 
181+ 
182+__all__ = ["A4PClient", "default_a4p_base_url", "default_a4p_timeout"]
AA4P/uv.lock+1207-0