@7h3/protocol 0.1.2 → 0.4.0

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 (230) hide show
  1. package/.dockerignore +19 -0
  2. package/.github/dependabot.yml +32 -0
  3. package/.github/workflows/ci.yml +31 -0
  4. package/.github/workflows/publish.yml +59 -0
  5. package/.github/workflows/scorecard.yml +37 -0
  6. package/7h3.example.yaml +125 -0
  7. package/CHANGELOG.md +92 -0
  8. package/CONTRIBUTING.md +82 -0
  9. package/Dockerfile +73 -0
  10. package/GOVERNANCE.md +62 -0
  11. package/README.md +323 -6
  12. package/SECURITY.md +70 -0
  13. package/bench-results/replay-cache-full-1777891033256.json +10 -0
  14. package/bench-results/replay-cache-full-1777896317488.json +10 -0
  15. package/bench-results/replay-cache-full-1777900993184.json +10 -0
  16. package/bench-results/replay-cache-full-1777901019285.json +10 -0
  17. package/bench-results/replay-cache-quick-1777870170126.json +10 -0
  18. package/bench-results/signature-profiles-quick-1775875160079.json +85 -0
  19. package/bench-results/signature-profiles-quick-1775983539716.json +85 -0
  20. package/bench-results/signature-profiles-quick-1776237913190.json +85 -0
  21. package/bench-results/wire-codecs-full-1777891019803.json +93 -0
  22. package/bench-results/wire-codecs-full-1777896260964.json +93 -0
  23. package/bench-results/wire-codecs-full-1777901004247.json +93 -0
  24. package/bench-results/wire-codecs-quick-1775972879056.json +93 -0
  25. package/bench-results/wire-codecs-quick-1775983541111.json +93 -0
  26. package/bench-results/wire-codecs-quick-1776237914299.json +93 -0
  27. package/bench-results/wire-codecs-quick-1777841285236.json +93 -0
  28. package/bench-results/wire-codecs-quick-1777841321772.json +93 -0
  29. package/bench-results/wire-codecs-quick-1777841330408.json +93 -0
  30. package/bench-results/wire-codecs-quick-1777852886082.json +93 -0
  31. package/bench-results/wire-codecs-quick-1777852988773.json +93 -0
  32. package/bench-results/wire-codecs-quick-1777870188095.json +93 -0
  33. package/bench-results/wire-codecs-quick-1777870263918.json +93 -0
  34. package/bench-results/wire-codecs-quick-1777870455034.json +93 -0
  35. package/bench-results/wire-codecs-quick-1778816163081.json +93 -0
  36. package/bench-results/wire-codecs-quick-1778843936130.json +93 -0
  37. package/bin/7h3.ts +385 -0
  38. package/conformance/7h3_v0_1.json +77 -0
  39. package/conformance/7h3_v0_1_binary.json +20 -0
  40. package/conformance/aip_v0_1_binary.json +20 -0
  41. package/docker-compose.yaml +77 -0
  42. package/docs/ADOPTION_PLAN.md +120 -0
  43. package/docs/AGENTS.md +77 -0
  44. package/docs/AIP_RFC_v0.1.md +97 -0
  45. package/docs/AI_DECISION_CARD.md +122 -0
  46. package/docs/AI_RUNTIME_POLICY.json +126 -0
  47. package/docs/AI_RUNTIME_POLICY.yaml +110 -0
  48. package/docs/BACKPRESSURE_TUNING.md +65 -0
  49. package/docs/BENCHMARK_CLAIM_MATRIX.md +42 -0
  50. package/docs/BENCHMARK_REPORT_TEMPLATE.md +169 -0
  51. package/docs/BINARY_CODEC_BENCH.md +23 -0
  52. package/docs/CLEAN_CLONE_RUNBOOK.md +36 -0
  53. package/docs/CLOCK_SKEW_POLICY.md +30 -0
  54. package/docs/DISTRIBUTED_REPLAY.md +142 -0
  55. package/docs/FUZZ_CAMPAIGN.md +121 -0
  56. package/docs/GATEWAY.md +195 -0
  57. package/docs/KEY_MANAGEMENT_POLICY.md +53 -0
  58. package/docs/KEY_REVOCATION.md +69 -0
  59. package/docs/MCP_WRAPPER.md +159 -0
  60. package/docs/MIGRATION_GUIDE.md +40 -0
  61. package/docs/OPERATORS.md +184 -0
  62. package/docs/PERF_REGRESSION_POLICY.md +34 -0
  63. package/docs/PROJECT_EXAMINATION_2026-05-31.md +219 -0
  64. package/docs/RELEASE_BENCHMARK_REPORT_2026-05-15.md +135 -0
  65. package/docs/RELEASE_GATE.md +25 -0
  66. package/docs/RELEASE_NOTES_v0.1.0.md +54 -0
  67. package/docs/SECURITY_REVIEW_2026-06-05.md +165 -0
  68. package/docs/TELEMETRY.md +41 -0
  69. package/docs/THREAT_MODEL.md +89 -0
  70. package/docs/VERSIONING_POLICY.md +30 -0
  71. package/docs/assets/banner.png +0 -0
  72. package/eslint.config.js +15 -0
  73. package/fuzz/ts/harness-decode.ts +136 -0
  74. package/fuzz/ts/harness-verify.ts +121 -0
  75. package/fuzz/ts/run.ts +35 -0
  76. package/mcp-server/README.md +38 -0
  77. package/mcp-server/package-lock.json +1187 -0
  78. package/mcp-server/package.json +35 -0
  79. package/mcp-server/src/index.ts +236 -0
  80. package/mcp-server/tsconfig.json +14 -0
  81. package/package.json +79 -13
  82. package/scripts/aip-framework-quickstart.ts +110 -0
  83. package/scripts/aip-mcp-gateway.ts +38 -0
  84. package/scripts/aip-mcp-wrap-demo.ts +72 -0
  85. package/scripts/aip-quickstart.ts +60 -0
  86. package/scripts/bench-diff.ts +118 -0
  87. package/scripts/bench-protocol-e2e.ts +937 -0
  88. package/scripts/bench-protocol-openloop.ts +1397 -0
  89. package/scripts/bench-replay-cache.ts +76 -0
  90. package/scripts/bench-signature-profiles.ts +180 -0
  91. package/scripts/bench-wire-codecs.ts +161 -0
  92. package/scripts/build-binary-conformance.ts +36 -0
  93. package/scripts/build-release-dashboard.ts +175 -0
  94. package/scripts/canary-rollout.ts +38 -0
  95. package/scripts/mcpGatewayCli.test.ts +116 -0
  96. package/scripts/prepare-aip-package.ts +88 -0
  97. package/scripts/regen-conformance-sigs.ts +18 -0
  98. package/scripts/release-gate.ts +19 -0
  99. package/scripts/validate-runtime-policy.ts +18 -0
  100. package/sdk/browser/index.test.ts +162 -0
  101. package/sdk/browser/index.ts +257 -0
  102. package/sdk/browser/package.json +13 -0
  103. package/sdk/go/go.mod +3 -0
  104. package/sdk/go/http.go +135 -0
  105. package/sdk/go/protocol.go +324 -0
  106. package/sdk/go/protocol_test.go +334 -0
  107. package/sdk/go/webhook.go +136 -0
  108. package/sdk/python/README.md +18 -0
  109. package/sdk/python/protocol_7h3/__init__.py +46 -0
  110. package/sdk/python/protocol_7h3/http.py +212 -0
  111. package/sdk/python/protocol_7h3/keys.py +149 -0
  112. package/sdk/python/protocol_7h3/protocol.py +525 -0
  113. package/sdk/python/protocol_7h3/queue.py +118 -0
  114. package/sdk/python/protocol_7h3/webhook.py +116 -0
  115. package/sdk/python/pyproject.toml +40 -0
  116. package/sdk/python/tests/test_conformance.py +110 -0
  117. package/sdk/python/tests/test_http.py +305 -0
  118. package/sdk/python/tests/test_keys.py +417 -0
  119. package/sdk/python/tests/test_queue.py +120 -0
  120. package/sdk/python/tests/test_webhook.py +345 -0
  121. package/sdk/rust/Cargo.lock +371 -0
  122. package/sdk/rust/Cargo.toml +25 -0
  123. package/sdk/rust/README.md +31 -0
  124. package/sdk/rust/fuzz/Cargo.toml +29 -0
  125. package/sdk/rust/fuzz/fuzz_targets/fuzz_canonicalize.rs +46 -0
  126. package/sdk/rust/fuzz/fuzz_targets/fuzz_decode.rs +11 -0
  127. package/sdk/rust/src/bin/aip_mcp_gateway.rs +59 -0
  128. package/sdk/rust/src/http.rs +145 -0
  129. package/sdk/rust/src/keys.rs +161 -0
  130. package/sdk/rust/src/lib.rs +688 -0
  131. package/sdk/rust/src/queue.rs +79 -0
  132. package/sdk/rust/src/webhook.rs +86 -0
  133. package/sdk/rust/tests/conformance.rs +148 -0
  134. package/sdk/rust/tests/gateway.rs +130 -0
  135. package/sdk/rust/tests/http_webhook_queue.rs +201 -0
  136. package/sdk/rust/tests/keys.rs +189 -0
  137. package/src/agentAdapter.test.ts +48 -0
  138. package/src/agentAdapter.ts +56 -0
  139. package/src/auditLog.test.ts +145 -0
  140. package/src/auditLog.ts +147 -0
  141. package/src/conformance.test.ts +136 -0
  142. package/src/conformanceVectors.ts +99 -0
  143. package/src/frameworkAdapters.test.ts +290 -0
  144. package/src/frameworkAdapters.ts +261 -0
  145. package/src/gateway.test.ts +343 -0
  146. package/src/gateway.ts +171 -0
  147. package/src/grpcBinding.test.ts +211 -0
  148. package/src/grpcBinding.ts +103 -0
  149. package/src/httpBinding.test.ts +376 -0
  150. package/src/httpBinding.ts +163 -0
  151. package/src/index.ts +32 -0
  152. package/src/keyInfra.test.ts +278 -0
  153. package/src/keyInfra.ts +228 -0
  154. package/src/keyRegistry.ts +59 -0
  155. package/src/keyRotation.test.ts +78 -0
  156. package/src/keyRotation.ts +72 -0
  157. package/src/mcpGateway.test.ts +129 -0
  158. package/src/mcpGateway.ts +250 -0
  159. package/src/mcpTransports.test.ts +92 -0
  160. package/src/mcpTransports.ts +169 -0
  161. package/src/mcpWrapper.test.ts +179 -0
  162. package/src/mcpWrapper.ts +206 -0
  163. package/src/policyEnforcer.test.ts +99 -0
  164. package/src/policyEnforcer.ts +169 -0
  165. package/src/policyTelemetryFeedback.test.ts +25 -0
  166. package/src/policyTelemetryFeedback.ts +38 -0
  167. package/src/protocol.bench.ts +37 -0
  168. package/src/protocol.test.ts +155 -0
  169. package/src/protocol.ts +413 -0
  170. package/src/protocolAgent.test.ts +105 -0
  171. package/src/protocolAgent.ts +169 -0
  172. package/src/protocolBinary.test.ts +165 -0
  173. package/src/protocolBinary.ts +312 -0
  174. package/src/protocolCapabilities.ts +70 -0
  175. package/src/protocolFuzz.advanced.test.ts +235 -0
  176. package/src/protocolFuzz.test.ts +111 -0
  177. package/src/protocolNegative.test.ts +97 -0
  178. package/src/protocolReplay.test.ts +71 -0
  179. package/src/protocolReplay.ts +194 -0
  180. package/src/protocolTransport.test.ts +556 -0
  181. package/src/protocolTransport.ts +483 -0
  182. package/src/queueBinding.test.ts +130 -0
  183. package/src/queueBinding.ts +102 -0
  184. package/src/rateLimiter.test.ts +96 -0
  185. package/src/rateLimiter.ts +46 -0
  186. package/src/redisClient.ts +140 -0
  187. package/src/redisIntegration.test.ts +134 -0
  188. package/src/replayStores.test.ts +141 -0
  189. package/src/replayStores.ts +82 -0
  190. package/src/revocation.test.ts +98 -0
  191. package/src/revocation.ts +0 -0
  192. package/src/routePolicy.test.ts +87 -0
  193. package/src/routePolicy.ts +72 -0
  194. package/src/runtimePolicy.test.ts +49 -0
  195. package/src/runtimePolicy.ts +81 -0
  196. package/src/runtimePolicyManager.test.ts +29 -0
  197. package/src/runtimePolicyManager.ts +50 -0
  198. package/src/runtimePolicyPresets.ts +43 -0
  199. package/src/signedResponse.test.ts +111 -0
  200. package/src/signedResponse.ts +83 -0
  201. package/src/webhookBinding.test.ts +144 -0
  202. package/src/webhookBinding.ts +115 -0
  203. package/src/wsBinding.test.ts +221 -0
  204. package/src/wsBinding.ts +100 -0
  205. package/tsconfig.json +15 -0
  206. package/tsconfig.lib.json +23 -0
  207. package/vite.lib.config.ts +16 -0
  208. package/agentAdapter.d.ts +0 -26
  209. package/conformanceVectors.d.ts +0 -20
  210. package/frameworkAdapters.d.ts +0 -72
  211. package/index.d.ts +0 -20
  212. package/index.js +0 -1702
  213. package/keyRotation.d.ts +0 -20
  214. package/mcpGateway.d.ts +0 -37
  215. package/mcpTransports.d.ts +0 -62
  216. package/mcpWrapper.d.ts +0 -83
  217. package/policyEnforcer.d.ts +0 -50
  218. package/policyTelemetryFeedback.d.ts +0 -11
  219. package/protocol.d.ts +0 -66
  220. package/protocolAgent.d.ts +0 -58
  221. package/protocolBinary.d.ts +0 -8
  222. package/protocolCapabilities.d.ts +0 -24
  223. package/protocolReplay.d.ts +0 -35
  224. package/protocolTransport.d.ts +0 -73
  225. package/redisClient.d.ts +0 -49
  226. package/replayStores.d.ts +0 -32
  227. package/revocation.d.ts +0 -71
  228. package/runtimePolicy.d.ts +0 -24
  229. package/runtimePolicyManager.d.ts +0 -15
  230. package/runtimePolicyPresets.d.ts +0 -11
@@ -0,0 +1,79 @@
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
+ }
@@ -0,0 +1,86 @@
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
+ }
@@ -0,0 +1,148 @@
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
+ }
@@ -0,0 +1,130 @@
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
+ }
@@ -0,0 +1,201 @@
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
+ }