From ae0957ad7219668454f949ffcce5f3352f38af60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 7 Sep 2026 05:17:41 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20fix:=20telemetry=20privacy=20swe?= =?UTF-8?q?ep,=20in-flight=20gauge=20guards,=20request-id=20validation,=20?= =?UTF-8?q?tenant=20gauge=20on=20create?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - No account name reaches an exported log record: the admin seed (domain/user.rs), the ADMIN_USERNAME refusal and the builder seed (domain/builder.rs) log the event without the `username` field. - The forbidden-key list moves to tests/common (`FORBIDDEN_TELEMETRY_KEYS`, `is_forbidden_key`), gains `username`/`email` and the header prefixes, and is used by both the HTTP-edge and the AI-bridge guard tests. The telemetry suite now also exports tracing EVENTS through an in-memory log exporter and holds log records to the same rule. - `http.server.active_requests` and `ai_requests_inflight` are closed by a `Drop` guard, so a dropped request future (client hang-up, outer timeout) no longer leaks the gauge upwards. A cancelled request is recorded as 499. - A caller-supplied `x-request-id` is only kept when it is at most 64 chars of `[A-Za-z0-9._-]`; anything else is dropped and a UUID is minted, so a client cannot write free text onto `http.request.id` of every span. - `tenant_cache_size` is reported by `Tenants::create` and by the bootstrap insert, not only by the lazy-dial path. - The keepalive logs its first `up` verdict, which its comment already claimed. Claude-Session: https://claude.ai/code/session_018sqvyBCZ9kpQP6vnGomT2s --- src/ai/server.rs | 27 +++++- src/domain/builder.rs | 7 +- src/domain/user.rs | 10 +-- src/lib.rs | 91 ++++++++++++++++++-- src/main.rs | 4 + src/tenant.rs | 21 +++-- src/web/room.rs | 2 + tests/ai_bridge.rs | 21 +---- tests/common/mod.rs | 56 ++++++++++-- tests/telemetry.rs | 193 ++++++++++++++++++++++++++++++++++++------ 10 files changed, 353 insertions(+), 79 deletions(-) diff --git a/src/ai/server.rs b/src/ai/server.rs index f957855..90a6886 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -283,7 +283,7 @@ impl AiBridge { ); let metrics = self.inner.metrics(); let attrs = [KeyValue::new("capability", capability.to_string())]; - metrics.ai_requests_inflight.add(1, &attrs); + let _in_flight = InFlight::started(metrics, &attrs); let started = Instant::now(); let outcome = async { @@ -339,7 +339,6 @@ impl AiBridge { .instrument(span.clone()) .await; - metrics.ai_requests_inflight.add(-1, &attrs); metrics .ai_request_duration .record(started.elapsed().as_secs_f64(), &attrs); @@ -1059,6 +1058,30 @@ fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } +/// One dispatched-and-unanswered AI request, counted for as long as it lives. +/// +/// `AiBridge::send`'s future is dropped whenever its caller goes away (an HTTP +/// client disconnecting, an outer timeout), and a decrement written after the +/// `.await` is skipped on exactly those paths — leaking the gauge upwards for +/// the process's whole life. `Drop` covers every exit. +struct InFlight<'a> { + metrics: &'a Metrics, + attrs: &'a [KeyValue], +} + +impl<'a> InFlight<'a> { + fn started(metrics: &'a Metrics, attrs: &'a [KeyValue]) -> Self { + metrics.ai_requests_inflight.add(1, attrs); + Self { metrics, attrs } + } +} + +impl Drop for InFlight<'_> { + fn drop(&mut self) { + self.metrics.ai_requests_inflight.add(-1, self.attrs); + } +} + #[cfg(test)] mod tests { use axum::routing::get; diff --git a/src/domain/builder.rs b/src/domain/builder.rs index 9cfb66a..ebd0cee 100644 --- a/src/domain/builder.rs +++ b/src/domain/builder.rs @@ -108,10 +108,9 @@ impl Builder { .content(builder.clone()) .await?; created.ok_or_else(|| AppError::Internal("failed to create the builder account".into()))?; - tracing::info!( - username = builder.username.as_str(), - "seeded builder account" - ); + // The account name stays out of the event: exported log records must + // name no person (see `telemetry`). + tracing::info!("seeded the builder account named by BUILDER_USERNAME"); Ok(()) } } diff --git a/src/domain/user.rs b/src/domain/user.rs index 15ee0c1..3ac16b5 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -438,7 +438,6 @@ impl User { Some(user) if user.role == Role::Admin => Ok(()), Some(_) => { tracing::warn!( - username = username.as_str(), "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ Grant the role through an existing admin or the manual SurrealQL path." ); @@ -452,10 +451,11 @@ impl User { // is no marker that could tell such a row apart from a stranger // who registered the name first, so the hole cannot be healed // later; it has to be impossible to open. - let admin = - Self::create_with_role(username, password.hash_async().await?, Role::Admin, db) - .await?; - tracing::info!(username = admin.username.as_str(), "seeded admin account"); + Self::create_with_role(username, password.hash_async().await?, Role::Admin, db) + .await?; + // No `username` field: with OTLP on every event is exported as a + // log record, so an account name here leaves the process. + tracing::info!("seeded the admin account named by ADMIN_USERNAME"); Ok(()) } } diff --git a/src/lib.rs b/src/lib.rs index 3e14720..35e70bc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -297,8 +297,37 @@ pub fn build_router(state: AppState) -> Router { HeaderName::from_static(REQUEST_ID_HEADER), MakeRequestUuid, )) + // Above `SetRequestIdLayer`, which keeps a caller-supplied id verbatim: + // an unusable one is dropped here so the layer below mints a UUID. + .layer(axum::middleware::from_fn(drop_unusable_request_id)) } +/// Refuse a caller-supplied `x-request-id` that is not a short, boring token. +/// +/// The id lands on `http.request.id` of every span, so anything a client can +/// put there it can export: free text (personal data) and unbounded cardinality +/// both. Accepting only `[A-Za-z0-9._-]{1,64}` keeps the useful case — a +/// gateway correlating its own request id with ours — and mints a UUID for +/// everything else. +async fn drop_unusable_request_id(mut req: Request, next: Next) -> Response { + let usable = req.headers().get(REQUEST_ID_HEADER).is_some_and(|value| { + value.to_str().is_ok_and(|id| { + !id.is_empty() + && id.len() <= MAX_REQUEST_ID_LEN + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) + }) + }); + if !usable { + req.headers_mut().remove(REQUEST_ID_HEADER); + } + next.run(req).await +} + +/// The longest caller-supplied request id we will carry. +const MAX_REQUEST_ID_LEN: usize = 64; + /// The header carrying the per-request id, in and out. const REQUEST_ID_HEADER: &str = "x-request-id"; @@ -377,19 +406,63 @@ async fn measure(metrics: crate::telemetry::Metrics, mut req: Request, next: Nex .to_owned(); let school = SchoolSlot::default(); req.extensions_mut().insert(school.clone()); - metrics.request_started(&method); - let started = std::time::Instant::now(); + let mut in_flight = InFlight::started(&metrics, method, route, school); let res = next.run(req).await; - metrics.request_finished( - &method, - &route, - res.status().as_u16(), - school.get(), - started.elapsed(), - ); + in_flight.status = res.status().as_u16(); res } +/// The in-flight accounting for one request, closed by `Drop`. +/// +/// A dropped request future — the client disconnected, an outer timeout fired — +/// never returns from `next.run`, so a decrement written after the `.await` +/// leaks the gauge upwards for the process's whole life. Same shape as +/// [`web::room::Connected`]: `Drop` is the only placement every exit passes +/// through. +struct InFlight<'a> { + metrics: &'a crate::telemetry::Metrics, + method: String, + route: String, + school: SchoolSlot, + started: std::time::Instant, + /// The answer's status, or `499` ("client closed request") while there is + /// no answer — which is what a cancelled request is recorded as. + status: u16, +} + +impl<'a> InFlight<'a> { + fn started( + metrics: &'a crate::telemetry::Metrics, + method: String, + route: String, + school: SchoolSlot, + ) -> Self { + metrics.request_started(&method); + Self { + metrics, + method, + route, + school, + started: std::time::Instant::now(), + status: 499, + } + } +} + +impl Drop for InFlight<'_> { + fn drop(&mut self) { + // `request_finished` owns both halves — the decrement and the duration + // sample — so a cancelled request lands here too, under `499`. + self.metrics.request_finished( + &self.method, + &self.route, + self.status, + self.school.get(), + self.started.elapsed(), + ); + } +} + /// Refuse work the database cannot currently do, and cap how long any request /// may wait on it. /// diff --git a/src/main.rs b/src/main.rs index 5d6df58..5d29d1a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -115,6 +115,10 @@ fn keepalive(db: Database, health: DbHealth) { health.set(up); metrics.db_up.record(u64::from(up), &[]); match (was_up, up) { + // The first verdict announces itself either way, so an operator + // reading the log can tell "healthy since boot" from "we never + // logged anything yet". + (None, true) => tracing::info!(db_up = true, "database reachable"), (Some(true) | None, false) => { down_since = Some(started); tracing::warn!("database is down: the keepalive ping did not answer"); diff --git a/src/tenant.rs b/src/tenant.rs index 5410a6d..d263192 100644 --- a/src/tenant.rs +++ b/src/tenant.rs @@ -328,11 +328,12 @@ impl Tenants { .create(school.id.record()) .content(school) .await?; - tenants - .cache - .write() - .expect("tenant cache lock") - .insert(slug.as_str().to_string(), db); + let size = { + let mut cache = tenants.cache.write().expect("tenant cache lock"); + cache.insert(slug.as_str().to_string(), db); + cache.len() + }; + Self::report_size(size); Ok(tenants) } @@ -436,10 +437,12 @@ impl Tenants { return Err(err); } }; - self.cache - .write() - .expect("tenant cache lock") - .insert(slug.as_str().to_string(), db.clone()); + let size = { + let mut cache = self.cache.write().expect("tenant cache lock"); + cache.insert(slug.as_str().to_string(), db.clone()); + cache.len() + }; + Self::report_size(size); Ok(db) } diff --git a/src/web/room.rs b/src/web/room.rs index 5d484f7..a47c429 100644 --- a/src/web/room.rs +++ b/src/web/room.rs @@ -53,6 +53,8 @@ impl Connected { metrics .ws_connections .add(1, &[opentelemetry::KeyValue::new("kind", kind)]); + // `id` is a resource id (exam, board) and `school` a slug — both are + // allowed on telemetry. A user id never is. tracing::info!(kind, school, id, "websocket opened"); Self { metrics: metrics.clone(), diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 33c0404..5c88fee 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -2593,25 +2593,6 @@ async fn a_blob_read_is_refused_module_disabled_when_the_school_has_no_chatbot() // ------------------------------------------------------------- telemetry -- -/// Attribute keys telemetry may never leave the process with — the list -/// `tests/telemetry.rs` fixes for the HTTP edge, applied to the bridge's own -/// spans. A prompt, a message or a user id showing up here is the failure this -/// guards against. -const FORBIDDEN: &[&str] = &[ - "url.path", - "url.full", - "url.query", - "client.address", - "network.peer.address", - "user_agent.original", - "user.id", - "user.name", - "enduser.id", - "cookie", - "http.request.body", - "http.response.body", -]; - /// The bridge's own observability, asserted end to end over real QUIC: one /// dispatched request must produce an `ai.request` span naming the capability /// and nothing about the caller, and one refused handshake must reach the @@ -2708,7 +2689,7 @@ async fn a_dispatch_is_traced_by_capability_and_a_refused_handshake_is_counted() for span in &spans { for (key, _) in attrs_of(span) { assert!( - !FORBIDDEN.contains(&key.as_str()), + !common::is_forbidden_key(&key), "span {:?} carries {key:?}, which may never leave this process", span.name ); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 354d5c9..94cba73 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -13,6 +13,7 @@ use hezarfen_backend::database::Database; use hezarfen_backend::module::ModuleSet; use hezarfen_backend::rate_limit::RateLimitConfig; use hezarfen_backend::state::{AppState, DbHealth}; +use hezarfen_backend::telemetry::Metrics; use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants}; use hezarfen_backend::{build_router, database}; use serde_json::{Value, json}; @@ -48,7 +49,7 @@ pub async fn app_and_db() -> (Router, Database) { /// [`app_and_db`] plus the registry behind it, for the suites whose subject is /// tenancy itself (a second school, a suspension, the builder surface). pub async fn app_and_tenants() -> (Router, Database, Tenants) { - let (app, db, tenants) = app_parts(None, Default::default()).await; + let (app, db, tenants) = app_parts(None, Default::default(), Metrics::noop()).await; (app, db, tenants) } @@ -98,14 +99,14 @@ pub async fn app_with_ai(ai: Option) -> (Router, Database) { /// [`app_with_ai`] plus the registry behind it, for the suites whose subject is /// an AI service reading *across* schools. pub async fn app_with_ai_tenants(ai: Option) -> (Router, Database, Tenants) { - app_parts(ai, Default::default()).await + app_parts(ai, Default::default(), Metrics::noop()).await } /// [`app_with_ai`] with the liveness flag handed in, so a test can take the /// database socket down under a running app — the api-read path re-checks it in /// place of the HTTP db guard it bypasses. pub async fn app_with_ai_health(ai: Option, db_up: DbHealth) -> (Router, Database) { - let (app, db, _) = app_parts(ai, db_up).await; + let (app, db, _) = app_parts(ai, db_up, Metrics::noop()).await; (app, db) } @@ -113,7 +114,11 @@ pub async fn app_with_ai_health(ai: Option, db_up: DbHealth) -> (Route /// school), a router over it, and the demo school's handle — which is what /// every suite means by "the database", since that is where users and rows /// live. -async fn app_parts(ai: Option, db_up: DbHealth) -> (Router, Database, Tenants) { +async fn app_parts( + ai: Option, + db_up: DbHealth, + metrics: hezarfen_backend::telemetry::Metrics, +) -> (Router, Database, Tenants) { let tenants = database::init_mem_tenants() .await .expect("in-memory deployment"); @@ -131,11 +136,50 @@ async fn app_parts(ai: Option, db_up: DbHealth) -> (Router, Database, board_hub: Default::default(), db_up, ai, - metrics: hezarfen_backend::telemetry::Metrics::noop(), + metrics, }); (app, db, tenants) } +/// The same router with the caller's instruments, so a test can read back what +/// the HTTP edge recorded without touching the process-global meter provider. +pub async fn app_with_metrics(metrics: Metrics) -> (Router, Database) { + let (app, db, _) = app_parts(None, Default::default(), metrics).await; + (app, db) +} + +/// Attribute keys that would carry personal data out of the process. KVKK +/// analysis fixed this list: telemetry names the school and the route, never +/// the person, their address, or what they sent. Shared so the HTTP edge +/// (`telemetry.rs`) and the AI bridge (`ai_bridge.rs`) are held to one list. +/// +/// `server.address` is deliberately absent: that is our own bind address, not +/// a caller's. +pub const FORBIDDEN_TELEMETRY_KEYS: &[&str] = &[ + "url.path", + "url.full", + "url.query", + "client.address", + "network.peer.address", + "user_agent.original", + "user.id", + "user.name", + "username", + "email", + "enduser.id", + "cookie", + "http.request.body", + "http.response.body", +]; + +/// [`FORBIDDEN_TELEMETRY_KEYS`] plus the two header prefixes — any captured +/// request or response header is personal data by default. +pub fn is_forbidden_key(key: &str) -> bool { + FORBIDDEN_TELEMETRY_KEYS.contains(&key) + || key.starts_with("http.request.header.") + || key.starts_with("http.response.header.") +} + /// A router backed by a fresh in-memory database. pub async fn mem_app() -> Router { app_and_db().await.0 @@ -685,7 +729,7 @@ pub async fn remote_deployment(schools: &[(&str, &str)]) -> Option Option .find(|kv| kv.key.as_str() == key) .map(|kv| kv.value.to_string()) } + +/// A request whose future is dropped mid-flight — the client hung up, an outer +/// timeout fired — must still be counted out of `http.server.active_requests`. +/// Driven with a request body that never yields, so the handler is parked +/// inside the middleware when the future is dropped; a gauge that only +/// decrements after the `.await` stays at 1 forever here. +/// +/// Its own meter provider (never the process-global one) so the sum is this +/// test's requests and nothing else's. +#[tokio::test] +async fn a_cancelled_request_is_counted_out_of_the_in_flight_gauge() { + let exporter = InMemoryMetricExporter::default(); + let meter_provider = SdkMeterProvider::builder() + .with_reader(PeriodicReader::builder(exporter.clone()).build()) + .build(); + let metrics = Metrics::from_meter(meter_provider.meter("test")); + let (app, _db) = common::app_with_metrics(metrics).await; + + // A body that is never going to produce its bytes: the `Json` extractor on + // `POST /auth/login` parks on it. + let body = Body::from_stream(futures_util::stream::pending::< + Result, std::io::Error>, + >()); + let req = axum::http::Request::builder() + .method("POST") + .uri("/auth/login") + .header("content-type", "application/json") + .body(body) + .expect("request"); + let pending = tokio::time::timeout( + std::time::Duration::from_millis(50), + tower::ServiceExt::oneshot(app, req), + ) + .await; + assert!(pending.is_err(), "the parked request answered after all"); + + meter_provider.force_flush().expect("flush metrics"); + let mut points = 0; + let mut sum = 0i64; + for resource in exporter.get_finished_metrics().expect("metrics") { + for scope in resource.scope_metrics() { + for metric in scope.metrics() { + if metric.name() != "http.server.active_requests" { + continue; + } + if let AggregatedMetrics::I64(MetricData::Sum(data)) = metric.data() { + for point in data.data_points() { + points += 1; + sum += point.value(); + } + } + } + } + } + assert!( + points > 0, + "the gauge was never recorded — the test drove nothing" + ); + assert_eq!( + sum, 0, + "the cancelled request is still counted as in flight" + ); +} + +/// `http.request.id` lands on every span, so a caller-supplied one is only +/// echoed when it is a short, boring token; anything else is replaced with a +/// minted UUID. Without this a client writes free text — personal data, or an +/// unbounded label — onto the telemetry of every request it makes. +#[tokio::test] +async fn an_unusable_caller_supplied_request_id_is_replaced_with_a_uuid() { + let exporter = InMemorySpanExporter::default(); + let provider = SdkTracerProvider::builder() + .with_simple_exporter(exporter.clone()) + .build(); + let subscriber = tracing_subscriber::registry() + .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test"))); + let _guard = tracing::subscriber::set_default(subscriber); + + let app = mem_app().await; + let long = "x".repeat(70); + let sent = |id: &str| { + let app = app.clone(); + let id = id.to_string(); + async move { + let req = axum::http::Request::builder() + .method("GET") + .uri("/health") + .header("x-request-id", &id) + .body(Body::empty()) + .expect("request"); + let res = tower::ServiceExt::oneshot(app, req) + .await + .expect("response"); + res.headers() + .get("x-request-id") + .expect("every response carries an id") + .to_str() + .expect("an ascii id") + .to_string() + } + }; + + let minted = sent(&long).await; + assert_ne!(minted, long, "the 70-character id was echoed back"); + assert!( + uuid::Uuid::parse_str(&minted).is_ok(), + "an unusable id is replaced with a UUID, got {minted:?}" + ); + let echoed = sent("ok-123").await; + assert_eq!(echoed, "ok-123", "a boring id is the caller's to keep"); + + provider.force_flush().expect("flush"); + let ids: Vec = exporter + .get_finished_spans() + .expect("spans") + .iter() + .filter(|s| s.name == "GET /health") + .filter_map(|s| attr(s, "http.request.id")) + .collect(); + assert!( + ids.contains(&minted) && ids.contains(&echoed), + "the span must carry the id the response carried: {ids:?}" + ); + assert!( + !ids.contains(&long), + "the rejected id reached a span anyway: {ids:?}" + ); +}