1
use super::*;
2
use axum::{
3
    Form, Router,
4
    body::to_bytes,
5
    http::StatusCode,
6
    middleware::{self, Next},
7
    routing::{get, post},
8
};
9
use serde::Deserialize;
10
use tower::ServiceExt;
11

            
12
const HOSTILE: &str = "<script>alert(1)</script>";
13

            
14
28
async fn failing() -> Result<&'static str, WebError> {
15
28
    Err(WebError::unprocessable(HOSTILE))
16
28
}
17

            
18
10
async fn logged_out() -> Result<&'static str, WebError> {
19
10
    Err(WebError::unauthorized("Not logged in"))
20
10
}
21

            
22
4
async fn forbidden() -> Result<&'static str, WebError> {
23
4
    Err(WebError::forbidden("No admin"))
24
4
}
25

            
26
4
async fn down() -> Result<&'static str, WebError> {
27
4
    Err(WebError::unavailable("Temporarily unavailable"))
28
4
}
29

            
30
2
async fn fine() -> &'static str {
31
2
    "OK"
32
2
}
33

            
34
#[derive(Deserialize)]
35
struct Flag {
36
    enabled: bool,
37
}
38

            
39
async fn takes_form(Form(flag): Form<Flag>) -> String {
40
    flag.enabled.to_string()
41
}
42

            
43
/// Stands in for `auth`, which appends rotated cookies to whatever the handler answered.
44
54
async fn rotating_cookies(req: Request<Body>, next: Next) -> Response {
45
54
    let mut response = next.run(req).await;
46
54
    for cookie in ["access_token=a; HttpOnly", "refresh_token=r; HttpOnly"] {
47
108
        response
48
108
            .headers_mut()
49
108
            .append(header::SET_COOKIE, HeaderValue::from_static(cookie));
50
    }
51
54
    response
52
54
}
53

            
54
54
fn app() -> Router {
55
54
    Router::new()
56
54
        .route("/fail", get(failing))
57
54
        .route("/fine", get(fine))
58
54
        .route("/logged-out", get(logged_out))
59
54
        .route("/forbidden", get(forbidden))
60
54
        .route("/down", get(down))
61
54
        .route("/form", post(takes_form))
62
54
        .merge(
63
54
            Router::new()
64
54
                .route("/page", get(failing))
65
54
                .route("/page-logged-out", get(logged_out))
66
54
                .route_layer(middleware::from_fn(full_page)),
67
54
        )
68
54
        .layer(middleware::from_fn(rotating_cookies))
69
54
        .layer(middleware::from_fn(render_web_error))
70
54
}
71

            
72
34
async fn fetch(uri: &str, headers: &[(&str, &str)]) -> (StatusCode, String, String) {
73
34
    let mut builder = Request::builder().uri(uri);
74
34
    for (name, value) in headers {
75
52
        builder = builder.header(*name, *value);
76
    }
77
34
    let response = app()
78
34
        .oneshot(builder.body(Body::empty()).unwrap())
79
34
        .await
80
        .unwrap();
81
34
    let status = response.status();
82
34
    let content_type = header_str(response.headers(), "content-type")
83
34
        .unwrap_or_default()
84
34
        .to_string();
85
34
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
86
34
    (
87
34
        status,
88
34
        content_type,
89
34
        String::from_utf8(body.to_vec()).unwrap(),
90
34
    )
91
34
}
92

            
93
#[tokio::test]
94
2
async fn htmx_gets_an_escaped_fragment_with_the_status_kept() {
95
    let (status, content_type, body) =
96
2
        fetch("/fail", &[("hx-request", "true"), ("accept", "text/html")]).await;
97
2
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
98
2
    assert!(content_type.starts_with("text/html"));
99
2
    assert_eq!(
100
2
        body,
101
2
        r#"<div class="error-alert">&#60;script&#62;alert(1)&#60;/script&#62;</div>"#
102
2
    );
103
2
}
104

            
105
#[tokio::test]
106
2
async fn html_navigation_gets_the_error_page() {
107
2
    let (status, content_type, body) = fetch("/fail", &[("accept", "text/html")]).await;
108
2
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
109
2
    assert!(content_type.starts_with("text/html"));
110
2
    assert!(body.contains("<title>Error</title>"));
111
2
    assert!(body.contains("Error 422"));
112
2
    assert!(!body.contains(HOSTILE));
113
2
    assert!(body.contains("&#60;script&#62;"));
114
2
    assert!(body.contains(r#"href="/""#));
115
2
}
116

            
117
#[tokio::test]
118
2
async fn page_links_back_to_a_same_origin_referer() {
119
2
    let (_, _, body) = fetch(
120
2
        "/fail",
121
2
        &[
122
2
            ("accept", "text/html"),
123
2
            ("host", "app.example"),
124
2
            ("referer", "https://app.example/transaction/new?x=1"),
125
2
        ],
126
2
    )
127
2
    .await;
128
2
    assert!(body.contains(r#"href="/transaction/new?x=1""#));
129
2
}
130

            
131
#[tokio::test]
132
2
async fn page_ignores_a_foreign_referer() {
133
2
    let (_, _, body) = fetch(
134
2
        "/fail",
135
2
        &[
136
2
            ("accept", "text/html"),
137
2
            ("host", "app.example"),
138
2
            ("referer", "https://evil.example/phish"),
139
2
        ],
140
2
    )
141
2
    .await;
142
2
    assert!(body.contains(r#"href="/""#));
143
2
    assert!(!body.contains("evil.example"));
144
2
}
145

            
146
#[tokio::test]
147
2
async fn back_link_never_becomes_protocol_relative() {
148
2
    let (_, _, body) = fetch(
149
2
        "/fail",
150
2
        &[
151
2
            ("accept", "text/html"),
152
2
            ("host", "app.example"),
153
2
            ("referer", "https://app.example//evil.example/x"),
154
2
        ],
155
2
    )
156
2
    .await;
157
2
    assert!(body.contains(r#"href="/evil.example/x""#));
158
2
}
159

            
160
#[tokio::test]
161
2
async fn referer_without_a_path_links_to_the_root() {
162
2
    let (_, _, body) = fetch(
163
2
        "/fail",
164
2
        &[
165
2
            ("accept", "text/html"),
166
2
            ("host", "app.example"),
167
2
            ("referer", "https://app.example"),
168
2
        ],
169
2
    )
170
2
    .await;
171
2
    assert!(body.contains(r#"href="/""#));
172
2
}
173

            
174
#[tokio::test]
175
2
async fn other_clients_keep_the_json() {
176
2
    let (status, content_type, body) = fetch("/fail", &[("accept", "application/json")]).await;
177
2
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
178
2
    assert!(content_type.starts_with("application/json"));
179
2
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
180
2
    assert_eq!(json["status"], "error");
181
2
    assert_eq!(json["message"], HOSTILE);
182
2
}
183

            
184
#[tokio::test]
185
2
async fn responses_without_a_web_error_pass_untouched() {
186
2
    let (status, _, body) = fetch("/fine", &[("hx-request", "true")]).await;
187
2
    assert_eq!(status, StatusCode::OK);
188
2
    assert_eq!(body, "OK");
189
2
}
190

            
191
12
async fn raw(uri: &str, headers: &[(&str, &str)]) -> Response {
192
12
    let mut builder = Request::builder().uri(uri);
193
12
    for (name, value) in headers {
194
16
        builder = builder.header(*name, *value);
195
    }
196
12
    app()
197
12
        .oneshot(builder.body(Body::empty()).unwrap())
198
12
        .await
199
        .unwrap()
200
12
}
201

            
202
#[tokio::test]
203
2
async fn a_page_that_is_not_logged_in_is_sent_to_login() {
204
2
    let response = raw("/logged-out", &[("accept", "text/html")]).await;
205
2
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
206
2
    assert_eq!(response.headers().get(header::LOCATION).unwrap(), "/login");
207
2
}
208

            
209
#[tokio::test]
210
2
async fn htmx_that_is_not_logged_in_is_told_to_redirect() {
211
2
    let response = raw(
212
2
        "/logged-out",
213
2
        &[("hx-request", "true"), ("accept", "text/html")],
214
2
    )
215
2
    .await;
216
2
    assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
217
2
    assert_eq!(response.headers().get("hx-redirect").unwrap(), "/login");
218
2
    assert!(response.headers().get(header::LOCATION).is_none());
219
2
}
220

            
221
#[tokio::test]
222
2
async fn json_clients_that_are_not_logged_in_keep_the_401() {
223
    let (status, content_type, body) =
224
2
        fetch("/logged-out", &[("accept", "application/json")]).await;
225
2
    assert_eq!(status, StatusCode::UNAUTHORIZED);
226
2
    assert!(content_type.starts_with("application/json"));
227
2
    let json: serde_json::Value = serde_json::from_str(&body).unwrap();
228
2
    assert_eq!(json["message"], "Not logged in");
229
2
}
230

            
231
#[tokio::test]
232
2
async fn forbidden_is_shown_not_redirected() {
233
2
    let (status, _, page) = fetch("/forbidden", &[("accept", "text/html")]).await;
234
2
    assert_eq!(status, StatusCode::FORBIDDEN);
235
2
    assert!(page.contains("Error 403") && page.contains("No admin"));
236
2
    let (status, _, fragment) = fetch(
237
2
        "/forbidden",
238
2
        &[("hx-request", "true"), ("accept", "text/html")],
239
2
    )
240
2
    .await;
241
2
    assert_eq!(status, StatusCode::FORBIDDEN);
242
2
    assert_eq!(fragment, r#"<div class="error-alert">No admin</div>"#);
243
2
}
244

            
245
#[tokio::test]
246
2
async fn unavailable_gets_the_error_page_or_fragment() {
247
2
    let (status, _, page) = fetch("/down", &[("accept", "text/html")]).await;
248
2
    assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
249
2
    assert!(page.contains("Error 503") && page.contains("Temporarily unavailable"));
250
    let (status, _, fragment) =
251
2
        fetch("/down", &[("hx-request", "true"), ("accept", "text/html")]).await;
252
2
    assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
253
2
    assert!(fragment.contains("Temporarily unavailable"));
254
2
}
255

            
256
10
fn cookies(response: &Response) -> Vec<&str> {
257
10
    response
258
10
        .headers()
259
10
        .get_all(header::SET_COOKIE)
260
10
        .iter()
261
20
        .filter_map(|value| value.to_str().ok())
262
        .collect()
263
10
}
264

            
265
#[tokio::test]
266
2
async fn rendered_errors_keep_the_rotated_session_cookies() {
267
2
    let expected = vec!["access_token=a; HttpOnly", "refresh_token=r; HttpOnly"];
268
2
    for headers in [
269
2
        &[("accept", "text/html")][..],
270
2
        &[("hx-request", "true"), ("accept", "text/html")][..],
271
2
        &[("accept", "application/json")][..],
272
2
    ] {
273
6
        let response = raw("/fail", headers).await;
274
6
        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
275
6
        assert_eq!(cookies(&response), expected);
276
2
    }
277
2
}
278

            
279
#[tokio::test]
280
2
async fn the_login_redirect_keeps_the_cookies_too() {
281
2
    let response = raw("/logged-out", &[("accept", "text/html")]).await;
282
2
    assert_eq!(response.status(), StatusCode::SEE_OTHER);
283
2
    assert_eq!(cookies(&response).len(), 2);
284
2
}
285

            
286
6
async fn bad_form(headers: &[(&str, &str)]) -> Response {
287
6
    let mut builder = Request::builder()
288
6
        .method("POST")
289
6
        .uri("/form")
290
6
        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
291
6
    for (name, value) in headers {
292
6
        builder = builder.header(*name, *value);
293
    }
294
6
    app()
295
6
        .oneshot(
296
6
            builder
297
6
                .body(Body::from("enabled=%3Cscript%3Ealert(1)%3C/script%3E"))
298
6
                .unwrap(),
299
6
        )
300
6
        .await
301
        .unwrap()
302
6
}
303

            
304
#[tokio::test]
305
2
async fn an_extractor_rejection_is_rendered_as_an_escaped_fragment() {
306
2
    let response = bad_form(&[("hx-request", "true")]).await;
307
2
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
308
2
    assert_eq!(cookies(&response).len(), 2);
309
2
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
310
2
    let body = String::from_utf8(body.to_vec()).unwrap();
311
2
    assert!(body.starts_with(r#"<div class="error-alert">"#));
312
2
    assert!(!body.contains("<script>"));
313
2
}
314

            
315
#[tokio::test]
316
2
async fn an_extractor_rejection_gets_the_error_page_or_json() {
317
2
    let page = bad_form(&[("accept", "text/html")]).await;
318
2
    assert!(
319
2
        header_str(page.headers(), "content-type")
320
2
            .unwrap_or_default()
321
2
            .starts_with("text/html")
322
    );
323
2
    let json = bad_form(&[("accept", "application/json")]).await;
324
2
    let body = to_bytes(json.into_body(), usize::MAX).await.unwrap();
325
2
    let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
326
2
    assert_eq!(json["status"], "error");
327
2
}
328

            
329
#[tokio::test]
330
2
async fn adopting_leaves_html_json_and_success_alone() {
331
2
    let html = (StatusCode::BAD_REQUEST, Html("<p>x</p>")).into_response();
332
2
    let adopted = adopt_rejection(html).await;
333
2
    assert!(adopted.extensions().get::<WebError>().is_none());
334
2
    let ok = adopt_rejection("fine".into_response()).await;
335
2
    assert_eq!(ok.status(), StatusCode::OK);
336
2
    let own = adopt_rejection(WebError::forbidden("No").into_response()).await;
337
2
    assert_eq!(
338
2
        own.extensions().get::<WebError>(),
339
2
        Some(&WebError::forbidden("No"))
340
2
    );
341
2
}
342

            
343
#[tokio::test]
344
2
async fn a_long_rejection_text_is_bounded() {
345
2
    let long = (StatusCode::BAD_REQUEST, "x".repeat(5000)).into_response();
346
2
    let adopted = adopt_rejection(long).await;
347
2
    let error = adopted.extensions().get::<WebError>().cloned().unwrap();
348
2
    assert_eq!(error.status, StatusCode::BAD_REQUEST);
349
2
    assert!(error.message.chars().count() <= REJECTION_MESSAGE_CHARS);
350
2
}
351

            
352
#[tokio::test]
353
2
async fn a_page_route_failure_is_a_page_whatever_the_request_accepts() {
354
2
    for headers in [&[][..], &[("accept", "application/json")][..]] {
355
4
        let (status, content_type, body) = fetch("/page", headers).await;
356
4
        assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY);
357
4
        assert!(content_type.starts_with("text/html"), "{content_type}");
358
4
        assert!(body.contains("Error 422"), "{body}");
359
4
        assert!(body.contains(r#"href="/""#), "{body}");
360
    }
361
2
    let (_, _, fragment) = fetch("/page", &[("hx-request", "true")]).await;
362
2
    assert!(
363
2
        fragment.starts_with(r#"<div class="error-alert">"#),
364
        "{fragment}"
365
    );
366
2
    let (_, content_type, _) = fetch("/fail", &[]).await;
367
2
    assert!(
368
2
        content_type.starts_with("application/json"),
369
2
        "{content_type}"
370
2
    );
371
2
}
372

            
373
#[tokio::test]
374
2
async fn a_page_route_without_a_session_goes_to_login() {
375
2
    let response = app()
376
2
        .oneshot(
377
2
            Request::builder()
378
2
                .uri("/page-logged-out")
379
2
                .body(Body::empty())
380
2
                .unwrap(),
381
2
        )
382
2
        .await
383
        .unwrap();
384
2
    assert!(response.status().is_redirection());
385
2
    assert_eq!(header_str(response.headers(), "location"), Some(LOGIN));
386
2
}