1use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use crate::checksum::Checksum;
24use crate::error::ModelError;
25use crate::ids::{ArtifactId, ProductReleaseId, TeaTimestamp};
26
27pub const LOCK_SCHEMA_VERSION: u64 = 1;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
35#[non_exhaustive]
36pub enum LockedIntegrity {
37 Verified,
40 VerifiedWeakOnly,
43 NotDeclared,
45}
46
47impl LockedIntegrity {
48 #[must_use]
50 pub fn as_str(self) -> &'static str {
51 match self {
52 Self::Verified => "Verified",
53 Self::VerifiedWeakOnly => "VerifiedWeakOnly",
54 Self::NotDeclared => "NotDeclared",
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase", deny_unknown_fields)]
62#[non_exhaustive]
63pub struct LockedChecksum {
64 pub algorithm: String,
66 pub value: String,
68}
69
70impl LockedChecksum {
71 #[must_use]
73 pub fn new(algorithm: impl Into<String>, value: impl Into<String>) -> Self {
74 Self {
75 algorithm: algorithm.into(),
76 value: value.into(),
77 }
78 }
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase", deny_unknown_fields)]
84#[non_exhaustive]
85pub struct LockedArtifact {
86 pub uuid: String,
88 pub revision: u64,
90 #[serde(rename = "type")]
92 pub artifact_type: String,
93 pub media_type: String,
95 pub size: u64,
97 pub checksums: Vec<LockedChecksum>,
99 pub integrity: LockedIntegrity,
101 pub fetched_at: String,
104}
105
106impl LockedArtifact {
107 #[must_use]
109 #[allow(clippy::too_many_arguments)]
110 pub fn new(
111 uuid: impl Into<String>,
112 revision: u64,
113 artifact_type: impl Into<String>,
114 media_type: impl Into<String>,
115 size: u64,
116 checksums: Vec<LockedChecksum>,
117 integrity: LockedIntegrity,
118 fetched_at: impl Into<String>,
119 ) -> Self {
120 Self {
121 uuid: uuid.into(),
122 revision,
123 artifact_type: artifact_type.into(),
124 media_type: media_type.into(),
125 size,
126 checksums,
127 integrity,
128 fetched_at: fetched_at.into(),
129 }
130 }
131
132 fn key(&self) -> (&str, &str) {
133 (self.uuid.as_str(), self.media_type.as_str())
134 }
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase", deny_unknown_fields)]
140#[non_exhaustive]
141pub struct LockFile {
142 pub schema_version: u64,
144 pub tei: String,
146 pub server: String,
148 pub api_version: String,
150 pub spec_commit: String,
152 pub product_release: String,
154 pub collection_version: u64,
156 pub artifacts: Vec<LockedArtifact>,
158}
159
160impl LockFile {
161 #[must_use]
163 pub fn new(
164 tei: impl Into<String>,
165 server: impl Into<String>,
166 api_version: impl Into<String>,
167 spec_commit: impl Into<String>,
168 product_release: impl Into<String>,
169 collection_version: u64,
170 ) -> Self {
171 Self {
172 schema_version: LOCK_SCHEMA_VERSION,
173 tei: tei.into(),
174 server: server.into(),
175 api_version: api_version.into(),
176 spec_commit: spec_commit.into(),
177 product_release: product_release.into(),
178 collection_version,
179 artifacts: Vec::new(),
180 }
181 }
182
183 pub fn normalize(&mut self) {
185 for artifact in &mut self.artifacts {
186 artifact.checksums.sort();
187 }
188 self.artifacts.sort_by(|a, b| {
189 (a.uuid.as_str(), a.media_type.as_str(), a.revision).cmp(&(
190 b.uuid.as_str(),
191 b.media_type.as_str(),
192 b.revision,
193 ))
194 });
195 }
196
197 pub fn validate(&self) -> Result<(), ModelError> {
206 if self.schema_version != LOCK_SCHEMA_VERSION {
207 return Err(ModelError::Invalid(format!(
208 "unsupported lock schemaVersion {}",
209 self.schema_version
210 )));
211 }
212 check_server(&self.server)?;
213 check_text("tei", &self.tei, 1, MAX_TEI_LEN)?;
214 check_text("apiVersion", &self.api_version, 1, MAX_VERSION_LEN)?;
215 ProductReleaseId::parse(&self.product_release)?;
216 if self.collection_version < 1 {
217 return Err(ModelError::Invalid(
218 "collectionVersion starts at 1".to_owned(),
219 ));
220 }
221 let mut seen = BTreeMap::new();
222 for artifact in &self.artifacts {
223 ArtifactId::parse(&artifact.uuid)?;
224 TeaTimestamp::parse(&artifact.fetched_at)?;
225 if artifact.revision < 1 {
226 return Err(ModelError::Invalid("artifact revision starts at 1".into()));
227 }
228 check_text("type", &artifact.artifact_type, 1, MAX_TYPE_LEN)?;
232 check_text("mediaType", &artifact.media_type, 1, MAX_MEDIA_TYPE_LEN)?;
233 for checksum in &artifact.checksums {
234 check_text(
235 "checksum algorithm",
236 &checksum.algorithm,
237 1,
238 MAX_ALGORITHM_LEN,
239 )?;
240 Checksum::new(
241 crate::enums::ChecksumAlgorithm::from_wire(&checksum.algorithm),
242 &checksum.value,
243 )?;
244 }
245 if seen.insert(artifact.key(), ()).is_some() {
246 return Err(ModelError::Invalid(format!(
247 "two lock entries for artifact {} and media type {}",
248 artifact.uuid, artifact.media_type
249 )));
250 }
251 }
252 Ok(())
253 }
254
255 pub fn to_json(&self) -> Result<String, ModelError> {
263 let mut canonical = self.clone();
264 canonical.normalize();
265 canonical.validate()?;
266 let mut text = serde_json::to_string_pretty(&canonical)
267 .map_err(|err| ModelError::Invalid(format!("lock serialisation failed: {err}")))?;
268 text.push('\n');
269 Ok(text)
270 }
271
272 pub fn parse(bytes: &[u8]) -> Result<Self, ModelError> {
283 #[derive(Deserialize)]
284 #[serde(rename_all = "camelCase")]
285 struct Probe {
286 schema_version: Option<u64>,
287 }
288 let probe: Probe = serde_json::from_slice(bytes)
289 .map_err(|err| ModelError::Invalid(format!("lock file is not valid JSON: {err}")))?;
290 match probe.schema_version {
291 Some(LOCK_SCHEMA_VERSION) => {}
292 Some(other) => {
293 return Err(ModelError::Invalid(format!(
294 "unsupported lock schemaVersion {other}"
295 )))
296 }
297 None => {
298 return Err(ModelError::Invalid(
299 "lock file has no schemaVersion".to_owned(),
300 ))
301 }
302 }
303 let mut lock: Self = serde_json::from_slice(bytes)
304 .map_err(|err| ModelError::Invalid(format!("lock file is not valid: {err}")))?;
305 lock.validate()?;
306 lock.normalize();
307 Ok(lock)
308 }
309}
310
311pub const MAX_TEI_LEN: usize = 2048;
313pub const MAX_VERSION_LEN: usize = 64;
315pub const MAX_TYPE_LEN: usize = 128;
317pub const MAX_MEDIA_TYPE_LEN: usize = 255;
319pub const MAX_ALGORITHM_LEN: usize = 64;
321
322fn check_text(field: &str, value: &str, min: usize, max: usize) -> Result<(), ModelError> {
325 let chars = value.chars().count();
326 if chars < min || chars > max {
327 return Err(ModelError::Invalid(format!(
328 "lock field {field} must be {min} to {max} characters"
329 )));
330 }
331 if crate::error::escape_control_chars(value) != value || value.contains(['\n', '\t']) {
333 return Err(ModelError::Invalid(format!(
334 "lock field {field} contains a control character"
335 )));
336 }
337 Ok(())
338}
339
340fn check_server(server: &str) -> Result<(), ModelError> {
341 let url = url::Url::parse(server)
342 .map_err(|_| ModelError::Invalid("lock server is not a URL".to_owned()))?;
343 if !url.username().is_empty()
344 || url.password().is_some()
345 || url.query().is_some()
346 || url.fragment().is_some()
347 {
348 return Err(ModelError::Invalid(
349 "lock server must not carry userinfo, a query or a fragment".to_owned(),
350 ));
351 }
352 Ok(())
353}
354
355#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
357#[non_exhaustive]
358pub struct FieldChange {
359 pub field: String,
361 pub old: String,
363 pub new: String,
365}
366
367#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
369#[non_exhaustive]
370pub struct ChangedArtifact {
371 pub uuid: String,
373 pub media_type: String,
375 pub fields: Vec<FieldChange>,
377}
378
379#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
381#[non_exhaustive]
382pub struct LockDiff {
383 pub header: Vec<FieldChange>,
385 pub added: Vec<LockedArtifact>,
387 pub removed: Vec<LockedArtifact>,
389 pub modified: Vec<ChangedArtifact>,
391}
392
393impl LockDiff {
394 #[must_use]
396 pub fn is_empty(&self) -> bool {
397 self.header.is_empty()
398 && self.added.is_empty()
399 && self.removed.is_empty()
400 && self.modified.is_empty()
401 }
402}
403
404fn change(out: &mut Vec<FieldChange>, field: &str, old: String, new: String) {
405 if old != new {
406 out.push(FieldChange {
407 field: field.to_owned(),
408 old,
409 new,
410 });
411 }
412}
413
414fn checksums_text(checksums: &[LockedChecksum]) -> String {
415 let mut sorted: Vec<&LockedChecksum> = checksums.iter().collect();
416 sorted.sort();
417 sorted
418 .iter()
419 .map(|checksum| format!("{}:{}", checksum.algorithm, checksum.value))
420 .collect::<Vec<_>>()
421 .join(",")
422}
423
424#[must_use]
428pub fn diff(old: &LockFile, new: &LockFile) -> LockDiff {
429 let mut header = Vec::new();
430 change(&mut header, "tei", old.tei.clone(), new.tei.clone());
431 change(
432 &mut header,
433 "server",
434 old.server.clone(),
435 new.server.clone(),
436 );
437 change(
438 &mut header,
439 "apiVersion",
440 old.api_version.clone(),
441 new.api_version.clone(),
442 );
443 change(
444 &mut header,
445 "specCommit",
446 old.spec_commit.clone(),
447 new.spec_commit.clone(),
448 );
449 change(
450 &mut header,
451 "productRelease",
452 old.product_release.clone(),
453 new.product_release.clone(),
454 );
455 change(
456 &mut header,
457 "collectionVersion",
458 old.collection_version.to_string(),
459 new.collection_version.to_string(),
460 );
461
462 let old_by_key: BTreeMap<_, _> = old.artifacts.iter().map(|a| (a.key(), a)).collect();
463 let new_by_key: BTreeMap<_, _> = new.artifacts.iter().map(|a| (a.key(), a)).collect();
464 let mut added = Vec::new();
465 let mut removed = Vec::new();
466 let mut modified = Vec::new();
467 for (key, entry) in &new_by_key {
468 match old_by_key.get(key) {
469 None => added.push((*entry).clone()),
470 Some(before) => {
471 let mut fields = Vec::new();
472 change(
473 &mut fields,
474 "revision",
475 before.revision.to_string(),
476 entry.revision.to_string(),
477 );
478 change(
479 &mut fields,
480 "type",
481 before.artifact_type.clone(),
482 entry.artifact_type.clone(),
483 );
484 change(
485 &mut fields,
486 "size",
487 before.size.to_string(),
488 entry.size.to_string(),
489 );
490 change(
491 &mut fields,
492 "checksums",
493 checksums_text(&before.checksums),
494 checksums_text(&entry.checksums),
495 );
496 change(
497 &mut fields,
498 "integrity",
499 before.integrity.as_str().to_owned(),
500 entry.integrity.as_str().to_owned(),
501 );
502 if !fields.is_empty() {
503 modified.push(ChangedArtifact {
504 uuid: key.0.to_owned(),
505 media_type: key.1.to_owned(),
506 fields,
507 });
508 }
509 }
510 }
511 }
512 for (key, entry) in &old_by_key {
513 if !new_by_key.contains_key(key) {
514 removed.push((*entry).clone());
515 }
516 }
517 LockDiff {
518 header,
519 added,
520 removed,
521 modified,
522 }
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 const REL: &str = "2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d";
530 const A1: &str = "11111111-1111-4111-8111-111111111111";
531 const A2: &str = "22222222-2222-4222-8222-222222222222";
532 const SHA256_ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
533
534 fn entry(uuid: &str, media: &str) -> LockedArtifact {
535 LockedArtifact::new(
536 uuid,
537 1,
538 "BOM",
539 media,
540 3,
541 vec![LockedChecksum::new("SHA-256", SHA256_ABC)],
542 LockedIntegrity::Verified,
543 "2026-11-08T00:00:00Z",
544 )
545 }
546
547 fn lock(artifacts: Vec<LockedArtifact>) -> LockFile {
548 let mut lock = LockFile::new(
549 "tei://example.com/uuid/2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d",
550 "https://tea.example.com/",
551 "1.0.0",
552 "962a0228af1bfcc1232ac3f79239317ff33fdb04",
553 REL,
554 2,
555 );
556 lock.artifacts = artifacts;
557 lock
558 }
559
560 #[test]
561 fn serialisation_is_canonical_and_round_trips() {
562 let a = lock(vec![entry(A2, "text/plain"), entry(A1, "application/json")]);
563 let b = lock(vec![entry(A1, "application/json"), entry(A2, "text/plain")]);
564 let text = a.to_json().unwrap();
565 assert_eq!(text, b.to_json().unwrap(), "input order must not matter");
566 assert!(text.ends_with("}\n"));
567 let parsed = LockFile::parse(text.as_bytes()).unwrap();
568 assert_eq!(parsed.to_json().unwrap(), text);
569 assert_eq!(parsed.artifacts[0].uuid, A1);
570 let value: serde_json::Value = serde_json::from_str(&text).unwrap();
572 let mut keys: Vec<_> = value.as_object().unwrap().keys().cloned().collect();
573 keys.sort();
574 assert_eq!(
575 keys,
576 [
577 "apiVersion",
578 "artifacts",
579 "collectionVersion",
580 "productRelease",
581 "schemaVersion",
582 "server",
583 "specCommit",
584 "tei"
585 ]
586 );
587 let mut entry_keys: Vec<_> = value["artifacts"][0]
588 .as_object()
589 .unwrap()
590 .keys()
591 .cloned()
592 .collect();
593 entry_keys.sort();
594 assert_eq!(
595 entry_keys,
596 [
597 "checksums",
598 "fetchedAt",
599 "integrity",
600 "mediaType",
601 "revision",
602 "size",
603 "type",
604 "uuid"
605 ]
606 );
607 }
608
609 #[test]
610 fn unsupported_version_unknown_fields_and_garbage_are_rejected() {
611 let good = lock(vec![entry(A1, "text/plain")]).to_json().unwrap();
612 let v2 = good.replace("\"schemaVersion\": 1", "\"schemaVersion\": 2");
613 assert!(LockFile::parse(v2.as_bytes()).is_err());
614 let extra = good.replacen("\"tei\"", "\"extra\": 1,\n \"tei\"", 1);
615 assert!(LockFile::parse(extra.as_bytes()).is_err());
616 let no_version = good.replace("\"schemaVersion\": 1,", "");
617 assert!(LockFile::parse(no_version.as_bytes()).is_err());
618 assert!(LockFile::parse(b"not json").is_err());
619 assert!(LockFile::parse(b"[]").is_err());
620 assert!(LockFile::parse(b"").is_err());
621 }
622
623 #[test]
624 fn a_server_that_could_hold_a_secret_is_rejected() {
625 for server in [
626 "https://user:pw@tea.example.com/",
627 "https://tea.example.com/?token=abc",
628 "https://tea.example.com/#frag",
629 "not a url",
630 ] {
631 let mut bad = lock(vec![]);
632 bad.server = server.to_owned();
633 assert!(bad.validate().is_err(), "{server}");
634 assert!(bad.to_json().is_err(), "{server}");
635 }
636 }
637
638 #[test]
639 fn bad_identifiers_checksums_timestamps_and_duplicates_are_rejected() {
640 let mut bad_uuid = lock(vec![entry("not-a-uuid", "text/plain")]);
641 assert!(bad_uuid.validate().is_err());
642 bad_uuid.artifacts[0].uuid = A1.into();
643 assert!(bad_uuid.validate().is_ok());
644
645 let mut bad_time = lock(vec![entry(A1, "text/plain")]);
646 bad_time.artifacts[0].fetched_at = "yesterday".into();
647 assert!(bad_time.validate().is_err());
648
649 let mut bad_sum = lock(vec![entry(A1, "text/plain")]);
650 bad_sum.artifacts[0].checksums = vec![LockedChecksum::new("SHA-256", "ABC")];
651 assert!(bad_sum.validate().is_err());
652
653 let dup = lock(vec![entry(A1, "text/plain"), entry(A1, "text/plain")]);
654 assert!(dup.validate().is_err());
655
656 let mut bad_collection = lock(vec![]);
657 bad_collection.collection_version = 0;
658 assert!(bad_collection.validate().is_err());
659 }
660
661 #[test]
662 fn diff_reports_added_removed_changed_and_header_but_not_fetched_at() {
663 let old = lock(vec![entry(A1, "text/plain"), entry(A2, "text/plain")]);
664 assert!(diff(&old, &old).is_empty());
665
666 let mut later = old.clone();
667 for artifact in &mut later.artifacts {
668 artifact.fetched_at = "2030-01-01T00:00:00Z".into();
669 }
670 assert!(diff(&old, &later).is_empty(), "fetchedAt must be ignored");
671
672 let mut new = old.clone();
673 new.collection_version = 3;
674 new.artifacts.remove(1);
675 new.artifacts.push(entry(A2, "application/json"));
676 new.artifacts[0].revision = 2;
677 new.artifacts[0].size = 99;
678 new.artifacts[0].checksums = vec![LockedChecksum::new("SHA-256", "0".repeat(64))];
679 let delta = diff(&old, &new);
680 assert_eq!(delta.header.len(), 1);
681 assert_eq!(delta.header[0].field, "collectionVersion");
682 assert_eq!(delta.added.len(), 1);
683 assert_eq!(delta.added[0].media_type, "application/json");
684 assert_eq!(delta.removed.len(), 1);
685 assert_eq!(delta.removed[0].uuid, A2);
686 assert_eq!(delta.modified.len(), 1);
687 let fields: Vec<_> = delta.modified[0]
688 .fields
689 .iter()
690 .map(|f| f.field.as_str())
691 .collect();
692 assert_eq!(fields, ["revision", "size", "checksums"]);
693 assert!(!delta.is_empty());
694 }
695
696 #[test]
697 fn server_text_in_the_lock_is_bounded_and_free_of_control_characters() {
698 let bad_values = [
699 "ok\u{7}bell",
700 "esc\u{1b}[31mred",
701 "nul\u{0}",
702 "del\u{7f}",
703 "c1\u{9b}31m",
704 "bidi\u{202e}override",
705 "line\nbreak",
706 ];
707 for value in bad_values {
708 for field in 0..4 {
709 let mut lock = lock(vec![entry(A1, "text/plain")]);
710 match field {
711 0 => lock.artifacts[0].media_type = value.to_owned(),
712 1 => lock.artifacts[0].artifact_type = value.to_owned(),
713 2 => lock.tei = value.to_owned(),
714 _ => lock.artifacts[0].checksums[0].algorithm = value.to_owned(),
715 }
716 assert!(lock.validate().is_err(), "{value:?} in field {field}");
717 assert!(lock.to_json().is_err());
718 }
719 }
720 let mut lock = lock(vec![entry(A1, "text/plain")]);
722 lock.artifacts[0].media_type = String::new();
723 assert!(lock.validate().is_err());
724 for (set, limit) in [
725 (0usize, MAX_MEDIA_TYPE_LEN),
726 (1, MAX_TYPE_LEN),
727 (2, MAX_TEI_LEN),
728 (3, MAX_VERSION_LEN),
729 ] {
730 let mut lock = lock_with_entry();
731 let long = "a".repeat(limit + 1);
732 let exact = "a".repeat(limit);
733 match set {
734 0 => lock.artifacts[0].media_type = long,
735 1 => lock.artifacts[0].artifact_type = long,
736 2 => lock.tei = long,
737 _ => lock.api_version = long,
738 }
739 assert!(lock.validate().is_err(), "limit {limit}");
740 let mut ok = lock_with_entry();
741 match set {
742 0 => ok.artifacts[0].media_type = exact,
743 1 => ok.artifacts[0].artifact_type = exact,
744 2 => ok.tei = exact,
745 _ => ok.api_version = exact,
746 }
747 assert!(
748 ok.validate().is_ok(),
749 "exactly {limit} characters is allowed"
750 );
751 }
752 let mut ok = lock_with_entry();
754 ok.artifacts[0].media_type = "application/vnd.cyclonedx+json; version=1.6".into();
755 ok.artifacts[0].artifact_type = "VULNERABILITIES".into();
756 assert!(ok.validate().is_ok());
757 }
758
759 fn lock_with_entry() -> LockFile {
760 lock(vec![entry(A1, "text/plain")])
761 }
762
763 #[test]
764 fn integrity_names_are_stable() {
765 assert_eq!(LockedIntegrity::Verified.as_str(), "Verified");
766 assert_eq!(
767 LockedIntegrity::VerifiedWeakOnly.as_str(),
768 "VerifiedWeakOnly"
769 );
770 assert_eq!(LockedIntegrity::NotDeclared.as_str(), "NotDeclared");
771 }
772}