@7h3/protocol 0.4.0 → 0.5.1

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.
Files changed (248) hide show
  1. package/README.md +6 -323
  2. package/agentAdapter.d.ts +26 -0
  3. package/auditLog.d.ts +54 -0
  4. package/capability.d.ts +67 -0
  5. package/cborCodec.d.ts +34 -0
  6. package/conformanceVectors.d.ts +20 -0
  7. package/encryption.d.ts +85 -0
  8. package/envelopeCbor.d.ts +33 -0
  9. package/frameworkAdapters.d.ts +72 -0
  10. package/gateway.d.ts +53 -0
  11. package/grpcBinding.d.ts +29 -0
  12. package/httpBinding.d.ts +50 -0
  13. package/index.d.ts +39 -0
  14. package/index.js +3662 -0
  15. package/keyInfra.d.ts +64 -0
  16. package/keyRegistry.d.ts +9 -0
  17. package/keyRotation.d.ts +20 -0
  18. package/mcpGateway.d.ts +37 -0
  19. package/mcpTransports.d.ts +62 -0
  20. package/mcpWrapper.d.ts +83 -0
  21. package/otel.d.ts +65 -0
  22. package/package.json +13 -79
  23. package/policyEnforcer.d.ts +50 -0
  24. package/policyTelemetryFeedback.d.ts +11 -0
  25. package/protocol.d.ts +66 -0
  26. package/protocolAgent.d.ts +58 -0
  27. package/protocolBinary.d.ts +8 -0
  28. package/protocolCapabilities.d.ts +24 -0
  29. package/protocolReplay.d.ts +35 -0
  30. package/protocolTransport.d.ts +73 -0
  31. package/queueBinding.d.ts +43 -0
  32. package/rateLimiter.d.ts +18 -0
  33. package/{src/redisClient.ts → redisClient.d.ts} +25 -75
  34. package/replayStores.d.ts +98 -0
  35. package/revocation.d.ts +71 -0
  36. package/routePolicy.d.ts +30 -0
  37. package/runtimePolicy.d.ts +24 -0
  38. package/runtimePolicyManager.d.ts +15 -0
  39. package/runtimePolicyPresets.d.ts +11 -0
  40. package/signedResponse.d.ts +21 -0
  41. package/stream.d.ts +59 -0
  42. package/telemetry.d.ts +79 -0
  43. package/webhookBinding.d.ts +30 -0
  44. package/wsBinding.d.ts +52 -0
  45. package/.dockerignore +0 -19
  46. package/.github/dependabot.yml +0 -32
  47. package/.github/workflows/ci.yml +0 -31
  48. package/.github/workflows/publish.yml +0 -59
  49. package/.github/workflows/scorecard.yml +0 -37
  50. package/7h3.example.yaml +0 -125
  51. package/CHANGELOG.md +0 -92
  52. package/CONTRIBUTING.md +0 -82
  53. package/Dockerfile +0 -73
  54. package/GOVERNANCE.md +0 -62
  55. package/SECURITY.md +0 -70
  56. package/bench-results/replay-cache-full-1777891033256.json +0 -10
  57. package/bench-results/replay-cache-full-1777896317488.json +0 -10
  58. package/bench-results/replay-cache-full-1777900993184.json +0 -10
  59. package/bench-results/replay-cache-full-1777901019285.json +0 -10
  60. package/bench-results/replay-cache-quick-1777870170126.json +0 -10
  61. package/bench-results/signature-profiles-quick-1775875160079.json +0 -85
  62. package/bench-results/signature-profiles-quick-1775983539716.json +0 -85
  63. package/bench-results/signature-profiles-quick-1776237913190.json +0 -85
  64. package/bench-results/wire-codecs-full-1777891019803.json +0 -93
  65. package/bench-results/wire-codecs-full-1777896260964.json +0 -93
  66. package/bench-results/wire-codecs-full-1777901004247.json +0 -93
  67. package/bench-results/wire-codecs-quick-1775972879056.json +0 -93
  68. package/bench-results/wire-codecs-quick-1775983541111.json +0 -93
  69. package/bench-results/wire-codecs-quick-1776237914299.json +0 -93
  70. package/bench-results/wire-codecs-quick-1777841285236.json +0 -93
  71. package/bench-results/wire-codecs-quick-1777841321772.json +0 -93
  72. package/bench-results/wire-codecs-quick-1777841330408.json +0 -93
  73. package/bench-results/wire-codecs-quick-1777852886082.json +0 -93
  74. package/bench-results/wire-codecs-quick-1777852988773.json +0 -93
  75. package/bench-results/wire-codecs-quick-1777870188095.json +0 -93
  76. package/bench-results/wire-codecs-quick-1777870263918.json +0 -93
  77. package/bench-results/wire-codecs-quick-1777870455034.json +0 -93
  78. package/bench-results/wire-codecs-quick-1778816163081.json +0 -93
  79. package/bench-results/wire-codecs-quick-1778843936130.json +0 -93
  80. package/bin/7h3.ts +0 -385
  81. package/conformance/7h3_v0_1.json +0 -77
  82. package/conformance/7h3_v0_1_binary.json +0 -20
  83. package/conformance/aip_v0_1_binary.json +0 -20
  84. package/docker-compose.yaml +0 -77
  85. package/docs/ADOPTION_PLAN.md +0 -120
  86. package/docs/AGENTS.md +0 -77
  87. package/docs/AIP_RFC_v0.1.md +0 -97
  88. package/docs/AI_DECISION_CARD.md +0 -122
  89. package/docs/AI_RUNTIME_POLICY.json +0 -126
  90. package/docs/AI_RUNTIME_POLICY.yaml +0 -110
  91. package/docs/BACKPRESSURE_TUNING.md +0 -65
  92. package/docs/BENCHMARK_CLAIM_MATRIX.md +0 -42
  93. package/docs/BENCHMARK_REPORT_TEMPLATE.md +0 -169
  94. package/docs/BINARY_CODEC_BENCH.md +0 -23
  95. package/docs/CLEAN_CLONE_RUNBOOK.md +0 -36
  96. package/docs/CLOCK_SKEW_POLICY.md +0 -30
  97. package/docs/DISTRIBUTED_REPLAY.md +0 -142
  98. package/docs/FUZZ_CAMPAIGN.md +0 -121
  99. package/docs/GATEWAY.md +0 -195
  100. package/docs/KEY_MANAGEMENT_POLICY.md +0 -53
  101. package/docs/KEY_REVOCATION.md +0 -69
  102. package/docs/MCP_WRAPPER.md +0 -159
  103. package/docs/MIGRATION_GUIDE.md +0 -40
  104. package/docs/OPERATORS.md +0 -184
  105. package/docs/PERF_REGRESSION_POLICY.md +0 -34
  106. package/docs/PROJECT_EXAMINATION_2026-05-31.md +0 -219
  107. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +0 -135
  108. package/docs/RELEASE_GATE.md +0 -25
  109. package/docs/RELEASE_NOTES_v0.1.0.md +0 -54
  110. package/docs/SECURITY_REVIEW_2026-06-05.md +0 -165
  111. package/docs/TELEMETRY.md +0 -41
  112. package/docs/THREAT_MODEL.md +0 -89
  113. package/docs/VERSIONING_POLICY.md +0 -30
  114. package/docs/assets/banner.png +0 -0
  115. package/eslint.config.js +0 -15
  116. package/fuzz/ts/harness-decode.ts +0 -136
  117. package/fuzz/ts/harness-verify.ts +0 -121
  118. package/fuzz/ts/run.ts +0 -35
  119. package/mcp-server/README.md +0 -38
  120. package/mcp-server/package-lock.json +0 -1187
  121. package/mcp-server/package.json +0 -35
  122. package/mcp-server/src/index.ts +0 -236
  123. package/mcp-server/tsconfig.json +0 -14
  124. package/scripts/aip-framework-quickstart.ts +0 -110
  125. package/scripts/aip-mcp-gateway.ts +0 -38
  126. package/scripts/aip-mcp-wrap-demo.ts +0 -72
  127. package/scripts/aip-quickstart.ts +0 -60
  128. package/scripts/bench-diff.ts +0 -118
  129. package/scripts/bench-protocol-e2e.ts +0 -937
  130. package/scripts/bench-protocol-openloop.ts +0 -1397
  131. package/scripts/bench-replay-cache.ts +0 -76
  132. package/scripts/bench-signature-profiles.ts +0 -180
  133. package/scripts/bench-wire-codecs.ts +0 -161
  134. package/scripts/build-binary-conformance.ts +0 -36
  135. package/scripts/build-release-dashboard.ts +0 -175
  136. package/scripts/canary-rollout.ts +0 -38
  137. package/scripts/mcpGatewayCli.test.ts +0 -116
  138. package/scripts/prepare-aip-package.ts +0 -88
  139. package/scripts/regen-conformance-sigs.ts +0 -18
  140. package/scripts/release-gate.ts +0 -19
  141. package/scripts/validate-runtime-policy.ts +0 -18
  142. package/sdk/browser/index.test.ts +0 -162
  143. package/sdk/browser/index.ts +0 -257
  144. package/sdk/browser/package.json +0 -13
  145. package/sdk/go/go.mod +0 -3
  146. package/sdk/go/http.go +0 -135
  147. package/sdk/go/protocol.go +0 -324
  148. package/sdk/go/protocol_test.go +0 -334
  149. package/sdk/go/webhook.go +0 -136
  150. package/sdk/python/README.md +0 -18
  151. package/sdk/python/protocol_7h3/__init__.py +0 -46
  152. package/sdk/python/protocol_7h3/http.py +0 -212
  153. package/sdk/python/protocol_7h3/keys.py +0 -149
  154. package/sdk/python/protocol_7h3/protocol.py +0 -525
  155. package/sdk/python/protocol_7h3/queue.py +0 -118
  156. package/sdk/python/protocol_7h3/webhook.py +0 -116
  157. package/sdk/python/pyproject.toml +0 -40
  158. package/sdk/python/tests/test_conformance.py +0 -110
  159. package/sdk/python/tests/test_http.py +0 -305
  160. package/sdk/python/tests/test_keys.py +0 -417
  161. package/sdk/python/tests/test_queue.py +0 -120
  162. package/sdk/python/tests/test_webhook.py +0 -345
  163. package/sdk/rust/Cargo.lock +0 -371
  164. package/sdk/rust/Cargo.toml +0 -25
  165. package/sdk/rust/README.md +0 -31
  166. package/sdk/rust/fuzz/Cargo.toml +0 -29
  167. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +0 -46
  168. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +0 -11
  169. package/sdk/rust/src/bin/aip_mcp_gateway.rs +0 -59
  170. package/sdk/rust/src/http.rs +0 -145
  171. package/sdk/rust/src/keys.rs +0 -161
  172. package/sdk/rust/src/lib.rs +0 -688
  173. package/sdk/rust/src/queue.rs +0 -79
  174. package/sdk/rust/src/webhook.rs +0 -86
  175. package/sdk/rust/tests/conformance.rs +0 -148
  176. package/sdk/rust/tests/gateway.rs +0 -130
  177. package/sdk/rust/tests/http_webhook_queue.rs +0 -201
  178. package/sdk/rust/tests/keys.rs +0 -189
  179. package/src/agentAdapter.test.ts +0 -48
  180. package/src/agentAdapter.ts +0 -56
  181. package/src/auditLog.test.ts +0 -145
  182. package/src/auditLog.ts +0 -147
  183. package/src/conformance.test.ts +0 -136
  184. package/src/conformanceVectors.ts +0 -99
  185. package/src/frameworkAdapters.test.ts +0 -290
  186. package/src/frameworkAdapters.ts +0 -261
  187. package/src/gateway.test.ts +0 -343
  188. package/src/gateway.ts +0 -171
  189. package/src/grpcBinding.test.ts +0 -211
  190. package/src/grpcBinding.ts +0 -103
  191. package/src/httpBinding.test.ts +0 -376
  192. package/src/httpBinding.ts +0 -163
  193. package/src/index.ts +0 -32
  194. package/src/keyInfra.test.ts +0 -278
  195. package/src/keyInfra.ts +0 -228
  196. package/src/keyRegistry.ts +0 -59
  197. package/src/keyRotation.test.ts +0 -78
  198. package/src/keyRotation.ts +0 -72
  199. package/src/mcpGateway.test.ts +0 -129
  200. package/src/mcpGateway.ts +0 -250
  201. package/src/mcpTransports.test.ts +0 -92
  202. package/src/mcpTransports.ts +0 -169
  203. package/src/mcpWrapper.test.ts +0 -179
  204. package/src/mcpWrapper.ts +0 -206
  205. package/src/policyEnforcer.test.ts +0 -99
  206. package/src/policyEnforcer.ts +0 -169
  207. package/src/policyTelemetryFeedback.test.ts +0 -25
  208. package/src/policyTelemetryFeedback.ts +0 -38
  209. package/src/protocol.bench.ts +0 -37
  210. package/src/protocol.test.ts +0 -155
  211. package/src/protocol.ts +0 -413
  212. package/src/protocolAgent.test.ts +0 -105
  213. package/src/protocolAgent.ts +0 -169
  214. package/src/protocolBinary.test.ts +0 -165
  215. package/src/protocolBinary.ts +0 -312
  216. package/src/protocolCapabilities.ts +0 -70
  217. package/src/protocolFuzz.advanced.test.ts +0 -235
  218. package/src/protocolFuzz.test.ts +0 -111
  219. package/src/protocolNegative.test.ts +0 -97
  220. package/src/protocolReplay.test.ts +0 -71
  221. package/src/protocolReplay.ts +0 -194
  222. package/src/protocolTransport.test.ts +0 -556
  223. package/src/protocolTransport.ts +0 -483
  224. package/src/queueBinding.test.ts +0 -130
  225. package/src/queueBinding.ts +0 -102
  226. package/src/rateLimiter.test.ts +0 -96
  227. package/src/rateLimiter.ts +0 -46
  228. package/src/redisIntegration.test.ts +0 -134
  229. package/src/replayStores.test.ts +0 -141
  230. package/src/replayStores.ts +0 -82
  231. package/src/revocation.test.ts +0 -98
  232. package/src/revocation.ts +0 -0
  233. package/src/routePolicy.test.ts +0 -87
  234. package/src/routePolicy.ts +0 -72
  235. package/src/runtimePolicy.test.ts +0 -49
  236. package/src/runtimePolicy.ts +0 -81
  237. package/src/runtimePolicyManager.test.ts +0 -29
  238. package/src/runtimePolicyManager.ts +0 -50
  239. package/src/runtimePolicyPresets.ts +0 -43
  240. package/src/signedResponse.test.ts +0 -111
  241. package/src/signedResponse.ts +0 -83
  242. package/src/webhookBinding.test.ts +0 -144
  243. package/src/webhookBinding.ts +0 -115
  244. package/src/wsBinding.test.ts +0 -221
  245. package/src/wsBinding.ts +0 -100
  246. package/tsconfig.json +0 -15
  247. package/tsconfig.lib.json +0 -23
  248. package/vite.lib.config.ts +0 -16
@@ -1,79 +0,0 @@
1
- //! Queue binding — signed message envelope for Kafka/SQS/Pub-Sub transit.
2
-
3
- use crate::{
4
- create_envelope, sign_envelope_ed25519, validate_envelope, verify_envelope_ed25519,
5
- ProtocolBody, ProtocolEnvelope,
6
- };
7
- use serde::{Deserialize, Serialize};
8
-
9
- pub const DEFAULT_TTL_MS: i64 = 3_600_000;
10
-
11
- #[derive(Serialize, Deserialize)]
12
- pub struct QueueMessage<T: Serialize> {
13
- pub envelope: ProtocolEnvelope,
14
- pub payload: T,
15
- }
16
-
17
- fn now_ms() -> i64 {
18
- std::time::SystemTime::now()
19
- .duration_since(std::time::UNIX_EPOCH)
20
- .unwrap_or_default()
21
- .as_millis() as i64
22
- }
23
-
24
- /// Sign a payload for queue transit. Returns a JSON string.
25
- pub fn sign_queue_message<T: Serialize>(
26
- payload: &T,
27
- private_key: &str,
28
- key_id: &str,
29
- sender: &str,
30
- recipient: Option<&str>,
31
- ttl_ms: Option<i64>,
32
- ) -> Result<String, Box<dyn std::error::Error>> {
33
- let content = serde_json::to_string(payload)?;
34
- let now = now_ms();
35
- let envelope = create_envelope(
36
- sender,
37
- recipient,
38
- "TASK",
39
- &content,
40
- None,
41
- None,
42
- now,
43
- ttl_ms.unwrap_or(DEFAULT_TTL_MS),
44
- );
45
- let signed = sign_envelope_ed25519(&envelope, private_key, key_id)
46
- .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
47
- // Re-serialize payload as Value so the QueueMessage wrapper holds both fields
48
- let payload_value = serde_json::to_value(payload)?;
49
- let msg = serde_json::json!({
50
- "envelope": signed,
51
- "payload": payload_value,
52
- });
53
- Ok(serde_json::to_string(&msg)?)
54
- }
55
-
56
- /// Verify and unwrap a queue message. Returns (payload_json_value, envelope).
57
- pub fn verify_queue_message(
58
- message: &str,
59
- public_key: &str,
60
- ) -> Result<(serde_json::Value, ProtocolEnvelope), Box<dyn std::error::Error>> {
61
- let wrapper: serde_json::Value = serde_json::from_str(message)?;
62
-
63
- let envelope: ProtocolEnvelope = serde_json::from_value(wrapper["envelope"].clone())
64
- .map_err(|e| -> Box<dyn std::error::Error> { format!("malformed envelope: {e}").into() })?;
65
-
66
- let now = now_ms();
67
- let diags = validate_envelope(&envelope, Some(now));
68
- if diags.iter().any(|d| d.level == "error") {
69
- return Err("envelope expired or invalid".into());
70
- }
71
-
72
- let valid = verify_envelope_ed25519(&envelope, public_key)
73
- .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
74
- if !valid {
75
- return Err("invalid signature".into());
76
- }
77
-
78
- Ok((wrapper["payload"].clone(), envelope))
79
- }
@@ -1,86 +0,0 @@
1
- //! Webhook binding — lightweight per-payload Ed25519/HMAC signing.
2
- //! Signs "${timestamp_ms}.${body}" to bind time and content together.
3
-
4
- use crate::{
5
- sign_canonical_payload_ed25519, sign_canonical_payload_hmac, verify_canonical_payload_ed25519,
6
- verify_canonical_payload_hmac,
7
- };
8
-
9
- pub const SIG_HEADER: &str = "x-7h3-sig";
10
- pub const TS_HEADER: &str = "x-7h3-ts";
11
- pub const DEFAULT_TTL_MS: u64 = 300_000;
12
-
13
- fn signing_payload(timestamp_ms: u64, body: &str) -> String {
14
- format!("{timestamp_ms}.{body}")
15
- }
16
-
17
- fn now_ms() -> u64 {
18
- std::time::SystemTime::now()
19
- .duration_since(std::time::UNIX_EPOCH)
20
- .unwrap_or_default()
21
- .as_millis() as u64
22
- }
23
-
24
- /// Sign a webhook payload with Ed25519. Returns (sig_header_value, ts_header_value).
25
- pub fn sign_webhook(
26
- body: &str,
27
- private_key: &str,
28
- ) -> Result<(String, String), Box<dyn std::error::Error>> {
29
- let ts = now_ms();
30
- let payload = signing_payload(ts, body);
31
- let sig = sign_canonical_payload_ed25519(&payload, private_key)
32
- .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
33
- Ok((sig, ts.to_string()))
34
- }
35
-
36
- /// Verify a webhook Ed25519 signature. Returns true if valid and not expired.
37
- pub fn verify_webhook(
38
- body: &str,
39
- sig: &str,
40
- ts_str: &str,
41
- public_key: &str,
42
- max_age_ms: Option<u64>,
43
- ) -> Result<bool, Box<dyn std::error::Error>> {
44
- let ts: u64 = ts_str
45
- .parse()
46
- .map_err(|_| -> Box<dyn std::error::Error> { "invalid timestamp".into() })?;
47
- let max_age = max_age_ms.unwrap_or(DEFAULT_TTL_MS);
48
- let now = now_ms();
49
- if now.saturating_sub(ts) > max_age {
50
- return Ok(false);
51
- }
52
- let payload = signing_payload(ts, body);
53
- verify_canonical_payload_ed25519(&payload, sig, public_key)
54
- .map_err(|e| -> Box<dyn std::error::Error> { e.into() })
55
- }
56
-
57
- /// Sign a webhook payload with HMAC-SHA256 shared secret.
58
- /// Returns (sig_header_value, ts_header_value).
59
- pub fn sign_webhook_hmac(
60
- body: &str,
61
- secret: &str,
62
- ) -> Result<(String, String), Box<dyn std::error::Error>> {
63
- let ts = now_ms();
64
- let payload = signing_payload(ts, body);
65
- let sig = sign_canonical_payload_hmac(&payload, secret);
66
- Ok((sig, ts.to_string()))
67
- }
68
-
69
- /// Verify an HMAC webhook signature.
70
- pub fn verify_webhook_hmac(
71
- body: &str,
72
- sig: &str,
73
- ts_str: &str,
74
- secret: &str,
75
- max_age_ms: Option<u64>,
76
- ) -> Result<bool, Box<dyn std::error::Error>> {
77
- let ts: u64 = ts_str
78
- .parse()
79
- .map_err(|_| -> Box<dyn std::error::Error> { "invalid timestamp".into() })?;
80
- let max_age = max_age_ms.unwrap_or(DEFAULT_TTL_MS);
81
- if now_ms().saturating_sub(ts) > max_age {
82
- return Ok(false);
83
- }
84
- let payload = signing_payload(ts, body);
85
- Ok(verify_canonical_payload_hmac(&payload, sig, secret))
86
- }
@@ -1,148 +0,0 @@
1
- use protocol_7h3::{
2
- canonicalize_envelope, decode_envelope, encode_envelope_compact, sign_canonical_payload_hmac,
3
- sign_envelope_ed25519, sign_envelope_hmac, validate_envelope, verify_canonical_payload_ed25519,
4
- verify_canonical_payload_hmac, verify_envelope_ed25519, verify_envelope_hmac, ProtocolEnvelope,
5
- };
6
- use serde::Deserialize;
7
- use std::fs;
8
- use std::path::PathBuf;
9
-
10
- #[derive(Debug, Deserialize)]
11
- struct VectorFixture {
12
- id: String,
13
- secret: String,
14
- #[serde(rename = "keyId")]
15
- key_id: String,
16
- envelope: ProtocolEnvelope,
17
- canonical: String,
18
- signature: String,
19
- }
20
-
21
- #[derive(Debug, Deserialize)]
22
- struct Fixtures {
23
- vectors: Vec<VectorFixture>,
24
- #[serde(rename = "ed25519Vectors", default)]
25
- ed25519_vectors: Vec<Ed25519VectorFixture>,
26
- }
27
-
28
- #[derive(Debug, Deserialize)]
29
- struct Ed25519VectorFixture {
30
- id: String,
31
- #[serde(rename = "keyId")]
32
- key_id: String,
33
- #[serde(rename = "publicKey")]
34
- public_key: String,
35
- #[serde(rename = "privateKey")]
36
- private_key: String,
37
- envelope: ProtocolEnvelope,
38
- canonical: String,
39
- signature: String,
40
- }
41
-
42
- fn load_fixtures() -> Fixtures {
43
- let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
44
- path.push("../../conformance/7h3_v0_1.json");
45
- let raw = fs::read_to_string(path).expect("conformance fixture should exist");
46
- serde_json::from_str(&raw).expect("conformance fixture should be valid JSON")
47
- }
48
-
49
- #[test]
50
- fn conformance_vectors_match_canonical_and_signatures() {
51
- let fixtures = load_fixtures();
52
- for vector in fixtures.vectors {
53
- let canonical = canonicalize_envelope(&vector.envelope);
54
- assert_eq!(
55
- canonical, vector.canonical,
56
- "canonical mismatch for {}",
57
- vector.id
58
- );
59
-
60
- let signature = sign_canonical_payload_hmac(&canonical, &vector.secret);
61
- assert_eq!(
62
- signature, vector.signature,
63
- "signature mismatch for {}",
64
- vector.id
65
- );
66
-
67
- let signed = sign_envelope_hmac(&vector.envelope, &vector.secret, &vector.key_id);
68
- assert!(verify_canonical_payload_hmac(
69
- &canonical,
70
- &vector.signature,
71
- &vector.secret
72
- ));
73
- assert!(verify_envelope_hmac(&signed, &vector.secret));
74
- assert!(!verify_envelope_hmac(
75
- &signed,
76
- &format!("{}-bad", vector.secret)
77
- ));
78
- }
79
- }
80
-
81
- #[test]
82
- fn compact_roundtrip_and_ttl_validation() {
83
- let fixtures = load_fixtures();
84
- for vector in fixtures.vectors {
85
- let signed = sign_envelope_hmac(&vector.envelope, &vector.secret, &vector.key_id);
86
- let encoded = encode_envelope_compact(&signed);
87
- let decoded = decode_envelope(&encoded).expect("compact decode should succeed");
88
- assert_eq!(
89
- canonicalize_envelope(&decoded),
90
- canonicalize_envelope(&signed)
91
- );
92
- assert_eq!(decoded.signature, signed.signature);
93
-
94
- let valid = validate_envelope(&decoded, Some(decoded.header.timestamp_ms + 1));
95
- assert!(
96
- valid.iter().all(|d| d.message != "Message TTL expired"),
97
- "valid envelope unexpectedly expired for {}",
98
- vector.id
99
- );
100
-
101
- let expired = validate_envelope(
102
- &decoded,
103
- Some(decoded.header.timestamp_ms + decoded.header.ttl_ms + 1),
104
- );
105
- assert!(
106
- expired.iter().any(|d| d.message == "Message TTL expired"),
107
- "expired envelope missing TTL diagnostic for {}",
108
- vector.id
109
- );
110
- }
111
- }
112
-
113
- #[test]
114
- fn ed25519_vectors_match_canonical_and_signatures() {
115
- let fixtures = load_fixtures();
116
- for vector in fixtures.ed25519_vectors {
117
- let canonical = canonicalize_envelope(&vector.envelope);
118
- assert_eq!(
119
- canonical, vector.canonical,
120
- "canonical mismatch for {}",
121
- vector.id
122
- );
123
-
124
- let signature = protocol_7h3::sign_canonical_payload_ed25519(&canonical, &vector.private_key)
125
- .expect("ed25519 sign should succeed");
126
- assert_eq!(
127
- signature, vector.signature,
128
- "ed25519 signature mismatch for {}",
129
- vector.id
130
- );
131
-
132
- assert!(
133
- verify_canonical_payload_ed25519(&canonical, &vector.signature, &vector.public_key)
134
- .expect("ed25519 verify should succeed"),
135
- "ed25519 verify failed for {}",
136
- vector.id
137
- );
138
-
139
- let signed = sign_envelope_ed25519(&vector.envelope, &vector.private_key, &vector.key_id)
140
- .expect("sign envelope ed25519 should succeed");
141
- assert!(
142
- verify_envelope_ed25519(&signed, &vector.public_key)
143
- .expect("verify envelope ed25519 should succeed"),
144
- "ed25519 envelope verify failed for {}",
145
- vector.id
146
- );
147
- }
148
- }
@@ -1,130 +0,0 @@
1
- use protocol_7h3::{
2
- create_aip_mcp_gateway_runtime, create_signed_task_from_jsonrpc,
3
- jsonrpc_response_from_envelope, AipMcpGatewayOptions, JsonRpcBridgeConfig, JsonRpcId,
4
- JsonRpcRequestLike,
5
- };
6
- use serde_json::json;
7
-
8
- #[test]
9
- fn jsonrpc_bridge_creates_signed_task_with_capability() {
10
- let request = JsonRpcRequestLike {
11
- jsonrpc: "2.0".to_string(),
12
- id: JsonRpcId::Number(7),
13
- method: "tools/call".to_string(),
14
- params: Some(json!({"name":"planner"})),
15
- };
16
-
17
- let config = JsonRpcBridgeConfig {
18
- recipient: Some("agent.worker".to_string()),
19
- allowed_methods: Some(vec!["tools/call".to_string()]),
20
- capability_prefix: "mcp.".to_string(),
21
- };
22
-
23
- let envelope = create_signed_task_from_jsonrpc(
24
- &request,
25
- "agent.gateway",
26
- "secret",
27
- "gateway-k1",
28
- 1_700_000_000_000,
29
- &config,
30
- Option::<fn(&JsonRpcRequestLike, &protocol_7h3::JsonRpcPolicyContext) -> bool>::None,
31
- Option::<fn(&str, &JsonRpcRequestLike, &protocol_7h3::JsonRpcPolicyContext) -> bool>::None,
32
- )
33
- .expect("bridge should produce envelope");
34
-
35
- assert_eq!(envelope.body.intent, "TASK");
36
- assert_eq!(envelope.body.capability.as_deref(), Some("mcp.tools/call"));
37
- assert_eq!(envelope.body.correlation_id.as_deref(), Some("7"));
38
- assert!(envelope.signature.is_some());
39
- }
40
-
41
- #[test]
42
- fn jsonrpc_bridge_blocks_disallowed_method() {
43
- let request = JsonRpcRequestLike {
44
- jsonrpc: "2.0".to_string(),
45
- id: JsonRpcId::String("abc".to_string()),
46
- method: "resources/read".to_string(),
47
- params: None,
48
- };
49
-
50
- let config = JsonRpcBridgeConfig {
51
- recipient: Some("agent.worker".to_string()),
52
- allowed_methods: Some(vec!["tools/call".to_string()]),
53
- capability_prefix: "mcp.".to_string(),
54
- };
55
-
56
- let error = create_signed_task_from_jsonrpc(
57
- &request,
58
- "agent.gateway",
59
- "secret",
60
- "gateway-k1",
61
- 1_700_000_000_000,
62
- &config,
63
- Option::<fn(&JsonRpcRequestLike, &protocol_7h3::JsonRpcPolicyContext) -> bool>::None,
64
- Option::<fn(&str, &JsonRpcRequestLike, &protocol_7h3::JsonRpcPolicyContext) -> bool>::None,
65
- )
66
- .expect_err("bridge should reject disallowed methods");
67
-
68
- assert!(error.contains("not allowed"));
69
- }
70
-
71
- #[test]
72
- fn gateway_runtime_handles_line_success_and_errors() {
73
- let options = AipMcpGatewayOptions {
74
- shared_secret: "gateway-secret".to_string(),
75
- ..AipMcpGatewayOptions::default()
76
- };
77
- let runtime = create_aip_mcp_gateway_runtime(options);
78
-
79
- let ok_line = json!({
80
- "jsonrpc": "2.0",
81
- "id": 1,
82
- "method": "tools/call",
83
- "params": {"name":"planner"}
84
- })
85
- .to_string();
86
- let ok_response = runtime
87
- .handle_line(&ok_line, 1_700_000_000_000)
88
- .expect("non-empty response expected");
89
- let ok_json: serde_json::Value =
90
- serde_json::from_str(&ok_response).expect("valid json response");
91
- assert_eq!(ok_json["jsonrpc"], "2.0");
92
- assert_eq!(ok_json["id"], 1);
93
- assert!(ok_json.get("result").is_some());
94
-
95
- let bad_line = json!({"bad":true}).to_string();
96
- let bad_response = runtime
97
- .handle_line(&bad_line, 1_700_000_000_001)
98
- .expect("error response expected");
99
- let bad_json: serde_json::Value =
100
- serde_json::from_str(&bad_response).expect("valid json response");
101
- assert_eq!(bad_json["error"]["code"], -32600);
102
- }
103
-
104
- #[test]
105
- fn jsonrpc_response_maps_error_intent() {
106
- let envelope = protocol_7h3::ProtocolEnvelope {
107
- header: protocol_7h3::ProtocolHeader {
108
- version: "7h3/0.1".to_string(),
109
- message_id: "m1".to_string(),
110
- timestamp_ms: 1,
111
- ttl_ms: 1,
112
- sender: "agent.worker".to_string(),
113
- recipient: Some("agent.gateway".to_string()),
114
- nonce: "n1".to_string(),
115
- },
116
- body: protocol_7h3::ProtocolBody {
117
- intent: "ERROR".to_string(),
118
- content: "permission denied".to_string(),
119
- capability: Some("mcp.tools/call".to_string()),
120
- correlation_id: Some("7".to_string()),
121
- },
122
- signature: None,
123
- };
124
-
125
- let response = jsonrpc_response_from_envelope(&envelope, JsonRpcId::Number(7));
126
- assert_eq!(response.jsonrpc, "2.0");
127
- assert_eq!(response.id, JsonRpcId::Number(7));
128
- assert!(response.result.is_none());
129
- assert_eq!(response.error.expect("error expected").code, -32000);
130
- }
@@ -1,201 +0,0 @@
1
- use protocol_7h3::{
2
- create_envelope,
3
- http::{sign_http_request, verify_http_envelope, EnvelopeInput, StaticKeyRegistry, VerifyFailReason, DEFAULT_HEADER},
4
- queue::{sign_queue_message, verify_queue_message},
5
- webhook::{sign_webhook, sign_webhook_hmac, verify_webhook, verify_webhook_hmac},
6
- ProtocolBody,
7
- };
8
- use std::collections::HashMap;
9
-
10
- // Ed25519 test keys from the conformance vectors.
11
- const TEST_PRIVATE_KEY: &str = "MC4CAQAwBQYDK2VwBCIEICheZbQGuDVb6hezIlcs0QnCHGxz6IhiLkC9M0qr8OOZ";
12
- const TEST_PUBLIC_KEY: &str = "MCowBQYDK2VwAyEA-mUFiTQtcKN4nnD19V_-Wyy4q19OivnAutRUPhOcC78";
13
- const TEST_SENDER: &str = "agent.ed";
14
-
15
- fn make_registry() -> StaticKeyRegistry {
16
- let mut keys = HashMap::new();
17
- keys.insert(TEST_SENDER.to_string(), TEST_PUBLIC_KEY.to_string());
18
- StaticKeyRegistry::new(keys)
19
- }
20
-
21
- fn make_input() -> EnvelopeInput {
22
- EnvelopeInput {
23
- sender: TEST_SENDER.to_string(),
24
- recipient: Some("agent.verify".to_string()),
25
- ttl_ms: 60_000,
26
- body: ProtocolBody {
27
- intent: "TASK".to_string(),
28
- content: "hello-http".to_string(),
29
- capability: None,
30
- correlation_id: None,
31
- },
32
- key_id: "key-1".to_string(),
33
- }
34
- }
35
-
36
- // ── HTTP tests ────────────────────────────────────────────────────────────────
37
-
38
- #[test]
39
- fn http_sign_produces_correct_header() {
40
- let (name, value) = sign_http_request(&make_input(), TEST_PRIVATE_KEY, None)
41
- .expect("sign_http_request should succeed");
42
- assert_eq!(name, DEFAULT_HEADER, "header name should be x-7h3-envelope");
43
- // value must be valid JSON containing an ED25519 signature
44
- let parsed: serde_json::Value =
45
- serde_json::from_str(&value).expect("header value must be valid JSON");
46
- assert_eq!(
47
- parsed["signature"]["alg"].as_str().unwrap(),
48
- "ED25519",
49
- "alg must be ED25519"
50
- );
51
- }
52
-
53
- #[test]
54
- fn http_verify_passes_on_valid_envelope() {
55
- let (name, value) = sign_http_request(&make_input(), TEST_PRIVATE_KEY, None)
56
- .expect("sign should succeed");
57
- let mut headers = HashMap::new();
58
- headers.insert(name, value);
59
-
60
- let registry = make_registry();
61
- let result = verify_http_envelope(&headers, &registry, None, false);
62
- assert!(result.is_ok(), "verification should pass: {:?}", result.err());
63
- assert_eq!(result.unwrap().header.sender, TEST_SENDER);
64
- }
65
-
66
- #[test]
67
- fn http_verify_fails_on_missing_header() {
68
- let registry = make_registry();
69
- let headers = HashMap::new();
70
- let result = verify_http_envelope(&headers, &registry, None, false);
71
- assert_eq!(result.unwrap_err(), VerifyFailReason::MissingHeader);
72
- }
73
-
74
- #[test]
75
- fn http_verify_fails_on_tampered_envelope() {
76
- let (name, value) = sign_http_request(&make_input(), TEST_PRIVATE_KEY, None)
77
- .expect("sign should succeed");
78
-
79
- // Tamper: change the sender in the JSON
80
- let mut parsed: serde_json::Value = serde_json::from_str(&value).unwrap();
81
- parsed["header"]["sender"] = serde_json::json!("attacker.agent");
82
- let tampered = serde_json::to_string(&parsed).unwrap();
83
-
84
- let mut headers = HashMap::new();
85
- headers.insert(name, tampered);
86
-
87
- // The registry won't know "attacker.agent"
88
- let registry = make_registry();
89
- let result = verify_http_envelope(&headers, &registry, None, false);
90
- assert!(
91
- matches!(
92
- result.unwrap_err(),
93
- VerifyFailReason::UnknownSender(_) | VerifyFailReason::InvalidSignature
94
- ),
95
- "expected UnknownSender or InvalidSignature"
96
- );
97
- }
98
-
99
- // ── Webhook Ed25519 tests ─────────────────────────────────────────────────────
100
-
101
- #[test]
102
- fn webhook_ed25519_sign_verify_roundtrip() {
103
- let body = r#"{"event":"order.created","id":42}"#;
104
- let (sig, ts) =
105
- sign_webhook(body, TEST_PRIVATE_KEY).expect("sign_webhook should succeed");
106
-
107
- let valid = verify_webhook(body, &sig, &ts, TEST_PUBLIC_KEY, None)
108
- .expect("verify_webhook should not error");
109
- assert!(valid, "webhook signature should verify");
110
- }
111
-
112
- #[test]
113
- fn webhook_hmac_sign_verify_roundtrip() {
114
- let secret = "shared-hmac-secret-for-test";
115
- let body = r#"{"event":"payment.captured"}"#;
116
-
117
- let (sig, ts) = sign_webhook_hmac(body, secret).expect("sign_webhook_hmac should succeed");
118
- let valid = verify_webhook_hmac(body, &sig, &ts, secret, None)
119
- .expect("verify_webhook_hmac should not error");
120
- assert!(valid, "HMAC webhook signature should verify");
121
- }
122
-
123
- #[test]
124
- fn webhook_expired_timestamp_returns_false() {
125
- let body = "test-payload";
126
- let secret = "any-secret";
127
- // Use a timestamp 10 minutes in the past (600_000 ms), default TTL is 300_000 ms
128
- let old_ts = {
129
- let now = std::time::SystemTime::now()
130
- .duration_since(std::time::UNIX_EPOCH)
131
- .unwrap()
132
- .as_millis() as u64;
133
- now - 600_000
134
- };
135
- let payload = format!("{old_ts}.{body}");
136
- let sig = protocol_7h3::sign_canonical_payload_hmac(&payload, secret);
137
-
138
- let valid = verify_webhook_hmac(body, &sig, &old_ts.to_string(), secret, None)
139
- .expect("should not error");
140
- assert!(!valid, "expired timestamp should return false");
141
- }
142
-
143
- // ── Queue tests ───────────────────────────────────────────────────────────────
144
-
145
- #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)]
146
- struct TestTask {
147
- action: String,
148
- priority: u32,
149
- }
150
-
151
- #[test]
152
- fn queue_sign_verify_roundtrip() {
153
- let task = TestTask {
154
- action: "compute".to_string(),
155
- priority: 5,
156
- };
157
-
158
- let msg = sign_queue_message(
159
- &task,
160
- TEST_PRIVATE_KEY,
161
- "key-1",
162
- TEST_SENDER,
163
- Some("agent.worker"),
164
- None,
165
- )
166
- .expect("sign_queue_message should succeed");
167
-
168
- let (payload_val, envelope) =
169
- verify_queue_message(&msg, TEST_PUBLIC_KEY).expect("verify_queue_message should succeed");
170
-
171
- assert_eq!(envelope.header.sender, TEST_SENDER);
172
-
173
- let recovered: TestTask =
174
- serde_json::from_value(payload_val).expect("payload should deserialize");
175
- assert_eq!(recovered, task);
176
- }
177
-
178
- #[test]
179
- fn queue_fails_on_tampered_message() {
180
- let task = TestTask {
181
- action: "delete-all".to_string(),
182
- priority: 99,
183
- };
184
- let msg = sign_queue_message(
185
- &task,
186
- TEST_PRIVATE_KEY,
187
- "key-1",
188
- TEST_SENDER,
189
- None,
190
- None,
191
- )
192
- .expect("sign should succeed");
193
-
194
- // Tamper with the payload section
195
- let mut parsed: serde_json::Value = serde_json::from_str(&msg).unwrap();
196
- parsed["envelope"]["header"]["sender"] = serde_json::json!("evil-agent");
197
- let tampered = serde_json::to_string(&parsed).unwrap();
198
-
199
- let result = verify_queue_message(&tampered, TEST_PUBLIC_KEY);
200
- assert!(result.is_err(), "tampered message should fail verification");
201
- }