forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

telemetry.rs357 lines, 13.7 KiBHistoryRawDownload
1//! What the request span is allowed to say — and, more importantly, what it is
2//! not.
3//!
4//! Its own test binary because installing a tracer needs a *process-global*
5//! `tracing` subscriber: the other suites run in the same process as each other
6//! and would race for it (and would then export spans for every request every
7//! other test makes).
8
9mod common;
10
11use std::collections::BTreeSet;
12
13use axum::body::Body;
14use common::{is_forbidden_key, mem_app, send_raw};
15use hezarfen_backend::telemetry::Metrics;
16use opentelemetry::metrics::MeterProvider as _;
17use opentelemetry::trace::TracerProvider as _;
18use opentelemetry_appender_tracing::layer::OpenTelemetryTracingBridge;
19use opentelemetry_sdk::logs::{InMemoryLogExporter, SdkLoggerProvider};
20use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData};
21use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider};
22use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider};
23use tracing_subscriber::layer::SubscriberExt;
24use tracing_subscriber::util::SubscriberInitExt;
25
26#[tokio::test]
27async fn the_request_span_names_the_route_and_nothing_about_the_caller() {
28 let exporter = InMemorySpanExporter::default();
29 let provider = SdkTracerProvider::builder()
30 .with_simple_exporter(exporter.clone())
31 .build();
32 // Events are exported too, as OTLP log records — the same rule applies to
33 // them, so the same subscriber carries the appender bridge `telemetry::init`
34 // installs in production.
35 let logs = InMemoryLogExporter::default();
36 let logger = SdkLoggerProvider::builder()
37 .with_simple_exporter(logs.clone())
38 .build();
39 tracing_subscriber::registry()
40 .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")))
41 .with(OpenTelemetryTracingBridge::new(&logger))
42 .init();
43
44 let app = mem_app().await;
45 let (_, headers, _) = send_raw(&app, "GET", "/health", None, None, Vec::new()).await;
46 assert!(
47 headers.get("x-request-id").is_some_and(|v| !v.is_empty()),
48 "every response must carry the id its span was tagged with"
49 );
50 // An unrouted path must not become a span name — that is how a record id
51 // ends up in a metric label.
52 let _ = send_raw(&app, "GET", "/nope/42", None, None, Vec::new()).await;
53 provider.force_flush().expect("flush");
54
55 let spans = exporter.get_finished_spans().expect("exported spans");
56 let names: BTreeSet<_> = spans.iter().map(|s| s.name.to_string()).collect();
57 assert!(
58 names.contains("GET /health"),
59 "expected a span named after the METHOD and route template, got {names:?}"
60 );
61 assert!(
62 names.contains("GET unmatched"),
63 "an unrouted request is 'unmatched', never its URL: {names:?}"
64 );
65
66 let health = spans
67 .iter()
68 .find(|s| s.name == "GET /health")
69 .expect("the health span");
70 let attrs: Vec<(String, String)> = health
71 .attributes
72 .iter()
73 .map(|kv| (kv.key.to_string(), kv.value.to_string()))
74 .collect();
75 assert!(
76 attrs.contains(&("http.route".to_string(), "/health".to_string())),
77 "{attrs:?}"
78 );
79 assert!(
80 attrs
81 .iter()
82 .any(|(k, v)| k == "http.response.status_code" && v.parse::<u16>() == Ok(200)),
83 "the status must be recorded, as a number: {attrs:?}"
84 );
85 assert!(
86 attrs
87 .iter()
88 .any(|(k, v)| k == "http.request.id" && !v.is_empty()),
89 "{attrs:?}"
90 );
91
92 for span in &spans {
93 for kv in span.attributes.iter() {
94 let key = kv.key.to_string();
95 assert!(
96 !is_forbidden_key(&key),
97 "span {:?} carries {key:?}, which telemetry may never leave this process with",
98 span.name
99 );
100 }
101 }
102
103 // The events: a login and a seeded account are the two places an account
104 // name has historically leaked, so they are what is driven here.
105 let (app, db) = common::app_and_db().await;
106 let _ = common::login_as(&app, &db, LOGIN_USERNAME, "teacher").await;
107 logger.force_flush().expect("flush logs");
108 let records = logs.get_emitted_logs().expect("emitted logs");
109 assert!(!records.is_empty(), "no log records were exported at all");
110 for record in &records {
111 for (key, value) in record.record.attributes_iter() {
112 let key = key.to_string();
113 assert!(
114 !is_forbidden_key(&key),
115 "a log record carries {key:?} = {value:?}"
116 );
117 }
118 let body = format!("{:?}", record.record.body());
119 assert!(
120 !body.contains(LOGIN_USERNAME),
121 "a log record body names the caller: {body}"
122 );
123 }
124}
125
126/// The account the log assertions above look for. Unusual enough that a match
127/// in a log body is the account name and not a coincidence.
128const LOGIN_USERNAME: &str = "telemetryprobeteacher";
129
130/// The class of a refusal, on the span: `error.type` is the grouping key a
131/// dashboard slices errors by, so it must be the stable name of the *kind* of
132/// refusal (`not_found`) and never the status code or anything from the URL.
133///
134/// Own subscriber, scoped to this thread with `set_default` rather than
135/// `init` — the process-global slot belongs to the guard test above, and a
136/// second `init` in this binary would panic.
137#[tokio::test]
138async fn a_refusal_records_its_class_on_the_span() {
139 let exporter = InMemorySpanExporter::default();
140 let provider = SdkTracerProvider::builder()
141 .with_simple_exporter(exporter.clone())
142 .build();
143 let subscriber = tracing_subscriber::registry()
144 .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));
145 let _guard = tracing::subscriber::set_default(subscriber);
146
147 let (app, db) = common::app_and_db().await;
148 let cookie = common::login_as(&app, &db, "classteacher", "teacher").await;
149 let (status, _, _) = send_raw(
150 &app,
151 "GET",
152 "/notes/nosuchnote",
153 Some(&cookie),
154 None,
155 Vec::new(),
156 )
157 .await;
158 assert_eq!(status, 404);
159 provider.force_flush().expect("flush");
160
161 let spans = exporter.get_finished_spans().expect("exported spans");
162 let span = spans
163 .iter()
164 .find(|s| s.name == "GET /notes/{id}")
165 .unwrap_or_else(|| panic!("the note span, got {:?}", names(&spans)));
166 assert_eq!(attr(span, "error.type").as_deref(), Some("not_found"));
167 // A 404 is the caller's mistake, not ours: the span is not marked failed.
168 assert_eq!(attr(span, "otel.status_code"), None);
169}
170
171/// A panicking handler answers the same 500 body every other internal error
172/// answers, and its span says `panic` — not `500`, which is already there as
173/// the status code.
174///
175/// Built from the two layers `build_router` wires (`lib.rs`: the
176/// `CatchPanicLayer::custom(panic_response)` at :303 inside the `TraceLayer`
177/// at :310) rather than driven through the real router, because no route in
178/// the API panics and `Router::route` on an already-layered router adds a
179/// route *outside* those layers — the assembled stack cannot be given a
180/// panicking endpoint from a test without a test-only route in `build_router`.
181#[tokio::test]
182async fn a_panicking_handler_is_a_500_with_the_standard_body_and_a_panic_span() {
183 let exporter = InMemorySpanExporter::default();
184 let provider = SdkTracerProvider::builder()
185 .with_simple_exporter(exporter.clone())
186 .build();
187 let subscriber = tracing_subscriber::registry()
188 .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));
189 let _guard = tracing::subscriber::set_default(subscriber);
190
191 let app: axum::Router = axum::Router::new()
192 .route("/boom", axum::routing::get(boom))
193 .layer(tower_http::catch_panic::CatchPanicLayer::custom(
194 hezarfen_backend::panic_response,
195 ))
196 .layer(
197 tower_http::trace::TraceLayer::new_for_http()
198 .make_span_with(hezarfen_backend::request_span),
199 );
200
201 let (status, _, body) = send_raw(&app, "GET", "/boom", None, None, Vec::new()).await;
202 assert_eq!(status, 500);
203 // Byte-identical to `AppError::Internal`'s body: a panic is not a special
204 // wire shape a client has to learn.
205 assert_eq!(body, br#"{"error":"internal server error"}"#);
206 provider.force_flush().expect("flush");
207
208 let spans = exporter.get_finished_spans().expect("exported spans");
209 let span = spans
210 .iter()
211 .find(|s| s.name == "GET /boom")
212 .unwrap_or_else(|| panic!("the panicking span, got {:?}", names(&spans)));
213 assert_eq!(attr(span, "error.type").as_deref(), Some("panic"));
214}
215
216async fn boom() -> &'static str {
217 panic!("handler exploded")
218}
219
220fn names(spans: &[opentelemetry_sdk::trace::SpanData]) -> Vec<String> {
221 spans.iter().map(|s| s.name.to_string()).collect()
222}
223
224fn attr(span: &opentelemetry_sdk::trace::SpanData, key: &str) -> Option<String> {
225 span.attributes
226 .iter()
227 .find(|kv| kv.key.as_str() == key)
228 .map(|kv| kv.value.to_string())
229}
230
231/// A request whose future is dropped mid-flight — the client hung up, an outer
232/// timeout fired — must still be counted out of `http.server.active_requests`.
233/// Driven with a request body that never yields, so the handler is parked
234/// inside the middleware when the future is dropped; a gauge that only
235/// decrements after the `.await` stays at 1 forever here.
236///
237/// Its own meter provider (never the process-global one) so the sum is this
238/// test's requests and nothing else's.
239#[tokio::test]
240async fn a_cancelled_request_is_counted_out_of_the_in_flight_gauge() {
241 let exporter = InMemoryMetricExporter::default();
242 let meter_provider = SdkMeterProvider::builder()
243 .with_reader(PeriodicReader::builder(exporter.clone()).build())
244 .build();
245 let metrics = Metrics::from_meter(meter_provider.meter("test"));
246 let (app, _db) = common::app_with_metrics(metrics).await;
247
248 // A body that is never going to produce its bytes: the `Json` extractor on
249 // `POST /auth/login` parks on it.
250 let body = Body::from_stream(futures_util::stream::pending::<
251 Result<Vec<u8>, std::io::Error>,
252 >());
253 let req = axum::http::Request::builder()
254 .method("POST")
255 .uri("/auth/login")
256 .header("content-type", "application/json")
257 .body(body)
258 .expect("request");
259 let pending = tokio::time::timeout(
260 std::time::Duration::from_millis(50),
261 tower::ServiceExt::oneshot(app, req),
262 )
263 .await;
264 assert!(pending.is_err(), "the parked request answered after all");
265
266 meter_provider.force_flush().expect("flush metrics");
267 let mut points = 0;
268 let mut sum = 0i64;
269 for resource in exporter.get_finished_metrics().expect("metrics") {
270 for scope in resource.scope_metrics() {
271 for metric in scope.metrics() {
272 if metric.name() != "http.server.active_requests" {
273 continue;
274 }
275 if let AggregatedMetrics::I64(MetricData::Sum(data)) = metric.data() {
276 for point in data.data_points() {
277 points += 1;
278 sum += point.value();
279 }
280 }
281 }
282 }
283 }
284 assert!(
285 points > 0,
286 "the gauge was never recorded — the test drove nothing"
287 );
288 assert_eq!(
289 sum, 0,
290 "the cancelled request is still counted as in flight"
291 );
292}
293
294/// `http.request.id` lands on every span, so a caller-supplied one is only
295/// echoed when it is a short, boring token; anything else is replaced with a
296/// minted UUID. Without this a client writes free text — personal data, or an
297/// unbounded label — onto the telemetry of every request it makes.
298#[tokio::test]
299async fn an_unusable_caller_supplied_request_id_is_replaced_with_a_uuid() {
300 let exporter = InMemorySpanExporter::default();
301 let provider = SdkTracerProvider::builder()
302 .with_simple_exporter(exporter.clone())
303 .build();
304 let subscriber = tracing_subscriber::registry()
305 .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));
306 let _guard = tracing::subscriber::set_default(subscriber);
307
308 let app = mem_app().await;
309 let long = "x".repeat(70);
310 let sent = |id: &str| {
311 let app = app.clone();
312 let id = id.to_string();
313 async move {
314 let req = axum::http::Request::builder()
315 .method("GET")
316 .uri("/health")
317 .header("x-request-id", &id)
318 .body(Body::empty())
319 .expect("request");
320 let res = tower::ServiceExt::oneshot(app, req)
321 .await
322 .expect("response");
323 res.headers()
324 .get("x-request-id")
325 .expect("every response carries an id")
326 .to_str()
327 .expect("an ascii id")
328 .to_string()
329 }
330 };
331
332 let minted = sent(&long).await;
333 assert_ne!(minted, long, "the 70-character id was echoed back");
334 assert!(
335 uuid::Uuid::parse_str(&minted).is_ok(),
336 "an unusable id is replaced with a UUID, got {minted:?}"
337 );
338 let echoed = sent("ok-123").await;
339 assert_eq!(echoed, "ok-123", "a boring id is the caller's to keep");
340
341 provider.force_flush().expect("flush");
342 let ids: Vec<String> = exporter
343 .get_finished_spans()
344 .expect("spans")
345 .iter()
346 .filter(|s| s.name == "GET /health")
347 .filter_map(|s| attr(s, "http.request.id"))
348 .collect();
349 assert!(
350 ids.contains(&minted) && ids.contains(&echoed),
351 "the span must carry the id the response carried: {ids:?}"
352 );
353 assert!(
354 !ids.contains(&long),
355 "the rejected id reached a span anyway: {ids:?}"
356 );
357}