use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use super::{
BlockedHost, IndexUrlError, PolicyGate, RedactedUrl, RegistryAccessPolicy, RegistryUrlKind,
TrustedConstantRegistryUrl, ValidatedRegistryUrl, WorkspaceRegistryAccess, classify_host,
};
use crate::EgressTier;
use crate::config_trust::OperatorPath;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RegistryTrust {
Trusted,
WorkspaceDeclared,
}
impl RegistryTrust {
#[must_use]
pub const fn egress(self) -> EgressTier {
match self {
Self::Trusted => EgressTier::Baseline,
Self::WorkspaceDeclared => EgressTier::Guarded,
}
}
}
#[must_use]
pub fn floor_block(url: &url::Url, level: WorkspaceRegistryAccess) -> Option<BlockedHost> {
let class = classify_host(url);
let test_http_loopback = cfg!(any(test, feature = "test-util")) && url.scheme() == "http";
(class.never_a_registry() && !test_http_loopback).then(|| BlockedHost::new(class, level))
}
fn canonical(url: &url::Url) -> String {
url.as_str().trim_end_matches('/').to_string()
}
#[derive(Clone, Default, PartialEq, Eq)]
pub struct OperatorRegistries {
urls: HashSet<String>,
}
impl std::fmt::Debug for OperatorRegistries {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("OperatorRegistries")
.field("urls", &self.urls.len())
.finish()
}
}
impl OperatorRegistries {
#[must_use]
pub fn declared_in<S: AsRef<str>>(
_file: &OperatorPath,
candidates: impl IntoIterator<Item = S>,
) -> Self {
let urls = candidates
.into_iter()
.filter_map(|candidate| url::Url::parse(candidate.as_ref()).ok())
.filter(|url| url.username().is_empty() && url.password().is_none())
.map(|url| canonical(&url))
.collect();
Self { urls }
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.urls.is_empty()
}
#[must_use]
pub fn contains_str(&self, candidate: &str) -> bool {
url::Url::parse(candidate).is_ok_and(|url| self.contains(&url))
}
fn contains(&self, url: &url::Url) -> bool {
self.urls.contains(&canonical(url))
}
pub fn classify<K: RegistryUrlKind>(
&self,
candidate: &str,
raw_for_log: &str,
policy: &RegistryAccessPolicy,
) -> Result<DeclaredRegistry<K>, K::Error> {
let shape = ValidatedRegistryUrl::<K>::build(candidate, raw_for_log, PolicyGate::Skip)?;
let parsed = url::Url::parse(shape.as_str())
.map_err(|_| IndexUrlError::InvalidUrl(RedactedUrl::new(raw_for_log)))?;
if self.contains(&parsed) {
if let Some(block) = floor_block(&parsed, policy.get()) {
tracing::warn!(
url = %RedactedUrl::new(raw_for_log),
class = ?block.class(),
ecosystem = %K::ECOSYSTEM,
"operator-declared registry host is never a registry; rejected"
);
return Err(IndexUrlError::BlockedHost { block }.into());
}
return Ok(DeclaredRegistry {
url: shape,
trust: RegistryTrust::Trusted,
});
}
let url =
ValidatedRegistryUrl::<K>::build(candidate, raw_for_log, PolicyGate::Enforce(policy))?;
Ok(DeclaredRegistry {
url,
trust: RegistryTrust::WorkspaceDeclared,
})
}
}
pub struct DeclaredRegistry<K> {
url: ValidatedRegistryUrl<K>,
trust: RegistryTrust,
}
impl<K> DeclaredRegistry<K> {
#[must_use]
pub const fn url(&self) -> &ValidatedRegistryUrl<K> {
&self.url
}
#[must_use]
pub const fn trust(&self) -> RegistryTrust {
self.trust
}
#[must_use]
pub fn as_str(&self) -> &str
where
K: RegistryUrlKind,
{
self.url.as_str()
}
#[must_use]
pub const fn egress(&self) -> EgressTier {
self.trust.egress()
}
}
impl<K: TrustedConstantRegistryUrl> DeclaredRegistry<K> {
pub fn trusted_constant(raw: &'static str) -> Result<Self, K::Error> {
Ok(Self {
url: ValidatedRegistryUrl::<K>::new_trusted_constant(raw)?,
trust: RegistryTrust::Trusted,
})
}
}
impl<K> Clone for DeclaredRegistry<K> {
fn clone(&self) -> Self {
Self {
url: self.url.clone(),
trust: self.trust,
}
}
}
impl<K: RegistryUrlKind> std::fmt::Debug for DeclaredRegistry<K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DeclaredRegistry")
.field("url", &self.url)
.field("trust", &self.trust)
.finish()
}
}
impl<K> PartialEq for DeclaredRegistry<K> {
fn eq(&self, other: &Self) -> bool {
self.url == other.url && self.trust == other.trust
}
}
impl<K> Eq for DeclaredRegistry<K> {}
impl<K> Hash for DeclaredRegistry<K> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.url.hash(state);
self.trust.hash(state);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::assert_matches;
use crate::EcosystemId;
use crate::net_policy::{BlockingPolicy, HostClass, WorkspaceRegistryAccess};
enum TestKind {}
impl crate::net_policy::private::Sealed for TestKind {}
impl RegistryUrlKind for TestKind {
const ECOSYSTEM: EcosystemId = EcosystemId::Npm;
const REJECT_QUERY_FRAGMENT: bool = false;
type Error = IndexUrlError;
}
fn file() -> OperatorPath {
OperatorPath::for_test("/home/me/.npmrc")
}
fn policy(level: WorkspaceRegistryAccess) -> RegistryAccessPolicy {
RegistryAccessPolicy::new(level)
}
fn classify(
set: &OperatorRegistries,
url: &str,
level: WorkspaceRegistryAccess,
) -> Result<DeclaredRegistry<TestKind>, IndexUrlError> {
set.classify::<TestKind>(url, url, &policy(level))
}
#[test]
fn egress_follows_trust() {
assert_eq!(RegistryTrust::Trusted.egress(), EgressTier::Baseline);
assert_eq!(
RegistryTrust::WorkspaceDeclared.egress(),
EgressTier::Guarded
);
}
#[test]
fn operator_url_is_trusted_whatever_spelling_and_policy() {
let set = OperatorRegistries::declared_in(&file(), ["https://Npm.Corp.example:443/"]);
for spelling in [
"https://npm.corp.example",
"https://npm.corp.example/",
"https://NPM.corp.example:443",
] {
let declared = classify(&set, spelling, WorkspaceRegistryAccess::Off).unwrap();
assert_eq!(declared.trust(), RegistryTrust::Trusted, "{spelling}");
assert_eq!(declared.egress(), EgressTier::Baseline);
}
}
#[test]
fn workspace_only_url_is_workspace_declared_and_policy_gated() {
let set = OperatorRegistries::declared_in(&file(), ["https://npm.corp.example"]);
let declared = classify(
&set,
"https://repo.example",
WorkspaceRegistryAccess::PublicOnly,
)
.unwrap();
assert_eq!(declared.trust(), RegistryTrust::WorkspaceDeclared);
let blocked = classify(&set, "https://repo.example", WorkspaceRegistryAccess::Off);
assert_matches!(blocked, Err(IndexUrlError::BlockedHost { .. }));
}
#[test]
fn same_host_different_path_is_not_trusted() {
let set = OperatorRegistries::declared_in(&file(), ["https://npm.corp.example/team-a"]);
let other = classify(
&set,
"https://npm.corp.example/team-b",
WorkspaceRegistryAccess::PublicOnly,
)
.unwrap();
assert_eq!(other.trust(), RegistryTrust::WorkspaceDeclared);
let off = classify(
&set,
"https://npm.corp.example/team-b",
WorkspaceRegistryAccess::Off,
);
assert_matches!(off, Err(IndexUrlError::BlockedHost { .. }));
}
#[test]
fn trusted_never_a_registry_host_is_rejected_at_the_floor() {
let set = OperatorRegistries::declared_in(&file(), ["https://169.254.169.254/"]);
let error = classify(
&set,
"https://169.254.169.254",
WorkspaceRegistryAccess::All,
)
.unwrap_err();
let IndexUrlError::BlockedHost { block } = error else {
panic!("expected a blocked host, got {error:?}");
};
assert_eq!(block.class(), HostClass::CloudMetadata);
assert_eq!(block.policy(), BlockingPolicy::Floor);
}
#[test]
fn userinfo_and_http_are_rejected_even_for_an_operator_url() {
let set = OperatorRegistries::declared_in(
&file(),
[
"https://user:pw@npm.corp.example",
"http://npm.corp.example",
],
);
assert!(
classify(
&set,
"https://user:pw@npm.corp.example",
WorkspaceRegistryAccess::All
)
.is_err()
);
assert!(
classify(
&set,
"http://npm.corp.example",
WorkspaceRegistryAccess::All
)
.is_err()
);
}
#[test]
fn empty_set_trusts_nothing() {
let set = OperatorRegistries::default();
assert!(set.is_empty());
let declared = classify(
&set,
"https://npm.corp.example",
WorkspaceRegistryAccess::All,
)
.unwrap();
assert_eq!(declared.trust(), RegistryTrust::WorkspaceDeclared);
}
#[test]
fn debug_never_renders_a_url_or_credential() {
let set = OperatorRegistries::declared_in(
&file(),
[
"https://registry.corp.example/npm?_authToken=tok-secret",
"https://user:s3cr3t@registry.corp.example/",
],
);
let rendered = format!("{set:?}");
for leak in ["tok-secret", "s3cr3t", "registry.corp.example"] {
assert!(!rendered.contains(leak), "{rendered}");
}
assert!(!set.contains_str("https://user:s3cr3t@registry.corp.example/"));
}
#[test]
fn unparseable_candidates_are_skipped() {
let set = OperatorRegistries::declared_in(&file(), ["not a url", "https://a.example"]);
assert!(set.contains_str("https://a.example"));
assert!(!set.is_empty());
}
}