Skip to main content

objectstore_types/
metadata.rs

1//! Per-object metadata types and HTTP header serialization.
2//!
3//! This module defines [`Metadata`], the per-object metadata structure that
4//! travels through the entire system: clients set it via HTTP headers, the
5//! server parses and validates it, the service passes it to backends, and
6//! backends persist it alongside the stored object.
7//!
8//! [`MetadataUpdate`] is the separate JSON request contract for explicit
9//! metadata updates. It is not a persisted metadata representation.
10//!
11//! # Serialization
12//!
13//! Metadata has three serialization formats:
14//!
15//! - **HTTP headers** — used by the single-object public API. [`Metadata::from_headers`] and
16//!   [`Metadata::to_headers`] handle this conversion for public fields only.
17//! - **JSON over the wire** — an alternate representation in API request and response bodies:
18//!   [`WriteMetadata`] for writes and [`ReadMetadata`] for reads.
19//! - **JSON storage** — used internally by backends, through the serde implementation of
20//!   [`Metadata`]. It includes additional internal fields that are skipped in the header
21//!   representation, and differs from the wire format.
22//!
23//! # HTTP header prefixes
24//!
25//! Headers use three prefix conventions:
26//!
27//! - Standard HTTP headers where applicable (`Content-Type`, `Content-Encoding`)
28//! - `x-sn-*` for objectstore-specific fields (e.g. `x-sn-expiration`)
29//! - `x-snme-` for custom user metadata (e.g. `x-snme-build_id`)
30//!
31//! Backends that store metadata as object metadata (like GCS) layer their own
32//! prefix on top, so `x-sn-expiration` becomes `x-goog-meta-x-sn-expiration`.
33//! The [`Metadata::from_headers`] and [`Metadata::to_headers`] methods accept
34//! a `prefix` parameter for this purpose.
35//!
36//! # Escaping free-form values
37//!
38//! [`Metadata`] always holds logical strings: [`filename`](Metadata::filename),
39//! [`origin`](Metadata::origin), and [`custom`](Metadata::custom) values may
40//! contain arbitrary Unicode.
41//!
42//! Over the wire, metadata travels in HTTP headers, which have no charset. In
43//! practice anything outside visible ASCII is either rejected outright or
44//! silently reinterpreted.
45//!
46//! The fields are therefore percent-encoded in headers, via
47//! [`headers::encode_header_value`] and [`headers::decode_header_value`].
48//! Encoding is a property of the *transport*, never of the stored value:
49//! anything reading [`Metadata`] sees the logical string.
50//!
51//! # Custom metadata keys
52//!
53//! Custom metadata keys are restricted by [`normalize_custom_key`] and escaped in header names by
54//! [`encode_custom_key`] and [`headers::decode_header_str_lossy`]; see those functions for the exact
55//! rules.
56//!
57//! The key rule applies to *writes* only: [`Metadata::from_insert_headers`] and the JSON request
58//! paths reject invalid keys, while [`Metadata::from_headers`] and backend reads accept whatever
59//! is stored, so objects written before the rule was explicit stay readable.
60
61use std::borrow::Cow;
62use std::collections::BTreeMap;
63use std::fmt;
64use std::num::ParseIntError;
65use std::str::FromStr;
66use std::time::Duration;
67
68use http::header::{self, HeaderMap, HeaderName};
69use serde::{Deserialize, Serialize};
70
71use crate::duration::{ParseDurationError, format_duration, parse_duration};
72use crate::headers;
73use crate::time::{InvalidTimestamp, Rfc3339Timestamp, Timestamp};
74
75/// The custom HTTP header that contains the serialized [`ExpirationPolicy`].
76pub const HEADER_EXPIRATION: &str = "x-sn-expiration";
77/// The custom HTTP header that contains the object creation time.
78pub const HEADER_TIME_CREATED: &str = "x-sn-time-created";
79/// The custom HTTP header that contains the object expiration time.
80pub const HEADER_TIME_EXPIRES: &str = "x-sn-time-expires";
81/// The custom HTTP header that contains the origin of the object.
82pub const HEADER_ORIGIN: &str = "x-sn-origin";
83/// The custom HTTP header that contains the filename of the object.
84pub const HEADER_FILENAME: &str = "x-sn-filename";
85/// The custom HTTP header that contains the size of the stored object in bytes.
86pub const HEADER_SIZE: &str = "x-sn-size";
87/// The prefix for custom HTTP headers containing custom per-object metadata.
88pub const HEADER_META_PREFIX: &str = "x-snme-";
89
90/// The default content type for objects without a known content type.
91pub const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream";
92
93/// Upper bound on the TTI debounce window.
94///
95/// The debounce window for TTI bumps is `min(tti / 4, MAX_TTI_DEBOUNCE)`. For
96/// TTI values above 4 days the debounce stays at 24 hours (the historical
97/// constant); shorter TTI values get a proportionally smaller window so that
98/// bumps are not silently suppressed.
99const MAX_TTI_DEBOUNCE: Duration = Duration::from_hours(24);
100
101/// An application-specific JSON request for updating object metadata.
102///
103/// This is intentionally separate from [`Metadata`]: omitted fields are not merge-patch
104/// operations, and metadata headers are not interpreted as updates. Unknown fields are rejected.
105#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
106#[serde(deny_unknown_fields)]
107pub struct MetadataUpdate {
108    /// Extends the existing expiration deadline, adjusting TTL duration to match.
109    pub extend_expiry: ExpiryExtension,
110}
111
112/// A requested minimum expiration deadline.
113///
114/// The absolute form contains `at`. The relative form contains both `after` and `from`.
115/// Mixed, incomplete, and unknown fields are rejected during deserialization.
116#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
117#[serde(untagged, deny_unknown_fields)]
118pub enum ExpiryExtension {
119    /// An RFC3339 deadline, validated during deserialization.
120    At {
121        /// The requested absolute deadline.
122        at: Rfc3339Timestamp,
123    },
124    /// A duration relative to an explicit anchor.
125    After {
126        /// A duration in the format documented by [`crate::duration`].
127        #[serde(with = "crate::duration")]
128        after: Duration,
129        /// The timestamp against which the duration is resolved.
130        from: ExpiryAnchor,
131    },
132}
133
134/// The timestamp against which a relative expiry extension is resolved.
135#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
136#[serde(rename_all = "snake_case")]
137pub enum ExpiryAnchor {
138    /// The object's observed creation time.
139    Creation,
140    /// The request-start time.
141    Now,
142}
143
144/// A content type is not a valid [IANA Media
145/// Type](https://www.iana.org/assignments/media-types/media-types.xhtml).
146///
147/// The message describes which part is malformed. The underlying parser is an implementation
148/// detail and not part of the public API.
149#[derive(Debug, thiserror::Error)]
150#[error(transparent)]
151pub struct InvalidContentType(mediatype::MediaTypeError);
152
153/// Errors that can happen dealing with metadata
154#[derive(Debug, thiserror::Error)]
155pub enum Error {
156    /// Any problems dealing with http headers, essentially converting to/from [`str`].
157    #[error("error dealing with http headers")]
158    Header(#[from] Option<http::Error>),
159    /// The value for the expiration policy is invalid.
160    #[error("invalid expiration policy value")]
161    Expiration(#[from] Option<ParseDurationError>),
162    /// The compression algorithm is invalid.
163    #[error("invalid compression value")]
164    Compression,
165    /// The content type is invalid.
166    #[error("invalid content type")]
167    ContentType(#[from] InvalidContentType),
168    /// The creation time is invalid.
169    #[error("invalid creation time")]
170    CreationTime(#[from] humantime::TimestampError),
171    /// The expiration timestamp is outside the supported range.
172    #[error("invalid expiration time")]
173    ExpirationTime(#[from] InvalidTimestamp),
174    /// The object size is not a valid byte count.
175    #[error("invalid object size")]
176    Size(#[from] ParseIntError),
177    /// A free-form header value did not decode into a logical string.
178    #[error("invalid metadata header value")]
179    Encoding(#[from] crate::headers::DecodeError),
180    /// A custom metadata key is empty or contains a disallowed character.
181    ///
182    /// See [`normalize_custom_key`] for the accepted key format.
183    #[error("invalid custom metadata key {0:?}")]
184    CustomKey(String),
185    /// An internal consistency invariant on the metadata was violated.
186    #[error("invariant violation: {0}")]
187    Invariant(&'static str),
188}
189impl From<header::InvalidHeaderValue> for Error {
190    fn from(err: header::InvalidHeaderValue) -> Self {
191        Self::Header(Some(err.into()))
192    }
193}
194impl From<header::InvalidHeaderName> for Error {
195    fn from(err: header::InvalidHeaderName) -> Self {
196        Self::Header(Some(err.into()))
197    }
198}
199impl From<header::ToStrError> for Error {
200    fn from(_err: header::ToStrError) -> Self {
201        // the error happens when converting a header value back to a `str`
202        Self::Header(None)
203    }
204}
205
206/// The per-object expiration policy.
207///
208/// Controls automatic object cleanup. The policy is set by the client at upload
209/// time via the [`x-sn-expiration`](HEADER_EXPIRATION) header and persisted with
210/// the object.
211///
212/// | Variant      | Wire format | Behavior                                     |
213/// |--------------|-------------|----------------------------------------------|
214/// | `Manual`     | `manual`    | No automatic expiration (default)            |
215/// | `TimeToLive` | `ttl:30s`   | Expires after a fixed duration from creation |
216/// | `TimeToIdle` | `tti:1h`    | Expires after a duration of no access        |
217///
218/// Durations use the [wire format](crate::duration), which is written in days, hours, minutes,
219/// and seconds (e.g. `30s`, `5m`, `1h`, `7d`, `400d 12h`).
220///
221/// **Important:** `Manual` is the default and must remain so — persisted objects
222/// without an explicit policy are deserialized as `Manual`.
223#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
224pub enum ExpirationPolicy {
225    /// Manual expiration, meaning no automatic cleanup.
226    // IMPORTANT: Do not change the default, we rely on this for persisted objects.
227    #[default]
228    Manual,
229    /// Time to live, with expiration after the specified duration.
230    TimeToLive(Duration),
231    /// Time to idle, with expiration once the object has not been accessed within the specified duration.
232    TimeToIdle(Duration),
233}
234impl ExpirationPolicy {
235    /// Returns the duration after which the object expires.
236    pub fn expires_in(&self) -> Option<Duration> {
237        match self {
238            ExpirationPolicy::Manual => None,
239            ExpirationPolicy::TimeToLive(duration) => Some(*duration),
240            ExpirationPolicy::TimeToIdle(duration) => Some(*duration),
241        }
242    }
243
244    /// Returns `true` if this policy indicates time-based expiry.
245    pub fn is_timeout(&self) -> bool {
246        match self {
247            ExpirationPolicy::TimeToLive(_) => true,
248            ExpirationPolicy::TimeToIdle(_) => true,
249            ExpirationPolicy::Manual => false,
250        }
251    }
252
253    /// Returns `true` if this policy is `Manual`.
254    pub fn is_manual(&self) -> bool {
255        *self == ExpirationPolicy::Manual
256    }
257
258    /// Checks whether a TTI deadline needs bumping given the current expiry and access time.
259    ///
260    /// Returns `Some(new_expire_at)` when the current deadline is stale enough
261    /// to justify a write, `None` otherwise. The debounce window scales with the
262    /// TTI duration so short-TTI objects get bumped more frequently.
263    ///
264    /// Returns `None` if the new deadline would exceed the supported timestamp range.
265    pub fn check_tti_bump(
266        &self,
267        time_expires: Option<Timestamp>,
268        access_time: Timestamp,
269    ) -> Option<Timestamp> {
270        let ExpirationPolicy::TimeToIdle(tti) = *self else {
271            return None;
272        };
273
274        let time_expires = time_expires?;
275        let new_expire_at = access_time.checked_add(tti)?;
276        let debounce = (tti / 4).min(MAX_TTI_DEBOUNCE);
277        (new_expire_at.checked_duration_since(time_expires)? > debounce).then_some(new_expire_at)
278    }
279}
280impl fmt::Display for ExpirationPolicy {
281    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282        match self {
283            ExpirationPolicy::TimeToLive(duration) => {
284                write!(f, "ttl:{}", format_duration(*duration))
285            }
286            ExpirationPolicy::TimeToIdle(duration) => {
287                write!(f, "tti:{}", format_duration(*duration))
288            }
289            ExpirationPolicy::Manual => f.write_str("manual"),
290        }
291    }
292}
293impl FromStr for ExpirationPolicy {
294    type Err = Error;
295
296    fn from_str(s: &str) -> Result<Self, Self::Err> {
297        if s == "manual" {
298            return Ok(ExpirationPolicy::Manual);
299        }
300        if let Some(duration) = s.strip_prefix("ttl:") {
301            return Ok(ExpirationPolicy::TimeToLive(parse_duration(duration)?));
302        }
303        if let Some(duration) = s.strip_prefix("tti:") {
304            return Ok(ExpirationPolicy::TimeToIdle(parse_duration(duration)?));
305        }
306        Err(Error::Expiration(None))
307    }
308}
309
310/// The compression algorithm applied to an object's payload.
311///
312/// Transmitted via the standard `Content-Encoding` HTTP header. Supported
313/// algorithms are Zstandard (`zstd`) and `gzip`.
314#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
315pub enum Compression {
316    /// Compressed using `zstd`.
317    Zstd,
318    /// Compressed using `gzip`.
319    Gzip,
320}
321
322impl Compression {
323    /// Returns a string representation of the compression algorithm.
324    pub fn as_str(&self) -> &str {
325        match self {
326            Compression::Zstd => "zstd",
327            Compression::Gzip => "gzip",
328        }
329    }
330}
331
332impl fmt::Display for Compression {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        f.write_str(self.as_str())
335    }
336}
337
338impl FromStr for Compression {
339    type Err = Error;
340
341    fn from_str(s: &str) -> Result<Self, Self::Err> {
342        match s {
343            "zstd" => Ok(Compression::Zstd),
344            "gzip" => Ok(Compression::Gzip),
345            _ => Err(Error::Compression),
346        }
347    }
348}
349
350/// Per-object metadata.
351///
352/// Includes first-class fields (expiration, compression, timestamps, etc.) and
353/// arbitrary user-provided key-value metadata. See the [module-level
354/// documentation](self) for the HTTP header mapping conventions.
355#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
356#[serde(default)]
357pub struct Metadata {
358    /// The expiration policy of the object (header: `x-sn-expiration`).
359    ///
360    /// Skipped during serialization when set to [`ExpirationPolicy::Manual`].
361    #[serde(skip_serializing_if = "ExpirationPolicy::is_manual")]
362    pub expiration_policy: ExpirationPolicy,
363
364    /// The creation/last replacement time of the object (header: `x-sn-time-created`).
365    ///
366    /// Set by the server every time an object is put, i.e. when objects are first
367    /// created and when existing objects are overwritten.
368    #[serde(skip_serializing_if = "Option::is_none")]
369    pub time_created: Option<Timestamp>,
370
371    /// The resolved expiration timestamp (header: `x-sn-time-expires`).
372    ///
373    /// Initially derived from the [`expiration_policy`](Self::expiration_policy), but may be later
374    /// extended by explicit updates. This timestamp reflects the deadline present *prior to* the
375    /// current access to the object.
376    ///
377    /// Fractional deadlines round up to whole seconds; see [`Timestamp`].
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub time_expires: Option<Timestamp>,
380
381    /// IANA media type of the object (header: `Content-Type`).
382    ///
383    /// Defaults to [`DEFAULT_CONTENT_TYPE`] (`application/octet-stream`).
384    pub content_type: Cow<'static, str>,
385
386    /// The compression algorithm used for this object (header: `Content-Encoding`).
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub compression: Option<Compression>,
389
390    /// The origin of the object (header: `x-sn-origin`).
391    ///
392    /// Typically the IP address of the original source. This is an optional but
393    /// encouraged field that tracks where the payload was originally obtained
394    /// from (e.g. the IP of a Sentry SDK or CLI).
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub origin: Option<String>,
397
398    /// An optional filename associated with this object (header: `x-sn-filename`).
399    ///
400    /// This filename is returned when downloading the object.
401    ///
402    /// This is a logical string and may contain arbitrary Unicode; it is escaped only on the
403    /// wire (see [the module docs](self#escaping-free-form-values)).
404    #[serde(skip_serializing_if = "Option::is_none")]
405    pub filename: Option<String>,
406
407    /// Size of the stored data in bytes, if known (header: `x-sn-size`).
408    ///
409    /// Read-only. This is the size of the complete object, even when only a range of it is
410    /// being returned. It describes the stored bytes, so for a compressed object it is the
411    /// compressed size.
412    #[serde(skip_serializing_if = "Option::is_none")]
413    pub size: Option<usize>,
414
415    /// Arbitrary user-provided key-value metadata (header prefix: `x-snme-`).
416    ///
417    /// Each entry is transmitted as `x-snme-{key}: {value}`, where `{key}` is escaped as described
418    /// in [the module docs](self#custom-metadata-keys).
419    ///
420    /// Keys must satisfy [`normalize_custom_key`] when written; reading never rejects a key.
421    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
422    pub custom: BTreeMap<String, String>,
423}
424
425impl Metadata {
426    /// Parses the metadata headers accepted from writing endpoints.
427    ///
428    /// Unlike [`from_headers`](Self::from_headers), this skips parsing read-only attributes so
429    /// clients cannot set them via headers.
430    ///
431    /// Uses `access_time` to materialize the following attributes:
432    /// - [`time_created`](Self::time_created)
433    /// - [`time_expires`](Self::time_expires)
434    ///
435    /// A prefix can also be provided which is stripped from custom non-standard headers.
436    pub fn from_insert_headers(
437        headers: &HeaderMap,
438        prefix: &str,
439        access_time: Timestamp,
440    ) -> Result<Self, Error> {
441        let mut metadata = Self::parse_headers(headers, prefix, true)?;
442        metadata.materialize_write_times(access_time)?;
443        Ok(metadata)
444    }
445
446    /// Sets `time_created` and resolves `time_expires` for an object written at `access_time`.
447    fn materialize_write_times(&mut self, access_time: Timestamp) -> Result<(), Error> {
448        self.time_created = Some(access_time);
449        self.time_expires = self
450            .expiration_policy
451            .expires_in()
452            .map(|ttl| access_time.checked_add(ttl).ok_or(InvalidTimestamp))
453            .transpose()?;
454        Ok(())
455    }
456
457    /// Validates internal consistency of the metadata.
458    ///
459    /// A time-based [`expiration_policy`](Self::expiration_policy) must carry a resolved
460    /// [`time_expires`](Self::time_expires); backends rely on this to persist a concrete
461    /// expiration.
462    pub fn validate(&self) -> Result<(), Error> {
463        if self.expiration_policy.is_timeout() && self.time_expires.is_none() {
464            return Err(Error::Invariant(
465                "expiration policy requires a resolved expiration time",
466            ));
467        }
468        if self.expiration_policy.is_manual() && self.time_expires.is_some() {
469            return Err(Error::Invariant(
470                "manual expiration policy must not have a resolved expiration time",
471            ));
472        }
473        Ok(())
474    }
475
476    /// Returns whether the object has expired at the given time.
477    pub fn is_expired(&self, access_time: Timestamp) -> bool {
478        self.time_expires
479            .is_some_and(|deadline| deadline < access_time)
480    }
481
482    /// Checks whether this object's TTI deadline needs bumping.
483    ///
484    /// See [`ExpirationPolicy::check_tti_bump`] for details.
485    pub fn check_tti_bump(&self, access_time: Timestamp) -> Option<Timestamp> {
486        self.expiration_policy
487            .check_tti_bump(self.time_expires, access_time)
488    }
489
490    /// Extracts public API metadata from the given [`HeaderMap`].
491    ///
492    /// A prefix can be also be provided which is being stripped from custom non-standard headers.
493    pub fn from_headers(headers: &HeaderMap, prefix: &str) -> Result<Self, Error> {
494        Self::parse_headers(headers, prefix, false)
495    }
496
497    /// Parses metadata from the given [`HeaderMap`].
498    ///
499    /// When `skip_read_only` is set, read-only attributes are not parsed off the headers, so a
500    /// malformed client-supplied value cannot fail the parse. A prefix can also be provided which
501    /// is stripped from custom non-standard headers.
502    fn parse_headers(
503        headers: &HeaderMap,
504        prefix: &str,
505        skip_read_only: bool,
506    ) -> Result<Self, Error> {
507        let mut metadata = Metadata::default();
508
509        for (name, value) in headers {
510            match *name {
511                // standard HTTP headers
512                header::CONTENT_TYPE => {
513                    let content_type = value.to_str()?;
514                    validate_content_type(content_type)?;
515                    metadata.content_type = content_type.to_owned().into();
516                }
517                header::CONTENT_ENCODING => {
518                    let compression = value.to_str()?;
519                    metadata.compression = Some(Compression::from_str(compression)?);
520                }
521                _ => {
522                    let Some(name) = name.as_str().strip_prefix(prefix) else {
523                        continue;
524                    };
525
526                    match name {
527                        // Objectstore first-class metadata
528                        HEADER_EXPIRATION => {
529                            let expiration_policy = value.to_str()?;
530                            metadata.expiration_policy =
531                                ExpirationPolicy::from_str(expiration_policy)?;
532                        }
533                        HEADER_TIME_CREATED if !skip_read_only => {
534                            let timestamp = value.to_str()?;
535                            let time = Timestamp::from_rfc3339(timestamp)?;
536                            metadata.time_created = Some(time);
537                        }
538                        HEADER_TIME_EXPIRES if !skip_read_only => {
539                            let timestamp = value.to_str()?;
540                            let time = Timestamp::from_rfc3339(timestamp)?;
541                            metadata.time_expires = Some(time);
542                        }
543                        HEADER_ORIGIN => {
544                            metadata.origin = Some(headers::decode_header_value(value)?);
545                        }
546                        HEADER_FILENAME => {
547                            metadata.filename = Some(headers::decode_header_value(value)?);
548                        }
549                        HEADER_SIZE if !skip_read_only => {
550                            let size = value.to_str()?;
551                            metadata.size = Some(size.parse()?);
552                        }
553                        _ => {
554                            // customer-provided metadata
555                            if let Some(name) = name.strip_prefix(HEADER_META_PREFIX) {
556                                let key = headers::decode_header_str_lossy(name);
557                                // Only writes are validated; stored keys must stay readable.
558                                let key = if skip_read_only {
559                                    normalize_custom_key(&key)?
560                                } else {
561                                    key.into_owned()
562                                };
563                                let value = headers::decode_header_value(value)?;
564                                metadata.custom.insert(key, value);
565                            }
566                        }
567                    }
568                }
569            }
570        }
571
572        Ok(metadata)
573    }
574
575    /// Turns the metadata into a [`HeaderMap`] for the public API.
576    ///
577    /// It will prefix any non-standard headers with the given `prefix`. GCS-specific headers are
578    /// not emitted; backends handle those separately.
579    pub fn to_headers(&self, prefix: &str) -> Result<HeaderMap, Error> {
580        let Self {
581            content_type,
582            compression,
583            origin,
584            filename,
585            expiration_policy,
586            time_created,
587            time_expires,
588            size,
589            custom,
590        } = self;
591
592        let mut headers = HeaderMap::new();
593
594        // standard headers
595        headers.append(header::CONTENT_TYPE, content_type.parse()?);
596        if let Some(compression) = compression {
597            headers.append(header::CONTENT_ENCODING, compression.as_str().parse()?);
598        }
599
600        // Objectstore first-class metadata
601        if *expiration_policy != ExpirationPolicy::Manual {
602            let name = HeaderName::try_from(format!("{prefix}{HEADER_EXPIRATION}"))?;
603            headers.append(name, expiration_policy.to_string().parse()?);
604        }
605        if let Some(time) = time_created {
606            let name = HeaderName::try_from(format!("{prefix}{HEADER_TIME_CREATED}"))?;
607            let timestamp = time.as_rfc3339();
608            headers.append(name, timestamp.to_string().parse()?);
609        }
610        if let Some(time) = time_expires {
611            let name = HeaderName::try_from(format!("{prefix}{HEADER_TIME_EXPIRES}"))?;
612            let timestamp = time.as_rfc3339();
613            headers.append(name, timestamp.to_string().parse()?);
614        }
615        if let Some(origin) = origin {
616            let name = HeaderName::try_from(format!("{prefix}{HEADER_ORIGIN}"))?;
617            headers.append(name, headers::encode_header_value(origin));
618        }
619        if let Some(filename) = filename {
620            let name = HeaderName::try_from(format!("{prefix}{HEADER_FILENAME}"))?;
621            headers.append(name, headers::encode_header_value(filename));
622        }
623        if let Some(size) = size {
624            let name = HeaderName::try_from(format!("{prefix}{HEADER_SIZE}"))?;
625            headers.append(name, size.to_string().parse()?);
626        }
627
628        // customer-provided metadata
629        for (key, value) in custom {
630            let key = encode_custom_key(key);
631            let name = HeaderName::try_from(format!("{prefix}{HEADER_META_PREFIX}{key}"))?;
632            headers.append(name, headers::encode_header_value(value));
633        }
634
635        Ok(headers)
636    }
637}
638
639/// Validates and normalizes a custom metadata key.
640///
641/// ASCII letters are lowercased. The result must be non-empty and consist only of
642/// `a-z`, `0-9`, and the symbols `_ - | ~ % $ # + . :`. Anything else, including whitespace,
643/// other punctuation, and non-ASCII characters, is rejected with [`Error::CustomKey`].
644///
645/// Every writer of custom metadata (HTTP headers, JSON bodies, clients) must apply this rule.
646/// Readers must not: objects stored before the rule was explicit may carry other keys.
647///
648/// To use a key as part of a header name, see [`encode_custom_key`].
649///
650/// # Examples
651///
652/// ```
653/// use objectstore_types::metadata::normalize_custom_key;
654///
655/// assert_eq!(normalize_custom_key("Build_ID:7")?, "build_id:7");
656/// assert!(normalize_custom_key("").is_err());
657/// # Ok::<(), objectstore_types::metadata::Error>(())
658/// ```
659pub fn normalize_custom_key(key: &str) -> Result<String, Error> {
660    let is_allowed = |ch: char| {
661        ch.is_ascii_alphanumeric()
662            || matches!(
663                ch,
664                '_' | '-' | '|' | '~' | '%' | '$' | '#' | '+' | '.' | ':'
665            )
666    };
667
668    if key.is_empty() || !key.chars().all(is_allowed) {
669        return Err(Error::CustomKey(key.to_owned()));
670    }
671    Ok(key.to_ascii_lowercase())
672}
673
674/// Encodes a custom metadata key for use in a header name after `x-snme-`.
675///
676/// `%` becomes `%25` and `:` becomes `%3a`; nothing else changes. The result contains only
677/// RFC 9110 token characters when `key` satisfies [`normalize_custom_key`].
678///
679/// The inverse is [`headers::decode_header_str_lossy`], which also decodes any other escape.
680///
681/// # Examples
682///
683/// ```
684/// use objectstore_types::metadata::encode_custom_key;
685///
686/// assert_eq!(encode_custom_key("build:id"), "build%3aid");
687/// assert_eq!(encode_custom_key("100%"), "100%25");
688/// assert_eq!(encode_custom_key("plain"), "plain");
689/// ```
690pub fn encode_custom_key(key: &str) -> Cow<'_, str> {
691    if !key.contains(['%', ':']) {
692        return Cow::Borrowed(key);
693    }
694
695    let mut encoded = String::with_capacity(key.len() + 4);
696    for ch in key.chars() {
697        match ch {
698            '%' => encoded.push_str("%25"),
699            ':' => encoded.push_str("%3a"),
700            other => encoded.push(other),
701        }
702    }
703    Cow::Owned(encoded)
704}
705
706/// Validates that `content_type` is a valid [IANA Media
707/// Type](https://www.iana.org/assignments/media-types/media-types.xhtml).
708fn validate_content_type(content_type: &str) -> Result<(), Error> {
709    mediatype::MediaType::parse(content_type).map_err(InvalidContentType)?;
710    Ok(())
711}
712
713impl Default for Metadata {
714    fn default() -> Self {
715        Self {
716            expiration_policy: ExpirationPolicy::Manual,
717            time_created: None,
718            time_expires: None,
719            content_type: DEFAULT_CONTENT_TYPE.into(),
720            compression: None,
721            origin: None,
722            filename: None,
723            size: None,
724            custom: BTreeMap::new(),
725        }
726    }
727}
728
729/// The writable subset of [`Metadata`], as sent in JSON when inserting an object.
730///
731/// Values use their header syntax, for example `"zstd"` or `"ttl:30d"`, and are validated by
732/// [`into_metadata`](Self::into_metadata). Unknown fields are ignored.
733#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
734#[serde(default)]
735#[non_exhaustive]
736pub struct WriteMetadata {
737    /// See [`Metadata::content_type`].
738    #[serde(skip_serializing_if = "Option::is_none")]
739    pub content_type: Option<String>,
740    /// See [`Metadata::compression`].
741    #[serde(skip_serializing_if = "Option::is_none")]
742    pub content_encoding: Option<String>,
743    /// See [`Metadata::expiration_policy`].
744    #[serde(skip_serializing_if = "Option::is_none")]
745    pub expiration: Option<String>,
746    /// See [`Metadata::origin`].
747    #[serde(skip_serializing_if = "Option::is_none")]
748    pub origin: Option<String>,
749    /// See [`Metadata::filename`].
750    #[serde(skip_serializing_if = "Option::is_none")]
751    pub filename: Option<String>,
752    /// See [`Metadata::custom`].
753    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
754    pub custom: BTreeMap<String, String>,
755}
756
757impl WriteMetadata {
758    /// Validates the fields and converts them into [`Metadata`] for an object written at
759    /// `access_time`.
760    ///
761    /// Sets the creation and expiration times like [`Metadata::from_insert_headers`]. Custom keys
762    /// are normalized with [`normalize_custom_key`].
763    ///
764    /// # Errors
765    ///
766    /// Returns an error if a value is invalid.
767    pub fn into_metadata(self, access_time: Timestamp) -> Result<Metadata, Error> {
768        if let Some(content_type) = &self.content_type {
769            validate_content_type(content_type)?;
770        }
771
772        let custom = self
773            .custom
774            .into_iter()
775            .map(|(key, value)| Ok((normalize_custom_key(&key)?, value)))
776            .collect::<Result<_, Error>>()?;
777
778        let expiration_policy = self.expiration.as_deref().map(str::parse).transpose()?;
779        let mut metadata = Metadata {
780            expiration_policy: expiration_policy.unwrap_or_default(),
781            content_type: self
782                .content_type
783                .map_or(DEFAULT_CONTENT_TYPE.into(), Into::into),
784            compression: self
785                .content_encoding
786                .as_deref()
787                .map(str::parse)
788                .transpose()?,
789            origin: self.origin,
790            filename: self.filename,
791            custom,
792            ..Default::default()
793        };
794        metadata.materialize_write_times(access_time)?;
795        Ok(metadata)
796    }
797}
798
799impl From<Metadata> for WriteMetadata {
800    fn from(metadata: Metadata) -> Self {
801        Self {
802            content_type: (metadata.content_type != DEFAULT_CONTENT_TYPE)
803                .then(|| metadata.content_type.into_owned()),
804            content_encoding: metadata.compression.map(|c| c.to_string()),
805            expiration: (!metadata.expiration_policy.is_manual())
806                .then(|| metadata.expiration_policy.to_string()),
807            origin: metadata.origin,
808            filename: metadata.filename,
809            custom: metadata.custom,
810        }
811    }
812}
813
814/// [`Metadata`] of an existing object, as returned in JSON.
815///
816/// Values use their header syntax, for example `"zstd"` or `"ttl:30d"`, and timestamps are RFC
817/// 3339. Unset fields are omitted. Unknown fields are ignored.
818#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
819#[non_exhaustive]
820pub struct ReadMetadata {
821    /// See [`Metadata::content_type`].
822    pub content_type: String,
823    /// See [`Metadata::compression`].
824    #[serde(skip_serializing_if = "Option::is_none")]
825    pub content_encoding: Option<String>,
826    /// See [`Metadata::expiration_policy`].
827    #[serde(skip_serializing_if = "Option::is_none")]
828    pub expiration: Option<String>,
829    /// See [`Metadata::origin`].
830    #[serde(skip_serializing_if = "Option::is_none")]
831    pub origin: Option<String>,
832    /// See [`Metadata::filename`].
833    #[serde(skip_serializing_if = "Option::is_none")]
834    pub filename: Option<String>,
835    /// See [`Metadata::custom`].
836    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
837    pub custom: BTreeMap<String, String>,
838    /// See [`Metadata::time_created`].
839    #[serde(skip_serializing_if = "Option::is_none")]
840    pub time_created: Option<Rfc3339Timestamp>,
841    /// See [`Metadata::time_expires`].
842    #[serde(skip_serializing_if = "Option::is_none")]
843    pub time_expires: Option<Rfc3339Timestamp>,
844    /// See [`Metadata::size`].
845    #[serde(skip_serializing_if = "Option::is_none")]
846    pub size: Option<usize>,
847}
848
849impl From<Metadata> for ReadMetadata {
850    fn from(metadata: Metadata) -> Self {
851        Self {
852            content_type: metadata.content_type.into_owned(),
853            content_encoding: metadata.compression.map(|c| c.to_string()),
854            expiration: (!metadata.expiration_policy.is_manual())
855                .then(|| metadata.expiration_policy.to_string()),
856            origin: metadata.origin,
857            filename: metadata.filename,
858            custom: metadata.custom,
859            time_created: metadata.time_created.map(Timestamp::as_rfc3339),
860            time_expires: metadata.time_expires.map(Timestamp::as_rfc3339),
861            size: metadata.size,
862        }
863    }
864}
865
866impl TryFrom<ReadMetadata> for Metadata {
867    type Error = Error;
868
869    fn try_from(object: ReadMetadata) -> Result<Self, Error> {
870        let expiration_policy = object.expiration.as_deref().map(str::parse).transpose()?;
871        Ok(Self {
872            expiration_policy: expiration_policy.unwrap_or_default(),
873            time_created: object.time_created.map(Rfc3339Timestamp::into_inner),
874            time_expires: object.time_expires.map(Rfc3339Timestamp::into_inner),
875            content_type: object.content_type.into(),
876            compression: object
877                .content_encoding
878                .as_deref()
879                .map(str::parse)
880                .transpose()?,
881            origin: object.origin,
882            filename: object.filename,
883            size: object.size,
884            custom: object.custom,
885        })
886    }
887}
888
889#[cfg(test)]
890mod tests {
891    use super::*;
892
893    #[test]
894    fn metadata_update_parses_supported_expiry_extensions() {
895        let cases = [
896            (
897                r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z"}}"#,
898                ExpiryExtension::At {
899                    at: "2026-10-16T12:00:00Z".parse().unwrap(),
900                },
901            ),
902            (
903                r#"{"extend_expiry":{"after":"30d","from":"creation"}}"#,
904                ExpiryExtension::After {
905                    after: Duration::from_secs(30 * 86400),
906                    from: ExpiryAnchor::Creation,
907                },
908            ),
909            (
910                r#"{"extend_expiry":{"after":"0s","from":"now"}}"#,
911                ExpiryExtension::After {
912                    after: Duration::ZERO,
913                    from: ExpiryAnchor::Now,
914                },
915            ),
916        ];
917
918        for (json, expected) in cases {
919            let update: MetadataUpdate = serde_json::from_str(json).unwrap();
920            assert_eq!(update.extend_expiry, expected);
921            assert_eq!(serde_json::to_string(&update).unwrap(), json);
922        }
923    }
924
925    #[test]
926    fn metadata_update_rejects_invalid_structures() {
927        let cases = [
928            r#"{"extend_expiry":{"at":"not a timestamp"}}"#,
929            r#"{"extend_expiry":{"after":"not a duration","from":"now"}}"#,
930            r#"{}"#,
931            r#"{"extend_expiry":null}"#,
932            r#"{"extend_expiry":{}}"#,
933            r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z","after":"30d","from":"now"}}"#,
934            r#"{"extend_expiry":{"after":"30d"}}"#,
935            r#"{"extend_expiry":{"after":"30d","from":"unsupported"}}"#,
936            r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z","unknown":true}}"#,
937            r#"{"extend_expiry":{"after":"30d","from":"now","unknown":true}}"#,
938            r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z"},"content_type":"text/plain"}"#,
939        ];
940
941        for json in cases {
942            assert!(
943                serde_json::from_str::<MetadataUpdate>(json).is_err(),
944                "unexpectedly accepted {json}"
945            );
946        }
947    }
948
949    #[test]
950    fn from_headers_with_origin() {
951        let mut headers = HeaderMap::new();
952        headers.insert("content-type", "text/plain".parse().unwrap());
953        headers.insert(HEADER_ORIGIN, "203.0.113.42".parse().unwrap());
954
955        let metadata = Metadata::from_headers(&headers, "").unwrap();
956        assert_eq!(metadata.origin.as_deref(), Some("203.0.113.42"));
957        assert_eq!(metadata.content_type, "text/plain");
958    }
959
960    #[test]
961    fn from_headers_without_origin() {
962        let mut headers = HeaderMap::new();
963        headers.insert("content-type", "text/plain".parse().unwrap());
964
965        let metadata = Metadata::from_headers(&headers, "").unwrap();
966        assert!(metadata.origin.is_none());
967    }
968
969    #[test]
970    fn to_headers_with_origin() {
971        let metadata = Metadata {
972            origin: Some("203.0.113.42".into()),
973            ..Default::default()
974        };
975
976        let headers = metadata.to_headers("").unwrap();
977        assert_eq!(headers.get(HEADER_ORIGIN).unwrap(), "203.0.113.42");
978    }
979
980    #[test]
981    fn to_headers_without_origin() {
982        let metadata = Metadata::default();
983        let headers = metadata.to_headers("").unwrap();
984        assert!(headers.get(HEADER_ORIGIN).is_none());
985    }
986
987    #[test]
988    fn origin_header_roundtrip() {
989        let metadata = Metadata {
990            origin: Some("203.0.113.42".into()),
991            ..Default::default()
992        };
993
994        let headers = metadata.to_headers("").unwrap();
995        let roundtripped = Metadata::from_headers(&headers, "").unwrap();
996        assert_eq!(roundtripped.origin, metadata.origin);
997    }
998
999    #[test]
1000    fn from_headers_with_filename() {
1001        let mut headers = HeaderMap::new();
1002        headers.insert(HEADER_FILENAME, "report.pdf".parse().unwrap());
1003
1004        let metadata = Metadata::from_headers(&headers, "").unwrap();
1005        assert_eq!(metadata.filename.as_deref(), Some("report.pdf"));
1006    }
1007
1008    #[test]
1009    fn from_headers_without_filename() {
1010        let headers = HeaderMap::new();
1011        let metadata = Metadata::from_headers(&headers, "").unwrap();
1012        assert!(metadata.filename.is_none());
1013    }
1014
1015    #[test]
1016    fn to_headers_with_filename() {
1017        let metadata = Metadata {
1018            filename: Some("report.pdf".into()),
1019            ..Default::default()
1020        };
1021
1022        let headers = metadata.to_headers("").unwrap();
1023        assert_eq!(headers.get(HEADER_FILENAME).unwrap(), "report.pdf");
1024    }
1025
1026    #[test]
1027    fn to_headers_without_filename() {
1028        let metadata = Metadata::default();
1029        let headers = metadata.to_headers("").unwrap();
1030        assert!(headers.get(HEADER_FILENAME).is_none());
1031    }
1032
1033    #[test]
1034    fn filename_header_roundtrip() {
1035        let metadata = Metadata {
1036            filename: Some("report.pdf".into()),
1037            ..Default::default()
1038        };
1039
1040        let headers = metadata.to_headers("").unwrap();
1041        let roundtripped = Metadata::from_headers(&headers, "").unwrap();
1042        assert_eq!(roundtripped.filename, metadata.filename);
1043    }
1044
1045    /// Every free-form field is escaped on the way out and decoded on the way back in.
1046    ///
1047    /// The escaping itself is covered in [`crate::headers`]; this only pins down that each of the
1048    /// three fields that needs it actually goes through it, in both directions.
1049    #[test]
1050    fn free_form_values_are_escaped_on_the_wire() {
1051        let metadata = Metadata {
1052            origin: Some("Ünknown-源".into()),
1053            filename: Some("réport-📄.pdf".into()),
1054            custom: BTreeMap::from([("release".to_owned(), "100% vérsion-🚀".to_owned())]),
1055            ..Default::default()
1056        };
1057
1058        let headers = metadata.to_headers("").unwrap();
1059        assert_eq!(
1060            headers.get(HEADER_ORIGIN).unwrap(),
1061            "%C3%9Cnknown-%E6%BA%90"
1062        );
1063        assert_eq!(
1064            headers.get(HEADER_FILENAME).unwrap(),
1065            "r%C3%A9port-%F0%9F%93%84.pdf",
1066        );
1067        assert_eq!(
1068            headers.get(format!("{HEADER_META_PREFIX}release")).unwrap(),
1069            "100%25 v%C3%A9rsion-%F0%9F%9A%80",
1070        );
1071
1072        let roundtripped = Metadata::from_headers(&headers, "").unwrap();
1073        assert_eq!(roundtripped.origin, metadata.origin);
1074        assert_eq!(roundtripped.filename, metadata.filename);
1075        assert_eq!(roundtripped.custom, metadata.custom);
1076    }
1077
1078    #[test]
1079    fn from_headers_content_type_and_encoding() {
1080        let mut headers = HeaderMap::new();
1081        headers.insert("content-type", "application/json".parse().unwrap());
1082        headers.insert("content-encoding", "zstd".parse().unwrap());
1083
1084        let metadata = Metadata::from_headers(&headers, "").unwrap();
1085        assert_eq!(metadata.content_type, "application/json");
1086        assert_eq!(metadata.compression, Some(Compression::Zstd));
1087    }
1088
1089    #[test]
1090    fn from_headers_expiration_policy() {
1091        let mut headers = HeaderMap::new();
1092        headers.insert(HEADER_EXPIRATION, "ttl:30s".parse().unwrap());
1093
1094        let metadata = Metadata::from_headers(&headers, "").unwrap();
1095        assert_eq!(
1096            metadata.expiration_policy,
1097            ExpirationPolicy::TimeToLive(Duration::from_secs(30))
1098        );
1099    }
1100
1101    #[test]
1102    fn expiration_policy_keeps_long_durations_in_days() {
1103        let ttl = Duration::from_secs(400 * 86400 + 3600);
1104        let policy = ExpirationPolicy::TimeToLive(ttl);
1105
1106        assert_eq!(policy.to_string(), "ttl:400d 1h");
1107        assert_eq!(
1108            policy.to_string().parse::<ExpirationPolicy>().unwrap(),
1109            policy
1110        );
1111    }
1112
1113    #[test]
1114    fn expiration_policy_parses_units_that_are_never_emitted() {
1115        let policy: ExpirationPolicy = "tti:2weeks".parse().unwrap();
1116        assert_eq!(
1117            policy,
1118            ExpirationPolicy::TimeToIdle(Duration::from_secs(14 * 86400))
1119        );
1120        // Re-emitting normalizes to the units of the wire format.
1121        assert_eq!(policy.to_string(), "tti:14d");
1122    }
1123
1124    #[test]
1125    fn from_headers_timestamps() {
1126        let mut headers = HeaderMap::new();
1127        headers.insert(
1128            HEADER_TIME_CREATED,
1129            "2024-01-15T12:00:00.123456Z".parse().unwrap(),
1130        );
1131        headers.insert(
1132            HEADER_TIME_EXPIRES,
1133            "2024-01-16T12:00:00.123456Z".parse().unwrap(),
1134        );
1135
1136        let metadata = Metadata::from_headers(&headers, "").unwrap();
1137        let encoded = metadata.to_headers("").unwrap();
1138        assert_eq!(encoded[HEADER_TIME_CREATED], "2024-01-15T12:00:01Z");
1139        assert_eq!(encoded[HEADER_TIME_EXPIRES], "2024-01-16T12:00:01Z");
1140        let deadline = metadata.time_expires.unwrap();
1141        assert!(!metadata.is_expired(deadline - Duration::from_secs(1)));
1142        assert!(!metadata.is_expired(deadline));
1143        assert!(metadata.is_expired(deadline + Duration::from_secs(1)));
1144    }
1145
1146    #[test]
1147    fn from_insert_headers_ignores_read_only_fields() {
1148        // Read-only and output attributes must never be taken from an untrusted
1149        // client request, even if the client supplies the headers.
1150        let forged_created = "2024-01-15T12:00:00.000000Z";
1151        let mut headers = HeaderMap::new();
1152        headers.insert("content-type", "text/plain".parse().unwrap());
1153        headers.insert(HEADER_TIME_CREATED, forged_created.parse().unwrap());
1154        headers.insert(
1155            HEADER_TIME_EXPIRES,
1156            "2024-01-16T12:00:00.000000Z".parse().unwrap(),
1157        );
1158
1159        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1160        // `time_created` is stamped by the server, not the client's forged value.
1161        let created = metadata.time_created.unwrap();
1162        assert_ne!(created, Timestamp::from_rfc3339(forged_created).unwrap());
1163        assert!(metadata.time_expires.is_none());
1164        assert!(metadata.size.is_none());
1165        // Client-settable fields are still parsed.
1166        assert_eq!(metadata.content_type, "text/plain");
1167    }
1168
1169    #[test]
1170    fn from_insert_headers_ignores_malformed_read_only_fields() {
1171        // A malformed read-only header must not fail the write: it is skipped, not parsed.
1172        let mut headers = HeaderMap::new();
1173        headers.insert(HEADER_TIME_CREATED, "not-a-timestamp".parse().unwrap());
1174        headers.insert(HEADER_TIME_EXPIRES, "not-a-timestamp".parse().unwrap());
1175
1176        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1177        assert!(metadata.time_created.is_some());
1178        assert!(metadata.time_expires.is_none());
1179    }
1180
1181    #[test]
1182    fn from_insert_headers_resolves_time_expires_for_ttl() {
1183        let mut headers = HeaderMap::new();
1184        headers.insert(HEADER_EXPIRATION, "ttl:30s".parse().unwrap());
1185
1186        let access_time = Timestamp::UNIX_EPOCH;
1187        let metadata = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
1188        let created = metadata.time_created.unwrap();
1189        assert_eq!(created, access_time);
1190        let expires = metadata.time_expires.unwrap();
1191        assert_eq!(expires, created + Duration::from_secs(30));
1192    }
1193
1194    #[test]
1195    fn from_insert_headers_resolves_time_expires_for_tti() {
1196        let mut headers = HeaderMap::new();
1197        headers.insert(HEADER_EXPIRATION, "tti:1h".parse().unwrap());
1198
1199        let access_time = Timestamp::UNIX_EPOCH;
1200        let metadata = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
1201        let created = metadata.time_created.unwrap();
1202        assert_eq!(created, access_time);
1203        let expires = metadata.time_expires.unwrap();
1204        assert_eq!(expires, created + Duration::from_hours(1));
1205    }
1206
1207    #[test]
1208    fn from_insert_headers_manual_leaves_time_expires_none() {
1209        let headers = HeaderMap::new();
1210        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1211        assert_eq!(metadata.expiration_policy, ExpirationPolicy::Manual);
1212        assert!(metadata.time_expires.is_none());
1213    }
1214
1215    #[test]
1216    fn validate_accepts_resolved_timeout() {
1217        let metadata = Metadata {
1218            expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_secs(30)),
1219            time_expires: Some(Timestamp::now() + Duration::from_secs(30)),
1220            ..Default::default()
1221        };
1222        assert!(metadata.validate().is_ok());
1223    }
1224
1225    #[test]
1226    fn validate_accepts_manual_without_expiry() {
1227        let metadata = Metadata::default();
1228        assert!(metadata.validate().is_ok());
1229    }
1230
1231    #[test]
1232    fn validate_rejects_timeout_without_expiry() {
1233        let metadata = Metadata {
1234            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1235            time_expires: None,
1236            ..Default::default()
1237        };
1238        assert!(matches!(metadata.validate(), Err(Error::Invariant(_))));
1239    }
1240
1241    #[test]
1242    fn from_headers_custom_metadata_with_prefix() {
1243        let mut headers = HeaderMap::new();
1244        // Simulate a backend that prefixes headers, e.g. "x-goog-meta-"
1245        let prefix = "x-goog-meta-";
1246        let expiration_header: HeaderName = format!("{prefix}{HEADER_EXPIRATION}").parse().unwrap();
1247        headers.insert(expiration_header, "tti:1h".parse().unwrap());
1248
1249        let custom_header: HeaderName = format!("{prefix}{HEADER_META_PREFIX}my-key")
1250            .parse()
1251            .unwrap();
1252        headers.insert(custom_header, "my-value".parse().unwrap());
1253
1254        let metadata = Metadata::from_headers(&headers, prefix).unwrap();
1255        assert_eq!(
1256            metadata.expiration_policy,
1257            ExpirationPolicy::TimeToIdle(Duration::from_hours(1))
1258        );
1259        assert_eq!(metadata.custom.get("my-key").unwrap(), "my-value");
1260    }
1261
1262    #[test]
1263    fn normalize_custom_key_accepts_allowed_characters_and_lowercases() {
1264        let allowed = "abcdefghijklmnopqrstuvwxyz0123456789_-|~%$#+.:";
1265        for ch in allowed.chars() {
1266            let key = format!("k{ch}k");
1267            assert_eq!(normalize_custom_key(&key).unwrap(), key, "rejected {ch:?}");
1268        }
1269        assert_eq!(normalize_custom_key(allowed).unwrap(), allowed);
1270        assert_eq!(normalize_custom_key("Build_ID:X").unwrap(), "build_id:x");
1271    }
1272
1273    #[test]
1274    fn normalize_custom_key_rejects_empty_and_other_characters() {
1275        let rejected = [
1276            "", "a b", "a\tb", "a!b", "a\"b", "a&b", "a'b", "a(b", "a)b", "a*b", "a,b", "a/b",
1277            "a;b", "a<b", "a=b", "a>b", "a?b", "a@b", "a[b", "a\\b", "a]b", "a^b", "a`b", "a{b",
1278            "a}b", "a\nb", "a\x7fb", "kéy", "键", "k🚀",
1279        ];
1280        for key in rejected {
1281            std::assert_matches!(
1282                normalize_custom_key(key),
1283                Err(Error::CustomKey(_)),
1284                "accepted {key:?}"
1285            );
1286        }
1287    }
1288
1289    #[test]
1290    fn custom_key_header_name_encoding_roundtrips() {
1291        assert_eq!(encode_custom_key("plain-key_1"), "plain-key_1");
1292        assert_eq!(encode_custom_key("a:b"), "a%3ab");
1293        assert_eq!(encode_custom_key("a%b"), "a%25b");
1294        assert_eq!(encode_custom_key("a%3ab"), "a%253ab");
1295        std::assert_matches!(encode_custom_key("plain"), Cow::Borrowed(_));
1296
1297        assert_eq!(headers::decode_header_str_lossy("a%3ab"), "a:b");
1298        assert_eq!(headers::decode_header_str_lossy("a%3Ab"), "a:b");
1299        assert_eq!(headers::decode_header_str_lossy("a%61"), "aa");
1300        assert_eq!(headers::decode_header_str_lossy("a%253ab"), "a%3ab");
1301        std::assert_matches!(headers::decode_header_str_lossy("plain"), Cow::Borrowed(_));
1302
1303        for key in ["a:b", "a%b", "a%3ab", "a%253ab", "%:%", "a%25", "x:y%z"] {
1304            assert_eq!(
1305                headers::decode_header_str_lossy(&encode_custom_key(key)),
1306                key
1307            );
1308        }
1309    }
1310
1311    #[test]
1312    fn custom_key_header_name_decoding_is_lenient() {
1313        // Malformed escapes stay literal.
1314        for literal in ["100%", "a%", "a%3", "a%zz", "a%%b", "%2", "50%off"] {
1315            assert_eq!(headers::decode_header_str_lossy(literal), literal);
1316        }
1317        // Invalid UTF-8 never fails to decode.
1318        assert_eq!(headers::decode_header_str_lossy("a%ffb"), "a\u{FFFD}b");
1319    }
1320
1321    #[test]
1322    fn custom_keys_with_colon_and_percent_roundtrip_through_headers() {
1323        let metadata = Metadata {
1324            custom: BTreeMap::from([
1325                ("a:b".to_owned(), "colon".to_owned()),
1326                ("a%3ab".to_owned(), "encoded-looking".to_owned()),
1327                ("100%".to_owned(), "percent".to_owned()),
1328            ]),
1329            ..Default::default()
1330        };
1331
1332        for prefix in ["", "x-goog-meta-"] {
1333            let headers = metadata.to_headers(prefix).unwrap();
1334            assert_eq!(
1335                headers.get(format!("{prefix}x-snme-a%3ab")).unwrap(),
1336                "colon"
1337            );
1338            assert_eq!(
1339                headers.get(format!("{prefix}x-snme-a%253ab")).unwrap(),
1340                "encoded-looking"
1341            );
1342
1343            let roundtripped = Metadata::from_headers(&headers, prefix).unwrap();
1344            assert_eq!(roundtripped.custom, metadata.custom);
1345
1346            let access_time = Timestamp::from_unix_secs(1_700_000_000).unwrap();
1347            let inserted = Metadata::from_insert_headers(&headers, prefix, access_time).unwrap();
1348            assert_eq!(inserted.custom, metadata.custom);
1349        }
1350    }
1351
1352    #[test]
1353    fn from_headers_does_not_validate_custom_keys() {
1354        let mut headers = HeaderMap::new();
1355        headers.insert("x-snme-a*b", "v".parse().unwrap());
1356        headers.insert("x-snme-100%", "legacy".parse().unwrap());
1357        headers.insert("x-snme-", "empty".parse().unwrap());
1358        let metadata = Metadata::from_headers(&headers, "").unwrap();
1359        assert_eq!(metadata.custom.get("a*b").unwrap(), "v");
1360        assert_eq!(metadata.custom.get("100%").unwrap(), "legacy");
1361        assert_eq!(metadata.custom.get("").unwrap(), "empty");
1362    }
1363
1364    #[test]
1365    fn from_insert_headers_rejects_invalid_custom_keys() {
1366        let access_time = Timestamp::from_unix_secs(1_700_000_000).unwrap();
1367        for name in [
1368            "x-snme-a*b",
1369            "x-snme-a!b",
1370            "x-snme-a%ffb",
1371            "x-snme-a%20b",
1372            "x-snme-",
1373        ] {
1374            let mut headers = HeaderMap::new();
1375            headers.insert(name, "v".parse().unwrap());
1376            std::assert_matches!(
1377                Metadata::from_insert_headers(&headers, "", access_time),
1378                Err(Error::CustomKey(_)),
1379                "accepted {name}"
1380            );
1381        }
1382    }
1383
1384    #[test]
1385    fn from_headers_invalid_content_type() {
1386        let mut headers = HeaderMap::new();
1387        headers.insert("content-type", "not a valid media type!".parse().unwrap());
1388
1389        let err = Metadata::from_headers(&headers, "").unwrap_err();
1390        assert!(matches!(err, Error::ContentType(_)));
1391    }
1392
1393    #[test]
1394    fn from_headers_invalid_compression() {
1395        let mut headers = HeaderMap::new();
1396        headers.insert("content-encoding", "brotli".parse().unwrap());
1397
1398        let err = Metadata::from_headers(&headers, "").unwrap_err();
1399        assert!(matches!(err, Error::Compression));
1400    }
1401
1402    #[test]
1403    fn from_headers_invalid_expiration() {
1404        let mut headers = HeaderMap::new();
1405        headers.insert(HEADER_EXPIRATION, "garbage".parse().unwrap());
1406
1407        let err = Metadata::from_headers(&headers, "").unwrap_err();
1408        assert!(matches!(err, Error::Expiration(_)));
1409    }
1410
1411    #[test]
1412    fn from_headers_invalid_timestamp() {
1413        let mut headers = HeaderMap::new();
1414        headers.insert(HEADER_TIME_CREATED, "not-a-timestamp".parse().unwrap());
1415
1416        let err = Metadata::from_headers(&headers, "").unwrap_err();
1417        assert!(matches!(err, Error::CreationTime(_)));
1418    }
1419
1420    #[test]
1421    fn to_headers_all_fields() {
1422        let metadata = Metadata {
1423            expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_mins(1)),
1424            time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1425            time_expires: Some(Timestamp::from_unix_secs(1_700_000_060).unwrap()),
1426            content_type: "text/html".into(),
1427            compression: Some(Compression::Zstd),
1428            origin: Some("10.0.0.1".into()),
1429            filename: Some("report.pdf".into()),
1430            size: None,
1431            custom: BTreeMap::from([("foo".into(), "bar".into())]),
1432        };
1433
1434        let headers = metadata.to_headers("pfx-").unwrap();
1435        let map: BTreeMap<_, _> = headers
1436            .iter()
1437            .map(|(k, v)| (k.as_str(), v.to_str().unwrap()))
1438            .collect();
1439
1440        insta::assert_debug_snapshot!(map, @r#"
1441        {
1442            "content-encoding": "zstd",
1443            "content-type": "text/html",
1444            "pfx-x-sn-expiration": "ttl:1m",
1445            "pfx-x-sn-filename": "report.pdf",
1446            "pfx-x-sn-origin": "10.0.0.1",
1447            "pfx-x-sn-time-created": "2023-11-14T22:13:20Z",
1448            "pfx-x-sn-time-expires": "2023-11-14T22:14:20Z",
1449            "pfx-x-snme-foo": "bar",
1450        }
1451        "#);
1452    }
1453
1454    #[test]
1455    fn full_roundtrip_all_fields() {
1456        let prefix = "x-test-";
1457        let metadata = Metadata {
1458            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(2)),
1459            time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1460            time_expires: Some(Timestamp::from_unix_secs(1_700_007_200).unwrap()),
1461            content_type: "image/png".into(),
1462            compression: Some(Compression::Zstd),
1463            origin: Some("192.168.1.1".into()),
1464            filename: Some("image.png".into()),
1465            size: None,
1466            custom: BTreeMap::from([
1467                ("key1".into(), "value1".into()),
1468                ("key2".into(), "value2".into()),
1469            ]),
1470        };
1471
1472        let headers = metadata.to_headers(prefix).unwrap();
1473        let roundtripped = Metadata::from_headers(&headers, prefix).unwrap();
1474
1475        assert_eq!(roundtripped.expiration_policy, metadata.expiration_policy);
1476        assert_eq!(roundtripped.content_type, metadata.content_type);
1477        assert_eq!(roundtripped.compression, metadata.compression);
1478        assert_eq!(roundtripped.origin, metadata.origin);
1479        assert_eq!(roundtripped.filename, metadata.filename);
1480        assert_eq!(roundtripped.time_created, metadata.time_created);
1481        assert_eq!(roundtripped.time_expires, metadata.time_expires);
1482        assert_eq!(roundtripped.custom, metadata.custom);
1483    }
1484
1485    #[test]
1486    fn from_headers_empty() {
1487        let headers = HeaderMap::new();
1488        let metadata = Metadata::from_headers(&headers, "x-goog-meta-").unwrap();
1489        assert_eq!(metadata, Metadata::default());
1490    }
1491
1492    #[test]
1493    fn from_headers_invalid_time_expires() {
1494        let mut headers = HeaderMap::new();
1495        let name: HeaderName = format!("x-goog-meta-{HEADER_TIME_EXPIRES}")
1496            .parse()
1497            .unwrap();
1498        headers.insert(name, "not-a-timestamp".parse().unwrap());
1499
1500        // NOTE: This produces InvalidCreationTime even for time_expires because
1501        // both fields share the same humantime::TimestampError #[from] conversion.
1502        assert!(Metadata::from_headers(&headers, "x-goog-meta-").is_err());
1503    }
1504
1505    #[test]
1506    fn serde_roundtrip_default() {
1507        let metadata = Metadata::default();
1508        let json = serde_json::to_string(&metadata).unwrap();
1509        let deserialized: Metadata = serde_json::from_str(&json).unwrap();
1510        assert_eq!(deserialized, metadata);
1511    }
1512
1513    #[test]
1514    fn serde_roundtrip_all_fields() {
1515        let metadata = Metadata {
1516            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1517            time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1518            time_expires: Some(Timestamp::from_unix_secs(1_700_003_600).unwrap()),
1519            content_type: "application/json".into(),
1520            compression: Some(Compression::Zstd),
1521            origin: Some("10.0.0.1".into()),
1522            filename: Some("data.json".into()),
1523            size: Some(1024),
1524            custom: BTreeMap::from([("key".into(), "value".into())]),
1525        };
1526
1527        let json = serde_json::to_string(&metadata).unwrap();
1528        let deserialized: Metadata = serde_json::from_str(&json).unwrap();
1529        assert_eq!(deserialized, metadata);
1530    }
1531
1532    #[test]
1533    fn size_roundtrips_through_headers() {
1534        let metadata = Metadata {
1535            size: Some(42),
1536            ..Default::default()
1537        };
1538
1539        let headers = metadata.to_headers("").unwrap();
1540        assert_eq!(headers.get(HEADER_SIZE).unwrap(), "42");
1541        assert_eq!(Metadata::from_headers(&headers, "").unwrap().size, Some(42));
1542    }
1543
1544    #[test]
1545    fn size_is_prefixed_in_headers() {
1546        let metadata = Metadata {
1547            size: Some(42),
1548            ..Default::default()
1549        };
1550
1551        let headers = metadata.to_headers("x-goog-meta-").unwrap();
1552        assert_eq!(headers.get("x-goog-meta-x-sn-size").unwrap(), "42");
1553    }
1554
1555    #[test]
1556    fn from_insert_headers_ignores_size() {
1557        // Size is materialized by the server; a client-supplied value must never be trusted.
1558        let mut headers = HeaderMap::new();
1559        headers.insert(HEADER_SIZE, "9999".parse().unwrap());
1560
1561        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1562        assert!(metadata.size.is_none());
1563    }
1564
1565    #[test]
1566    fn from_headers_rejects_malformed_size() {
1567        let mut headers = HeaderMap::new();
1568        headers.insert(HEADER_SIZE, "not-a-number".parse().unwrap());
1569
1570        assert!(matches!(
1571            Metadata::from_headers(&headers, ""),
1572            Err(Error::Size(_))
1573        ));
1574    }
1575
1576    #[test]
1577    fn default_metadata() {
1578        let metadata = Metadata::default();
1579        assert_eq!(metadata.content_type, DEFAULT_CONTENT_TYPE);
1580        assert_eq!(metadata.expiration_policy, ExpirationPolicy::Manual);
1581        assert!(metadata.compression.is_none());
1582        assert!(metadata.origin.is_none());
1583        assert!(metadata.filename.is_none());
1584        assert!(metadata.time_created.is_none());
1585        assert!(metadata.time_expires.is_none());
1586        assert!(metadata.size.is_none());
1587        assert!(metadata.custom.is_empty());
1588    }
1589
1590    #[test]
1591    fn expiration_display_roundtrip() {
1592        let cases = [
1593            ExpirationPolicy::Manual,
1594            ExpirationPolicy::TimeToLive(Duration::from_secs(30)),
1595            ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1596        ];
1597
1598        for policy in cases {
1599            let displayed = policy.to_string();
1600            let parsed: ExpirationPolicy = displayed.parse().unwrap();
1601            assert_eq!(parsed, policy);
1602        }
1603    }
1604
1605    #[test]
1606    fn expiration_parse_invalid() {
1607        assert!(ExpirationPolicy::from_str("garbage").is_err());
1608        assert!(ExpirationPolicy::from_str("ttl:").is_err());
1609        assert!(ExpirationPolicy::from_str("").is_err());
1610    }
1611
1612    #[test]
1613    fn expiration_policy_helpers() {
1614        assert_eq!(ExpirationPolicy::Manual.expires_in(), None);
1615        assert!(ExpirationPolicy::Manual.is_manual());
1616        assert!(!ExpirationPolicy::Manual.is_timeout());
1617
1618        let ttl = ExpirationPolicy::TimeToLive(Duration::from_mins(1));
1619        assert_eq!(ttl.expires_in(), Some(Duration::from_mins(1)));
1620        assert!(ttl.is_timeout());
1621        assert!(!ttl.is_manual());
1622
1623        let tti = ExpirationPolicy::TimeToIdle(Duration::from_mins(2));
1624        assert_eq!(tti.expires_in(), Some(Duration::from_mins(2)));
1625        assert!(tti.is_timeout());
1626        assert!(!tti.is_manual());
1627    }
1628
1629    #[test]
1630    fn compression_display_roundtrip() {
1631        for (compression, expected) in [(Compression::Zstd, "zstd"), (Compression::Gzip, "gzip")] {
1632            let displayed = compression.to_string();
1633            assert_eq!(displayed, expected);
1634            let parsed: Compression = displayed.parse().unwrap();
1635            assert_eq!(parsed, compression);
1636        }
1637    }
1638
1639    #[test]
1640    fn compression_parse_invalid() {
1641        assert!(Compression::from_str("lz4").is_err());
1642        assert!(Compression::from_str("").is_err());
1643    }
1644
1645    #[test]
1646    fn check_tti_bump_returns_none_for_manual() {
1647        let metadata = Metadata::default();
1648        assert!(metadata.check_tti_bump(Timestamp::now()).is_none());
1649    }
1650
1651    #[test]
1652    fn check_tti_bump_returns_none_for_ttl() {
1653        let now = Timestamp::now();
1654        let metadata = Metadata {
1655            expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_hours(1)),
1656            time_expires: Some(now + Duration::from_hours(1)),
1657            ..Default::default()
1658        };
1659        assert!(metadata.check_tti_bump(now).is_none());
1660    }
1661
1662    #[test]
1663    fn check_tti_bump_returns_none_when_fresh() {
1664        let now = Timestamp::now();
1665        let tti = Duration::from_hours(2 * 24);
1666        let metadata = Metadata {
1667            expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1668            time_expires: Some(now + tti),
1669            ..Default::default()
1670        };
1671        assert!(metadata.check_tti_bump(now).is_none());
1672    }
1673
1674    #[test]
1675    fn check_tti_bump_returns_new_deadline_when_stale() {
1676        let now = Timestamp::now();
1677        let tti = Duration::from_hours(2 * 24);
1678        let debounce = tti / 4;
1679        let stale_deadline = now + tti - debounce - Duration::from_mins(1);
1680        let metadata = Metadata {
1681            expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1682            time_expires: Some(stale_deadline),
1683            ..Default::default()
1684        };
1685        let new_deadline = metadata.check_tti_bump(now).unwrap();
1686        assert_eq!(new_deadline, now + tti);
1687    }
1688
1689    #[test]
1690    fn check_tti_bump_short_tti_triggers_bump() {
1691        let now = Timestamp::now();
1692        for tti in [
1693            Duration::from_hours(2),
1694            Duration::from_secs(3),
1695            Duration::from_secs(4),
1696        ] {
1697            let debounce = tti / 4;
1698            let new_deadline = now + tti;
1699            let mut metadata = Metadata {
1700                expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1701                time_expires: Some(new_deadline - Duration::from_secs(debounce.as_secs() + 1)),
1702                ..Default::default()
1703            };
1704            assert_eq!(metadata.check_tti_bump(now), Some(new_deadline));
1705            metadata.time_expires = Some(new_deadline - Duration::from_secs(debounce.as_secs()));
1706            assert!(metadata.check_tti_bump(now).is_none());
1707        }
1708    }
1709
1710    #[test]
1711    fn check_tti_bump_debounce_caps_at_24h() {
1712        let now = Timestamp::now();
1713        let tti = Duration::from_hours(30 * 24);
1714        let capped_debounce = Duration::from_hours(24);
1715        let stale_deadline = now + tti - capped_debounce - Duration::from_mins(1);
1716        let metadata = Metadata {
1717            expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1718            time_expires: Some(stale_deadline),
1719            ..Default::default()
1720        };
1721        assert!(metadata.check_tti_bump(now).is_some());
1722
1723        let fresh_deadline = now + tti - capped_debounce + Duration::from_mins(1);
1724        let metadata = Metadata {
1725            time_expires: Some(fresh_deadline),
1726            ..metadata
1727        };
1728        assert!(metadata.check_tti_bump(now).is_none());
1729    }
1730
1731    #[test]
1732    fn check_tti_bump_returns_none_when_time_expires_missing() {
1733        let metadata = Metadata {
1734            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1735            time_expires: None,
1736            ..Default::default()
1737        };
1738        assert!(metadata.check_tti_bump(Timestamp::now()).is_none());
1739    }
1740
1741    // JSON wire representation
1742
1743    fn write_json(json: &str) -> Result<Metadata, Error> {
1744        let insert: WriteMetadata = serde_json::from_str(json).unwrap();
1745        insert.into_metadata(Timestamp::from_unix_secs(1_700_000_000).unwrap())
1746    }
1747
1748    fn full_metadata() -> Metadata {
1749        Metadata {
1750            expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_hours(30 * 24)),
1751            time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1752            time_expires: Some(Timestamp::from_unix_secs(1_702_592_000).unwrap()),
1753            content_type: "image/png".into(),
1754            compression: Some(Compression::Zstd),
1755            origin: Some("203.0.113.42".into()),
1756            filename: Some("résumé.png".into()),
1757            size: Some(1024),
1758            custom: BTreeMap::from([("build".into(), "123".into())]),
1759        }
1760    }
1761
1762    #[test]
1763    fn write_metadata_minimal() {
1764        let metadata = write_json("{}").unwrap();
1765        assert_eq!(
1766            metadata,
1767            Metadata {
1768                time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1769                ..Default::default()
1770            }
1771        );
1772
1773        let json = serde_json::to_string(&WriteMetadata::from(Metadata::default())).unwrap();
1774        assert_eq!(json, "{}");
1775    }
1776
1777    #[test]
1778    fn write_metadata_full() {
1779        let expected = Metadata {
1780            size: None,
1781            ..full_metadata()
1782        };
1783
1784        let json = serde_json::to_string(&WriteMetadata::from(full_metadata())).unwrap();
1785        assert_eq!(
1786            json,
1787            r#"{"content_type":"image/png","content_encoding":"zstd","expiration":"ttl:30d","origin":"203.0.113.42","filename":"résumé.png","custom":{"build":"123"}}"#
1788        );
1789        assert_eq!(write_json(&json).unwrap(), expected);
1790    }
1791
1792    #[test]
1793    fn write_metadata_odd_cases() {
1794        // Unknown and read-only fields are ignored, custom keys are normalized, and strings are
1795        // never percent-decoded.
1796        let json = r#"{
1797            "future": 1,
1798            "size": 9,
1799            "time_created": "2020-01-01T00:00:00Z",
1800            "filename": "50%41.txt",
1801            "custom": {"Build": "100%25"}
1802        }"#;
1803        let metadata = write_json(json).unwrap();
1804        assert_eq!(
1805            metadata.time_created,
1806            Some(Timestamp::from_unix_secs(1_700_000_000).unwrap())
1807        );
1808        assert_eq!(metadata.size, None);
1809        assert_eq!(metadata.filename.as_deref(), Some("50%41.txt"));
1810        assert_eq!(metadata.custom["build"], "100%25");
1811
1812        for json in [
1813            r#"{"content_type":"not a media type!"}"#,
1814            r#"{"content_encoding":"brotli"}"#,
1815            r#"{"expiration":"garbage"}"#,
1816            r#"{"custom":{"a b":"v"}}"#,
1817        ] {
1818            assert!(write_json(json).is_err(), "unexpectedly accepted {json}");
1819        }
1820    }
1821
1822    #[test]
1823    fn write_metadata_matches_insert_headers() {
1824        let access_time = Timestamp::from_unix_secs(1_700_000_000).unwrap();
1825        for expiration in ["manual", "ttl:30d", "tti:1h"] {
1826            let mut headers = HeaderMap::new();
1827            headers.insert("content-type", "text/plain".parse().unwrap());
1828            headers.insert(HEADER_EXPIRATION, expiration.parse().unwrap());
1829            let from_headers = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
1830
1831            let json = format!(r#"{{"content_type":"text/plain","expiration":"{expiration}"}}"#);
1832            assert_eq!(write_json(&json).unwrap(), from_headers, "{expiration}");
1833        }
1834    }
1835
1836    #[test]
1837    fn read_metadata_minimal() {
1838        let json = serde_json::to_string(&ReadMetadata::from(Metadata::default())).unwrap();
1839        assert_eq!(json, r#"{"content_type":"application/octet-stream"}"#);
1840
1841        let object: ReadMetadata = serde_json::from_str(&json).unwrap();
1842        assert_eq!(Metadata::try_from(object).unwrap(), Metadata::default());
1843    }
1844
1845    #[test]
1846    fn read_metadata_full() {
1847        let json = serde_json::to_string_pretty(&ReadMetadata::from(full_metadata())).unwrap();
1848        insta::assert_snapshot!(json, @r#"
1849        {
1850          "content_type": "image/png",
1851          "content_encoding": "zstd",
1852          "expiration": "ttl:30d",
1853          "origin": "203.0.113.42",
1854          "filename": "résumé.png",
1855          "custom": {
1856            "build": "123"
1857          },
1858          "time_created": "2023-11-14T22:13:20Z",
1859          "time_expires": "2023-12-14T22:13:20Z",
1860          "size": 1024
1861        }
1862        "#);
1863
1864        let object: ReadMetadata = serde_json::from_str(&json).unwrap();
1865        assert_eq!(Metadata::try_from(object).unwrap(), full_metadata());
1866    }
1867
1868    #[test]
1869    fn read_metadata_odd_cases() {
1870        // Unknown fields are ignored and any stored custom key is accepted.
1871        let json = r#"{"content_type":"text/plain","future":1,"custom":{"a*b":"v"}}"#;
1872        let object: ReadMetadata = serde_json::from_str(json).unwrap();
1873        assert_eq!(Metadata::try_from(object).unwrap().custom["a*b"], "v");
1874
1875        let json = r#"{"content_type":"text/plain","expiration":"garbage"}"#;
1876        let object: ReadMetadata = serde_json::from_str(json).unwrap();
1877        assert!(Metadata::try_from(object).is_err());
1878    }
1879}