webserver-base 0.4.2

A Rust library which contains shared logic for all of my webserver projects.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
//! Which requests become Sentry transactions, through the real router with
//! the real tracing layer and sampler at a rate of 1 (so a request that is
//! missing was *excluded*, not unlucky), and what the browser is told at each
//! browser rate.

use std::path::PathBuf;
use std::sync::Arc;

use axum::Router;
use axum::http::Method;
use sentry::protocol::{EnvelopeItem, Transaction};
use sentry::test::TestTransport;
use sentry::{Client, ClientOptions, Hub, HubSwitchGuard};
use tracing_subscriber::Layer;
use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::layer::SubscriberExt;

use super::{
    Environment, FrontendParams, Pages, Shutdown, WebServer, analytics_home, built_site,
    frontend_with, frontend_with_analytics, get, text,
};
use crate::TracesSampleRate;
use crate::analytics::AnalyticsConfig;
use crate::observability::with_traces;
use crate::templates::PageTemplateData;

/// The transactions Sentry would receive for `requests`, in order, from a
/// server whose router is `router`. Each request is a `(method, uri)`.
async fn transactions(router: &Router, requests: &[(Method, &str)]) -> Vec<Transaction<'static>> {
    transactions_at(router, TracesSampleRate::ALL, None, requests).await
}

/// Like [`transactions`], at `rate`, sending `sentry_trace` (if any) on each request.
async fn transactions_at(
    router: &Router,
    rate: TracesSampleRate,
    sentry_trace: Option<&str>,
    requests: &[(Method, &str)],
) -> Vec<Transaction<'static>> {
    let transport: Arc<TestTransport> = TestTransport::new();
    let mut options: ClientOptions = with_traces(ClientOptions::default(), rate);
    options.dsn = Some(
        "https://public@sentry.invalid/1"
            .parse()
            .expect("a valid DSN"),
    );
    options.transport = Some(Arc::new(transport.clone()));
    let hub: Arc<Hub> = Arc::new(Hub::new(
        Some(Arc::new(Client::from(options))),
        Arc::new(sentry::Scope::default()),
    ));
    let _hub: HubSwitchGuard = HubSwitchGuard::new(hub);
    let _subscriber: tracing::subscriber::DefaultGuard = tracing::subscriber::set_default(
        tracing_subscriber::registry()
            .with(sentry::integrations::tracing::SpanLayer::new().with_filter(LevelFilter::INFO)),
    );

    for (method, uri) in requests {
        let mut builder = axum::http::Request::builder()
            .method(method.clone())
            .uri(*uri);
        if let Some(value) = sentry_trace {
            builder = builder.header("sentry-trace", value);
        }
        let response = tower::ServiceExt::oneshot(
            router.clone(),
            builder
                .body(axum::body::Body::empty())
                .expect("a valid request"),
        )
        .await
        .expect("a router never fails");
        axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("a readable body");
    }

    transport
        .fetch_and_clear_envelopes()
        .iter()
        .flat_map(|envelope| envelope.items())
        .filter_map(|item| match item {
            EnvelopeItem::Transaction(transaction) => Some((**transaction).clone()),
            _ => None,
        })
        .collect()
}

fn names(transactions: &[Transaction<'static>]) -> Vec<String> {
    transactions
        .iter()
        .map(|transaction| transaction.name.clone().unwrap_or_default())
        .collect()
}

fn pages() -> Pages {
    Pages::new()
        .static_page(PageTemplateData::new("home", "Home", "/"), ())
        .dynamic_page("/things/{slug}", axum::routing::get(super::thing))
        .unlisted()
}

#[tokio::test(flavor = "current_thread")]
async fn only_the_sites_own_routes_are_traced_by_pattern_and_the_rest_never() {
    let root: PathBuf = built_site("trace-routes");
    let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
        .root_dir(&root)
        .frontend(frontend_with(pages()))
        .into_router(Shutdown::manual())
        .expect("the built site boots");
    let hashed: String = crate::assets::CacheBuster::load_in(&root)
        .expect("the manifest the build wrote")
        .get_file(super::STYLESHEET);
    let hashed_path: String = format!("/{hashed}");
    let get_all: Vec<(Method, &str)> = vec![
        (Method::GET, "/"),
        (Method::GET, "/things/a-slug"),
        (Method::GET, "/api/v1/health"),
        (Method::GET, "/robots.txt"),
        (Method::GET, "/humans.txt"),
        (Method::GET, "/site.webmanifest"),
        (Method::GET, "/sitemap.xml"),
        (Method::GET, "/favicon.ico"),
        (Method::GET, "/apple-touch-icon.png"),
        (Method::GET, &hashed_path),
        (Method::GET, "/static/no/such/file.css"),
        (Method::GET, "/no/such/page"),
    ];
    let actual: Vec<String> = names(&transactions(&router, &get_all).await);

    let expected: Vec<String> = vec![String::from("GET /"), String::from("GET /things/{slug}")];
    assert_eq!(expected, actual);
}

#[tokio::test(flavor = "current_thread")]
async fn a_dynamic_page_without_a_matching_resource_is_still_traced_and_a_scanner_404_is_not() {
    let root: PathBuf = built_site("trace-404");
    let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
        .root_dir(&root)
        .frontend(frontend_with(pages()))
        .into_router(Shutdown::manual())
        .expect("the built site boots");

    let actual: Vec<String> = names(
        &transactions(
            &router,
            &[
                (Method::GET, "/things/missing"),
                (Method::GET, "/wp-admin/setup.php"),
            ],
        )
        .await,
    );

    assert_eq!(vec![String::from("GET /things/{slug}")], actual);
}

#[tokio::test(flavor = "current_thread")]
async fn trailing_slash_redirects_are_never_traced_but_pages_under_their_prefix_are() {
    let root: PathBuf = built_site("trace-redirects");
    let pages: Pages = Pages::new()
        .static_page(PageTemplateData::new("home", "Home", "/"), ())
        .static_page(PageTemplateData::new("home", "About", "/about"), ())
        .dynamic_page("/things/{slug}", axum::routing::get(super::thing))
        .unlisted()
        .dynamic_page("/docs/", axum::routing::get(|| async { "docs" }))
        .dynamic_page("/docs/{slug}", axum::routing::get(super::thing))
        .unlisted();
    let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
        .root_dir(&root)
        .frontend(frontend_with(pages))
        .into_router(Shutdown::manual())
        .expect("the built site boots");

    let actual: Vec<String> = names(
        &transactions(
            &router,
            &[
                (Method::GET, "/about/"),
                (Method::GET, "/things/a-slug/"),
                (Method::GET, "/docs"),
                (Method::GET, "/about"),
                (Method::GET, "/docs/a-slug"),
            ],
        )
        .await,
    );

    let expected: Vec<String> = vec![String::from("GET /about"), String::from("GET /docs/{slug}")];
    assert_eq!(expected, actual);
}

#[tokio::test(flavor = "current_thread")]
async fn a_projects_own_nested_service_is_never_traced() {
    let root: PathBuf = built_site("trace-nested");
    std::fs::write(root.join("note.txt"), "hello").expect("a writable root");
    let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
        .root_dir(&root)
        .frontend(frontend_with(pages()))
        .nest_service("/downloads/", tower_http::services::ServeDir::new(&root))
        .into_router(Shutdown::manual())
        .expect("the built site boots");

    let actual: Vec<String> = names(
        &transactions(
            &router,
            &[
                (Method::GET, "/downloads/note.txt"),
                (Method::GET, "/downloads/missing.txt"),
                (Method::GET, "/"),
            ],
        )
        .await,
    );

    assert_eq!(vec![String::from("GET /")], actual);
}

#[tokio::test(flavor = "current_thread")]
async fn an_incoming_sampled_flag_does_not_turn_tracing_on_when_the_server_rate_is_off() {
    let root: PathBuf = built_site("trace-flag-off");
    let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
        .root_dir(&root)
        .frontend(frontend_with(pages()))
        .into_router(Shutdown::manual())
        .expect("the built site boots");

    let actual: Vec<String> = names(
        &transactions_at(
            &router,
            TracesSampleRate::OFF,
            Some("771a43a4192642f0b136d5159a501700-1234567890abcdef-1"),
            &[(Method::GET, "/")],
        )
        .await,
    );

    assert!(actual.is_empty(), "{actual:?}");
}

#[tokio::test(flavor = "current_thread")]
async fn the_proxy_scripts_and_endpoints_are_on_the_untraced_list() {
    let root: PathBuf = built_site("trace-library");
    let cache_buster: crate::assets::CacheBuster =
        crate::assets::CacheBuster::load_in(&root).expect("the manifest the build wrote");
    let frontend: crate::webserver::Frontend<()> = crate::webserver::Frontend::build(
        frontend_with_analytics(analytics_home(), AnalyticsConfig::new("pa-fixture")),
        None,
        &cache_buster,
        Environment::Production,
    )
    .expect("the frontend builds");

    let routes: Vec<String> = super::super::server::library_routes(&frontend);

    for path in [
        &frontend.runtime.sentry_browser.script_path,
        &frontend.runtime.sentry_browser.tunnel_path,
        &frontend
            .runtime
            .analytics
            .as_ref()
            .expect("enabled")
            .script_path,
        &frontend
            .runtime
            .analytics
            .as_ref()
            .expect("enabled")
            .event_path,
    ] {
        assert!(routes.contains(path), "{path} in {routes:?}");
    }
}

fn params_at(rate: Option<TracesSampleRate>) -> FrontendParams {
    let params: FrontendParams = frontend_with(analytics_home());
    match rate {
        Some(rate) => params.with_browser_traces_sample_rate(rate),
        None => params,
    }
}

async fn page_at(name: &str, rate: Option<TracesSampleRate>) -> String {
    let root: PathBuf = built_site(name);
    let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
        .root_dir(&root)
        .frontend(params_at(rate))
        .into_router(Shutdown::manual())
        .expect("the built site boots");
    text(get(&router, "/").await).await
}

#[tokio::test]
async fn a_browser_rate_of_zero_renders_errors_only_init_and_a_no_op_span_helper() {
    let body: String = page_at("trace-browser-off", Some(TracesSampleRate::OFF)).await;

    assert!(body.contains("Sentry.init({"), "{body}");
    assert!(
        body.contains(
            "dsn: \"https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968\""
        ),
        "{body}"
    );
    assert!(body.contains("tunnel: \"/api/v1/fixture-"), "{body}");
    assert!(!body.contains("tracesSampleRate"), "{body}");
    assert!(!body.contains("browserTracingIntegration"), "{body}");
    assert!(!body.contains("startInactiveSpan"), "{body}");
    assert!(body.contains("window.webserverBase = {"), "{body}");
    assert!(!body.contains("sentryOnLoad"), "{body}");
}

#[tokio::test]
async fn the_span_helper_exists_before_sentry_is_touched_so_a_blocked_bundle_cannot_break_page_scripts()
 {
    let body: String = page_at("trace-browser-blocked", None).await;

    let helper: usize = body.find("window.webserverBase = ").expect("the helper");
    let init: usize = body.find("Sentry.init({").expect("the init");
    assert!(helper < init, "{body}");
    assert!(body.contains("typeof Sentry !== \"undefined\""), "{body}");
}

#[tokio::test]
async fn a_browser_rate_above_zero_renders_tracing_init_at_that_rate() {
    let body: String = page_at(
        "trace-browser-on",
        Some(TracesSampleRate::new(0.05).expect("valid")),
    )
    .await;

    assert!(body.contains("tracesSampleRate: 0.05,"), "{body}");
    assert!(
        body.contains("integrations: [Sentry.browserTracingIntegration()],"),
        "{body}"
    );
    assert!(body.contains("Sentry.startInactiveSpan({"), "{body}");
    assert!(body.contains("window.webserverBase = {"), "{body}");
}

#[tokio::test]
async fn the_browser_rate_defaults_to_the_named_constant() {
    let body: String = page_at("trace-browser-default", None).await;

    let expected: String = format!(
        "tracesSampleRate: {},",
        crate::DEFAULT_BROWSER_TRACES_SAMPLE_RATE
    );
    assert!(body.contains(&expected), "{body}");
}

#[tokio::test]
async fn the_page_script_order_puts_the_bundle_before_the_init_module() {
    let body: String = page_at("trace-browser-order", None).await;

    let bundle: usize = body
        .find("<script defer src=\"/script/fixture-")
        .expect("the bundle tag");
    let init: usize = body
        .find("<script type=\"module\">")
        .expect("the init module");
    assert!(bundle < init, "{body}");
}

async fn page_with_release(name: &str, release: Option<&str>) -> String {
    let root: PathBuf = built_site(name);
    let params: FrontendParams = match release {
        Some(release) => frontend_with(analytics_home()).with_browser_release(release),
        None => frontend_with(analytics_home()),
    };
    let router: Router = WebServer::new("127.0.0.1", 0, Environment::Local)
        .root_dir(&root)
        .frontend(params)
        .into_router(Shutdown::manual())
        .expect("the built site boots");
    text(get(&router, "/").await).await
}

#[tokio::test]
async fn without_a_browser_release_the_page_is_identical_and_has_no_release_key() {
    let without: String = page_with_release("release-absent", None).await;

    let start: usize = without.find("Sentry.init({").expect("the init");
    let end: usize = start + without[start..].find("});").expect("the init end");
    let init: Vec<&str> = without[start..end].lines().map(str::trim).collect();
    assert_eq!(init.len(), 7, "{init:?}");
    assert_eq!(init[0], "Sentry.init({");
    assert_eq!(
        init[1],
        "dsn: \"https://abc123@o4504844394627072.ingest.sentry.io/4504862450515968\","
    );
    assert_eq!(init[2], "environment: \"local\",");
    assert!(
        init[3].starts_with("tunnel: \"/api/v1/fixture-"),
        "{init:?}"
    );
    assert!(init[3].ends_with("\","), "{init:?}");
    assert_eq!(
        init[4],
        format!(
            "tracesSampleRate: {},",
            crate::DEFAULT_BROWSER_TRACES_SAMPLE_RATE
        )
    );
    assert_eq!(
        init[5],
        "integrations: [Sentry.browserTracingIntegration()],"
    );
    assert_eq!(init[6], "");

    let with: String = page_with_release("release-present-plain", Some("site@1.2.3")).await;
    let stripped: String = with.replace("        release: \"site@1.2.3\",\n", "");
    assert_eq!(without, stripped);
    assert!(with.contains("release: \"site@1.2.3\","), "{with}");
}

#[tokio::test]
async fn a_browser_release_is_a_json_string_that_cannot_break_out_of_the_script() {
    let body: String = page_with_release("release-hostile", Some("v\"1</script><b>\u{2028}")).await;

    assert!(
        body.contains("release: \"v\\\"1\\u003c/script>\\u003cb>\\u2028\","),
        "{body}"
    );
    assert!(!body.contains("</script><b>"), "{body}");
}

#[tokio::test]
async fn a_backslash_in_a_browser_release_is_escaped() {
    let body: String = page_with_release("release-backslash", Some("a\\b")).await;

    assert!(body.contains("release: \"a\\\\b\","), "{body}");
}

#[tokio::test]
async fn an_html_comment_opener_in_a_browser_release_is_escaped() {
    let body: String = page_with_release("release-comment", Some("<!--x")).await;

    assert!(body.contains("release: \"\\u003c!--x\","), "{body}");
    assert!(!body.contains("<!--x"), "{body}");
}