Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/holger

server/lib/src/pull_intake/door.rs

//! **What the production repository's read door answers for a remote source.**
//! Plain values ([`DoorReply`]); `exposed::http` only turns them into responses.
//!
//! | asked for | AVAILABLE | being pulled | waiting for a person | refused |
//! |---|---|---|---|---|
//! | pip project page | the PEP 503/691 page over the AVAILABLE set | `503` + `Retry-After` | `404`, the state named | `404`, the reason |
//! | pip file | the sealed bytes | `503` + `Retry-After` | `404` | `404` |
//! | OCI manifest | the sealed manifest, `Docker-Content-Digest` | `503` `UNAVAILABLE` + `Retry-After` | `404` `MANIFEST_UNKNOWN` | `403` `DENIED` |
//! | OCI blob | the sealed blob | — | `404` `BLOB_UNKNOWN` | `404` `BLOB_UNKNOWN` |
//! | npm packument | npm's document over the AVAILABLE versions | `503` + `Retry-After`, `{"error"}` | `404` `{"error"}`, the state named | `403` `{"error"}`, the reason |
//! | npm tarball | the sealed bytes | `503` + `Retry-After` | `404` | `403` |
//! | Maven POM / JAR / other file | the sealed bytes | `503` + `Retry-After` | `404` | `403` |
//! | Maven checksum (`.sha1`, `.sha256`, `.sha512`, `.md5`) | of the sealed bytes | as its file | as its file | as its file |
//! | `maven-metadata.xml` | the AVAILABLE versions only | `503` + `Retry-After` | `404` | `403` |
//! | cargo `config.json` | `dl` below the source; `auth-required` where reads are gated | — | — | — |
//! | cargo index file | the AVAILABLE versions' lines, `cksum` the sealed sha256 | `503` + `Retry-After` | `404` | `403` |
//! | `.crate` | the sealed bytes | `503` + `Retry-After` | `404` | `403` |
//! | APK `<arch>/APKINDEX.tar.gz` | the AVAILABLE packages' stanzas, signed with Holger's key | — | — | — |
//! | APK `<arch>/-/pull/<name>` | `200`, the AVAILABLE versions named | `503` + `Retry-After` | `404`, the state named | `403`, the reason |
//! | APK `<arch>/<name>-<version>.apk` | the sealed bytes | `503` + `Retry-After` | `404` | `403` |
//! | APK `-/apk-key-name`, `<that name>` | Holger's key's name; its PEM, for `/etc/apk/keys/` | — | — | — |
//! | Go `<module>/@v/<v>.info`, `.mod`, `.zip` ([`super::go`]) | the AVAILABLE version's files | `503` + `Retry-After` | `404`, the state named | `403`, the reason |
//! | Go `<module>/@v/list`, `@latest` | the AVAILABLE versions | — | — | — |
//!
//! A serve-only source (no `url`; a downstream's view, H3) answers every miss with
//! `holger-downstream-4`: its upstream has not sent it, and it is never fetched here.
//!
//! npm retries a 5xx (`fetch-retries`, two by default, `fetch-retry-mintimeout` 10 s);
//! Maven depends on its version (measured with real Maven, HOL-DOCFIND i, 2026-11-01):
//! 3.9.5 and later (Maven Resolver's HTTP transport) retry a `503` three times and honour
//! `Retry-After`, then fail; 3.8.x and 3.9.0 to 3.9.4 do not retry a `503` at all. So a
//! Maven source also holds its request (`wait_secs`, 30 s by default); cargo counts a 5xx as a spurious network error and retries it
//! (`net.retry`, three by default).
//!
//! pip retries a 503 (urllib3's `Retry`, five times, honouring `Retry-After`)
//! and then reports the page as unreachable; podman's `--retry` (3 by default)
//! retries `UNAVAILABLE` and stops on `MANIFEST_UNKNOWN` and `DENIED`; docker
//! reports the registry's error at once.

use super::{oci, Ask, RemoteKind};
use crate::promote::intake::IntakeChain;
use traits::ArtifactId;

/// **The refusal, on one line** (lane HOL-310-CHECK): the header a refused file's answer
/// carries. The HTTP door also puts it in the status line's reason phrase ("403 Refused by
/// Holger: ..."), the one part of the answer pip prints when a download fails.
pub const REFUSAL_HEADER: &str = "X-Holger-Refusal";

/// `s` as one header-safe line: visible ASCII and spaces only (anything else is `?`), at most
/// `max` bytes.
pub fn one_line(s: &str, max: usize) -> String {
    let mut out: String = s
        .chars()
        .map(|c| {
            if c == ' ' || c.is_ascii_graphic() {
                c
            } else {
                '?'
            }
        })
        .collect();
    out.truncate(max);
    out
}

/// One reply of the read door.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DoorReply {
    pub status: u16,
    pub headers: Vec<(&'static str, String)>,
    pub body: Vec<u8>,
    /// The audit note.
    pub note: String,
}

impl DoorReply {
    fn text(status: u16, msg: String) -> Self {
        Self {
            status,
            headers: vec![("Content-Type", "text/plain; charset=utf-8".into())],
            body: msg.clone().into_bytes(),
            note: msg,
        }
    }
    fn bytes(ctype: &str, body: Vec<u8>, note: &str) -> Self {
        Self {
            status: 200,
            headers: vec![
                ("Content-Type", ctype.into()),
                ("X-Holger-Intake-State", "AVAILABLE".into()),
            ],
            body,
            note: note.into(),
        }
    }
    fn with(mut self, k: &'static str, v: String) -> Self {
        self.headers.push((k, v));
        self
    }
}

/// **The project page with the upstream's other files** (lane HOL-FIELD-TEST P2): the AVAILABLE
/// page (or an empty one) and, for each [`super::HeldFile`], an entry yanked with its reason
/// (PEP 592; PEP 691 `"yanked": "<reason>"`, PEP 503 `data-yanked`) whose link is the source's
/// file door, `../../<source>/<file>` beside the AVAILABLE files' own.
fn with_held(
    page: Option<(&'static str, Vec<u8>)>,
    json: bool,
    project: &str,
    held: &[super::HeldFile],
) -> (&'static str, Vec<u8>) {
    if json {
        let mut doc = page
            .and_then(|(_, b)| serde_json::from_slice::<serde_json::Value>(&b).ok())
            .unwrap_or_else(|| {
                serde_json::json!({ "meta": { "api-version": "1.0" }, "name": project, "files": [] })
            });
        if let Some(files) = doc.get_mut("files").and_then(|f| f.as_array_mut()) {
            for h in held {
                files.push(serde_json::json!({
                    "filename": h.filename,
                    "url": format!("../../{}/{}", h.source, h.filename),
                    "hashes": { "sha256": h.sha256 },
                    "yanked": h.reason,
                }));
            }
        }
        return (
            "application/vnd.pypi.simple.v1+json",
            doc.to_string().into_bytes(),
        );
    }
    let esc = |s: &str| {
        s.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
    };
    let mut body = match page {
        Some((_, b)) => String::from_utf8_lossy(&b).into_owned(),
        None => format!(
            "<!DOCTYPE html>\n<html><head><meta name=\"pypi:repository-version\" content=\"1.0\"><title>Links for {p}</title></head><body>\n<h1>Links for {p}</h1>\n</body></html>\n",
            p = esc(project)
        ),
    };
    let links: String = held
        .iter()
        .map(|h| {
            format!(
                "<a href=\"../../{}/{}#sha256={}\" data-yanked=\"{}\">{}</a><br/>\n",
                esc(&h.source),
                esc(&h.filename),
                esc(&h.sha256),
                esc(&h.reason),
                esc(&h.filename)
            )
        })
        .collect();
    match body.rfind("</body>") {
        Some(at) => body.insert_str(at, &links),
        None => body.push_str(&links),
    }
    ("text/html; charset=utf-8", body.into_bytes())
}

/// `refused`: the status of a refusal: 403 for a file (lane HOL-310-CHECK; it was 404), 404 for
/// a project page, which pip reads as "no such project" and reports with the reason.
fn pip_not_yet(ask: Ask, what: &str, refused: u16) -> DoorReply {
    match ask {
        Ask::Ready => DoorReply::text(404, format!("{what}: not AVAILABLE")),
        Ask::Fetching { retry_after_secs, job } => DoorReply::text(
            503,
            format!("{what}: not yet AVAILABLE; it is being pulled into the intake chain (job {job}); retry in {retry_after_secs} s"),
        )
        .with("Retry-After", retry_after_secs.to_string()),
        Ask::Held { detail, .. } => DoorReply::text(404, format!("{what}: not yet AVAILABLE; {detail}")),
        Ask::Refused { why } => DoorReply::text(refused, format!("{what}: refused by the intake chain and never served: {why}"))
            .with(REFUSAL_HEADER, one_line(&why, 900)),
        Ask::Unknown { why } => DoorReply::text(404, format!("{what}: {why}")),
    }
}

/// **A production `simple/<project>/` page** while the chain has a Python
/// source. `None` for any other path (the root page stays the chain's own).
pub fn pip_index(chain: &IntakeChain, sub: &str, json: bool) -> Option<DoorReply> {
    let pull = chain.pull()?;
    pull.python_sources().next()?;
    let clean = sub.split('?').next().unwrap_or(sub);
    let clean = clean
        .trim_end_matches('/')
        .strip_suffix("/json")
        .unwrap_or(clean.trim_end_matches('/'));
    let project = clean
        .trim_start_matches('/')
        .strip_prefix("simple/")?
        .trim_matches('/');
    if project.is_empty() || project.contains('/') {
        return None;
    }
    let ask = pull.ask_project(chain, project);
    let held = pull.pip_held(chain, project);
    let page = chain.simple_index_as(sub, json);
    if !held.is_empty() {
        let name = crate::promote::intake::normalize_project(project);
        let (ctype, body) = with_held(page.map(|(c, b)| (c, b.to_vec())), json, &name, &held);
        return Some(DoorReply {
            status: 200,
            headers: vec![("Content-Type", ctype.into())],
            body,
            note: "intake: simple index over the AVAILABLE set, the upstream's other files yanked"
                .into(),
        });
    }
    match page {
        Some((ctype, body)) => Some(DoorReply {
            status: 200,
            headers: vec![("Content-Type", ctype.into())],
            body: body.to_vec(),
            note: "intake: simple index over the AVAILABLE set".into(),
        }),
        None => Some(pip_not_yet(ask, &format!("project '{project}'"), 404)),
    }
}

/// **A production file that is not AVAILABLE**: when it names a Python source
/// (`<source>/<file>`), pull it, or say where it stands.
pub fn pip_file(chain: &IntakeChain, id: &ArtifactId) -> Option<DoorReply> {
    let pull = chain.pull()?;
    if id.namespace.is_some() || !id.version.is_empty() {
        return None;
    }
    let (source, file) = id.name.trim_start_matches('/').split_once('/')?;
    pull.source(source)
        .filter(|s| s.cfg.kind == RemoteKind::Python)?;
    let ask = pull.ask_file(chain, source, file);
    if ask == Ask::Ready {
        if let Ok(Some(bytes)) = chain.serve(id) {
            return Some(DoorReply::bytes(
                "application/octet-stream",
                bytes,
                "intake: AVAILABLE (pulled through), served from the sealed store",
            ));
        }
    }
    Some(pip_not_yet(ask, file, 403))
}

fn registry_error(status: u16, code: &str, message: String) -> DoorReply {
    let body =
        serde_json::json!({ "errors": [ { "code": code, "message": message, "detail": {} } ] })
            .to_string()
            .into_bytes();
    DoorReply {
        status,
        headers: vec![
            ("Content-Type", "application/json".into()),
            ("Docker-Distribution-API-Version", "registry/2.0".into()),
        ],
        body,
        note: format!("{code}: {message}"),
    }
}

/// **What an AVAILABLE image carries beside itself** (HOL-REFERRERS): its attached
/// manifests and blobs are in its layouts; Holger's own evidence about each image
/// digest, and the merged `.att` manifests, are built here from `attest`.
struct Attached {
    layouts: Vec<std::sync::Arc<oci::Layout>>,
    evidence: crate::referrers::Evidence,
    /// `sha256-<hex>.att` → the manifest to serve (the image's own, with Holger's layers).
    att: std::collections::BTreeMap<String, Vec<u8>>,
}

impl Attached {
    fn of(
        chain: &IntakeChain,
        source: &str,
        image: &str,
        attest: Option<&crate::attest::AttestStore>,
    ) -> Option<Self> {
        let pull = chain.pull()?;
        let layouts = pull.oci_layouts(chain, source, image);
        let mut evidence = crate::referrers::Evidence::default();
        let mut att = std::collections::BTreeMap::new();
        for l in &layouts {
            for d in &l.images {
                let Some((mt, m)) = l.manifest(d) else {
                    continue;
                };
                let mut e =
                    crate::referrers::Evidence::of(attest, &crate::referrers::Subject::of(mt, m));
                let tag = format!("sha256-{}.att", d.trim_start_matches("sha256:"));
                let own = l
                    .attached_tags
                    .get(&tag)
                    .and_then(|ad| l.manifest(ad))
                    .map(|(_, b)| b.to_vec());
                if let Some(m) = e.att_manifest(own.as_deref()) {
                    att.insert(tag, m);
                }
                evidence.absorb(e);
            }
        }
        Some(Self {
            layouts,
            evidence,
            att,
        })
    }

    /// The image's own manifest by digest, wherever it is AVAILABLE: `(media type, bytes)`.
    fn subject(&self, digest: &str) -> Option<(String, Vec<u8>)> {
        self.layouts.iter().find_map(|l| {
            l.manifest(digest)
                .map(|(mt, b)| (mt.to_string(), b.to_vec()))
        })
    }

    /// An attached tag (`sha256-<hex>.sig|.att|.sbom`).
    fn tag(&self, tag: &str) -> Option<(String, Vec<u8>)> {
        if let Some(m) = self.att.get(tag) {
            return Some((crate::referrers::MANIFEST_MEDIA_TYPE.to_string(), m.clone()));
        }
        self.layouts.iter().find_map(|l| {
            l.attached_tags
                .get(tag)
                .and_then(|d| l.manifest(d))
                .map(|(mt, b)| (mt.to_string(), b.to_vec()))
        })
    }

    /// One of Holger's evidence objects (a referrer manifest, a bundle, a merged `.att`).
    fn object(&self, digest: &str) -> Option<(String, Vec<u8>)> {
        self.evidence
            .object(digest)
            .map(|(mt, b)| (mt.to_string(), b.to_vec()))
    }

    /// The referrers of `digest`: what came with the image, then Holger's evidence.
    fn referrers(&self, digest: &str) -> Vec<serde_json::Value> {
        let own = self
            .layouts
            .iter()
            .flat_map(|l| l.referrers.get(digest).cloned().unwrap_or_default());
        let holger = self.evidence.referrers.iter().filter(|r| {
            self.object(r.get("digest").and_then(|d| d.as_str()).unwrap_or(""))
                .and_then(|(_, m)| serde_json::from_slice::<serde_json::Value>(&m).ok())
                .is_some_and(|m| {
                    m.pointer("/subject/digest").and_then(|d| d.as_str()) == Some(digest)
                })
        });
        own.chain(holger.cloned()).collect()
    }
}

fn manifest_reply(mt: String, body: Vec<u8>, note: String) -> DoorReply {
    let digest = crate::referrers::sha256_digest(&body);
    DoorReply {
        status: 200,
        headers: vec![
            ("Content-Type", mt),
            ("Docker-Content-Digest", digest),
            ("Docker-Distribution-API-Version", "registry/2.0".into()),
            ("X-Holger-Intake-State", "AVAILABLE".into()),
        ],
        body,
        note,
    }
}

/// **A registry read below `/v2/<production>/`** whose first path segment is
/// an OCI source. `rest` is the path below the repository (with its query);
/// `attest` the store Holger's own evidence is read from.
pub fn oci(
    chain: &IntakeChain,
    rest: &str,
    attest: Option<&crate::attest::AttestStore>,
) -> Option<DoorReply> {
    let pull = chain.pull()?;
    let (source, _) = rest.trim_start_matches('/').split_once('/')?;
    pull.source(source)
        .filter(|s| s.cfg.kind == RemoteKind::Oci)?;
    let Some(p) = oci::parse_path(rest) else {
        return Some(registry_error(
            404,
            "NAME_UNKNOWN",
            format!("'{rest}' is not a registry path Holger serves"),
        ));
    };
    let strip = |name: &str| name.strip_prefix(&format!("{source}/")).map(str::to_string);
    Some(match p {
        // ★ The attached artifacts and Holger's evidence (HOL-REFERRERS): served from
        // the AVAILABLE layouts and the attestation store, never pulled on their own.
        oci::OciPath::Referrers {
            name,
            digest,
            artifact_type,
        } => {
            let Some(image) = strip(&name) else {
                return Some(registry_error(404, "NAME_UNKNOWN", name));
            };
            let found = Attached::of(chain, source, &image, attest)
                .map(|a| a.referrers(&digest))
                .unwrap_or_default();
            let n = found.len();
            let (body, filtered) = crate::referrers::index(found, artifact_type.as_deref());
            let mut r = DoorReply {
                status: 200,
                headers: vec![("Content-Type", crate::referrers::INDEX_MEDIA_TYPE.into()), ("Docker-Distribution-API-Version", "registry/2.0".into())],
                body,
                note: format!("intake: the referrers of {image}@{digest} ({n} before any filter), from the AVAILABLE layouts and Holger's evidence"),
            };
            if filtered {
                r = r.with("OCI-Filters-Applied", "artifactType".into());
            }
            r
        }
        oci::OciPath::Manifest { name, reference }
            if crate::referrers::cosign_tag(&reference).is_some() =>
        {
            let Some(image) = strip(&name) else {
                return Some(registry_error(404, "NAME_UNKNOWN", name));
            };
            match Attached::of(chain, source, &image, attest).and_then(|a| a.tag(&reference)) {
                Some((mt, body)) => manifest_reply(
                    mt,
                    body,
                    format!("intake: {image}:{reference}, attached to an AVAILABLE image"),
                ),
                None => registry_error(
                    404,
                    "MANIFEST_UNKNOWN",
                    format!("{image}:{reference}: no AVAILABLE image carries it"),
                ),
            }
        }
        oci::OciPath::Manifest { name, reference }
            if oci::is_digest(&reference)
                && strip(&name)
                    .and_then(|i| Attached::of(chain, source, &i, attest))
                    .is_some_and(|a| {
                        a.object(&reference).is_some() && a.subject(&reference).is_none()
                    }) =>
        {
            let image = strip(&name).unwrap_or_default();
            let (mt, body) = Attached::of(chain, source, &image, attest)
                .and_then(|a| a.object(&reference))
                .unwrap_or_default();
            manifest_reply(
                mt,
                body,
                format!("intake: Holger's evidence about {image}, {reference}"),
            )
        }
        oci::OciPath::Manifest { name, reference } => {
            let Some(image) = strip(&name) else {
                return Some(registry_error(404, "NAME_UNKNOWN", name));
            };
            match pull.oci_manifest(chain, source, &image, &reference) {
                Ok((mt, body, digest)) => DoorReply {
                    status: 200,
                    headers: vec![
                        ("Content-Type", mt),
                        ("Docker-Content-Digest", digest),
                        ("Docker-Distribution-API-Version", "registry/2.0".into()),
                        ("X-Holger-Intake-State", "AVAILABLE".into()),
                    ],
                    body,
                    note: format!("intake: {image}:{reference} AVAILABLE (pulled through from '{source}'), served from the sealed store"),
                },
                Err(Ask::Fetching { retry_after_secs, job }) => registry_error(
                    503,
                    "UNAVAILABLE",
                    format!("{image}:{reference} is not yet AVAILABLE: Holger is pulling it from '{source}' into its intake chain (job {job}); retry in {retry_after_secs} s"),
                )
                .with("Retry-After", retry_after_secs.to_string()),
                Err(Ask::Held { detail, .. }) => registry_error(404, "MANIFEST_UNKNOWN", format!("{image}:{reference} is not yet AVAILABLE: {detail}")),
                Err(Ask::Refused { why }) => registry_error(403, "DENIED", format!("{image}:{reference} was refused by Holger's intake chain and is never served: {why}")),
                Err(Ask::Unknown { why }) => registry_error(404, "MANIFEST_UNKNOWN", why),
                Err(Ask::Ready) => registry_error(404, "MANIFEST_UNKNOWN", format!("{image}:{reference}")),
            }
        }
        oci::OciPath::Blob { name, digest } => {
            let Some(image) = strip(&name) else {
                return Some(registry_error(404, "NAME_UNKNOWN", name));
            };
            let blob = pull.oci_blob(chain, source, &image, &digest).or_else(|| {
                Attached::of(chain, source, &image, attest)
                    .and_then(|a| a.object(&digest))
                    .map(|(_, b)| b)
            });
            match blob {
                Some(b) => DoorReply {
                    status: 200,
                    headers: vec![
                        ("Content-Type", "application/octet-stream".into()),
                        ("Docker-Content-Digest", digest),
                        ("X-Holger-Intake-State", "AVAILABLE".into()),
                    ],
                    body: b,
                    note: format!(
                        "intake: a blob of {image} (AVAILABLE), served from the sealed store"
                    ),
                },
                None => registry_error(
                    404,
                    "BLOB_UNKNOWN",
                    format!("{digest} is in no AVAILABLE image of {image}"),
                ),
            }
        }
        oci::OciPath::Tags { name } => {
            let Some(image) = strip(&name) else {
                return Some(registry_error(404, "NAME_UNKNOWN", name));
            };
            let tags = pull.oci_tags(chain, source, &image);
            let body = serde_json::json!({ "name": name, "tags": tags })
                .to_string()
                .into_bytes();
            DoorReply {
                status: 200,
                headers: vec![("Content-Type", "application/json".into())],
                body,
                note: format!("intake: the AVAILABLE tags of {image}"),
            }
        }
    })
}

fn npm_error(status: u16, msg: String) -> DoorReply {
    DoorReply {
        status,
        headers: vec![("Content-Type", "application/json".into())],
        body: serde_json::json!({ "error": msg }).to_string().into_bytes(),
        note: msg,
    }
}

/// The "not yet" of npm, Maven and cargo: `503` + `Retry-After` while it is
/// pulled, `404` while it waits for a person (the state named), `403` once the
/// chain refused it.
fn not_yet(ask: Ask, what: &str, json: bool) -> DoorReply {
    let reply = |status: u16, msg: String| {
        if json {
            npm_error(status, msg)
        } else {
            DoorReply::text(status, msg)
        }
    };
    match ask {
        Ask::Ready => reply(404, format!("{what}: not AVAILABLE")),
        Ask::Fetching { retry_after_secs, job } => reply(
            503,
            format!("{what}: not yet AVAILABLE; Holger is pulling it into its intake chain (job {job}); retry in {retry_after_secs} s"),
        )
        .with("Retry-After", retry_after_secs.to_string()),
        Ask::Held { detail, .. } => reply(404, format!("{what}: not yet AVAILABLE; {detail}")),
        Ask::Refused { why } => reply(403, format!("{what}: refused by Holger's intake chain and never served: {why}")),
        Ask::Unknown { why } => reply(404, format!("{what}: {why}")),
    }
}

/// **A production read below an npm, Maven or crates source**
/// (`/<production>/<source>/…`). `sub` is the path below the repository, `base`
/// the public URL of the repository (`https://holger.example/production`).
/// `None` when the first segment names no such source.
/// `gated`: reads of the production repository need a credential (a crates source's
/// `config.json` then says `auth-required`, or cargo never sends its token past it).
pub fn remote(chain: &IntakeChain, sub: &str, base: &str, gated: bool) -> Option<DoorReply> {
    let pull = chain.pull()?;
    let sub = sub.split('?').next().unwrap_or(sub).trim_start_matches('/');
    let (source, rest) = sub.split_once('/').unwrap_or((sub, ""));
    let kind = pull.source(source)?.cfg.kind;
    let source_base = format!("{}/{source}", base.trim_end_matches('/'));
    Some(match kind {
        RemoteKind::Npm => {
            use crate::promote::npm::Route;
            match crate::promote::npm::route(&format!("/{rest}")) {
                Route::Packument(package) => match pull.npm_packument(chain, source, &package, &source_base) {
                    Ok(body) => DoorReply::bytes("application/json", body, &format!("intake: the packument of {package} over the AVAILABLE versions (pulled through from '{source}')")),
                    Err(ask) => not_yet(ask, &format!("package '{package}'"), true),
                },
                Route::Tarball { package, file } => match pull.npm_tarball(chain, source, &package, &file) {
                    Ok(body) => DoorReply::bytes("application/octet-stream", body, "intake: AVAILABLE (pulled through), served from the sealed store"),
                    Err(ask) => not_yet(ask, &file, true),
                },
                _ => npm_error(404, format!("'{rest}' is not an npm read Holger serves for '{source}'")),
            }
        }
        RemoteKind::Maven => match super::maven::parse(rest) {
            Some(p) => match pull.maven_read(chain, source, &p) {
                Ok((ctype, body)) => DoorReply::bytes(
                    ctype,
                    body,
                    &format!(
                        "intake: {} (pulled through from '{source}'), from the sealed store",
                        p.path()
                    ),
                ),
                Err(ask) => not_yet(ask, &p.path(), false),
            },
            None => DoorReply::text(
                404,
                format!("'{rest}' is not a Maven path Holger serves for '{source}'"),
            ),
        },
        RemoteKind::Crates => {
            if rest == "config.json" {
                return Some(DoorReply::bytes(
                    "application/json",
                    super::crates::config_json(base, source, gated),
                    "intake: the crates source's config.json",
                ));
            }
            if let Some(name) = super::crates::name_of_index_path(rest) {
                return Some(match pull.crate_index(chain, source, &name) {
                    Ok(body) => DoorReply::bytes(
                        "text/plain",
                        body,
                        &format!("intake: the index of {name} over the AVAILABLE versions"),
                    ),
                    Err(ask) => not_yet(ask, &format!("crate '{name}'"), false),
                });
            }
            let id = ArtifactId {
                namespace: None,
                name: format!("{source}/{}", rest.to_ascii_lowercase()),
                version: String::new(),
            };
            match super::crates::coords_of(source, &id) {
                Some((name, version)) => match pull.crate_file(chain, source, &name, &version) {
                    Ok(body) => DoorReply::bytes(
                        "application/x-tar",
                        body,
                        "intake: AVAILABLE (pulled through), served from the sealed store",
                    ),
                    Err(ask) => not_yet(ask, &format!("{name}-{version}.crate"), false),
                },
                None => DoorReply::text(
                    404,
                    format!("'{rest}' is not a cargo index read Holger serves for '{source}'"),
                ),
            }
        }
        RemoteKind::Apk => {
            let signer = || pull.apk_signer();
            if rest == "-/apk-key-name" {
                return Some(match signer() {
                    Ok(k) => DoorReply::bytes(
                        "text/plain",
                        format!("{}\n", k.name).into_bytes(),
                        "intake: the name of Holger's apk signing key",
                    ),
                    Err(e) => DoorReply::text(500, format!("{e:#}")),
                });
            }
            if !rest.contains('/') && rest.ends_with(".rsa.pub") {
                return Some(match signer() {
                    Ok(k) if k.name == rest => DoorReply::bytes(
                        "application/x-pem-file",
                        k.public_pem.clone().into_bytes(),
                        "intake: Holger's apk signing key",
                    ),
                    Ok(_) => DoorReply::text(
                        404,
                        format!("'{rest}' is not this Holger's apk key (see -/apk-key-name)"),
                    ),
                    Err(e) => DoorReply::text(500, format!("{e:#}")),
                });
            }
            let (arch, file) = rest.split_once('/').unwrap_or((rest, ""));
            if file == "APKINDEX.tar.gz" {
                return Some(match pull.apk_index(chain, source, arch) {
                    Ok(body) => DoorReply::bytes("application/gzip", body, &format!("intake: the {arch} APK index over the AVAILABLE packages of '{source}', signed by Holger")),
                    Err(ask) => not_yet(ask, &format!("{arch}/APKINDEX.tar.gz"), false),
                });
            }
            if let Some(name) = file.strip_prefix("-/pull/") {
                return Some(match pull.apk_pull(chain, source, arch, name) {
                    Ok(line) => DoorReply::bytes(
                        "text/plain",
                        line.into_bytes(),
                        &format!("intake: {name} AVAILABLE (pulled through from '{source}')"),
                    ),
                    Err(ask) => not_yet(ask, &format!("package '{name}'"), false),
                });
            }
            if super::apk::parse_file(file).is_some() && !file.contains('/') {
                return Some(match pull.apk_file(chain, source, arch, file) {
                    Ok(body) => DoorReply::bytes(
                        "application/octet-stream",
                        body,
                        "intake: AVAILABLE (pulled through), served from the sealed store",
                    ),
                    Err(ask) => not_yet(ask, file, false),
                });
            }
            DoorReply::text(
                404,
                format!("'{rest}' is not an APK read Holger serves for '{source}'"),
            )
        }
        RemoteKind::Go => match pull.go_read(chain, source, rest) {
            Ok(Some((ctype, body))) => DoorReply::bytes(
                ctype,
                body,
                &format!("intake: Go {rest} over the AVAILABLE set of '{source}'"),
            ),
            Ok(None) => DoorReply::text(
                404,
                format!("'{rest}' is not a Go module read this Holger has for '{source}'"),
            ),
            Err(ask) => not_yet(ask, rest, false),
        },
        RemoteKind::Python | RemoteKind::Oci => return None,
    })
}