runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! Multipart request parsing — text field extraction and file uploads to disk.
use crate::{
    errors::error::ErrorContext,
    utils::aliases::StrVecMap,
    utils::constante::session_key::session::CSRF_TOKEN_KEY,
    utils::trad::{t, tf},
};
use axum::{
    extract::Multipart,
    http::StatusCode,
    response::{IntoResponse, Response},
};
use futures_util::StreamExt;
use std::sync::Arc;
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
};
use tokio::io::AsyncWriteExt;
use tracing::warn;
use uuid::Uuid;

/// Staging dirs older than this are considered orphaned by a rejected upload.
const STAGING_TTL_SECS: u64 = 3600;

/// Reads a multipart body: text fields as they are, files written to a
/// `.staging-*` folder under `upload_dir` (their path as the value), each held
/// to `max_upload_mb`. No CSRF check here: the request pipeline uses
/// `parse_multipart_guarded`.
pub async fn parse_multipart(
    multipart: Multipart,
    upload_dir: &Path,
    max_upload_mb: u64,
    max_text_field_kb: usize,
) -> Result<StrVecMap, Response> {
    parse_multipart_guarded(
        multipart,
        upload_dir,
        max_upload_mb,
        max_text_field_kb,
        None,
    )
    .await
}

/// `parse_multipart`, with `csrf_session` the session token when the request
/// carries no valid `X-CSRF-Token` header: a file is then written only once a
/// `csrf_token` field matching it has been read, earlier in the body (the
/// framework renders that field before every other). A file before it ends the
/// request with a 403, nothing written.
pub(crate) async fn parse_multipart_guarded(
    mut multipart: Multipart,
    upload_dir: &Path,
    max_upload_mb: u64,
    max_text_field_kb: usize,
    csrf_session: Option<&str>,
) -> Result<StrVecMap, Response> {
    let max_file_bytes = max_upload_mb.saturating_mul(1024).saturating_mul(1024);
    let max_text_bytes = max_text_field_kb.saturating_mul(1024);

    let mut data: StrVecMap = HashMap::new();
    // Staging dir (under upload_dir → même filesystem, donc le rename de finalize()
    // est atomique). Les fichiers y restent jusqu'à ce que `FileField::finalize` les
    // committe vers leur destination servie — APRÈS CSRF + validation. Créé à la
    // demande au premier vrai fichier (aucun accès disque pour un form texte seul).
    let mut tmp_dir: Option<PathBuf> = None;
    let mut csrf_checked = csrf_session.is_none();

    // Best-effort : purge des staging laissés par des uploads précédemment rejetés.
    sweep_stale_staging(upload_dir).await;

    loop {
        // An error here (body over the limit, cut connection) ends the request:
        // stopping quietly would hand the form a body cut short.
        let mut field = match multipart.next_field().await {
            Ok(Some(field)) => field,
            Ok(None) => break,
            Err(e) => {
                if let Some(ref tmp) = tmp_dir
                    && let Err(err) = tokio::fs::remove_dir_all(tmp).await
                {
                    warn!(dir = %tmp.display(), error = %err, "staging cleanup after a body error failed");
                }
                return Err(
                    (e.status(), t("forms.multipart_stream_error").into_owned()).into_response()
                );
            }
        };
        let name = match field.name() {
            Some(n) => n.to_string(),
            None => continue,
        };

        // --- File field ---
        if let Some(filename) = field.file_name().map(std::string::ToString::to_string) {
            // No file selected (filename="" + empty body) — ignore
            if filename.is_empty() {
                while field.next().await.is_some() {}
                continue;
            }

            if !csrf_checked {
                return Err((
                    StatusCode::FORBIDDEN,
                    t("csrf.invalid_or_missing").into_owned(),
                )
                    .into_response());
            }

            // Lazy init: create upload_dir and tmp dir only on first real file.
            if tmp_dir.is_none() {
                tokio::fs::create_dir_all(upload_dir).await.map_err(|e| {
                    let msg = format!(
                        "{} — path: {:?}, os error: {}",
                        t("forms.upload_dir_error"),
                        upload_dir,
                        e
                    );
                    let ctx = ErrorContext::generic(StatusCode::INTERNAL_SERVER_ERROR, &msg);
                    let mut res = StatusCode::INTERNAL_SERVER_ERROR.into_response();
                    res.extensions_mut().insert(Arc::new(ctx));
                    res
                })?;
                let dir = upload_dir.join(format!(".staging-{}", Uuid::new_v4()));
                tokio::fs::create_dir_all(&dir).await.map_err(|_| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        t("forms.upload_dir_error").to_string(),
                    )
                        .into_response()
                })?;
                tmp_dir = Some(dir);
            }
            let cur_tmp = tmp_dir.as_ref().unwrap();

            let safe = sanitize_filename(&filename);
            let tmp_path = cur_tmp.join(&safe);

            // Stream into staging — the file handle is scoped to this block
            // to ensure its closure before any staging cleanup.
            let stream_result: Result<(), Response> = async {
                let mut file = tokio::fs::File::create(&tmp_path).await.map_err(|_| {
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        t("forms.file_create_error").to_string(),
                    )
                        .into_response()
                })?;

                let mut written: u64 = 0;
                while let Some(chunk) = field.next().await {
                    let bytes = chunk.map_err(|_| {
                        (
                            StatusCode::BAD_REQUEST,
                            t("forms.multipart_stream_error").to_string(),
                        )
                            .into_response()
                    })?;
                    written = written.saturating_add(bytes.len() as u64);
                    if written > max_file_bytes {
                        return Err((
                            StatusCode::PAYLOAD_TOO_LARGE,
                            tf("forms.upload_too_large", &[&max_upload_mb]).clone(),
                        )
                            .into_response());
                    }
                    file.write_all(&bytes).await.map_err(|_| {
                        (
                            StatusCode::INTERNAL_SERVER_ERROR,
                            t("forms.file_write_error").to_string(),
                        )
                            .into_response()
                    })?;
                }
                Ok(())
            }
            .await;

            if let Err(e) = stream_result {
                if let Some(ref tmp) = tmp_dir
                    && let Err(err) = tokio::fs::remove_dir_all(tmp).await
                {
                    warn!(dir = %tmp.display(), error = %err, "staging cleanup after stream error failed");
                }
                return Err(e);
            }

            // Chemin de staging : finalize() le committera en destination servie.
            // Pas de commit eager ici → aucune écriture servie avant CSRF/validation.
            data.entry(name)
                .or_default()
                .push(tmp_path.to_string_lossy().to_string());
        }
        // --- Text field ---
        else {
            let text_result: Result<String, Response> = async {
                let mut bytes: Vec<u8> = Vec::new();
                while let Some(chunk) = field.next().await {
                    let b = chunk.map_err(|_| {
                        (
                            StatusCode::BAD_REQUEST,
                            t("forms.multipart_stream_error").to_string(),
                        )
                            .into_response()
                    })?;
                    if bytes.len().saturating_add(b.len()) > max_text_bytes {
                        return Err((
                            StatusCode::PAYLOAD_TOO_LARGE,
                            t("forms.text_field_too_large").to_string(),
                        )
                            .into_response());
                    }
                    bytes.extend_from_slice(&b);
                }
                Ok(String::from_utf8_lossy(&bytes).into_owned())
            }
            .await;

            match text_result {
                Ok(text) => {
                    if let Some(session) = csrf_session
                        && name == CSRF_TOKEN_KEY
                        && crate::forms::extractor::token_matches(&text, session)
                    {
                        csrf_checked = true;
                    }
                    data.entry(name).or_default().push(text);
                }
                Err(e) => {
                    if let Some(ref tmp) = tmp_dir
                        && let Err(err) = tokio::fs::remove_dir_all(tmp).await
                    {
                        warn!(dir = %tmp.display(), error = %err, "staging cleanup after text-field error failed");
                    }
                    return Err(e);
                }
            }
        }
    }

    // Pas de commit ici : les fichiers restent en staging. `FileField::finalize`
    // (le seul committer) les déplacera en destination servie après CSRF + validation.
    // En cas de rejet (CSRF/validation), le staging est purgé par `sweep_stale_staging`
    // au prochain upload (best-effort, TTL).

    Ok(data)
}

/// Best-effort cleanup of orphaned `.staging-*` folders (uploads rejected before
/// `finalize`). Removes those older than `STAGING_TTL_SECS`. Failures are
/// logged, never silently swallowed.
async fn sweep_stale_staging(upload_dir: &Path) {
    let mut entries = match tokio::fs::read_dir(upload_dir).await {
        Ok(e) => e,
        Err(_) => return, // upload_dir pas encore créé : rien à purger
    };
    let now = std::time::SystemTime::now();
    loop {
        let entry = match entries.next_entry().await {
            Ok(Some(e)) => e,
            Ok(None) => break,
            Err(err) => {
                warn!(dir = %upload_dir.display(), error = %err, "staging sweep: read_dir failed");
                break;
            }
        };
        let name = entry.file_name();
        let Some(name) = name.to_str() else { continue };
        if !name.starts_with(".staging-") {
            continue;
        }
        let path = entry.path();
        let age = entry
            .metadata()
            .await
            .ok()
            .and_then(|m| m.modified().ok())
            .and_then(|t| now.duration_since(t).ok())
            .map(|d| d.as_secs())
            .unwrap_or(0);
        if age > STAGING_TTL_SECS
            && let Err(err) = tokio::fs::remove_dir_all(&path).await
        {
            warn!(dir = %path.display(), error = %err, "staging sweep: remove failed");
        }
    }
}

/// Builds a safe on-disk name `{uuid}.{ext}`. The user-supplied basename is
/// discarded (the UUID kills path traversal / name collisions); the extension is
/// kept only as lowercase ASCII alphanumerics, capped at 10 chars. This strips
/// exotic bytes — notably `:` which on NTFS would open an Alternate Data Stream
/// (`photo.php:zone`) — and normalizes case to match the extension whitelist.
fn sanitize_filename(filename: &str) -> String {
    let ext: String = Path::new(filename)
        .extension()
        .and_then(|e: &std::ffi::OsStr| e.to_str())
        .unwrap_or("")
        .chars()
        .filter(char::is_ascii_alphanumeric)
        .map(|c| c.to_ascii_lowercase())
        .take(10)
        .collect();
    let uuid = Uuid::new_v4().to_string();
    if ext.is_empty() {
        uuid
    } else {
        format!("{uuid}.{ext}")
    }
}

#[cfg(test)]
mod sanitize_tests {
    use super::sanitize_filename;

    fn ext_of(name: &str) -> String {
        // sanitize_filename returns "{uuid}.{ext}" (or just "{uuid}"); grab the ext.
        match name.rsplit_once('.') {
            Some((_, ext)) => ext.to_string(),
            None => String::new(),
        }
    }

    #[test]
    fn strips_ntfs_ads_colon_from_extension() {
        // "photo.php:zone" → extension "php:zone". The security property is that the
        // ':' (which opens an NTFS Alternate Data Stream) is removed; the remaining
        // alphanumerics are concatenated, so "php:zone" → "phpzone" (no ':' left).
        let name = sanitize_filename("photo.php:zone");
        assert!(!name.contains(':'), "colon must be stripped: {name}");
        assert_eq!(ext_of(&name), "phpzone");
    }

    #[test]
    fn lowercases_and_keeps_alnum() {
        assert_eq!(ext_of(&sanitize_filename("IMG.JPolice")), "jpolice");
        assert_eq!(ext_of(&sanitize_filename("archive.PNG")), "png");
    }

    #[test]
    fn drops_exotic_unicode_and_caps_length() {
        // Non-ASCII stripped entirely.
        assert_eq!(ext_of(&sanitize_filename("x.café")), "caf");
        // Capped at 10 chars.
        assert_eq!(
            ext_of(&sanitize_filename("x.abcdefghijklmnop")),
            "abcdefghij"
        );
    }

    #[test]
    fn no_extension_yields_bare_uuid() {
        // No dot → no extension → bare uuid (no trailing dot).
        assert!(!sanitize_filename("noext").contains('.'));
        // Extension made entirely of stripped chars → treated as no extension.
        assert!(!sanitize_filename("weird.:::").contains('.'));
    }

    #[test]
    fn dotfile_has_no_extension() {
        // ".htaccess" has no extension per Path semantics → bare uuid.
        assert!(!sanitize_filename(".htaccess").contains('.'));
    }
}

#[cfg(test)]
mod staging_tests {
    use super::*;
    use axum::body::Body;
    use axum::extract::FromRequest;
    use axum::http::Request;

    fn multipart_req(boundary: &str, field: &str, filename: &str, content: &str) -> Request<Body> {
        let body = format!(
            "--{b}\r\nContent-Disposition: form-data; name=\"{f}\"; filename=\"{fn}\"\r\nContent-Type: application/octet-stream\r\n\r\n{c}\r\n--{b}--\r\n",
            b = boundary, f = field, fn = filename, c = content
        );
        Request::builder()
            .method("POST")
            .header(
                "content-type",
                format!("multipart/form-data; boundary={boundary}"),
            )
            .body(Body::from(body))
            .unwrap()
    }

    /// The upload must NOT be committed under the media_root during parsing:
    /// it stays in staging (`.staging-*`), `finalize` will commit it later, after
    /// CSRF + validation. Secures C1 (no served write before it's been checked).
    #[tokio::test]
    async fn parse_multipart_stages_file_without_eager_commit() {
        let media = std::env::temp_dir().join(format!("rq_pm_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&media).unwrap();

        let req = multipart_req("BNDRY", "avatar", "a.png", "HELLO");
        let mp = Multipart::from_request(req, &()).await.unwrap();

        let parsed = parse_multipart(mp, &media, 10, 64).await.unwrap();

        let path = parsed.get("avatar").expect("champ avatar")[0].clone();
        let p = Path::new(&path);

        assert!(
            path.contains(".staging"),
            "chemin doit pointer vers staging: {path}"
        );
        assert!(p.exists(), "fichier présent en staging");

        // Pas de commit eager : la racine media_root ne contient que le dossier staging,
        // pas le fichier final directement.
        let filename = p.file_name().unwrap();
        assert!(
            !media.join(filename).exists(),
            "aucun fichier commité en racine media_root"
        );

        let _ = std::fs::remove_dir_all(&media);
    }

    const SESSION: &str = "a3f1c2d4e5b60718293a4b5c6d7e8f90a3f1c2d4e5b60718293a4b5c6d7e8f90";
    const OTHER: &str = "0000000000000000000000000000000000000000000000000000000000000000";

    /// A body of `(name, filename, content)` parts, in this order.
    fn parts_req(parts: &[(&str, Option<&str>, &str)]) -> Request<Body> {
        let b = "BNDRY";
        let mut body = String::new();
        for (name, filename, content) in parts {
            let disposition = match filename {
                Some(f) => format!("form-data; name=\"{name}\"; filename=\"{f}\""),
                None => format!("form-data; name=\"{name}\""),
            };
            body.push_str(&format!(
                "--{b}\r\nContent-Disposition: {disposition}\r\n\r\n{content}\r\n"
            ));
        }
        body.push_str(&format!("--{b}--\r\n"));
        Request::builder()
            .method("POST")
            .header("content-type", format!("multipart/form-data; boundary={b}"))
            .body(Body::from(body))
            .unwrap()
    }

    /// Parses with the CSRF gate on; the media folder is removed afterwards.
    /// Returns the result and whether anything was written under it.
    async fn gated(parts: &[(&str, Option<&str>, &str)]) -> (Result<StrVecMap, u16>, bool) {
        let media = std::env::temp_dir().join(format!("rq_gate_{}", uuid::Uuid::new_v4()));
        std::fs::create_dir_all(&media).unwrap();
        let mp = Multipart::from_request(parts_req(parts), &())
            .await
            .unwrap();
        let out = parse_multipart_guarded(mp, &media, 10, 64, Some(SESSION))
            .await
            .map_err(|r| r.status().as_u16());
        let written = std::fs::read_dir(&media).unwrap().next().is_some();
        let _ = std::fs::remove_dir_all(&media);
        (out, written)
    }

    #[tokio::test]
    async fn a_file_is_written_only_after_a_valid_csrf_field() {
        let token = crate::utils::crypto::csrf::mask_csrf_token(SESSION).unwrap();
        let (out, written) =
            gated(&[("csrf_token", None, &token), ("doc", Some("a.pdf"), "x")]).await;
        assert!(out.is_ok() && written, "token first: the file is staged");
    }

    #[tokio::test]
    async fn a_file_before_the_csrf_field_is_refused_unwritten() {
        let token = crate::utils::crypto::csrf::mask_csrf_token(SESSION).unwrap();
        let (out, written) = gated(&[
            ("doc", Some("a.html"), "<script>"),
            ("csrf_token", None, &token),
        ])
        .await;
        assert_eq!(out.err(), Some(403));
        assert!(!written, "nothing on disk");
    }

    #[tokio::test]
    async fn a_wrong_or_missing_token_writes_nothing() {
        let other = crate::utils::crypto::csrf::mask_csrf_token(OTHER).unwrap();
        for parts in [
            vec![
                ("csrf_token", None, other.as_str()),
                ("doc", Some("a.pdf"), "x"),
            ],
            vec![("title", None, "t"), ("doc", Some("a.pdf"), "x")],
        ] {
            let (out, written) = gated(&parts).await;
            assert_eq!(out.err(), Some(403));
            assert!(!written);
        }
    }

    #[tokio::test]
    async fn without_files_the_gate_lets_the_form_through() {
        // No file: nothing to protect here, the token is checked by Prisme.
        let (out, written) = gated(&[("title", None, "t")]).await;
        assert!(out.is_ok() && !written);
    }
}