1use std::{borrow::Borrow, collections::BTreeMap, fmt, str::FromStr};
7
8use mime::Mime;
9use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
10use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
11use thiserror::Error;
12
13use crate::{
14 ArtifactId, ByteCount, CapabilityReference, ContentMetadata, ContentSource, Digest, EventId,
15 JsonContent, PrincipalIdentity, RunId, SchemaReference, TenantId, TextContent,
16};
17
18const MEDIA_TYPE_PATTERN: &str =
19 "^[a-z0-9][a-z0-9!#$&.^_+-]{0,126}/[a-z0-9][a-z0-9!#$&.^_+-]{0,126}(?:;.*)?$";
20const RETENTION_CLASS_PATTERN: &str = "^[A-Za-z0-9][A-Za-z0-9._:/-]{0,63}$";
21
22#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
31pub struct MediaType(Box<str>);
32
33impl MediaType {
34 pub const MAX_LEN: usize = 512;
36
37 pub const MAX_PARAMETERS: usize = 16;
39
40 pub const MAX_PARAMETER_VALUE_LEN: usize = 128;
42
43 pub fn new(value: impl AsRef<str>) -> Result<Self, MediaTypeError> {
50 let value = value.as_ref();
51 if value.is_empty() {
52 return Err(MediaTypeError::Empty);
53 }
54 if value.len() > Self::MAX_LEN {
55 return Err(MediaTypeError::TooLong {
56 max: Self::MAX_LEN,
57 actual: value.len(),
58 });
59 }
60
61 let parsed = value
62 .parse::<Mime>()
63 .map_err(|_| MediaTypeError::InvalidSyntax)?;
64 let essence = parsed.essence_str();
65 let (top_level, subtype) = essence
66 .split_once('/')
67 .ok_or(MediaTypeError::InvalidSyntax)?;
68
69 if top_level == "*" || subtype == "*" {
70 return Err(MediaTypeError::WildcardNotAllowed);
71 }
72 if !is_restricted_name(top_level) {
73 return Err(MediaTypeError::InvalidTypeName);
74 }
75 if !is_restricted_name(subtype) {
76 return Err(MediaTypeError::InvalidSubtypeName);
77 }
78
79 let mut parameters = BTreeMap::new();
80 for (index, (name, parameter_value)) in parsed.params().enumerate() {
81 let actual = index + 1;
82 if actual > Self::MAX_PARAMETERS {
83 return Err(MediaTypeError::TooManyParameters {
84 max: Self::MAX_PARAMETERS,
85 actual,
86 });
87 }
88
89 let name = name.as_str();
90 if !is_restricted_name(name) {
91 return Err(MediaTypeError::InvalidParameterName);
92 }
93
94 let parameter_value = parameter_value.as_str();
95 if parameter_value.len() > Self::MAX_PARAMETER_VALUE_LEN {
96 return Err(MediaTypeError::ParameterValueTooLong {
97 max: Self::MAX_PARAMETER_VALUE_LEN,
98 actual: parameter_value.len(),
99 });
100 }
101 if !is_supported_parameter_value(parameter_value) {
102 return Err(MediaTypeError::InvalidParameterValue);
103 }
104
105 if parameters
106 .insert(name.to_owned(), parameter_value.to_owned())
107 .is_some()
108 {
109 return Err(MediaTypeError::DuplicateParameter);
110 }
111 }
112
113 let mut canonical = String::with_capacity(value.len());
114 canonical.push_str(essence);
115 for (name, parameter_value) in parameters {
116 canonical.push(';');
117 canonical.push_str(&name);
118 canonical.push('=');
119 push_canonical_parameter_value(&mut canonical, ¶meter_value);
120 }
121
122 if canonical.len() > Self::MAX_LEN {
123 return Err(MediaTypeError::TooLong {
124 max: Self::MAX_LEN,
125 actual: canonical.len(),
126 });
127 }
128
129 Ok(Self(canonical.into_boxed_str()))
130 }
131
132 #[must_use]
134 pub fn as_str(&self) -> &str {
135 &self.0
136 }
137
138 #[must_use]
140 pub fn essence(&self) -> &str {
141 self.as_str()
142 .split_once(';')
143 .map_or(self.as_str(), |(essence, _)| essence)
144 }
145
146 #[must_use]
148 pub fn top_level(&self) -> &str {
149 self.essence()
150 .split_once('/')
151 .map_or("", |(top_level, _)| top_level)
152 }
153
154 #[must_use]
156 pub fn subtype(&self) -> &str {
157 self.essence()
158 .split_once('/')
159 .map_or("", |(_, subtype)| subtype)
160 }
161}
162
163impl AsRef<str> for MediaType {
164 fn as_ref(&self) -> &str {
165 self.as_str()
166 }
167}
168
169impl Borrow<str> for MediaType {
170 fn borrow(&self) -> &str {
171 self.as_str()
172 }
173}
174
175impl fmt::Debug for MediaType {
176 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
177 formatter
178 .debug_tuple("MediaType")
179 .field(&self.as_str())
180 .finish()
181 }
182}
183
184impl fmt::Display for MediaType {
185 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
186 formatter.write_str(self.as_str())
187 }
188}
189
190impl FromStr for MediaType {
191 type Err = MediaTypeError;
192
193 fn from_str(value: &str) -> Result<Self, Self::Err> {
194 Self::new(value)
195 }
196}
197
198impl TryFrom<String> for MediaType {
199 type Error = MediaTypeError;
200
201 fn try_from(value: String) -> Result<Self, Self::Error> {
202 Self::new(value)
203 }
204}
205
206impl TryFrom<&str> for MediaType {
207 type Error = MediaTypeError;
208
209 fn try_from(value: &str) -> Result<Self, Self::Error> {
210 Self::new(value)
211 }
212}
213
214impl From<MediaType> for String {
215 fn from(value: MediaType) -> Self {
216 value.0.into()
217 }
218}
219
220impl Serialize for MediaType {
221 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
222 where
223 S: Serializer,
224 {
225 serializer.serialize_str(self.as_str())
226 }
227}
228
229impl<'de> Deserialize<'de> for MediaType {
230 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
231 where
232 D: Deserializer<'de>,
233 {
234 deserializer.deserialize_string(MediaTypeVisitor)
235 }
236}
237
238struct MediaTypeVisitor;
239
240impl de::Visitor<'_> for MediaTypeVisitor {
241 type Value = MediaType;
242
243 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
244 formatter.write_str("a bounded concrete RFC media type")
245 }
246
247 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
248 where
249 E: de::Error,
250 {
251 MediaType::new(value).map_err(E::custom)
252 }
253
254 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
255 where
256 E: de::Error,
257 {
258 MediaType::new(value).map_err(E::custom)
259 }
260}
261
262impl JsonSchema for MediaType {
263 fn schema_name() -> std::borrow::Cow<'static, str> {
264 "MediaType".into()
265 }
266
267 fn schema_id() -> std::borrow::Cow<'static, str> {
268 concat!(module_path!(), "::MediaType").into()
269 }
270
271 fn json_schema(_: &mut SchemaGenerator) -> Schema {
272 json_schema!({
273 "type": "string",
274 "minLength": 3,
275 "maxLength": 512,
276 "pattern": MEDIA_TYPE_PATTERN,
277 "description": "A canonical concrete media type. StateKnot additionally enforces RFC name syntax, unique sorted parameters, parameter count/value bounds, and canonical quoting at runtime."
278 })
279 }
280
281 fn inline_schema() -> bool {
282 true
283 }
284}
285
286#[derive(Clone, Debug, Eq, Error, PartialEq)]
288#[non_exhaustive]
289pub enum MediaTypeError {
290 #[error("media type must not be empty")]
292 Empty,
293
294 #[error("media type is {actual} bytes; maximum is {max}")]
296 TooLong {
297 max: usize,
299 actual: usize,
301 },
302
303 #[error("media type syntax is invalid")]
305 InvalidSyntax,
306
307 #[error("artifact media type must not contain a wildcard")]
309 WildcardNotAllowed,
310
311 #[error("media top-level type violates RFC 6838 restricted-name syntax")]
313 InvalidTypeName,
314
315 #[error("media subtype violates RFC 6838 restricted-name syntax")]
317 InvalidSubtypeName,
318
319 #[error("media parameter name violates RFC 6838 restricted-name syntax")]
321 InvalidParameterName,
322
323 #[error("media type contains a duplicate parameter name")]
325 DuplicateParameter,
326
327 #[error("media type has {actual} parameters; maximum is {max}")]
329 TooManyParameters {
330 max: usize,
332 actual: usize,
334 },
335
336 #[error("media parameter value is {actual} bytes; maximum is {max}")]
338 ParameterValueTooLong {
339 max: usize,
341 actual: usize,
343 },
344
345 #[error("media parameter value uses unsupported or ambiguous characters")]
347 InvalidParameterValue,
348}
349
350fn is_restricted_name(value: &str) -> bool {
351 let bytes = value.as_bytes();
352 if bytes.is_empty() || bytes.len() > 127 || !bytes[0].is_ascii_alphanumeric() {
353 return false;
354 }
355
356 bytes.iter().copied().skip(1).all(|byte| {
357 byte.is_ascii_alphanumeric()
358 || matches!(
359 byte,
360 b'!' | b'#' | b'$' | b'&' | b'-' | b'^' | b'_' | b'.' | b'+'
361 )
362 })
363}
364
365fn is_http_token_byte(byte: u8) -> bool {
366 byte.is_ascii_alphanumeric()
367 || matches!(
368 byte,
369 b'!' | b'#'
370 | b'$'
371 | b'%'
372 | b'&'
373 | b'\''
374 | b'*'
375 | b'+'
376 | b'-'
377 | b'.'
378 | b'^'
379 | b'_'
380 | b'`'
381 | b'|'
382 | b'~'
383 )
384}
385
386fn is_supported_parameter_value(value: &str) -> bool {
387 !value.is_empty()
388 && value
389 .bytes()
390 .all(|byte| (0x20..=0x7e).contains(&byte) && !matches!(byte, b'"' | b'\\'))
391}
392
393fn push_canonical_parameter_value(output: &mut String, value: &str) {
394 if value.bytes().all(is_http_token_byte) {
395 output.push_str(value);
396 } else {
397 output.push('"');
398 output.push_str(value);
399 output.push('"');
400 }
401}
402
403#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
410pub struct ArtifactName(Box<str>);
411
412impl ArtifactName {
413 pub const MAX_BYTES: usize = 255;
415
416 pub fn new(value: impl Into<String>) -> Result<Self, ArtifactNameError> {
423 let value = value.into();
424 validate_artifact_name(&value)?;
425 Ok(Self(value.into_boxed_str()))
426 }
427
428 #[must_use]
430 pub fn as_str(&self) -> &str {
431 &self.0
432 }
433}
434
435impl AsRef<str> for ArtifactName {
436 fn as_ref(&self) -> &str {
437 self.as_str()
438 }
439}
440
441impl Borrow<str> for ArtifactName {
442 fn borrow(&self) -> &str {
443 self.as_str()
444 }
445}
446
447impl fmt::Debug for ArtifactName {
448 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
449 formatter
450 .debug_struct("ArtifactName")
451 .field("utf8_bytes", &self.0.len())
452 .finish_non_exhaustive()
453 }
454}
455
456impl FromStr for ArtifactName {
457 type Err = ArtifactNameError;
458
459 fn from_str(value: &str) -> Result<Self, Self::Err> {
460 Self::new(value)
461 }
462}
463
464impl TryFrom<String> for ArtifactName {
465 type Error = ArtifactNameError;
466
467 fn try_from(value: String) -> Result<Self, Self::Error> {
468 Self::new(value)
469 }
470}
471
472impl TryFrom<&str> for ArtifactName {
473 type Error = ArtifactNameError;
474
475 fn try_from(value: &str) -> Result<Self, Self::Error> {
476 Self::new(value)
477 }
478}
479
480impl From<ArtifactName> for String {
481 fn from(value: ArtifactName) -> Self {
482 value.0.into()
483 }
484}
485
486impl Serialize for ArtifactName {
487 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
488 where
489 S: Serializer,
490 {
491 serializer.serialize_str(self.as_str())
492 }
493}
494
495impl<'de> Deserialize<'de> for ArtifactName {
496 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
497 where
498 D: Deserializer<'de>,
499 {
500 deserializer.deserialize_string(ArtifactNameVisitor)
501 }
502}
503
504struct ArtifactNameVisitor;
505
506impl de::Visitor<'_> for ArtifactNameVisitor {
507 type Value = ArtifactName;
508
509 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
510 formatter.write_str("a bounded logical artifact name")
511 }
512
513 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
514 where
515 E: de::Error,
516 {
517 ArtifactName::new(value).map_err(E::custom)
518 }
519
520 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
521 where
522 E: de::Error,
523 {
524 ArtifactName::new(value).map_err(E::custom)
525 }
526}
527
528impl JsonSchema for ArtifactName {
529 fn schema_name() -> std::borrow::Cow<'static, str> {
530 "ArtifactName".into()
531 }
532
533 fn schema_id() -> std::borrow::Cow<'static, str> {
534 concat!(module_path!(), "::ArtifactName").into()
535 }
536
537 fn json_schema(_: &mut SchemaGenerator) -> Schema {
538 json_schema!({
539 "type": "string",
540 "minLength": 1,
541 "maxLength": 255,
542 "description": "A logical artifact name bounded to 255 UTF-8 bytes. StateKnot rejects path separators, dot-segments, leading/trailing whitespace, controls, and Unicode noncharacters at runtime."
543 })
544 }
545
546 fn inline_schema() -> bool {
547 true
548 }
549}
550
551#[derive(Clone, Debug, Eq, Error, PartialEq)]
553#[non_exhaustive]
554pub enum ArtifactNameError {
555 #[error("artifact name must not be empty")]
557 Empty,
558
559 #[error("artifact name is {actual} UTF-8 bytes; maximum is {max}")]
561 TooLong {
562 max: usize,
564 actual: usize,
566 },
567
568 #[error("artifact name must not be a path dot-segment")]
570 PathLike,
571
572 #[error("artifact name must not begin or end with whitespace")]
574 BoundaryWhitespace,
575
576 #[error("artifact name contains a path separator at UTF-8 byte offset {byte_index}")]
578 PathSeparator {
579 byte_index: usize,
581 },
582
583 #[error("artifact name contains a disallowed Unicode scalar at UTF-8 byte offset {byte_index}")]
585 DisallowedCodePoint {
586 byte_index: usize,
588 },
589}
590
591fn validate_artifact_name(value: &str) -> Result<(), ArtifactNameError> {
592 if value.is_empty() {
593 return Err(ArtifactNameError::Empty);
594 }
595 if value.len() > ArtifactName::MAX_BYTES {
596 return Err(ArtifactNameError::TooLong {
597 max: ArtifactName::MAX_BYTES,
598 actual: value.len(),
599 });
600 }
601 if matches!(value, "." | "..") {
602 return Err(ArtifactNameError::PathLike);
603 }
604 if value.chars().next().is_some_and(char::is_whitespace)
605 || value.chars().next_back().is_some_and(char::is_whitespace)
606 {
607 return Err(ArtifactNameError::BoundaryWhitespace);
608 }
609 if let Some((byte_index, _)) = value
610 .char_indices()
611 .find(|(_, scalar)| matches!(scalar, '/' | '\\'))
612 {
613 return Err(ArtifactNameError::PathSeparator { byte_index });
614 }
615 if let Some((byte_index, _)) = value
616 .char_indices()
617 .find(|(_, scalar)| scalar.is_control() || is_unicode_noncharacter(*scalar))
618 {
619 return Err(ArtifactNameError::DisallowedCodePoint { byte_index });
620 }
621
622 Ok(())
623}
624
625#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
630pub struct ArtifactDescription(Box<str>);
631
632impl ArtifactDescription {
633 pub const MAX_BYTES: usize = 4096;
635
636 pub fn new(value: impl Into<String>) -> Result<Self, ArtifactDescriptionError> {
643 let value = value.into();
644 validate_artifact_description(&value)?;
645 Ok(Self(value.into_boxed_str()))
646 }
647
648 #[must_use]
650 pub fn as_str(&self) -> &str {
651 &self.0
652 }
653}
654
655impl AsRef<str> for ArtifactDescription {
656 fn as_ref(&self) -> &str {
657 self.as_str()
658 }
659}
660
661impl fmt::Debug for ArtifactDescription {
662 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
663 formatter
664 .debug_struct("ArtifactDescription")
665 .field("utf8_bytes", &self.0.len())
666 .finish_non_exhaustive()
667 }
668}
669
670impl FromStr for ArtifactDescription {
671 type Err = ArtifactDescriptionError;
672
673 fn from_str(value: &str) -> Result<Self, Self::Err> {
674 Self::new(value)
675 }
676}
677
678impl TryFrom<String> for ArtifactDescription {
679 type Error = ArtifactDescriptionError;
680
681 fn try_from(value: String) -> Result<Self, Self::Error> {
682 Self::new(value)
683 }
684}
685
686impl TryFrom<&str> for ArtifactDescription {
687 type Error = ArtifactDescriptionError;
688
689 fn try_from(value: &str) -> Result<Self, Self::Error> {
690 Self::new(value)
691 }
692}
693
694impl From<ArtifactDescription> for String {
695 fn from(value: ArtifactDescription) -> Self {
696 value.0.into()
697 }
698}
699
700impl Serialize for ArtifactDescription {
701 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
702 where
703 S: Serializer,
704 {
705 serializer.serialize_str(self.as_str())
706 }
707}
708
709impl<'de> Deserialize<'de> for ArtifactDescription {
710 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
711 where
712 D: Deserializer<'de>,
713 {
714 deserializer.deserialize_string(ArtifactDescriptionVisitor)
715 }
716}
717
718struct ArtifactDescriptionVisitor;
719
720impl de::Visitor<'_> for ArtifactDescriptionVisitor {
721 type Value = ArtifactDescription;
722
723 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
724 formatter.write_str("a bounded human-readable artifact description")
725 }
726
727 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
728 where
729 E: de::Error,
730 {
731 ArtifactDescription::new(value).map_err(E::custom)
732 }
733
734 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
735 where
736 E: de::Error,
737 {
738 ArtifactDescription::new(value).map_err(E::custom)
739 }
740}
741
742impl JsonSchema for ArtifactDescription {
743 fn schema_name() -> std::borrow::Cow<'static, str> {
744 "ArtifactDescription".into()
745 }
746
747 fn schema_id() -> std::borrow::Cow<'static, str> {
748 concat!(module_path!(), "::ArtifactDescription").into()
749 }
750
751 fn json_schema(_: &mut SchemaGenerator) -> Schema {
752 json_schema!({
753 "type": "string",
754 "minLength": 1,
755 "maxLength": 4096,
756 "description": "A description bounded to 4096 UTF-8 bytes. StateKnot rejects disallowed controls and Unicode noncharacters at runtime."
757 })
758 }
759
760 fn inline_schema() -> bool {
761 true
762 }
763}
764
765#[derive(Clone, Debug, Eq, Error, PartialEq)]
767#[non_exhaustive]
768pub enum ArtifactDescriptionError {
769 #[error("artifact description must not be empty")]
771 Empty,
772
773 #[error("artifact description is {actual} UTF-8 bytes; maximum is {max}")]
775 TooLong {
776 max: usize,
778 actual: usize,
780 },
781
782 #[error(
784 "artifact description contains a disallowed Unicode scalar at UTF-8 byte offset {byte_index}"
785 )]
786 DisallowedCodePoint {
787 byte_index: usize,
789 },
790}
791
792fn validate_artifact_description(value: &str) -> Result<(), ArtifactDescriptionError> {
793 if value.is_empty() {
794 return Err(ArtifactDescriptionError::Empty);
795 }
796 if value.len() > ArtifactDescription::MAX_BYTES {
797 return Err(ArtifactDescriptionError::TooLong {
798 max: ArtifactDescription::MAX_BYTES,
799 actual: value.len(),
800 });
801 }
802 if let Some((byte_index, _)) = value.char_indices().find(|(_, scalar)| {
803 (scalar.is_control() && !matches!(scalar, '\t' | '\n' | '\r'))
804 || is_unicode_noncharacter(*scalar)
805 }) {
806 return Err(ArtifactDescriptionError::DisallowedCodePoint { byte_index });
807 }
808 Ok(())
809}
810
811const fn is_unicode_noncharacter(value: char) -> bool {
812 let value = value as u32;
813 (value >= 0xfdd0 && value <= 0xfdef) || (value & 0xfffe) == 0xfffe
814}
815
816#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
822pub struct RetentionClass(Box<str>);
823
824impl RetentionClass {
825 pub const MAX_LEN: usize = 64;
827
828 pub fn new(value: impl Into<String>) -> Result<Self, RetentionClassError> {
835 let value = value.into();
836 validate_retention_class(&value)?;
837 Ok(Self(value.into_boxed_str()))
838 }
839
840 #[must_use]
842 pub fn as_str(&self) -> &str {
843 &self.0
844 }
845}
846
847impl AsRef<str> for RetentionClass {
848 fn as_ref(&self) -> &str {
849 self.as_str()
850 }
851}
852
853impl Borrow<str> for RetentionClass {
854 fn borrow(&self) -> &str {
855 self.as_str()
856 }
857}
858
859impl fmt::Debug for RetentionClass {
860 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
861 formatter
862 .debug_tuple("RetentionClass")
863 .field(&self.as_str())
864 .finish()
865 }
866}
867
868impl fmt::Display for RetentionClass {
869 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
870 formatter.write_str(self.as_str())
871 }
872}
873
874impl FromStr for RetentionClass {
875 type Err = RetentionClassError;
876
877 fn from_str(value: &str) -> Result<Self, Self::Err> {
878 Self::new(value)
879 }
880}
881
882impl TryFrom<String> for RetentionClass {
883 type Error = RetentionClassError;
884
885 fn try_from(value: String) -> Result<Self, Self::Error> {
886 Self::new(value)
887 }
888}
889
890impl TryFrom<&str> for RetentionClass {
891 type Error = RetentionClassError;
892
893 fn try_from(value: &str) -> Result<Self, Self::Error> {
894 Self::new(value)
895 }
896}
897
898impl From<RetentionClass> for String {
899 fn from(value: RetentionClass) -> Self {
900 value.0.into()
901 }
902}
903
904impl Serialize for RetentionClass {
905 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
906 where
907 S: Serializer,
908 {
909 serializer.serialize_str(self.as_str())
910 }
911}
912
913impl<'de> Deserialize<'de> for RetentionClass {
914 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
915 where
916 D: Deserializer<'de>,
917 {
918 deserializer.deserialize_string(RetentionClassVisitor)
919 }
920}
921
922struct RetentionClassVisitor;
923
924impl de::Visitor<'_> for RetentionClassVisitor {
925 type Value = RetentionClass;
926
927 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
928 formatter.write_str("a bounded artifact retention-policy class")
929 }
930
931 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
932 where
933 E: de::Error,
934 {
935 RetentionClass::new(value).map_err(E::custom)
936 }
937
938 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
939 where
940 E: de::Error,
941 {
942 RetentionClass::new(value).map_err(E::custom)
943 }
944}
945
946impl JsonSchema for RetentionClass {
947 fn schema_name() -> std::borrow::Cow<'static, str> {
948 "RetentionClass".into()
949 }
950
951 fn schema_id() -> std::borrow::Cow<'static, str> {
952 concat!(module_path!(), "::RetentionClass").into()
953 }
954
955 fn json_schema(_: &mut SchemaGenerator) -> Schema {
956 json_schema!({
957 "type": "string",
958 "minLength": 1,
959 "maxLength": 64,
960 "pattern": RETENTION_CLASS_PATTERN,
961 "description": "An opaque, case-sensitive retention-policy class; it grants no deletion or declassification authority by itself."
962 })
963 }
964
965 fn inline_schema() -> bool {
966 true
967 }
968}
969
970#[derive(Clone, Debug, Eq, Error, PartialEq)]
972#[non_exhaustive]
973pub enum RetentionClassError {
974 #[error("retention class must not be empty")]
976 Empty,
977
978 #[error("retention class is {actual} bytes; maximum is {max}")]
980 TooLong {
981 max: usize,
983 actual: usize,
985 },
986
987 #[error("retention class must start with an ASCII letter or digit")]
989 InvalidStart,
990
991 #[error("retention class contains an invalid byte at offset {index}")]
993 InvalidByte {
994 index: usize,
996 },
997}
998
999fn validate_retention_class(value: &str) -> Result<(), RetentionClassError> {
1000 if value.is_empty() {
1001 return Err(RetentionClassError::Empty);
1002 }
1003 if value.len() > RetentionClass::MAX_LEN {
1004 return Err(RetentionClassError::TooLong {
1005 max: RetentionClass::MAX_LEN,
1006 actual: value.len(),
1007 });
1008 }
1009 if !value.as_bytes()[0].is_ascii_alphanumeric() {
1010 return Err(RetentionClassError::InvalidStart);
1011 }
1012 if let Some((index, _)) = value.bytes().enumerate().skip(1).find(|(_, byte)| {
1013 !byte.is_ascii_alphanumeric() && !matches!(byte, b'.' | b'_' | b':' | b'/' | b'-')
1014 }) {
1015 return Err(RetentionClassError::InvalidByte { index });
1016 }
1017 Ok(())
1018}
1019
1020#[derive(
1026 Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
1027)]
1028#[non_exhaustive]
1029#[serde(rename_all = "snake_case")]
1030pub enum ArtifactModality {
1031 Text,
1033 Image,
1035 Audio,
1037 Video,
1039 Document,
1041 StructuredData,
1043 Archive,
1045 Binary,
1047}
1048
1049#[derive(
1051 Clone, Debug, Deserialize, Eq, Hash, JsonSchema, Ord, PartialEq, PartialOrd, Serialize,
1052)]
1053#[serde(deny_unknown_fields)]
1054pub struct ArtifactIdentity {
1055 tenant_id: TenantId,
1056 artifact_id: ArtifactId,
1057}
1058
1059impl ArtifactIdentity {
1060 #[must_use]
1062 pub const fn new(tenant_id: TenantId, artifact_id: ArtifactId) -> Self {
1063 Self {
1064 tenant_id,
1065 artifact_id,
1066 }
1067 }
1068
1069 #[must_use]
1071 pub const fn tenant_id(&self) -> &TenantId {
1072 &self.tenant_id
1073 }
1074
1075 #[must_use]
1077 pub const fn artifact_id(&self) -> ArtifactId {
1078 self.artifact_id
1079 }
1080}
1081
1082#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
1084#[serde(deny_unknown_fields)]
1085pub struct ArtifactPresentation {
1086 name: ArtifactName,
1087 #[serde(skip_serializing_if = "Option::is_none")]
1088 description: Option<ArtifactDescription>,
1089}
1090
1091impl ArtifactPresentation {
1092 #[must_use]
1094 pub const fn new(name: ArtifactName, description: Option<ArtifactDescription>) -> Self {
1095 Self { name, description }
1096 }
1097
1098 #[must_use]
1100 pub const fn name(&self) -> &ArtifactName {
1101 &self.name
1102 }
1103
1104 #[must_use]
1106 pub const fn description(&self) -> Option<&ArtifactDescription> {
1107 self.description.as_ref()
1108 }
1109}
1110
1111#[derive(Clone, Debug, Eq, JsonSchema, PartialEq, Serialize)]
1113#[serde(deny_unknown_fields)]
1114pub struct ArtifactRepresentation {
1115 media_type: MediaType,
1116 modality: ArtifactModality,
1117 byte_length: ByteCount,
1118 digest: Digest,
1119 #[serde(skip_serializing_if = "Option::is_none")]
1120 schema: Option<SchemaReference>,
1121}
1122
1123impl ArtifactRepresentation {
1124 pub fn new(
1131 media_type: MediaType,
1132 modality: ArtifactModality,
1133 byte_length: ByteCount,
1134 digest: Digest,
1135 schema: Option<SchemaReference>,
1136 ) -> Result<Self, ArtifactRepresentationError> {
1137 if byte_length.get() == 0 && digest != Digest::sha256(b"") {
1138 return Err(ArtifactRepresentationError::EmptyDigestMismatch);
1139 }
1140 if schema.is_some() && modality != ArtifactModality::StructuredData {
1141 return Err(ArtifactRepresentationError::SchemaRequiresStructuredData);
1142 }
1143 Ok(Self {
1144 media_type,
1145 modality,
1146 byte_length,
1147 digest,
1148 schema,
1149 })
1150 }
1151
1152 #[must_use]
1154 pub const fn media_type(&self) -> &MediaType {
1155 &self.media_type
1156 }
1157
1158 #[must_use]
1160 pub const fn modality(&self) -> ArtifactModality {
1161 self.modality
1162 }
1163
1164 #[must_use]
1166 pub const fn byte_length(&self) -> ByteCount {
1167 self.byte_length
1168 }
1169
1170 #[must_use]
1172 pub const fn digest(&self) -> Digest {
1173 self.digest
1174 }
1175
1176 #[must_use]
1178 pub const fn schema(&self) -> Option<&SchemaReference> {
1179 self.schema.as_ref()
1180 }
1181}
1182
1183impl<'de> Deserialize<'de> for ArtifactRepresentation {
1184 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1185 where
1186 D: Deserializer<'de>,
1187 {
1188 #[derive(Deserialize)]
1189 #[serde(deny_unknown_fields)]
1190 struct Wire {
1191 media_type: MediaType,
1192 modality: ArtifactModality,
1193 byte_length: ByteCount,
1194 digest: Digest,
1195 schema: Option<SchemaReference>,
1196 }
1197
1198 let wire = Wire::deserialize(deserializer)?;
1199 Self::new(
1200 wire.media_type,
1201 wire.modality,
1202 wire.byte_length,
1203 wire.digest,
1204 wire.schema,
1205 )
1206 .map_err(de::Error::custom)
1207 }
1208}
1209
1210#[derive(Clone, Debug, Eq, Error, PartialEq)]
1212#[non_exhaustive]
1213pub enum ArtifactRepresentationError {
1214 #[error("zero-length artifact must use the SHA-256 digest of empty bytes")]
1216 EmptyDigestMismatch,
1217
1218 #[error("artifact schemas require the structured_data modality")]
1220 SchemaRequiresStructuredData,
1221}
1222
1223#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
1229#[serde(deny_unknown_fields)]
1230pub struct ArtifactProvenance {
1231 principal: PrincipalIdentity,
1232 #[serde(skip_serializing_if = "Option::is_none")]
1233 capability: Option<CapabilityReference>,
1234 run_id: RunId,
1235 event_id: EventId,
1236}
1237
1238impl ArtifactProvenance {
1239 #[must_use]
1241 pub const fn new(
1242 principal: PrincipalIdentity,
1243 capability: Option<CapabilityReference>,
1244 run_id: RunId,
1245 event_id: EventId,
1246 ) -> Self {
1247 Self {
1248 principal,
1249 capability,
1250 run_id,
1251 event_id,
1252 }
1253 }
1254
1255 #[must_use]
1257 pub const fn principal(&self) -> &PrincipalIdentity {
1258 &self.principal
1259 }
1260
1261 #[must_use]
1263 pub const fn capability(&self) -> Option<&CapabilityReference> {
1264 self.capability.as_ref()
1265 }
1266
1267 #[must_use]
1269 pub const fn run_id(&self) -> RunId {
1270 self.run_id
1271 }
1272
1273 #[must_use]
1275 pub const fn event_id(&self) -> EventId {
1276 self.event_id
1277 }
1278}
1279
1280#[derive(Clone, Default, Eq, Hash, PartialEq)]
1286pub struct ArtifactParents(Box<[ArtifactId]>);
1287
1288impl ArtifactParents {
1289 pub const MAX_LEN: usize = 32;
1291
1292 #[must_use]
1294 pub fn empty() -> Self {
1295 Self::default()
1296 }
1297
1298 pub fn new<I>(values: I) -> Result<Self, ArtifactParentsError>
1305 where
1306 I: IntoIterator<Item = ArtifactId>,
1307 {
1308 let mut parents = Vec::new();
1309 for parent in values {
1310 if parents.len() == Self::MAX_LEN {
1311 return Err(ArtifactParentsError::TooMany {
1312 max: Self::MAX_LEN,
1313 actual: Self::MAX_LEN + 1,
1314 });
1315 }
1316 parents.push(parent);
1317 }
1318 parents.sort_unstable();
1319 if parents.windows(2).any(|pair| pair[0] == pair[1]) {
1320 return Err(ArtifactParentsError::Duplicate);
1321 }
1322 Ok(Self(parents.into_boxed_slice()))
1323 }
1324
1325 #[must_use]
1327 pub const fn as_slice(&self) -> &[ArtifactId] {
1328 &self.0
1329 }
1330
1331 #[must_use]
1333 pub const fn len(&self) -> usize {
1334 self.0.len()
1335 }
1336
1337 #[must_use]
1339 pub const fn is_empty(&self) -> bool {
1340 self.0.is_empty()
1341 }
1342
1343 fn contains(&self, artifact_id: ArtifactId) -> bool {
1344 self.0.binary_search(&artifact_id).is_ok()
1345 }
1346}
1347
1348impl fmt::Debug for ArtifactParents {
1349 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1350 formatter
1351 .debug_struct("ArtifactParents")
1352 .field("count", &self.len())
1353 .finish_non_exhaustive()
1354 }
1355}
1356
1357impl Serialize for ArtifactParents {
1358 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1359 where
1360 S: Serializer,
1361 {
1362 self.0.serialize(serializer)
1363 }
1364}
1365
1366impl<'de> Deserialize<'de> for ArtifactParents {
1367 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1368 where
1369 D: Deserializer<'de>,
1370 {
1371 deserializer.deserialize_seq(ArtifactParentsVisitor)
1372 }
1373}
1374
1375struct ArtifactParentsVisitor;
1376
1377impl<'de> de::Visitor<'de> for ArtifactParentsVisitor {
1378 type Value = ArtifactParents;
1379
1380 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1381 write!(
1382 formatter,
1383 "an array containing at most {} unique artifact identifiers",
1384 ArtifactParents::MAX_LEN
1385 )
1386 }
1387
1388 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
1389 where
1390 A: de::SeqAccess<'de>,
1391 {
1392 let mut parents = Vec::with_capacity(
1393 sequence
1394 .size_hint()
1395 .unwrap_or_default()
1396 .min(ArtifactParents::MAX_LEN),
1397 );
1398 while let Some(parent) = sequence.next_element::<ArtifactId>()? {
1399 if parents.contains(&parent) {
1400 return Err(de::Error::custom(ArtifactParentsError::Duplicate));
1401 }
1402 if parents.len() == ArtifactParents::MAX_LEN {
1403 return Err(de::Error::custom(ArtifactParentsError::TooMany {
1404 max: ArtifactParents::MAX_LEN,
1405 actual: ArtifactParents::MAX_LEN + 1,
1406 }));
1407 }
1408 parents.push(parent);
1409 }
1410 parents.sort_unstable();
1411 Ok(ArtifactParents(parents.into_boxed_slice()))
1412 }
1413}
1414
1415impl JsonSchema for ArtifactParents {
1416 fn schema_name() -> std::borrow::Cow<'static, str> {
1417 "ArtifactParents".into()
1418 }
1419
1420 fn schema_id() -> std::borrow::Cow<'static, str> {
1421 concat!(module_path!(), "::ArtifactParents").into()
1422 }
1423
1424 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
1425 json_schema!({
1426 "type": "array",
1427 "items": generator.subschema_for::<ArtifactId>(),
1428 "maxItems": 32,
1429 "uniqueItems": true,
1430 "description": "A canonical lexicographically sorted set of direct artifact parents. Sorting is enforced at runtime."
1431 })
1432 }
1433
1434 fn inline_schema() -> bool {
1435 true
1436 }
1437}
1438
1439#[derive(Clone, Debug, Eq, Error, PartialEq)]
1441#[non_exhaustive]
1442pub enum ArtifactParentsError {
1443 #[error("artifact has {actual} direct parents; maximum is {max}")]
1445 TooMany {
1446 max: usize,
1448 actual: usize,
1450 },
1451
1452 #[error("artifact parent identifiers must be unique")]
1454 Duplicate,
1455}
1456
1457#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
1463#[serde(deny_unknown_fields)]
1464pub struct ArtifactRef {
1465 identity: ArtifactIdentity,
1466 presentation: ArtifactPresentation,
1467 representation: ArtifactRepresentation,
1468 metadata: ContentMetadata,
1469 retention_class: RetentionClass,
1470 provenance: ArtifactProvenance,
1471 parents: ArtifactParents,
1472}
1473
1474impl ArtifactRef {
1475 pub fn new(
1482 identity: ArtifactIdentity,
1483 presentation: ArtifactPresentation,
1484 representation: ArtifactRepresentation,
1485 metadata: ContentMetadata,
1486 retention_class: RetentionClass,
1487 provenance: ArtifactProvenance,
1488 parents: ArtifactParents,
1489 ) -> Result<Self, ArtifactRefError> {
1490 if metadata.source() != ContentSource::Artifact {
1491 return Err(ArtifactRefError::InvalidContentSource {
1492 actual: metadata.source(),
1493 });
1494 }
1495 if parents.contains(identity.artifact_id()) {
1496 return Err(ArtifactRefError::SelfParent);
1497 }
1498 Ok(Self {
1499 identity,
1500 presentation,
1501 representation,
1502 metadata,
1503 retention_class,
1504 provenance,
1505 parents,
1506 })
1507 }
1508
1509 #[must_use]
1511 pub const fn identity(&self) -> &ArtifactIdentity {
1512 &self.identity
1513 }
1514
1515 #[must_use]
1517 pub const fn presentation(&self) -> &ArtifactPresentation {
1518 &self.presentation
1519 }
1520
1521 #[must_use]
1523 pub const fn representation(&self) -> &ArtifactRepresentation {
1524 &self.representation
1525 }
1526
1527 #[must_use]
1529 pub const fn metadata(&self) -> &ContentMetadata {
1530 &self.metadata
1531 }
1532
1533 #[must_use]
1535 pub const fn retention_class(&self) -> &RetentionClass {
1536 &self.retention_class
1537 }
1538
1539 #[must_use]
1541 pub const fn provenance(&self) -> &ArtifactProvenance {
1542 &self.provenance
1543 }
1544
1545 #[must_use]
1547 pub const fn parents(&self) -> &ArtifactParents {
1548 &self.parents
1549 }
1550}
1551
1552impl fmt::Debug for ArtifactRef {
1553 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1554 formatter
1555 .debug_struct("ArtifactRef")
1556 .field("identity", &self.identity)
1557 .field("presentation", &self.presentation)
1558 .field("representation", &self.representation)
1559 .field("metadata", &self.metadata)
1560 .field("retention_class", &self.retention_class)
1561 .field("provenance", &self.provenance)
1562 .field("parent_count", &self.parents.len())
1563 .finish_non_exhaustive()
1564 }
1565}
1566
1567impl<'de> Deserialize<'de> for ArtifactRef {
1568 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1569 where
1570 D: Deserializer<'de>,
1571 {
1572 #[derive(Deserialize)]
1573 #[serde(deny_unknown_fields)]
1574 struct Wire {
1575 identity: ArtifactIdentity,
1576 presentation: ArtifactPresentation,
1577 representation: ArtifactRepresentation,
1578 metadata: ContentMetadata,
1579 retention_class: RetentionClass,
1580 provenance: ArtifactProvenance,
1581 parents: ArtifactParents,
1582 }
1583
1584 let wire = Wire::deserialize(deserializer)?;
1585 Self::new(
1586 wire.identity,
1587 wire.presentation,
1588 wire.representation,
1589 wire.metadata,
1590 wire.retention_class,
1591 wire.provenance,
1592 wire.parents,
1593 )
1594 .map_err(de::Error::custom)
1595 }
1596}
1597
1598#[derive(Clone, Debug, Eq, Error, PartialEq)]
1600#[non_exhaustive]
1601pub enum ArtifactRefError {
1602 #[error("artifact reference metadata source must be artifact, got {actual:?}")]
1604 InvalidContentSource {
1605 actual: ContentSource,
1607 },
1608
1609 #[error("artifact must not list itself as a direct parent")]
1611 SelfParent,
1612}
1613
1614#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
1620#[non_exhaustive]
1621#[serde(
1622 tag = "type",
1623 content = "content",
1624 rename_all = "snake_case",
1625 deny_unknown_fields
1626)]
1627pub enum ContentPart {
1628 Text(TextContent),
1630 Json(JsonContent),
1632 Artifact(Box<ArtifactRef>),
1634}
1635
1636impl ContentPart {
1637 #[must_use]
1639 pub const fn metadata(&self) -> &ContentMetadata {
1640 match self {
1641 Self::Text(content) => content.metadata(),
1642 Self::Json(content) => content.metadata(),
1643 Self::Artifact(content) => content.metadata(),
1644 }
1645 }
1646
1647 #[must_use]
1653 pub fn inline_payload_bytes(&self) -> usize {
1654 match self {
1655 Self::Text(content) => content.text().len(),
1656 Self::Json(content) => content.value().stats().compact_bytes(),
1657 Self::Artifact(_) => 0,
1658 }
1659 }
1660}
1661
1662impl From<TextContent> for ContentPart {
1663 fn from(value: TextContent) -> Self {
1664 Self::Text(value)
1665 }
1666}
1667
1668impl From<JsonContent> for ContentPart {
1669 fn from(value: JsonContent) -> Self {
1670 Self::Json(value)
1671 }
1672}
1673
1674impl From<ArtifactRef> for ContentPart {
1675 fn from(value: ArtifactRef) -> Self {
1676 Self::Artifact(Box::new(value))
1677 }
1678}
1679
1680#[cfg(test)]
1681mod tests {
1682 use super::*;
1683 use crate::{
1684 BoundedJson, ContentTrust, IssuerId, RedactionState, SecurityLabel, SubjectId, Version,
1685 };
1686 use serde_json::{Value, from_value, json, to_value};
1687
1688 const ARTIFACT_ID: &str = "01912345-6789-7abc-8def-0123456789ab";
1689 const PARENT_A: &str = "01912345-6789-7abc-8def-0123456789ac";
1690 const PARENT_B: &str = "01912345-6789-7abc-8def-0123456789ad";
1691 const RUN_ID: &str = "01912345-6789-7abc-8def-0123456789ae";
1692 const EVENT_ID: &str = "01912345-6789-7abc-8def-0123456789af";
1693
1694 fn artifact_metadata() -> ContentMetadata {
1695 ContentMetadata::new(
1696 ContentSource::Artifact,
1697 ContentTrust::Untrusted,
1698 "internal/pii".parse::<SecurityLabel>().unwrap(),
1699 RedactionState::NotApplied,
1700 )
1701 }
1702
1703 fn provenance() -> ArtifactProvenance {
1704 ArtifactProvenance::new(
1705 PrincipalIdentity::new(
1706 "https://issuer.example.com".parse::<IssuerId>().unwrap(),
1707 "service-account".parse::<SubjectId>().unwrap(),
1708 ),
1709 Some(CapabilityReference::new(
1710 "files.convert".parse().unwrap(),
1711 Version::new(1, 2, 3),
1712 )),
1713 RUN_ID.parse().unwrap(),
1714 EVENT_ID.parse().unwrap(),
1715 )
1716 }
1717
1718 fn representation() -> ArtifactRepresentation {
1719 ArtifactRepresentation::new(
1720 "application/pdf".parse().unwrap(),
1721 ArtifactModality::Document,
1722 ByteCount::new(12),
1723 Digest::sha256(b"artifact-pdf"),
1724 None,
1725 )
1726 .unwrap()
1727 }
1728
1729 fn artifact_ref() -> ArtifactRef {
1730 ArtifactRef::new(
1731 ArtifactIdentity::new("tenant-a".parse().unwrap(), ARTIFACT_ID.parse().unwrap()),
1732 ArtifactPresentation::new(
1733 "incident-report.pdf".parse().unwrap(),
1734 Some("Sanitized incident report".parse().unwrap()),
1735 ),
1736 representation(),
1737 artifact_metadata(),
1738 "audit/7y".parse().unwrap(),
1739 provenance(),
1740 ArtifactParents::new([PARENT_B.parse().unwrap(), PARENT_A.parse().unwrap()]).unwrap(),
1741 )
1742 .unwrap()
1743 }
1744
1745 fn assert_no_storage_coordinate_keys(value: &Value) {
1746 match value {
1747 Value::Object(object) => {
1748 for key in object.keys() {
1749 assert!(
1750 !matches!(
1751 key.as_str(),
1752 "url" | "uri" | "bucket" | "object_key" | "path" | "credential"
1753 ),
1754 "wire contains forbidden storage-coordinate key {key}"
1755 );
1756 }
1757 for value in object.values() {
1758 assert_no_storage_coordinate_keys(value);
1759 }
1760 }
1761 Value::Array(values) => {
1762 for value in values {
1763 assert_no_storage_coordinate_keys(value);
1764 }
1765 }
1766 _ => {}
1767 }
1768 }
1769
1770 #[test]
1771 fn media_types_normalize_case_parameters_order_and_quotes() {
1772 for (input, expected) in [
1773 ("IMAGE/PNG", "image/png"),
1774 (
1775 "Text/Plain; Format=flowed; Charset=UTF-8",
1776 "text/plain;charset=utf-8;format=flowed",
1777 ),
1778 (
1779 "video/mp4; codecs=\"avc1.42E01E, mp4a.40.2\"",
1780 "video/mp4;codecs=\"avc1.42E01E, mp4a.40.2\"",
1781 ),
1782 ] {
1783 let media_type = input.parse::<MediaType>().unwrap();
1784 assert_eq!(media_type.as_str(), expected);
1785 assert_eq!(to_value(media_type).unwrap(), Value::from(expected));
1786 }
1787
1788 let media_type = "application/ld+json;profile=\"https://example.com/v1\""
1789 .parse::<MediaType>()
1790 .unwrap();
1791 assert_eq!(media_type.essence(), "application/ld+json");
1792 assert_eq!(media_type.top_level(), "application");
1793 assert_eq!(media_type.subtype(), "ld+json");
1794 }
1795
1796 #[test]
1797 fn media_types_reject_ranges_ambiguity_and_resource_excess() {
1798 assert_eq!("".parse::<MediaType>(), Err(MediaTypeError::Empty));
1799 for wildcard in ["*/*", "image/*"] {
1800 assert!(matches!(
1801 wildcard.parse::<MediaType>(),
1802 Err(MediaTypeError::WildcardNotAllowed | MediaTypeError::InvalidSubtypeName)
1803 ));
1804 }
1805 assert_eq!(
1806 "application/json;a=1;A=2".parse::<MediaType>(),
1807 Err(MediaTypeError::DuplicateParameter)
1808 );
1809 assert_eq!(
1810 "application/json;bad%=value".parse::<MediaType>(),
1811 Err(MediaTypeError::InvalidParameterName)
1812 );
1813 assert_eq!(
1814 "application/json;profile=\"bad\\value\"".parse::<MediaType>(),
1815 Err(MediaTypeError::InvalidParameterValue)
1816 );
1817 assert_eq!(
1818 "application/json;profile=\"é\"".parse::<MediaType>(),
1819 Err(MediaTypeError::InvalidParameterValue)
1820 );
1821
1822 let too_many = format!(
1823 "application/json;{}",
1824 (0..=MediaType::MAX_PARAMETERS)
1825 .map(|index| format!("p{index}=v"))
1826 .collect::<Vec<_>>()
1827 .join(";")
1828 );
1829 assert_eq!(
1830 too_many.parse::<MediaType>(),
1831 Err(MediaTypeError::TooManyParameters {
1832 max: MediaType::MAX_PARAMETERS,
1833 actual: MediaType::MAX_PARAMETERS + 1,
1834 })
1835 );
1836
1837 let too_long = "a".repeat(MediaType::MAX_LEN + 1);
1838 assert_eq!(
1839 too_long.parse::<MediaType>(),
1840 Err(MediaTypeError::TooLong {
1841 max: MediaType::MAX_LEN,
1842 actual: MediaType::MAX_LEN + 1,
1843 })
1844 );
1845 }
1846
1847 #[test]
1848 fn media_type_serde_and_schema_revalidate_input() {
1849 let media_type = from_value::<MediaType>(json!("Application/JSON")).unwrap();
1850 assert_eq!(media_type.as_str(), "application/json");
1851 assert!(from_value::<MediaType>(json!(42)).is_err());
1852 assert!(from_value::<MediaType>(json!("image/*")).is_err());
1853
1854 let schema = to_value(schemars::schema_for!(MediaType)).unwrap();
1855 assert_eq!(schema["type"], "string");
1856 assert_eq!(schema["maxLength"], MediaType::MAX_LEN);
1857 assert_eq!(schema["pattern"], MEDIA_TYPE_PATTERN);
1858 }
1859
1860 #[test]
1861 fn artifact_names_are_bounded_path_safe_and_debug_redacted() {
1862 for value in ["report.pdf", "事故报告 42.pdf", "résumé.txt"] {
1863 let name = value.parse::<ArtifactName>().unwrap();
1864 assert_eq!(name.as_str(), value);
1865 assert_eq!(to_value(&name).unwrap(), Value::from(value));
1866 let debug = format!("{name:?}");
1867 assert!(!debug.contains(value));
1868 }
1869
1870 assert_eq!("".parse::<ArtifactName>(), Err(ArtifactNameError::Empty));
1871 assert_eq!(
1872 ".".parse::<ArtifactName>(),
1873 Err(ArtifactNameError::PathLike)
1874 );
1875 assert_eq!(
1876 "..".parse::<ArtifactName>(),
1877 Err(ArtifactNameError::PathLike)
1878 );
1879 for value in [" report.pdf", "report.pdf "] {
1880 assert_eq!(
1881 value.parse::<ArtifactName>(),
1882 Err(ArtifactNameError::BoundaryWhitespace)
1883 );
1884 }
1885 for (value, byte_index) in [("../secret", 2), ("dir\\secret", 3)] {
1886 assert_eq!(
1887 value.parse::<ArtifactName>(),
1888 Err(ArtifactNameError::PathSeparator { byte_index })
1889 );
1890 }
1891 assert_eq!(
1892 "a\nb".parse::<ArtifactName>(),
1893 Err(ArtifactNameError::DisallowedCodePoint { byte_index: 1 })
1894 );
1895 }
1896
1897 #[test]
1898 fn descriptions_and_retention_classes_are_strict_and_redacted() {
1899 let description = "Secret line one\nline two"
1900 .parse::<ArtifactDescription>()
1901 .unwrap();
1902 assert_eq!(description.as_str(), "Secret line one\nline two");
1903 assert!(!format!("{description:?}").contains("Secret"));
1904 assert_eq!(
1905 "a\u{0}b".parse::<ArtifactDescription>(),
1906 Err(ArtifactDescriptionError::DisallowedCodePoint { byte_index: 1 })
1907 );
1908
1909 let retention = "Audit/7Y".parse::<RetentionClass>().unwrap();
1910 assert_eq!(retention.as_str(), "Audit/7Y");
1911 assert_ne!(retention, "audit/7y".parse().unwrap());
1912 assert_eq!(
1913 "bad class".parse::<RetentionClass>(),
1914 Err(RetentionClassError::InvalidByte { index: 3 })
1915 );
1916 }
1917
1918 #[test]
1919 fn zero_length_representation_requires_the_known_empty_digest() {
1920 let valid = ArtifactRepresentation::new(
1921 "application/octet-stream".parse().unwrap(),
1922 ArtifactModality::Binary,
1923 ByteCount::new(0),
1924 Digest::sha256(b""),
1925 None,
1926 );
1927 assert!(valid.is_ok());
1928
1929 assert_eq!(
1930 ArtifactRepresentation::new(
1931 "application/octet-stream".parse().unwrap(),
1932 ArtifactModality::Binary,
1933 ByteCount::new(0),
1934 Digest::sha256(b"not empty"),
1935 None,
1936 ),
1937 Err(ArtifactRepresentationError::EmptyDigestMismatch)
1938 );
1939
1940 let invalid_wire = json!({
1941 "media_type": "application/octet-stream",
1942 "modality": "binary",
1943 "byte_length": "0",
1944 "digest": Digest::sha256(b"not empty").to_string()
1945 });
1946 assert!(from_value::<ArtifactRepresentation>(invalid_wire).is_err());
1947
1948 let schema = SchemaReference::new(
1949 "https://schemas.example.com/artifact/1.0.0"
1950 .parse()
1951 .unwrap(),
1952 Version::new(1, 0, 0),
1953 Digest::sha256(b"artifact schema"),
1954 );
1955 assert_eq!(
1956 ArtifactRepresentation::new(
1957 "application/pdf".parse().unwrap(),
1958 ArtifactModality::Document,
1959 ByteCount::new(12),
1960 Digest::sha256(b"artifact-pdf"),
1961 Some(schema),
1962 ),
1963 Err(ArtifactRepresentationError::SchemaRequiresStructuredData)
1964 );
1965 }
1966
1967 #[test]
1968 fn artifact_parents_are_sorted_unique_bounded_and_redacted() {
1969 let parent_a = PARENT_A.parse::<ArtifactId>().unwrap();
1970 let parent_b = PARENT_B.parse::<ArtifactId>().unwrap();
1971 let parents = ArtifactParents::new([parent_b, parent_a]).unwrap();
1972 assert_eq!(parents.as_slice(), &[parent_a, parent_b]);
1973 assert_eq!(to_value(&parents).unwrap(), json!([PARENT_A, PARENT_B]));
1974 assert_eq!(format!("{parents:?}"), "ArtifactParents { count: 2, .. }");
1975 assert_eq!(
1976 ArtifactParents::new([parent_a, parent_a]),
1977 Err(ArtifactParentsError::Duplicate)
1978 );
1979
1980 let too_many = (0..=ArtifactParents::MAX_LEN)
1981 .map(|_| ArtifactId::generate())
1982 .collect::<Vec<_>>();
1983 assert_eq!(
1984 ArtifactParents::new(too_many),
1985 Err(ArtifactParentsError::TooMany {
1986 max: ArtifactParents::MAX_LEN,
1987 actual: ArtifactParents::MAX_LEN + 1,
1988 })
1989 );
1990
1991 assert!(from_value::<ArtifactParents>(json!([PARENT_B, PARENT_A])).is_ok());
1992 assert!(from_value::<ArtifactParents>(json!([PARENT_A, PARENT_A])).is_err());
1993 assert_eq!(ArtifactParents::default(), ArtifactParents::empty());
1994
1995 let too_many_wire = (0..=ArtifactParents::MAX_LEN)
1996 .map(|_| ArtifactId::generate())
1997 .collect::<Vec<_>>();
1998 assert!(from_value::<ArtifactParents>(json!(too_many_wire)).is_err());
1999 }
2000
2001 #[test]
2002 fn complete_artifact_reference_round_trips_without_storage_coordinates() {
2003 let artifact = artifact_ref();
2004 let encoded = to_value(&artifact).unwrap();
2005 assert_eq!(encoded["identity"]["tenant_id"], "tenant-a");
2006 assert_eq!(encoded["identity"]["artifact_id"], ARTIFACT_ID);
2007 assert_eq!(encoded["representation"]["media_type"], "application/pdf");
2008 assert_eq!(encoded["parents"], json!([PARENT_A, PARENT_B]));
2009 assert_eq!(
2010 from_value::<ArtifactRef>(encoded.clone()).unwrap(),
2011 artifact
2012 );
2013
2014 assert_no_storage_coordinate_keys(&encoded);
2015
2016 let debug = format!("{artifact:?}");
2017 assert!(!debug.contains("incident-report.pdf"));
2018 assert!(!debug.contains("Sanitized incident report"));
2019 assert!(!debug.contains("service-account"));
2020 }
2021
2022 #[test]
2023 fn artifact_reference_rejects_source_confusion_self_parent_and_unknown_fields() {
2024 let identity =
2025 ArtifactIdentity::new("tenant-a".parse().unwrap(), ARTIFACT_ID.parse().unwrap());
2026 let presentation = ArtifactPresentation::new("report.pdf".parse().unwrap(), None);
2027 let wrong_metadata = ContentMetadata::new(
2028 ContentSource::RemoteAgent,
2029 ContentTrust::Untrusted,
2030 "internal".parse().unwrap(),
2031 RedactionState::NotApplied,
2032 );
2033 assert_eq!(
2034 ArtifactRef::new(
2035 identity.clone(),
2036 presentation.clone(),
2037 representation(),
2038 wrong_metadata,
2039 "audit/7y".parse().unwrap(),
2040 provenance(),
2041 ArtifactParents::empty(),
2042 ),
2043 Err(ArtifactRefError::InvalidContentSource {
2044 actual: ContentSource::RemoteAgent,
2045 })
2046 );
2047 assert_eq!(
2048 ArtifactRef::new(
2049 identity,
2050 presentation,
2051 representation(),
2052 artifact_metadata(),
2053 "audit/7y".parse().unwrap(),
2054 provenance(),
2055 ArtifactParents::new([ARTIFACT_ID.parse().unwrap()]).unwrap(),
2056 ),
2057 Err(ArtifactRefError::SelfParent)
2058 );
2059
2060 let mut encoded = to_value(artifact_ref()).unwrap();
2061 encoded["extra"] = Value::Bool(true);
2062 assert!(from_value::<ArtifactRef>(encoded).is_err());
2063 }
2064
2065 #[test]
2066 fn content_part_is_closed_tagged_and_exposes_security_metadata() {
2067 let artifact = artifact_ref();
2068 let part = ContentPart::from(artifact.clone());
2069 let expected = json!({
2070 "type": "artifact",
2071 "content": to_value(artifact).unwrap()
2072 });
2073 assert_eq!(to_value(&part).unwrap(), expected);
2074 assert_eq!(from_value::<ContentPart>(expected).unwrap(), part);
2075 assert_eq!(part.metadata(), artifact_metadata().borrow());
2076
2077 for invalid in [
2078 json!({"type": "raw", "content": "AA=="}),
2079 json!({"type": "url", "content": "https://example.com/file"}),
2080 json!({
2081 "type": "artifact",
2082 "content": to_value(artifact_ref()).unwrap(),
2083 "extra": true
2084 }),
2085 ] {
2086 assert!(from_value::<ContentPart>(invalid).is_err());
2087 }
2088
2089 let schema = to_value(schemars::schema_for!(ContentPart)).unwrap();
2090 assert!(schema.get("oneOf").is_some());
2091 }
2092
2093 #[test]
2094 fn artifact_schemas_close_objects_and_express_collection_bounds() {
2095 let identity = to_value(schemars::schema_for!(ArtifactIdentity)).unwrap();
2096 assert_eq!(identity["additionalProperties"], false);
2097 assert_eq!(identity["required"], json!(["tenant_id", "artifact_id"]));
2098
2099 let parents = to_value(schemars::schema_for!(ArtifactParents)).unwrap();
2100 assert_eq!(parents["type"], "array");
2101 assert_eq!(parents["maxItems"], ArtifactParents::MAX_LEN);
2102 assert_eq!(parents["uniqueItems"], true);
2103
2104 let artifact = to_value(schemars::schema_for!(ArtifactRef)).unwrap();
2105 assert_eq!(artifact["type"], "object");
2106 assert_eq!(artifact["additionalProperties"], false);
2107 assert_eq!(
2108 artifact["required"],
2109 json!([
2110 "identity",
2111 "presentation",
2112 "representation",
2113 "metadata",
2114 "retention_class",
2115 "provenance",
2116 "parents"
2117 ])
2118 );
2119 }
2120
2121 #[test]
2122 fn bounded_json_content_still_maps_to_the_json_content_part() {
2123 let json_content = JsonContent::new(
2124 BoundedJson::from_str(r#"{"answer":42}"#).unwrap(),
2125 None,
2126 ContentMetadata::new(
2127 ContentSource::Tool,
2128 ContentTrust::Untrusted,
2129 "internal".parse().unwrap(),
2130 RedactionState::NotApplied,
2131 ),
2132 );
2133 let part = ContentPart::from(json_content);
2134 assert!(matches!(part, ContentPart::Json(_)));
2135 }
2136}