mariadb-cli 0.1.1

One-shot agent-native command line client for MariaDB servers
Documentation
//! Raw bytes as a short description, never as content by default.
//!
//! A column holding an image is read like any other column. If its content
//! came back whole, one ordinary query would fill the answer and leave no room
//! for the rows the caller actually wanted. So a byte value becomes a short
//! description: how large it is, what it looks like, and a signature that
//! identifies it. The content only leaves under an explicit request, and even
//! then only below a ceiling the caller sets.

use crate::error::{Failure, Result};
use base64::Engine as _;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

/// Whether the content itself leaves, and under which ceiling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Content {
    /// Only the description leaves. This is the default.
    Described,
    /// The content leaves as text, up to this many bytes.
    Raw {
        /// Ceiling on the byte count that may be encoded.
        max_bytes: usize,
    },
}

/// Everything that shapes a byte value on its way out.
///
/// There is deliberately no `Default`. The field is a published setting, and a
/// default written here would be a second copy of a value the registry already
/// carries — which is exactly how a published setting comes to have no effect.
/// A value of this type can only be built from the registry, so a call site
/// cannot quietly opt out of the caller's configuration.
#[derive(Debug, Clone, Copy)]
pub struct Policy {
    /// Whether the content itself leaves.
    pub content: Content,
}

/// Describes a byte value, adding its content only when asked.
///
/// # Errors
///
/// Returns a limit failure when the content was requested and the value is
/// larger than the ceiling, so an oversized answer is refused rather than
/// emitted.
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))
}

/// Describes a spatial value.
///
/// When the server already returned the readable form, that text is what
/// leaves. When it returned its packed form instead, the description leaves,
/// because inventing a readable form here would mean re-implementing the
/// server's own renderer and risking a text it would not agree with.
///
/// # Errors
///
/// Returns a limit failure when the content was requested and the value is
/// larger than the ceiling.
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))
}

/// Adds the content when the policy asks for it and the ceiling allows it.
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(())
}

/// The stable signature of a byte value.
fn signature(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    format!("sha256:{}", hex::encode(digest))
}

/// The apparent kind of a byte value, from its leading bytes.
///
/// This is a hint for the reader and never changes how the value is handled.
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::*;

    /// The published shape, written here rather than derived, because a test
    /// asserting the registry's own numbers would only be restating them.
    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");
    }
}