rullst-security 12.3.0

Runtime application security, RASP, OWASP headers, Login Jail, and WAF middleware for Rullst.
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
use crate::telemetry::SecurityStore;
use axum::{
    body::Body,
    extract::Request,
    http::{HeaderValue, StatusCode},
    middleware::Next,
    response::{IntoResponse, Response},
};
use serde::de::{self, Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
use std::{collections::HashSet, fmt};

mod policy;
pub use policy::{JsonSchemaPolicy, SchemaPolicyError};

/// Default maximum JSON payload size: 2MB
pub const DEFAULT_MAX_PAYLOAD_BYTES: usize = 2 * 1024 * 1024;
/// Default maximum object nesting depth: 32 levels
pub const DEFAULT_MAX_NESTING_DEPTH: usize = 32;
const DUPLICATE_KEY_MARKER: &str = "duplicate JSON object key";

struct StrictJson;

impl<'de> Deserialize<'de> for StrictJson {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(StrictJsonVisitor)
    }
}

struct StrictJsonVisitor;

impl<'de> Visitor<'de> for StrictJsonVisitor {
    type Value = StrictJson;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a JSON value without duplicate object keys")
    }

    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: MapAccess<'de>,
    {
        let mut keys = HashSet::new();
        while let Some(key) = map.next_key::<String>()? {
            if !keys.insert(key) {
                return Err(de::Error::custom(DUPLICATE_KEY_MARKER));
            }
            map.next_value::<StrictJson>()?;
        }
        Ok(StrictJson)
    }

    fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
    where
        A: SeqAccess<'de>,
    {
        while sequence.next_element::<StrictJson>()?.is_some() {}
        Ok(StrictJson)
    }

    fn visit_bool<E>(self, _value: bool) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }

    fn visit_i64<E>(self, _value: i64) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }

    fn visit_u64<E>(self, _value: u64) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }

    fn visit_f64<E>(self, _value: f64) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }

    fn visit_str<E>(self, _value: &str) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }

    fn visit_string<E>(self, _value: String) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }

    fn visit_none<E>(self) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }

    fn visit_unit<E>(self) -> Result<Self::Value, E> {
        Ok(StrictJson)
    }
}

/// Validates JSON syntax, duplicate object keys, size and nesting depth.
///
/// This is a transport guard, not an OpenAPI/JSON Schema validator.
pub fn inspect_json_payload(
    bytes: &[u8],
    max_depth: usize,
    max_bytes: usize,
) -> Result<(), &'static str> {
    if bytes.len() > max_bytes {
        SecurityStore::global().inc_schema_violations();
        return Err("Payload exceeds maximum allowed size");
    }

    let mut current_depth: usize = 0;
    let mut in_string = false;
    let mut escape = false;

    for &b in bytes {
        if escape {
            escape = false;
            continue;
        }

        if b == b'\\' && in_string {
            escape = true;
            continue;
        }

        if b == b'"' {
            in_string = !in_string;
            continue;
        }

        if !in_string {
            if b == b'{' || b == b'[' {
                current_depth += 1;
                if current_depth > max_depth {
                    SecurityStore::global().inc_schema_violations();
                    return Err("Payload exceeds maximum allowed object nesting depth");
                }
            } else if b == b'}' || b == b']' {
                current_depth = current_depth.saturating_sub(1);
            }
        }
    }

    if let Err(error) = serde_json::from_slice::<StrictJson>(bytes) {
        SecurityStore::global().inc_schema_violations();
        if error.to_string().contains(DUPLICATE_KEY_MARKER) {
            return Err("JSON object contains a duplicate key");
        }
        return Err("Payload is not valid JSON");
    }

    Ok(())
}

/// Accepts every JSON media type axum's `Json` extractor accepts, in any
/// ASCII case, so a body the handler parses cannot skip these checks.
fn is_json_content_type(value: &str) -> bool {
    crate::media_type::is_json(crate::media_type::essence(value))
}

/// Middleware that inspects application/json request payloads for JSON bombs and depth limits.
pub async fn schema_guard_middleware(req: Request, next: Next) -> Response {
    let content_type = req
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v: &HeaderValue| v.to_str().ok())
        .unwrap_or("");

    if is_json_content_type(content_type) {
        let (parts, body) = req.into_parts();

        // Read request body up to MAX_PAYLOAD_BYTES + 1
        let bytes = match axum::body::to_bytes(body, DEFAULT_MAX_PAYLOAD_BYTES + 1).await {
            Ok(b) => b,
            Err(_) => {
                SecurityStore::global().inc_schema_violations();
                return (
                    StatusCode::BAD_REQUEST,
                    "Failed to read JSON request body or payload too large",
                )
                    .into_response();
            }
        };

        if let Err(err_msg) =
            inspect_json_payload(&bytes, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_PAYLOAD_BYTES)
        {
            return (StatusCode::BAD_REQUEST, err_msg).into_response();
        }

        let reconstructed_req = Request::from_parts(parts, Body::from(bytes));
        next.run(reconstructed_req).await
    } else {
        next.run(req).await
    }
}

/// Route-scoped middleware that applies the strict transport checks and then a
/// precompiled JSON Schema 2020-12 policy supplied by the application.
///
/// Mount this with `axum::middleware::from_fn_with_state`. The policy disables
/// filesystem and network reference resolution and accepts only local `$ref`
/// and `$dynamicRef` values.
pub async fn json_schema_guard_middleware(
    axum::extract::State(policy): axum::extract::State<JsonSchemaPolicy>,
    req: Request,
    next: Next,
) -> Response {
    let content_type = req
        .headers()
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .unwrap_or("");
    if !is_json_content_type(content_type) {
        if matches!(
            *req.method(),
            axum::http::Method::GET | axum::http::Method::HEAD | axum::http::Method::OPTIONS
        ) {
            return next.run(req).await;
        }
        SecurityStore::global().inc_schema_violations();
        return (
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            "This route requires a JSON Content-Type",
        )
            .into_response();
    }

    let (parts, body) = req.into_parts();
    let bytes = match axum::body::to_bytes(body, DEFAULT_MAX_PAYLOAD_BYTES + 1).await {
        Ok(bytes) => bytes,
        Err(_) => {
            SecurityStore::global().inc_schema_violations();
            return (
                StatusCode::BAD_REQUEST,
                "Failed to read JSON request body or payload too large",
            )
                .into_response();
        }
    };
    if let Err(message) =
        inspect_json_payload(&bytes, DEFAULT_MAX_NESTING_DEPTH, DEFAULT_MAX_PAYLOAD_BYTES)
    {
        return (StatusCode::BAD_REQUEST, message).into_response();
    }
    let instance = match serde_json::from_slice(&bytes) {
        Ok(instance) => instance,
        Err(_) => {
            SecurityStore::global().inc_schema_violations();
            return (StatusCode::BAD_REQUEST, "Payload is not valid JSON").into_response();
        }
    };
    if policy.validate(&instance).is_err() {
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            "JSON payload does not match the configured schema",
        )
            .into_response();
    }

    next.run(Request::from_parts(parts, Body::from(bytes)))
        .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{Router, http::Request, middleware, routing::post};
    use tower::ServiceExt;

    #[test]
    fn test_inspect_json_payload_valid() {
        let json = b"{\"user\": {\"name\": \"Alice\", \"roles\": [\"admin\", \"user\"]}}";
        assert!(inspect_json_payload(json, 10, 1024).is_ok());
    }

    #[test]
    fn test_inspect_json_payload_braces_in_strings() {
        // String with 50 braces should not trigger a depth limit of 5
        let json = br#"{"snippet": "{{{{{{{{{{[[[[[[[[[[}}}}}}}}}}]]]]]]]]]]", "status": 200}"#;
        assert!(inspect_json_payload(json, 5, 1024).is_ok());
    }

    #[test]
    fn test_inspect_json_payload_excessive_depth() {
        let mut deep_json = Vec::new();
        for _ in 0..40 {
            deep_json.extend_from_slice(b"{\"a\":");
        }
        deep_json.extend_from_slice(b"1");
        for _ in 0..40 {
            deep_json.extend_from_slice(b"}");
        }

        let res = inspect_json_payload(&deep_json, 10, 1024 * 1024);
        assert!(res.is_err());
        assert_eq!(
            res.unwrap_err(),
            "Payload exceeds maximum allowed object nesting depth"
        );
    }

    #[test]
    fn test_inspect_json_payload_too_large() {
        let json = vec![b'a'; 2000];
        let res = inspect_json_payload(&json, 10, 1000);
        assert!(res.is_err());
        assert_eq!(res.unwrap_err(), "Payload exceeds maximum allowed size");
    }

    #[test]
    fn syntax_and_duplicate_keys_are_rejected_recursively() {
        assert_eq!(
            inspect_json_payload(br#"{"role":"user","role":"admin"}"#, 10, 1_024),
            Err("JSON object contains a duplicate key")
        );
        assert_eq!(
            inspect_json_payload(br#"{"outer":{"id":1,"id":2}}"#, 10, 1_024),
            Err("JSON object contains a duplicate key")
        );
        assert_eq!(
            inspect_json_payload(br#"{"unterminated":true"#, 10, 1_024),
            Err("Payload is not valid JSON")
        );
    }

    #[test]
    fn content_type_matching_is_exact_and_supports_json_suffixes() {
        assert!(is_json_content_type("application/json; charset=utf-8"));
        assert!(is_json_content_type("application/problem+json"));
        assert!(!is_json_content_type("text/application/json"));
        assert!(!is_json_content_type("application/json-malicious"));
    }

    #[test]
    fn content_type_matching_accepts_every_json_form_axum_parses() {
        for content_type in [
            "APPLICATION/JSON",
            "application/vnd.api+JSON",
            "Application/problem+json; charset=utf-8",
            "application/json+patch",
        ] {
            assert!(is_json_content_type(content_type), "{content_type}");
        }
        for content_type in ["application/xml", "text/json", "application/jsonp"] {
            assert!(!is_json_content_type(content_type), "{content_type}");
        }
    }

    #[tokio::test]
    async fn case_and_suffix_variants_cannot_skip_duplicate_key_checks() {
        for content_type in ["application/vnd.api+JSON", "Application/problem+json"] {
            let response = guarded_app()
                .oneshot(
                    Request::post("/")
                        .header(axum::http::header::CONTENT_TYPE, content_type)
                        .body(Body::from(r#"{"role":"user","role":"admin"}"#))
                        .expect("request should be valid"),
                )
                .await
                .expect("middleware request should complete");
            assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{content_type}");
        }
    }

    fn guarded_app() -> Router {
        Router::new()
            .route("/", post(|body: String| async move { body }))
            .layer(middleware::from_fn(schema_guard_middleware))
    }

    #[tokio::test]
    async fn middleware_preserves_valid_json_and_non_json_bodies() {
        for (content_type, body) in [
            ("application/json; charset=utf-8", r#"{"safe":[1,2,3]}"#),
            ("text/plain", "not JSON { and deliberately unbalanced"),
        ] {
            let response = guarded_app()
                .oneshot(
                    Request::post("/")
                        .header(axum::http::header::CONTENT_TYPE, content_type)
                        .body(Body::from(body))
                        .expect("request should be valid"),
                )
                .await
                .expect("middleware request should complete");
            assert_eq!(response.status(), StatusCode::OK);
            let returned = axum::body::to_bytes(response.into_body(), 1_024)
                .await
                .expect("response body should be readable");
            assert_eq!(returned.as_ref(), body.as_bytes());
        }
    }

    #[tokio::test]
    async fn middleware_rejects_deep_and_oversized_json() {
        let deep = format!("{}0{}", "[".repeat(33), "]".repeat(33));
        let response = guarded_app()
            .oneshot(
                Request::post("/")
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .body(Body::from(deep))
                    .expect("request should be valid"),
            )
            .await
            .expect("middleware request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);

        let response = guarded_app()
            .oneshot(
                Request::post("/")
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .body(Body::from(vec![b' '; DEFAULT_MAX_PAYLOAD_BYTES + 2]))
                    .expect("request should be valid"),
            )
            .await
            .expect("middleware request should complete");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    fn schema_bound_app() -> Router {
        let policy = JsonSchemaPolicy::from_schema(serde_json::json!({
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "type": "object",
            "properties": {"name": {"type": "string", "minLength": 1}},
            "required": ["name"],
            "additionalProperties": false
        }))
        .expect("route schema");
        Router::new().route(
            "/",
            post(|body: String| async move { body }).layer(middleware::from_fn_with_state(
                policy,
                json_schema_guard_middleware,
            )),
        )
    }

    #[tokio::test]
    async fn compiled_schema_middleware_preserves_valid_bodies_and_fails_closed() {
        let valid = schema_bound_app()
            .oneshot(
                Request::post("/")
                    .header(axum::http::header::CONTENT_TYPE, "application/json")
                    .body(Body::from(r#"{"name":"Ada"}"#))
                    .expect("valid request"),
            )
            .await
            .expect("valid schema response");
        assert_eq!(valid.status(), StatusCode::OK);
        let returned = axum::body::to_bytes(valid.into_body(), 1_024)
            .await
            .expect("preserved body");
        assert_eq!(returned, r#"{"name":"Ada"}"#);

        for (content_type, body, expected) in [
            (
                "application/json",
                r#"{"name":"Ada","role":"admin"}"#,
                StatusCode::UNPROCESSABLE_ENTITY,
            ),
            (
                "application/json",
                r#"{"name":"Ada","name":"Mallory"}"#,
                StatusCode::BAD_REQUEST,
            ),
            (
                "text/plain",
                r#"{"name":"Ada"}"#,
                StatusCode::UNSUPPORTED_MEDIA_TYPE,
            ),
        ] {
            let response = schema_bound_app()
                .oneshot(
                    Request::post("/")
                        .header(axum::http::header::CONTENT_TYPE, content_type)
                        .body(Body::from(body))
                        .expect("schema rejection request"),
                )
                .await
                .expect("schema rejection response");
            assert_eq!(response.status(), expected);
        }
    }
}