Skip to main content

gent_protocol/transport_exchange/
binary.rs

1//! V1 binary envelope on the existing authenticated exchange route. The first
2//! JSON response advertises support; an old client can ignore that header.
3//! All integers are big-endian. The 5-byte request/response magic precedes
4//! a u8 item count. A request item starts with a u8 method (GET=0, PUT=1),
5//! u16 path length and path bytes. A response item starts with its u16 status.
6//! Both end in a u8 compact flag (0 or 1), u32 body length and body bytes.
7//! Compact bodies use the signed object type implied by the mailbox operation.
8use super::{MAX_BYTES, MAX_OPERATIONS, MAX_PATH_BYTES, valid_route};
9use std::fmt;
10
11pub const MEDIA_TYPE: &str = "application/vnd.gent.exchange-v1";
12pub const SUPPORT_HEADER: &str = "x-gent-exchange";
13pub const SUPPORT_VALUE: &str = "binary-v1";
14/// A binary client that understands the extended /state body requests it
15/// explicitly. Earlier binary clients use the same exchange media type.
16pub const STATE_RETIREMENT_HEADER: &str = "x-gent-state-retirement";
17const REQUEST: &[u8; 5] = b"GNTX\x01";
18const RESPONSE: &[u8; 5] = b"GNTY\x01";
19
20#[derive(Debug)]
21pub struct InvalidExchange;
22impl fmt::Display for InvalidExchange {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        f.write_str("invalid binary mailbox exchange")
25    }
26}
27impl std::error::Error for InvalidExchange {}
28type Result<T> = std::result::Result<T, InvalidExchange>;
29
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct Operation {
32    pub method: String,
33    pub path: String,
34    pub compact: bool,
35    pub body: Vec<u8>,
36}
37impl Operation {
38    pub fn valid(&self) -> bool {
39        valid_route(&self.method, &self.path, !self.body.is_empty())
40            && (!self.compact || !self.body.is_empty())
41            && self.body.len() <= crate::transport_batch::MAX_BYTES
42    }
43}
44#[derive(Debug, PartialEq, Eq)]
45pub struct Item {
46    pub status: u16,
47    pub compact: bool,
48    pub body: Vec<u8>,
49}
50
51fn header(magic: &[u8; 5], count: usize) -> Result<Vec<u8>> {
52    if !(1..=MAX_OPERATIONS).contains(&count) {
53        return Err(InvalidExchange);
54    }
55    let mut out = magic.to_vec();
56    out.push(count as u8);
57    Ok(out)
58}
59fn body(out: &mut Vec<u8>, compact: bool, bytes: &[u8]) -> Result<()> {
60    if bytes.len() > MAX_BYTES || out.len() + 5 + bytes.len() > MAX_BYTES {
61        return Err(InvalidExchange);
62    }
63    out.push(u8::from(compact));
64    out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
65    out.extend_from_slice(bytes);
66    Ok(())
67}
68pub fn encode_request(ops: &[Operation]) -> Result<Vec<u8>> {
69    let mut out = header(REQUEST, ops.len())?;
70    for op in ops {
71        if !op.valid() {
72            return Err(InvalidExchange);
73        }
74        out.push(u8::from(op.method == "PUT"));
75        out.extend_from_slice(&(op.path.len() as u16).to_be_bytes());
76        out.extend_from_slice(op.path.as_bytes());
77        body(&mut out, op.compact, &op.body)?;
78    }
79    Ok(out)
80}
81pub fn encode_response(items: &[Item]) -> Result<Vec<u8>> {
82    let mut out = header(RESPONSE, items.len())?;
83    for item in items {
84        if !(100..=599).contains(&item.status) {
85            return Err(InvalidExchange);
86        }
87        out.extend_from_slice(&item.status.to_be_bytes());
88        body(&mut out, item.compact, &item.body)?;
89    }
90    Ok(out)
91}
92
93struct Reader<'a>(&'a [u8]);
94impl<'a> Reader<'a> {
95    fn take(&mut self, len: usize) -> Result<&'a [u8]> {
96        let (v, rest) = self.0.split_at_checked(len).ok_or(InvalidExchange)?;
97        self.0 = rest;
98        Ok(v)
99    }
100    fn array<const N: usize>(&mut self) -> Result<[u8; N]> {
101        self.take(N)?.try_into().map_err(|_| InvalidExchange)
102    }
103    fn flag(&mut self) -> Result<bool> {
104        match self.array()? {
105            [0] => Ok(false),
106            [1] => Ok(true),
107            _ => Err(InvalidExchange),
108        }
109    }
110    fn body(&mut self, limit: usize) -> Result<(bool, Vec<u8>)> {
111        let compact = self.flag()?;
112        let len = u32::from_be_bytes(self.array()?) as usize;
113        if len > limit {
114            return Err(InvalidExchange);
115        }
116        Ok((compact, self.take(len)?.to_vec()))
117    }
118}
119fn decode<T>(
120    bytes: &[u8],
121    magic: &[u8; 5],
122    mut read: impl FnMut(&mut Reader<'_>) -> Result<T>,
123) -> Result<Vec<T>> {
124    if bytes.len() > MAX_BYTES {
125        return Err(InvalidExchange);
126    }
127    let mut r = Reader(bytes);
128    if r.take(5)? != magic {
129        return Err(InvalidExchange);
130    }
131    let [count] = r.array()?;
132    if !(1..=MAX_OPERATIONS).contains(&(count as usize)) {
133        return Err(InvalidExchange);
134    }
135    let items = (0..count)
136        .map(|_| read(&mut r))
137        .collect::<Result<Vec<_>>>()?;
138    if !r.0.is_empty() {
139        return Err(InvalidExchange);
140    }
141    Ok(items)
142}
143pub fn decode_request(bytes: &[u8]) -> Result<Vec<Operation>> {
144    decode(bytes, REQUEST, |r| {
145        let method = if r.flag()? { "PUT" } else { "GET" };
146        let len = u16::from_be_bytes(r.array()?) as usize;
147        if len > MAX_PATH_BYTES {
148            return Err(InvalidExchange);
149        }
150        let path = std::str::from_utf8(r.take(len)?)
151            .map_err(|_| InvalidExchange)?
152            .to_owned();
153        let (compact, body) = r.body(crate::transport_batch::MAX_BYTES)?;
154        let op = Operation {
155            method: method.into(),
156            path,
157            compact,
158            body,
159        };
160        if !op.valid() {
161            return Err(InvalidExchange);
162        }
163        Ok(op)
164    })
165}
166pub fn decode_response(bytes: &[u8]) -> Result<Vec<Item>> {
167    decode(bytes, RESPONSE, |r| {
168        let status = u16::from_be_bytes(r.array()?);
169        if !(100..=599).contains(&status) {
170            return Err(InvalidExchange);
171        }
172        let (compact, body) = r.body(MAX_BYTES)?;
173        Ok(Item {
174            status,
175            compact,
176            body,
177        })
178    })
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    #[test]
185    fn rejects_invalid_framing_before_returning_any_operations() {
186        let op = Operation {
187            method: "PUT".into(),
188            path: "/v1/mailboxes/g/batch/1".into(),
189            compact: false,
190            body: vec![0, 255],
191        };
192        let bytes = encode_request(std::slice::from_ref(&op)).unwrap();
193        assert_eq!(decode_request(&bytes).unwrap(), vec![op.clone()]);
194        for end in 0..bytes.len() {
195            assert!(decode_request(&bytes[..end]).is_err());
196        }
197        for byte in [4, 5, 6, 7, 8, 9 + op.path.len(), 10 + op.path.len()] {
198            let mut bad = bytes.clone();
199            bad[byte] = 255;
200            assert!(decode_request(&bad).is_err());
201        }
202        let mut trailing = bytes.clone();
203        trailing.push(0);
204        assert!(decode_request(&trailing).is_err());
205        assert!(encode_request(&vec![op.clone(); MAX_OPERATIONS + 1]).is_err());
206        assert!(
207            encode_request(&[Operation {
208                path: "/v1/configuration/g".into(),
209                ..op
210            }])
211            .is_err()
212        );
213        let items = vec![
214            Item {
215                status: 200,
216                compact: true,
217                body: vec![255, 0],
218            },
219            Item {
220                status: 409,
221                compact: false,
222                body: vec![],
223            },
224        ];
225        let result = encode_response(&items).unwrap();
226        assert_eq!(decode_response(&result).unwrap(), items);
227        assert!(decode_response(&bytes).is_err());
228        assert!(decode_response(&result[..result.len() - 1]).is_err());
229    }
230}