Skip to main content

bynk/registry/
conformance.rs

1//! `bynk registry conformance` (first-party registry track R0, #2311): run the
2//! registry protocol's observable behaviour against a registry URL, and report
3//! each check.
4//!
5//! Servers are judged by the client's own code wherever it can be used — the
6//! `config.json` and key-chain reading, line verification, archive fetching
7//! and checksumming are exactly what a consumer runs. Only requests a client
8//! would never make (a bad token, a mismatched URL, a hostile archive, an
9//! oversized declared length) go through `transport::request` directly.
10//!
11//! A full run publishes one throwaway package, `<org>/conformance_<utc>_<hex>`,
12//! and yanks every version it published: indexes are append-only, so that
13//! package stays behind, yanked, and the report names it (decision B).
14//! `--read-only` publishes nothing.
15
16use std::path::{Path, PathBuf};
17use std::time::{Duration, Instant};
18
19use bynk_project::manifest::RegistryConfig;
20
21use super::protocol::{Config, ConfigTrust, IndexLine, Signers, fingerprint, verify};
22use super::transport::{self, Auth, Body};
23use super::{Client, archive};
24
25/// A failed check: the registry breaks the protocol.
26pub const NONCONFORMANT: &str = "bynk.registry.nonconformant";
27
28/// What to run against.
29#[derive(Debug, Clone)]
30pub struct Options {
31    /// The registry's index URL.
32    pub index: String,
33    /// The organisation the token may publish and yank under.
34    pub org: String,
35    /// The registry name the token is found under (`BYNK_REGISTRY_<NAME>_TOKEN`).
36    pub name: String,
37    /// A key to pin, `ed25519:…`; trusted on first use for the run otherwise.
38    pub key: Option<String>,
39    /// Publish nothing: check `config.json` and an existing package only.
40    pub read_only: bool,
41    /// The existing `org/package` a `--read-only` run verifies.
42    pub package: Option<String>,
43    /// A token that can't act for `org`, for the `auth.scope` check:
44    /// `Err(variable)` when the variable it was asked to come from is unset.
45    pub narrow_token: Option<Result<String, String>>,
46    /// The upload cap to test `413` against.
47    pub max_upload: u64,
48}
49
50/// A check's outcome.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Outcome {
53    Pass,
54    Fail,
55    Skip,
56}
57
58impl Outcome {
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Outcome::Pass => "pass",
62            Outcome::Fail => "fail",
63            Outcome::Skip => "skip",
64        }
65    }
66}
67
68/// Every check a full (publishing) run reports, in order, so the set of ids is
69/// stable whatever fails: a check a run couldn't reach is reported skipped.
70pub const FULL_RUN: &[&str] = &[
71    "config.shape",
72    "config.chain",
73    "config.delegations",
74    "publish.created",
75    "publish.read-back",
76    "publish.signer",
77    "publish.retry-same-tree",
78    "publish.conflict",
79    "refuse.other-package",
80    "refuse.other-version",
81    "refuse.junk",
82    "refuse.traversal",
83    "refuse.path-dependency",
84    "refuse.clean",
85    "auth.missing",
86    "auth.unknown",
87    "auth.scope",
88    "limits.too-large",
89    "consume.resolve",
90    "yank.yank",
91    "yank.unyank",
92    "yank.missing",
93    "errors.shape",
94];
95
96/// One check's result.
97#[derive(Debug, Clone)]
98pub struct Check {
99    /// A stable id, `group.name`.
100    pub id: &'static str,
101    pub outcome: Outcome,
102    pub detail: String,
103    /// The protocol spec section the check holds a registry to.
104    pub spec: &'static str,
105}
106
107/// A run's results.
108#[derive(Debug, Clone, Default)]
109pub struct Report {
110    /// The registry's declared `id`, once `config.json` was read.
111    pub registry_id: Option<String>,
112    /// The throwaway package a full run published (and yanked).
113    pub published: Option<String>,
114    pub checks: Vec<Check>,
115}
116
117impl Report {
118    pub fn failed(&self) -> usize {
119        self.count(Outcome::Fail)
120    }
121
122    pub fn count(&self, outcome: Outcome) -> usize {
123        self.checks.iter().filter(|c| c.outcome == outcome).count()
124    }
125
126    /// The report as JSON: the registry, the package, and each check.
127    pub fn render_json(&self) -> String {
128        let checks: Vec<serde_json::Value> = self
129            .checks
130            .iter()
131            .map(|c| {
132                serde_json::json!({
133                    "id": c.id,
134                    "outcome": c.outcome.as_str(),
135                    "detail": c.detail,
136                    "spec": c.spec,
137                })
138            })
139            .collect();
140        let doc = serde_json::json!({
141            "registry": self.registry_id,
142            "published": self.published,
143            "passed": self.count(Outcome::Pass),
144            "failed": self.count(Outcome::Fail),
145            "skipped": self.count(Outcome::Skip),
146            "checks": checks,
147        });
148        serde_json::to_string_pretty(&doc).expect("a JSON value renders") + "\n"
149    }
150}
151
152const S_CONFIG: &str = "/reference/tooling/registry-protocol/#configjson";
153const S_TRUST: &str = "/reference/tooling/registry-protocol/#trust";
154const S_INDEX: &str = "/reference/tooling/registry-protocol/#index-files";
155const S_ARCHIVES: &str = "/reference/tooling/registry-protocol/#archives";
156const S_PUBLISH: &str = "/reference/tooling/registry-protocol/#publish-api";
157const S_DELEGATION: &str = "/reference/tooling/registry-protocol/#delegation-and-revocation";
158const S_WITHDRAWALS: &str = "/reference/tooling/registry-protocol/#withdrawals";
159const SPEC_FOR_SKIP: &str = "/reference/tooling/registry-protocol/#conformance";
160
161/// How long `yank.yank` and `yank.unyank` wait for the index to show the
162/// change: an edge cache may serve an index file for up to a minute (the
163/// first-party registry's `max-age=60`), and a purge racing the response it
164/// should clear can leave the old copy for that long.
165const YANK_SETTLE: Duration = Duration::from_secs(65);
166/// How often they read the index while waiting.
167const YANK_POLL: Duration = Duration::from_secs(2);
168
169struct Run<'o> {
170    opts: &'o Options,
171    report: Report,
172    work: PathBuf,
173    /// #2316: the registry's `config.json` as served, and who may sign its
174    /// lines, once `config.delegations` has read them.
175    config: Option<(Config, Signers)>,
176}
177
178impl Run<'_> {
179    fn record(&mut self, id: &'static str, spec: &'static str, result: Result<String, String>) {
180        let (outcome, detail) = match result {
181            Ok(d) => (Outcome::Pass, d),
182            Err(d) => (Outcome::Fail, d),
183        };
184        self.report.checks.push(Check {
185            id,
186            outcome,
187            detail,
188            spec,
189        });
190    }
191
192    /// Report every full-run check not yet reported as skipped, with `why`.
193    fn skip_rest(&mut self, why: &str) {
194        for id in FULL_RUN {
195            if !self.report.checks.iter().any(|c| c.id == *id) {
196                self.skip(id, SPEC_FOR_SKIP, why);
197            }
198        }
199    }
200
201    fn skip(&mut self, id: &'static str, spec: &'static str, why: &str) {
202        self.report.checks.push(Check {
203            id,
204            outcome: Outcome::Skip,
205            detail: why.to_string(),
206            spec,
207        });
208    }
209}
210
211/// Run the suite.
212pub fn run(opts: &Options) -> Report {
213    let work = scratch_dir();
214    let mut run = Run {
215        opts,
216        report: Report::default(),
217        work: work.clone(),
218        config: None,
219    };
220    checks(&mut run);
221    let _ = std::fs::remove_dir_all(&work);
222    run.report
223}
224
225fn client(opts: &Options) -> Client {
226    Client::new(
227        vec![RegistryConfig {
228            name: opts.name.clone(),
229            index: opts.index.clone(),
230            organisations: vec![opts.org.clone()],
231            mirror_of: None,
232            key: opts.key.clone(),
233        }],
234        None,
235    )
236}
237
238fn checks(run: &mut Run<'_>) {
239    let opts = run.opts;
240    // config.*: the client's own reading of `config.json` and its chain.
241    let mut reader = client(opts);
242    let token = super::token_for(&opts.name, Some(&opts.org), &mut Vec::new()).map(|(t, _)| t);
243    let api = match reader.open(&opts.name) {
244        Ok(o) => {
245            run.report.registry_id = Some(o.id.clone());
246            let id = o.id.clone();
247            let keys = o.keys.len();
248            let api = o.api.clone();
249            let index = o.index.clone();
250            let served = raw_config(&index);
251            let protocol = match &served {
252                Ok(c) if !c.delegations.is_empty() || !c.revoked.is_empty() => 2,
253                _ => 1,
254            };
255            run.record(
256                "config.shape",
257                S_CONFIG,
258                Ok(format!(
259                    "protocol {protocol}, id `{id}`, dl, auth{}",
260                    if api.is_some() { ", api" } else { "" }
261                )),
262            );
263            run.record(
264                "config.chain",
265                S_TRUST,
266                Ok(format!(
267                    "{keys} key{} trusted, each link verified",
268                    if keys == 1 { "" } else { "s" }
269                )),
270            );
271            // config.delegations (#2316): every delegation and revocation
272            // verifies against the chain.
273            let result = served.and_then(|config| {
274                let first = fingerprint(&config.keys[0].key).unwrap_or_default();
275                config
276                    .chain_from(&first)
277                    .ok_or("the key chain doesn't verify from its first key")?;
278                // Judged as a client pinned to the newest key sees it: the
279                // strictest view, since every anchor reaches the newest key.
280                let newest = config.keys.last().expect("parse checks").key.clone();
281                let signers = config.signers(&[newest]);
282                let detail = format!(
283                    "{} delegation(s), {} revocation(s), each signed by the newest chain key",
284                    config.delegations.len(),
285                    config.revoked.len()
286                );
287                let ignored = signers.ignored.clone();
288                run.config = Some((config, signers));
289                if ignored.is_empty() {
290                    Ok(detail)
291                } else {
292                    Err(format!("`config.json` has {}", ignored.join("; ")))
293                }
294            });
295            run.record("config.delegations", S_DELEGATION, result);
296            api
297        }
298        Err(e) => {
299            let chain = e.code == super::KEY_MISMATCH || e.code == super::BAD_SIGNATURE;
300            if chain {
301                run.record("config.shape", S_CONFIG, Ok("`config.json` parses".into()));
302                run.record("config.chain", S_TRUST, Err(e.to_string()));
303            } else {
304                run.record("config.shape", S_CONFIG, Err(e.to_string()));
305                run.skip("config.chain", S_TRUST, "`config.json` couldn't be read");
306            }
307            if !opts.read_only {
308                run.skip_rest("`config.json` didn't verify");
309            }
310            return;
311        }
312    };
313
314    if opts.read_only {
315        read_only(run, &mut reader);
316        return;
317    }
318    let Some(api) = api else {
319        run.record(
320            "publish.api",
321            S_PUBLISH,
322            Err("`config.json` has no `api`, so the registry takes no publishes over HTTP — run with `--read-only`".into()),
323        );
324        run.skip_rest("the registry has no publish API");
325        return;
326    };
327    let Some(token) = token else {
328        run.record(
329            "publish.token",
330            S_PUBLISH,
331            Err(format!(
332                "no publish token: set `{}`",
333                bynk_project::manifest::registry_token_var(&opts.name)
334            )),
335        );
336        run.skip_rest("no publish token");
337        return;
338    };
339    publishing(run, &mut reader, &api, &token);
340}
341
342/// `--read-only`: the lines of an existing package verify, its newest
343/// version's archive (that isn't withdrawn) is the signed tree, and its
344/// withdrawals are consistent.
345fn read_only(run: &mut Run<'_>, reader: &mut Client) {
346    let name = run.opts.name.as_str();
347    let Some(package) = run.opts.package.clone() else {
348        run.skip("read.lines", S_INDEX, "no `--package` given to read back");
349        run.skip("read.archive", S_ARCHIVES, "no `--package` given");
350        run.skip("read.revoked", S_DELEGATION, "no `--package` given");
351        run.skip("read.withdrawn", S_WITHDRAWALS, "no `--package` given");
352        return;
353    };
354    match reader.lines(name, &package) {
355        Ok(lines) if !lines.is_empty() => {
356            run.record(
357                "read.lines",
358                S_INDEX,
359                Ok(format!("{} line(s) of `{package}` verify", lines.len())),
360            );
361            // #2330: a withdrawn version has no archive to fetch.
362            match lines.iter().rev().find(|l| l.withdrawn.is_none()).cloned() {
363                Some(last) => {
364                    let home = run.work.join("home");
365                    let result = reader
366                        .fetch(name, &last, &home)
367                        .map(|_| format!("{} {} is the signed tree", package, last.version))
368                        .map_err(|e| e.to_string());
369                    run.record("read.archive", S_ARCHIVES, result);
370                }
371                None => run.skip("read.archive", S_ARCHIVES, "every version is withdrawn"),
372            }
373        }
374        Ok(_) => {
375            run.record(
376                "read.lines",
377                S_INDEX,
378                Err(format!("`{package}` has no lines")),
379            );
380            run.skip("read.archive", S_ARCHIVES, "no line to fetch");
381        }
382        Err(e) => {
383            run.record("read.lines", S_INDEX, Err(e.to_string()));
384            run.skip("read.archive", S_ARCHIVES, "the index didn't verify");
385        }
386    }
387    // read.revoked (#2316): judged on the index as served, independently of
388    // the client's own verdict, so a revoked signer fails this check by name.
389    let index = reader
390        .open(name)
391        .map(|o| o.index.clone())
392        .unwrap_or_default();
393    let revoked = match (&run.config, get_index(&transport::join(&index, &package))) {
394        (Some((config, signers)), Ok(bytes)) => {
395            let text = String::from_utf8_lossy(&bytes).into_owned();
396            let mut found = Vec::new();
397            for raw in text.lines().filter(|l| !l.trim().is_empty()) {
398                match IndexLine::parse(raw) {
399                    Ok(line) => {
400                        let payload = line.payload(&config.id);
401                        if let Some(k) = signers
402                            .revoked
403                            .iter()
404                            .find(|k| verify(k, &payload, &line.sig))
405                        {
406                            found.push(format!(
407                                "{} {} is signed by the revoked key {k}",
408                                line.name, line.version
409                            ));
410                        }
411                    }
412                    Err(e) => found.push(e),
413                }
414            }
415            if found.is_empty() {
416                Ok("no line is signed by a revoked key".to_string())
417            } else {
418                Err(found.join("; "))
419            }
420        }
421        (None, _) => Err("the served `config.json` couldn't be read".to_string()),
422        (_, Err(e)) => Err(e),
423    };
424    run.record("read.revoked", S_DELEGATION, revoked);
425    let withdrawn = withdrawals(reader, name, &index, &package);
426    run.record("read.withdrawn", S_WITHDRAWALS, withdrawn);
427}
428
429/// #2330 (F): `read.withdrawn` — every withdrawn line of `package`, as served,
430/// is also yanked, and its archive is no longer served (`404`) unless a live
431/// version of the package names the same tree. A tree shared with another
432/// package is beyond what a one-package check can see.
433fn withdrawals(
434    reader: &mut Client,
435    name: &str,
436    index: &str,
437    package: &str,
438) -> Result<String, String> {
439    let bytes = get_index(&transport::join(index, package))?;
440    let text = String::from_utf8_lossy(&bytes).into_owned();
441    let lines = text
442        .lines()
443        .filter(|l| !l.trim().is_empty())
444        .map(IndexLine::parse)
445        .collect::<Result<Vec<_>, _>>()?;
446    // A tree another, live version still names keeps its archive (`bynk
447    // registry withdraw` keeps a shared one), so it may still be served.
448    let live: std::collections::BTreeSet<&str> = lines
449        .iter()
450        .filter(|l| l.withdrawn.is_none())
451        .map(|l| l.checksum.as_str())
452        .collect();
453    let opened = reader.open(name).map_err(|e| e.to_string())?;
454    let mut problems = Vec::new();
455    let mut count = 0;
456    for line in lines.iter().filter(|l| l.withdrawn.is_some()) {
457        count += 1;
458        if !line.yanked {
459            problems.push(format!(
460                "{} {} is withdrawn but not yanked",
461                line.name, line.version
462            ));
463        }
464        if live.contains(line.checksum.as_str()) {
465            continue;
466        }
467        let hex = bynk_project::lock::checksum_hex(&line.checksum)
468            .ok_or_else(|| format!("{} {}'s checksum is malformed", line.name, line.version))?;
469        let url = transport::join(&opened.dl, &format!("sha256/{hex}"));
470        match opened.transport.get(&url) {
471            Ok(None) => {}
472            Ok(Some(_)) => problems.push(format!(
473                "{} {} is withdrawn, but its archive `{url}` is still served (and no live version of `{package}` names its tree)",
474                line.name, line.version
475            )),
476            Err(e) => problems.push(e.to_string()),
477        }
478    }
479    if !problems.is_empty() {
480        Err(problems.join("; "))
481    } else if count == 0 {
482        Ok(format!("`{package}` has no withdrawn versions"))
483    } else {
484        Ok(format!(
485            "{count} withdrawn version(s) of `{package}`, each yanked, its archive gone"
486        ))
487    }
488}
489
490/// A fixture package `name` at `version`, its commons returning `n`, with
491/// extra manifest text; packed. `(archive, checksum)`.
492fn fixture(
493    work: &Path,
494    name: &str,
495    version: &str,
496    n: u32,
497    extra: &str,
498) -> Result<(Vec<u8>, String), String> {
499    let dir = work.join(format!("{}-{version}-{n}", name.replace('/', "_")));
500    let _ = std::fs::remove_dir_all(&dir);
501    std::fs::create_dir_all(dir.join("src")).map_err(|e| e.to_string())?;
502    std::fs::write(
503        dir.join("bynk.toml"),
504        format!("[package]\nname = \"{name}\"\nversion = \"{version}\"\n{extra}"),
505    )
506    .map_err(|e| e.to_string())?;
507    std::fs::write(
508        dir.join("src/probe.bynk"),
509        format!("commons probe\n\nfn value() -> Int {{\n  {n}\n}}\n"),
510    )
511    .map_err(|e| e.to_string())?;
512    archive::pack(&dir).map_err(|e| format!("could not pack a fixture: {e}"))
513}
514
515/// A `refuse.*` check: its id, the API path, and the upload (or why it
516/// couldn't be built).
517type Refusal = (&'static str, String, Result<Vec<u8>, String>);
518
519/// The refusals seen, for the `errors.shape` check: `(check, status, content
520/// type, body, expected code)`.
521type Seen = Vec<(&'static str, u16, Option<String>, Vec<u8>, &'static str)>;
522
523fn publishing(run: &mut Run<'_>, reader: &mut Client, api: &str, token: &str) {
524    let opts = run.opts;
525    let name = opts.name.as_str();
526    let org = opts.org.clone();
527    let package = format!("{org}/conformance_{}_{}", utc_stamp(), hex4());
528    let url = |rest: &str| transport::join(api, rest);
529    let as_token = Auth::Bearer(token);
530    let mut seen: Seen = Vec::new();
531
532    let Ok((first, first_sum)) = fixture(&run.work, &package, "0.0.1", 1, "") else {
533        run.record(
534            "publish.created",
535            S_PUBLISH,
536            Err("could not build the fixture package".into()),
537        );
538        run.skip_rest("the fixture package couldn't be built");
539        return;
540    };
541
542    // publish.created
543    let created = transport::request(
544        "PUT",
545        &url(&format!("{package}/0.0.1")),
546        Body::Bytes(&first),
547        Auth::Bearer(token),
548    );
549    let created_line = match &created {
550        Ok((201, _, body)) => match parse_line(body) {
551            Ok(line) => {
552                run.report.published = Some(package.clone());
553                run.record(
554                    "publish.created",
555                    S_PUBLISH,
556                    Ok(format!("201 with the signed line for {package} 0.0.1")),
557                );
558                Some(line)
559            }
560            Err(e) => {
561                run.record(
562                    "publish.created",
563                    S_PUBLISH,
564                    Err(format!("201, but the body isn't an index line: {e}")),
565                );
566                None
567            }
568        },
569        Ok((status, _, body)) => {
570            run.record(
571                "publish.created",
572                S_PUBLISH,
573                Err(format!("expected 201, got {status}: {}", snippet(body))),
574            );
575            None
576        }
577        Err(e) => {
578            run.record("publish.created", S_PUBLISH, Err(e.clone()));
579            None
580        }
581    };
582    if created_line.is_none() {
583        // A 2xx may still have created it: name it, and yank it (best effort),
584        // as decision B promises.
585        if matches!(&created, Ok((status, _, _)) if (200..300).contains(status)) {
586            run.report.published = Some(package.clone());
587            let _ = transport::request(
588                "POST",
589                &url(&format!("{package}/0.0.1/yank")),
590                Body::None,
591                Auth::Bearer(token),
592            );
593        }
594        run.skip_rest("`publish.created` failed");
595        return;
596    }
597
598    // publish.read-back: through the verifying client.
599    reader.forget(name, &package);
600    let read_back = reader
601        .lines(name, &package)
602        .map_err(|e| e.to_string())
603        .and_then(|lines| {
604            let line = lines
605                .iter()
606                .find(|l| l.version == "0.0.1")
607                .cloned()
608                .ok_or("the index doesn't list 0.0.1")?;
609            if line.checksum != first_sum {
610                return Err(format!(
611                    "the line's checksum is {}, but the tree sent is {first_sum}",
612                    line.checksum
613                ));
614            }
615            reader
616                .fetch(name, &line, &run.work.join("home"))
617                .map_err(|e| e.to_string())?;
618            Ok("the line verifies, its checksum is the tree sent, and the archive matches".into())
619        });
620    run.record("publish.read-back", S_INDEX, read_back);
621
622    // publish.signer (#2316): signed by the chain or a valid delegate, and
623    // not by a revoked one.
624    let signer = match (&run.config, &created_line) {
625        (Some((config, signers)), Some(line)) => signed_by(config, signers, line),
626        _ => Err("the served `config.json` couldn't be read".to_string()),
627    };
628    run.record("publish.signer", S_DELEGATION, signer);
629    let index_url = transport::join(&reader_index(reader, name), &package);
630    let index_before = get_index(&index_url);
631
632    // publish.retry-same-tree (D10)
633    let retry = transport::request(
634        "PUT",
635        &url(&format!("{package}/0.0.1")),
636        Body::Bytes(&first),
637        Auth::Bearer(token),
638    );
639    let result = match retry {
640        Ok((200, _, body)) => match (parse_line(&body), &created_line) {
641            (Ok(line), Some(orig)) if line == *orig => Ok("200 with the existing line".to_string()),
642            (Ok(_), _) => Err("200, but not with the existing line".to_string()),
643            (Err(e), _) => Err(format!("200, but the body isn't an index line: {e}")),
644        },
645        Ok((status, _, body)) => Err(format!(
646            "expected 200 with the existing line, got {status}: {}",
647            snippet(&body)
648        )),
649        Err(e) => Err(e),
650    };
651    run.record("publish.retry-same-tree", S_PUBLISH, result);
652
653    // publish.conflict
654    let conflict = fixture(&run.work, &package, "0.0.1", 2, "").and_then(|(other, _)| {
655        transport::request(
656            "PUT",
657            &url(&format!("{package}/0.0.1")),
658            Body::Bytes(&other),
659            Auth::Bearer(token),
660        )
661    });
662    let after = get_index(&index_url);
663    let result = expect_refusal(
664        &mut seen,
665        "publish.conflict",
666        conflict,
667        409,
668        "version_exists",
669    )
670    .and_then(|d| match (&index_before, &after) {
671        (Ok(before), Ok(after)) if before == after => Ok(format!("{d}; the index is unchanged")),
672        (Ok(_), Ok(_)) => Err("409, but the index changed".to_string()),
673        (Err(e), _) | (_, Err(e)) => Err(format!(
674            "{d}, but the index couldn't be read to confirm it is unchanged: {e}"
675        )),
676    });
677    run.record("publish.conflict", S_PUBLISH, result);
678
679    // refuse.*: each a 400 that leaves no line behind.
680    let other_name = format!("{package}x");
681    let junk_traversal = {
682        let mut evil = b"bynk-tree-v1\n../escape.txt\x005\x00hello".to_vec();
683        evil.extend_from_slice(b"bynk.toml\x000\x00");
684        evil
685    };
686    let path_dep = fixture(
687        &run.work,
688        &package,
689        "0.0.7",
690        7,
691        &format!(
692            "\n[dependencies]\nhelper = {{ package = \"{org}/helper\", path = \"../helper\" }}\n"
693        ),
694    );
695    let refusals: Vec<Refusal> = vec![
696        (
697            "refuse.other-package",
698            format!("{other_name}/0.0.1"),
699            Ok(first.clone()),
700        ),
701        (
702            "refuse.other-version",
703            format!("{package}/0.0.4"),
704            Ok(first.clone()),
705        ),
706        (
707            "refuse.junk",
708            format!("{package}/0.0.5"),
709            Ok(b"not an archive".to_vec()),
710        ),
711        (
712            "refuse.traversal",
713            format!("{package}/0.0.6"),
714            Ok(junk_traversal),
715        ),
716        (
717            "refuse.path-dependency",
718            format!("{package}/0.0.7"),
719            path_dep.map(|(b, _)| b),
720        ),
721    ];
722    for (id, path, body) in refusals {
723        let result = match body {
724            Ok(body) => {
725                let sent =
726                    transport::request("PUT", &url(&path), Body::Bytes(&body), Auth::Bearer(token));
727                expect_refusal(&mut seen, id, sent, 400, "invalid_package")
728            }
729            Err(e) => Err(format!("could not build the upload: {e}")),
730        };
731        run.record(id, S_PUBLISH, result);
732    }
733    reader.forget(name, &package);
734    let stray = reader
735        .lines(name, &package)
736        .map(|lines| {
737            lines
738                .iter()
739                .filter(|l| l.version != "0.0.1")
740                .map(|l| l.version.clone())
741                .collect::<Vec<_>>()
742        })
743        .map_err(|e| e.to_string());
744    // The upload to another package's URL must not have created it.
745    let other = match reader.lines(name, &other_name) {
746        Ok(lines) if lines.is_empty() => Ok(()),
747        Ok(_) => Err(format!("`{other_name}` gained a line")),
748        Err(e) if e.code == super::UNAVAILABLE => Ok(()),
749        Err(e) => Err(format!("`{other_name}`'s index couldn't be checked: {e}")),
750    };
751    let clean = match (stray, other) {
752        (Ok(v), Ok(())) if v.is_empty() => {
753            Ok("no refused upload left a line, here or under another package".to_string())
754        }
755        (Ok(v), Ok(())) => Err(format!("refused uploads left lines: {}", v.join(", "))),
756        (Err(e), _) | (_, Err(e)) => Err(e),
757    };
758    run.record("refuse.clean", S_PUBLISH, clean);
759
760    // auth.*
761    let auth_url = url(&format!("{package}/0.0.8"));
762    let sent = transport::request("PUT", &auth_url, Body::Bytes(&first), Auth::Without);
763    let r = expect_refusal(&mut seen, "auth.missing", sent, 401, "unauthorised");
764    run.record("auth.missing", S_PUBLISH, r);
765    let bogus = format!("bynk_{}{}", hex4(), "0".repeat(60));
766    let sent = transport::request("PUT", &auth_url, Body::Bytes(&first), Auth::Bearer(&bogus));
767    let r = expect_refusal(&mut seen, "auth.unknown", sent, 401, "unauthorised");
768    run.record("auth.unknown", S_PUBLISH, r);
769    match &opts.narrow_token {
770        Some(Err(var)) => run.record(
771            "auth.scope",
772            S_PUBLISH,
773            Err(format!(
774                "`--narrow-token-env {var}` was given, but `{var}` isn't set"
775            )),
776        ),
777        Some(Ok(narrow)) => {
778            let sent =
779                transport::request("PUT", &auth_url, Body::Bytes(&first), Auth::Bearer(narrow));
780            let r = expect_refusal(&mut seen, "auth.scope", sent, 403, "forbidden");
781            run.record("auth.scope", S_PUBLISH, r);
782        }
783        None => run.skip(
784            "auth.scope",
785            S_PUBLISH,
786            "no narrow token given (`--narrow-token-env`)",
787        ),
788    }
789
790    // limits.too-large
791    let sent = transport::request(
792        "PUT",
793        &url(&format!("{package}/0.0.9")),
794        Body::Zeros(opts.max_upload + 1),
795        as_token,
796    );
797    let r = expect_refusal(&mut seen, "limits.too-large", sent, 413, "too_large");
798    run.record("limits.too-large", S_PUBLISH, r);
799
800    // consume: a fresh client and store select and admit the version.
801    let consumer_home = run.work.join("consumer");
802    let mut consumer = client(opts);
803    let consumed = consumer
804        .lines(name, &package)
805        .map_err(|e| e.to_string())
806        .and_then(|lines| {
807            let v = semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("our own version");
808            let line = super::select::choose(&lines, &["^0.0.1".to_string()], None, &v)
809                .map_err(|_| "no version could be chosen".to_string())?
810                .clone();
811            consumer
812                .fetch(name, &line, &consumer_home)
813                .map_err(|e| e.to_string())?;
814            Ok(format!(
815                "a fresh client chose {} and admitted its tree",
816                line.version
817            ))
818        });
819    run.record("consume.resolve", S_INDEX, consumed);
820
821    // yank.*
822    let yank = |verb: &str| {
823        transport::request(
824            "POST",
825            &url(&format!("{package}/0.0.1/{verb}")),
826            Body::None,
827            Auth::Bearer(token),
828        )
829    };
830    let mut flip = |run: &mut Run<'_>, id: &'static str, verb: &str, want: bool| {
831        let result = match yank(verb) {
832            Ok((200, _, _)) => index_shows_yank(reader, name, &package, want),
833            Ok((status, _, body)) => Err(format!("expected 200, got {status}: {}", snippet(&body))),
834            Err(e) => Err(e),
835        };
836        run.record(id, S_PUBLISH, result);
837    };
838    flip(run, "yank.yank", "yank", true);
839    flip(run, "yank.unyank", "unyank", false);
840    let sent = transport::request(
841        "POST",
842        &url(&format!("{package}/9.9.9/yank")),
843        Body::None,
844        Auth::Bearer(token),
845    );
846    let r = expect_refusal(&mut seen, "yank.missing", sent, 404, "not_found");
847    run.record("yank.missing", S_PUBLISH, r);
848
849    // errors.shape: every refusal is JSON `{error, message}` with its code.
850    let mut bad = Vec::new();
851    for (id, _status, kind, body, code) in &seen {
852        let json = kind
853            .as_deref()
854            .is_some_and(|k| k.starts_with("application/json"));
855        let parsed: Option<(String, bool)> = serde_json::from_slice::<serde_json::Value>(body)
856            .ok()
857            .and_then(|v| {
858                Some((
859                    v.get("error")?.as_str()?.to_owned(),
860                    v.get("message")?.is_string(),
861                ))
862            });
863        match parsed {
864            Some((c, true)) if json && c == *code => {}
865            Some((c, _)) if c != *code => {
866                bad.push(format!("{id}: `error` is `{c}`, expected `{code}`"))
867            }
868            _ => bad.push(format!("{id}: not a JSON `{{error, message}}` body")),
869        }
870    }
871    let result = if seen.is_empty() {
872        Err("no refusal was observed".to_string())
873    } else if bad.is_empty() {
874        Ok(format!(
875            "{} refusals, each JSON with the right `error`",
876            seen.len()
877        ))
878    } else {
879        Err(bad.join("; "))
880    };
881    run.record("errors.shape", S_PUBLISH, result);
882
883    // Leave the throwaway package yanked (decision B).
884    let _ = yank("yank");
885}
886
887/// Check a response is the refusal `status` with `code`, recording it for
888/// `errors.shape`.
889fn expect_refusal(
890    seen: &mut Seen,
891    id: &'static str,
892    sent: Result<(u16, Option<String>, Vec<u8>), String>,
893    status: u16,
894    code: &'static str,
895) -> Result<String, String> {
896    match sent {
897        Ok((got, kind, body)) if got == status => {
898            seen.push((id, got, kind, body, code));
899            Ok(format!("{status} `{code}`"))
900        }
901        Ok((got, _, body)) => Err(format!(
902            "expected {status} `{code}`, got {got}: {}",
903            snippet(&body)
904        )),
905        Err(e) => Err(e),
906    }
907}
908
909/// The served `config.json`, parsed.
910fn raw_config(index: &str) -> Result<Config, String> {
911    let bytes = get_index(&transport::join(index, "config.json"))?;
912    Config::parse(&bytes)
913}
914
915/// Which kind of key signed `line`: a chain key or a valid delegate; an error
916/// when it is a revoked delegate, or none of them.
917fn signed_by(config: &Config, signers: &Signers, line: &IndexLine) -> Result<String, String> {
918    let payload = line.payload(&config.id);
919    if let Some(k) = signers
920        .revoked
921        .iter()
922        .find(|k| verify(k, &payload, &line.sig))
923    {
924        return Err(format!(
925            "{} {} is signed by the revoked key {k}",
926            line.name, line.version
927        ));
928    }
929    match signers.keys.iter().find(|k| verify(k, &payload, &line.sig)) {
930        Some(k) if config.keys.iter().any(|c| &c.key == k) => {
931            Ok(format!("signed by the chain key {k}"))
932        }
933        Some(k) => Ok(format!("signed by the delegate {k}")),
934        None => Err(format!(
935            "{} {} is signed by no key the registry trusts",
936            line.name, line.version
937        )),
938    }
939}
940
941/// An index file's bytes, or why it couldn't be read (anything but `200`).
942fn get_index(url: &str) -> Result<Vec<u8>, String> {
943    match transport::request("GET", url, Body::None, Auth::Without)? {
944        (200, _, body) => Ok(body),
945        (status, _, _) => Err(format!("`{url}` answered {status}")),
946    }
947}
948
949fn parse_line(body: &[u8]) -> Result<IndexLine, String> {
950    let text = std::str::from_utf8(body).map_err(|_| "not UTF-8".to_string())?;
951    IndexLine::parse(text.trim())
952}
953
954fn reader_index(reader: &mut Client, name: &str) -> String {
955    reader
956        .open(name)
957        .map(|o| o.index.clone())
958        .unwrap_or_default()
959}
960
961fn snippet(body: &[u8]) -> String {
962    let text = String::from_utf8_lossy(body);
963    let text = text.trim();
964    if text.is_empty() {
965        "(empty body)".to_string()
966    } else if text.chars().count() > 160 {
967        format!("{}…", text.chars().take(160).collect::<String>())
968    } else {
969        text.to_string()
970    }
971}
972
973fn scratch_dir() -> PathBuf {
974    loop {
975        let dir = std::env::temp_dir().join(format!("bynk-conformance-{}{}", hex4(), hex4()));
976        if std::fs::create_dir(&dir).is_ok() {
977            return dir;
978        }
979    }
980}
981
982fn hex4() -> String {
983    let mut raw = [0u8; 2];
984    let _ = ring::rand::SecureRandom::fill(&ring::rand::SystemRandom::new(), &mut raw);
985    format!("{:02x}{:02x}", raw[0], raw[1])
986}
987
988/// The current UTC time as `yyyymmddhhmmss`.
989/// After a `200` yank or un-yank: whether `package`'s index comes to show
990/// `0.0.1` with `yanked = want`. A cached index may lag the change (caching is
991/// the operator's choice), so read until it shows it or the cache's longest
992/// life has passed.
993fn index_shows_yank(
994    reader: &mut Client,
995    name: &str,
996    package: &str,
997    want: bool,
998) -> Result<String, String> {
999    let started = Instant::now();
1000    loop {
1001        reader.forget(name, package);
1002        let lines = reader.lines(name, package).map_err(|e| e.to_string())?;
1003        let Some(line) = lines.iter().find(|l| l.version == "0.0.1") else {
1004            return Err("the line disappeared".to_string());
1005        };
1006        let waited = started.elapsed();
1007        if line.yanked == want {
1008            return Ok(if waited < YANK_POLL {
1009                format!("200, and the index shows yanked = {want}")
1010            } else {
1011                format!(
1012                    "200, and the index shows yanked = {want} after {}s",
1013                    waited.as_secs()
1014                )
1015            });
1016        }
1017        if waited >= YANK_SETTLE {
1018            return Err(format!(
1019                "200, but the index doesn't show yanked = {want} after {}s",
1020                waited.as_secs()
1021            ));
1022        }
1023        std::thread::sleep(YANK_POLL);
1024    }
1025}
1026
1027fn utc_stamp() -> String {
1028    let secs = std::time::SystemTime::now()
1029        .duration_since(std::time::UNIX_EPOCH)
1030        .map_or(0, |d| d.as_secs());
1031    let (days, rem) = (secs / 86_400, secs % 86_400);
1032    // Howard Hinnant's civil-from-days.
1033    let z = days as i64 + 719_468;
1034    let era = z.div_euclid(146_097);
1035    let doe = z.rem_euclid(146_097);
1036    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
1037    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
1038    let mp = (5 * doy + 2) / 153;
1039    let d = doy - (153 * mp + 2) / 5 + 1;
1040    let m = if mp < 10 { mp + 3 } else { mp - 9 };
1041    let y = yoe + era * 400 + i64::from(m <= 2);
1042    format!(
1043        "{y:04}{m:02}{d:02}{:02}{:02}{:02}",
1044        rem / 3_600,
1045        rem % 3_600 / 60,
1046        rem % 60
1047    )
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use super::*;
1053
1054    #[test]
1055    fn the_stamp_is_fourteen_digits() {
1056        let s = utc_stamp();
1057        assert_eq!(s.len(), 14, "{s}");
1058        assert!(s.starts_with("20"), "{s}");
1059        assert!(s.chars().all(|c| c.is_ascii_digit()));
1060    }
1061}