use crate::error::{Failure, Result};
use base64::Engine as _;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Content {
Described,
Raw {
max_bytes: usize,
},
}
#[derive(Debug, Clone, Copy)]
pub struct Policy {
pub content: Content,
}
pub fn describe(bytes: &[u8], policy: &Policy) -> Result<Value> {
let mut fields = Map::new();
fields.insert("kind".to_owned(), Value::from("binary"));
fields.insert("bytes".to_owned(), Value::from(bytes.len()));
fields.insert("appears_to_be".to_owned(), Value::from(sniff(bytes)));
fields.insert("signature".to_owned(), Value::from(signature(bytes)));
attach_content(&mut fields, bytes, policy)?;
Ok(Value::Object(fields))
}
pub fn describe_geometry(bytes: &[u8], policy: &Policy) -> Result<Value> {
if let Ok(text) = std::str::from_utf8(bytes) {
if text.chars().all(|character| !character.is_control()) {
return Ok(Value::from(text));
}
}
let mut fields = Map::new();
fields.insert("kind".to_owned(), Value::from("geometry"));
fields.insert("bytes".to_owned(), Value::from(bytes.len()));
fields.insert("form".to_owned(), Value::from("packed"));
fields.insert("signature".to_owned(), Value::from(signature(bytes)));
attach_content(&mut fields, bytes, policy)?;
Ok(Value::Object(fields))
}
fn attach_content(fields: &mut Map<String, Value>, bytes: &[u8], policy: &Policy) -> Result<()> {
let Content::Raw { max_bytes } = policy.content else {
return Ok(());
};
if bytes.len() > max_bytes {
return Err(Failure::limit(
"binary.above_ceiling",
format!(
"the value holds {} bytes and the ceiling for raw content is {max_bytes}",
bytes.len()
),
)
.with_detail("detail", format!("{} > {max_bytes}", bytes.len()))
.with_hint("raise the ceiling for raw binary content, or read the description instead"));
}
fields.insert("encoding".to_owned(), Value::from("base64"));
fields.insert(
"content".to_owned(),
Value::from(base64::engine::general_purpose::STANDARD.encode(bytes)),
);
Ok(())
}
fn signature(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
format!("sha256:{}", hex::encode(digest))
}
fn sniff(bytes: &[u8]) -> &'static str {
const SIGNATURES: [(&[u8], &str); 9] = [
(b"\x89PNG\r\n\x1a\n", "png"),
(b"\xff\xd8\xff", "jpeg"),
(b"GIF87a", "gif"),
(b"GIF89a", "gif"),
(b"RIFF", "riff"),
(b"%PDF-", "pdf"),
(b"PK\x03\x04", "zip"),
(b"\x1f\x8b", "gzip"),
(b"SQLite format 3\0", "sqlite"),
];
if bytes.is_empty() {
return "empty";
}
for (magic, name) in SIGNATURES {
if bytes.starts_with(magic) {
return name;
}
}
if std::str::from_utf8(bytes).is_ok() {
return "utf8_text";
}
"opaque"
}
#[cfg(test)]
mod tests {
use super::*;
fn described() -> Policy {
Policy {
content: Content::Described,
}
}
#[test]
fn a_byte_value_leaves_as_a_description_and_not_as_content() {
let payload = vec![7u8; 4096];
let described = describe(&payload, &described()).expect("describes");
assert_eq!(described["kind"], "binary");
assert_eq!(described["bytes"], 4096);
assert!(
described.get("content").is_none(),
"content must stay behind"
);
let text = described.to_string();
assert!(
text.len() < 200,
"the description must stay small: {}",
text.len()
);
}
#[test]
fn the_apparent_kind_comes_from_the_leading_bytes() {
let png = describe(b"\x89PNG\r\n\x1a\nrest", &described()).expect("describes");
assert_eq!(png["appears_to_be"], "png");
let opaque = describe(&[0x00, 0xff, 0xfe], &described()).expect("describes");
assert_eq!(opaque["appears_to_be"], "opaque");
}
#[test]
fn the_signature_is_the_same_for_the_same_bytes() {
let first = describe(b"same", &described()).expect("describes");
let second = describe(b"same", &described()).expect("describes");
assert_eq!(first["signature"], second["signature"]);
let other = describe(b"different", &described()).expect("describes");
assert_ne!(first["signature"], other["signature"]);
}
#[test]
fn content_leaves_only_under_request_and_below_the_ceiling() {
let policy = Policy {
content: Content::Raw { max_bytes: 16 },
};
let small = describe(b"tiny", &policy).expect("describes");
assert_eq!(small["encoding"], "base64");
assert_eq!(small["content"], "dGlueQ==");
}
#[test]
fn content_above_the_ceiling_is_refused_rather_than_emitted() {
let policy = Policy {
content: Content::Raw { max_bytes: 4 },
};
let failure = describe(&[0u8; 64], &policy).expect_err("must refuse");
assert_eq!(failure.code(), "binary.above_ceiling");
assert_eq!(failure.category(), crate::error::Category::Limit);
}
#[test]
fn a_spatial_value_the_server_already_rendered_leaves_as_that_text() {
let readable = describe_geometry(b"POINT(1 2)", &described()).expect("describes");
assert_eq!(readable, "POINT(1 2)");
let packed = describe_geometry(&[0x00, 0x01, 0x02, 0x03], &described()).expect("describes");
assert_eq!(packed["kind"], "geometry");
assert_eq!(packed["form"], "packed");
}
}