Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 80 additions & 1 deletion apps/auth-service/src/federation/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,18 @@ 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::{
DatabaseConfig, DatabaseTransaction, InsertExternalIdentity, InsertUser, InsertVerifiedEmail,
};
use std::collections::HashMap;
use tower::ServiceExt;
use tracing::Instrument;

/// Isolated database fixture with replaceable provider endpoints and unique subjects.
struct TestApp {
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions apps/auth-service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions crates/auth-sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]

Expand All @@ -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]
Expand Down
70 changes: 49 additions & 21 deletions crates/auth-sdk/src/http.rs
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
}
}
4 changes: 4 additions & 0 deletions crates/auth-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

Expand Down
4 changes: 3 additions & 1 deletion docs/architecture/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading