Skip to main content

protocol_7h3/
lib.rs

1pub mod http;
2pub mod keys;
3pub mod queue;
4pub mod webhook;
5
6use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7use base64::Engine;
8use ed25519_dalek::pkcs8::{DecodePrivateKey, DecodePublicKey};
9use ed25519_dalek::{Signature as Ed25519Signature, Signer, SigningKey, Verifier, VerifyingKey};
10use hmac::{Hmac, Mac};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use sha2::Sha256;
14
15type HmacSha256 = Hmac<Sha256>;
16
17#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
18pub struct ProtocolHeader {
19    pub version: String,
20    #[serde(rename = "messageId")]
21    pub message_id: String,
22    #[serde(rename = "timestampMs")]
23    pub timestamp_ms: i64,
24    #[serde(rename = "ttlMs")]
25    pub ttl_ms: i64,
26    pub sender: String,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub recipient: Option<String>,
29    pub nonce: String,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
33pub struct ProtocolBody {
34    pub intent: String,
35    pub content: String,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub capability: Option<String>,
38    #[serde(rename = "correlationId", skip_serializing_if = "Option::is_none")]
39    pub correlation_id: Option<String>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
43pub struct ProtocolSignature {
44    pub alg: String,
45    #[serde(rename = "keyId")]
46    pub key_id: String,
47    pub value: String,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
51pub struct ProtocolEnvelope {
52    pub header: ProtocolHeader,
53    pub body: ProtocolBody,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub signature: Option<ProtocolSignature>,
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct ProtocolDiagnostic {
60    pub level: String,
61    pub message: String,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65struct CompactSignature {
66    #[serde(skip_serializing_if = "Option::is_none")]
67    a: Option<String>,
68    k: String,
69    v: String,
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73struct CompactEnvelope {
74    v: String,
75    mid: String,
76    ts: i64,
77    ttl: i64,
78    s: String,
79    n: String,
80    i: String,
81    c: String,
82    #[serde(skip_serializing_if = "Option::is_none")]
83    r: Option<String>,
84    #[serde(skip_serializing_if = "Option::is_none")]
85    cap: Option<String>,
86    #[serde(skip_serializing_if = "Option::is_none")]
87    cid: Option<String>,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    sig: Option<CompactSignature>,
90}
91
92fn json_string<T: Serialize>(value: &T) -> String {
93    serde_json::to_string(value).expect("json serialization should not fail")
94}
95
96pub fn canonicalize_envelope(envelope: &ProtocolEnvelope) -> String {
97    let mut body_parts: Vec<String> = Vec::new();
98    if let Some(capability) = &envelope.body.capability {
99        body_parts.push(format!("\"capability\":{}", json_string(capability)));
100    }
101    body_parts.push(format!(
102        "\"content\":{}",
103        json_string(&envelope.body.content)
104    ));
105    if let Some(correlation_id) = &envelope.body.correlation_id {
106        body_parts.push(format!("\"correlationId\":{}", json_string(correlation_id)));
107    }
108    body_parts.push(format!("\"intent\":{}", json_string(&envelope.body.intent)));
109
110    let mut header_parts: Vec<String> = vec![
111        format!("\"messageId\":{}", json_string(&envelope.header.message_id)),
112        format!("\"nonce\":{}", json_string(&envelope.header.nonce)),
113    ];
114    if let Some(recipient) = &envelope.header.recipient {
115        header_parts.push(format!("\"recipient\":{}", json_string(recipient)));
116    }
117    header_parts.push(format!(
118        "\"sender\":{}",
119        json_string(&envelope.header.sender)
120    ));
121    header_parts.push(format!("\"timestampMs\":{}", envelope.header.timestamp_ms));
122    header_parts.push(format!("\"ttlMs\":{}", envelope.header.ttl_ms));
123    header_parts.push(format!(
124        "\"version\":{}",
125        json_string(&envelope.header.version)
126    ));
127
128    format!(
129        "{{\"body\":{{{}}},\"header\":{{{}}}}}",
130        body_parts.join(","),
131        header_parts.join(",")
132    )
133}
134
135/// Cryptographically secure random nonce (96 bits, hex-encoded).
136/// Nonces back replay protection, so they must come from the OS CSPRNG —
137/// never a timestamp or a non-cryptographic PRNG.
138pub fn random_nonce() -> String {
139    let mut buf = [0u8; 12];
140    getrandom::getrandom(&mut buf).expect("OS RNG should be available");
141    buf.iter().map(|b| format!("{b:02x}")).collect()
142}
143
144pub fn sign_canonical_payload_hmac(canonical_payload: &str, secret: &str) -> String {
145    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC key should be valid");
146    mac.update(canonical_payload.as_bytes());
147    let digest = mac.finalize().into_bytes();
148    URL_SAFE_NO_PAD.encode(digest)
149}
150
151pub fn verify_canonical_payload_hmac(
152    canonical_payload: &str,
153    signature: &str,
154    secret: &str,
155) -> bool {
156    let Ok(signature_bytes) = URL_SAFE_NO_PAD.decode(signature) else {
157        return false;
158    };
159    let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).expect("HMAC key should be valid");
160    mac.update(canonical_payload.as_bytes());
161    // verify_slice performs a constant-time comparison; a plain `==` on the
162    // encoded strings would leak matching-prefix length as a timing oracle.
163    mac.verify_slice(&signature_bytes).is_ok()
164}
165
166pub fn sign_canonical_payload_ed25519(
167    canonical_payload: &str,
168    private_key_pkcs8_base64url: &str,
169) -> Result<String, String> {
170    let private_der = URL_SAFE_NO_PAD
171        .decode(private_key_pkcs8_base64url)
172        .map_err(|_| "Invalid ED25519 private key encoding".to_string())?;
173    let signing_key = SigningKey::from_pkcs8_der(&private_der)
174        .map_err(|_| "Invalid ED25519 private key".to_string())?;
175    let signature = signing_key.sign(canonical_payload.as_bytes());
176    Ok(URL_SAFE_NO_PAD.encode(signature.to_bytes()))
177}
178
179pub fn verify_canonical_payload_ed25519(
180    canonical_payload: &str,
181    signature_base64url: &str,
182    public_key_spki_base64url: &str,
183) -> Result<bool, String> {
184    let public_der = URL_SAFE_NO_PAD
185        .decode(public_key_spki_base64url)
186        .map_err(|_| "Invalid ED25519 public key encoding".to_string())?;
187    let verifying_key = VerifyingKey::from_public_key_der(&public_der)
188        .map_err(|_| "Invalid ED25519 public key".to_string())?;
189
190    let signature_raw = URL_SAFE_NO_PAD
191        .decode(signature_base64url)
192        .map_err(|_| "Invalid ED25519 signature encoding".to_string())?;
193    let signature = Ed25519Signature::from_slice(&signature_raw)
194        .map_err(|_| "Invalid ED25519 signature".to_string())?;
195
196    Ok(verifying_key
197        .verify(canonical_payload.as_bytes(), &signature)
198        .is_ok())
199}
200
201pub fn sign_envelope_hmac(
202    envelope: &ProtocolEnvelope,
203    secret: &str,
204    key_id: &str,
205) -> ProtocolEnvelope {
206    let mut unsigned = envelope.clone();
207    unsigned.signature = None;
208    let canonical = canonicalize_envelope(&unsigned);
209    let signature = sign_canonical_payload_hmac(&canonical, secret);
210    let mut signed = unsigned;
211    signed.signature = Some(ProtocolSignature {
212        alg: "HS256".to_string(),
213        key_id: key_id.to_string(),
214        value: signature,
215    });
216    signed
217}
218
219pub fn verify_envelope_hmac(envelope: &ProtocolEnvelope, secret: &str) -> bool {
220    let Some(signature) = &envelope.signature else {
221        return false;
222    };
223    if signature.alg != "HS256" {
224        return false;
225    }
226    let mut unsigned = envelope.clone();
227    unsigned.signature = None;
228    let canonical = canonicalize_envelope(&unsigned);
229    verify_canonical_payload_hmac(&canonical, &signature.value, secret)
230}
231
232pub fn sign_envelope_ed25519(
233    envelope: &ProtocolEnvelope,
234    private_key_pkcs8_base64url: &str,
235    key_id: &str,
236) -> Result<ProtocolEnvelope, String> {
237    let mut unsigned = envelope.clone();
238    unsigned.signature = None;
239    let canonical = canonicalize_envelope(&unsigned);
240    let signature = sign_canonical_payload_ed25519(&canonical, private_key_pkcs8_base64url)?;
241    let mut signed = unsigned;
242    signed.signature = Some(ProtocolSignature {
243        alg: "ED25519".to_string(),
244        key_id: key_id.to_string(),
245        value: signature,
246    });
247    Ok(signed)
248}
249
250pub fn verify_envelope_ed25519(
251    envelope: &ProtocolEnvelope,
252    public_key_spki_base64url: &str,
253) -> Result<bool, String> {
254    let Some(signature) = &envelope.signature else {
255        return Ok(false);
256    };
257    if signature.alg != "ED25519" {
258        return Ok(false);
259    }
260    let mut unsigned = envelope.clone();
261    unsigned.signature = None;
262    let canonical = canonicalize_envelope(&unsigned);
263    verify_canonical_payload_ed25519(&canonical, &signature.value, public_key_spki_base64url)
264}
265
266pub fn encode_envelope_compact(envelope: &ProtocolEnvelope) -> String {
267    let compact = CompactEnvelope {
268        v: envelope.header.version.clone(),
269        mid: envelope.header.message_id.clone(),
270        ts: envelope.header.timestamp_ms,
271        ttl: envelope.header.ttl_ms,
272        s: envelope.header.sender.clone(),
273        n: envelope.header.nonce.clone(),
274        i: envelope.body.intent.clone(),
275        c: envelope.body.content.clone(),
276        r: envelope.header.recipient.clone(),
277        cap: envelope.body.capability.clone(),
278        cid: envelope.body.correlation_id.clone(),
279        sig: envelope.signature.as_ref().map(|sig| CompactSignature {
280            a: Some(sig.alg.clone()),
281            k: sig.key_id.clone(),
282            v: sig.value.clone(),
283        }),
284    };
285    serde_json::to_string(&compact).expect("compact envelope serialization should not fail")
286}
287
288pub fn decode_envelope(raw: &str) -> Result<ProtocolEnvelope, String> {
289    let parsed: Value =
290        serde_json::from_str(raw).map_err(|_| "Invalid JSON payload".to_string())?;
291
292    if parsed.get("header").is_some() && parsed.get("body").is_some() {
293        return serde_json::from_value(parsed)
294            .map_err(|_| "Envelope JSON shape is not recognized".to_string());
295    }
296
297    let compact: CompactEnvelope = serde_json::from_value(parsed)
298        .map_err(|_| "Envelope JSON shape is not recognized".to_string())?;
299    if compact.v != "7h3/0.1" {
300        return Err("Envelope JSON shape is not recognized".to_string());
301    }
302
303    Ok(ProtocolEnvelope {
304        header: ProtocolHeader {
305            version: compact.v,
306            message_id: compact.mid,
307            timestamp_ms: compact.ts,
308            ttl_ms: compact.ttl,
309            sender: compact.s,
310            recipient: compact.r,
311            nonce: compact.n,
312        },
313        body: ProtocolBody {
314            intent: compact.i,
315            content: compact.c,
316            capability: compact.cap,
317            correlation_id: compact.cid,
318        },
319        signature: compact.sig.map(|sig| ProtocolSignature {
320            alg: sig.a.unwrap_or_else(|| "HS256".to_string()),
321            key_id: sig.k,
322            value: sig.v,
323        }),
324    })
325}
326
327pub fn validate_envelope(
328    envelope: &ProtocolEnvelope,
329    now_ms: Option<i64>,
330) -> Vec<ProtocolDiagnostic> {
331    let mut diagnostics: Vec<ProtocolDiagnostic> = Vec::new();
332
333    if envelope.header.version != "7h3/0.1" {
334        diagnostics.push(ProtocolDiagnostic {
335            level: "error".to_string(),
336            message: format!("Unsupported protocol version '{}'", envelope.header.version),
337        });
338    }
339    if envelope.header.message_id.trim().is_empty() {
340        diagnostics.push(ProtocolDiagnostic {
341            level: "error".to_string(),
342            message: "Missing messageId".to_string(),
343        });
344    }
345    if envelope.header.sender.trim().is_empty() {
346        diagnostics.push(ProtocolDiagnostic {
347            level: "error".to_string(),
348            message: "Missing sender identity".to_string(),
349        });
350    }
351    if envelope.header.ttl_ms <= 0 {
352        diagnostics.push(ProtocolDiagnostic {
353            level: "error".to_string(),
354            message: "ttlMs must be greater than zero".to_string(),
355        });
356    }
357    if let Some(now) = now_ms {
358        if envelope.header.timestamp_ms + envelope.header.ttl_ms < now {
359            diagnostics.push(ProtocolDiagnostic {
360                level: "error".to_string(),
361                message: "Message TTL expired".to_string(),
362            });
363        }
364    }
365    if envelope.body.content.trim().is_empty() {
366        diagnostics.push(ProtocolDiagnostic {
367            level: "warning".to_string(),
368            message: "Empty content payload".to_string(),
369        });
370    }
371
372    diagnostics
373}
374
375#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
376#[serde(untagged)]
377pub enum JsonRpcId {
378    Null,
379    String(String),
380    Number(i64),
381}
382
383impl JsonRpcId {
384    fn as_string(&self) -> String {
385        match self {
386            JsonRpcId::Null => "null".to_string(),
387            JsonRpcId::String(value) => value.clone(),
388            JsonRpcId::Number(value) => value.to_string(),
389        }
390    }
391}
392
393#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
394pub struct JsonRpcRequestLike {
395    pub jsonrpc: String,
396    pub id: JsonRpcId,
397    pub method: String,
398    #[serde(skip_serializing_if = "Option::is_none")]
399    pub params: Option<Value>,
400}
401
402#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
403pub struct JsonRpcError {
404    pub code: i64,
405    pub message: String,
406    #[serde(skip_serializing_if = "Option::is_none")]
407    pub data: Option<Value>,
408}
409
410#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
411pub struct JsonRpcResponseLike {
412    pub jsonrpc: String,
413    pub id: JsonRpcId,
414    #[serde(skip_serializing_if = "Option::is_none")]
415    pub result: Option<Value>,
416    #[serde(skip_serializing_if = "Option::is_none")]
417    pub error: Option<JsonRpcError>,
418}
419
420#[derive(Debug, Clone, PartialEq, Eq)]
421pub struct JsonRpcPolicyContext {
422    pub intent: String,
423    pub recipient: Option<String>,
424    pub capability: String,
425    pub correlation_id: String,
426    pub created_at_ms: i64,
427}
428
429#[derive(Debug, Clone)]
430pub struct JsonRpcBridgeConfig {
431    pub recipient: Option<String>,
432    pub allowed_methods: Option<Vec<String>>,
433    pub capability_prefix: String,
434}
435
436impl Default for JsonRpcBridgeConfig {
437    fn default() -> Self {
438        Self {
439            recipient: None,
440            allowed_methods: None,
441            capability_prefix: "mcp.".to_string(),
442        }
443    }
444}
445
446pub fn create_envelope(
447    sender: &str,
448    recipient: Option<&str>,
449    intent: &str,
450    content: &str,
451    capability: Option<&str>,
452    correlation_id: Option<&str>,
453    now_ms: i64,
454    ttl_ms: i64,
455) -> ProtocolEnvelope {
456    ProtocolEnvelope {
457        header: ProtocolHeader {
458            version: "7h3/0.1".to_string(),
459            message_id: format!("msg-{}-{}", now_ms, sender),
460            timestamp_ms: now_ms,
461            ttl_ms,
462            sender: sender.to_string(),
463            recipient: recipient.map(|value| value.to_string()),
464            nonce: random_nonce(),
465        },
466        body: ProtocolBody {
467            intent: intent.to_string(),
468            content: content.to_string(),
469            capability: capability.map(|value| value.to_string()),
470            correlation_id: correlation_id.map(|value| value.to_string()),
471        },
472        signature: None,
473    }
474}
475
476pub fn create_signed_task_from_jsonrpc<F, G>(
477    request: &JsonRpcRequestLike,
478    sender: &str,
479    secret: &str,
480    key_id: &str,
481    now_ms: i64,
482    config: &JsonRpcBridgeConfig,
483    authorize: Option<F>,
484    rate_limit: Option<G>,
485) -> Result<ProtocolEnvelope, String>
486where
487    F: Fn(&JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool,
488    G: Fn(&str, &JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool,
489{
490    if request.jsonrpc != "2.0" {
491        return Err("JSON-RPC request must have jsonrpc='2.0'".to_string());
492    }
493    if request.method.trim().is_empty() {
494        return Err("JSON-RPC request must include method".to_string());
495    }
496    if let Some(allowlist) = &config.allowed_methods {
497        if !allowlist.iter().any(|method| method == &request.method) {
498            return Err(format!(
499                "JSON-RPC method '{}' is not allowed",
500                request.method
501            ));
502        }
503    }
504
505    let correlation_id = request.id.as_string();
506    let capability = format!("{}{}", config.capability_prefix, request.method);
507    let context = JsonRpcPolicyContext {
508        intent: "TASK".to_string(),
509        recipient: config.recipient.clone(),
510        capability: capability.clone(),
511        correlation_id: correlation_id.clone(),
512        created_at_ms: now_ms,
513    };
514
515    if let Some(authorize_fn) = authorize {
516        if !authorize_fn(request, &context) {
517            return Err(format!(
518                "JSON-RPC method '{}' is not authorized",
519                request.method
520            ));
521        }
522    }
523
524    let rate_key = request.method.clone();
525    if let Some(rate_limit_fn) = rate_limit {
526        if !rate_limit_fn(&rate_key, request, &context) {
527            return Err(format!(
528                "JSON-RPC method '{}' is rate-limited",
529                request.method
530            ));
531        }
532    }
533
534    let content = json_string(&serde_json::json!({
535        "method": request.method,
536        "params": request.params.clone().unwrap_or(Value::Null),
537    }));
538    let envelope = create_envelope(
539        sender,
540        config.recipient.as_deref(),
541        "TASK",
542        &content,
543        Some(&capability),
544        Some(&correlation_id),
545        now_ms,
546        60_000,
547    );
548    Ok(sign_envelope_hmac(&envelope, secret, key_id))
549}
550
551pub fn jsonrpc_response_from_envelope(
552    envelope: &ProtocolEnvelope,
553    id: JsonRpcId,
554) -> JsonRpcResponseLike {
555    if envelope.body.intent == "ERROR" {
556        return JsonRpcResponseLike {
557            jsonrpc: "2.0".to_string(),
558            id,
559            result: None,
560            error: Some(JsonRpcError {
561                code: -32000,
562                message: envelope.body.content.clone(),
563                data: Some(serde_json::json!({
564                    "capability": envelope.body.capability,
565                    "correlationId": envelope.body.correlation_id,
566                })),
567            }),
568        };
569    }
570
571    let result = serde_json::from_str::<Value>(&envelope.body.content)
572        .unwrap_or_else(|_| Value::String(envelope.body.content.clone()));
573    JsonRpcResponseLike {
574        jsonrpc: "2.0".to_string(),
575        id,
576        result: Some(result),
577        error: None,
578    }
579}
580
581#[derive(Debug, Clone)]
582pub struct AipMcpGatewayOptions {
583    pub shared_secret: String,
584    pub gateway_agent_id: String,
585    pub worker_agent_id: String,
586    pub allowed_methods: Vec<String>,
587    pub capability_prefix: String,
588}
589
590impl Default for AipMcpGatewayOptions {
591    fn default() -> Self {
592        Self {
593            shared_secret: "mcp-gateway-secret".to_string(),
594            gateway_agent_id: "agent.gateway".to_string(),
595            worker_agent_id: "agent.worker".to_string(),
596            allowed_methods: vec![
597                "tools/call".to_string(),
598                "resources/read".to_string(),
599                "prompts/get".to_string(),
600            ],
601            capability_prefix: "mcp.".to_string(),
602        }
603    }
604}
605
606#[derive(Debug, Clone)]
607pub struct AipMcpGatewayRuntime {
608    options: AipMcpGatewayOptions,
609}
610
611pub fn create_aip_mcp_gateway_runtime(options: AipMcpGatewayOptions) -> AipMcpGatewayRuntime {
612    AipMcpGatewayRuntime { options }
613}
614
615impl AipMcpGatewayRuntime {
616    fn error_response(id: Option<JsonRpcId>, code: i64, message: &str) -> String {
617        let response = JsonRpcResponseLike {
618            jsonrpc: "2.0".to_string(),
619            id: id.unwrap_or(JsonRpcId::Null),
620            result: None,
621            error: Some(JsonRpcError {
622                code,
623                message: message.to_string(),
624                data: None,
625            }),
626        };
627        json_string(&response)
628    }
629
630    pub fn handle_line(&self, line: &str, now_ms: i64) -> Option<String> {
631        let raw = line.trim();
632        if raw.is_empty() {
633            return None;
634        }
635
636        let request: JsonRpcRequestLike = match serde_json::from_str(raw) {
637            Ok(parsed) => parsed,
638            Err(_) => {
639                return Some(Self::error_response(None, -32600, "Invalid Request"));
640            }
641        };
642
643        let bridge_config = JsonRpcBridgeConfig {
644            recipient: Some(self.options.worker_agent_id.clone()),
645            allowed_methods: Some(self.options.allowed_methods.clone()),
646            capability_prefix: self.options.capability_prefix.clone(),
647        };
648
649        let outbound = match create_signed_task_from_jsonrpc(
650            &request,
651            &self.options.gateway_agent_id,
652            &self.options.shared_secret,
653            "gateway-k1",
654            now_ms,
655            &bridge_config,
656            Option::<fn(&JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool>::None,
657            Option::<fn(&str, &JsonRpcRequestLike, &JsonRpcPolicyContext) -> bool>::None,
658        ) {
659            Ok(envelope) => envelope,
660            Err(message) => {
661                let code = if message.contains("not allowed") {
662                    -32601
663                } else if message.contains("not authorized") {
664                    -32001
665                } else if message.contains("rate-limited") {
666                    -32002
667                } else {
668                    -32603
669                };
670                return Some(Self::error_response(Some(request.id), code, &message));
671            }
672        };
673
674        let worker_payload = serde_json::json!({
675            "ok": true,
676            "capability": outbound.body.capability,
677            "content": outbound.body.content,
678        });
679        let worker_envelope = create_envelope(
680            &self.options.worker_agent_id,
681            Some(&self.options.gateway_agent_id),
682            "RESULT",
683            &json_string(&worker_payload),
684            outbound.body.capability.as_deref(),
685            outbound.body.correlation_id.as_deref(),
686            now_ms,
687            60_000,
688        );
689        let signed_worker =
690            sign_envelope_hmac(&worker_envelope, &self.options.shared_secret, "worker-k1");
691
692        if !verify_envelope_hmac(&signed_worker, &self.options.shared_secret) {
693            return Some(Self::error_response(
694                Some(request.id),
695                -32603,
696                "AIP verification failed",
697            ));
698        }
699
700        let response = jsonrpc_response_from_envelope(&signed_worker, request.id);
701        Some(json_string(&response))
702    }
703}