gent_protocol/
transport_exchange.rs1use serde::{Deserialize, Serialize};
3pub mod binary;
4pub const VERSION: u8 = 1;
5pub const MAX_OPERATIONS: usize = 16;
6pub const MAX_BYTES: usize = 4 * 1024 * 1024;
7const MAX_PATH_BYTES: usize = 432;
8pub const ROUTE: &str = "/v2/exchange";
9
10#[derive(Clone, Serialize, Deserialize)]
11#[serde(deny_unknown_fields)]
12pub struct Operation {
13 pub method: String,
14 pub path: String,
15 #[serde(default, skip_serializing_if = "String::is_empty")]
16 pub body: String,
17}
18impl Operation {
19 pub fn valid(&self) -> bool {
20 valid_route(&self.method, &self.path, !self.body.is_empty())
21 }
22}
23fn valid_route(method: &str, path: &str, has_body: bool) -> bool {
24 if path.len() > MAX_PATH_BYTES {
25 return false;
26 }
27 let parts: Vec<_> = path.split('/').collect();
28 if !(4..=6).contains(&parts.len()) || !parts[0].is_empty() || parts[1..3] != ["v1", "mailboxes"]
29 {
30 return false;
31 }
32 let mailbox = parts[3];
33 if mailbox.is_empty()
34 || mailbox.len() > 384
35 || !mailbox
36 .bytes()
37 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
38 {
39 return false;
40 }
41 if method != "GET" && method != "PUT" {
42 return false;
43 }
44 if method == "GET" && has_body {
45 return false;
46 }
47 let sequence = |s: &str| {
48 s.parse::<u64>()
49 .is_ok_and(|n| n <= (1 << 53) - 2 && n.to_string() == s)
50 };
51 match parts.len() {
52 4 => method == "GET",
53 5 => {
54 sequence(parts[4])
55 || parts[4] == "checkpoint"
56 || (parts[4] == "state" && method == "GET")
57 || (parts[4] == "retire" && method == "PUT")
58 }
59 6 => parts[4] == "batch" && sequence(parts[5]),
60 _ => false,
61 }
62}
63#[derive(Serialize, Deserialize)]
64#[serde(deny_unknown_fields)]
65pub struct Request {
66 pub version: u8,
67 pub operations: Vec<Operation>,
68}
69#[derive(Serialize, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct ResultItem {
72 pub status: u16,
73 pub body: String,
74}
75#[derive(Serialize, Deserialize)]
76#[serde(deny_unknown_fields)]
77pub struct Response {
78 pub version: u8,
79 pub results: Vec<ResultItem>,
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85 #[test]
86 fn exchange_cannot_route_outside_opaque_mailboxes() {
87 for path in [
88 "/v1/mailboxes/a/0",
89 "/v1/mailboxes/a/batch/10",
90 "/v1/mailboxes/a/checkpoint",
91 "/v1/mailboxes/a/retire",
92 ] {
93 assert!(
94 Operation {
95 method: "PUT".into(),
96 path: path.into(),
97 body: String::new()
98 }
99 .valid()
100 );
101 }
102 for path in [
103 "https://elsewhere/v1/mailboxes/a/0",
104 "/v1/mailboxes/../0",
105 "/v1/mailboxes/a/01",
106 "/v1/mailboxes/a/0?other",
107 "/v1/configuration/commits",
108 ] {
109 assert!(
110 !Operation {
111 method: "PUT".into(),
112 path: path.into(),
113 body: String::new()
114 }
115 .valid()
116 );
117 }
118 }
119}