Skip to main content

libtea_core/
lock.rs

1//! Lock file: a record of what a TEI resolved to and what the artifacts were.
2//!
3//! *Experimental until 0.9.* The JSON layout is versioned by `schemaVersion`
4//! (currently [`LOCK_SCHEMA_VERSION`]); the Rust types may change in a minor
5//! release.
6//!
7//! The format is documented in `docs/lock-file.md` and described by
8//! `docs/schemas/lock-v1.schema.json`. This module does no I/O and reads no
9//! clock: callers supply every value, including `fetchedAt`.
10//!
11//! **What a lock proves.** It records the integrity outcome of checksums over
12//! decoded artifact bytes at `fetchedAt`. That is not publisher authenticity,
13//! and a lock file is not signed: whoever can edit it can change it.
14//!
15//! **No secrets.** [`LockFile::validate`] rejects a `server` URL that carries
16//! userinfo, a query or a fragment. Nothing else in the format holds
17//! credentials.
18
19use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use crate::checksum::Checksum;
24use crate::error::ModelError;
25use crate::ids::{ArtifactId, ProductReleaseId, TeaTimestamp};
26
27/// The only lock layout this crate reads and writes.
28pub const LOCK_SCHEMA_VERSION: u64 = 1;
29
30/// How an artifact's declared checksums fared when the lock was written.
31///
32/// Only outcomes that let the artifact into a lock exist: a failed or
33/// incomplete check makes `sync` fail instead.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
35#[non_exhaustive]
36pub enum LockedIntegrity {
37    /// Every declared checksum matched the decoded bytes, and at least one
38    /// uses a non-weak algorithm. Integrity only, not authenticity.
39    Verified,
40    /// Every declared checksum matched, but all of them are weak (SHA-1) and
41    /// the caller accepted that explicitly.
42    VerifiedWeakOnly,
43    /// The format declares no checksum, so nothing was checked.
44    NotDeclared,
45}
46
47impl LockedIntegrity {
48    /// The name used in the lock file.
49    #[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/// A declared checksum as recorded in a lock.
60#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase", deny_unknown_fields)]
62#[non_exhaustive]
63pub struct LockedChecksum {
64    /// Algorithm name as declared (for example `SHA-256`).
65    pub algorithm: String,
66    /// Lowercase hex digest as declared.
67    pub value: String,
68}
69
70impl LockedChecksum {
71    /// Record one declared checksum.
72    #[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/// One format of one artifact revision.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "camelCase", deny_unknown_fields)]
84#[non_exhaustive]
85pub struct LockedArtifact {
86    /// Artifact UUID.
87    pub uuid: String,
88    /// Revision number.
89    pub revision: u64,
90    /// Artifact type as the server published it (for example `BOM`).
91    #[serde(rename = "type")]
92    pub artifact_type: String,
93    /// Media type of the format.
94    pub media_type: String,
95    /// Decoded size in bytes, as counted while downloading.
96    pub size: u64,
97    /// Declared checksums, sorted.
98    pub checksums: Vec<LockedChecksum>,
99    /// Integrity outcome when the lock was written.
100    pub integrity: LockedIntegrity,
101    /// When the bytes were fetched (RFC 3339 UTC with `Z`). Ignored by
102    /// [`diff`], because it changes on every run.
103    pub fetched_at: String,
104}
105
106impl LockedArtifact {
107    /// Build an entry. Checksums are sorted by [`LockFile::normalize`].
108    #[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/// A lock file, `schemaVersion` 1.
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase", deny_unknown_fields)]
140#[non_exhaustive]
141pub struct LockFile {
142    /// Always [`LOCK_SCHEMA_VERSION`].
143    pub schema_version: u64,
144    /// The TEI that was resolved, as given.
145    pub tei: String,
146    /// The API root that served the release, without userinfo, query or fragment.
147    pub server: String,
148    /// The advertised API version that was used.
149    pub api_version: String,
150    /// The TEA specification commit this client is pinned to.
151    pub spec_commit: String,
152    /// Product release UUID.
153    pub product_release: String,
154    /// Collection version that was locked.
155    pub collection_version: u64,
156    /// Artifacts, sorted by UUID then media type.
157    pub artifacts: Vec<LockedArtifact>,
158}
159
160impl LockFile {
161    /// Start a lock with no artifacts.
162    #[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    /// Put artifacts and checksums into their canonical order.
184    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    /// Check the lock is one this crate would write.
198    ///
199    /// # Errors
200    ///
201    /// Returns an error for an unsupported `schemaVersion`, a `server` that
202    /// could carry a secret, an identifier or timestamp that does not parse, a
203    /// checksum that is not valid, or two entries for the same artifact and
204    /// media type.
205    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            // These strings come from the server. Bound them and keep control
229            // characters (terminal escapes, bidi overrides) out of a file that
230            // people read and tools print.
231            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    /// Serialise in the canonical form: validated, sorted, two-space indent,
256    /// camelCase keys in a fixed order, one trailing newline. The same content
257    /// always yields the same bytes.
258    ///
259    /// # Errors
260    ///
261    /// Returns an error when [`LockFile::validate`] fails.
262    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    /// Parse and validate a lock file.
273    ///
274    /// Unknown fields are rejected: the format is ours and version-gated, so a
275    /// field this reader does not know means a newer `schemaVersion`, and
276    /// silently dropping it on the next write would lose data.
277    ///
278    /// # Errors
279    ///
280    /// Returns an error for malformed JSON, an unsupported `schemaVersion`, an
281    /// unknown field, or a lock that fails [`LockFile::validate`].
282    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
311/// Longest accepted `tei`.
312pub const MAX_TEI_LEN: usize = 2048;
313/// Longest accepted `apiVersion`.
314pub const MAX_VERSION_LEN: usize = 64;
315/// Longest accepted artifact `type`.
316pub const MAX_TYPE_LEN: usize = 128;
317/// Longest accepted `mediaType`.
318pub const MAX_MEDIA_TYPE_LEN: usize = 255;
319/// Longest accepted checksum algorithm name.
320pub const MAX_ALGORITHM_LEN: usize = 64;
321
322/// A text field of the lock: bounded, one line, and free of control characters
323/// (C0, DEL, C1 and bidi overrides, the set `escape_control_chars` rewrites).
324fn 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    // `escape_control_chars` keeps tab and newline; these fields are one line.
332    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/// A change to one scalar of the lock header or of an entry.
356#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
357#[non_exhaustive]
358pub struct FieldChange {
359    /// Field name as in the lock file.
360    pub field: String,
361    /// Value in the old lock.
362    pub old: String,
363    /// Value in the new lock.
364    pub new: String,
365}
366
367/// An entry present in both locks whose content differs.
368#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
369#[non_exhaustive]
370pub struct ChangedArtifact {
371    /// Artifact UUID.
372    pub uuid: String,
373    /// Media type of the format.
374    pub media_type: String,
375    /// What differs.
376    pub fields: Vec<FieldChange>,
377}
378
379/// Differences between two locks. `fetchedAt` is ignored.
380#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
381#[non_exhaustive]
382pub struct LockDiff {
383    /// Header fields that differ.
384    pub header: Vec<FieldChange>,
385    /// Entries only in the new lock.
386    pub added: Vec<LockedArtifact>,
387    /// Entries only in the old lock.
388    pub removed: Vec<LockedArtifact>,
389    /// Entries in both whose content differs.
390    pub modified: Vec<ChangedArtifact>,
391}
392
393impl LockDiff {
394    /// Whether the two locks are equal apart from `fetchedAt`.
395    #[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/// Compare two locks. Neither is modified; entries are matched by artifact
425/// UUID and media type, so a new revision shows as a change, not as a removal
426/// plus an addition.
427#[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        // The documented key names.
571        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        // Empty and overlong.
721        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        // Ordinary text with punctuation and non-ASCII letters is fine.
753        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}