holger-znippy-python-repository 0.1.3

Holger guards your artifacts at rest. May Allfather Odin watch over every bit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Python (pip) repository backend: serves a PEP 503 "simple" index synthesized
//! from wheels/sdists inside a read-only znippy archive. Sibling to the other
//! `znippy-<eco>` backends; implements [`RepositoryBackendTrait`] and is wired in
//! read-only (`is_writable` false, `put` errors).
//!
//! Layout convention: files live at `packages/{normalized-name}/{filename}`, name
//! normalized per PEP 503 (lowercase, `_`/`.` → `-`). `handle_http2_request` routes
//! `/simple/`, `/simple/{name}/`, and `/packages/{name}/{filename}` after stripping
//! the repo-name prefix.
//!
//! Coord resolution has two tiers: prefer the concrete archive's typed python view
//! ([`ZnippyArchive::as_python`]) whose `(name, version)` come from index columns the
//! python plugin extracted, so wheels vs sdists resolve authoritatively; fall back to
//! parsing the dist *filename* when that view is empty (e.g. an archive built by the
//! agent's directory→znippy path, which tags `pkg_type` but writes no columns) or when
//! only a generic `ZnippyReader` is configured.
//!
//! Gotcha: the simple index reflects attacker-influenced package/file names into HTML,
//! so every interpolated value goes through `html_escape` (reflected-injection, M10).

use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::fmt::Write as _;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use anyhow::{anyhow, Result};

use traits::{ArtifactEntry, ArtifactFormat, ArtifactId, RepositoryBackendTrait};
use znippy_common::{ZnippyArchive, ZnippyReader};

/// SHA-256 of `bytes`, lower-hex. This is the digest pip/uv verify a downloaded
/// distribution against — znippy content-addresses with blake3 (which pip/uv do
/// not accept), so the PEP-facing hash MUST be a real SHA-256 of the served file.
fn sha256_hex(bytes: &[u8]) -> String {
    // LAW #5 dedup: the PEP-facing SHA-256 comes from the shared `nornir-hash`
    // leaf (edda) — byte-identical to the digest pip/uv verify against.
    nornir_hash::sha256_hex(bytes)
}

/// JSON-string-escape `s` for safe interpolation into a hand-built PEP 691 body
/// (the index reflects attacker-influenced package/file names). Escapes the two
/// structural characters plus control chars; package/file names never legitimately
/// contain quotes or backslashes, so a hostile one is neutralised, not reflected.
fn json_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out
}

/// Escape a string for safe interpolation into HTML text/attribute contexts.
///
/// The PEP 503 simple index reflects attacker-influenced values (the requested
/// package `name` from the URL, and package/file names from archive contents)
/// into HTML. Without escaping these are a reflected HTML/script-injection
/// vector (M10). Escapes the five significant characters; sufficient for both
/// element text and double-quoted attribute values.
fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#x27;"),
            _ => out.push(c),
        }
    }
    out
}

/// znippy-backed Python package index implementing PEP 503.
///
/// Serves packages from any `ZnippyReader` backend.
/// Files stored as: `packages/{normalized-name}/{filename}`.
pub struct PipRepoZnippy {
    pub name: String,
    reader: Option<Arc<dyn ZnippyReader>>,
    /// Concrete archive — drives the typed python view ([`ZnippyArchive::as_python`])
    /// so `(name, version)` coords come from the index columns the python plugin
    /// extracted (wheel filename / sdist), resolving wheels vs sdists correctly
    /// instead of guessing `{name}-{version}.tar.gz` or substring-matching the
    /// version. Built once at open, held, reused (view cached behind `OnceLock`).
    archive: Option<Arc<ZnippyArchive>>,
    /// Memoised SHA-256 (lower-hex) of each served distribution, keyed by its
    /// archive path. The simple-index detail page (PEP 503 `#sha256=` fragment /
    /// PEP 691 `hashes.sha256`) needs the digest pip/uv verify against, and znippy
    /// stores only blake3 — so it is computed from the file bytes on first touch
    /// and reused. Never on the artifact-download hot path (`/packages/...`), which
    /// is byte-identical to before.
    sha_cache: Mutex<HashMap<String, String>>,
}

// Manual Debug impl because dyn ZnippyReader does not implement Debug.
impl fmt::Debug for PipRepoZnippy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PipRepoZnippy")
            .field("name", &self.name)
            .field("reader", &self.reader.as_ref().map(|_| "<dyn ZnippyReader>"))
            .field("archive", &self.archive.as_ref().map(|_| "<ZnippyArchive>"))
            .field("sha_cached", &self.sha_cache.lock().map(|c| c.len()).unwrap_or(0))
            .finish()
    }
}

/// Normalize a package name per PEP 503: lowercase and replace `_` / `.` with `-`.
/// Parse a python distribution filename into `(name, version)`.
///
/// - Wheel `{dist}-{version}(-{build})?-{py}-{abi}-{plat}.whl`: the first two
///   `-`-separated tokens are the distribution and version (PEP 427).
/// - sdist `{name}-{version}.tar.gz` / `.zip`: split at the last `-`.
///
/// Returns `None` for anything else (e.g. a stray `.txt`).
fn parse_dist_filename(filename: &str) -> Option<(String, String)> {
    if let Some(stem) = filename.strip_suffix(".whl") {
        let parts: Vec<&str> = stem.split('-').collect();
        if parts.len() >= 2 && !parts[0].is_empty() && !parts[1].is_empty() {
            return Some((parts[0].to_string(), parts[1].to_string()));
        }
        return None;
    }
    let stem = filename
        .strip_suffix(".tar.gz")
        .or_else(|| filename.strip_suffix(".tgz"))
        .or_else(|| filename.strip_suffix(".zip"))?;
    let (name, version) = stem.rsplit_once('-')?;
    if name.is_empty() || version.is_empty() {
        return None;
    }
    Some((name.to_string(), version.to_string()))
}

fn normalize_name(s: &str) -> String {
    s.to_lowercase().replace(['_', '.'], "-")
}

impl PipRepoZnippy {
    pub fn new(name: String) -> Self {
        Self { name, reader: None, archive: None, sha_cache: Mutex::new(HashMap::new()) }
    }

    /// Create a repo backed by a specific znippy archive file
    pub fn with_archive(name: String, archive_path: PathBuf) -> Result<Self> {
        let archive = Arc::new(ZnippyArchive::open(&archive_path)?);
        Ok(Self {
            name,
            reader: Some(Arc::clone(&archive) as Arc<dyn ZnippyReader>),
            archive: Some(archive),
            sha_cache: Mutex::new(HashMap::new()),
        })
    }

    /// Create a repo backed by any ZnippyReader implementation
    pub fn with_reader(name: String, reader: Arc<dyn ZnippyReader>) -> Self {
        Self {
            name,
            reader: Some(reader),
            archive: None,
            sha_cache: Mutex::new(HashMap::new()),
        }
    }

    /// SHA-256 (lower-hex) of the distribution at archive `path`, memoised. Returns
    /// `None` when the file cannot be read (so a link is emitted without a hash
    /// fragment rather than the request failing). This is the digest pip/uv verify
    /// the download against; see [`sha256_hex`].
    fn sha256_hex_of(&self, path: &str) -> Option<String> {
        if let Ok(cache) = self.sha_cache.lock() {
            if let Some(h) = cache.get(path) {
                return Some(h.clone());
            }
        }
        let bytes = self.get_file(path).ok()?;
        let hex = sha256_hex(&bytes);
        if let Ok(mut cache) = self.sha_cache.lock() {
            cache.insert(path.to_string(), hex.clone());
        }
        Some(hex)
    }

    pub fn list_files(&self) -> Vec<String> {
        match &self.reader {
            Some(r) => r.list_files().unwrap_or_default(),
            None => vec![],
        }
    }

    pub fn get_file(&self, relative_path: &str) -> Result<Vec<u8>> {
        let reader = self.reader.as_ref()
            .ok_or_else(|| anyhow!("No reader configured"))?;
        reader.extract_file(relative_path)
    }

    /// The distribution files for one (already-requested) package `name`, as
    /// `(filename, href, sha256_hex)` triples. `href` is the download URL served
    /// by this repo (`/{repo}/packages/{normalized}/{filename}`); `sha256_hex` is
    /// the memoised SHA-256 pip/uv verify against (`None` if unreadable). Shared by
    /// the PEP 503 HTML detail page and the PEP 691 JSON representation so the two
    /// never drift.
    fn dist_files(&self, name: &str) -> Vec<(String, String, Option<String>)> {
        let normalized = normalize_name(name);
        let prefix = format!("packages/{}/", normalized);
        let mut out = Vec::new();
        for f in self.list_files() {
            let Some(filename) = f.strip_prefix(&prefix) else { continue };
            // Skip nested directories — only direct distribution files.
            if filename.is_empty() || filename.contains('/') {
                continue;
            }
            let href = format!("/{}/{}", self.name, f);
            let sha = self.sha256_hex_of(&f);
            out.push((filename.to_string(), href, sha));
        }
        out
    }
}

impl RepositoryBackendTrait for PipRepoZnippy {
    fn name(&self) -> &str {
        &self.name
    }

    fn handle_http2_request(
        &self,
        method: &str,
        suburl: &str,
        body: &[u8],
    ) -> anyhow::Result<(u16, Vec<(String, String)>, Vec<u8>)> {
        let _ = (method, body);
        log::debug!("Pip repo znippy handle_http2_request.suburl={}", suburl);

        // Strip leading repo name prefix: /{repo}/simple/... or /{repo}/packages/...
        let path = suburl.trim_start_matches('/');
        let remainder = match path.strip_prefix(&self.name) {
            Some(r) => r.trim_start_matches('/'),
            None => path,
        };

        // Split on '/' and drop empty segments (handles trailing slashes).
        let parts: Vec<&str> = remainder.split('/').filter(|s| !s.is_empty()).collect();

        match parts.as_slice() {
            // GET /{repo}/simple/  →  list all unique package names
            ["simple"] => {
                let files = self.list_files();
                let mut names: BTreeSet<String> = BTreeSet::new();
                for f in &files {
                    if let Some(rest) = f.strip_prefix("packages/") {
                        if let Some(slash_pos) = rest.find('/') {
                            let pkg_name = &rest[..slash_pos];
                            if !pkg_name.is_empty() {
                                names.insert(pkg_name.to_string());
                            }
                        }
                    }
                }

                let mut links = String::new();
                for n in &names {
                    let e = html_escape(n);
                    links.push_str(&format!("<a href=\"{}/\">{}</a><br>\n", e, e));
                }
                let html = format!(
                    "<!DOCTYPE html>\n<html><head><title>Simple Index</title></head>\n<body>\n{}</body></html>",
                    links
                );
                Ok((
                    200,
                    vec![("Content-Type".into(), "text/html".into())],
                    html.into_bytes(),
                ))
            }

            // GET /{repo}/simple/{name}/json  →  PEP 691 JSON project detail. Same
            // data as the HTML detail page, machine-readable. (uv/pip negotiate
            // this via an `Accept:` header, which the backend trait does not
            // surface today; this explicit `.../json` route makes the PEP 691
            // representation reachable + testable meanwhile — see design doc.)
            ["simple", name, "json"] => {
                let dists = self.dist_files(name);
                let mut files_json = String::new();
                for (i, (filename, href, sha)) in dists.iter().enumerate() {
                    if i > 0 {
                        files_json.push(',');
                    }
                    let hashes = match sha {
                        Some(h) => format!("{{\"sha256\":\"{}\"}}", json_escape(h)),
                        None => "{}".to_string(),
                    };
                    let _ = write!(
                        files_json,
                        "{{\"filename\":\"{}\",\"url\":\"{}\",\"hashes\":{}}}",
                        json_escape(filename),
                        json_escape(href),
                        hashes,
                    );
                }
                let body = format!(
                    "{{\"meta\":{{\"api-version\":\"1.0\"}},\"name\":\"{}\",\"files\":[{}]}}",
                    json_escape(&normalize_name(name)),
                    files_json,
                );
                Ok((
                    200,
                    vec![(
                        "Content-Type".into(),
                        "application/vnd.pypi.simple.v1+json".into(),
                    )],
                    body.into_bytes(),
                ))
            }

            // GET /{repo}/simple/{name}/  →  list all files for the package. Each
            // link carries a `#sha256=<hex>` fragment (PEP 503) so pip/uv can
            // verify the download — the digest of the served bytes (memoised).
            ["simple", name] => {
                let mut links = String::new();
                for (filename, href, sha) in self.dist_files(name) {
                    let href_frag = match &sha {
                        Some(h) => format!("{}#sha256={}", href, h),
                        None => href,
                    };
                    links.push_str(&format!(
                        "<a href=\"{}\">{}</a><br>\n",
                        html_escape(&href_frag),
                        html_escape(&filename)
                    ));
                }

                let name_esc = html_escape(name);
                let html = format!(
                    "<!DOCTYPE html>\n<html><head><title>Links for {name}</title></head>\n<body><h1>Links for {name}</h1>\n{links}</body></html>",
                    name = name_esc,
                    links = links,
                );
                Ok((
                    200,
                    vec![("Content-Type".into(), "text/html".into())],
                    html.into_bytes(),
                ))
            }

            // GET /{repo}/packages/{name}/{filename}  →  serve file from archive
            ["packages", name, filename] => {
                let normalized = normalize_name(name);
                let archive_path = format!("packages/{}/{}", normalized, filename);
                match self.get_file(&archive_path) {
                    Ok(data) => {
                        let content_type = if filename.ends_with(".whl") {
                            "application/zip"
                        } else if filename.ends_with(".tar.gz") {
                            "application/gzip"
                        } else if filename.ends_with(".zip") {
                            "application/zip"
                        } else {
                            "application/octet-stream"
                        };
                        Ok((
                            200,
                            vec![("Content-Type".into(), content_type.into())],
                            data,
                        ))
                    }
                    Err(_) => Ok((404, Vec::new(), b"Not found in archive".to_vec())),
                }
            }

            _ => Ok((404, Vec::new(), b"Not found".to_vec())),
        }
    }

    fn format(&self) -> ArtifactFormat {
        ArtifactFormat::Pip
    }

    fn is_writable(&self) -> bool {
        false
    }

    /// Browse: one entry per distribution file in the archive. Prefers the typed
    /// python view (authoritative `name`/`version` columns the python plugin wrote);
    /// when that view is empty — e.g. an archive packed by the agent's
    /// directory→znippy builder, which tags `pkg_type` but writes no columns — it
    /// falls back to parsing the wheel/sdist *filename*, so wheels still Browse.
    fn list(&self, name_filter: Option<&str>, limit: usize) -> anyhow::Result<Vec<ArtifactEntry>> {
        let mut out = Vec::new();

        // Authoritative path: typed view coords.
        if let Some(archive) = &self.archive {
            if let Some(python) = archive.as_python() {
                for (name, version) in python.list() {
                    if name_filter.is_some_and(|f| !name.contains(f)) {
                        continue;
                    }
                    out.push(ArtifactEntry {
                        id: ArtifactId { namespace: None, name, version },
                        size_bytes: 0,
                        content_type: "application/octet-stream".into(),
                    });
                    if limit != 0 && out.len() >= limit {
                        break;
                    }
                }
                if !out.is_empty() {
                    return Ok(out);
                }
            }
        }

        // Fallback: parse distribution filenames from the raw file list.
        for path in self.list_files() {
            let filename = path.rsplit('/').next().unwrap_or(&path);
            let Some((name, version)) = parse_dist_filename(filename) else {
                continue;
            };
            if name_filter.is_some_and(|f| !name.contains(f)) {
                continue;
            }
            let size_bytes = self
                .reader
                .as_ref()
                .and_then(|r| r.file_size(&path))
                .unwrap_or(0) as i64;
            out.push(ArtifactEntry {
                id: ArtifactId { namespace: None, name, version },
                size_bytes,
                content_type: "application/octet-stream".into(),
            });
            if limit != 0 && out.len() >= limit {
                break;
            }
        }
        Ok(out)
    }

    /// Archive view: the raw distribution filenames stored in this repo.
    fn archive_files(&self, prefix: Option<&str>) -> anyhow::Result<Vec<String>> {
        Ok(self
            .list_files()
            .into_iter()
            .filter(|p| prefix.is_none_or(|pre| p.starts_with(pre)))
            .collect())
    }

    fn fetch(&self, id: &ArtifactId) -> anyhow::Result<Option<Vec<u8>>> {
        // Static archive: resolve through the typed python view — `(name, version)`
        // coords are read from the index columns the python plugin extracted, so a
        // wheel or sdist resolves by its authoritative coords (kind included)
        // rather than guessing the `.tar.gz` filename or substring-matching.
        if let Some(archive) = &self.archive {
            if let Some(python) = archive.as_python() {
                return match python.get(&id.name, &id.version) {
                    Some(pkg) => Ok(Some(pkg.into_bytes()?)),
                    None => Ok(None),
                };
            }
        }

        // Fallback (generic reader): canonical filename then substring match.
        // id.namespace = None, id.name = "requests", id.version = "2.31.0"
        // Try: packages/requests/requests-2.31.0.tar.gz
        let canonical = format!("packages/{}/{}-{}.tar.gz", id.name, id.name, id.version);
        if let Ok(data) = self.get_file(&canonical) {
            return Ok(Some(data));
        }

        // Fallback: list all files under packages/{name}/ and return the first
        // whose filename contains the requested version string.
        let prefix = format!("packages/{}/", normalize_name(&id.name));
        for f in self.list_files() {
            if f.starts_with(&prefix) {
                if let Some(filename) = f.strip_prefix(&prefix) {
                    if filename.contains(id.version.as_str()) {
                        if let Ok(data) = self.get_file(&f) {
                            return Ok(Some(data));
                        }
                    }
                }
            }
        }

        Ok(None)
    }

    fn put(&self, _id: &ArtifactId, _data: &[u8]) -> anyhow::Result<()> {
        Err(anyhow!("Pip znippy repository is read-only"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Emit one functional-status row for a real check. Gated behind
    /// `--features testmatrix` so release builds strip it (dep is optional).
    #[cfg(feature = "testmatrix")]
    fn fstatus(component: &str, check: &str, ok: bool, detail: &str) {
        nornir_testmatrix::functional_status(component, check, ok, detail);
    }

    #[test]
    fn test_html_escape_blocks_injection() {
        // A package/file name carrying an HTML/script payload must come back
        // fully escaped so the PEP 503 simple index cannot reflect markup (M10).
        let hostile = r#"<script>alert("x")</script>&'"#;
        let escaped = html_escape(hostile);
        assert!(!escaped.contains('<'));
        assert!(!escaped.contains('>'));
        assert!(!escaped.contains('"'));
        assert!(!escaped.contains('\''));
        assert_eq!(
            escaped,
            "&lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;&amp;&#x27;"
        );
        // Benign names pass through unchanged.
        assert_eq!(html_escape("requests-2.31.0.tar.gz"), "requests-2.31.0.tar.gz");
    }

    #[test]
    fn parse_dist_filename_wheels_and_sdists() {
        // wheel: first two `-` tokens are dist + version (build/py/abi/plat ignored)
        assert_eq!(
            parse_dist_filename("requests-2.31.0-py3-none-any.whl"),
            Some(("requests".into(), "2.31.0".into()))
        );
        assert_eq!(
            parse_dist_filename("python_dateutil-2.9.0.post0-py2.py3-none-any.whl"),
            Some(("python_dateutil".into(), "2.9.0.post0".into()))
        );
        // sdist: split at the last `-`
        assert_eq!(
            parse_dist_filename("requests-2.31.0.tar.gz"),
            Some(("requests".into(), "2.31.0".into()))
        );
        assert_eq!(
            parse_dist_filename("Flask-3.0.0.zip"),
            Some(("Flask".into(), "3.0.0".into()))
        );
        // non-distribution files are ignored
        assert_eq!(parse_dist_filename("index.html"), None);
        assert_eq!(parse_dist_filename("noversion.whl"), None);

        #[cfg(feature = "testmatrix")]
        fstatus(
            "znippy-python",
            "parse_dist_filename",
            parse_dist_filename("requests-2.31.0-py3-none-any.whl").is_some(),
            "wheel + sdist filenames parse to (name, version)",
        );
    }

    #[test]
    fn test_new() {
        let repo = PipRepoZnippy::new("pip-test".to_string());
        assert_eq!(repo.name(), "pip-test");
        assert!(repo.list_files().is_empty());

        #[cfg(feature = "testmatrix")]
        fstatus(
            "znippy-python",
            "new_repo_named_and_empty",
            repo.name() == "pip-test" && repo.list_files().is_empty(),
            &format!("name={} files={}", repo.name(), repo.list_files().len()),
        );
    }

    #[test]
    fn test_readonly() {
        let repo = PipRepoZnippy::new("pip-test".to_string());
        assert!(!repo.is_writable());
        let id = ArtifactId {
            namespace: None,
            name: "requests".to_string(),
            version: "2.31.0".to_string(),
        };
        let put = repo.put(&id, b"data");
        assert!(put.is_err());

        #[cfg(feature = "testmatrix")]
        fstatus(
            "znippy-python",
            "is_readonly",
            !repo.is_writable() && put.is_err(),
            &format!("writable={} put_err={}", repo.is_writable(), put.is_err()),
        );
    }

    #[test]
    fn test_format() {
        let repo = PipRepoZnippy::new("pip-test".to_string());
        assert_eq!(repo.format(), ArtifactFormat::Pip);

        #[cfg(feature = "testmatrix")]
        fstatus(
            "znippy-python",
            "format_is_pip",
            repo.format() == ArtifactFormat::Pip,
            &format!("format = {:?}", repo.format()),
        );
    }

    #[test]
    fn test_sha256_hex_known_vector() {
        // NIST/RFC-well-known: SHA-256("abc").
        assert_eq!(
            sha256_hex(b"abc"),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        // SHA-256("") — empty input.
        assert_eq!(
            sha256_hex(b""),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
        // Digest is always 64 lower-hex chars.
        let h = sha256_hex(b"holger");
        assert_eq!(h.len(), 64);
        assert!(h.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()));

        #[cfg(feature = "testmatrix")]
        fstatus(
            "znippy-python",
            "sha256_hex_content_address",
            sha256_hex(b"abc")
                == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
            "SHA-256(\"abc\") matches the known vector — the digest pip/uv verify against",
        );
    }

    #[test]
    fn test_json_escape_blocks_injection() {
        // A hostile filename cannot break out of a JSON string (PEP 691 body).
        assert_eq!(json_escape(r#"a"b\c"#), r#"a\"b\\c"#);
        assert_eq!(json_escape("line\nbreak"), "line\\nbreak");
        // A control char is \u-escaped, never emitted raw.
        assert!(json_escape("\u{0007}").starts_with("\\u0007"));
        // Benign package names pass through.
        assert_eq!(json_escape("apache-airflow"), "apache-airflow");

        #[cfg(feature = "testmatrix")]
        fstatus(
            "znippy-python",
            "json_escape_pep691",
            json_escape(r#"a"b\c"#) == r#"a\"b\\c"#,
            "quote + backslash escaped so a hostile filename can't break the PEP 691 JSON",
        );
    }

    #[test]
    fn test_normalize_name() {
        assert_eq!(normalize_name("Requests"), "requests");
        assert_eq!(normalize_name("my_package"), "my-package");
        assert_eq!(normalize_name("my.package"), "my-package");
        assert_eq!(normalize_name("My_Package.Name"), "my-package-name");

        #[cfg(feature = "testmatrix")]
        fstatus(
            "znippy-python",
            "normalize_name_pep503",
            normalize_name("Requests") == "requests"
                && normalize_name("My_Package.Name") == "my-package-name",
            &format!("My_Package.Name -> {}", normalize_name("My_Package.Name")),
        );
    }
}