1use crate::error::{Failure, Result};
11use base64::Engine as _;
12use serde_json::{Map, Value};
13use sha2::{Digest, Sha256};
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Content {
18 Described,
20 Raw {
22 max_bytes: usize,
24 },
25}
26
27#[derive(Debug, Clone, Copy)]
35pub struct Policy {
36 pub content: Content,
38}
39
40pub fn describe(bytes: &[u8], policy: &Policy) -> Result<Value> {
48 let mut fields = Map::new();
49 fields.insert("kind".to_owned(), Value::from("binary"));
50 fields.insert("bytes".to_owned(), Value::from(bytes.len()));
51 fields.insert("appears_to_be".to_owned(), Value::from(sniff(bytes)));
52 fields.insert("signature".to_owned(), Value::from(signature(bytes)));
53 attach_content(&mut fields, bytes, policy)?;
54 Ok(Value::Object(fields))
55}
56
57pub fn describe_geometry(bytes: &[u8], policy: &Policy) -> Result<Value> {
69 if let Ok(text) = std::str::from_utf8(bytes) {
70 if text.chars().all(|character| !character.is_control()) {
71 return Ok(Value::from(text));
72 }
73 }
74 let mut fields = Map::new();
75 fields.insert("kind".to_owned(), Value::from("geometry"));
76 fields.insert("bytes".to_owned(), Value::from(bytes.len()));
77 fields.insert("form".to_owned(), Value::from("packed"));
78 fields.insert("signature".to_owned(), Value::from(signature(bytes)));
79 attach_content(&mut fields, bytes, policy)?;
80 Ok(Value::Object(fields))
81}
82
83fn attach_content(fields: &mut Map<String, Value>, bytes: &[u8], policy: &Policy) -> Result<()> {
85 let Content::Raw { max_bytes } = policy.content else {
86 return Ok(());
87 };
88 if bytes.len() > max_bytes {
89 return Err(Failure::limit(
90 "binary.above_ceiling",
91 format!(
92 "the value holds {} bytes and the ceiling for raw content is {max_bytes}",
93 bytes.len()
94 ),
95 )
96 .with_detail("detail", format!("{} > {max_bytes}", bytes.len()))
97 .with_hint("raise the ceiling for raw binary content, or read the description instead"));
98 }
99 fields.insert("encoding".to_owned(), Value::from("base64"));
100 fields.insert(
101 "content".to_owned(),
102 Value::from(base64::engine::general_purpose::STANDARD.encode(bytes)),
103 );
104 Ok(())
105}
106
107fn signature(bytes: &[u8]) -> String {
109 let digest = Sha256::digest(bytes);
110 format!("sha256:{}", hex::encode(digest))
111}
112
113fn sniff(bytes: &[u8]) -> &'static str {
117 const SIGNATURES: [(&[u8], &str); 9] = [
118 (b"\x89PNG\r\n\x1a\n", "png"),
119 (b"\xff\xd8\xff", "jpeg"),
120 (b"GIF87a", "gif"),
121 (b"GIF89a", "gif"),
122 (b"RIFF", "riff"),
123 (b"%PDF-", "pdf"),
124 (b"PK\x03\x04", "zip"),
125 (b"\x1f\x8b", "gzip"),
126 (b"SQLite format 3\0", "sqlite"),
127 ];
128 if bytes.is_empty() {
129 return "empty";
130 }
131 for (magic, name) in SIGNATURES {
132 if bytes.starts_with(magic) {
133 return name;
134 }
135 }
136 if std::str::from_utf8(bytes).is_ok() {
137 return "utf8_text";
138 }
139 "opaque"
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145
146 fn described() -> Policy {
149 Policy {
150 content: Content::Described,
151 }
152 }
153
154 #[test]
155 fn a_byte_value_leaves_as_a_description_and_not_as_content() {
156 let payload = vec![7u8; 4096];
157 let described = describe(&payload, &described()).expect("describes");
158 assert_eq!(described["kind"], "binary");
159 assert_eq!(described["bytes"], 4096);
160 assert!(
161 described.get("content").is_none(),
162 "content must stay behind"
163 );
164 let text = described.to_string();
165 assert!(
166 text.len() < 200,
167 "the description must stay small: {}",
168 text.len()
169 );
170 }
171
172 #[test]
173 fn the_apparent_kind_comes_from_the_leading_bytes() {
174 let png = describe(b"\x89PNG\r\n\x1a\nrest", &described()).expect("describes");
175 assert_eq!(png["appears_to_be"], "png");
176 let opaque = describe(&[0x00, 0xff, 0xfe], &described()).expect("describes");
177 assert_eq!(opaque["appears_to_be"], "opaque");
178 }
179
180 #[test]
181 fn the_signature_is_the_same_for_the_same_bytes() {
182 let first = describe(b"same", &described()).expect("describes");
183 let second = describe(b"same", &described()).expect("describes");
184 assert_eq!(first["signature"], second["signature"]);
185 let other = describe(b"different", &described()).expect("describes");
186 assert_ne!(first["signature"], other["signature"]);
187 }
188
189 #[test]
190 fn content_leaves_only_under_request_and_below_the_ceiling() {
191 let policy = Policy {
192 content: Content::Raw { max_bytes: 16 },
193 };
194 let small = describe(b"tiny", &policy).expect("describes");
195 assert_eq!(small["encoding"], "base64");
196 assert_eq!(small["content"], "dGlueQ==");
197 }
198
199 #[test]
200 fn content_above_the_ceiling_is_refused_rather_than_emitted() {
201 let policy = Policy {
202 content: Content::Raw { max_bytes: 4 },
203 };
204 let failure = describe(&[0u8; 64], &policy).expect_err("must refuse");
205 assert_eq!(failure.code(), "binary.above_ceiling");
206 assert_eq!(failure.category(), crate::error::Category::Limit);
207 }
208
209 #[test]
210 fn a_spatial_value_the_server_already_rendered_leaves_as_that_text() {
211 let readable = describe_geometry(b"POINT(1 2)", &described()).expect("describes");
212 assert_eq!(readable, "POINT(1 2)");
213
214 let packed = describe_geometry(&[0x00, 0x01, 0x02, 0x03], &described()).expect("describes");
215 assert_eq!(packed["kind"], "geometry");
216 assert_eq!(packed["form"], "packed");
217 }
218}