1use crate::error::AuthError;
7use crate::fs::{FileTransaction, resolve};
8use crate::registry::RegistryPolicy;
9use crate::token::validate_token;
10use regex::Regex;
11use std::collections::BTreeMap;
12use std::path::Path;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum NpmrcConfigType {
17 Registry {
19 scope: Option<String>,
21 registry: String,
23 raw: String,
25 },
26 AuthToken {
28 registry: String,
30 token: String,
32 },
33 Password {
35 registry: String,
37 password: String,
39 },
40 Username {
42 registry: String,
44 },
45 Other(String),
47}
48
49impl NpmrcConfigType {
50 pub fn to_line(&self) -> String {
52 match self {
53 NpmrcConfigType::Registry { raw, .. } => raw.clone(),
54 NpmrcConfigType::AuthToken { registry, token } => {
55 format!("{registry}:_authToken=\"{token}\"")
56 }
57 NpmrcConfigType::Password { registry, password } => {
58 format!("{registry}:_password={password}")
59 }
60 NpmrcConfigType::Username { registry } => {
61 format!("{registry}:username=oauth2accesstoken")
62 }
63 NpmrcConfigType::Other(line) => line.clone(),
64 }
65 }
66}
67
68pub struct NpmrcParser {
70 policy: RegistryPolicy,
71 registry_re: Regex,
72 auth_token_re: Regex,
73 password_re: Regex,
74 username_re: Regex,
75}
76
77impl NpmrcParser {
78 pub fn new(allow_all_domains: bool) -> Result<Self, AuthError> {
82 Ok(Self {
83 policy: RegistryPolicy { allow_all_domains },
84 registry_re: Regex::new(
85 r"^(@[a-zA-Z0-9-*~][a-zA-Z0-9-*._~]*:)?registry=(https://[^ \t\r\n]+)$",
86 )?,
87 auth_token_re: Regex::new(r"^(//[^ \t\r\n]+):_authToken=.*$")?,
88 password_re: Regex::new(r"^(//[^ \t\r\n]+):_password=.*$")?,
89 username_re: Regex::new(r"^(//[^ \t\r\n]+):username=oauth2accesstoken$")?,
90 })
91 }
92
93 pub fn parse_line(&self, line: &str) -> Result<NpmrcConfigType, AuthError> {
95 let trimmed = line.trim();
96
97 if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with(';') {
98 return Ok(NpmrcConfigType::Other(line.to_string()));
99 }
100
101 if let Some(caps) = self.registry_re.captures(trimmed) {
102 let scope = caps
103 .get(1)
104 .map(|m| m.as_str().trim_end_matches(':').to_string());
105 let registry_raw = caps.get(2).map(|m| m.as_str()).unwrap_or("");
106 if let Some(registry) = self.policy.parse(registry_raw)? {
107 return Ok(NpmrcConfigType::Registry {
108 scope,
109 registry: registry.npm_key().to_string(),
110 raw: line.to_string(),
111 });
112 }
113 }
114
115 if let Some(caps) = self.auth_token_re.captures(trimmed) {
116 let key = caps.get(1).map(|m| m.as_str()).unwrap_or("");
117 if let Some(registry) = self.policy.parse_npm_key(key)? {
118 let token_part = trimmed
119 .split_once(":_authToken=")
120 .map(|(_, t)| t.trim().trim_matches('"').trim_matches('\'').to_string())
121 .unwrap_or_default();
122 return Ok(NpmrcConfigType::AuthToken {
123 registry: registry.npm_key().to_string(),
124 token: token_part,
125 });
126 }
127 }
128
129 if let Some(caps) = self.password_re.captures(trimmed) {
130 let key = caps.get(1).map(|m| m.as_str()).unwrap_or("");
131 if let Some(registry) = self.policy.parse_npm_key(key)? {
132 let pass_part = trimmed
133 .split_once(":_password=")
134 .map(|(_, p)| p.trim().to_string())
135 .unwrap_or_default();
136 return Ok(NpmrcConfigType::Password {
137 registry: registry.npm_key().to_string(),
138 password: pass_part,
139 });
140 }
141 }
142
143 if let Some(caps) = self.username_re.captures(trimmed) {
144 let key = caps.get(1).map(|m| m.as_str()).unwrap_or("");
145 if let Some(registry) = self.policy.parse_npm_key(key)? {
146 return Ok(NpmrcConfigType::Username {
147 registry: registry.npm_key().to_string(),
148 });
149 }
150 }
151
152 Ok(NpmrcConfigType::Other(line.to_string()))
153 }
154}
155
156pub fn has_registry(
158 from_content: &str,
159 to_content: &str,
160 allow_all_domains: bool,
161) -> Result<bool, AuthError> {
162 let parser = NpmrcParser::new(allow_all_domains)?;
163 for line in from_content.lines().chain(to_content.lines()) {
164 if matches!(parser.parse_line(line)?, NpmrcConfigType::Registry { .. }) {
165 return Ok(true);
166 }
167 }
168 Ok(false)
169}
170
171pub fn transform_npmrc_contents(
192 from_content: &str,
193 to_content: &str,
194 creds: &str,
195 allow_all_domains: bool,
196 same_file: bool,
197) -> Result<(String, String), AuthError> {
198 validate_token(creds)?;
199 let parser = NpmrcParser::new(allow_all_domains)?;
200 let mut registries_found = BTreeMap::new();
201 let mut from_lines_out = Vec::new();
202
203 for line in from_content.lines() {
205 match parser.parse_line(line)? {
206 NpmrcConfigType::Registry {
207 scope,
208 registry,
209 raw,
210 } => {
211 registries_found.insert(registry.clone(), scope);
212 from_lines_out.push(raw);
213 }
214 NpmrcConfigType::AuthToken { registry, .. } => {
215 if same_file {
216 } else {
218 log::debug!(
219 "Moving existing _authToken for {registry} from project .npmrc to credential .npmrc"
220 );
221 }
223 }
224 NpmrcConfigType::Password { registry, .. } => {
225 if !same_file {
226 log::debug!("Removing legacy password for {registry} from project .npmrc");
227 }
228 }
229 NpmrcConfigType::Username { .. } => {
230 }
232 NpmrcConfigType::Other(other) => {
233 from_lines_out.push(other);
234 }
235 }
236 }
237
238 if !same_file {
239 for line in to_content.lines() {
240 if let NpmrcConfigType::Registry {
241 scope, registry, ..
242 } = parser.parse_line(line)?
243 {
244 registries_found.entry(registry).or_insert(scope);
245 }
246 }
247 }
248
249 if registries_found.is_empty() {
250 return Err(AuthError::Config(
251 "No Artifact Registry configuration found.\n\
252 Ensure your .npmrc contains a registry line such as:\n\
253 @my-scope:registry=https://<region>-npm.pkg.dev/<project>/<repo>/\n\
254 Run `gcloud artifacts print-settings npm` to generate configuration."
255 .to_string(),
256 ));
257 }
258
259 let mut to_lines_out = Vec::new();
261 let mut pending_registries = registries_found.clone();
262
263 if !to_content.is_empty() {
264 for line in to_content.lines() {
265 let parsed = parser.parse_line(line)?;
266 match parsed {
267 NpmrcConfigType::AuthToken { registry, .. } => {
268 if registries_found.contains_key(®istry) {
269 if pending_registries.remove(®istry).is_some() {
270 to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
271 }
272 } else {
273 to_lines_out.push(line.to_string());
274 }
275 }
276 NpmrcConfigType::Password { registry, .. } => {
277 if registries_found.contains_key(®istry) {
278 if pending_registries.remove(®istry).is_some() {
279 to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
280 }
281 } else {
282 to_lines_out.push(line.to_string());
283 }
284 }
285 NpmrcConfigType::Username { registry } => {
286 if !registries_found.contains_key(®istry) {
287 to_lines_out.push(line.to_string());
288 }
289 }
290 _ => {
291 to_lines_out.push(line.to_string());
292 }
293 }
294 }
295 }
296
297 for (registry, _) in pending_registries {
299 log::debug!("Adding auth token for registry {registry}");
300 to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
301 }
302
303 let to_output = to_lines_out.join("\n") + "\n";
304 let from_output = from_lines_out.join("\n") + "\n";
305
306 Ok((from_output, to_output))
307}
308
309pub fn update_npmrc_configs(
321 from_path: &Path,
322 to_path: &Path,
323 creds: &str,
324 allow_all_domains: bool,
325) -> Result<(), AuthError> {
326 let from_path = resolve(from_path)?;
327 let to_path = resolve(to_path)?;
328 let same_file = from_path == to_path;
329 let mut transaction = FileTransaction::new(&[from_path.clone(), to_path.clone()])?;
330 let from_content = transaction.contents(&from_path)?.to_owned();
331 let to_content = transaction.contents(&to_path)?.to_owned();
332
333 let (from_output, to_output) = transform_npmrc_contents(
334 &from_content,
335 if same_file {
336 &from_content
337 } else {
338 &to_content
339 },
340 creds,
341 allow_all_domains,
342 same_file,
343 )?;
344
345 transaction.stage(&to_path, &to_output)?;
346 if !same_file && transaction.existed(&from_path)? && from_output != from_content {
347 transaction.stage(&from_path, &from_output)?;
348 }
349 transaction.commit()?;
350 Ok(())
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356 use std::fs;
357 use tempfile::tempdir;
358
359 #[test]
360 fn test_parser_standard_ar() {
361 let parser = NpmrcParser::new(false).unwrap();
362
363 let line = "@my-org:registry=https://us-central1-npm.pkg.dev/my-project/my-repo/";
364 let parsed = parser.parse_line(line).unwrap();
365 match parsed {
366 NpmrcConfigType::Registry {
367 scope, registry, ..
368 } => {
369 assert_eq!(scope.as_deref(), Some("@my-org"));
370 assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
371 }
372 _ => panic!("Expected Registry variant"),
373 }
374 }
375
376 #[test]
377 fn test_parser_unscoped_ar() {
378 let parser = NpmrcParser::new(false).unwrap();
379
380 let line = "registry=https://europe-west1-npm.pkg.dev/google-cloud/demo-repo/";
381 let parsed = parser.parse_line(line).unwrap();
382 match parsed {
383 NpmrcConfigType::Registry {
384 scope, registry, ..
385 } => {
386 assert_eq!(scope, None);
387 assert_eq!(
388 registry,
389 "//europe-west1-npm.pkg.dev/google-cloud/demo-repo/"
390 );
391 }
392 _ => panic!("Expected Registry variant"),
393 }
394 }
395
396 #[test]
397 fn test_parser_existing_auth_token() {
398 let parser = NpmrcParser::new(false).unwrap();
399
400 let line = "//us-central1-npm.pkg.dev/my-project/my-repo/:_authToken=\"ya29.sample-token\"";
401 let parsed = parser.parse_line(line).unwrap();
402 match parsed {
403 NpmrcConfigType::AuthToken { registry, token } => {
404 assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
405 assert_eq!(token, "ya29.sample-token");
406 }
407 _ => panic!("Expected AuthToken variant"),
408 }
409 }
410
411 #[test]
412 fn test_in_memory_transform() {
413 let from =
414 "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\nstrict-ssl=true\n";
415 let to = "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n";
416 let token = "fresh-adc-token-12345";
417
418 let (from_out, to_out) = transform_npmrc_contents(from, to, token, false, false).unwrap();
419 assert!(
420 from_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/")
421 );
422 assert!(from_out.contains("strict-ssl=true"));
423 assert!(to_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
424 assert!(to_out.contains(
425 "//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\""
426 ));
427 }
428
429 #[test]
430 fn duplicate_legacy_credentials_are_removed() {
431 let source = "@corp:registry=https://us-npm.pkg.dev/project/repo/\n";
432 let target = "//us-npm.pkg.dev/project/repo/:_authToken=old\n//us-npm.pkg.dev/project/repo/:_password=old\n//us-npm.pkg.dev/project/repo/:username=oauth2accesstoken\n";
433 let (_, updated) = transform_npmrc_contents(source, target, "new", false, false).unwrap();
434 assert_eq!(updated.matches(":_authToken=").count(), 1);
435 assert!(!updated.contains("old"));
436 assert!(!updated.contains(":username="));
437 }
438
439 #[test]
440 fn test_update_npmrc_moves_token_to_user_config() {
441 let dir = tempdir().unwrap();
442 let project_npmrc = dir.path().join("project.npmrc");
443 let user_npmrc = dir.path().join("user.npmrc");
444
445 fs::write(
446 &project_npmrc,
447 "# Project configuration\n\
448 @corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
449 //us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"old-expired-token\"\n\
450 strict-ssl=true\n",
451 )
452 .unwrap();
453
454 fs::write(
455 &user_npmrc,
456 "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n",
457 )
458 .unwrap();
459
460 let token = "fresh-adc-token-12345";
461 update_npmrc_configs(&project_npmrc, &user_npmrc, token, false).unwrap();
462
463 let project_out = fs::read_to_string(&project_npmrc).unwrap();
464 let user_out = fs::read_to_string(&user_npmrc).unwrap();
465
466 assert!(
467 project_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/")
468 );
469 assert!(project_out.contains("strict-ssl=true"));
470 assert!(!project_out.contains("_authToken"));
471
472 assert!(user_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
473 assert!(user_out.contains(
474 "//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\""
475 ));
476 }
477
478 #[test]
479 fn test_update_npmrc_legacy_password_conversion() {
480 let dir = tempdir().unwrap();
481 let project_npmrc = dir.path().join("project.npmrc");
482 let user_npmrc = dir.path().join("user.npmrc");
483
484 fs::write(
485 &project_npmrc,
486 "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
487 //us-central1-npm.pkg.dev/my-corp/my-npm/:_password=base64pass\n\
488 //us-central1-npm.pkg.dev/my-corp/my-npm/:username=oauth2accesstoken\n",
489 )
490 .unwrap();
491
492 update_npmrc_configs(&project_npmrc, &user_npmrc, "new-token", false).unwrap();
493
494 let project_out = fs::read_to_string(&project_npmrc).unwrap();
495 let user_out = fs::read_to_string(&user_npmrc).unwrap();
496
497 assert!(!project_out.contains("_password"));
498 assert!(!project_out.contains("username=oauth2accesstoken"));
499 assert!(
500 user_out.contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"new-token\"")
501 );
502 }
503
504 #[test]
505 fn test_update_npmrc_single_file_local_credential() {
506 let dir = tempdir().unwrap();
507 let local_npmrc = dir.path().join(".npmrc");
508
509 fs::write(
510 &local_npmrc,
511 "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
512 save-exact=true\n",
513 )
514 .unwrap();
515
516 let token = "local-token-999";
517 update_npmrc_configs(&local_npmrc, &local_npmrc, token, false).unwrap();
518
519 let out = fs::read_to_string(&local_npmrc).unwrap();
520 assert!(out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
521 assert!(out.contains("save-exact=true"));
522 assert!(
523 out.contains(
524 "//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"local-token-999\""
525 )
526 );
527 }
528}