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
38 if url.scheme() != "https"
39 || url.host_str().is_none()
40 || !url.username().is_empty()
41 || url.password().is_some()
42 || url.query().is_some()
43 || url.fragment().is_some()
44 {
45 return Err(AuthError::Config(
46 "Registry URL must be HTTPS without credentials, query, or fragment".to_string(),
47 ));
48 }
49
50 let host = url.host_str().unwrap().to_owned();
51 let is_gar = host.strip_suffix("-npm.pkg.dev").is_some_and(|region| {
52 !region.is_empty()
53 && region
54 .bytes()
55 .all(|b| b.is_ascii_alphanumeric() || b == b'-')
56 });
57
58 if !self.allow_all_domains && !is_gar {
59 return Ok(None);
60 }
61
62 if is_gar && url.port().is_some() && !self.allow_all_domains {
63 return Err(AuthError::Config(
64 "Artifact Registry URL may not use a nonstandard port".to_string(),
65 ));
66 }
67
68 if is_gar
69 && url
70 .path_segments()
71 .is_none_or(|segments| segments.filter(|s| !s.is_empty()).count() < 2)
72 {
73 return Err(AuthError::Config(
74 "Artifact Registry URL must include project and repository".to_string(),
75 ));
76 }
77
78 if !url.path().ends_with('/') {
79 let path = format!("{}/", url.path());
80 url.set_path(&path);
81 }
82
83 let authority = match url.port() {
84 Some(port) => format!("{host}:{port}"),
85 None => host,
86 };
87 let npm_key = format!("//{authority}{}", url.path());
88
89 Ok(Some(RegistryUrl { url, npm_key }))
90 }
91
92 pub fn parse_npm_key(&self, key: &str) -> Result<Option<RegistryUrl>, AuthError> {
94 if !key.starts_with("//") {
95 return Err(AuthError::Config("Invalid npm registry key".to_string()));
96 }
97
98 self.parse(&format!("https:{key}"))
99 }
100}
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn policy_checks_parsed_host_and_scheme() {
108 let policy = RegistryPolicy {
109 allow_all_domains: false,
110 };
111 assert_eq!(
112 policy.parse("https://registry.example.com/p/r").unwrap(),
113 None
114 );
115 assert_eq!(
116 policy
117 .parse("https://us-npm.pkg.dev.evil.test/p/r")
118 .unwrap(),
119 None
120 );
121 assert!(policy.parse("http://us-npm.pkg.dev/p/r").is_err());
122 assert!(policy.parse("https://user@us-npm.pkg.dev/p/r").is_err());
123 assert!(policy.parse("https://us-npm.pkg.dev/p/r?x=1").is_err());
124 assert!(policy.parse("https://us-npm.pkg.dev:444/p/r").is_err());
125 assert_eq!(
126 policy
127 .parse("https://us-npm.pkg.dev/p/r")
128 .unwrap()
129 .unwrap()
130 .npm_key(),
131 "//us-npm.pkg.dev/p/r/"
132 );
133 }
134
135 #[test]
136 fn override_allows_other_https_hosts() {
137 let policy = RegistryPolicy {
138 allow_all_domains: true,
139 };
140 assert!(
141 policy
142 .parse("https://registry.example.com/private")
143 .unwrap()
144 .is_some()
145 );
146 }
147}