From 65d567fec6468dcbb2d52528b4594fe4a0c26b59 Mon Sep 17 00:00:00 2001 From: Ruben Fiszel Date: Sun, 29 Nov 2026 12:44:12 +0000 Subject: [PATCH] fix: tighten generated SQL names, flow input lookup and app install steps (#12748) * fix: refuse database manager names that would break the generated SQL * fix: read a flow argument directly only for a plain argument name * fix: drop the hook's delivery URL from GitHub webhook payloads * fix: use a pinned non-redirecting client for Nextcloud servers a connection names * fix: build raw apps without their bunfig.toml or the job's own env vars * fix(cli): skip lifecycle scripts when installing app dependencies * fix(cli): keep resources stored under a dbt project folder out of its bundle * fix: keep only the registry settings of a raw app's bunfig.toml when building it * feat: allow private Nextcloud servers listed in ALLOW_PRIVATE_NEXTCLOUD_URLS --- backend/windmill-api/src/apps_raw_bundler.ts | 70 +++++++++- backend/windmill-common/src/query_builders.rs | 78 ++++++++++- backend/windmill-jseval/src/lib.rs | 124 +++++++++++++++++- .../src/github/external.rs | 10 +- backend/windmill-native-triggers/src/lib.rs | 106 +++++++++++++-- cli/src/commands/app/bundle.ts | 12 +- cli/src/commands/script/script.ts | 13 ++ cli/test/dbt_module_tracker_unit.test.ts | 15 +++ 8 files changed, 404 insertions(+), 24 deletions(-) diff --git a/backend/windmill-api/src/apps_raw_bundler.ts b/backend/windmill-api/src/apps_raw_bundler.ts index 78bcfdf532..5bf68f372f 100644 --- a/backend/windmill-api/src/apps_raw_bundler.ts +++ b/backend/windmill-api/src/apps_raw_bundler.ts @@ -53,7 +53,19 @@ export async function main( await fs.mkdir(path.dirname(abs), { recursive: true }) await fs.writeFile(abs, content) } + // bun reads `bunfig.toml` from the build directory, and some of its settings (install + // scanners, preloads, plugins) load modules from the app. The build is the deployer's job, + // and the app's files may have been written by someone else, so only the settings that say + // where packages come from are kept. + const bunfig = path.join(dir, 'bunfig.toml') for (const [p, content] of Object.entries(files ?? {})) { + if (target(p) === bunfig) { + const kept = registryOnlyBunfig(content) + if (kept !== undefined) { + await write(p, kept) + } + continue + } await write(p, content) } // `ui/` next to the app is where `wmill app bundle` looks for the shared UI. @@ -66,8 +78,13 @@ export async function main( // Piped rather than inherited so the output can go in the error too, then // echoed either way — the job's log is where someone looks to see what the // build did. + // The install and the build read the app's files (an `.npmrc` expands `${VAR}`), so they + // get the worker's environment without the job's own credentials. + const env = Object.fromEntries( + Object.entries(process.env).filter(([k]) => !k.startsWith('WM_')) + ) const spawn = (argv: string[]) => { - const proc = Bun.spawnSync(argv, { cwd: dir, stdout: 'pipe', stderr: 'pipe' }) + const proc = Bun.spawnSync(argv, { cwd: dir, env, stdout: 'pipe', stderr: 'pipe' }) const output = proc.stdout.toString() + proc.stderr.toString() console.log(output) return { ok: proc.exitCode === 0, output } @@ -180,3 +197,54 @@ export async function main( const gz = (s: string) => Buffer.from(Bun.gzipSync(Buffer.from(s, 'utf8'))).toString('base64') return { js_gz: gz(js), css_gz: gz(css), triggerables_v2 } } + +/** `[install]` keys that only say where packages come from and how to resolve them. */ +const BUNFIG_INSTALL_KEYS = [ + 'registry', + 'scopes', + 'cafile', + 'ca', + 'exact', + 'optional', + 'dev', + 'peer', + 'production', + 'frozenLockfile', + 'saveTextLockfile', + 'linkWorkspacePackages' +] + +/** The app's bunfig reduced to the allowed `[install]` keys, or undefined if none is set. */ +function registryOnlyBunfig(content: string): string | undefined { + let parsed: any + try { + parsed = Bun.TOML.parse(content) + } catch (e) { + throw new Error(`the app's bunfig.toml is not valid TOML: ${e}`) + } + const install = parsed?.install + if (install === null || typeof install !== 'object') { + console.log("ignoring the app's bunfig.toml: it has no [install] settings") + return undefined + } + const lines = Object.keys(install) + .filter((k) => BUNFIG_INSTALL_KEYS.includes(k)) + .map((k) => `${JSON.stringify(k)} = ${tomlValue(install[k])}`) + const dropped = Object.keys(parsed).filter((k) => k !== 'install') + dropped.push(...Object.keys(install).filter((k) => !BUNFIG_INSTALL_KEYS.includes(k))) + if (dropped.length > 0) { + console.log(`ignoring bunfig.toml settings: ${dropped.join(', ')}`) + } + return lines.length > 0 ? `[install]\n${lines.join('\n')}\n` : undefined +} + +function tomlValue(v: unknown): string { + if (typeof v === 'string') return JSON.stringify(v) + if (typeof v === 'number' || typeof v === 'boolean') return String(v) + if (Array.isArray(v)) return `[${v.map(tomlValue).join(', ')}]` + if (v !== null && typeof v === 'object') { + const entries = Object.entries(v).map(([k, x]) => `${JSON.stringify(k)} = ${tomlValue(x)}`) + return `{ ${entries.join(', ')} }` + } + throw new Error(`unsupported bunfig.toml value: ${JSON.stringify(v)}`) +} diff --git a/backend/windmill-common/src/query_builders.rs b/backend/windmill-common/src/query_builders.rs index 145228abdf..59d1a7379e 100644 --- a/backend/windmill-common/src/query_builders.rs +++ b/backend/windmill-common/src/query_builders.rs @@ -442,7 +442,37 @@ pub fn try_expand_internal_db_query( _ => Err(format!("Unknown WM_INTERNAL_DB operation: {}", op)), }; - Some(result) + // The SQL executors replace `%%WM_*%%` contextual variables anywhere in the script, quoted + // or not, so a table, column or type name spelling one would receive the viewer's value. + Some(result.and_then(|expanded| { + if expanded.code.contains("%%WM_") { + Err("Names containing `%%WM_` are not supported by the database manager".to_string()) + } else { + Ok(expanded) + } + })) +} + +/// Column names and types are written into `-- $1 name (type)` parameter declarations, which +/// a line break would end, turning the rest of the name into script lines. +fn check_param_columns<'a>( + columns: impl IntoIterator, +) -> Result<(), String> { + for (field, datatype) in columns { + if field.chars().chain(datatype.chars()).any(char::is_control) { + return Err(format!( + "Column {field:?} of type {datatype:?}: names and types containing control \ + characters are not supported by the database manager" + )); + } + } + Ok(()) +} + +fn column_def_pairs(columns: &[ColumnDef]) -> impl Iterator { + columns + .iter() + .map(|c| (c.field.as_str(), c.datatype.as_str())) } impl ExpandedQuery { @@ -542,6 +572,7 @@ fn pk_columns_or_all(columns: &[ColumnDef]) -> Vec { fn expand_delete(json_str: &str, db_type: DbType) -> Result { let payload: DeletePayload = serde_json::from_str(json_str).map_err(|e| format!("Invalid DELETE payload: {}", e))?; + check_param_columns(column_def_pairs(&payload.columns))?; let where_columns = pk_columns_or_all(&payload.columns); let query = make_delete_query(&payload.table, &where_columns, db_type); @@ -551,6 +582,7 @@ fn expand_delete(json_str: &str, db_type: DbType) -> Result { fn expand_insert(json_str: &str, db_type: DbType) -> Result { let payload: InsertPayload = serde_json::from_str(json_str).map_err(|e| format!("Invalid INSERT payload: {}", e))?; + check_param_columns(column_def_pairs(&payload.columns))?; let query = make_insert_query(&payload.table, &payload.columns, db_type)?; Ok(maybe_wrap_ducklake(query, payload.ducklake.as_deref())) @@ -559,6 +591,10 @@ fn expand_insert(json_str: &str, db_type: DbType) -> Result { fn expand_update(json_str: &str, db_type: DbType) -> Result { let payload: UpdatePayload = serde_json::from_str(json_str).map_err(|e| format!("Invalid UPDATE payload: {}", e))?; + check_param_columns(column_def_pairs(&payload.columns).chain([( + payload.column.field.as_str(), + payload.column.datatype.as_str(), + )]))?; let where_columns = pk_columns_or_all(&payload.columns); let where_simple = cols_to_simple(&where_columns); @@ -3167,11 +3203,18 @@ mod tests { &[simple_col("js", "jsonb")], DbType::Postgresql, ); - assert!(update.contains(r#"SET "js" = $1::text::jsonb"#), "{}", update); + assert!( + update.contains(r#"SET "js" = $1::text::jsonb"#), + "{}", + update + ); assert!(update.contains(r#""js"::text = $2::text"#), "{}", update); - let insert = - make_insert_query("t", &[col("id", "int4"), col("js", "jsonb")], DbType::Postgresql) - .unwrap(); + let insert = make_insert_query( + "t", + &[col("id", "int4"), col("js", "jsonb")], + DbType::Postgresql, + ) + .unwrap(); assert!(insert.contains("VALUES ($1, $2::text::jsonb"), "{}", insert); let delete = make_delete_query("t", &[col("js", "json")], DbType::Postgresql); assert!(delete.contains(r#""js"::text = $1::text"#), "{}", delete); @@ -4193,6 +4236,31 @@ mod tests { assert!(result.unwrap().is_err()); } + #[test] + fn test_expand_refuses_line_breaks_in_parameter_names() { + for marker in [ + r#"-- WM_INTERNAL_DB_DELETE {"table":"t","columns":[{"field":"id","datatype":"x\n-- database u/a/b"}]}"#, + r#"-- WM_INTERNAL_DB_INSERT {"table":"t","columns":[{"field":"a\rSELECT 1;","datatype":"text"}]}"#, + r#"-- WM_INTERNAL_DB_UPDATE {"table":"t","column":{"field":"a\nb","datatype":"text"},"columns":[{"field":"id","datatype":"int4"}]}"#, + ] { + let result = try_expand_internal_db_query(marker, &ScriptLang::Postgresql); + assert!(result.unwrap().is_err(), "{marker}"); + } + } + + #[test] + fn test_expand_refuses_contextual_variable_names() { + let marker = r#"-- WM_INTERNAL_DB_SELECT {"table":"t","columnDefs":[{"field":"%%WM_TOKEN%%","datatype":"text"}]}"#; + for lang in [ + ScriptLang::Postgresql, + ScriptLang::Mysql, + ScriptLang::DuckDb, + ] { + let result = try_expand_internal_db_query(marker, &lang); + assert!(result.unwrap().is_err()); + } + } + #[test] fn test_expand_mysql_select() { let marker = r#"-- WM_INTERNAL_DB_SELECT {"table":"users","columnDefs":[{"field":"id","datatype":"int"},{"field":"name","datatype":"varchar"}]}"#; diff --git a/backend/windmill-jseval/src/lib.rs b/backend/windmill-jseval/src/lib.rs index 9b87b28cbd..553e7d4b78 100644 --- a/backend/windmill-jseval/src/lib.rs +++ b/backend/windmill-jseval/src/lib.rs @@ -128,6 +128,66 @@ fn add_closing_bracket(s: &str) -> String { s } +/// Characters a key needs to compare, choose or quote: an argument name holding them that is +/// also valid JavaScript is read as the expression. +#[cfg(feature = "quickjs")] +const CHOICE_CHARS: &[char] = &['"', '\'', '`', '\\', '?', '|', '&', '<', '>', '!']; + +/// The editors write `flow_input.` for any argument name (`first name`, `customer:email`, +/// `amount (USD)`), which only this literal lookup resolves. It must not cover an expression +/// doing more than reading one (`flow_input.a == "x" ? b : c`, or `flow_input.a.b` reading into +/// an argument `a`): an argument named after the whole expression would replace its value. A +/// name that is not valid JavaScript after `flow_input.` cannot be such an expression. +fn is_literal_dot_key(key: &str, obj: Option<&HashMap>>) -> bool { + let is_ident = |c: char| c.is_alphanumeric() || matches!(c, '_' | '$'); + if key.is_empty() { + return false; + } + if key.chars().all(is_ident) { + return true; + } + let (leading_name, rest) = key.split_at(key.find(|c: char| !is_ident(c)).unwrap_or(key.len())); + let reads_into_argument = + rest.starts_with('.') && obj.is_some_and(|obj| obj.contains_key(leading_name)); + #[cfg(feature = "quickjs")] + { + if !parses_as_expression(&format!("{FLOW_INPUT_PREFIX}.{key}")) { + return true; + } + !reads_into_argument && !key.contains(CHOICE_CHARS) && !key.contains("==") + } + #[cfg(not(feature = "quickjs"))] + { + const EXPRESSION_CHARS: &[char] = &[ + '"', '\'', '`', '\\', '?', ':', '(', ')', '[', ']', '{', '}', '=', '!', '<', '>', '|', + '&', ',', ';', + ]; + !key.contains(EXPRESSION_CHARS) && !reads_into_argument + } +} + +/// Whether `expr` compiles in either shape the evaluator runs it in: returned from an async +/// function, or as its body. Compiled as a module that is never evaluated, so nothing in it +/// runs; a failure to set up the check counts as compiling, the stricter answer. +#[cfg(feature = "quickjs")] +fn parses_as_expression(expr: &str) -> bool { + let Ok(runtime) = rquickjs::Runtime::new() else { + return true; + }; + let Ok(context) = rquickjs::Context::full(&runtime) else { + return true; + }; + // The line breaks keep a `//` in `expr` from commenting out the rest of the wrapper. + [ + format!("(async function() {{ return {expr}\n; }});"), + format!("(async function() {{ {expr}\n }});"), + ] + .into_iter() + .any(|source| { + context.with(|ctx| rquickjs::Module::declare(ctx, "flow_input_key", source).is_ok()) + }) +} + pub fn try_exact_property_access( expr: &str, flow_input: Option<&mappable_rc::Marc>>>, @@ -149,7 +209,7 @@ pub fn try_exact_property_access( let suffix = &expr[access_pattern_pos..]; let maybe_key_name = if suffix.starts_with(DOT_PATTERN) { let key_name_pos = DOT_PATTERN.len(); - Some(&suffix[key_name_pos..]) + Some(&suffix[key_name_pos..]).filter(|key| is_literal_dot_key(key, obj)) } else if suffix.starts_with(START_BRACKET_PATTERN) { let key_name_pos = START_BRACKET_PATTERN.len(); let suffix = &suffix[key_name_pos..]; @@ -161,7 +221,7 @@ pub fn try_exact_property_access( let end_key_name_pos = expr.len() - END_BRACKET_PATTERN.len(); &expr[start_key_name_pos..end_key_name_pos] }) - .filter(|s| s.len() > 0); + .filter(|s| s.len() > 0 && !s.contains(['"', '\\'])); flow_arg_name } else { None @@ -1347,6 +1407,62 @@ mod tests { assert_eq!(result.unwrap().get(), "\"production\""); } + #[test] + fn test_try_exact_property_access_only_reads_one_argument() { + let expr_key = r#"region == "eu" ? "a" : "b""#; + let bracket_key = r#"x"] || flow_input["y"#; + let mut fi = HashMap::new(); + for key in [ + expr_key, + bracket_key, + "first name", + "my-arg", + "customer.email", + "pinned", + "pinned.field", + "first", + "customer:email", + "amount (USD)", + "a=b", + "amount", + "my", + ] { + fi.insert(key.to_string(), to_raw_value(&json!("argument"))); + } + let fi = mappable_rc::Marc::new(fi); + + for expr in [ + format!("flow_input.{expr_key}"), + format!("flow_input[\"{bracket_key}\"]"), + "flow_input.pinned.field".to_string(), + ] { + assert!(try_exact_property_access(&expr, Some(&fi), None).is_none()); + } + for expr in [ + "flow_input.first name", + "flow_input.my-arg", + "flow_input.customer.email", + "flow_input.customer:email", + "flow_input.amount (USD)", + "flow_input.a=b", + ] { + assert!( + try_exact_property_access(expr, Some(&fi), None).is_some(), + "{expr}" + ); + } + } + + #[test] + fn test_parses_as_expression() { + assert!(parses_as_expression( + r#"flow_input.region == "eu" ? "a" : "b""# + )); + assert!(parses_as_expression("flow_input.amount (USD)")); + assert!(!parses_as_expression("flow_input.customer:email")); + assert!(!parses_as_expression("flow_input.first name")); + } + #[test] fn test_try_exact_property_access_missing_key() { let fi = mappable_rc::Marc::new(HashMap::new()); @@ -3145,7 +3261,9 @@ mod tests { Some(deadline), ) .await; - let err = err.expect_err("an endless script must be interrupted").to_string(); + let err = err + .expect_err("an endless script must be interrupted") + .to_string(); assert!(err.contains("took too long"), "unexpected error: {err}"); } diff --git a/backend/windmill-native-triggers/src/github/external.rs b/backend/windmill-native-triggers/src/github/external.rs index 6e34154df3..51c705cf29 100644 --- a/backend/windmill-native-triggers/src/github/external.rs +++ b/backend/windmill-native-triggers/src/github/external.rs @@ -302,7 +302,15 @@ impl External for GitHub { .cloned() .unwrap_or_default(); - let payload: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); + let mut payload: serde_json::Value = serde_json::from_str(&body).unwrap_or_default(); + // GitHub echoes the hook's own delivery URL (ping and meta events), which carries the + // token Windmill registered for it; the run's arguments are readable by every viewer. + if let Some(config) = payload + .pointer_mut("/hook/config") + .and_then(|config| config.as_object_mut()) + { + config.remove("url"); + } args.insert( "event".to_string(), diff --git a/backend/windmill-native-triggers/src/lib.rs b/backend/windmill-native-triggers/src/lib.rs index 453884e8d5..7e19012b28 100644 --- a/backend/windmill-native-triggers/src/lib.rs +++ b/backend/windmill-native-triggers/src/lib.rs @@ -425,8 +425,10 @@ pub trait External: Send + Sync + 'static { Some(connection_path), ) .await?; + let client = client_for(&oauth_config, url, Self::DISPLAY_NAME).await?; let result = make_http_request( + &client, url, method.clone(), headers.clone(), @@ -449,17 +451,17 @@ pub trait External: Send + Sync + 'static { let access_token = refresh_connection(db, workspace_id, &oauth_config) .await - .map_err(|f| { - self.external_error( - f.rejected.then_some(StatusCode::UNAUTHORIZED), - format!( - "the stored credentials could not be refreshed: {}", - f.message - ), - ) - })?; + .map_err(|f| { + self.external_error( + f.rejected.then_some(StatusCode::UNAUTHORIZED), + format!( + "the stored credentials could not be refreshed: {}", + f.message + ), + ) + })?; - make_http_request(url, method, headers, body.as_ref(), &access_token) + make_http_request(&client, url, method, headers, body.as_ref(), &access_token) .await .map_err(|e| self.external_api_error(e)) } @@ -590,16 +592,71 @@ pub struct OAuthConfig { /// own `baseUrl` belongs to. #[serde(default)] pub managed: bool, + /// `base_url` is the server an admin configured for the workspace's or the instance's client. + #[serde(default)] + pub base_url_configured: bool, +} + +const ALLOW_PRIVATE_NEXTCLOUD_URLS_ENV: &str = "ALLOW_PRIVATE_NEXTCLOUD_URLS"; + +lazy_static::lazy_static! { + /// Private Nextcloud servers a connection's resource may name, as a host, host:port or + /// CIDR list (`true` for every private host), like the other `ALLOW_PRIVATE_*` settings. + static ref ALLOW_PRIVATE_NEXTCLOUD_URLS: windmill_common::ssrf::PrivateHostAllowance = + windmill_common::ssrf::PrivateHostAllowance::from_env(ALLOW_PRIVATE_NEXTCLOUD_URLS_ENV); +} + +/// The client for a call to `url`. A server only a connection's resource names may be anyone's +/// choice, so it must be public or allowed by `ALLOW_PRIVATE_NEXTCLOUD_URLS`, is connected to at +/// the address that was checked, and may not redirect elsewhere. The server an admin configured +/// as the client's needs neither. +async fn client_for( + oauth_config: &OAuthConfig, + url: &str, + display_name: &str, +) -> Result> { + if oauth_config.base_url.is_empty() || oauth_config.base_url_configured { + return Ok(std::borrow::Cow::Borrowed(&*HTTP_CLIENT)); + } + let target = + windmill_common::ssrf::validate_url_for_ssrf_allowing(url, &ALLOW_PRIVATE_NEXTCLOUD_URLS) + .await + .map_err(|e| { + let hint = match e { + windmill_common::ssrf::SsrfValidationError::Private { .. } => format!( + " To use a server on a private network, configure it as the \ + {display_name} integration's server, or add its host (host, host:port \ + or CIDR range) to the comma-separated {ALLOW_PRIVATE_NEXTCLOUD_URLS_ENV} \ + environment variable." + ), + _ => String::new(), + }; + Error::BadRequest(format!( + "The {display_name} server {} cannot be used: {e}.{hint}", + oauth_config.base_url + )) + })?; + let client = target + .apply_dns_pinning(windmill_common::utils::configure_client( + reqwest::ClientBuilder::new(), + )) + .user_agent("windmill/beta") + .redirect(reqwest::redirect::Policy::none()) + .timeout(std::time::Duration::from_secs(20)) + .connect_timeout(std::time::Duration::from_secs(10)) + .build() + .map_err(|e| Error::internal_err(format!("building the {display_name} client: {e}")))?; + Ok(std::borrow::Cow::Owned(client)) } pub async fn make_http_request( + client: &reqwest::Client, url: &str, method: Method, headers: Option>, body: Option<&B>, access_token: &str, ) -> std::result::Result { - let client = &*HTTP_CLIENT; let mut request = client.request(method, url); request = request @@ -781,6 +838,30 @@ pub(crate) fn instance_base_url(entry: &serde_json::Value) -> String { } } +/// Whether `base_url` is the server of the workspace's or the instance's client, both set by an +/// admin, rather than one a connection's resource names. +async fn is_admin_configured_base_url( + db: &DB, + workspace_id: &str, + service_name: ServiceName, + base_url: &str, +) -> Result { + let base_url = base_url.trim_end_matches('/'); + let same = |url: &str| url.trim_end_matches('/') == base_url; + // No integration (or failing to read it) leaves the server to the stricter check. + if let Ok(integration) = get_workspace_integration(db, workspace_id, service_name).await { + if integration.oauth_data["base_url"] + .as_str() + .is_some_and(same) + { + return Ok(true); + } + } + Ok(instance_oauth_entry(db, service_name) + .await? + .is_some_and(|entry| same(&instance_base_url(&entry)))) +} + /// Assemble the credentials of one connection: the resource of the service's type at /// `connection_path` and the token variable at the same path. /// @@ -857,9 +938,12 @@ pub async fn decrypt_oauth_data( .unwrap_or_default(), _ => String::new(), }; + let base_url_configured = !base_url.is_empty() + && is_admin_configured_base_url(db, workspace_id, service_name, &base_url).await?; let assembled = json!({ "base_url": base_url, + "base_url_configured": base_url_configured, "access_token": access_token, "refresh_token": row.refresh_token, "connection_path": connection_path, diff --git a/cli/src/commands/app/bundle.ts b/cli/src/commands/app/bundle.ts index f99aba58a7..3e4443bcb5 100644 --- a/cli/src/commands/app/bundle.ts +++ b/cli/src/commands/app/bundle.ts @@ -268,7 +268,9 @@ export async function createFrameworkPlugins( /** * Ensures node_modules exists in the specified directory - * Runs npm install if node_modules is missing + * Runs npm install if node_modules is missing, without lifecycle scripts: the + * app's package.json may come from a sync pull of someone else's app. An app + * whose dependencies need their scripts can run `npm install` itself first. * @param appDir Directory to check for node_modules (defaults to entry point directory) */ export async function ensureNodeModules(appDir?: string): Promise { @@ -276,9 +278,13 @@ export async function ensureNodeModules(appDir?: string): Promise { const nodeModulesPath = path.join(targetDir, "node_modules"); if (!fs.existsSync(nodeModulesPath)) { - log.info(colors.yellow("📦 node_modules not found, running npm install...")); + log.info( + colors.yellow( + "📦 node_modules not found, running npm install --ignore-scripts..." + ) + ); const code = await new Promise((resolve, reject) => { - const npmInstall = spawn("npm", ["install"], { + const npmInstall = spawn("npm", ["install", "--ignore-scripts"], { cwd: targetDir, stdio: "inherit", shell: true, diff --git a/cli/src/commands/script/script.ts b/cli/src/commands/script/script.ts index 28f7ab588c..bd3dd588f4 100644 --- a/cli/src/commands/script/script.ts +++ b/cli/src/commands/script/script.ts @@ -845,6 +845,19 @@ export async function readModulesFromDisk( const relPath = relPrefix ? relPrefix + "/" + entry.name : entry.name; const isTopLevel = relPrefix === ""; + // A resource whose path lies under the project's folder is written there by a + // pull, but it is its own item, possibly someone else's: not a project file. + if ( + verbatim && + (entry.isDirectory() + ? entry.name.endsWith(".fileset") + : isFileResource(entry.name) || /\.resource\.(json|ya?ml)$/.test(entry.name)) + ) { + log.warn( + `Skipping ${relPath}: a resource stored under the dbt project's folder is not part of the project`, + ); + continue; + } if (entry.isDirectory()) { // A configured `target-path` may be nested (`build/target`), so the // comparison is on the project-relative path, not the entry name. diff --git a/cli/test/dbt_module_tracker_unit.test.ts b/cli/test/dbt_module_tracker_unit.test.ts index 90abee18ae..c587cb9b62 100644 --- a/cli/test/dbt_module_tracker_unit.test.ts +++ b/cli/test/dbt_module_tracker_unit.test.ts @@ -142,4 +142,19 @@ describe("buildTracker with a dbt project", () => { expect(isDbtGeneratedPath("f/analytics/analytics__dbt/.env")).toBe(true); expect(isDbtGeneratedPath("f/analytics/analytics__dbt/models/stg.sql")).toBe(false); }); + + test("a resource stored under the project folder is not bundled", async () => { + const project = path.join(dir, "f/analytics/analytics__dbt"); + fs.mkdirSync(path.join(project, "models/notes.fileset"), { recursive: true }); + fs.writeFileSync(path.join(project, "models/notes.fileset/copy.sql"), "select 2"); + fs.writeFileSync(path.join(project, "models/notes.resource.yaml"), "value: {}\n"); + fs.writeFileSync(path.join(project, "models/q.resource.file.sql"), "select 3"); + fs.writeFileSync(path.join(project, "models/stg.sql"), "select 1"); + + const modules = await readModulesFromDisk(project, undefined, false, true); + expect(Object.keys(modules ?? {}).sort()).toEqual([ + "dbt_project.yml", + "models/stg.sql", + ]); + }); });