rustango 0.65.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! Query-parameter parsing shared by list endpoints.
//!
//! [`viewset::handle_list`](crate::viewset) and the
//! [`ListView`](crate::template_views::ListView) CBV read the same
//! parameters: `?page=N`, `?ordering=col`, `?search=term`, and the
//! model's own filter keys. This module holds the parts they must
//! agree on:
//!
//! * [`RESERVED_LIST_KEYS`] / [`is_reserved_list_key`] — parameters
//!   that control paging, sorting and search, so they are never
//!   filters.
//! * [`parse_ordering`] — splits `?ordering=col,-col2`.
//! * [`clamp_page_size`] — resolves `?page_size=N`.
//! * [`parse_page`] / [`page_offset`] — `?page=N` and its overflow-safe offset;
//!   [`check_offset`] refuses one past [`DEFAULT_MAX_OFFSET`] or the list's own cap.
//! * [`split_in_list`] — a `__in` value, capped at [`MAX_IN_VALUES`];
//!   [`in_values_budget`] caps all lists of a request together.
//! * [`reject_nul`] — refuses a filter or search value holding `\0`.
//!
//! Each layer still builds its own WHERE clause, because viewset
//! supports a richer filter syntax than the CBV.
//!
//! [`RESERVED_LIST_KEYS`]: crate::list_params::RESERVED_LIST_KEYS
//! [`is_reserved_list_key`]: crate::list_params::is_reserved_list_key
//! [`parse_ordering`]: crate::list_params::parse_ordering
//! [`clamp_page_size`]: crate::list_params::clamp_page_size
//! [`parse_page`]: crate::list_params::parse_page
//! [`page_offset`]: crate::list_params::page_offset
//! [`check_offset`]: crate::list_params::check_offset
//! [`DEFAULT_MAX_OFFSET`]: crate::list_params::DEFAULT_MAX_OFFSET
//! [`split_in_list`]: crate::list_params::split_in_list
//! [`MAX_IN_VALUES`]: crate::list_params::MAX_IN_VALUES
//! [`in_values_budget`]: crate::list_params::in_values_budget
//! [`reject_nul`]: crate::list_params::reject_nul

use std::collections::HashMap;

use crate::core::{ModelSchema, OrderItem};

/// Query keys that control paging, sorting and search. A list
/// handler must never treat one of these as a model filter, even if
/// a column has the same name.
pub const RESERVED_LIST_KEYS: &[&str] = &[
    "page",
    "page_size",
    "ordering",
    "search",
    "cursor",
    "limit",
    "offset",
];

/// `true` when `key` is one of [`RESERVED_LIST_KEYS`]. Use it to
/// skip these keys before parsing filters:
///
/// ```ignore
/// for (k, v) in &params {
///     if rustango::list_params::is_reserved_list_key(k) {
///         continue;
///     }
///     // ... treat as filter ...
/// }
/// ```
#[must_use]
pub fn is_reserved_list_key(key: &str) -> bool {
    RESERVED_LIST_KEYS.iter().any(|r| *r == key)
}

/// Parse `?ordering=col,-col2,col3` into [`OrderItem`]s. A leading
/// `-` means descending.
///
/// A token is dropped, without error, when it is not in `allowlist`
/// or when [`ModelSchema::field`] does not know it. An empty allowlist
/// permits nothing, so a client cannot sort by `password_hash` (#1996).
///
/// The result is empty when nothing survives, and the caller should
/// then fall back to its default ordering.
///
/// A column is kept at its first mention only, and at most
/// [`MAX_ORDERING_TERMS`] columns are kept, so a long query string
/// cannot build a huge `ORDER BY`.
#[must_use]
pub fn parse_ordering(
    raw: &str,
    allowlist: &[String],
    schema: &'static ModelSchema,
) -> Vec<OrderItem> {
    let mut seen: Vec<&'static str> = Vec::new();
    raw.split(',')
        .filter(|s| !s.is_empty())
        .filter_map(|part| {
            let (field_name, desc) = if let Some(name) = part.strip_prefix('-') {
                (name, true)
            } else {
                (part, false)
            };
            if !allowlist.iter().any(|f| f == field_name) {
                return None;
            }
            let column = schema.field(field_name)?.column;
            // A later term on the same column cannot change the order.
            if seen.contains(&column) {
                return None;
            }
            seen.push(column);
            Some(OrderItem::column(column, desc))
        })
        .take(MAX_ORDERING_TERMS)
        .collect()
}

/// Most `?ordering=` columns [`parse_ordering`] keeps.
pub const MAX_ORDERING_TERMS: usize = 8;

/// Work out the page size from `?page_size=N`.
///
/// A value above `max` is clamped to `max`, which stops a client
/// asking for a million rows. A missing, unparseable, zero or
/// negative value gives `default`.
#[must_use]
pub fn clamp_page_size(default: i64, max: i64, params: &HashMap<String, String>) -> i64 {
    params
        .get("page_size")
        .and_then(|s| s.parse::<i64>().ok())
        .filter(|n| *n > 0)
        .map_or(default, |n| n.min(max))
}

/// Most values one `?field__in=` list may carry. Far under every
/// dialect's bind limit, so a long list is a 400, not a driver error (#1865).
pub const MAX_IN_VALUES: usize = 1000;

/// Binds a list request keeps free for its other filters, search and paging.
const RESERVED_BINDS: usize = 1000;

/// A `__in` list longer than [`MAX_IN_VALUES`], or `__in` lists whose sum
/// passes [`in_values_budget`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InListTooLong {
    /// One list is over [`MAX_IN_VALUES`].
    One,
    /// All lists together are over this budget.
    Total(usize),
}

impl std::fmt::Display for InListTooLong {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::One => write!(f, "an `__in` filter takes at most {MAX_IN_VALUES} values"),
            Self::Total(n) => write!(f, "the `__in` filters take at most {n} values in total"),
        }
    }
}

/// Most `__in` values one request may carry over all its lists, so a dialect
/// with `max_bind_params` binds gets a 400 rather than a driver 500.
#[must_use]
pub fn in_values_budget(max_bind_params: usize) -> usize {
    max_bind_params.saturating_sub(RESERVED_BINDS)
}

/// Split a comma-separated `__in` value, dropping empty entries.
/// Stops reading past the cap, so a 2 MB body is not split in full.
///
/// # Errors
/// [`InListTooLong`] when more than [`MAX_IN_VALUES`] entries remain.
pub fn split_in_list(raw: &str) -> Result<Vec<&str>, InListTooLong> {
    let parts: Vec<&str> = raw
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .take(MAX_IN_VALUES + 1)
        .collect();
    if parts.len() > MAX_IN_VALUES {
        return Err(InListTooLong::One);
    }
    Ok(parts)
}

/// `?page=N`, 1-based. Missing, garbage, zero or negative gives page 1.
#[must_use]
pub fn parse_page(params: &HashMap<String, String>) -> i64 {
    params
        .get("page")
        .and_then(|s| s.parse::<i64>().ok())
        .unwrap_or(1)
        .max(1)
}

/// Row offset of 1-based `page`. Saturates, so a huge page is an
/// empty page rather than a wrapped negative OFFSET (#1865).
#[must_use]
pub fn page_offset(page: i64, page_size: i64) -> i64 {
    page.max(1)
        .saturating_sub(1)
        .saturating_mul(page_size.max(0))
}

/// Default deepest row a list may skip to: a deeper `OFFSET` reads every
/// skipped row, so one short URL costs a near-full scan.
pub const DEFAULT_MAX_OFFSET: usize = 10_000;

/// An offset past the list's cap.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct OffsetTooDeep;

impl std::fmt::Display for OffsetTooDeep {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("this page is too deep; narrow the list with filters or use cursor pagination")
    }
}

impl std::error::Error for OffsetTooDeep {}

/// `offset`, unless it is past `max`; `max = 0` lifts the cap.
///
/// # Errors
/// [`OffsetTooDeep`] when `offset > max`.
pub fn check_offset(offset: i64, max: usize) -> Result<i64, OffsetTooDeep> {
    let cap = i64::try_from(max).unwrap_or(i64::MAX);
    if max > 0 && offset > cap {
        Err(OffsetTooDeep)
    } else {
        Ok(offset)
    }
}

/// A filter or search value holding a NUL byte.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct NulInValue;

impl std::fmt::Display for NulInValue {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("a query value must not contain a NUL byte")
    }
}

impl std::error::Error for NulInValue {}

/// `value`, unless it holds `\0`. Postgres refuses NUL in text, so every
/// backend answers 400 for it rather than PG alone failing with a 500.
///
/// # Errors
/// [`NulInValue`] when `value` contains a NUL byte.
pub fn reject_nul(value: &str) -> Result<&str, NulInValue> {
    if value.contains('\0') {
        Err(NulInValue)
    } else {
        Ok(value)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// An empty allow-list sorts on nothing, not on every column (#1996).
    #[test]
    fn parse_ordering_with_an_empty_allowlist_is_empty() {
        static FIELDS: &[crate::core::FieldSchema] = &[crate::core::FieldSchema::new(
            "secret",
            "secret",
            crate::core::FieldType::String,
        )];
        let mut schema = ModelSchema::new("lp_t", "lp_t");
        schema.fields = FIELDS;
        let schema: &'static ModelSchema = Box::leak(Box::new(schema));
        assert!(parse_ordering("secret,-secret", &[], schema).is_empty());
        let allowed = parse_ordering("-secret", &["secret".to_owned()], schema);
        assert_eq!(allowed.len(), 1);
    }

    /// Repeats collapse to the first mention, and at most eight columns sort.
    #[test]
    fn parse_ordering_dedups_and_caps() {
        static FIELDS: &[crate::core::FieldSchema] = &[
            crate::core::FieldSchema::new("a", "a", crate::core::FieldType::String),
            crate::core::FieldSchema::new("b", "b", crate::core::FieldType::String),
        ];
        let mut schema = ModelSchema::new("lp_d", "lp_d");
        schema.fields = FIELDS;
        let schema: &'static ModelSchema = Box::leak(Box::new(schema));
        let allow = ["a".to_owned(), "b".to_owned()];
        let raw = ["-a"; 10_000].join(",") + ",b";
        let got = parse_ordering(&raw, &allow, schema);
        assert_eq!(got.len(), 2);
        assert_eq!(got[0], OrderItem::column("a", true));
        assert_eq!(got[1], OrderItem::column("b", false));

        let many: Vec<String> = (0..12).map(|i| format!("f{i}")).collect();
        let fields: &'static [crate::core::FieldSchema] = Box::leak(
            many.iter()
                .map(|n| {
                    let n: &'static str = Box::leak(n.clone().into_boxed_str());
                    crate::core::FieldSchema::new(n, n, crate::core::FieldType::String)
                })
                .collect::<Vec<_>>()
                .into_boxed_slice(),
        );
        let mut wide = ModelSchema::new("lp_w", "lp_w");
        wide.fields = fields;
        let wide: &'static ModelSchema = Box::leak(Box::new(wide));
        let got = parse_ordering(&many.join(","), &many, wide);
        assert_eq!(got.len(), MAX_ORDERING_TERMS);
    }

    #[test]
    fn page_offset_saturates_instead_of_wrapping() {
        assert_eq!(page_offset(1, 20), 0);
        assert_eq!(page_offset(3, 20), 40);
        assert_eq!(page_offset(i64::MAX, 50), i64::MAX);
        assert_eq!(page_offset(i64::MIN, 50), 0);
    }

    #[test]
    fn check_offset_refuses_past_the_cap_and_zero_lifts_it() {
        assert_eq!(check_offset(10, 10), Ok(10));
        assert_eq!(check_offset(11, 10), Err(OffsetTooDeep));
        assert_eq!(check_offset(i64::MAX, 0), Ok(i64::MAX));
    }

    #[test]
    fn parse_page_clamps_to_one() {
        let mut p = HashMap::new();
        assert_eq!(parse_page(&p), 1);
        p.insert("page".into(), "-4".into());
        assert_eq!(parse_page(&p), 1);
        p.insert("page".into(), i64::MAX.to_string());
        assert_eq!(parse_page(&p), i64::MAX);
    }

    #[test]
    fn in_list_cap_is_under_every_dialect_bind_limit() {
        use crate::sql::Dialect as _;
        assert!(MAX_IN_VALUES < crate::sql::Postgres.max_bind_params());
        assert!(MAX_IN_VALUES < crate::sql::MySql.max_bind_params());
        assert!(MAX_IN_VALUES < crate::sql::Sqlite.max_bind_params());
    }

    #[test]
    fn split_in_list_caps_values() {
        let ok = vec!["1"; MAX_IN_VALUES].join(",");
        assert_eq!(split_in_list(&ok).unwrap().len(), MAX_IN_VALUES);
        let long = vec!["1"; MAX_IN_VALUES + 1].join(",");
        assert_eq!(split_in_list(&long), Err(InListTooLong::One));
        assert_eq!(split_in_list("1,,2, ").unwrap(), ["1", "2"]);
    }

    #[test]
    fn reserved_keys_match_documented_set() {
        for k in [
            "page",
            "page_size",
            "ordering",
            "search",
            "cursor",
            "limit",
            "offset",
        ] {
            assert!(is_reserved_list_key(k), "{k} should be reserved");
        }
        assert!(!is_reserved_list_key("name"));
        assert!(!is_reserved_list_key("created_at"));
        assert!(!is_reserved_list_key(""));
    }

    #[test]
    fn clamp_page_size_picks_param_when_valid() {
        let mut p = HashMap::new();
        p.insert("page_size".into(), "30".into());
        assert_eq!(clamp_page_size(20, 100, &p), 30);
    }

    #[test]
    fn clamp_page_size_caps_at_max() {
        let mut p = HashMap::new();
        p.insert("page_size".into(), "999".into());
        assert_eq!(clamp_page_size(20, 100, &p), 100);
    }

    #[test]
    fn clamp_page_size_falls_back_on_missing() {
        let p = HashMap::new();
        assert_eq!(clamp_page_size(20, 100, &p), 20);
    }

    #[test]
    fn clamp_page_size_falls_back_on_garbage() {
        let mut p = HashMap::new();
        p.insert("page_size".into(), "not-a-number".into());
        assert_eq!(clamp_page_size(20, 100, &p), 20);
    }

    #[test]
    fn clamp_page_size_falls_back_on_zero_or_negative() {
        let mut p = HashMap::new();
        p.insert("page_size".into(), "0".into());
        assert_eq!(clamp_page_size(20, 100, &p), 20);
        p.insert("page_size".into(), "-5".into());
        assert_eq!(clamp_page_size(20, 100, &p), 20);
    }
}