feat: record client IP and user agent on audit entries (#12673)

* feat: record client IP and user agent on audit entries

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: trust the compose network's proxy for the audit client IP

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: treat undecodable forwarded-for entries as a stop in the client IP walk

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep the legacy audit view in step with the new audit columns

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor: add the audit origin columns to audit_partitioned only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* revert: keep the legacy audit table and view in step with the new columns

Older servers read the legacy audit table in a SELECT * UNION ALL with audit_partitioned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: update ee-repo-ref to 8604f6779f08ff2208e85628503877edce8e2343

This commit updates the EE repository reference after PR #1009 was merged in windmill-ee-private.

Previous ee-repo-ref: 8c44649a51062cf4f056792c0e2da09b7b7354b5

New ee-repo-ref: 8604f6779f08ff2208e85628503877edce8e2343

Automated by sync-ee-ref workflow.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
This commit is contained in:
Ruben Fiszel
2026-11-26 12:54:08 +01:00
committed by GitHub
co-authored by Claude Opus 5.5 windmill-internal-app[bot]
parent 9a7ab54746
commit c689d74505
15 changed files with 400 additions and 5 deletions
@@ -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"
}
@@ -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"
}
@@ -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"
}
+1 -1
View File
@@ -1 +1 @@
302da0e8e3817d5cbda5cf1053a9fe89019d7c27
8604f6779f08ff2208e85628503877edce8e2343
@@ -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;
@@ -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 $$;
@@ -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)
+6
View File
@@ -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
+25 -1
View File
@@ -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::<axum::extract::ConnectInfo<std::net::SocketAddr>>()
.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::<std::net::SocketAddr>(),
);
tracing::info!(
instance = %*INSTANCE_NAME,
+5 -2
View File
@@ -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")
+4
View File
@@ -26,6 +26,10 @@ pub struct AuditLog {
pub resource: Option<String>,
pub parameters: Option<serde_json::Value>,
pub span: Option<String>,
#[sqlx(default)]
pub client_ip: Option<String>,
#[sqlx(default)]
pub user_agent: Option<String>,
}
#[derive(Deserialize)]
@@ -924,6 +924,7 @@ pub const ENV_SETTINGS: &[&str] = &[
"WORKER_GROUP",
"SAML_METADATA",
"INSTANCE_IS_DEV",
"TRUSTED_PROXIES",
"OTEL_METRICS",
"OTEL_TRACING",
"OTEL_LOGS",
+1
View File
@@ -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"))]
@@ -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<IpAddr>,
pub user_agent: Option<String>,
}
tokio::task_local! {
static REQUEST_ORIGIN: Arc<RequestOrigin>;
}
/// 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<F: std::future::Future>(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<Arc<RequestOrigin>> {
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<Vec<IpNet>> =
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<IpNet> {
v.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.filter_map(|s| {
let parsed = s
.parse::<IpNet>()
.ok()
.or_else(|| s.parse::<IpAddr>().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<IpAddr>, 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<IpAddr> {
let s = s.trim();
s.parse::<IpAddr>()
.ok()
.or_else(|| s.parse::<std::net::SocketAddr>().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(&current) {
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<String> = 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(&current) {
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"));
}
}