From 5b6ee1001c0092576bd1e4de5c8bfdca9698aeca Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Mon, 30 Nov 2026 09:27:57 +0000 Subject: [PATCH] feat: configurable CRAN repository url for R scripts (#12759) * feat: configurable CRAN repository url for R scripts Co-Authored-By: Claude Opus 5.5 * fix: keep mirror credentials out of the R lockfile, resolve operator secret refs Co-Authored-By: Claude Opus 5.5 * fix: mask CRAN mirror credentials in R job logs Co-Authored-By: Claude Opus 5.5 * chore: update ee-repo-ref to 20c54ad02dff7d771a1dbb820e12c57f5f9f6bf4 This commit updates the EE repository reference after PR #1029 was merged in windmill-ee-private. Previous ee-repo-ref: ab2e605929c5895002094f515c24562e03096c32 New ee-repo-ref: 20c54ad02dff7d771a1dbb820e12c57f5f9f6bf4 Automated by sync-ee-ref workflow. --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: windmill-internal-app[bot] --- backend/ee-repo-ref.txt | 2 +- backend/src/main.rs | 8 +- backend/src/monitor.rs | 15 +++ .../windmill-common/src/global_settings.rs | 1 + .../windmill-common/src/instance_config.rs | 3 + backend/windmill-worker/src/r_executor.rs | 119 ++++++++++++++++-- backend/windmill-worker/src/worker.rs | 1 + .../src/lib/components/instanceSettings.ts | 10 ++ 8 files changed, 146 insertions(+), 13 deletions(-) diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index acbad8f6f0..fb746f0ddd 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -c93fbda372440a8c5559fb20d203d0f275d97289 +20c54ad02dff7d771a1dbb820e12c57f5f9f6bf4 diff --git a/backend/src/main.rs b/backend/src/main.rs index 3259094423..f86543261c 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -8,8 +8,9 @@ use anyhow::Context; use monitor::{ flush_pending_log_files_to_object_store, load_base_url, load_otel, - reload_critical_alerts_on_db_oversize, reload_delete_logs_periodically_setting, - reload_indexer_config, reload_instance_python_version_setting, reload_maven_repos_setting, + reload_cran_repo_url_setting, reload_critical_alerts_on_db_oversize, + reload_delete_logs_periodically_setting, reload_indexer_config, + reload_instance_python_version_setting, reload_maven_repos_setting, reload_maven_settings_xml_setting, reload_no_default_maven_setting, reload_nuget_config_setting, reload_powershell_repo_pat_setting, reload_powershell_repo_url_setting, reload_ruby_repos_setting, @@ -2066,6 +2067,9 @@ async fn process_notify_event( MAVEN_SETTINGS_XML_SETTING => reload_maven_settings_xml_setting(conn).await, NO_DEFAULT_MAVEN_SETTING => reload_no_default_maven_setting(conn).await, RUBY_REPOS_SETTING => reload_ruby_repos_setting(conn).await, + windmill_common::global_settings::CRAN_REPO_URL_SETTING => { + reload_cran_repo_url_setting(conn).await + } CARGO_REGISTRIES_SETTING => reload_cargo_registries_setting(conn).await, WORKSPACE_REGISTRIES_SETTING => reload_workspace_registries_setting(conn).await, HUB_API_SECRET_SETTING => reload_hub_api_secret_setting(conn).await, diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index afcec8681a..49a4a590e6 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -788,6 +788,11 @@ pub async fn initial_load( "RUBY_REPOS", windmill_worker::RUBY_REPOS.clone(), ); + pass.option_setting( + gs::CRAN_REPO_URL_SETTING, + "CRAN_REPO_URL", + windmill_worker::CRAN_REPO_URL.clone(), + ); pass.option_setting( gs::CARGO_REGISTRIES_SETTING, "CARGO_REGISTRIES", @@ -3276,6 +3281,16 @@ pub async fn reload_ruby_repos_setting(conn: &Connection) { .await; } +pub async fn reload_cran_repo_url_setting(conn: &Connection) { + reload_option_setting_with_tracing( + conn, + windmill_common::global_settings::CRAN_REPO_URL_SETTING, + "CRAN_REPO_URL", + windmill_worker::CRAN_REPO_URL.clone(), + ) + .await; +} + pub async fn reload_workspace_registries_setting(conn: &Connection) { match load_value_from_global_settings_with_conn( conn, diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index 8d447f2e7a..23d5d5e6a0 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -47,6 +47,7 @@ pub const MAVEN_REPOS_SETTING: &str = "maven_repos"; pub const MAVEN_SETTINGS_XML_SETTING: &str = "maven_settings_xml"; pub const NO_DEFAULT_MAVEN_SETTING: &str = "no_default_maven"; pub const RUBY_REPOS_SETTING: &str = "ruby_repos"; +pub const CRAN_REPO_URL_SETTING: &str = "cran_repo_url"; pub const CARGO_REGISTRIES_SETTING: &str = "cargo_registries"; pub const EXTRA_PIP_INDEX_URL_SETTING: &str = "pip_extra_index_url"; diff --git a/backend/windmill-common/src/instance_config.rs b/backend/windmill-common/src/instance_config.rs index cb4776cc93..d0923a08c6 100644 --- a/backend/windmill-common/src/instance_config.rs +++ b/backend/windmill-common/src/instance_config.rs @@ -339,6 +339,8 @@ pub struct GlobalSettings { #[serde(skip_serializing_if = "Option::is_none")] pub ruby_repos: Option, #[serde(skip_serializing_if = "Option::is_none")] + pub cran_repo_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] pub powershell_repo_url: Option, #[serde(skip_serializing_if = "Option::is_none")] pub powershell_repo_pat: Option, @@ -1216,6 +1218,7 @@ const SENSITIVE_SETTINGS: &[&str] = &[ "npmrc", "maven_repos", "ruby_repos", + "cran_repo_url", "powershell_repo_pat", "workspace_registries", "sandbox_registry_auth", diff --git a/backend/windmill-worker/src/r_executor.rs b/backend/windmill-worker/src/r_executor.rs index 4220feba91..bcf94ba603 100644 --- a/backend/windmill-worker/src/r_executor.rs +++ b/backend/windmill-worker/src/r_executor.rs @@ -10,6 +10,7 @@ use uuid::Uuid; use windmill_common::{ client::AuthedClient, error::Error, + sensitive_log_masks, utils::calculate_hash, worker::{write_file, Connection, RlangAnnotations}, }; @@ -26,11 +27,11 @@ use crate::{ }, get_proxy_envs_for_lang, get_run_proxy_envs, handle_child::{self}, - is_sandboxing_enabled, nsjail_clone_newnet, + is_sandboxing_enabled, nsjail_clone_newnet, read_ee_registry_with_workspace_override, universal_pkg_installer::{ par_install_language_dependencies_seq, DependencyGraph, InstallDeps, RequiredDependency, }, - DISABLE_NUSER, NSJAIL_AVAILABLE, NSJAIL_PATH, PATH_ENV, PROXY_ENVS, R_CACHE_DIR, + CRAN_REPO_URL, DISABLE_NUSER, NSJAIL_AVAILABLE, NSJAIL_PATH, PATH_ENV, PROXY_ENVS, R_CACHE_DIR, TRACING_PROXY_CA_CERT_PATH, WIN_ENVS, }; use windmill_common::scripts::ScriptLang; @@ -47,6 +48,38 @@ lazy_static::lazy_static! { }; } +const DEFAULT_CRAN_REPO_URL: &str = "https://cloud.r-project.org"; + +/// The CRAN mirror configured for this workspace (or instance), if any. +/// +/// renv echoes the full repository URL when a download fails, so credentials in it are +/// registered with the job's log masks before any R process sees the URL. +async fn configured_cran_repo_url(job_id: &Uuid, w_id: &str, conn: &Connection) -> Option { + let repo = read_ee_registry_with_workspace_override( + CRAN_REPO_URL.read().await.clone(), + "cran_repo_url", + "CRAN repository url", + job_id, + w_id, + conn, + ) + .await + .map(|s| s.trim().to_string())?; + if let Ok(parsed) = url::Url::parse(&repo) { + if let Some(password) = parsed.password() { + sensitive_log_masks::register_secret_for_job( + *job_id, + &format!("{}:{}", parsed.username(), password), + ); + sensitive_log_masks::register_secret_for_job(*job_id, password); + } else if !parsed.username().is_empty() { + // A bare userinfo is commonly a token. + sensitive_log_masks::register_secret_for_job(*job_id, parsed.username()); + } + } + Some(repo) +} + const NSJAIL_CONFIG_RUN_R_CONTENT: &str = include_str!("../nsjail/run.r.config.proto"); const NSJAIL_CONFIG_INSTALL_R_CONTENT: &str = include_str!("../nsjail/install.r.config.proto"); @@ -208,8 +241,14 @@ pub async fn resolve<'a>( } } - // Check cache - let req_hash = format!("r-{}", calculate_hash(&packages)); + let custom_repo = configured_cran_repo_url(job_id, w_id, conn).await; + + // A mirror resolves its own versions, so it must not share a cache entry with CRAN. + let req_hash = match &custom_repo { + Some(repo) => format!("r-{}", calculate_hash(&format!("{packages}\n#repo:{repo}"))), + None => format!("r-{}", calculate_hash(&packages)), + }; + let repo_url = custom_repo.as_deref().unwrap_or(DEFAULT_CRAN_REPO_URL); if let Some(db) = conn.as_sql() { if let Some(cached) = sqlx::query_scalar!( "SELECT lockfile FROM pip_resolution_cache WHERE hash = $1", @@ -235,7 +274,7 @@ pub async fn resolve<'a>( // Disable renv's own package cache — Windmill manages its own install cache. let resolve_script = format!( r#"options( - repos = c(CRAN = "https://cloud.r-project.org"), + repos = c(CRAN = "{repo_url}"), renv.verbose = {verbose_r}, renv.config.cache.enabled = FALSE, renv.config.restart.enabled = FALSE, @@ -247,6 +286,7 @@ suppressMessages(renv::install(prompt = FALSE)) suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) "#, verbose_r = if verbose { "TRUE" } else { "FALSE" }, + repo_url = escape_r_double_quoted(repo_url), ); let mut file = File::create(format!("{}/resolve.r", job_dir)).await?; @@ -290,6 +330,9 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) let mut lock_file = File::open(&lock_path).await?; let mut lock = String::new(); lock_file.read_to_string(&mut lock).await?; + if custom_repo.is_some() { + lock = strip_repo_credentials(lock); + } // Cache the lockfile if let Some(db) = conn.as_sql() { @@ -315,6 +358,41 @@ suppressMessages(renv::snapshot(type = "implicit", prompt = FALSE)) Ok(lock) } +/// `renv::snapshot` records the `repos` option in the lockfile, which is stored as the +/// script's lock and readable by anyone who can see the script: credentials in the mirror +/// URL must not reach it. `install` takes the credentialed URL from the setting instead. +fn strip_repo_credentials(lock: String) -> String { + let Ok(mut json) = serde_json::from_str::(&lock) else { + return lock; + }; + let mut changed = false; + if let Some(repos) = json + .get_mut("R") + .and_then(|r| r.get_mut("Repositories")) + .and_then(|r| r.as_array_mut()) + { + for repo in repos { + let Some(url) = repo.get("URL").and_then(|u| u.as_str()) else { + continue; + }; + let Ok(mut parsed) = url::Url::parse(url) else { + continue; + }; + if parsed.username().is_empty() && parsed.password().is_none() { + continue; + } + let _ = parsed.set_username(""); + let _ = parsed.set_password(None); + repo["URL"] = serde_json::Value::String(parsed.to_string()); + changed = true; + } + } + if !changed { + return lock; + } + serde_json::to_string_pretty(&json).unwrap_or(lock) +} + struct RenvPackage { name: String, version: String, @@ -401,7 +479,7 @@ fn parse_renv_lock(lockfile: &str) -> Result, Error> { let repo_url = repo_urls .get(repo_name) .cloned() - .unwrap_or_else(|| "https://cloud.r-project.org".to_string()); + .unwrap_or_else(|| DEFAULT_CRAN_REPO_URL.to_string()); let mut dependencies = vec![]; if let Some(imports) = pkg.get("Imports").and_then(|v| v.as_array()) { @@ -440,11 +518,15 @@ async fn install<'a>( return Ok(lib_path); } + // The configured mirror wins over the URL recorded in the lockfile, so a lockfile + // resolved against CRAN still installs on an instance that can only reach the mirror. + let custom_repo = + configured_cran_repo_url(&args.job.id, &args.job.workspace_id, args.conn).await; + #[derive(Clone, Debug)] struct RPackagePayload { pkg: String, version: String, - #[allow(dead_code)] repo_url: String, } @@ -467,7 +549,9 @@ async fn install<'a>( custom_payload: RPackagePayload { pkg: renv_pkg.name.clone(), version: renv_pkg.version.clone(), - repo_url: renv_pkg.repo_url.clone(), + repo_url: custom_repo + .clone() + .unwrap_or_else(|| renv_pkg.repo_url.clone()), }, }, renv_pkg.dependencies.clone(), @@ -535,12 +619,13 @@ async fn install<'a>( .args(&[ "-e", &format!( - r#"options(renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = "{lib}", dependencies = FALSE)"#, + r#"options(repos = c(CRAN = "{repo}"), renv.verbose = {verbose_r}, renv.config.install.verbose = {install_verbose_r}, renv.config.restart.enabled = FALSE); renv::install("{pkg}@{version}", library = "{lib}", dependencies = FALSE)"#, verbose_r = verbose_r, install_verbose_r = install_verbose_r, pkg = escape_r_double_quoted(&dependency.custom_payload.pkg), version = escape_r_double_quoted(&dependency.custom_payload.version), lib = escape_r_double_quoted(&install_lib), + repo = escape_r_double_quoted(&dependency.custom_payload.repo_url), ), // install.packages fallback (no version pinning): // &format!( @@ -791,7 +876,9 @@ tryCatch({{ #[cfg(test)] mod tests { - use super::{escape_r_double_quoted, parse_renv_lock, validate_renv_package}; + use super::{ + escape_r_double_quoted, parse_renv_lock, strip_repo_credentials, validate_renv_package, + }; #[test] fn test_validate_renv_package_accepts_real() { @@ -849,4 +936,16 @@ mod tests { assert_eq!(pkgs.len(), 1); assert_eq!(pkgs[0].name, "ggplot2"); } + + #[test] + fn test_strip_repo_credentials() { + let lock = r#"{"R":{"Version":"4.4.1","Repositories":[{"Name":"CRAN","URL":"https://u:s3cret@nexus.example.com/repository/cran"}]},"Packages":{}}"#; + let stripped = strip_repo_credentials(lock.to_string()); + assert!(!stripped.contains("s3cret") && !stripped.contains("u:")); + assert!(stripped.contains("https://nexus.example.com/repository/cran")); + + let clean = + r#"{"R":{"Repositories":[{"Name":"CRAN","URL":"https://cloud.r-project.org"}]}}"#; + assert_eq!(strip_repo_credentials(clean.to_string()), clean); + } } diff --git a/backend/windmill-worker/src/worker.rs b/backend/windmill-worker/src/worker.rs index cfddc5aa0c..eb0d6df8c5 100644 --- a/backend/windmill-worker/src/worker.rs +++ b/backend/windmill-worker/src/worker.rs @@ -711,6 +711,7 @@ lazy_static::lazy_static! { .and_then(|x| x.parse::().ok()) .unwrap_or(false)); pub static ref RUBY_REPOS: Arc>>> = Arc::new(RwLock::new(None)); + pub static ref CRAN_REPO_URL: Arc>> = Arc::new(RwLock::new(None)); pub static ref CARGO_REGISTRIES: Arc>> = Arc::new(RwLock::new(None)); pub static ref WORKSPACE_REGISTRIES: Arc>> = Arc::new(RwLock::new(None)); diff --git a/frontend/src/lib/components/instanceSettings.ts b/frontend/src/lib/components/instanceSettings.ts index 14fa956dd5..4a647d7103 100644 --- a/frontend/src/lib/components/instanceSettings.ts +++ b/frontend/src/lib/components/instanceSettings.ts @@ -1170,6 +1170,16 @@ export const settings: Record = { storage: 'setting', ee_only: '' }, + { + label: 'CRAN repository URL', + description: + 'CRAN mirror R scripts resolve and install packages from, instead of https://cloud.r-project.org (e.g. a Nexus or Posit Package Manager proxy). Also settable with the CRAN_REPO_URL environment variable', + key: 'cran_repo_url', + fieldType: 'password', + placeholder: 'https://user:password@nexus.foo.com/repository/cran/', + storage: 'setting', + ee_only: '' + }, { label: 'Cargo registries', description: 'Write a .cargo/config.toml to set custom Cargo registries and credentials',