~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
597 lines · 20.2 KB Raw History
//! Docker/OCI registry source for `pkg:docker/` and `pkg:oci/` purls.
//!
//! The source is Docker Hub only. Versions are the registry tag list,
//! paginated through the RFC 8288 `Link` header and normalized through the
//! release version grammar. Tags that name a moving channel (`latest`,
//! `stable`, `edge`, `nightly`) are reported through
//! [`ReleaseSource::project_meta`] as `channelTags` instead of the version
//! catalog.
//!
//! Artifacts are the immutable manifest URL. The `Docker-Content-Digest`
//! response header is the authoritative digest, the `Content-Length` header or
//! the manifest entry sizes supply the size, and the `sha256:` digest is the
//! artifact hash. Statuses only report tag mutability: when a tag resolves to a
//! different digest than the cached one, the tag is surfaced as `deprecated`
//! with `kind: mutable_tag`. Nothing is inferred about security.
//!
//! Docker Hub requires an anonymous bearer token even for public
//! repositories. The token is fetched per operation from `auth.docker.io`,
//! travels only in the `Authorization` header, and is never logged or
//! persisted. A 401/403 becomes a typed
//! [`UnsupportedReason::Unavailable`]: the source cannot distinguish a private
//! repository from a missing one.
//!
//! [`DockerHttp`] exposes the response status and headers because the shared
//! [`RegistryHttp`](crate::release::http::RegistryHttp) contract hides both.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, Mutex};

use anyhow::{Context, Error, Result, bail};
use async_trait::async_trait;
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, percent_decode_str, utf8_percent_encode};
use serde_json::{Value, json};

use crate::release::artifact::normalize_version;
use crate::release::http::{HTTP_TIMEOUT, USER_AGENT};
use crate::release::source::{
    ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, UnsupportedReason,
    VersionInfo,
};

pub const DOCKER_REGISTRY: &str = "https://registry-1.docker.io";
pub const DOCKER_AUTH: &str = "https://auth.docker.io";
pub const DOCKER_TOKEN_SERVICE: &str = "registry.docker.io";
/// Tags are fetched in pages of this size; the `Link` header drives the rest.
pub const TAG_PAGE_SIZE: usize = 100;
/// Manifest index media types accepted from the registry.
pub const OCI_INDEX_ACCEPT: &str = "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json";
pub const OCI_INDEX_MEDIA_TYPE: &str = "application/vnd.oci.image.index.v1+json";
/// Moving tags that name a channel, not a version.
pub const CHANNEL_TAGS: &[&str] = &["latest", "stable", "edge", "nightly"];

const MAX_PAGES: usize = 100;
const SEGMENT: &AsciiSet = &NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'.')
    .remove(b'_')
    .remove(b'~');

/// A registry response with the status and headers Docker needs.
#[derive(Debug, Clone, Default)]
pub struct DockerResponse {
    pub status: u16,
    pub headers: BTreeMap<String, String>,
    pub body: Value,
}

/// One GET against the registry, including response headers. Tests inject a
/// fake; production uses [`ReqwestDockerHttp`].
#[async_trait]
pub trait DockerHttp: Send + Sync {
    async fn get(&self, url: &str, headers: &[(String, String)]) -> Result<DockerResponse>;
}

/// Production transport for Docker Hub.
pub struct ReqwestDockerHttp {
    client: reqwest::Client,
}

impl ReqwestDockerHttp {
    pub fn new() -> Result<Self> {
        let client = reqwest::Client::builder()
            .timeout(HTTP_TIMEOUT)
            .user_agent(USER_AGENT)
            .redirect(reqwest::redirect::Policy::limited(10))
            .build()
            .context("build docker registry HTTP client")?;
        Ok(Self { client })
    }
}

#[async_trait]
impl DockerHttp for ReqwestDockerHttp {
    async fn get(&self, url: &str, headers: &[(String, String)]) -> Result<DockerResponse> {
        let mut request = self.client.get(url);
        for (name, value) in headers {
            request = request.header(name.as_str(), value.as_str());
        }
        let response = request.send().await.with_context(|| format!("GET {url}"))?;
        let status = response.status().as_u16();
        let headers = response
            .headers()
            .iter()
            .map(|(name, value)| {
                (
                    name.as_str().to_owned(),
                    String::from_utf8_lossy(value.as_bytes()).into_owned(),
                )
            })
            .collect();
        let body = response.json::<Value>().await.unwrap_or(Value::Null);
        Ok(DockerResponse {
            status,
            headers,
            body,
        })
    }
}

/// Typed unsupported failure carried through [`anyhow::Error`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DockerUnsupported {
    pub reason: UnsupportedReason,
}

impl std::fmt::Display for DockerUnsupported {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "unsupported docker source request: {:?}",
            self.reason
        )
    }
}

impl std::error::Error for DockerUnsupported {}

fn unsupported(reason: UnsupportedReason) -> Error {
    Error::new(DockerUnsupported { reason })
}

/// Recover the typed reason from an error returned by this source.
pub fn unsupported_reason(error: &Error) -> Option<UnsupportedReason> {
    error
        .downcast_ref::<DockerUnsupported>()
        .map(|error| error.reason.clone())
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct DockerRepo {
    namespace: String,
    image: String,
}

impl DockerRepo {
    fn repository(&self) -> String {
        format!("{}/{}", self.namespace, self.image)
    }
}

/// Parse `pkg:docker/{namespace}/{image}` and `pkg:oci/...` purls. OCI purls
/// may carry the Docker Hub repository in a `repository_url` qualifier; other
/// registries are outside this source.
fn parse_project(project: &ProjectRef) -> Result<DockerRepo> {
    let purl = if project.purl.trim().is_empty() {
        format!(
            "pkg:{}/{}",
            project.purl_type.trim().to_ascii_lowercase(),
            project.name.trim()
        )
    } else {
        project.purl.trim().to_owned()
    };
    let body = purl.strip_prefix("pkg:").ok_or_else(|| {
        unsupported(UnsupportedReason::Unavailable(
            "purl is missing the pkg: scheme",
        ))
    })?;
    let body = body.split('#').next().unwrap_or(body);
    let (path, query) = body.split_once('?').unwrap_or((body, ""));
    let (purl_type, rest) = path.split_once('/').ok_or_else(|| {
        unsupported(UnsupportedReason::Unavailable(
            "purl is missing a type/name path",
        ))
    })?;
    let purl_type = purl_type.to_ascii_lowercase();
    if purl_type != "docker" && purl_type != "oci" {
        return Err(unsupported(UnsupportedReason::UnknownPurlType(purl_type)));
    }
    let rest = rest.rsplit_once('@').map_or(rest, |(head, _)| head);
    let path = percent_decode_str(rest).decode_utf8_lossy();
    let mut parts = path_parts(&path);
    if purl_type == "oci"
        && let Some(repository_url) = qualifier(query, "repository_url")
    {
        let repository_url = percent_decode_str(&repository_url).decode_utf8_lossy();
        parts = repository_parts(&repository_url)?;
    }
    match parts.as_slice() {
        [image] => repo("library", image),
        [namespace, image] => repo(namespace, image),
        [] => Err(unsupported(UnsupportedReason::Unavailable(
            "purl is missing the image name",
        ))),
        _ => Err(unsupported(UnsupportedReason::Unavailable(
            "docker purl must be namespace/image",
        ))),
    }
}

fn path_parts(path: &str) -> Vec<String> {
    path.split('/')
        .filter(|part| !part.is_empty())
        .map(|part| part.trim().to_ascii_lowercase())
        .collect()
}

/// Repository path from an OCI `repository_url` qualifier
/// (`docker.io/library/nginx`, optionally with a scheme).
fn repository_parts(repository_url: &str) -> Result<Vec<String>> {
    let trimmed = repository_url
        .trim()
        .trim_start_matches("https://")
        .trim_start_matches("http://");
    let (host, path) = match trimmed.split_once('/') {
        Some((host, path)) if host.contains('.') || host.contains(':') => {
            (host.to_ascii_lowercase(), path)
        }
        _ => (String::new(), trimmed),
    };
    if !host.is_empty()
        && !matches!(
            host.as_str(),
            "docker.io" | "index.docker.io" | "registry-1.docker.io"
        )
    {
        return Err(unsupported(UnsupportedReason::Unavailable(
            "oci repository_url is not Docker Hub",
        )));
    }
    Ok(path_parts(path))
}

fn repo(namespace: &str, image: &str) -> Result<DockerRepo> {
    for part in [namespace, image] {
        let valid = !part.is_empty()
            && part.chars().all(|character| {
                character.is_ascii_lowercase()
                    || character.is_ascii_digit()
                    || matches!(character, '.' | '_' | '-')
            });
        if !valid {
            return Err(unsupported(UnsupportedReason::Unavailable(
                "docker purl has an invalid repository path",
            )));
        }
    }
    Ok(DockerRepo {
        namespace: namespace.to_owned(),
        image: image.to_owned(),
    })
}

fn qualifier(query: &str, wanted: &str) -> Option<String> {
    query.split('&').find_map(|pair| {
        let (key, value) = pair.split_once('=')?;
        (key.eq_ignore_ascii_case(wanted) && !value.is_empty()).then(|| value.to_owned())
    })
}

fn header<'a>(response: &'a DockerResponse, name: &str) -> Option<&'a str> {
    response
        .headers
        .iter()
        .find(|(key, _)| key.eq_ignore_ascii_case(name))
        .map(|(_, value)| value.as_str())
}

/// The `rel="next"` target from an RFC 8288 `Link` header.
fn link_next(response: &DockerResponse) -> Option<String> {
    let link = header(response, "link")?;
    link.split(',').find_map(|part| {
        let part = part.trim();
        if !(part.contains("rel=\"next\"") || part.contains("rel=next")) {
            return None;
        }
        let start = part.find('<')? + 1;
        let end = part[start..].find('>')? + start;
        Some(part[start..end].to_owned())
    })
}

/// Registry pagination links may be relative.
fn absolute(link: &str) -> String {
    if link.starts_with("https://") || link.starts_with("http://") {
        link.to_owned()
    } else if link.starts_with('/') {
        format!("{DOCKER_REGISTRY}{link}")
    } else {
        format!("{DOCKER_REGISTRY}/{link}")
    }
}

fn is_channel_tag(tag: &str) -> bool {
    CHANNEL_TAGS
        .iter()
        .any(|channel| tag.eq_ignore_ascii_case(channel))
}

fn version_reference(version: &VersionInfo) -> &str {
    if version.raw.is_empty() {
        version.version.as_str()
    } else {
        version.raw.as_str()
    }
}

fn valid_digest(digest: &str) -> Option<String> {
    let digest = digest.trim();
    let hex = digest.strip_prefix("sha256:")?;
    (hex.len() == 64 && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
        .then(|| digest.to_ascii_lowercase())
}

/// Size from `Content-Length`, else the manifest layers (image manifest) or
/// entry sizes (index).
fn manifest_size(response: &DockerResponse) -> Option<u64> {
    if let Some(size) =
        header(response, "content-length").and_then(|value| value.trim().parse().ok())
    {
        return Some(size);
    }
    let entries = response
        .body
        .get("layers")
        .and_then(Value::as_array)
        .or_else(|| response.body.get("manifests").and_then(Value::as_array))?;
    let sizes: Vec<u64> = entries
        .iter()
        .filter_map(|entry| entry.get("size").and_then(Value::as_u64))
        .collect();
    (!sizes.is_empty()).then(|| sizes.iter().sum())
}

/// Docker Hub release source.
pub struct DockerSource {
    http: Arc<dyn DockerHttp>,
    /// Last observed manifest digest per `repository:tag`, used to detect a
    /// tag that moved. Only the newest digest is kept.
    digests: Mutex<HashMap<String, String>>,
}

impl DockerSource {
    pub fn new(http: Arc<dyn DockerHttp>) -> Self {
        Self {
            http,
            digests: Mutex::new(HashMap::new()),
        }
    }

    fn headers(token: Option<&str>, accept: &str) -> Vec<(String, String)> {
        let mut headers = vec![("Accept".to_owned(), accept.to_owned())];
        if let Some(token) = token {
            headers.push(("Authorization".to_owned(), format!("Bearer {token}")));
        }
        headers
    }

    /// Anonymous pull token scoped to one repository.
    async fn token(&self, repo: &DockerRepo) -> Result<String> {
        let url = format!(
            "{DOCKER_AUTH}/token?service={DOCKER_TOKEN_SERVICE}&scope=repository:{}:pull",
            repo.repository()
        );
        let response = self
            .http
            .get(&url, &Self::headers(None, "application/json"))
            .await?;
        match response.status {
            200 => {}
            401 | 403 => {
                return Err(unsupported(UnsupportedReason::Unavailable(
                    "docker hub token requires authentication",
                )));
            }
            status => bail!("docker hub token request failed with HTTP {status}"),
        }
        response
            .body
            .get("token")
            .or_else(|| response.body.get("access_token"))
            .and_then(Value::as_str)
            .filter(|token| !token.is_empty())
            .map(str::to_owned)
            .ok_or_else(|| {
                unsupported(UnsupportedReason::Unavailable(
                    "docker hub token response is missing a token",
                ))
            })
    }

    async fn registry_get(&self, token: &str, url: &str, accept: &str) -> Result<DockerResponse> {
        let response = self
            .http
            .get(url, &Self::headers(Some(token), accept))
            .await?;
        if response.status == 401 || response.status == 403 {
            return Err(unsupported(UnsupportedReason::Unavailable(
                "docker hub registry requires authentication",
            )));
        }
        Ok(response)
    }

    /// Every tag, following `Link` pagination, in registry order.
    async fn tags(&self, repo: &DockerRepo) -> Result<Vec<String>> {
        let token = self.token(repo).await?;
        let mut tags = Vec::new();
        let mut next = Some(format!(
            "{DOCKER_REGISTRY}/v2/{}/tags/list?n={TAG_PAGE_SIZE}",
            repo.repository()
        ));
        let mut pages = 0usize;
        while let Some(url) = next {
            pages += 1;
            if pages > MAX_PAGES {
                bail!("docker registry pagination exceeded {MAX_PAGES} pages");
            }
            let response = self.registry_get(&token, &url, "application/json").await?;
            if response.status != 200 {
                bail!(
                    "docker registry tags request failed with HTTP {} for {url}",
                    response.status
                );
            }
            if let Some(page) = response.body.get("tags").and_then(Value::as_array) {
                tags.extend(page.iter().filter_map(Value::as_str).map(str::to_owned));
            }
            next = link_next(&response).map(|link| absolute(&link));
        }
        Ok(tags)
    }

    fn manifest_url(repo: &DockerRepo, reference: &str) -> String {
        format!(
            "{DOCKER_REGISTRY}/v2/{}/manifests/{}",
            repo.repository(),
            utf8_percent_encode(reference, SEGMENT)
        )
    }

    async fn manifest(&self, repo: &DockerRepo, reference: &str) -> Result<DockerResponse> {
        let token = self.token(repo).await?;
        let url = Self::manifest_url(repo, reference);
        self.registry_get(&token, &url, OCI_INDEX_ACCEPT).await
    }
}

#[async_trait]
impl ReleaseSource for DockerSource {
    fn name(&self) -> &'static str {
        "docker"
    }

    fn capabilities(&self) -> SourceCapabilities {
        SourceCapabilities {
            versions: true,
            artifacts: true,
            statuses: true,
            project_meta: true,
        }
    }

    async fn versions(&self, project: &ProjectRef) -> Result<Vec<VersionInfo>> {
        let repo = parse_project(project)?;
        let tags = self.tags(&repo).await?;
        let mut seen = HashSet::new();
        let mut versions = Vec::new();
        for tag in tags {
            if is_channel_tag(&tag) {
                continue;
            }
            let Some(version) = normalize_version(&tag) else {
                continue;
            };
            if seen.insert(version.clone()) {
                versions.push(VersionInfo {
                    raw: tag,
                    version,
                    deprecated: false,
                    reason: String::new(),
                });
            }
        }
        if versions.is_empty() {
            return Err(unsupported(UnsupportedReason::NoVersions));
        }
        versions.sort_by(|left, right| left.version.cmp(&right.version));
        Ok(versions)
    }

    async fn artifacts(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<ArtifactInfo>> {
        let repo = parse_project(project)?;
        let reference = version_reference(version);
        let response = self.manifest(&repo, reference).await?;
        match response.status {
            200 => {}
            404 => return Err(unsupported(UnsupportedReason::NoArtifacts)),
            status => {
                bail!("docker manifest request failed with HTTP {status} for {reference}");
            }
        }
        let Some(digest) = header(&response, "docker-content-digest").and_then(valid_digest) else {
            return Err(unsupported(UnsupportedReason::NoArtifacts));
        };
        let sha256 = digest
            .strip_prefix("sha256:")
            .expect("validated sha256 digest")
            .to_owned();
        let mime_type = response
            .body
            .get("mediaType")
            .and_then(Value::as_str)
            .unwrap_or(OCI_INDEX_MEDIA_TYPE)
            .to_owned();
        Ok(vec![ArtifactInfo {
            file_name: format!("{}-{reference}.oci.json", repo.image),
            url: format!(
                "{DOCKER_REGISTRY}/v2/{}/manifests/{digest}",
                repo.repository()
            ),
            sha256: Some(sha256),
            size: manifest_size(&response),
            mime_type: Some(mime_type),
        }])
    }

    async fn statuses(
        &self,
        project: &ProjectRef,
        version: &VersionInfo,
    ) -> Result<Vec<StatusInfo>> {
        let repo = parse_project(project)?;
        let reference = version_reference(version);
        let response = self.manifest(&repo, reference).await?;
        match response.status {
            200 => {}
            404 => return Err(unsupported(UnsupportedReason::NoStatuses)),
            status => {
                bail!("docker manifest request failed with HTTP {status} for {reference}");
            }
        }
        let Some(digest) = header(&response, "docker-content-digest").and_then(valid_digest) else {
            return Err(unsupported(UnsupportedReason::NoStatuses));
        };
        let key = format!("{}:{reference}", repo.repository());
        let previous = self
            .digests
            .lock()
            .expect("docker digest cache")
            .insert(key, digest.clone());
        let Some(previous) = previous else {
            return Ok(Vec::new());
        };
        if previous == digest {
            return Ok(Vec::new());
        }
        Ok(vec![StatusInfo {
            status: "deprecated".to_owned(),
            kind: Some("mutable_tag".to_owned()),
            reason: format!("tag {reference} moved from {previous} to {digest}"),
        }])
    }

    async fn project_meta(&self, project: &ProjectRef) -> Result<Value> {
        let repo = parse_project(project)?;
        let mut tags = self.tags(&repo).await?;
        tags.sort();
        tags.dedup();
        let channel_tags: Vec<String> = tags
            .iter()
            .filter(|tag| is_channel_tag(tag))
            .cloned()
            .collect();
        Ok(json!({
            "registry": "registry-1.docker.io",
            "repository": repo.repository(),
            "tags": tags,
            "channelTags": channel_tags,
            "authRequired": true,
        }))
    }
}