Skip to main content

qualia_core_db/render/
texture_ingestion.rs

1//! Production texture ingestion for external/data URI and embedded images.
2//!
3//! Enforces strict MIME/magic signature checks, safe arithmetic, dimension and
4//! byte-budget ceilings, and failure-safe rollback.
5
6use super::texture_decode::TextureDecodeLimits;
7use super::texture_ktx2::KTX2_IDENTIFIER;
8use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
9use base64::Engine;
10use sha2::{Digest, Sha256};
11
12pub const PNG_SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];
13pub const JPEG_SIGNATURE: [u8; 3] = [0xFF, 0xD8, 0xFF];
14pub const WEBP_RIFF: [u8; 4] = *b"RIFF";
15pub const WEBP_MAGIC: [u8; 4] = *b"WEBP";
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum TextureIngestionError {
19    EmptySource,
20    EncodedInputTooLarge,
21    InvalidDataUri,
22    Base64DecodeFailed,
23    MimeSignatureMismatch,
24    UnsupportedMime,
25    ExternalUriRequiresResolver,
26}
27
28impl std::fmt::Display for TextureIngestionError {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        write!(f, "texture ingestion: {self:?}")
31    }
32}
33
34impl std::error::Error for TextureIngestionError {}
35
36/// Validate the binary file header against the declared MIME type.
37pub fn validate_image_signature(
38    mime_type: &str,
39    bytes: &[u8],
40) -> Result<(), TextureIngestionError> {
41    let clean_mime = mime_type.split(';').next().map(str::trim).unwrap_or("");
42    if clean_mime.eq_ignore_ascii_case("image/png") {
43        if bytes.len() < 8 || bytes[..8] != PNG_SIGNATURE {
44            return Err(TextureIngestionError::MimeSignatureMismatch);
45        }
46    } else if clean_mime.eq_ignore_ascii_case("image/jpeg")
47        || clean_mime.eq_ignore_ascii_case("image/jpg")
48    {
49        if bytes.len() < 3 || bytes[..3] != JPEG_SIGNATURE {
50            return Err(TextureIngestionError::MimeSignatureMismatch);
51        }
52    } else if clean_mime.eq_ignore_ascii_case("image/ktx2") {
53        if bytes.len() < 12 || bytes[..12] != KTX2_IDENTIFIER {
54            return Err(TextureIngestionError::MimeSignatureMismatch);
55        }
56    } else if clean_mime.eq_ignore_ascii_case("image/webp") {
57        if bytes.len() < 12 || bytes[..4] != WEBP_RIFF || bytes[8..12] != WEBP_MAGIC {
58            return Err(TextureIngestionError::MimeSignatureMismatch);
59        }
60    } else {
61        return Err(TextureIngestionError::UnsupportedMime);
62    }
63    Ok(())
64}
65
66fn percent_decode(input: &str) -> Option<Vec<u8>> {
67    let bytes = input.as_bytes();
68    let mut out = Vec::with_capacity(bytes.len());
69    let mut i = 0;
70    while i < bytes.len() {
71        if bytes[i] == b'%' {
72            if i + 2 >= bytes.len() {
73                return None;
74            }
75            let h1 = char::from(bytes[i + 1]).to_digit(16)? as u8;
76            let h2 = char::from(bytes[i + 2]).to_digit(16)? as u8;
77            out.push((h1 << 4) | h2);
78            i += 3;
79        } else {
80            out.push(bytes[i]);
81            i += 1;
82        }
83    }
84    Some(out)
85}
86
87/// Parse a `data:[mediatype][;base64],<data>` URI and decode the inner payload.
88pub fn parse_data_uri(
89    uri: &str,
90    max_bytes: usize,
91) -> Result<(String, Vec<u8>), TextureIngestionError> {
92    if !uri.starts_with("data:") {
93        return Err(TextureIngestionError::InvalidDataUri);
94    }
95    let rest = &uri[5..];
96    let comma_idx = rest
97        .find(',')
98        .ok_or(TextureIngestionError::InvalidDataUri)?;
99    let metadata = &rest[..comma_idx];
100    let payload_str = &rest[comma_idx + 1..];
101
102    let is_base64 = metadata.ends_with(";base64");
103    let mime_part = if is_base64 {
104        &metadata[..metadata.len() - 7]
105    } else {
106        metadata
107    };
108    let mime_type = if mime_part.is_empty() {
109        "application/octet-stream".to_string()
110    } else {
111        mime_part
112            .split(';')
113            .next()
114            .unwrap_or("")
115            .trim()
116            .to_ascii_lowercase()
117    };
118
119    let bytes = if is_base64 {
120        BASE64_STANDARD
121            .decode(payload_str.trim().as_bytes())
122            .map_err(|_| TextureIngestionError::Base64DecodeFailed)?
123    } else {
124        percent_decode(payload_str).ok_or(TextureIngestionError::InvalidDataUri)?
125    };
126
127    if bytes.len() > max_bytes {
128        return Err(TextureIngestionError::EncodedInputTooLarge);
129    }
130
131    validate_image_signature(&mime_type, &bytes)?;
132
133    Ok((mime_type, bytes))
134}
135
136/// A content-addressed, signature-verified ingested texture.
137#[derive(Clone, Debug, PartialEq, Eq)]
138pub struct IngestedTexture {
139    pub digest: [u8; 32],
140    pub mime_type: String,
141    pub bytes: Vec<u8>,
142}
143
144/// Ingest a texture from either a Data URI or raw encoded bytes with strict signature validation.
145pub fn ingest_texture_payload(
146    mime_type_or_uri: &str,
147    raw_bytes: Option<&[u8]>,
148    limits: TextureDecodeLimits,
149) -> Result<IngestedTexture, TextureIngestionError> {
150    let (mime_type, bytes) = if mime_type_or_uri.starts_with("data:") {
151        parse_data_uri(mime_type_or_uri, limits.max_encoded_bytes)?
152    } else if let Some(payload) = raw_bytes {
153        if payload.len() > limits.max_encoded_bytes {
154            return Err(TextureIngestionError::EncodedInputTooLarge);
155        }
156        validate_image_signature(mime_type_or_uri, payload)?;
157        (mime_type_or_uri.to_string(), payload.to_vec())
158    } else {
159        return Err(TextureIngestionError::ExternalUriRequiresResolver);
160    };
161
162    let digest: [u8; 32] = Sha256::digest(&bytes).into();
163    Ok(IngestedTexture {
164        digest,
165        mime_type,
166        bytes,
167    })
168}
169
170#[cfg(test)]
171#[path = "texture_ingestion_tests.rs"]
172mod tests;