Compare commits

..

3 Commits

Author SHA1 Message Date
Admin
ba46a10b3f remove substitute_ee.ps1 2025-06-26 02:30:44 +00:00
Admin
21a5b250ae fix: add windows paths to uv install to find git/ssh 2025-06-26 02:29:36 +00:00
claude[bot]
d933648d36 fix: optionally enable CSP headers (#6033)
* feat: add optional CSP headers when ENABLE_CSP_HEADERS is set

- Add middleware to conditionally set Content-Security-Policy headers
- Check for ENABLE_CSP_HEADERS environment variable  
- Apply secure default CSP policy suitable for web applications
- Follows existing middleware patterns in codebase

Resolves #6031

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com>

* perf: optimize CSP headers with lazy_static and add configurability

- Cache CSP_ENABLED and CSP_POLICY using lazy_static to avoid env var lookups on every request
- Add comprehensive documentation to add_csp_headers middleware function
- Make CSP policy configurable via CSP_POLICY environment variable
- Maintain backward compatibility with secure default policy
- Implement proper error handling for custom CSP policy values

Co-authored-by: Alexander Petric &lt;alpetric@users.noreply.github.com&gt;

* refactor: conditionally add CSP middleware layer instead of NO-OP

- Use .option_layer() to only add CSP middleware when ENABLE_CSP_HEADERS is set
- Remove runtime conditional check from add_csp_headers function
- Improve performance by avoiding unnecessary middleware execution when disabled

Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com>

* refactor: conditionally add CSP middleware layer instead of NO-OP

Remove CSP_ENABLED variable and instead check if CSP_POLICY is not empty.
This eliminates the need for a separate enable flag and simplifies the logic
to just check if a meaningful CSP policy is configured.

- Remove CSP_ENABLED lazy_static variable
- Simplify CSP_POLICY to use unwrap_or_default()
- Update conditional middleware logic to check !CSP_POLICY.is_empty()
- Update documentation to reflect new behavior

Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com>

* refactor: conditionally add CSP middleware layer instead of NO-OP

Move CSP headers from general middleware stack to static assets only.
CSP headers are only relevant for browsers consuming static content,
not for API endpoints.

Changes:
- Add CSP headers directly to static asset responses in serve_path()
- Remove CSP middleware from general middleware stack
- Remove unused add_csp_headers middleware function
- Maintain same CSP_POLICY environment variable configuration

Co-authored-by: Alexander Petric <alpetric@users.noreply.github.com>

* fix: conditionally compile CSP header imports with static_frontend feature

Fixes unused import errors by wrapping HeaderValue and CSP_POLICY imports 
with #[cfg(feature = "static_frontend")] to match their usage context.

Co-authored-by: Alexander Petric <alpetric@users.noreply.github.com>

* refactor: move CSP lazy static block to static_assets.rs

- Move CSP_POLICY lazy static from lib.rs to static_assets.rs for better encapsulation
- Remove crate-level import since CSP_POLICY is now local to static_assets module
- Maintain same functionality with proper feature gating for static_frontend

Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com>

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com>
Co-authored-by: Alexander Petric <alpetric@users.noreply.github.com>
2025-06-25 21:15:22 +02:00
3 changed files with 73 additions and 8 deletions

View File

@@ -238,6 +238,7 @@ lazy_static::lazy_static! {
}
// Compliance with cloud events spec.
pub async fn add_webhook_allowed_origin(
req: axum::extract::Request,
@@ -260,6 +261,7 @@ pub async fn add_webhook_allowed_origin(
next.run(req).await
}
#[cfg(not(feature = "tantivy"))]
type IndexReader = ();

View File

@@ -10,6 +10,8 @@ use axum::{body::Body, extract::OriginalUri, http::Response, response::IntoRespo
#[cfg(feature = "static_frontend")]
use axum::http::header;
#[cfg(feature = "static_frontend")]
use http::HeaderValue;
use hyper::Uri;
#[cfg(feature = "static_frontend")]
@@ -17,6 +19,12 @@ use mime_guess::mime;
#[cfg(feature = "static_frontend")]
use rust_embed::RustEmbed;
// Content Security Policy configuration
#[cfg(feature = "static_frontend")]
lazy_static::lazy_static! {
static ref CSP_POLICY: String = std::env::var("CSP_POLICY").unwrap_or_default();
}
// static_handler is a handler that serves static files from the
pub async fn static_handler(OriginalUri(original_uri): OriginalUri) -> StaticFile {
StaticFile(original_uri)
@@ -51,6 +59,13 @@ fn serve_path(path: &str) -> Response<Body> {
let mut res = Response::builder()
.header(header::CONTENT_TYPE, mime.as_ref())
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*");
// Add Content-Security-Policy header for static assets when policy is set
if !CSP_POLICY.is_empty() {
if let Ok(header_value) = HeaderValue::try_from(CSP_POLICY.as_str()) {
res = res.header("Content-Security-Policy", header_value);
}
}
if mime.as_ref() == mime::APPLICATION_JAVASCRIPT
|| mime.as_ref() == mime::TEXT_JAVASCRIPT
|| path.ends_with(".wasm")

View File

@@ -66,10 +66,10 @@ lazy_static::lazy_static! {
lazy_static::lazy_static! {
static ref PIPTAR_UPLOAD_CHANNEL: tokio::sync::mpsc::UnboundedSender<PiptarUploadTask> = {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
// Spawn background task to handle uploads sequentially
tokio::spawn(handle_piptar_uploads(rx));
tx
};
}
@@ -85,7 +85,7 @@ struct PiptarUploadTask {
async fn handle_piptar_uploads(mut rx: tokio::sync::mpsc::UnboundedReceiver<PiptarUploadTask>) {
use crate::global_cache::build_tar_and_push;
use windmill_common::s3_helpers::get_object_store;
while let Some(task) = rx.recv().await {
if let Some(os) = get_object_store().await {
match build_tar_and_push(os, task.venv_path.clone(), task.cache_dir, None, false).await {
@@ -324,6 +324,7 @@ pub async fn uv_pip_compile(
child_cmd
.env("SystemRoot", SYSTEM_ROOT.as_str())
.env("USERPROFILE", crate::USERPROFILE_ENV.as_str())
.env("HOME", crate::USERPROFILE_ENV.as_str())
.env(
"LOCALAPPDATA",
std::env::var("LOCALAPPDATA")
@@ -332,6 +333,29 @@ pub async fn uv_pip_compile(
.env(
"TMP",
std::env::var("TMP").unwrap_or_else(|_| String::from("/tmp")),
)
.env(
"APPDATA",
std::env::var("APPDATA")
.unwrap_or_else(|_| format!("{}\\AppData\\Roaming", crate::USERPROFILE_ENV.as_str())),
)
.env(
"ComSpec",
std::env::var("ComSpec").unwrap_or_else(|_| String::from("C:\\Windows\\System32\\cmd.exe")),
)
.env(
"PATHEXT",
std::env::var("PATHEXT").unwrap_or_else(|_|
String::from(".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL")
),
)
.env(
"ProgramData",
std::env::var("ProgramData").unwrap_or_else(|_| String::from("C:\\ProgramData")),
)
.env(
"ProgramFiles",
std::env::var("ProgramFiles").unwrap_or_else(|_| String::from("C:\\Program Files")),
);
}
@@ -602,7 +626,7 @@ pub async fn handle_python_job(
if v == '<function call>':
del pre_args[k]
kwargs = inner_script.preprocessor(**pre_args)
kwrags_json = res_to_json(kwargs)
kwrags_json = res_to_json(kwargs)
with open("args.json", 'w') as f:
f.write(kwrags_json)"#
)
@@ -678,7 +702,7 @@ except BaseException as e:
tb = traceback.format_tb(exc_traceback)
with open(result_json, 'w') as f:
err = {{ "message": str(e), "name": e.__class__.__name__, "stack": '\n'.join(tb[1:]) }}
extra = e.__dict__
extra = e.__dict__
if extra and len(extra) > 0:
err['extra'] = extra
flow_node_id = os.environ.get('WM_FLOW_STEP_ID')
@@ -1417,6 +1441,7 @@ async fn spawn_uv_install(
.envs(PROXY_ENVS.clone())
.env("SystemRoot", SYSTEM_ROOT.as_str())
.env("USERPROFILE", crate::USERPROFILE_ENV.as_str())
.env("HOME", HOME_ENV.as_str())
.env(
"TMP",
std::env::var("TMP").unwrap_or_else(|_| String::from("/tmp")),
@@ -1426,6 +1451,29 @@ async fn spawn_uv_install(
std::env::var("LOCALAPPDATA")
.unwrap_or_else(|_| format!("{}\\AppData\\Local", HOME_ENV.as_str())),
)
.env(
"APPDATA",
std::env::var("APPDATA")
.unwrap_or_else(|_| format!("{}\\AppData\\Roaming", crate::USERPROFILE_ENV.as_str())),
)
.env(
"ComSpec",
std::env::var("ComSpec").unwrap_or_else(|_| String::from("C:\\Windows\\System32\\cmd.exe")),
)
.env(
"PATHEXT",
std::env::var("PATHEXT").unwrap_or_else(|_|
String::from(".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL")
),
)
.env(
"ProgramData",
std::env::var("ProgramData").unwrap_or_else(|_| String::from("C:\\ProgramData")),
)
.env(
"ProgramFiles",
std::env::var("ProgramFiles").unwrap_or_else(|_| String::from("C:\\Program Files")),
)
.args(&command_args[1..])
.stdout(Stdio::piped())
.stderr(Stdio::piped());
@@ -1810,7 +1858,7 @@ pub async fn handle_python_reqs(
// Create a file to indicate that installation was successfull
let valid_path = venv_p.clone() + "/.valid.windmill";
// This is atomic operation, meaning, that it either completes and wheel is valid,
// This is atomic operation, meaning, that it either completes and wheel is valid,
// or it does not and wheel is invalid and will be reinstalled next run
if let Err(e) = File::create(&valid_path).await{
tracing::error!(
@@ -1942,7 +1990,7 @@ pub async fn handle_python_reqs(
venv_path: venv_p.clone(),
cache_dir: py_version.to_cache_dir_top_level(false),
};
if let Err(e) = PIPTAR_UPLOAD_CHANNEL.send(upload_task) {
tracing::warn!("Failed to queue piptar upload for {venv_p}: {e}");
} else {
@@ -1961,7 +2009,7 @@ pub async fn handle_python_reqs(
pids.lock().await.get_mut(i).and_then(|e| e.take());
// Create a file to indicate that installation was successfull
let valid_path = venv_p.clone() + "/.valid.windmill";
// This is atomic operation, meaning, that it either completes and wheel is valid,
// This is atomic operation, meaning, that it either completes and wheel is valid,
// or it does not and wheel is invalid and will be reinstalled next run
if let Err(e) = File::create(&valid_path).await{
tracing::error!(