Skip to main content

artifact_api/
lib.rs

1//! Stable, storage-independent artifact references shared across mHome runtimes.
2
3use std::fmt;
4
5use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7
8#[macro_use]
9mod object_message;
10
11mod policy;
12pub use policy::{ArtifactIdentity, ArtifactPolicy, ArtifactRetention};
13mod media;
14mod put;
15mod resolve;
16mod stream_upload;
17mod upload;
18
19pub use stream_upload::{
20    ArtifactUploadReceipt, CancelArtifactUploadRequest, CancelArtifactUploadResponse,
21    CompleteArtifactUploadRequest, CompleteArtifactUploadResponse, StartArtifactUploadRequest,
22    StartArtifactUploadResponse,
23};
24
25pub use media::{ArtifactUri, ImportArtifactRequest, MediaReference};
26
27pub use put::{PutArtifactRequest, PutArtifactResponse, PutArtifactValidationError};
28
29pub use resolve::{
30    ArtifactDelivery, ArtifactDeliveryOptions, ArtifactDeliveryRoute, ArtifactDeliveryTransport,
31    ResolveArtifactRequest, ResolveArtifactResponse, ResolveArtifactResponseError,
32};
33pub use upload::{
34    PrepareArtifactUploadRequest, PrepareArtifactUploadResponse,
35    PrepareArtifactUploadValidationError,
36};
37
38/// Prefix of the version 3 artifact URI format.
39pub const ARTIFACT_URL_PREFIX: &str = "meow-artifact://v3/";
40const MAX_URI_LENGTH: usize = 2_048;
41const MAX_SEGMENT_LENGTH: usize = 256;
42const MAX_MIME_LENGTH: usize = 255;
43const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
44const MAX_DIMENSION: u32 = i32::MAX as u32;
45
46/// Logical media kind encoded in an artifact reference.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
49pub enum ArtifactKind {
50    Image,
51    Audio,
52    Video,
53    File,
54}
55
56impl ArtifactKind {
57    #[must_use]
58    pub const fn code(self) -> &'static str {
59        match self {
60            Self::Image => "i",
61            Self::Audio => "a",
62            Self::Video => "v",
63            Self::File => "f",
64        }
65    }
66
67    pub fn from_code(value: &str) -> Result<Self, ArtifactReferenceError> {
68        match value {
69            "i" => Ok(Self::Image),
70            "a" => Ok(Self::Audio),
71            "v" => Ok(Self::Video),
72            "f" => Ok(Self::File),
73            _ => Err(invalid("unsupported artifact kind")),
74        }
75    }
76}
77
78/// Immutable metadata encoded into an artifact URI.
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct ArtifactMetadata {
81    kind: ArtifactKind,
82    mime_type: String,
83    size_bytes: u64,
84    width: Option<u32>,
85    height: Option<u32>,
86    duration_millis: Option<u64>,
87}
88
89impl ArtifactMetadata {
90    pub fn image(
91        mime_type: impl Into<String>,
92        size_bytes: usize,
93        width: u32,
94        height: u32,
95    ) -> Result<Self, ArtifactReferenceError> {
96        Self::build(
97            ArtifactKind::Image,
98            mime_type,
99            size_bytes,
100            Some(width),
101            Some(height),
102            None,
103        )
104    }
105
106    pub fn audio(
107        mime_type: impl Into<String>,
108        size_bytes: usize,
109        duration_millis: Option<u64>,
110    ) -> Result<Self, ArtifactReferenceError> {
111        Self::build(
112            ArtifactKind::Audio,
113            mime_type,
114            size_bytes,
115            None,
116            None,
117            duration_millis,
118        )
119    }
120
121    pub fn file(
122        mime_type: impl Into<String>,
123        size_bytes: usize,
124    ) -> Result<Self, ArtifactReferenceError> {
125        Self::build(ArtifactKind::File, mime_type, size_bytes, None, None, None)
126    }
127
128    pub fn video(
129        mime_type: impl Into<String>,
130        size_bytes: usize,
131        width: u32,
132        height: u32,
133        duration_millis: Option<u64>,
134    ) -> Result<Self, ArtifactReferenceError> {
135        Self::build(
136            ArtifactKind::Video,
137            mime_type,
138            size_bytes,
139            Some(width),
140            Some(height),
141            duration_millis,
142        )
143    }
144
145    fn build(
146        kind: ArtifactKind,
147        mime_type: impl Into<String>,
148        size_bytes: usize,
149        width: Option<u32>,
150        height: Option<u32>,
151        duration_millis: Option<u64>,
152    ) -> Result<Self, ArtifactReferenceError> {
153        let metadata = Self {
154            kind,
155            mime_type: mime_type.into(),
156            size_bytes: size_bytes as u64,
157            width,
158            height,
159            duration_millis,
160        };
161        metadata.validate()?;
162        Ok(metadata)
163    }
164
165    #[must_use]
166    pub const fn kind(&self) -> ArtifactKind {
167        self.kind
168    }
169
170    #[must_use]
171    pub fn mime_type(&self) -> &str {
172        &self.mime_type
173    }
174
175    #[must_use]
176    pub const fn size_bytes(&self) -> u64 {
177        self.size_bytes
178    }
179
180    #[must_use]
181    pub const fn width(&self) -> Option<u32> {
182        self.width
183    }
184
185    #[must_use]
186    pub const fn height(&self) -> Option<u32> {
187        self.height
188    }
189
190    #[must_use]
191    pub const fn duration_millis(&self) -> Option<u64> {
192        self.duration_millis
193    }
194
195    fn validate(&self) -> Result<(), ArtifactReferenceError> {
196        validate_mime_type(&self.mime_type)?;
197        validate_size_bytes(self.size_bytes).map_err(invalid)?;
198        validate_duration_millis(self.kind, self.duration_millis).map_err(invalid)?;
199        match self.kind {
200            ArtifactKind::Image => {
201                if !self.mime_type.starts_with("image/") {
202                    return Err(invalid("image artifact MIME type is invalid"));
203                }
204                if self
205                    .width
206                    .is_none_or(|value| value == 0 || value > MAX_DIMENSION)
207                    || self
208                        .height
209                        .is_none_or(|value| value == 0 || value > MAX_DIMENSION)
210                {
211                    return Err(invalid("image artifact metadata is invalid"));
212                }
213            }
214            ArtifactKind::Audio => {
215                if !self.mime_type.starts_with("audio/") {
216                    return Err(invalid("audio artifact MIME type is invalid"));
217                }
218                if self.width.is_some() || self.height.is_some() {
219                    return Err(invalid("audio artifact metadata is invalid"));
220                }
221            }
222            ArtifactKind::Video => {
223                if !self.mime_type.starts_with("video/")
224                    || self
225                        .width
226                        .is_none_or(|value| value == 0 || value > MAX_DIMENSION)
227                    || self
228                        .height
229                        .is_none_or(|value| value == 0 || value > MAX_DIMENSION)
230                {
231                    return Err(invalid("video artifact metadata is invalid"));
232                }
233            }
234            ArtifactKind::File => {
235                if self.mime_type.starts_with("video/") {
236                    return Err(invalid("video artifacts are not supported"));
237                }
238                if self.width.is_some() || self.height.is_some() {
239                    return Err(invalid("file artifact metadata is invalid"));
240                }
241            }
242        }
243        Ok(())
244    }
245}
246
247#[derive(Serialize, Deserialize)]
248#[serde(deny_unknown_fields)]
249struct RawArtifactMetadata {
250    k: String,
251    m: String,
252    s: u64,
253    #[serde(
254        default,
255        skip_serializing_if = "Option::is_none",
256        deserialize_with = "deserialize_optional_non_null"
257    )]
258    w: Option<u32>,
259    #[serde(
260        default,
261        skip_serializing_if = "Option::is_none",
262        deserialize_with = "deserialize_optional_non_null"
263    )]
264    h: Option<u32>,
265    #[serde(
266        default,
267        skip_serializing_if = "Option::is_none",
268        deserialize_with = "deserialize_optional_non_null"
269    )]
270    d: Option<u64>,
271}
272
273impl Serialize for ArtifactMetadata {
274    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
275    where
276        S: Serializer,
277    {
278        RawArtifactMetadata {
279            k: self.kind.code().to_string(),
280            m: self.mime_type.clone(),
281            s: self.size_bytes,
282            w: self.width,
283            h: self.height,
284            d: self.duration_millis,
285        }
286        .serialize(serializer)
287    }
288}
289
290impl<'de> Deserialize<'de> for ArtifactMetadata {
291    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
292    where
293        D: Deserializer<'de>,
294    {
295        let raw = RawArtifactMetadata::deserialize(deserializer)?;
296        let metadata = Self {
297            kind: ArtifactKind::from_code(&raw.k).map_err(serde::de::Error::custom)?,
298            mime_type: raw.m,
299            size_bytes: raw.s,
300            width: raw.w,
301            height: raw.h,
302            duration_millis: raw.d,
303        };
304        metadata.validate().map_err(serde::de::Error::custom)?;
305        Ok(metadata)
306    }
307}
308
309/// Canonical, scope-owned, content-addressed artifact identity.
310#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct ArtifactReference {
312    tenant_id: String,
313    scope_id: String,
314    sha256: String,
315    policy: ArtifactPolicy,
316    creation_id: Option<String>,
317    metadata: ArtifactMetadata,
318}
319
320impl ArtifactReference {
321    pub fn new(
322        tenant_id: impl Into<String>,
323        scope_id: impl Into<String>,
324        sha256: impl Into<String>,
325        metadata: ArtifactMetadata,
326    ) -> Result<Self, ArtifactReferenceError> {
327        Self::with_policy(
328            tenant_id,
329            scope_id,
330            sha256,
331            metadata,
332            ArtifactPolicy::AUTO_STD,
333            None,
334        )
335    }
336
337    pub fn with_policy(
338        tenant_id: impl Into<String>,
339        scope_id: impl Into<String>,
340        sha256: impl Into<String>,
341        metadata: ArtifactMetadata,
342        policy: ArtifactPolicy,
343        creation_id: Option<String>,
344    ) -> Result<Self, ArtifactReferenceError> {
345        let reference = Self {
346            policy,
347            creation_id,
348            tenant_id: tenant_id.into(),
349            scope_id: scope_id.into(),
350            sha256: sha256.into(),
351            metadata,
352        };
353        reference.validate()?;
354        Ok(reference)
355    }
356
357    pub fn parse(value: &str) -> Result<Self, ArtifactReferenceError> {
358        if value.len() > MAX_URI_LENGTH {
359            return Err(invalid("artifact URI is too long"));
360        }
361        let path = value
362            .strip_prefix(ARTIFACT_URL_PREFIX)
363            .ok_or_else(|| invalid("unsupported artifact URI"))?;
364        let segments = path.split('/').collect::<Vec<_>>();
365        if segments.len() != 7 {
366            return Err(invalid(
367                "artifact URI must contain tenant, scope, retention, identity, resource ID, digest, and metadata",
368            ));
369        }
370        let metadata_bytes = URL_SAFE_NO_PAD
371            .decode(segments[6])
372            .map_err(|_| invalid("artifact metadata is not valid base64url"))?;
373        let metadata: ArtifactMetadata = serde_json::from_slice(&metadata_bytes)
374            .map_err(|_| invalid("artifact metadata is invalid"))?;
375        let policy = ArtifactPolicy::new(
376            ArtifactIdentity::from_code(segments[3])?,
377            ArtifactRetention::from_code(segments[2])?,
378        );
379        let creation_id = if policy.identity == ArtifactIdentity::Man {
380            Some(segments[4].to_owned())
381        } else {
382            if segments[4] != segments[5] {
383                return Err(invalid("artifact resource ID must equal its digest"));
384            }
385            None
386        };
387        let reference = Self::with_policy(
388            segments[0],
389            segments[1],
390            segments[5],
391            metadata,
392            policy,
393            creation_id,
394        )?;
395        if reference.uri()? != value {
396            return Err(invalid("artifact URI is not canonical"));
397        }
398        Ok(reference)
399    }
400
401    pub fn uri(&self) -> Result<String, ArtifactReferenceError> {
402        self.validate()?;
403        let metadata = serde_json::to_vec(&self.metadata)
404            .map_err(|_| invalid("artifact metadata cannot be encoded"))?;
405        Ok(format!(
406            "{ARTIFACT_URL_PREFIX}{}/{}/{}/{}/{}/{}/{}",
407            self.tenant_id,
408            self.scope_id,
409            self.policy.retention.code(),
410            self.policy.identity.code(),
411            self.resource_id(),
412            self.sha256,
413            URL_SAFE_NO_PAD.encode(metadata)
414        ))
415    }
416
417    #[must_use]
418    pub fn tenant_id(&self) -> &str {
419        &self.tenant_id
420    }
421
422    #[must_use]
423    pub fn scope_id(&self) -> &str {
424        &self.scope_id
425    }
426
427    #[must_use]
428    pub fn sha256(&self) -> &str {
429        &self.sha256
430    }
431
432    #[must_use]
433    pub const fn metadata(&self) -> &ArtifactMetadata {
434        &self.metadata
435    }
436
437    pub const fn policy(&self) -> ArtifactPolicy {
438        self.policy
439    }
440
441    pub fn resource_id(&self) -> &str {
442        self.creation_id.as_deref().unwrap_or(&self.sha256)
443    }
444
445    pub fn creation_id(&self) -> Option<&str> {
446        self.creation_id.as_deref()
447    }
448
449    pub fn ensure_scope(
450        &self,
451        tenant_id: &str,
452        scope_id: &str,
453    ) -> Result<(), ArtifactReferenceError> {
454        if self.tenant_id != tenant_id || self.scope_id != scope_id {
455            return Err(ArtifactReferenceError::new(
456                ArtifactReferenceErrorKind::ScopeMismatch,
457                "artifact does not belong to the current scope",
458            ));
459        }
460        Ok(())
461    }
462
463    fn validate(&self) -> Result<(), ArtifactReferenceError> {
464        self.policy
465            .validate_creation_id(self.creation_id.as_deref())?;
466        validate_segment(&self.tenant_id, "tenant")?;
467        validate_segment(&self.scope_id, "scope")?;
468        if self.sha256.len() != 64
469            || !self
470                .sha256
471                .bytes()
472                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
473        {
474            return Err(invalid("artifact sha256 is invalid"));
475        }
476        self.metadata.validate()
477    }
478}
479
480// Serde's default Option handling conflates omission with null. Wire fields are optional,
481// but an explicitly supplied value must deserialize as T, matching the published schemas.
482fn deserialize_optional_non_null<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
483where
484    D: Deserializer<'de>,
485    T: Deserialize<'de>,
486{
487    T::deserialize(deserializer).map(Some)
488}
489
490fn validate_size_bytes(size_bytes: u64) -> Result<(), &'static str> {
491    if size_bytes == 0 || size_bytes > MAX_SAFE_INTEGER {
492        return Err("artifact size is invalid");
493    }
494    Ok(())
495}
496
497fn validate_duration_millis(
498    kind: ArtifactKind,
499    duration_millis: Option<u64>,
500) -> Result<(), &'static str> {
501    if let Some(duration) = duration_millis {
502        if !matches!(kind, ArtifactKind::Audio | ArtifactKind::Video) {
503            return Err("artifact duration is only valid for audio or video");
504        }
505        if duration == 0 || duration > MAX_SAFE_INTEGER {
506            return Err("artifact duration is invalid");
507        }
508    }
509    Ok(())
510}
511
512fn validate_segment(value: &str, name: &str) -> Result<(), ArtifactReferenceError> {
513    if value.is_empty()
514        || value.len() > MAX_SEGMENT_LENGTH
515        || value == "."
516        || value == ".."
517        || !value
518            .bytes()
519            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
520    {
521        return Err(invalid(format!("artifact {name} is not URL-safe")));
522    }
523    Ok(())
524}
525
526fn validate_mime_type(value: &str) -> Result<(), ArtifactReferenceError> {
527    if value.is_empty()
528        || value.len() > MAX_MIME_LENGTH
529        || value != value.trim()
530        || value.bytes().any(|byte| byte.is_ascii_uppercase())
531    {
532        return Err(invalid("artifact MIME type is invalid"));
533    }
534    let Some((media_type, subtype)) = value.split_once('/') else {
535        return Err(invalid("artifact MIME type is invalid"));
536    };
537    if media_type.is_empty()
538        || subtype.is_empty()
539        || subtype.contains('/')
540        || !value.bytes().all(|byte| {
541            byte.is_ascii_lowercase()
542                || byte.is_ascii_digit()
543                || matches!(
544                    byte,
545                    b'!' | b'#' | b'$' | b'&' | b'^' | b'_' | b'.' | b'+' | b'-' | b'/'
546                )
547        })
548    {
549        return Err(invalid("artifact MIME type is invalid"));
550    }
551    Ok(())
552}
553
554/// Stable category for reference validation failures.
555#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556pub enum ArtifactReferenceErrorKind {
557    InvalidReference,
558    ScopeMismatch,
559}
560
561/// Validation error returned for malformed or cross-scope references.
562#[derive(Debug, Clone, PartialEq, Eq)]
563pub struct ArtifactReferenceError {
564    kind: ArtifactReferenceErrorKind,
565    message: String,
566}
567
568impl ArtifactReferenceError {
569    fn new(kind: ArtifactReferenceErrorKind, message: impl Into<String>) -> Self {
570        Self {
571            kind,
572            message: message.into(),
573        }
574    }
575
576    #[must_use]
577    pub const fn kind(&self) -> ArtifactReferenceErrorKind {
578        self.kind
579    }
580
581    #[must_use]
582    pub fn message(&self) -> &str {
583        &self.message
584    }
585
586    #[must_use]
587    pub const fn is_scope_mismatch(&self) -> bool {
588        matches!(self.kind, ArtifactReferenceErrorKind::ScopeMismatch)
589    }
590}
591
592impl fmt::Display for ArtifactReferenceError {
593    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
594        formatter.write_str(&self.message)
595    }
596}
597
598impl std::error::Error for ArtifactReferenceError {}
599
600fn invalid(message: impl Into<String>) -> ArtifactReferenceError {
601    ArtifactReferenceError::new(ArtifactReferenceErrorKind::InvalidReference, message)
602}
603
604/// Public upload/import policy, not a limit on internally generated artifacts.
605pub const MAX_EXTERNAL_ARTIFACT_BYTES: usize = 1024 * 1024;
606
607#[cfg(test)]
608mod tests {
609    use super::*;
610
611    #[test]
612    fn scope_owned_reference_round_trips() {
613        let reference = ArtifactReference::new(
614            "tenant",
615            "scope",
616            "a".repeat(64),
617            ArtifactMetadata::image("image/jpeg", 100, 10, 10).unwrap(),
618        )
619        .unwrap();
620        assert_eq!(
621            reference.uri().unwrap(),
622            format!(
623                "meow-artifact://v3/tenant/scope/std/auto/{0}/{0}/eyJrIjoiaSIsIm0iOiJpbWFnZS9qcGVnIiwicyI6MTAwLCJ3IjoxMCwiaCI6MTB9",
624                "a".repeat(64)
625            )
626        );
627        assert_eq!(
628            ArtifactReference::parse(&reference.uri().unwrap()).unwrap(),
629            reference
630        );
631    }
632
633    #[test]
634    fn rejects_cross_scope_and_invalid_metadata() {
635        let reference = ArtifactReference::new(
636            "tenant",
637            "scope",
638            "a".repeat(64),
639            ArtifactMetadata::audio("audio/mpeg", 100, Some(1_000)).unwrap(),
640        )
641        .unwrap();
642
643        assert_eq!(
644            reference
645                .ensure_scope("tenant", "other")
646                .unwrap_err()
647                .kind(),
648            ArtifactReferenceErrorKind::ScopeMismatch
649        );
650        assert!(ArtifactMetadata::audio("image/png", 100, None).is_err());
651        assert!(ArtifactMetadata::file("video/mp4", 100).is_err());
652        assert!(ArtifactMetadata::video("video/mp4", 100, 1920, 1080, Some(1_000)).is_ok());
653        assert!(ArtifactMetadata::file("Application/PDF", 100).is_err());
654    }
655}
656
657object_message! {
658/// TLS identity of a local file endpoint, delivered over the authenticated business channel.
659/// It grants no Host management authority. Public cloud URLs omit this field.
660pub struct HostTlsIdentity {
661    pub host_id: String,
662    pub public_key: HostTlsPublicKey,
663}
664}
665object_message! {
666pub struct HostTlsPublicKey {
667    pub x: String,
668    pub y: String,
669}
670}
671
672/// Deletion accepts only the canonical URI, without delivery requirements.
673#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
674#[serde(deny_unknown_fields)]
675pub struct ArtifactUriRequest {
676    pub uri: String,
677}
678
679/// Delete only the selected canonical Artifact identity.
680pub type DeleteArtifactRequest = ArtifactUriRequest;