Skip to main content

libkeri_http/
lib.rs

1//! KERI transport over HTTP, shared by libkeri consumers (libkeri-witness, libkeri-cli).
2//!
3//! Layering: `libkeri` is the synchronous, network-free core (no threads, locks
4//! or async). This crate is the only place KERI-over-HTTP lives, so consumers do
5//! not each reimplement it. libkeri never depends on this crate.
6//!
7//! Implemented so far: the CESR-over-HTTP codec (keripy `app/httping.py`) and
8//! an async [`client`] for OOBIs and witness receipts.
9//! Each KERI message travels as one HTTP request whose body is the message's
10//! JSON and whose `CESR-ATTACHMENT` header carries its CESR attachments.
11
12pub mod client;
13pub use client::{Client, ClientError, ReceiptResponse};
14
15/// Content type for CESR-over-HTTP requests (keripy `httping.CESR_CONTENT_TYPE`
16/// in 1.1 and 1.2).
17pub const CESR_CONTENT_TYPE: &str = "application/cesr+json";
18
19/// The same content type as keripy main (2.x) names it. keripy servers accept
20/// only their own name and answer 406 to the other.
21pub const CESR_CONTENT_TYPE_V2: &str = "application/cesr";
22
23/// Content type keripy uses for CESR stream responses (OOBIs, receipts).
24pub const CESR_STREAM_CONTENT_TYPE: &str = "application/json+cesr";
25
26/// Header carrying the CESR attachments for the JSON body
27/// (keripy `httping.CESR_ATTACHMENT_HEADER`).
28pub const CESR_ATTACHMENT_HEADER: &str = "CESR-ATTACHMENT";
29
30/// Header naming the destination AID (keripy `httping.CESR_DESTINATION_HEADER`).
31pub const CESR_DESTINATION_HEADER: &str = "CESR-DESTINATION";
32
33/// One KERI message split for HTTP transport.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct CesrRequest {
36    /// Serialized message body (JSON).
37    pub body: Vec<u8>,
38    /// CESR attachments, sent in the `CESR-ATTACHMENT` header.
39    pub attachments: String,
40}
41
42#[derive(Debug, thiserror::Error, PartialEq, Eq)]
43pub enum CodecError {
44    #[error("message does not start with a KERI version string")]
45    MissingVersion,
46    #[error("invalid size in version string: {0}")]
47    InvalidSize(String),
48    #[error("stream ends before the {0}-byte message body is complete")]
49    Truncated(usize),
50    #[error("attachments are not text-domain CESR (not valid UTF-8)")]
51    BinaryAttachments,
52}
53
54impl CesrRequest {
55    /// Rejoin body and attachments into a CESR stream for the libkeri parser
56    /// (keripy `parseCesrHttpRequest` + `bytearray(serder.raw) + attachments`).
57    pub fn to_stream(&self) -> Vec<u8> {
58        join(&self.body, &self.attachments)
59    }
60}
61
62/// Concatenate a message body and its attachments into a CESR stream.
63pub fn join(body: &[u8], attachments: &str) -> Vec<u8> {
64    let mut msg = Vec::with_capacity(body.len() + attachments.len());
65    msg.extend_from_slice(body);
66    msg.extend_from_slice(attachments.as_bytes());
67    msg
68}
69
70/// Split a CESR stream of one or more KERI JSON messages (with text-domain
71/// attachments) into one [`CesrRequest`] per message, as keripy's
72/// `streamCESRRequests` does before POSTing each one.
73pub fn split(stream: &[u8]) -> Result<Vec<CesrRequest>, CodecError> {
74    let mut out = Vec::new();
75    let mut rest = stream;
76    while !rest.is_empty() {
77        let size = message_size(rest)?;
78        if rest.len() < size {
79            return Err(CodecError::Truncated(size));
80        }
81        let (body, tail) = rest.split_at(size);
82        // Attachments run until the next message body. Text-domain CESR never
83        // contains '{', so that marks the start of the next message.
84        let att_len = tail.iter().position(|&b| b == b'{').unwrap_or(tail.len());
85        let (att, next) = tail.split_at(att_len);
86        let attachments = std::str::from_utf8(att)
87            .map_err(|_| CodecError::BinaryAttachments)?
88            .to_string();
89        out.push(CesrRequest {
90            body: body.to_vec(),
91            attachments,
92        });
93        rest = next;
94    }
95    Ok(out)
96}
97
98/// Size in bytes of the JSON message at the start of `msg`, from its KERI v1
99/// version string (`"v":"KERI10JSON0000fd_"`: proto(4) vers(2) kind(4) size(6 hex)).
100fn message_size(msg: &[u8]) -> Result<usize, CodecError> {
101    const PREFIX: &[u8] = b"{\"v\":\"";
102    if !msg.starts_with(PREFIX) {
103        return Err(CodecError::MissingVersion);
104    }
105    let start = PREFIX.len() + 10;
106    let hex = msg
107        .get(start..start + 6)
108        .ok_or(CodecError::MissingVersion)?;
109    let hex = std::str::from_utf8(hex).map_err(|_| CodecError::MissingVersion)?;
110    usize::from_str_radix(hex, 16).map_err(|_| CodecError::InvalidSize(hex.to_string()))
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    const ICP: &str = r#"{"v":"KERI10JSON0000fd_","t":"icp","d":"EIkO4CUmYXukX4auGU9yaFoQaIicfVZkazQ0A3IO5biT","i":"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha","s":"0","kt":"1","k":["BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha"],"nt":"0","n":[],"bt":"0","b":[],"c":[],"a":[]}"#;
118    const ICP_ATT: &str = "-AABAAAMlb78gUo1_gPDwxbXyERk2sW8B0mtiNuACutAygnY78PHYUjbPj1fSY1jyid8fl4-TXgLXPnDmeoUs1UO-H0A";
119    const RPY: &str = r#"{"v":"KERI10JSON0000fa_","t":"rpy","d":"ELSHJwBjsy41VvikaWd5cSC5hoooONVeVsImCzjzBQWP","dt":"2022-01-20T12:57:59.823350+00:00","r":"/loc/scheme","a":{"eid":"BBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha","scheme":"http","url":"http://127.0.0.1:5642/"}}"#;
120    const RPY_ATT: &str = "-VAi-CABBBilc4-L3tFUnfM_wJr4S4OJanAv_VmF_dJNN6vkf2Ha0BDRY23xEjEXaAJs7jPJt6uyxK8N2apNJitvn9mo0q4Gh8p7Pf2bAEp1Ufed5l0FdlLxV-Z2sMO8D7wVtA-m_QEM";
121
122    #[test]
123    fn split_and_join_round_trip() {
124        let stream = [ICP, ICP_ATT, RPY, RPY_ATT].concat().into_bytes();
125        let reqs = split(&stream).unwrap();
126        assert_eq!(reqs.len(), 2);
127        assert_eq!(reqs[0].body, ICP.as_bytes());
128        assert_eq!(reqs[0].attachments, ICP_ATT);
129        assert_eq!(reqs[1].body, RPY.as_bytes());
130        assert_eq!(reqs[1].attachments, RPY_ATT);
131        let rejoined: Vec<u8> = reqs.iter().flat_map(|r| r.to_stream()).collect();
132        assert_eq!(rejoined, stream);
133    }
134
135    #[test]
136    fn message_without_attachments() {
137        let reqs = split(ICP.as_bytes()).unwrap();
138        assert_eq!(reqs.len(), 1);
139        assert_eq!(reqs[0].attachments, "");
140    }
141
142    #[test]
143    fn rejects_bad_input() {
144        assert_eq!(split(b"-AAB"), Err(CodecError::MissingVersion));
145        assert_eq!(
146            split(&ICP.as_bytes()[..100]),
147            Err(CodecError::Truncated(0xfd))
148        );
149    }
150}