1use crate::error::AuthError;
7use crate::fs::{FileTransaction, resolve};
8use crate::registry::{RegistryPolicy, RegistryUrl};
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 transform_npmrc_contents_with_registries(
199 from_content,
200 to_content,
201 creds,
202 allow_all_domains,
203 same_file,
204 &[],
205 )
206}
207
208pub(crate) fn transform_npmrc_contents_with_registries(
210 from_content: &str,
211 to_content: &str,
212 creds: &str,
213 allow_all_domains: bool,
214 same_file: bool,
215 additional_registries: &[RegistryUrl],
216) -> Result<(String, String), AuthError> {
217 validate_token(creds)?;
218 let parser = NpmrcParser::new(allow_all_domains)?;
219 let mut registries_found = BTreeMap::new();
220 let mut from_lines_out = Vec::new();
221
222 for line in from_content.lines() {
224 match parser.parse_line(line)? {
225 NpmrcConfigType::Registry {
226 scope,
227 registry,
228 raw,
229 } => {
230 registries_found.insert(registry.clone(), scope);
231 from_lines_out.push(raw);
232 }
233 NpmrcConfigType::AuthToken { registry, .. } => {
234 if same_file {
235 } else {
237 log::debug!(
238 "Moving existing _authToken for {registry} from project .npmrc to credential .npmrc"
239 );
240 }
242 }
243 NpmrcConfigType::Password { registry, .. } => {
244 if !same_file {
245 log::debug!("Removing legacy password for {registry} from project .npmrc");
246 }
247 }
248 NpmrcConfigType::Username { .. } => {
249 }
251 NpmrcConfigType::Other(other) => {
252 from_lines_out.push(other);
253 }
254 }
255 }
256
257 if !same_file {
258 for line in to_content.lines() {
259 if let NpmrcConfigType::Registry {
260 scope, registry, ..
261 } = parser.parse_line(line)?
262 {
263 registries_found.entry(registry).or_insert(scope);
264 }
265 }
266 }
267
268 for registry in additional_registries {
269 registries_found
270 .entry(registry.npm_key().to_string())
271 .or_insert(None);
272 }
273
274 if registries_found.is_empty() {
275 return Err(AuthError::Config(
276 "No Artifact Registry configuration found.\n\
277 Ensure your .npmrc contains a registry line such as:\n\
278 @my-scope:registry=https://<region>-npm.pkg.dev/<project>/<repo>/\n\
279 Run `gcloud artifacts print-settings npm` to generate configuration."
280 .to_string(),
281 ));
282 }
283
284 let mut to_lines_out = Vec::new();
286 let mut pending_registries = registries_found.clone();
287
288 if !to_content.is_empty() {
289 for line in to_content.lines() {
290 let parsed = parser.parse_line(line)?;
291 match parsed {
292 NpmrcConfigType::AuthToken { registry, .. } => {
293 if registries_found.contains_key(®istry) {
294 if pending_registries.remove(®istry).is_some() {
295 to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
296 }
297 } else {
298 to_lines_out.push(line.to_string());
299 }
300 }
301 NpmrcConfigType::Password { registry, .. } => {
302 if registries_found.contains_key(®istry) {
303 if pending_registries.remove(®istry).is_some() {
304 to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
305 }
306 } else {
307 to_lines_out.push(line.to_string());
308 }
309 }
310 NpmrcConfigType::Username { registry } => {
311 if !registries_found.contains_key(®istry) {
312 to_lines_out.push(line.to_string());
313 }
314 }
315 _ => {
316 to_lines_out.push(line.to_string());
317 }
318 }
319 }
320 }
321
322 for (registry, _) in pending_registries {
324 log::debug!("Adding auth token for registry {registry}");
325 to_lines_out.push(format!("{registry}:_authToken=\"{creds}\""));
326 }
327
328 let to_output = to_lines_out.join("\n") + "\n";
329 let from_output = from_lines_out.join("\n") + "\n";
330
331 Ok((from_output, to_output))
332}
333
334pub fn update_npmrc_configs(
346 from_path: &Path,
347 to_path: &Path,
348 creds: &str,
349 allow_all_domains: bool,
350) -> Result<(), AuthError> {
351 let from_path = resolve(from_path)?;
352 let to_path = resolve(to_path)?;
353 let same_file = from_path == to_path;
354 let mut transaction = FileTransaction::new(&[from_path.clone(), to_path.clone()])?;
355 let from_content = transaction.contents(&from_path)?.to_owned();
356 let to_content = transaction.contents(&to_path)?.to_owned();
357
358 let (from_output, to_output) = transform_npmrc_contents(
359 &from_content,
360 if same_file {
361 &from_content
362 } else {
363 &to_content
364 },
365 creds,
366 allow_all_domains,
367 same_file,
368 )?;
369
370 transaction.stage(&to_path, &to_output)?;
371 if !same_file && transaction.existed(&from_path)? && from_output != from_content {
372 transaction.stage(&from_path, &from_output)?;
373 }
374 transaction.commit()?;
375 Ok(())
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381 use std::fs;
382 use tempfile::tempdir;
383
384 #[test]
385 fn test_parser_standard_ar() {
386 let parser = NpmrcParser::new(false).unwrap();
387
388 let line = "@my-org:registry=https://us-central1-npm.pkg.dev/my-project/my-repo/";
389 let parsed = parser.parse_line(line).unwrap();
390 match parsed {
391 NpmrcConfigType::Registry {
392 scope, registry, ..
393 } => {
394 assert_eq!(scope.as_deref(), Some("@my-org"));
395 assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
396 }
397 _ => panic!("Expected Registry variant"),
398 }
399 }
400
401 #[test]
402 fn test_parser_unscoped_ar() {
403 let parser = NpmrcParser::new(false).unwrap();
404
405 let line = "registry=https://europe-west1-npm.pkg.dev/google-cloud/demo-repo/";
406 let parsed = parser.parse_line(line).unwrap();
407 match parsed {
408 NpmrcConfigType::Registry {
409 scope, registry, ..
410 } => {
411 assert_eq!(scope, None);
412 assert_eq!(
413 registry,
414 "//europe-west1-npm.pkg.dev/google-cloud/demo-repo/"
415 );
416 }
417 _ => panic!("Expected Registry variant"),
418 }
419 }
420
421 #[test]
422 fn test_parser_existing_auth_token() {
423 let parser = NpmrcParser::new(false).unwrap();
424
425 let line = "//us-central1-npm.pkg.dev/my-project/my-repo/:_authToken=\"ya29.sample-token\"";
426 let parsed = parser.parse_line(line).unwrap();
427 match parsed {
428 NpmrcConfigType::AuthToken { registry, token } => {
429 assert_eq!(registry, "//us-central1-npm.pkg.dev/my-project/my-repo/");
430 assert_eq!(token, "ya29.sample-token");
431 }
432 _ => panic!("Expected AuthToken variant"),
433 }
434 }
435
436 #[test]
437 fn test_in_memory_transform() {
438 let from = "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\nstrict-ssl=true\n";
439 let to = "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n";
440 let token = "fresh-adc-token-12345";
441
442 let (from_out, to_out) = transform_npmrc_contents(from, to, token, false, false).unwrap();
443 assert!(from_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
444 assert!(from_out.contains("strict-ssl=true"));
445 assert!(to_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
446 assert!(
447 to_out
448 .contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\"")
449 );
450 }
451
452 #[test]
453 fn duplicate_legacy_credentials_are_removed() {
454 let source = "@corp:registry=https://us-npm.pkg.dev/project/repo/\n";
455 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";
456 let (_, updated) = transform_npmrc_contents(source, target, "new", false, false).unwrap();
457 assert_eq!(updated.matches(":_authToken=").count(), 1);
458 assert!(!updated.contains("old"));
459 assert!(!updated.contains(":username="));
460 }
461
462 #[test]
463 fn test_update_npmrc_moves_token_to_user_config() {
464 let dir = tempdir().unwrap();
465 let project_npmrc = dir.path().join("project.npmrc");
466 let user_npmrc = dir.path().join("user.npmrc");
467
468 fs::write(
469 &project_npmrc,
470 "# Project configuration\n\
471 @corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
472 //us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"old-expired-token\"\n\
473 strict-ssl=true\n",
474 )
475 .unwrap();
476
477 fs::write(
478 &user_npmrc,
479 "//registry.npmjs.org/:_authToken=\"npm_secret_xyz\"\n",
480 )
481 .unwrap();
482
483 let token = "fresh-adc-token-12345";
484 update_npmrc_configs(&project_npmrc, &user_npmrc, token, false).unwrap();
485
486 let project_out = fs::read_to_string(&project_npmrc).unwrap();
487 let user_out = fs::read_to_string(&user_npmrc).unwrap();
488
489 assert!(project_out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
490 assert!(project_out.contains("strict-ssl=true"));
491 assert!(!project_out.contains("_authToken"));
492
493 assert!(user_out.contains("//registry.npmjs.org/:_authToken=\"npm_secret_xyz\""));
494 assert!(
495 user_out
496 .contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"fresh-adc-token-12345\"")
497 );
498 }
499
500 #[test]
501 fn test_update_npmrc_legacy_password_conversion() {
502 let dir = tempdir().unwrap();
503 let project_npmrc = dir.path().join("project.npmrc");
504 let user_npmrc = dir.path().join("user.npmrc");
505
506 fs::write(
507 &project_npmrc,
508 "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
509 //us-central1-npm.pkg.dev/my-corp/my-npm/:_password=base64pass\n\
510 //us-central1-npm.pkg.dev/my-corp/my-npm/:username=oauth2accesstoken\n",
511 )
512 .unwrap();
513
514 update_npmrc_configs(&project_npmrc, &user_npmrc, "new-token", false).unwrap();
515
516 let project_out = fs::read_to_string(&project_npmrc).unwrap();
517 let user_out = fs::read_to_string(&user_npmrc).unwrap();
518
519 assert!(!project_out.contains("_password"));
520 assert!(!project_out.contains("username=oauth2accesstoken"));
521 assert!(
522 user_out.contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"new-token\"")
523 );
524 }
525
526 #[test]
527 fn test_update_npmrc_single_file_local_credential() {
528 let dir = tempdir().unwrap();
529 let local_npmrc = dir.path().join(".npmrc");
530
531 fs::write(
532 &local_npmrc,
533 "@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/\n\
534 save-exact=true\n",
535 )
536 .unwrap();
537
538 let token = "local-token-999";
539 update_npmrc_configs(&local_npmrc, &local_npmrc, token, false).unwrap();
540
541 let out = fs::read_to_string(&local_npmrc).unwrap();
542 assert!(out.contains("@corp:registry=https://us-central1-npm.pkg.dev/my-corp/my-npm/"));
543 assert!(out.contains("save-exact=true"));
544 assert!(
545 out.contains("//us-central1-npm.pkg.dev/my-corp/my-npm/:_authToken=\"local-token-999\"")
546 );
547 }
548}