diff --git a/backend/.sqlx/query-18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397.json b/backend/.sqlx/query-18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397.json new file mode 100644 index 0000000000..3ceaafdbcb --- /dev/null +++ b/backend/.sqlx/query-18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397.json @@ -0,0 +1,44 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT to_char(timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS \"day!\",\n id AS \"id!\",\n timestamp AS \"ts!\",\n row_to_json(r)::text AS \"line!\"\n FROM (\n SELECT workspace_id, id, timestamp, username, operation,\n action_kind::text AS action_kind, resource, parameters, email, span,\n client_ip, user_agent\n FROM audit_partitioned\n WHERE timestamp >= $1 AND timestamp < $2\n AND (timestamp, id) > ($3, $4)\n ORDER BY timestamp, id\n LIMIT $5\n ) r\n ORDER BY timestamp, id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "day!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "id!", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "ts!", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "line!", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Timestamptz", + "Timestamptz", + "Timestamptz", + "Int8", + "Int8" + ] + }, + "nullable": [ + null, + false, + false, + null + ] + }, + "hash": "18d01ba5fb5a25984ae1291b7c20820613f4dd8cd03186b17e595f538a4d4397" +} diff --git a/backend/.sqlx/query-26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb.json b/backend/.sqlx/query-26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb.json new file mode 100644 index 0000000000..725d75aee1 --- /dev/null +++ b/backend/.sqlx/query-26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb.json @@ -0,0 +1,42 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH bounds AS (\n SELECT ($2::bigint % 4294967296)::text::xid AS prev_xid,\n ($3::bigint % 4294967296)::text::xid AS cur_xid,\n $1::timestamptz AS ts_floor\n ),\n batch AS (\n SELECT workspace_id, id, timestamp, username, operation,\n action_kind::text AS action_kind, resource, parameters, email, span,\n client_ip, user_agent\n FROM audit_partitioned, bounds b\n WHERE timestamp >= b.ts_floor\n AND age(xmin) > age(b.cur_xid)\n AND age(xmin) <= age(b.prev_xid)\n ORDER BY id\n )\n SELECT to_char(timestamp AT TIME ZONE 'UTC', 'YYYY-MM-DD') AS \"day!\",\n string_agg(row_to_json(batch)::text, E'\\n' ORDER BY id) AS \"ndjson!\",\n max(id) AS \"max_id!\",\n max(timestamp) AS \"max_ts!\"\n FROM batch\n GROUP BY 1\n ORDER BY 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "day!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "ndjson!", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "max_id!", + "type_info": "Int8" + }, + { + "ordinal": 3, + "name": "max_ts!", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Timestamptz", + "Int8", + "Int8" + ] + }, + "nullable": [ + null, + null, + null, + null + ] + }, + "hash": "26f1b3af9057517b82a3c263e0396ee2747445e2a66381ed1b9fd96e0d9909bb" +} diff --git a/backend/.sqlx/query-44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055.json b/backend/.sqlx/query-44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055.json new file mode 100644 index 0000000000..974782f017 --- /dev/null +++ b/backend/.sqlx/query-44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO audit_partitioned\n (workspace_id, username, operation, action_kind, resource, parameters, email, span,\n client_ip, user_agent)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + { + "Custom": { + "name": "action_kind", + "kind": { + "Enum": [ + "create", + "update", + "delete", + "execute" + ] + } + } + }, + "Varchar", + "Jsonb", + "Varchar", + "Varchar", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "44ad516d89eeb5411cbd34a839c4c6eab6782b23eb8d7f8831b2f0e9f9c17055" +} diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 01f7a1b754..b02e75bcb7 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -302da0e8e3817d5cbda5cf1053a9fe89019d7c27 +8604f6779f08ff2208e85628503877edce8e2343 diff --git a/backend/migrations/20261126085023_audit_client_ip_user_agent.down.sql b/backend/migrations/20261126085023_audit_client_ip_user_agent.down.sql new file mode 100644 index 0000000000..5d83f2c95f --- /dev/null +++ b/backend/migrations/20261126085023_audit_client_ip_user_agent.down.sql @@ -0,0 +1,15 @@ +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN + ALTER TABLE audit DROP COLUMN IF EXISTS client_ip, DROP COLUMN IF EXISTS user_agent; + ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN + DROP VIEW audit; + CREATE VIEW audit AS + SELECT workspace_id, id, timestamp, username, operation, action_kind, resource, + parameters, email, span + FROM audit_partitioned WHERE false; + GRANT ALL ON audit TO windmill_user, windmill_admin; + END IF; +END $$; + +ALTER TABLE audit_partitioned DROP COLUMN IF EXISTS client_ip, DROP COLUMN IF EXISTS user_agent; diff --git a/backend/migrations/20261126085023_audit_client_ip_user_agent.up.sql b/backend/migrations/20261126085023_audit_client_ip_user_agent.up.sql new file mode 100644 index 0000000000..dc9115bf23 --- /dev/null +++ b/backend/migrations/20261126085023_audit_client_ip_user_agent.up.sql @@ -0,0 +1,15 @@ +ALTER TABLE audit_partitioned ADD COLUMN IF NOT EXISTS client_ip TEXT, ADD COLUMN IF NOT EXISTS user_agent TEXT; + +-- Older servers read `SELECT * FROM audit_partitioned UNION ALL SELECT * FROM audit`, so the +-- legacy table, or the empty view that replaces it, carries the same columns in the same order. +DO $$ +BEGIN + IF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'r') THEN + ALTER TABLE audit ADD COLUMN IF NOT EXISTS client_ip TEXT, ADD COLUMN IF NOT EXISTS user_agent TEXT; + ELSIF EXISTS (SELECT 1 FROM pg_class WHERE oid = to_regclass('audit') AND relkind = 'v') THEN + CREATE OR REPLACE VIEW audit AS + SELECT workspace_id, id, timestamp, username, operation, action_kind, resource, + parameters, email, span, client_ip, user_agent + FROM audit_partitioned WHERE false; + END IF; +END $$; diff --git a/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs b/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs index 0c5c55f7ed..0abbb904db 100644 --- a/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs +++ b/backend/windmill-api-settings/src/audit_logs_s3_backfill.rs @@ -344,7 +344,8 @@ async fn run_backfill( row_to_json(r)::text AS "line!" FROM ( SELECT workspace_id, id, timestamp, username, operation, - action_kind::text AS action_kind, resource, parameters, email, span + action_kind::text AS action_kind, resource, parameters, email, span, + client_ip, user_agent FROM audit_partitioned WHERE timestamp >= $1 AND timestamp < $2 AND (timestamp, id) > ($3, $4) diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index 19df068d00..4ff29493e0 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -34449,6 +34449,12 @@ components: type: object span: type: string + client_ip: + type: string + description: Address of the client that made the request. Forwarding headers are believed only from the proxies listed in the TRUSTED_PROXIES environment variable (loopback by default, plus the private ranges on Windmill Cloud), so behind a reverse proxy this is the proxy's address until it is listed. Absent on entries no request stands behind. + user_agent: + type: string + description: User-Agent header of the request. required: - workspace_id - id diff --git a/backend/windmill-api/src/lib.rs b/backend/windmill-api/src/lib.rs index b1d3f60c76..26535b211f 100644 --- a/backend/windmill-api/src/lib.rs +++ b/backend/windmill-api/src/lib.rs @@ -323,6 +323,25 @@ async fn set_request_client( windmill_common::trigger_history::scope_client(client, next.run(req)).await } +/// Scope the request in its origin (client address and user agent), recorded on the audit +/// entries it writes. A request routed in-process has no connect info and keeps the origin +/// of the request that routed it. +async fn set_request_origin( + req: axum::extract::Request, + next: axum::middleware::Next, +) -> axum::response::Response { + use windmill_common::request_origin::{current, scope, RequestOrigin}; + let peer = req + .extensions() + .get::>() + .map(|c| c.0.ip()); + let origin = match (peer, current()) { + (None, Some(outer)) => (*outer).clone(), + (peer, _) => RequestOrigin::from_request(peer, req.headers()), + }; + scope(origin, next.run(req)).await +} + #[cfg(not(feature = "tantivy"))] type IndexReader = (); @@ -1292,6 +1311,8 @@ pub async fn run_server( let app = app.layer(axum::middleware::from_fn(set_request_client)); + let app = app.layer(axum::middleware::from_fn(set_request_origin)); + let app = app.layer(CatchPanicLayer::custom(|err| { tracing::error!("panic in handler, returning 500: {:?}", err); Response::builder() @@ -1308,7 +1329,10 @@ pub async fn run_server( let listener = listener.tap_io(move |tcp_stream| { let _ = tcp_stream.set_nodelay(!server_mode); }); - let server = axum::serve(listener, app.into_make_service()); + let server = axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ); tracing::info!( instance = %*INSTANCE_NAME, diff --git a/backend/windmill-api/src/live_migrations.rs b/backend/windmill-api/src/live_migrations.rs index a620807902..866eed1fab 100644 --- a/backend/windmill-api/src/live_migrations.rs +++ b/backend/windmill-api/src/live_migrations.rs @@ -367,8 +367,11 @@ async fn retire_legacy_audit_table(conn: &mut PgConnection) -> Result<(), Error> .await?; tx.execute("DROP TABLE audit").await?; tx.execute( - format!("CREATE VIEW audit AS SELECT {AUDIT_COLUMNS} FROM audit_partitioned WHERE false") - .as_str(), + format!( + "CREATE VIEW audit AS SELECT {AUDIT_COLUMNS}, client_ip, user_agent \ + FROM audit_partitioned WHERE false" + ) + .as_str(), ) .await?; tx.execute("GRANT ALL ON audit TO windmill_user, windmill_admin") diff --git a/backend/windmill-audit/src/lib.rs b/backend/windmill-audit/src/lib.rs index 89b5de067a..4371705f5f 100644 --- a/backend/windmill-audit/src/lib.rs +++ b/backend/windmill-audit/src/lib.rs @@ -26,6 +26,10 @@ pub struct AuditLog { pub resource: Option, pub parameters: Option, pub span: Option, + #[sqlx(default)] + pub client_ip: Option, + #[sqlx(default)] + pub user_agent: Option, } #[derive(Deserialize)] diff --git a/backend/windmill-common/src/global_settings.rs b/backend/windmill-common/src/global_settings.rs index e87dd17a76..eaa86d7066 100644 --- a/backend/windmill-common/src/global_settings.rs +++ b/backend/windmill-common/src/global_settings.rs @@ -924,6 +924,7 @@ pub const ENV_SETTINGS: &[&str] = &[ "WORKER_GROUP", "SAML_METADATA", "INSTANCE_IS_DEV", + "TRUSTED_PROXIES", "OTEL_METRICS", "OTEL_TRACING", "OTEL_LOGS", diff --git a/backend/windmill-common/src/lib.rs b/backend/windmill-common/src/lib.rs index 822b0fda31..a5a025959e 100644 --- a/backend/windmill-common/src/lib.rs +++ b/backend/windmill-common/src/lib.rs @@ -98,6 +98,7 @@ pub mod job_provenance; pub mod jobs; pub mod jwt; pub mod login_rate_limit; +pub mod request_origin; pub mod more_serde; pub mod oauth2; #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] diff --git a/backend/windmill-common/src/request_origin.rs b/backend/windmill-common/src/request_origin.rs new file mode 100644 index 0000000000..7b8b41c49d --- /dev/null +++ b/backend/windmill-common/src/request_origin.rs @@ -0,0 +1,192 @@ +//! Where the request being served came from: the client's IP address and user agent, as +//! recorded on the audit entries it writes. + +use std::net::IpAddr; +use std::sync::{Arc, LazyLock}; + +use http::HeaderMap; +use ipnet::IpNet; + +use crate::utils::truncate_chars; +use crate::worker::CLOUD_HOSTED; + +const USER_AGENT_MAX_CHARS: usize = 512; + +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RequestOrigin { + pub client_ip: Option, + pub user_agent: Option, +} + +tokio::task_local! { + static REQUEST_ORIGIN: Arc; +} + +/// Run `f` with `origin` as the origin of every audit entry it writes. Task-locals do not +/// cross `tokio::spawn`, so an entry written from a spawned task records no origin. +pub async fn scope(origin: RequestOrigin, f: F) -> F::Output { + REQUEST_ORIGIN.scope(Arc::new(origin), f).await +} + +/// The origin of the request being served, `None` outside a request. +pub fn current() -> Option> { + REQUEST_ORIGIN.try_with(|o| o.clone()).ok() +} + +/// The proxies whose forwarding headers are believed. `TRUSTED_PROXIES` (comma-separated +/// addresses or CIDRs, empty for none) replaces the default: loopback, plus the private +/// ranges on cloud, where every request arrives through our own load balancer. Private +/// ranges are not trusted by default elsewhere: a self-hosted instance is often reached +/// directly from a private network, and its clients could then name any address they like. +static TRUSTED_PROXIES: LazyLock> = + LazyLock::new(|| match std::env::var("TRUSTED_PROXIES") { + Ok(v) => parse_trusted_proxies(&v), + Err(_) => { + let mut nets = vec!["127.0.0.0/8", "::1/128"]; + if *CLOUD_HOSTED { + nets.extend(["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]); + } + nets.into_iter().filter_map(|n| n.parse().ok()).collect() + } + }); + +fn parse_trusted_proxies(v: &str) -> Vec { + v.split(',') + .map(str::trim) + .filter(|s| !s.is_empty()) + .filter_map(|s| { + let parsed = s + .parse::() + .ok() + .or_else(|| s.parse::().ok().map(IpNet::from)); + if parsed.is_none() { + tracing::warn!("Ignoring invalid TRUSTED_PROXIES entry: {s}"); + } + parsed + }) + .collect() +} + +impl RequestOrigin { + /// `peer` is the address the connection came from; `None` when the request did not arrive + /// over a socket, and then no header is believed either. + pub fn from_request(peer: Option, headers: &HeaderMap) -> Self { + Self { + client_ip: peer.map(|p| client_ip(p, headers, &TRUSTED_PROXIES)), + user_agent: headers + .get(http::header::USER_AGENT) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(|s| truncate_chars(s, USER_AGENT_MAX_CHARS).to_string()), + } + } +} + +fn parse_hop(s: &str) -> Option { + let s = s.trim(); + s.parse::() + .ok() + .or_else(|| s.parse::().ok().map(|a| a.ip())) + .map(|ip| ip.to_canonical()) +} + +/// The first address that is not a trusted proxy, walking `X-Forwarded-For` back from the +/// peer: each trusted hop vouches for the address before it, an untrusted one for nothing, +/// so entries left of it are whatever the client wrote. `X-Real-IP` is read only when there +/// is no `X-Forwarded-For`. +fn client_ip(peer: IpAddr, headers: &HeaderMap, trusted: &[IpNet]) -> IpAddr { + let is_trusted = |ip: &IpAddr| trusted.iter().any(|n| n.contains(ip)); + let mut current = peer.to_canonical(); + if !is_trusted(¤t) { + return current; + } + // Bytes that are not UTF-8 are kept as entries that fail to parse, so they stop the walk + // rather than vanish and let the client's own entries, or X-Real-IP, stand in. + let values: Vec = headers + .get_all("x-forwarded-for") + .iter() + .map(|v| String::from_utf8_lossy(v.as_bytes()).into_owned()) + .collect(); + let hops: Vec<&str> = values.iter().flat_map(|v| v.split(',')).collect(); + if values.is_empty() { + if let Some(ip) = headers + .get("x-real-ip") + .and_then(|v| v.to_str().ok()) + .and_then(parse_hop) + { + return ip; + } + return current; + } + for hop in hops.iter().rev() { + if !is_trusted(¤t) { + break; + } + match parse_hop(hop) { + Some(ip) => current = ip, + None => break, + } + } + current +} + +#[cfg(test)] +mod tests { + use super::*; + + fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap { + let mut h = HeaderMap::new(); + for (k, v) in pairs { + h.append(*k, v.parse().unwrap()); + } + h + } + + fn ip(s: &str) -> IpAddr { + s.parse().unwrap() + } + + #[test] + fn forwarded_addresses_are_believed_only_through_trusted_hops() { + let trusted = parse_trusted_proxies("10.0.0.0/8, 127.0.0.1"); + let xff = headers(&[("x-forwarded-for", "6.6.6.6, 1.2.3.4, 10.0.0.2")]); + + // An untrusted peer's headers say nothing. + assert_eq!(client_ip(ip("8.8.8.8"), &xff, &trusted), ip("8.8.8.8")); + // Trusted peer and trusted hop: the client is the first untrusted address, and the + // entry the client itself wrote left of it is ignored. + assert_eq!(client_ip(ip("10.0.0.1"), &xff, &trusted), ip("1.2.3.4")); + // Every hop trusted: the leftmost one. + let all_trusted = headers(&[("x-forwarded-for", "10.1.1.1, 10.0.0.2")]); + assert_eq!( + client_ip(ip("127.0.0.1"), &all_trusted, &trusted), + ip("10.1.1.1") + ); + // An unparseable hop stops the walk at the last address vouched for. + let garbage = headers(&[("x-forwarded-for", "1.2.3.4, unknown")]); + assert_eq!( + client_ip(ip("10.0.0.1"), &garbage, &trusted), + ip("10.0.0.1") + ); + // A hop that is not UTF-8 stops the walk too, and does not let X-Real-IP in. + let mut binary = headers(&[("x-real-ip", "5.5.5.5")]); + binary.append( + "x-forwarded-for", + http::HeaderValue::from_bytes(b"\x80, 1.2.3.4").unwrap(), + ); + assert_eq!(client_ip(ip("10.0.0.1"), &binary, &trusted), ip("1.2.3.4")); + let mut binary_last = headers(&[("x-real-ip", "5.5.5.5")]); + binary_last.append( + "x-forwarded-for", + http::HeaderValue::from_bytes(b"1.2.3.4, \x80").unwrap(), + ); + assert_eq!(client_ip(ip("10.0.0.1"), &binary_last, &trusted), ip("10.0.0.1")); + // X-Real-IP, only from a trusted peer and only without X-Forwarded-For. + let real = headers(&[("x-real-ip", "5.5.5.5")]); + assert_eq!(client_ip(ip("10.0.0.1"), &real, &trusted), ip("5.5.5.5")); + assert_eq!(client_ip(ip("8.8.8.8"), &real, &trusted), ip("8.8.8.8")); + // Nothing trusted. + assert_eq!(client_ip(ip("10.0.0.1"), &xff, &[]), ip("10.0.0.1")); + } +} diff --git a/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte b/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte index 1289deb222..edab31d0f4 100644 --- a/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte +++ b/frontend/src/lib/components/auditLogs/AuditLogDetails.svelte @@ -62,6 +62,18 @@ {/if} + {#if log.client_ip} +
+ Client IP + {log.client_ip} +
+ {/if} + {#if log.user_agent} +
+ User agent + {log.user_agent} +
+ {/if}
Parameters