Skip to main content

tapid_core/
lib.rs

1use std::{fmt, str::FromStr};
2
3#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
4pub struct PackageName(String);
5
6impl PackageName {
7    pub fn as_str(&self) -> &str {
8        &self.0
9    }
10}
11
12impl FromStr for PackageName {
13    type Err = DomainError;
14
15    fn from_str(value: &str) -> Result<Self, Self::Err> {
16        if value.is_empty()
17            || value.len() > 214
18            || value.starts_with('.')
19            || value.starts_with('_')
20            || value.ends_with('.')
21            || value.ends_with('_')
22            || value.chars().any(char::is_whitespace)
23        {
24            return Err(DomainError::InvalidPackageName(value.to_owned()));
25        }
26
27        if value.starts_with('@') {
28            let mut parts = value.split('/');
29            let scope = parts.next().unwrap_or_default();
30            let name = parts.next().unwrap_or_default();
31            if parts.next().is_some()
32                || scope.len() < 2
33                || name.is_empty()
34                || scope[1..].chars().any(|c| !is_name_character(c))
35                || name.chars().any(|c| !is_name_character(c))
36            {
37                return Err(DomainError::InvalidPackageName(value.to_owned()));
38            }
39        } else if value.chars().any(|c| !is_name_character(c)) {
40            return Err(DomainError::InvalidPackageName(value.to_owned()));
41        }
42
43        Ok(Self(value.to_owned()))
44    }
45}
46
47impl fmt::Display for PackageName {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        self.0.fmt(f)
50    }
51}
52
53#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
54pub struct PackageVersion {
55    pub major: u64,
56    pub minor: u64,
57    pub patch: u64,
58}
59
60impl FromStr for PackageVersion {
61    type Err = DomainError;
62
63    fn from_str(value: &str) -> Result<Self, Self::Err> {
64        let mut parts = value.split('.');
65        let numbers = [parts.next(), parts.next(), parts.next()];
66        if parts.next().is_some() || numbers.iter().any(Option::is_none) {
67            return Err(DomainError::InvalidPackageVersion(value.to_owned()));
68        }
69
70        let [Some(major), Some(minor), Some(patch)] = numbers else {
71            unreachable!("checked above");
72        };
73        let parse = |part: &str| {
74            if part.is_empty() || (part.len() > 1 && part.starts_with('0')) {
75                return Err(DomainError::InvalidPackageVersion(value.to_owned()));
76            }
77            part.parse::<u64>()
78                .map_err(|_| DomainError::InvalidPackageVersion(value.to_owned()))
79        };
80
81        Ok(Self {
82            major: parse(major)?,
83            minor: parse(minor)?,
84            patch: parse(patch)?,
85        })
86    }
87}
88
89impl fmt::Display for PackageVersion {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
92    }
93}
94
95#[derive(Clone, Debug, Eq, Hash, PartialEq)]
96pub struct ArtifactDigest(String);
97
98impl ArtifactDigest {
99    pub fn as_str(&self) -> &str {
100        &self.0
101    }
102}
103
104impl FromStr for ArtifactDigest {
105    type Err = DomainError;
106
107    fn from_str(value: &str) -> Result<Self, Self::Err> {
108        let Some(hex) = value.strip_prefix("sha256-") else {
109            return Err(DomainError::InvalidArtifactDigest(value.to_owned()));
110        };
111        if hex.len() != 64 || hex.chars().any(|c| !c.is_ascii_hexdigit()) {
112            return Err(DomainError::InvalidArtifactDigest(value.to_owned()));
113        }
114        Ok(Self(value.to_ascii_lowercase()))
115    }
116}
117
118impl fmt::Display for ArtifactDigest {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        self.0.fmt(f)
121    }
122}
123
124#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
125pub struct RegistryOrigin(String);
126
127impl RegistryOrigin {
128    pub fn as_str(&self) -> &str {
129        &self.0
130    }
131}
132
133impl FromStr for RegistryOrigin {
134    type Err = DomainError;
135
136    fn from_str(value: &str) -> Result<Self, Self::Err> {
137        let trimmed = value.trim_end_matches('/');
138        let valid = trimmed.starts_with("https://")
139            && trimmed.len() > "https://".len()
140            && !trimmed.contains(['@', '?', '#', '|'])
141            && trimmed[8..]
142                .split('/')
143                .next()
144                .is_some_and(|host| !host.is_empty());
145        if !valid {
146            return Err(DomainError::InvalidRegistryOrigin(value.to_owned()));
147        }
148        Ok(Self(trimmed.to_owned()))
149    }
150}
151
152impl fmt::Display for RegistryOrigin {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        self.0.fmt(f)
155    }
156}
157
158#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
159pub struct PackageInstanceId {
160    pub registry: RegistryOrigin,
161    pub name: PackageName,
162    pub version: PackageVersion,
163}
164
165impl PackageInstanceId {
166    pub fn new(registry: RegistryOrigin, name: PackageName, version: PackageVersion) -> Self {
167        Self {
168            registry,
169            name,
170            version,
171        }
172    }
173}
174
175#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
176pub struct PackageIntegrity(String);
177
178impl PackageIntegrity {
179    pub fn as_str(&self) -> &str {
180        &self.0
181    }
182}
183
184impl FromStr for PackageIntegrity {
185    type Err = DomainError;
186
187    fn from_str(value: &str) -> Result<Self, Self::Err> {
188        let Some(encoded) = value.strip_prefix("sha512-") else {
189            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
190        };
191        let valid_length = encoded.len() == 86 || encoded.len() == 88;
192        let valid_characters = encoded
193            .chars()
194            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '='));
195        if !valid_length || !valid_characters || (encoded.contains('=') && !encoded.ends_with("=="))
196        {
197            return Err(DomainError::InvalidPackageIntegrity(value.to_owned()));
198        }
199        Ok(Self(value.to_owned()))
200    }
201}
202
203impl fmt::Display for PackageIntegrity {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        self.0.fmt(f)
206    }
207}
208
209#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
210pub struct PeerContext(std::collections::BTreeMap<PackageName, PackageVersion>);
211
212impl PeerContext {
213    pub fn with(mut self, name: PackageName, version: PackageVersion) -> Self {
214        self.0.insert(name, version);
215        self
216    }
217    pub fn entries(&self) -> &std::collections::BTreeMap<PackageName, PackageVersion> {
218        &self.0
219    }
220}
221
222impl fmt::Display for PeerContext {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        let mut first = true;
225        for (name, version) in &self.0 {
226            if !first {
227                f.write_str(",")?;
228            }
229            first = false;
230            write!(f, "{name}@{version}")?;
231        }
232        Ok(())
233    }
234}
235
236#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
237pub struct PlatformContext {
238    pub os: Option<String>,
239    pub cpu: Option<String>,
240    pub libc: Option<String>,
241}
242
243impl PlatformContext {
244    pub fn new(
245        os: Option<&str>,
246        cpu: Option<&str>,
247        libc: Option<&str>,
248    ) -> Result<Self, DomainError> {
249        let context = Self {
250            os: os.map(str::to_owned),
251            cpu: cpu.map(str::to_owned),
252            libc: libc.map(str::to_owned),
253        };
254        if [&context.os, &context.cpu, &context.libc]
255            .into_iter()
256            .flatten()
257            .any(|v| {
258                v.is_empty()
259                    || v.chars().any(char::is_whitespace)
260                    || v.chars().any(char::is_control)
261                    || v == "-"
262                    || v.contains(['-', '|'])
263            })
264        {
265            return Err(DomainError::InvalidPlatformContext);
266        }
267        Ok(context)
268    }
269}
270
271impl fmt::Display for PlatformContext {
272    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
273        if self.os.is_none() && self.cpu.is_none() && self.libc.is_none() {
274            return Ok(());
275        }
276        let values = [&self.os, &self.cpu, &self.libc];
277        for (index, value) in values.into_iter().enumerate() {
278            if index > 0 {
279                f.write_str("-")?;
280            }
281            if let Some(value) = value {
282                f.write_str(value)?;
283            }
284        }
285        Ok(())
286    }
287}
288
289#[derive(Clone, Debug, Eq, PartialEq)]
290pub enum DomainError {
291    InvalidPackageName(String),
292    InvalidPackageVersion(String),
293    InvalidArtifactDigest(String),
294    InvalidRegistryOrigin(String),
295    InvalidPackageIntegrity(String),
296    InvalidPlatformContext,
297}
298
299impl fmt::Display for DomainError {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        match self {
302            Self::InvalidPackageName(value) => write!(f, "invalid package name: {value}"),
303            Self::InvalidPackageVersion(value) => write!(f, "invalid package version: {value}"),
304            Self::InvalidArtifactDigest(value) => write!(f, "invalid artifact digest: {value}"),
305            Self::InvalidRegistryOrigin(value) => write!(f, "invalid registry origin: {value}"),
306            Self::InvalidPackageIntegrity(value) => write!(f, "invalid package integrity: {value}"),
307            Self::InvalidPlatformContext => f.write_str("invalid platform context"),
308        }
309    }
310}
311
312impl std::error::Error for DomainError {}
313
314fn is_name_character(character: char) -> bool {
315    character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn accepts_scoped_and_unscoped_package_names() {
324        assert!("tapid".parse::<PackageName>().is_ok());
325        assert!("@tapid/core".parse::<PackageName>().is_ok());
326    }
327
328    #[test]
329    fn rejects_unsafe_package_names() {
330        for value in [
331            "",
332            "../tapid",
333            "@tapid",
334            "@tapid/core/extra",
335            "tap id",
336            "tapid/core",
337        ] {
338            assert!(value.parse::<PackageName>().is_err(), "accepted {value}");
339        }
340    }
341
342    #[test]
343    fn parses_canonical_versions() {
344        let version = "1.2.3".parse::<PackageVersion>().unwrap();
345        assert_eq!(version.to_string(), "1.2.3");
346        assert!("01.2.3".parse::<PackageVersion>().is_err());
347    }
348
349    #[test]
350    fn accepts_only_sha256_digests() {
351        let digest = format!("sha256-{}", "A".repeat(64))
352            .parse::<ArtifactDigest>()
353            .unwrap();
354        assert_eq!(digest.to_string(), format!("sha256-{}", "a".repeat(64)));
355        assert!("sha512-deadbeef".parse::<ArtifactDigest>().is_err());
356    }
357
358    #[test]
359    fn registry_origin_is_typed_and_canonical_without_secrets() {
360        let origin = "https://REGISTRY.example.test/"
361            .parse::<RegistryOrigin>()
362            .unwrap();
363        assert_eq!(origin.as_str(), "https://REGISTRY.example.test");
364        assert!(
365            "http://registry.example.test"
366                .parse::<RegistryOrigin>()
367                .is_err()
368        );
369        assert!(
370            "https://user:pass@registry.example.test"
371                .parse::<RegistryOrigin>()
372                .is_err()
373        );
374        assert!(
375            "https://registry.example.test/path|ambiguous"
376                .parse::<RegistryOrigin>()
377                .is_err()
378        );
379    }
380
381    #[test]
382    fn integrity_preserves_mixed_case_wire_encoding() {
383        let value = format!("sha512-{}", "AbCdEfGh".repeat(11));
384        let integrity = value.parse::<PackageIntegrity>().unwrap();
385        assert_eq!(integrity.to_string(), value);
386    }
387
388    #[test]
389    fn package_instance_identity_includes_registry() {
390        let name: PackageName = "tapid".parse().unwrap();
391        let version: PackageVersion = "1.0.0".parse().unwrap();
392        let first = PackageInstanceId::new(
393            "https://one.example".parse().unwrap(),
394            name.clone(),
395            version,
396        );
397        let second = PackageInstanceId::new("https://two.example".parse().unwrap(), name, version);
398        assert_ne!(first, second);
399    }
400
401    #[test]
402    fn contexts_have_deterministic_empty_and_nonempty_forms() {
403        let peer = PeerContext::default().with("react".parse().unwrap(), "18.2.0".parse().unwrap());
404        assert_eq!(peer.to_string(), "react@18.2.0");
405        let platform = PlatformContext::new(Some("linux"), Some("x86_64"), Some("gnu")).unwrap();
406        assert_eq!(platform.to_string(), "linux-x86_64-gnu");
407        assert!(PlatformContext::new(Some("linux-x"), None, None).is_err());
408        assert!(PlatformContext::new(Some("-"), None, None).is_err());
409        assert!(PlatformContext::new(Some("linux|custom"), None, None).is_err());
410        assert!(PlatformContext::new(Some("linux\u{0000}"), None, None).is_err());
411        assert!(PlatformContext::new(Some("linux\u{0007}"), None, None).is_err());
412        assert_eq!(
413            PlatformContext::new(None, Some("x86_64"), None)
414                .unwrap()
415                .to_string(),
416            "-x86_64-"
417        );
418        assert_eq!(
419            PlatformContext::new(Some("linux"), None, Some("gnu"))
420                .unwrap()
421                .to_string(),
422            "linux--gnu"
423        );
424    }
425}