Skip to main content

shardline_server_core/
protocol_support.rs

1use sha2::{Digest, Sha256};
2use shardline_protocol::RepositoryScope;
3use shardline_storage::ObjectKey;
4
5use crate::validate_content_hash;
6
7const MAX_UPLOAD_SESSION_ID_BYTES: usize = 64;
8
9pub trait ProtocolValidation {
10    fn invalid_digest() -> Self;
11    fn invalid_content_hash() -> Self;
12    fn invalid_repository_name() -> Self;
13    fn not_found() -> Self;
14    fn invalid_manifest_reference() -> Self;
15    fn invalid_upload_session() -> Self;
16}
17
18/// Parses a `sha256:<hex>` digest string, validating the hex portion.
19///
20/// # Errors
21///
22/// Returns `E::invalid_digest()` when the value is not prefixed with `sha256:`
23/// or the hex portion fails content-hash validation.
24pub fn parse_sha256_digest<E: ProtocolValidation>(value: &str) -> Result<String, E> {
25    let Some(hash_hex) = value.strip_prefix("sha256:") else {
26        return Err(E::invalid_digest());
27    };
28    validate_content_hash(hash_hex).map_err(|_error| E::invalid_digest())?;
29    Ok(hash_hex.to_owned())
30}
31
32#[must_use]
33pub fn scope_namespace(repository_scope: Option<&RepositoryScope>) -> String {
34    repository_scope.map_or_else(
35        || "global".to_owned(),
36        |scope| {
37            let mut hasher = Sha256::new();
38            hasher.update(scope.provider().as_str().as_bytes());
39            hasher.update([0]);
40            hasher.update(scope.owner().as_bytes());
41            hasher.update([0]);
42            hasher.update(scope.name().as_bytes());
43            hasher.update([0]);
44            if let Some(revision) = scope.revision() {
45                hasher.update(revision.as_bytes());
46            }
47            hex::encode(hasher.finalize())
48        },
49    )
50}
51
52/// Returns the deterministic file-record identifier used for a protocol object.
53///
54/// Keeping this derivation in the shared core lets online request handling and
55/// offline garbage collection address the same deduplicated record without
56/// copying the encoding contract.
57#[must_use]
58pub fn protocol_object_file_id(object_key: &ObjectKey) -> String {
59    format!(
60        "protocol-object-{}",
61        hex::encode(Sha256::digest(object_key.as_str().as_bytes()))
62    )
63}
64
65/// Parses an object key from a string path.
66///
67/// # Errors
68///
69/// Returns `E::invalid_content_hash()` when the string is not a valid
70/// [`ObjectKey`] (empty, unsafe path, or too long).
71pub fn object_key<E: ProtocolValidation>(value: &str) -> Result<ObjectKey, E> {
72    ObjectKey::parse(value).map_err(|_error| E::invalid_content_hash())
73}
74
75/// Builds a shared-namespace object key for a SHA-256 digest.
76///
77/// # Errors
78///
79/// Returns `E::invalid_content_hash()` when the digest hex is malformed.
80pub fn shared_sha256_object_key<E: ProtocolValidation>(digest_hex: &str) -> Result<ObjectKey, E> {
81    validate_content_hash(digest_hex).map_err(|_error| E::invalid_content_hash())?;
82    object_key(&format!("protocols/shared/sha256/{digest_hex}"))
83}
84
85/// Validates an OCI repository name according to the OCI distribution spec.
86///
87/// # Errors
88///
89/// Returns `E::invalid_repository_name()` when the name is empty, contains
90/// path separators or traversal sequences, or has non-compliant segments.
91pub fn validate_oci_repository_name<E: ProtocolValidation>(value: &str) -> Result<(), E> {
92    if value.is_empty() || value.starts_with('/') || value.ends_with('/') || value.contains('\\') {
93        return Err(E::invalid_repository_name());
94    }
95
96    for segment in value.split('/') {
97        if segment.is_empty()
98            || segment == "."
99            || segment == ".."
100            || !segment.bytes().all(|byte| {
101                byte.is_ascii_lowercase()
102                    || byte.is_ascii_digit()
103                    || matches!(byte, b'.' | b'_' | b'-')
104            })
105        {
106            return Err(E::invalid_repository_name());
107        }
108    }
109
110    Ok(())
111}
112
113/// Validates that an OCI repository name falls within a bound repository scope.
114///
115/// When no scope is configured the check is a no-op.
116///
117/// # Errors
118///
119/// Returns `E::not_found()` when the name does not match or extend the
120/// repository scope's `owner/name` prefix.
121pub fn validate_oci_repository_scope<E: ProtocolValidation>(
122    value: &str,
123    repository_scope: Option<&RepositoryScope>,
124) -> Result<(), E> {
125    let Some(repository_scope) = repository_scope else {
126        return Ok(());
127    };
128
129    let expected_root = format!(
130        "{}/{}",
131        repository_scope.owner().to_ascii_lowercase(),
132        repository_scope.name().to_ascii_lowercase()
133    );
134    if value == expected_root
135        || value
136            .strip_prefix(&expected_root)
137            .is_some_and(|suffix| suffix.starts_with('/'))
138    {
139        return Ok(());
140    }
141
142    Err(E::not_found())
143}
144
145/// Validates an OCI tag reference according to the OCI distribution spec.
146///
147/// # Errors
148///
149/// Returns `E::invalid_manifest_reference()` when the tag is empty, exceeds
150/// 128 bytes, or contains invalid characters.
151pub fn validate_oci_tag<E: ProtocolValidation>(value: &str) -> Result<(), E> {
152    let mut bytes = value.bytes();
153    let Some(first) = bytes.next() else {
154        return Err(E::invalid_manifest_reference());
155    };
156    if !(first.is_ascii_alphanumeric() || first == b'_') {
157        return Err(E::invalid_manifest_reference());
158    }
159    if value.len() > 128
160        || !bytes.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'.' | b'-'))
161    {
162        return Err(E::invalid_manifest_reference());
163    }
164
165    Ok(())
166}
167
168/// Validates an upload session identifier.
169///
170/// Must be non-empty, at most 64 bytes, and contain only ASCII hex digits
171/// or hyphens.
172///
173/// # Errors
174///
175/// Returns `E::invalid_upload_session()` when the identifier is malformed.
176pub fn validate_upload_session_id<E: ProtocolValidation>(value: &str) -> Result<(), E> {
177    if value.is_empty()
178        || value.len() > MAX_UPLOAD_SESSION_ID_BYTES
179        || !value
180            .bytes()
181            .all(|byte| byte.is_ascii_hexdigit() || byte == b'-')
182    {
183        return Err(E::invalid_upload_session());
184    }
185
186    Ok(())
187}
188
189impl ProtocolValidation for crate::ValidateContentHashError {
190    fn invalid_digest() -> Self {
191        Self
192    }
193    fn invalid_content_hash() -> Self {
194        Self
195    }
196    fn invalid_repository_name() -> Self {
197        Self
198    }
199    fn not_found() -> Self {
200        Self
201    }
202    fn invalid_manifest_reference() -> Self {
203        Self
204    }
205    fn invalid_upload_session() -> Self {
206        Self
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use crate::ValidateContentHashError;
214
215    #[test]
216    fn sha256_digest_parser_requires_prefixed_lowercase_hex() {
217        let digest = parse_sha256_digest::<ValidateContentHashError>(
218            "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
219        );
220        assert!(digest.is_ok());
221        assert_eq!(
222            digest.unwrap_or_default(),
223            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
224        );
225        assert!(
226            parse_sha256_digest::<ValidateContentHashError>(
227                "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
228            )
229            .is_err()
230        );
231        assert!(
232            parse_sha256_digest::<ValidateContentHashError>(
233                "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdeg"
234            )
235            .is_err()
236        );
237    }
238
239    #[test]
240    fn oci_repository_validator_rejects_traversal_and_uppercase() {
241        assert!(validate_oci_repository_name::<ValidateContentHashError>("team/assets").is_ok());
242        assert!(validate_oci_repository_name::<ValidateContentHashError>("../assets").is_err());
243        assert!(validate_oci_repository_name::<ValidateContentHashError>("Team/assets").is_err());
244        assert!(validate_oci_repository_name::<ValidateContentHashError>("team//assets").is_err());
245    }
246
247    #[test]
248    fn oci_tag_validator_enforces_allowed_characters() {
249        assert!(validate_oci_tag::<ValidateContentHashError>("v1").is_ok());
250        assert!(validate_oci_tag::<ValidateContentHashError>("_debug.2026-04-23").is_ok());
251        assert!(validate_oci_tag::<ValidateContentHashError>("bad/tag").is_err());
252        assert!(validate_oci_tag::<ValidateContentHashError>("-bad").is_err());
253    }
254
255    #[test]
256    fn upload_session_validator_accepts_hex_and_hyphen_only() {
257        assert!(validate_upload_session_id::<ValidateContentHashError>("0000000000000001").is_ok());
258        assert!(validate_upload_session_id::<ValidateContentHashError>("dead-beef").is_ok());
259        assert!(validate_upload_session_id::<ValidateContentHashError>("session_1").is_err());
260        assert!(
261            validate_upload_session_id::<ValidateContentHashError>(
262                &"a".repeat(MAX_UPLOAD_SESSION_ID_BYTES + 1)
263            )
264            .is_err()
265        );
266    }
267
268    #[test]
269    fn oci_repository_scope_validator_accepts_bound_roots_and_nested_namespaces() {
270        use shardline_protocol::{RepositoryProvider, RepositoryScope};
271        let scope =
272            RepositoryScope::new(RepositoryProvider::GitHub, "team", "assets", None).unwrap();
273
274        assert!(
275            validate_oci_repository_scope::<ValidateContentHashError>("team/assets", Some(&scope))
276                .is_ok()
277        );
278        assert!(
279            validate_oci_repository_scope::<ValidateContentHashError>(
280                "team/assets/cache",
281                Some(&scope)
282            )
283            .is_ok()
284        );
285        assert!(
286            validate_oci_repository_scope::<ValidateContentHashError>("team/other", Some(&scope))
287                .is_err()
288        );
289        assert!(
290            validate_oci_repository_scope::<ValidateContentHashError>("other/assets", Some(&scope))
291                .is_err()
292        );
293    }
294
295    #[test]
296    fn shared_sha256_key_uses_stable_shared_namespace() {
297        let key = shared_sha256_object_key::<ValidateContentHashError>(
298            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
299        )
300        .unwrap();
301        assert_eq!(
302            key.as_str(),
303            "protocols/shared/sha256/0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
304        );
305    }
306
307    #[test]
308    fn scope_namespace_global_when_no_repository_scope() {
309        let ns = scope_namespace(None);
310        assert_eq!(ns, "global");
311    }
312
313    #[test]
314    fn scope_namespace_with_repository_scope() {
315        use shardline_protocol::{RepositoryProvider, RepositoryScope};
316        let scope =
317            RepositoryScope::new(RepositoryProvider::GitHub, "team", "assets", Some("main"))
318                .unwrap();
319        let ns = scope_namespace(Some(&scope));
320        // Should be a 64-char hex string (SHA-256)
321        assert_eq!(ns.len(), 64);
322        assert!(ns.chars().all(|c| c.is_ascii_hexdigit()));
323    }
324
325    #[test]
326    fn scope_namespace_without_revision() {
327        use shardline_protocol::{RepositoryProvider, RepositoryScope};
328        let scope =
329            RepositoryScope::new(RepositoryProvider::GitHub, "team", "assets", None).unwrap();
330        let ns = scope_namespace(Some(&scope));
331        assert_eq!(ns.len(), 64);
332    }
333
334    #[test]
335    fn object_key_valid_path() {
336        let key = object_key::<ValidateContentHashError>("aa/abcdef");
337        assert!(key.is_ok());
338        assert_eq!(key.unwrap().as_str(), "aa/abcdef");
339    }
340
341    #[test]
342    fn object_key_invalid_path() {
343        let key = object_key::<ValidateContentHashError>("");
344        assert!(key.is_err());
345    }
346
347    #[test]
348    fn shared_sha256_key_rejects_bad_hash() {
349        let key = shared_sha256_object_key::<ValidateContentHashError>("bad");
350        assert!(key.is_err());
351    }
352
353    #[test]
354    fn validate_oci_repository_scope_no_scope_is_noop() {
355        let result = validate_oci_repository_scope::<ValidateContentHashError>("any/repo", None);
356        assert!(result.is_ok());
357    }
358
359    #[test]
360    fn validate_oci_repository_scope_rejects_non_matching() {
361        use shardline_protocol::{RepositoryProvider, RepositoryScope};
362        let scope =
363            RepositoryScope::new(RepositoryProvider::GitHub, "team", "assets", None).unwrap();
364        let result =
365            validate_oci_repository_scope::<ValidateContentHashError>("other/repo", Some(&scope));
366        assert!(result.is_err());
367    }
368
369    #[test]
370    fn validate_oci_tag_rejects_empty() {
371        let result = validate_oci_tag::<ValidateContentHashError>("");
372        assert!(result.is_err());
373    }
374
375    #[test]
376    fn validate_oci_tag_rejects_invalid_start_char() {
377        let result = validate_oci_tag::<ValidateContentHashError>(".tag");
378        assert!(result.is_err());
379    }
380
381    #[test]
382    fn validate_oci_tag_rejects_oversized() {
383        let result = validate_oci_tag::<ValidateContentHashError>(&"a".repeat(129));
384        assert!(result.is_err());
385    }
386
387    #[test]
388    fn validate_upload_session_id_rejects_empty() {
389        let result = validate_upload_session_id::<ValidateContentHashError>("");
390        assert!(result.is_err());
391    }
392
393    #[test]
394    fn validate_upload_session_id_accepts_hex() {
395        let result = validate_upload_session_id::<ValidateContentHashError>("a1b2c3d4e5f6");
396        assert!(result.is_ok());
397    }
398
399    #[test]
400    fn validate_upload_session_id_rejects_special_chars() {
401        let result = validate_upload_session_id::<ValidateContentHashError>("session@123");
402        assert!(result.is_err());
403    }
404
405    #[test]
406    fn validate_oci_repository_name_rejects_empty() {
407        let result = validate_oci_repository_name::<ValidateContentHashError>("");
408        assert!(result.is_err());
409    }
410
411    #[test]
412    fn validate_oci_repository_name_rejects_leading_slash() {
413        let result = validate_oci_repository_name::<ValidateContentHashError>("/repo");
414        assert!(result.is_err());
415    }
416
417    #[test]
418    fn validate_oci_repository_name_rejects_trailing_slash() {
419        let result = validate_oci_repository_name::<ValidateContentHashError>("repo/");
420        assert!(result.is_err());
421    }
422
423    #[test]
424    fn validate_oci_repository_name_rejects_backslash() {
425        let result = validate_oci_repository_name::<ValidateContentHashError>("team\\repo");
426        assert!(result.is_err());
427    }
428
429    #[test]
430    fn validate_oci_repository_name_rejects_double_slash() {
431        let result = validate_oci_repository_name::<ValidateContentHashError>("team//repo");
432        assert!(result.is_err());
433    }
434
435    #[test]
436    fn validate_oci_repository_name_rejects_dot_segment() {
437        let result = validate_oci_repository_name::<ValidateContentHashError>("team/./repo");
438        assert!(result.is_err());
439    }
440
441    #[test]
442    fn validate_oci_repository_name_rejects_dot_dot() {
443        let result = validate_oci_repository_name::<ValidateContentHashError>("team/../repo");
444        assert!(result.is_err());
445    }
446
447    #[test]
448    fn validate_oci_repository_name_rejects_uppercase() {
449        let result = validate_oci_repository_name::<ValidateContentHashError>("Team/Repo");
450        assert!(result.is_err());
451    }
452
453    #[test]
454    fn validate_oci_repository_name_rejects_invalid_chars() {
455        let result = validate_oci_repository_name::<ValidateContentHashError>("team/repo!");
456        assert!(result.is_err());
457    }
458
459    #[test]
460    fn parse_sha256_digest_missing_prefix() {
461        let result = parse_sha256_digest::<ValidateContentHashError>(
462            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
463        );
464        assert!(result.is_err());
465    }
466
467    #[test]
468    fn parse_sha256_digest_bad_hex() {
469        let result = parse_sha256_digest::<ValidateContentHashError>(
470            "sha256:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
471        );
472        assert!(result.is_err());
473    }
474}