686 lines · 27.0 KB · RustRaw
//! SHARED ALBUMS, the phone's half (SHARED CORE 1, 27 Nov//! 2026; the server's half is apps/business src/space/, its design//! assets/design/albums/SHARED-SPACE.md). A shared space holds sealed records//! and sealed files; the server never holds a key that opens one.//!//! ```text//! signing key = Ed25519(seed = HKDF-SHA256(ikm=DK, salt=database_id, info="cotton-sign-v1"))//! epoch key (e) = a set key (super::set), wrapped to each member's sharing key: w1(share_pub, key || "set\n" space "\n" e)//! record key = 32 random bytes per record//! record.key = g1:e:… seal_in_set(epoch key, space, e, record id, record key)//! record.body = "r1:" b64url(nonce12 || AES-256-GCM(record key, body JSON, aad))//! aad = "r1|" space "|" record id "|" kind "|" album//! record.sig = "s1:" b64url(Ed25519(signing key, message))//! message = "cotton-space-record-v3\n" space "\n" id "\n" kind "\n" album "\n" files joined "," "\n"//! version "\n" prev "\n" signer "\n" mark "\n" record.body//! mark = epoch sealed "|" roster seq "|" roster head hash "|" n "|" gone joined ","//! (n: the signer's own count of records and deletions in this space; gone: the counts it makes//! obsolete, each "member:n" — the version it replaces, or the record it deletes)//! prev = record_hash of the version before ("" for version 1); signer = the signer's member id//! deletion = "s1:" Ed25519(signing key, "cotton-space-tomb-v2\n" space "\n" id "\n" version "\n" prev "\n" signer//! "\n" mark "\n" whose) (whose: the deleted record's signer, whose counts `gone` covers)//! file = f1 under its own random FileKey (carried only in the item's body), object key "spaces/" space "/" file//! link secret = 32 random bytes, only ever after the link's '#'//! link private = HKDF-SHA256(ikm=secret, salt="", info="cotton-space-link-v1") (X25519, clamped on use)//! auth token = b64url(HKDF-SHA256(ikm=secret, salt="", info="cotton-space-link-auth-v1"))//! auth_hash = hex(SHA-256(auth token)) (all the server keeps)//! ```//!//! - **The signature covers the space id**, the record id, its kind, album and//! files and the whole sealed body, so a record moved to another space,//! another id or another album fails to verify, and a body nobody signed//! is shown as not verified. The record's `key` is not signed: it is//! re-wrapped on every epoch move, and a key that is not the record's own//! opens nothing (the body's AEAD).//! - **Re-wrapping never re-contents:** an epoch move changes only `key`//! ([`rewrap_record_key`]); body and signature stay byte for byte.//! - **A member's keys come from the space's member list** (which the server//! took from that member's own object), never typed in. What that still//! trusts the server for is said in DECISIONS.md.//! - **Nothing with metadata is sealed:** [`metadata_in`] names any EXIF, XMP, MPF, QuickTime `udta`/`meta`,//! IPTC or GPS left in a JPEG or PNG, and the shell's methods refuse to seal//! one (the shell strips them; this is the check that it did).use std::collections::BTreeMap;use std::io::{Read, Write};use aes_gcm::aead::{Aead, Payload};use aes_gcm::{Aes256Gcm, Key, KeyInit, Nonce};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engine as _;pub use ed25519_dalek::SigningKey;use ed25519_dalek::{Signature, Signer, Verifier, VerifyingKey};use hkdf::Hkdf;use rand::RngCore;use serde_json::Value;use sha2::{Digest, Sha256};use zeroize::{ZeroizeOnDrop, Zeroizing};use super::file::{open_file, seal_file, FileKey};use super::keys::{hkdf, DataKey};use super::set::{open_in_set, open_set_key, seal_in_set, wrap_set_key, SetKey};use super::{plain_field, SealError, NONCE_LEN};use crate::vault::wrap::public_of;pub const SIGN_INFO: &str = "cotton-sign-v1";pub const BODY_PREFIX: &str = "r1:";pub const SIG_PREFIX: &str = "s1:";const SIG_DOMAIN: &str = "cotton-space-record-v3";const TOMB_DOMAIN: &str = "cotton-space-tomb-v2";/// What every record and deletion says about when it was made (SHARED 5): the epoch it was sealed under, the roster/// head it saw (a phone that sees a later head than its own is behind), and the signer's own running count of/// statements in this space with the counts this one makes obsolete (a hole in someone's counts is a withheld record).#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]pub struct Mark { pub epoch: u32, pub roster_seq: u64, pub roster: String, pub n: u64, #[serde(default)] pub gone: Vec<String>,}impl Mark { fn line(&self) -> String { format!("{}|{}|{}|{}|{}", self.epoch, self.roster_seq, self.roster, self.n, self.gone.join(",")) }}const LINK_INFO: &[u8] = b"cotton-space-link-v1";const LINK_AUTH_INFO: &[u8] = b"cotton-space-link-auth-v1";/// The largest body the server keeps (SHARED-SPACE.md: 64 KB, sealed).pub const BODY_LIMIT: usize = 60 * 1024;fn b64(bytes: &[u8]) -> String { URL_SAFE_NO_PAD.encode(bytes)}fn unb64(text: &str) -> Result<Vec<u8>, SealError> { URL_SAFE_NO_PAD .decode(text) .map_err(|_| SealError::DoesNotOpen)}// ── the signing key ─────────────────────────────────────────────────────/// This person's signing key, derived from their DK as the sharing key is: every phone holding the DK holds it.pub fn signing_key(dk: &DataKey, database_id: &str) -> Result<SigningKey, SealError> { plain_field("database", database_id)?; let seed = hkdf(dk, database_id, SIGN_INFO)?; Ok(SigningKey::from_bytes(&seed))}/// The signing key's public half as the wire carries it (what `POST /v1/send/key {sign}` posts).pub fn signing_public(dk: &DataKey, database_id: &str) -> Result<String, SealError> { Ok(b64(signing_key(dk, database_id)? .verifying_key() .as_bytes()))}// ── records ─────────────────────────────────────────────────────────────/// What a record is outside its sealed body: everything the signature binds.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Head<'a> { pub space: &'a str, pub id: &'a str, pub kind: &'a str, pub album: &'a str, pub files: &'a [String], /// The adder's version of the record, 1 upward: a phone refuses one lower than it saw. pub version: u64, /// [`record_hash`] of the version before; empty for version 1. pub prev: &'a str, /// The signer's member id (the roster names their key): the name a phone shows is this one, verified. pub signer: &'a str, pub mark: &'a Mark,}impl Head<'_> { fn check(&self) -> Result<(), SealError> { plain_field("space", self.space)?; plain_field("record", self.id)?; plain_field("album", self.album)?; if self.kind != "album" && self.kind != "item" { return Err(SealError::BadInput(format!( "a record is an album or an item, not {:?}", self.kind ))); } for f in self.files { plain_field("file", f)?; } plain_field("signer", self.signer)?; if self.mark.n == 0 || self.mark.roster.contains(['\n', '|']) || self.mark.gone.iter().any(|g| g.contains(['\n', '|', ','])) { return Err(SealError::BadInput("a record's mark names its count (1 upward) and the roster head".into())); } if self.version == 0 || self.prev.contains('\n') || (self.version == 1) != self.prev.is_empty() { return Err(SealError::BadInput("a record's version is 1 with no previous hash, or more with one".into())); } Ok(()) } fn aad(&self) -> Vec<u8> { format!("r1|{}|{}|{}|{}", self.space, self.id, self.kind, self.album).into_bytes() } /// The bytes a record's signature is over. pub fn message(&self, body: &str) -> Vec<u8> { format!( "{SIG_DOMAIN}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{}\n{body}", self.space, self.id, self.kind, self.album, self.files.join(","), self.version, self.prev, self.signer, self.mark.line() ) .into_bytes() }}/// What the next version of a record names as its previous one: hex SHA-256 over its body and signature.pub fn record_hash(body: &str, sig: &str) -> String { hex(&Sha256::digest(format!("{body}\n{sig}").as_bytes()))}fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect()}/// A deletion: of record `id` at its next `version`, ending the version whose [`record_hash`] is `prev`, by `signer`,/// whose deleted record was signed by `whose` (whose counts the mark's `gone` covers).#[derive(Debug, Clone, PartialEq, Eq)]pub struct Tomb<'a> { pub space: &'a str, pub id: &'a str, pub version: u64, pub prev: &'a str, pub signer: &'a str, pub whose: &'a str, pub mark: &'a Mark,}impl Tomb<'_> { pub fn message(&self) -> Vec<u8> { format!("{TOMB_DOMAIN}\n{}\n{}\n{}\n{}\n{}\n{}\n{}", self.space, self.id, self.version, self.prev, self.signer, self.mark.line(), self.whose).into_bytes() }}/// A deletion signed.pub fn sign_tomb(signer_key: &SigningKey, tomb: &Tomb) -> String { format!("{SIG_PREFIX}{}", b64(&signer_key.sign(&tomb.message()).to_bytes()))}/// Whether `sig` is the deletion's signer's.pub fn verify_tomb(signer_key: &str, tomb: &Tomb, sig: &str) -> Result<(), SealError> { verify_bytes(signer_key, &tomb.message(), sig)}fn verify_bytes(signer: &str, message: &[u8], sig: &str) -> Result<(), SealError> { let public: [u8; 32] = unb64(signer)?.try_into().map_err(|_| SealError::DoesNotOpen)?; let key = VerifyingKey::from_bytes(&public).map_err(|_| SealError::DoesNotOpen)?; let bytes: [u8; 64] = unb64(sig.strip_prefix(SIG_PREFIX).ok_or(SealError::DoesNotOpen)?)?.try_into().map_err(|_| SealError::DoesNotOpen)?; key.verify(message, &Signature::from_bytes(&bytes)).map_err(|_| SealError::DoesNotOpen)}/// A short code for one person's keys (sharing and signing), shown when a key changed: "12345 67890".pub fn key_code(share: &str, sign: &str) -> String { let d = Sha256::digest(format!("cotton-key-code-v1\n{share}\n{sign}").as_bytes()); let n = u64::from_be_bytes(d[..8].try_into().expect("8 bytes")) % 10_000_000_000; format!("{:05} {:05}", n / 100_000, n % 100_000)}/// The safety number of two people (each by sharing and signing key), the same on both phones: "12345 67890 12345 67890".pub fn safety_code(a: (&str, &str), b: (&str, &str)) -> String { let (x, y) = if (a.0, a.1) <= (b.0, b.1) { (a, b) } else { (b, a) }; let d = Sha256::digest(format!("cotton-safety-v1\n{}\n{}\n{}\n{}", x.0, x.1, y.0, y.1).as_bytes()); let mut groups = Vec::new(); for chunk in d[..16].chunks(4) { groups.push(format!("{:05}", u32::from_be_bytes(chunk.try_into().expect("4 bytes")) % 100_000)); } groups.join(" ")}/// A record as the phone posts it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Sealed { pub key: String, pub body: String, pub sig: String,}/// A record's own key, wiped when it drops.#[derive(ZeroizeOnDrop)]struct RecordKey([u8; 32]);/// A record sealed and signed at `epoch`: a fresh record key under the epoch key, the body under it, the signature over both heads.pub fn seal_record( epoch_key: &SetKey, epoch: u32, signer: &SigningKey, head: &Head, body: &Value,) -> Result<Sealed, SealError> { let mut nonce = [0u8; NONCE_LEN]; rand::rngs::OsRng.fill_bytes(&mut nonce); let mut rk = [0u8; 32]; rand::rngs::OsRng.fill_bytes(&mut rk); seal_record_with(&nonce, RecordKey(rk), epoch_key, epoch, signer, head, body)}fn seal_record_with( nonce: &[u8; NONCE_LEN], rk: RecordKey, epoch_key: &SetKey, epoch: u32, signer: &SigningKey, head: &Head, body: &Value,) -> Result<Sealed, SealError> { head.check()?; let plain = Zeroizing::new( serde_json::to_vec(body) .map_err(|_| SealError::BadInput("a record body is JSON".into()))?, ); if plain.len() > BODY_LIMIT { return Err(SealError::BadInput(format!( "a record body is at most {BODY_LIMIT} bytes" ))); } let key = seal_in_set(epoch_key, head.space, epoch, head.id, &rk.0)?; let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&rk.0)); let ct = cipher .encrypt( Nonce::from_slice(nonce), Payload { msg: &plain, aad: &head.aad(), }, ) .map_err(|_| SealError::Failed)?; let mut out = Vec::with_capacity(NONCE_LEN + ct.len()); out.extend_from_slice(nonce); out.extend_from_slice(&ct); let body = format!("{BODY_PREFIX}{}", b64(&out)); let sig = format!( "{SIG_PREFIX}{}", b64(&signer.sign(&head.message(&body)).to_bytes()) ); Ok(Sealed { key, body, sig })}fn record_key(epoch_key: &SetKey, head: &Head, key: &str) -> Result<RecordKey, SealError> { let plain = Zeroizing::new(open_in_set(epoch_key, head.space, head.id, key)?); Ok(RecordKey( plain .as_slice() .try_into() .map_err(|_| SealError::DoesNotOpen)?, ))}/// A record's body opened with the key of the epoch its `key` names ([`super::set::epoch_of`]).pub fn open_record( epoch_key: &SetKey, head: &Head, key: &str, body: &str,) -> Result<Value, SealError> { head.check()?; let rk = record_key(epoch_key, head, key)?; let raw = unb64( body.strip_prefix(BODY_PREFIX) .ok_or(SealError::DoesNotOpen)?, )?; if raw.len() < NONCE_LEN + 16 { return Err(SealError::DoesNotOpen); } let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&rk.0)); let plain = Zeroizing::new( cipher .decrypt( Nonce::from_slice(&raw[..NONCE_LEN]), Payload { msg: &raw[NONCE_LEN..], aad: &head.aad(), }, ) .map_err(|_| SealError::DoesNotOpen)?, ); serde_json::from_slice(&plain).map_err(|_| SealError::DoesNotOpen)}/// Whether `sig` is the signature of the member whose signing key is `signer` over this record: anything else is `DoesNotOpen`.pub fn verify_record(signer: &str, head: &Head, body: &str, sig: &str) -> Result<(), SealError> { verify_bytes(signer, &head.message(body), sig)}/// On an epoch move: a record's key taken from under the old epoch's key and put under the new one. Body and signature are not touched.pub fn rewrap_record_key( old: &SetKey, new: &SetKey, new_epoch: u32, head: &Head, key: &str,) -> Result<String, SealError> { let rk = record_key(old, head, key)?; seal_in_set(new, head.space, new_epoch, head.id, &rk.0)}// ── epochs ──────────────────────────────────────────────────────────────/// One epoch's key wrapped to each member (member id → sharing key, from the space's member list).pub fn epoch_wraps( key: &SetKey, space: &str, epoch: u32, members: &BTreeMap<String, String>,) -> Result<BTreeMap<String, String>, SealError> { members .iter() .map(|(id, public)| { let public = super::share::key_from_text(public).ok_or_else(|| { SealError::BadInput(format!("member {id}'s sharing key is not 32 bytes")) })?; Ok((id.clone(), wrap_set_key(&public, key, space, epoch)?)) }) .collect()}/// This member's wrap of an epoch opened with their sharing secret; refused unless it names this space and epoch.pub fn open_epoch( share_secret: &[u8; 32], wrapped: &str, space: &str, epoch: u32,) -> Result<SetKey, SealError> { open_set_key(share_secret, wrapped, space, epoch)}// ── files ───────────────────────────────────────────────────────────────/// Where a shared file's bytes are, and what its seal is bound to.pub fn file_object_key(space: &str, file: &str) -> String { format!("spaces/{space}/{file}")}/// One rendition sealed under its own key for its place in the space; refused when it still carries metadata.pub fn seal_shared_file( fk: &FileKey, space: &str, file: &str, plain: &[u8], out: &mut impl Write,) -> Result<u64, SealError> { if let Some(what) = metadata_in(plain) { return Err(SealError::BadInput(format!( "the picture still holds {what}; the shell strips it before a photo is shared" ))); } seal_file(fk, &file_object_key(space, file), &mut &plain[..], out)}/// A shared file opened.pub fn open_shared_file( fk: &FileKey, space: &str, file: &str, sealed: &mut impl Read, out: &mut impl Write,) -> Result<u64, SealError> { open_file(fk, &file_object_key(space, file), sealed, out)}// ── links ───────────────────────────────────────────────────────────────/// A link's secret: 32 random bytes that live only after the link's `#`.#[derive(ZeroizeOnDrop)]pub struct LinkSecret([u8; 32]);/// What a link posts to the server, and what its holder sends: nothing that opens anything.#[derive(Debug, Clone, PartialEq, Eq)]pub struct LinkParts { pub public: String, pub auth: String, pub auth_hash: String,}impl LinkSecret { pub fn mint() -> LinkSecret { let mut bytes = [0u8; 32]; rand::rngs::OsRng.fill_bytes(&mut bytes); LinkSecret(bytes) } pub fn from_bytes(bytes: [u8; 32]) -> LinkSecret { LinkSecret(bytes) } pub fn text(&self) -> String { b64(&self.0) } pub fn read(text: &str) -> Result<LinkSecret, SealError> { Ok(LinkSecret( unb64(text)? .try_into() .map_err(|_| SealError::DoesNotOpen)?, )) } fn derive(&self, info: &[u8]) -> Zeroizing<[u8; 32]> { let mut out = Zeroizing::new([0u8; 32]); // HKDF-SHA256 expands 32 bytes for any info: it never refuses. let _ = Hkdf::<Sha256>::new(None, &self.0).expand(info, out.as_mut_slice()); out } /// The link's X25519 secret: what opens the link's wrap of the epoch key, in the holder's browser alone. pub fn private(&self) -> Zeroizing<[u8; 32]> { self.derive(LINK_INFO) } pub fn parts(&self) -> LinkParts { let auth = b64(&*self.derive(LINK_AUTH_INFO)); let auth_hash = Sha256::digest(auth.as_bytes()) .iter() .map(|b| format!("{b:02x}")) .collect(); LinkParts { public: b64(&public_of(&self.private())), auth, auth_hash, } }}/// The link's address: the secret after the `#`, which no browser sends.pub fn link_url(base: &str, space: &str, link: &str, secret: &LinkSecret) -> String { format!( "{}/a/{space}.{link}#{}", base.trim_end_matches('/'), secret.text() )}/// A link's address read back: space, link id, secret.pub fn read_link_url(url: &str) -> Result<(String, String, LinkSecret), SealError> { let (path, secret) = url.split_once('#').ok_or(SealError::DoesNotOpen)?; let tail = path .rsplit_once("/a/") .map(|(_, t)| t) .ok_or(SealError::DoesNotOpen)?; let (space, link) = tail.split_once('.').ok_or(SealError::DoesNotOpen)?; Ok(( space.to_string(), link.to_string(), LinkSecret::read(secret)?, ))}// ── metadata ────────────────────────────────────────────────────────────//// What is shared (SHARED 4, the coordinator's decision 10): a photo's renditions are JPEG (a HEIC is re-encoded on the// phone first); a video's is MP4, re-encoded on the phone at 1080p with no `udta`, `meta` or `uuid` box (where// QuickTime keeps the place and the camera). What an iPhone video carries, each refused here: `udta` (©xyz place, make,// model), `meta` with `keys`/`ilst` (com.apple.quicktime.location.ISO6709, make, model, software, creation date),// `mebx` timed-metadata tracks (live-photo still time, motion, place over time), and `free` padding (zeros, or a// renamed box still holding them). A JPEG's APP1 (EXIF, XMP), APP2 MPF, APP11 (JUMBF/C2PA), APP12, APP13 (IPTC) and// comments are refused; APP0 (JFIF) and APP2 ICC colour stay. Each check reads the WHOLE file: a JPEG past its scans to the end of the// image and nothing after it (a second picture appended carries its own EXIF), a PNG to IEND and nothing after, an// MP4 every top-level box and every box inside `moov` and each `trak`./// What metadata a rendition still holds, or which format it is that the core will not share; none when clean.pub fn metadata_in(bytes: &[u8]) -> Option<&'static str> { if bytes.starts_with(&[0xFF, 0xD8]) { return jpeg_metadata(bytes); } if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { return png_metadata(bytes); } if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" { return iso_metadata(bytes); } Some("a format the core cannot check (a photo is shared as JPEG, a video as MP4)")}/// A rendition of `kind` checked: the right container for it, and nothing in it but the picture.pub fn rendition_problem(kind: &str, bytes: &[u8]) -> Option<String> { let is_video = bytes.len() >= 12 && &bytes[4..8] == b"ftyp"; if kind == "video" && !is_video { return Some("a video is shared as MP4".into()); } if kind != "video" && is_video { return Some("a photo is shared as JPEG (a HEIC is re-encoded on the phone first)".into()); } metadata_in(bytes).map(str::to_string)}fn jpeg_metadata(bytes: &[u8]) -> Option<&'static str> { let mut at = 2; loop { if at + 2 > bytes.len() { return Some("a JPEG cut short"); } if bytes[at] != 0xFF { return Some("a JPEG the core cannot read to its end"); } let marker = bytes[at + 1]; match marker { 0xFF => { at += 1; continue; } 0xD9 => { // The end of the image: nothing may follow it (an appended picture brings its own metadata). return if at + 2 == bytes.len() { None } else { Some("data after the end of the picture") }; } 0x01 | 0xD0..=0xD7 => { at += 2; continue; } _ => {} } if at + 4 > bytes.len() { return Some("a JPEG cut short"); } let len = u16::from_be_bytes([bytes[at + 2], bytes[at + 3]]) as usize; if len < 2 || at + 2 + len > bytes.len() { return Some("a JPEG cut short"); } let segment = &bytes[at + 4..at + 2 + len]; match marker { 0xE1 if segment.starts_with(b"Exif\0") => return Some("EXIF (where GPS lives)"), 0xE1 => return Some("XMP"), 0xE2 if segment.starts_with(b"MPF\0") => return Some("more pictures inside (MPF)"), 0xED => return Some("IPTC"), 0xEB => return Some("JPEG XT or JUMBF data (APP11)"), 0xEC => return Some("picture info (APP12)"), 0xFE => return Some("a comment"), _ => {} } at += 2 + len; if marker == 0xDA { // The scan's coded data runs to the next marker that is not a stuffed 0xFF00 or a restart. while at + 1 < bytes.len() && !(bytes[at] == 0xFF && bytes[at + 1] != 0x00 && !(0xD0..=0xD7).contains(&bytes[at + 1])) { at += 1; } } }}fn png_metadata(bytes: &[u8]) -> Option<&'static str> { let mut at = 8; loop { if at + 12 > bytes.len() { return Some("a PNG cut short"); } let len = u32::from_be_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize; match &bytes[at + 4..at + 8] { b"eXIf" => return Some("EXIF"), b"iTXt" | b"tEXt" | b"zTXt" => return Some("XMP or text"), b"IEND" => return if at + 12 + len == bytes.len() { None } else { Some("data after the end of the picture") }, _ => {} } at += 12 + len; }}/// ISO media (MP4, MOV, HEIC): HEIC is refused by brand; an MP4 or MOV is read box by box.fn iso_metadata(bytes: &[u8]) -> Option<&'static str> { let brand = &bytes[8..12]; if [b"heic", b"heix", b"mif1", b"msf1", b"avif", b"hevc"].iter().any(|b| brand == *b) { return Some("a HEIC picture (it is shared as JPEG, re-encoded on the phone)"); } boxes_clean(bytes, 0)}fn boxes_clean(bytes: &[u8], depth: u8) -> Option<&'static str> { let mut at = 0; while at < bytes.len() { if at + 8 > bytes.len() { return Some("a video cut short"); } let mut size = u32::from_be_bytes(bytes[at..at + 4].try_into().expect("4 bytes")) as usize; let kind = &bytes[at + 4..at + 8]; let mut head = 8; if size == 1 { if at + 16 > bytes.len() { return Some("a video cut short"); } size = u64::from_be_bytes(bytes[at + 8..at + 16].try_into().expect("8 bytes")) as usize; head = 16; } else if size == 0 { size = bytes.len() - at; } if size < head || at + size > bytes.len() { return Some("a video cut short"); } let inner = &bytes[at + head..at + size]; match kind { b"udta" | b"meta" | b"uuid" | b"XMP_" | b"keys" | b"ilst" => return Some("metadata in the video (place, camera or XMP)"), // Padding is zeros; a box renamed to `free` by a careless stripper still holds what it held. b"free" | b"skip" | b"wide" if inner.iter().any(|b| *b != 0) => return Some("bytes left in padding (a renamed metadata box)"), // A timed-metadata track (QuickTime `mebx`: an iPhone's location, motion and still-image time). b"hdlr" if inner.len() >= 12 && &inner[8..12] == b"meta" => return Some("a timed-metadata track"), b"mebx" => return Some("a timed-metadata track"), b"stsd" if inner.windows(4).any(|w| w == b"mebx") => return Some("a timed-metadata track"), b"moov" | b"trak" | b"mdia" | b"minf" | b"stbl" if depth < 6 => { if let Some(why) = boxes_clean(inner, depth + 1) { return Some(why); } } _ => {} } at += size; } None}#[cfg(test)]#[path = "shared_album_tests.rs"]mod tests;