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, and a different
380/// `specCommit` is a note, not a change.
381#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
382#[non_exhaustive]
383pub struct LockDiff {
384    /// Header fields that differ.
385    pub header: Vec<FieldChange>,
386    /// Header fields that differ without counting as a change: `specCommit`.
387    /// It names the TEA specification commit the writing client was pinned
388    /// to, not anything the server served, so upgrading the client does not
389    /// make an existing lock out of date.
390    pub notes: Vec<FieldChange>,
391    /// Entries only in the new lock.
392    pub added: Vec<LockedArtifact>,
393    /// Entries only in the old lock.
394    pub removed: Vec<LockedArtifact>,
395    /// Entries in both whose content differs.
396    pub modified: Vec<ChangedArtifact>,
397}
398
399impl LockDiff {
400    /// Whether the two locks are equal apart from `fetchedAt` and the
401    /// fields in [`notes`](Self::notes).
402    #[must_use]
403    pub fn is_empty(&self) -> bool {
404        self.header.is_empty()
405            && self.added.is_empty()
406            && self.removed.is_empty()
407            && self.modified.is_empty()
408    }
409}
410
411fn change(out: &mut Vec<FieldChange>, field: &str, old: String, new: String) {
412    if old != new {
413        out.push(FieldChange {
414            field: field.to_owned(),
415            old,
416            new,
417        });
418    }
419}
420
421fn checksums_text(checksums: &[LockedChecksum]) -> String {
422    let mut sorted: Vec<&LockedChecksum> = checksums.iter().collect();
423    sorted.sort();
424    sorted
425        .iter()
426        .map(|checksum| format!("{}:{}", checksum.algorithm, checksum.value))
427        .collect::<Vec<_>>()
428        .join(",")
429}
430
431/// Compare two locks. Neither is modified; entries are matched by artifact
432/// UUID and media type, so a new revision shows as a change, not as a removal
433/// plus an addition.
434#[must_use]
435pub fn diff(old: &LockFile, new: &LockFile) -> LockDiff {
436    let mut header = Vec::new();
437    change(&mut header, "tei", old.tei.clone(), new.tei.clone());
438    change(
439        &mut header,
440        "server",
441        old.server.clone(),
442        new.server.clone(),
443    );
444    change(
445        &mut header,
446        "apiVersion",
447        old.api_version.clone(),
448        new.api_version.clone(),
449    );
450    let mut notes = Vec::new();
451    change(
452        &mut notes,
453        "specCommit",
454        old.spec_commit.clone(),
455        new.spec_commit.clone(),
456    );
457    change(
458        &mut header,
459        "productRelease",
460        old.product_release.clone(),
461        new.product_release.clone(),
462    );
463    change(
464        &mut header,
465        "collectionVersion",
466        old.collection_version.to_string(),
467        new.collection_version.to_string(),
468    );
469
470    let old_by_key: BTreeMap<_, _> = old.artifacts.iter().map(|a| (a.key(), a)).collect();
471    let new_by_key: BTreeMap<_, _> = new.artifacts.iter().map(|a| (a.key(), a)).collect();
472    let mut added = Vec::new();
473    let mut removed = Vec::new();
474    let mut modified = Vec::new();
475    for (key, entry) in &new_by_key {
476        match old_by_key.get(key) {
477            None => added.push((*entry).clone()),
478            Some(before) => {
479                let mut fields = Vec::new();
480                change(
481                    &mut fields,
482                    "revision",
483                    before.revision.to_string(),
484                    entry.revision.to_string(),
485                );
486                change(
487                    &mut fields,
488                    "type",
489                    before.artifact_type.clone(),
490                    entry.artifact_type.clone(),
491                );
492                change(
493                    &mut fields,
494                    "size",
495                    before.size.to_string(),
496                    entry.size.to_string(),
497                );
498                change(
499                    &mut fields,
500                    "checksums",
501                    checksums_text(&before.checksums),
502                    checksums_text(&entry.checksums),
503                );
504                change(
505                    &mut fields,
506                    "integrity",
507                    before.integrity.as_str().to_owned(),
508                    entry.integrity.as_str().to_owned(),
509                );
510                if !fields.is_empty() {
511                    modified.push(ChangedArtifact {
512                        uuid: key.0.to_owned(),
513                        media_type: key.1.to_owned(),
514                        fields,
515                    });
516                }
517            }
518        }
519    }
520    for (key, entry) in &old_by_key {
521        if !new_by_key.contains_key(key) {
522            removed.push((*entry).clone());
523        }
524    }
525    LockDiff {
526        header,
527        notes,
528        added,
529        removed,
530        modified,
531    }
532}
533
534#[cfg(test)]
535mod tests {
536    use super::*;
537
538    const REL: &str = "2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d";
539    const A1: &str = "11111111-1111-4111-8111-111111111111";
540    const A2: &str = "22222222-2222-4222-8222-222222222222";
541    const SHA256_ABC: &str = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
542
543    fn entry(uuid: &str, media: &str) -> LockedArtifact {
544        LockedArtifact::new(
545            uuid,
546            1,
547            "BOM",
548            media,
549            3,
550            vec![LockedChecksum::new("SHA-256", SHA256_ABC)],
551            LockedIntegrity::Verified,
552            "2026-11-08T00:00:00Z",
553        )
554    }
555
556    fn lock(artifacts: Vec<LockedArtifact>) -> LockFile {
557        let mut lock = LockFile::new(
558            "tei://example.com/uuid/2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d",
559            "https://tea.example.com/",
560            "1.0.0",
561            "962a0228af1bfcc1232ac3f79239317ff33fdb04",
562            REL,
563            2,
564        );
565        lock.artifacts = artifacts;
566        lock
567    }
568
569    #[test]
570    fn serialisation_is_canonical_and_round_trips() {
571        let a = lock(vec![entry(A2, "text/plain"), entry(A1, "application/json")]);
572        let b = lock(vec![entry(A1, "application/json"), entry(A2, "text/plain")]);
573        let text = a.to_json().unwrap();
574        assert_eq!(text, b.to_json().unwrap(), "input order must not matter");
575        assert!(text.ends_with("}\n"));
576        let parsed = LockFile::parse(text.as_bytes()).unwrap();
577        assert_eq!(parsed.to_json().unwrap(), text);
578        assert_eq!(parsed.artifacts[0].uuid, A1);
579        // The documented key names.
580        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
581        let mut keys: Vec<_> = value.as_object().unwrap().keys().cloned().collect();
582        keys.sort();
583        assert_eq!(
584            keys,
585            [
586                "apiVersion",
587                "artifacts",
588                "collectionVersion",
589                "productRelease",
590                "schemaVersion",
591                "server",
592                "specCommit",
593                "tei"
594            ]
595        );
596        let mut entry_keys: Vec<_> = value["artifacts"][0]
597            .as_object()
598            .unwrap()
599            .keys()
600            .cloned()
601            .collect();
602        entry_keys.sort();
603        assert_eq!(
604            entry_keys,
605            [
606                "checksums",
607                "fetchedAt",
608                "integrity",
609                "mediaType",
610                "revision",
611                "size",
612                "type",
613                "uuid"
614            ]
615        );
616    }
617
618    #[test]
619    fn unsupported_version_unknown_fields_and_garbage_are_rejected() {
620        let good = lock(vec![entry(A1, "text/plain")]).to_json().unwrap();
621        let v2 = good.replace("\"schemaVersion\": 1", "\"schemaVersion\": 2");
622        assert!(LockFile::parse(v2.as_bytes()).is_err());
623        let extra = good.replacen("\"tei\"", "\"extra\": 1,\n  \"tei\"", 1);
624        assert!(LockFile::parse(extra.as_bytes()).is_err());
625        let no_version = good.replace("\"schemaVersion\": 1,", "");
626        assert!(LockFile::parse(no_version.as_bytes()).is_err());
627        assert!(LockFile::parse(b"not json").is_err());
628        assert!(LockFile::parse(b"[]").is_err());
629        assert!(LockFile::parse(b"").is_err());
630    }
631
632    #[test]
633    fn a_server_that_could_hold_a_secret_is_rejected() {
634        for server in [
635            "https://user:pw@tea.example.com/",
636            "https://tea.example.com/?token=abc",
637            "https://tea.example.com/#frag",
638            "not a url",
639        ] {
640            let mut bad = lock(vec![]);
641            bad.server = server.to_owned();
642            assert!(bad.validate().is_err(), "{server}");
643            assert!(bad.to_json().is_err(), "{server}");
644        }
645    }
646
647    #[test]
648    fn bad_identifiers_checksums_timestamps_and_duplicates_are_rejected() {
649        let mut bad_uuid = lock(vec![entry("not-a-uuid", "text/plain")]);
650        assert!(bad_uuid.validate().is_err());
651        bad_uuid.artifacts[0].uuid = A1.into();
652        assert!(bad_uuid.validate().is_ok());
653
654        let mut bad_time = lock(vec![entry(A1, "text/plain")]);
655        bad_time.artifacts[0].fetched_at = "yesterday".into();
656        assert!(bad_time.validate().is_err());
657
658        let mut bad_sum = lock(vec![entry(A1, "text/plain")]);
659        bad_sum.artifacts[0].checksums = vec![LockedChecksum::new("SHA-256", "ABC")];
660        assert!(bad_sum.validate().is_err());
661
662        let dup = lock(vec![entry(A1, "text/plain"), entry(A1, "text/plain")]);
663        assert!(dup.validate().is_err());
664
665        let mut bad_collection = lock(vec![]);
666        bad_collection.collection_version = 0;
667        assert!(bad_collection.validate().is_err());
668    }
669
670    #[test]
671    fn diff_reports_added_removed_changed_and_header_but_not_fetched_at() {
672        let old = lock(vec![entry(A1, "text/plain"), entry(A2, "text/plain")]);
673        assert!(diff(&old, &old).is_empty());
674
675        let mut later = old.clone();
676        for artifact in &mut later.artifacts {
677            artifact.fetched_at = "2030-01-01T00:00:00Z".into();
678        }
679        assert!(diff(&old, &later).is_empty(), "fetchedAt must be ignored");
680
681        let mut new = old.clone();
682        new.collection_version = 3;
683        new.artifacts.remove(1);
684        new.artifacts.push(entry(A2, "application/json"));
685        new.artifacts[0].revision = 2;
686        new.artifacts[0].size = 99;
687        new.artifacts[0].checksums = vec![LockedChecksum::new("SHA-256", "0".repeat(64))];
688        let delta = diff(&old, &new);
689        assert_eq!(delta.header.len(), 1);
690        assert_eq!(delta.header[0].field, "collectionVersion");
691        assert_eq!(delta.added.len(), 1);
692        assert_eq!(delta.added[0].media_type, "application/json");
693        assert_eq!(delta.removed.len(), 1);
694        assert_eq!(delta.removed[0].uuid, A2);
695        assert_eq!(delta.modified.len(), 1);
696        let fields: Vec<_> = delta.modified[0]
697            .fields
698            .iter()
699            .map(|f| f.field.as_str())
700            .collect();
701        assert_eq!(fields, ["revision", "size", "checksums"]);
702        assert!(!delta.is_empty());
703        assert!(delta.notes.is_empty());
704    }
705
706    #[test]
707    fn a_different_spec_commit_is_a_note_not_a_change() {
708        let old = lock(vec![entry(A1, "text/plain")]);
709        let mut repinned = old.clone();
710        repinned.spec_commit = "a338cc06".repeat(5);
711        let delta = diff(&old, &repinned);
712        assert!(
713            delta.is_empty(),
714            "a re-pinned client must not invalidate a lock"
715        );
716        assert!(delta.header.is_empty());
717        assert_eq!(delta.notes.len(), 1);
718        assert_eq!(delta.notes[0].field, "specCommit");
719        assert_eq!(delta.notes[0].old, old.spec_commit);
720        assert_eq!(delta.notes[0].new, repinned.spec_commit);
721
722        // A real change next to it is still a change.
723        repinned.collection_version += 1;
724        let delta = diff(&old, &repinned);
725        assert!(!delta.is_empty());
726        assert_eq!(delta.header[0].field, "collectionVersion");
727        assert_eq!(delta.notes.len(), 1);
728    }
729
730    #[test]
731    fn server_text_in_the_lock_is_bounded_and_free_of_control_characters() {
732        let bad_values = [
733            "ok\u{7}bell",
734            "esc\u{1b}[31mred",
735            "nul\u{0}",
736            "del\u{7f}",
737            "c1\u{9b}31m",
738            "bidi\u{202e}override",
739            "line\nbreak",
740        ];
741        for value in bad_values {
742            for field in 0..4 {
743                let mut lock = lock(vec![entry(A1, "text/plain")]);
744                match field {
745                    0 => lock.artifacts[0].media_type = value.to_owned(),
746                    1 => lock.artifacts[0].artifact_type = value.to_owned(),
747                    2 => lock.tei = value.to_owned(),
748                    _ => lock.artifacts[0].checksums[0].algorithm = value.to_owned(),
749                }
750                assert!(lock.validate().is_err(), "{value:?} in field {field}");
751                assert!(lock.to_json().is_err());
752            }
753        }
754        // Empty and overlong.
755        let mut lock = lock(vec![entry(A1, "text/plain")]);
756        lock.artifacts[0].media_type = String::new();
757        assert!(lock.validate().is_err());
758        for (set, limit) in [
759            (0usize, MAX_MEDIA_TYPE_LEN),
760            (1, MAX_TYPE_LEN),
761            (2, MAX_TEI_LEN),
762            (3, MAX_VERSION_LEN),
763        ] {
764            let mut lock = lock_with_entry();
765            let long = "a".repeat(limit + 1);
766            let exact = "a".repeat(limit);
767            match set {
768                0 => lock.artifacts[0].media_type = long,
769                1 => lock.artifacts[0].artifact_type = long,
770                2 => lock.tei = long,
771                _ => lock.api_version = long,
772            }
773            assert!(lock.validate().is_err(), "limit {limit}");
774            let mut ok = lock_with_entry();
775            match set {
776                0 => ok.artifacts[0].media_type = exact,
777                1 => ok.artifacts[0].artifact_type = exact,
778                2 => ok.tei = exact,
779                _ => ok.api_version = exact,
780            }
781            assert!(
782                ok.validate().is_ok(),
783                "exactly {limit} characters is allowed"
784            );
785        }
786        // Ordinary text with punctuation and non-ASCII letters is fine.
787        let mut ok = lock_with_entry();
788        ok.artifacts[0].media_type = "application/vnd.cyclonedx+json; version=1.6".into();
789        ok.artifacts[0].artifact_type = "VULNERABILITIES".into();
790        assert!(ok.validate().is_ok());
791    }
792
793    fn lock_with_entry() -> LockFile {
794        lock(vec![entry(A1, "text/plain")])
795    }
796
797    #[test]
798    fn integrity_names_are_stable() {
799        assert_eq!(LockedIntegrity::Verified.as_str(), "Verified");
800        assert_eq!(
801            LockedIntegrity::VerifiedWeakOnly.as_str(),
802            "VerifiedWeakOnly"
803        );
804        assert_eq!(LockedIntegrity::NotDeclared.as_str(), "NotDeclared");
805    }
806}