1use crate::AuthError;
4use url::Url;
5
6#[derive(Clone, Copy, Debug)]
8pub struct RegistryPolicy {
9 pub allow_all_domains: bool,
11}
12
13#[derive(Clone, Debug, PartialEq, Eq)]
15pub struct RegistryUrl {
16 url: Url,
17 npm_key: String,
18}
19
20impl RegistryUrl {
21 pub fn as_url(&self) -> &str {
23 self.url.as_str()
24 }
25
26 pub fn npm_key(&self) -> &str {
28 &self.npm_key
29 }
30}
31
32impl RegistryPolicy {
33 pub fn parse(&self, input: &str) -> Result<Option<RegistryUrl>, AuthError> {
35 let mut url =
36 Url::parse(input).map_err(|e| AuthError::Config(format!("Invalid registry URL: {e}")))?;
37 if url.scheme() != "https"
38 || url.host_str().is_none()
39 || !url.username().is_empty()
40 || url.password().is_some()
41 || url.query().is_some()
42 || url.fragment().is_some()
43 {
44 return Err(AuthError::Config(
45 "Registry URL must be HTTPS without credentials, query, or fragment".to_string(),
46 ));
47 }
48
49 let host = url.host_str().unwrap().to_owned();
50 let is_gar = host.strip_suffix("-npm.pkg.dev").is_some_and(|region| {
51 !region.is_empty()
52 && region
53 .bytes()
54 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
55 });
56 if !self.allow_all_domains && !is_gar {
57 return Ok(None);
58 }
59 if is_gar && url.port().is_some() && !self.allow_all_domains {
60 return Err(AuthError::Config(
61 "Artifact Registry URL may not use a nonstandard port".to_string(),
62 ));
63 }
64 if is_gar
65 && url
66 .path_segments()
67 .is_none_or(|segments| segments.filter(|s| !s.is_empty()).count() < 2)
68 {
69 return Err(AuthError::Config(
70 "Artifact Registry URL must include project and repository".to_string(),
71 ));
72 }
73
74 if !url.path().ends_with('/') {
75 let path = format!("{}/", url.path());
76 url.set_path(&path);
77 }
78 let authority = match url.port() {
79 Some(port) => format!("{host}:{port}"),
80 None => host,
81 };
82 let npm_key = format!("//{authority}{}", url.path());
83 Ok(Some(RegistryUrl { url, npm_key }))
84 }
85
86 pub fn parse_npm_key(&self, key: &str) -> Result<Option<RegistryUrl>, AuthError> {
88 if !key.starts_with("//") {
89 return Err(AuthError::Config("Invalid npm registry key".to_string()));
90 }
91 self.parse(&format!("https:{key}"))
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn policy_checks_parsed_host_and_scheme() {
101 let policy = RegistryPolicy {
102 allow_all_domains: false,
103 };
104 assert_eq!(
105 policy.parse("https://registry.example.com/p/r").unwrap(),
106 None
107 );
108 assert_eq!(
109 policy
110 .parse("https://us-npm.pkg.dev.evil.test/p/r")
111 .unwrap(),
112 None
113 );
114 assert!(policy.parse("http://us-npm.pkg.dev/p/r").is_err());
115 assert!(policy.parse("https://user@us-npm.pkg.dev/p/r").is_err());
116 assert!(policy.parse("https://us-npm.pkg.dev/p/r?x=1").is_err());
117 assert!(policy.parse("https://us-npm.pkg.dev:444/p/r").is_err());
118 assert_eq!(
119 policy
120 .parse("https://us-npm.pkg.dev/p/r")
121 .unwrap()
122 .unwrap()
123 .npm_key(),
124 "//us-npm.pkg.dev/p/r/"
125 );
126 }
127
128 #[test]
129 fn override_allows_other_https_hosts() {
130 let policy = RegistryPolicy {
131 allow_all_domains: true,
132 };
133 assert!(
134 policy
135 .parse("https://registry.example.com/private")
136 .unwrap()
137 .is_some()
138 );
139 }
140}