diff --git a/apps/auth-service/src/federation/tests.rs b/apps/auth-service/src/federation/tests.rs index 19195b0ec..45ce28309 100644 --- a/apps/auth-service/src/federation/tests.rs +++ b/apps/auth-service/src/federation/tests.rs @@ -16,7 +16,10 @@ use axum::{ }; use piquel_auth::{KeyCache, KeySet}; use piquel_common::PasskeyId; -use piquel_common::{Handle, protocol::jwt::TokenType}; +use piquel_common::{ + Handle, + protocol::jwt::{Algorithm, TokenType}, +}; use piquel_crypto::Rs256Key; use piquel_crypto::Secret; use piquel_repository::{ @@ -24,6 +27,7 @@ use piquel_repository::{ }; use std::collections::HashMap; use tower::ServiceExt; +use tracing::Instrument; /// Isolated database fixture with replaceable provider endpoints and unique subjects. struct TestApp { @@ -745,6 +749,81 @@ async fn google_mock_validates_signature_audience_nonce_and_expiry_without_requi task.abort(); } +/// Fetching Google's signing keys is a client span of the request that needed them, +/// with its method, host and status only. +#[tokio::test] +async fn google_key_fetch_is_a_client_span_of_its_request() { + let capture = piquel_telemetry::Telemetry::capture(crate::TELEMETRY_FILTER); + let rsa = Rs256Key::generate("google-test").expect("RSA test key"); + let token = rsa + .sign(TokenType::Id, &serde_json::json!({})) + .expect("signed token"); + let keys = rsa.jwks().clone(); + let mock = Router::new().route("/keys", get(move || async move { Json(keys) })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("mock listener"); + let url = format!( + "http://{}/keys?client=secret", + listener.local_addr().expect("address") + ); + let task = tokio::spawn(async move { + axum::serve(listener, mock).await.expect("mock server"); + }); + let cache = KeyCache::new(url.parse().expect("mock key URL"), reqwest::Client::new()); + let jws = piquel_auth::Jws::parse(&token).expect("JWS"); + let request = tracing::info_span!("request"); + cache + .verify(&jws, Algorithm::Rs256) + .instrument(request) + .await + .expect("verified"); + task.abort(); + + let spans = capture.spans(); + let request = spans + .iter() + .find(|span| span.name == "request") + .expect("request span"); + let fetch = spans + .iter() + .find(|span| span.name == "GET") + .expect("key fetch span"); + assert_eq!(fetch.parent_span_id, request.span_context.span_id()); + assert_eq!(format!("{:?}", fetch.span_kind), "Client"); + let attributes: Vec<_> = fetch + .attributes + .iter() + .map(|attribute| format!("{}={}", attribute.key, attribute.value)) + .collect(); + for expected in [ + "http.request.method=GET", + "http.response.status_code=200", + "server.address=127.0.0.1", + ] { + assert!( + attributes.iter().any(|a| a == expected), + "{expected}: {attributes:?}" + ); + } + assert!( + !attributes + .iter() + .any(|attribute| attribute.contains("/keys") || attribute.contains("secret")), + "no path or query: {attributes:?}" + ); + let status = fetch + .attributes + .iter() + .find(|attribute| attribute.key.as_str() == "http.response.status_code") + .expect("status"); + assert_eq!( + format!("{:?}", status.value), + "I64(200)", + "an integer status" + ); +} + /// Stable provider subjects take priority over email observations and require an existing passkey. #[expect( clippy::too_many_lines, diff --git a/apps/auth-service/src/lib.rs b/apps/auth-service/src/lib.rs index 9d6902a31..bc3f8d6af 100644 --- a/apps/auth-service/src/lib.rs +++ b/apps/auth-service/src/lib.rs @@ -90,8 +90,9 @@ use thiserror::Error; /// The default `service.name` of exported telemetry. pub const SERVICE_NAME: &str = "auth-service"; /// What is traced, and logged unless `RUST_LOG` says otherwise: auth's own -/// operations, and its database queries and committed events. -pub const TELEMETRY_FILTER: &str = "auth_service=info,piquel_repository=info"; +/// operations, its database queries and committed events, and the SDK's requests, +/// such as Google's signing-key fetches. +pub const TELEMETRY_FILTER: &str = "auth_service=info,piquel_repository=info,piquel_auth=info"; /// Bound on browser ceremony and API JSON bodies. const MAX_REQUEST_BODY_BYTES: usize = 64 * 1024; diff --git a/crates/auth-sdk/Cargo.toml b/crates/auth-sdk/Cargo.toml index 639500c67..b99926b24 100644 --- a/crates/auth-sdk/Cargo.toml +++ b/crates/auth-sdk/Cargo.toml @@ -8,7 +8,7 @@ repository.workspace = true [features] # Extractors, layers and login routes for axum. -axum = ["dep:axum", "dep:tower", "dep:tracing"] +axum = ["dep:axum", "dep:tower"] # `axum::check_backend`, to test an application's session backend. test-util = ["axum"] @@ -28,7 +28,7 @@ sha2.workspace = true thiserror.workspace = true tokio.workspace = true tower = { workspace = true, optional = true } -tracing = { workspace = true, optional = true } +tracing.workspace = true url.workspace = true [dev-dependencies] diff --git a/crates/auth-sdk/src/http.rs b/crates/auth-sdk/src/http.rs index 373eb661a..dd9438d2a 100644 --- a/crates/auth-sdk/src/http.rs +++ b/crates/auth-sdk/src/http.rs @@ -1,9 +1,11 @@ -//! The SDK's HTTP client: bounded bodies and errors that name the URL. +//! The SDK's HTTP client: bounded bodies, errors that name the URL, and a client span +//! around each request. use base64::{Engine, engine::general_purpose::STANDARD}; use reqwest::{RequestBuilder, StatusCode, header}; use std::time::Duration; use thiserror::Error; +use tracing::{Instrument, field::Empty}; use url::Url; /// Most bytes read from any response. Metadata, key sets and token responses are a @@ -138,7 +140,10 @@ impl Http { self.send(url, request, authorization).await } - /// Authenticates, sends and reads a request. + /// Authenticates, sends and reads a request in an `http.client` span. Like auth's + /// own client spans, it records only the method, host and status: never the path, + /// query, headers or body, which carry codes and tokens. A failure or 4xx/5xx + /// status marks it failed. async fn send( &self, url: &Url, @@ -161,26 +166,49 @@ impl Http { url: url.clone(), source, }; - let mut response = request.send().await.map_err(failed)?; - let status = response.status(); - let max_age = response - .headers() - .get_all(header::CACHE_CONTROL) - .iter() - .filter_map(|value| value.to_str().ok()) - .flat_map(|value| value.split(',')) - .find_map(|directive| directive.trim().strip_prefix("max-age=")?.parse().ok()); - let mut body = Vec::new(); - while let Some(chunk) = response.chunk().await.map_err(failed)? { - if body.len() + chunk.len() > MAX_BODY_BYTES { - return Err(NetworkError::TooLarge { url: url.clone() }); + let request = request.build().map_err(failed)?; + let method = request.method().as_str(); + let span = tracing::info_span!( + "http.client", + otel.name = method, + otel.kind = "client", + otel.status_code = Empty, + http.request.method = method, + server.address = url.host_str(), + http.response.status_code = Empty, + ); + let exchange = async { + let mut response = self.0.execute(request).await.map_err(failed)?; + let status = response.status(); + // tracing-opentelemetry exports unsigned integers as strings. + span.record("http.response.status_code", i64::from(status.as_u16())); + if status.is_client_error() || status.is_server_error() { + span.record("otel.status_code", "ERROR"); } - body.extend_from_slice(&chunk); + let max_age = response + .headers() + .get_all(header::CACHE_CONTROL) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|value| value.split(',')) + .find_map(|directive| directive.trim().strip_prefix("max-age=")?.parse().ok()); + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(failed)? { + if body.len() + chunk.len() > MAX_BODY_BYTES { + return Err(NetworkError::TooLarge { url: url.clone() }); + } + body.extend_from_slice(&chunk); + } + Ok(Reply { + status, + max_age, + body, + }) + }; + let reply = exchange.instrument(span.clone()).await; + if reply.is_err() { + span.record("otel.status_code", "ERROR"); } - Ok(Reply { - status, - max_age, - body, - }) + reply } } diff --git a/crates/auth-sdk/src/lib.rs b/crates/auth-sdk/src/lib.rs index 92d8fb648..99f924f02 100644 --- a/crates/auth-sdk/src/lib.rs +++ b/crates/auth-sdk/src/lib.rs @@ -83,6 +83,10 @@ //! [`IssuerBuilder::http_client`] injects the `reqwest` client, for timeouts, proxies //! or extra trusted roots. //! +//! Each request runs in an `http.client` `tracing` span, at `info` under the +//! `piquel_auth` target, with its method, host and status only, as OpenTelemetry's +//! HTTP client conventions name them. +//! //! The behavior follows `docs/architecture/sdk.md` in the piquel-fr repository, and is //! tested against the shared vectors in `tests/sdk-vectors`. diff --git a/docs/architecture/telemetry.md b/docs/architecture/telemetry.md index d17e34f84..79bb85017 100644 --- a/docs/architecture/telemetry.md +++ b/docs/architecture/telemetry.md @@ -79,7 +79,9 @@ where one exists, and `piquel.auth.*` otherwise. Units follow UCUM: `s`, or `{thing}` for counts. **An outbound HTTP call:** `request.send_traced()` instead of `send()`. It -records the method, host and status only. +records the method, host and status only. Requests the Rust SDK sends, such as +Google's signing-key fetches through `KeyCache`, get the same span from the SDK +itself. ## What never goes in telemetry