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
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions apps/auth-service/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,8 @@ 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, 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";
/// operations, and its database queries and committed events.
pub const TELEMETRY_FILTER: &str = "auth_service=info,piquel_repository=info";

/// Bound on browser ceremony and API JSON bodies.
const MAX_REQUEST_BODY_BYTES: usize = 64 * 1024;
Expand Down
6 changes: 3 additions & 3 deletions crates/auth-sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ repository.workspace = true

[features]
# Extractors, layers and login routes for axum.
axum = ["dep:axum", "dep:tower"]
axum = ["dep:axum", "dep:tower", "dep:tracing"]
# `axum::check_backend`, to test an application's session backend.
test-util = ["axum"]

[dependencies]
piquel-common.workspace = true
piquel-common = { workspace = true, features = ["client-spans"] }

axum = { workspace = true, optional = true }
base64.workspace = true
Expand All @@ -28,7 +28,7 @@ sha2.workspace = true
thiserror.workspace = true
tokio.workspace = true
tower = { workspace = true, optional = true }
tracing.workspace = true
tracing = { workspace = true, optional = true }
url.workspace = true

[dev-dependencies]
Expand Down
69 changes: 22 additions & 47 deletions crates/auth-sdk/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
//! around each request.

use base64::{Engine, engine::general_purpose::STANDARD};
use piquel_common::SendTraced;
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 @@ -140,10 +140,8 @@ impl Http {
self.send(url, request, authorization).await
}

/// 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.
/// Authenticates, sends and reads a request. It is sent in the `http.client` span
/// of [`SendTraced`], which records only the method, host and status.
async fn send(
&self,
url: &Url,
Expand All @@ -166,49 +164,26 @@ impl Http {
url: url.clone(),
source,
};
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");
let mut response = request.send_traced().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 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");
body.extend_from_slice(&chunk);
}
reply
Ok(Reply {
status,
max_age,
body,
})
}
}
2 changes: 1 addition & 1 deletion crates/auth-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
//! 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
//! `piquel_common` 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
Expand Down
4 changes: 4 additions & 0 deletions crates/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ repository.workspace = true
[features]
# The views of administration, for auth and its dashboard.
admin = ["dep:serde_json"]
# `SendTraced`: client spans around `reqwest` requests, for auth and the SDK.
client-spans = ["dep:reqwest", "dep:tracing"]
# Environment variables, validated origins and secret references, for servers.
config = []
# Email address normalization, for servers that store or compare addresses.
Expand All @@ -20,10 +22,12 @@ sqlx = ["dep:sqlx"]

[dependencies]
chrono.workspace = true
reqwest = { workspace = true, optional = true }
serde.workspace = true
serde_json = { workspace = true, optional = true }
sqlx = { workspace = true, optional = true }
thiserror.workspace = true
tracing = { workspace = true, optional = true }
unicode-normalization = { workspace = true, optional = true }
url.workspace = true
uuid.workspace = true
Expand Down
23 changes: 13 additions & 10 deletions crates/telemetry/src/client.rs → crates/common/src/client_span.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,38 @@

use reqwest::{RequestBuilder, Response};
use tracing::{Instrument, field::Empty};
use tracing_opentelemetry::OpenTelemetrySpanExt;

/// Sends a `reqwest` request in a client span, e.g. `client.get(url).send_traced()`.
/// Auth's provider and delivery calls use it, and so does the Rust SDK, so every
/// request either sends looks the same in a trace.
pub trait SendTraced {
/// Sends the request in a span recording only its method, host and response
/// status: never its path, query, headers or body, which carry codes and tokens.
/// A failure or 4xx/5xx status marks the span failed.
/// Sends the request in an `http.client` span, at `info` under the
/// `piquel_common` target, recording only its method, host and response status
/// as OpenTelemetry's HTTP client conventions name them: never its path, query,
/// headers or body, which carry codes and tokens. A failure or 4xx/5xx status
/// marks the span failed.
fn send_traced(self) -> impl Future<Output = reqwest::Result<Response>> + Send;
}

impl SendTraced for RequestBuilder {
async fn send_traced(self) -> reqwest::Result<Response> {
let (client, request) = self.build_split();
let request = request?;
let method = request.method().as_str().to_owned();
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 = request.url().host_str(),
http.response.status_code = Empty,
);
span.set_attribute("http.request.method", method);
if let Some(host) = request.url().host_str() {
span.set_attribute("server.address", host.to_owned());
}
let response = client.execute(request).instrument(span.clone()).await;
match &response {
Ok(response) => {
span.set_attribute(
// tracing-opentelemetry exports unsigned integers as strings.
span.record(
"http.response.status_code",
i64::from(response.status().as_u16()),
);
Expand Down
6 changes: 6 additions & 0 deletions crates/common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//! the vocabulary macros. Servers add:
//!
//! - `admin`: the views of administration.
//! - `client-spans`: `SendTraced`, a client span around each `reqwest` request.
//! - `config`: environment variables, validated origins and secret references.
//! - `email`: email address normalization.
//! - `events`: the domain events auth records.
Expand All @@ -14,6 +15,9 @@
/// The views of administration: what the admin dashboard shows and the CLI prints.
#[cfg(feature = "admin")]
pub mod admin;
/// Client spans around outbound `reqwest` requests.
#[cfg(feature = "client-spans")]
mod client_span;
/// OAuth client registrations, each field validated by its type.
pub mod clients;
/// Environment variables, validated origins and secret references.
Expand All @@ -35,6 +39,8 @@ use std::{error::Error as StdError, fmt, str::FromStr};
use thiserror::Error;
use uuid::Uuid;

#[cfg(feature = "client-spans")]
pub use client_span::SendTraced;
pub use clients::ClientId;
pub use handle::{Handle, HandleError};

Expand Down
2 changes: 1 addition & 1 deletion crates/telemetry/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ repository.workspace = true
test-util = ["opentelemetry_sdk/testing"]

[dependencies]
piquel-common = { workspace = true, features = ["config"] }
piquel-common = { workspace = true, features = ["client-spans", "config"] }

async-trait.workspace = true
axum.workspace = true
Expand Down
10 changes: 4 additions & 6 deletions crates/telemetry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
//! Everything a span, log line or label holds may be exported. Never record a
//! secret, a query string or a request header.

/// Client spans for outbound `reqwest` requests.
mod client;
/// OTLP export through the workspace's `reqwest`.
mod export;
/// Server spans, access logs and request durations for axum routers.
Expand All @@ -32,9 +30,9 @@ mod capture;

#[cfg(any(test, feature = "test-util"))]
pub use capture::Capture;
pub use client::SendTraced;
pub use http::HttpTelemetry;
pub use metrics::{Counter, Gauge, Histogram, Label, Labels};
pub use piquel_common::SendTraced;

use export::Exporters;
use opentelemetry::{KeyValue, trace::TraceContextExt};
Expand Down Expand Up @@ -64,9 +62,9 @@ use uuid::Uuid;

/// Instrumentation scope of every tracer and meter.
const SCOPE: &str = "piquel";
/// Added to every filter: this crate's spans and access logs, and the SDK's own
/// warnings, such as failed exports.
const OWN_DIRECTIVES: &str = "piquel_telemetry=info,opentelemetry=warn";
/// Added to every filter: this crate's spans and access logs, the client spans of
/// [`SendTraced`], and the SDK's own warnings, such as failed exports.
const OWN_DIRECTIVES: &str = "piquel_telemetry=info,piquel_common=info,opentelemetry=warn";
/// Targets never exported as logs: the SDK, which logs its own failures, and the
/// HTTP stack export requests run on, outside the SDK's suppression of its own
/// telemetry. Exporting either would feed the exporter its own traffic. They still
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture/monorepo.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ is authentication, with its account settings, and the admin dashboard.
| `apps/auth-service` | Rust auth authority, browser ceremonies, social adapters, OIDC, server-rendered pages, the settings API, the admin dashboard at admin.piquel.fr, CLI; `assets/passkey.js`, the one script its pages load: the WebAuthn passkey ceremonies and the form hooks that run them |
| `crates/database` | `piquel-repository`: PostgreSQL connections, migrations and typed persistence operations |
| `crates/auth-sdk` | `piquel-auth`, the public Rust SDK: token validation, typed scopes, login and the JWKS cache auth also uses for Google; `axum` feature: extractors, bearer layer, login routes over an application's own session backend |
| `crates/common` | `piquel-common`, the one home for shared types: IDs, string enums, `Personal<T>`, and the wire types shared by auth and the SDKs (token claims, discovery metadata, JWK sets, OAuth/OIDC vocabulary and errors, bearer challenges, SDK error codes, and the bodies auth's settings API and the admin views share); `admin` feature: the views of administration, which the admin dashboard shows, the CLI prints as JSON and the database crate decodes into; `config` feature: environment variables, validated origins, secret references; `events` feature: domain events |
| `crates/common` | `piquel-common`, the one home for shared types: IDs, string enums, `Personal<T>`, and the wire types shared by auth and the SDKs (token claims, discovery metadata, JWK sets, OAuth/OIDC vocabulary and errors, bearer challenges, SDK error codes, and the bodies auth's settings API and the admin views share); `admin` feature: the views of administration, which the admin dashboard shows, the CLI prints as JSON and the database crate decodes into; `client-spans` feature: `SendTraced`, client spans around `reqwest` requests, for auth and the SDK; `config` feature: environment variables, validated origins, secret references; `email` feature: email address normalization; `events` feature: domain events |
| `crates/crypto` | Random secrets, SHA-256, HMAC, PKCE and RS256 signing |
| `crates/ui` | `piquel-ui`: the Topcoat components and layouts of auth's server-rendered pages, rendering plain data and taking URLs as props, the admin dashboard's included, and the shared stylesheet, `assets/style.css` |
| `crates/telemetry` | `piquel-telemetry`: stderr logs, and OpenTelemetry traces, metrics and logs over OTLP; request spans and access logs for axum routers, client spans, and typed metric instruments; see [telemetry.md](telemetry.md) |
Expand Down
6 changes: 3 additions & 3 deletions docs/architecture/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +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. Requests the Rust SDK sends, such as
Google's signing-key fetches through `KeyCache`, get the same span from the SDK
itself.
records the method, host and status only. `SendTraced` lives in `piquel-common`
so the Rust SDK sends its requests, such as Google's signing-key fetches through
`KeyCache`, the same way.

## What never goes in telemetry

Expand Down
Loading