what-core 1.7.5

Core framework for What - an HTML-first web framework powered by Rust
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
mod common;

use axum::http::StatusCode;
use common::*;
use what_core::server::create_router;

#[tokio::test]
async fn upload_creates_record_with_file_path() {
    let proj = TestProject::new();
    proj.add_page("index.html", r##"<h1>#flash.success|default:"none"#</h1>"##);
    let (_dir, state) = proj.build_state_with_uploads();
    let router = create_router(state);

    let resp = post_multipart(
        &router,
        "/w-upload/photos?w-redirect=/",
        vec![
            ("title", MultipartField::Text("My Photo")),
            (
                "file",
                MultipartField::File {
                    filename: "test.png",
                    content_type: "image/png",
                    data: b"fake-png-data",
                },
            ),
        ],
    )
    .await;

    assert_eq!(resp.status, StatusCode::SEE_OTHER);
    assert_eq!(resp.location(), Some("/"));

    // Follow redirect with cookie to see flash
    let cookie = resp.set_cookie().expect("should set session cookie");
    let resp = get_with_headers(&router, "/", vec![("cookie", cookie)]).await;
    resp.assert_contains("Item created in photos");
}

#[tokio::test]
async fn upload_disabled_returns_error_flash() {
    let proj = TestProject::new();
    proj.add_page("form.html", r##"<p>#flash.error|default:"no-error"#</p>"##);
    // Default config has uploads disabled
    let (_dir, state) = proj.build_state();
    let router = create_router(state);

    let resp = post_multipart_with_headers(
        &router,
        "/w-upload/photos?w-redirect=/form",
        vec![(
            "file",
            MultipartField::File {
                filename: "test.png",
                content_type: "image/png",
                data: b"fake-png-data",
            },
        )],
        vec![("referer", "/form")],
    )
    .await;

    assert_eq!(resp.status, StatusCode::SEE_OTHER);
    let cookie = resp.set_cookie().expect("should set session cookie");

    let resp = get_with_headers(&router, "/form", vec![("cookie", cookie)]).await;
    resp.assert_contains("not enabled");
}

#[tokio::test]
async fn delete_action_cannot_traverse_out_of_uploads_dir() {
    // SECURITY (CWE-22): a record field is attacker-controlled (create = all by
    // default). A crafted "/uploads/../<target>" value must NOT let the delete
    // action's file cleanup remove a file outside the uploads directory.
    let proj = TestProject::new();
    proj.add_page("index.html", r##"<form w-validate action="/x"></form><h1>ok</h1>"##);
    let (dir, state) = proj.build_state_with_uploads();

    // A sensitive file living OUTSIDE the uploads directory.
    let target = dir.path().join("SECRET_TARGET.txt");
    std::fs::write(&target, "do-not-delete").unwrap();

    let router = create_router(state);

    // Anonymous create with a traversal path stored in a normal field.
    let created = post_form(
        &router,
        "/w-action/notes?w-redirect=/",
        "evil=/uploads/../SECRET_TARGET.txt",
    )
    .await;
    let cookie = created.session_cookie().expect("session cookie");

    // The attacker reads their own CSRF token from a rendered page (the session
    // now carries one), then deletes their own record → cleanup runs.
    let page = get_with_headers(&router, "/", vec![("cookie", &cookie)]).await;
    let csrf = page.csrf_token().expect("csrf token in page");
    let del = post_form_with_headers(
        &router,
        "/w-action/notes/1?w-action=delete&w-redirect=/",
        "",
        vec![("cookie", &cookie), ("x-csrf-token", &csrf)],
    )
    .await;
    assert_eq!(del.status, StatusCode::SEE_OTHER);

    // The out-of-tree file must survive.
    assert!(
        target.exists(),
        "path traversal in cleanup deleted a file outside uploads/"
    );
}

#[tokio::test]
async fn uploaded_html_served_as_attachment_not_executed() {
    // SECURITY: an uploaded HTML/SVG file served same-origin could run script
    // (stored XSS). It must be sent as a download, never rendered inline.
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>ok</h1>");
    let (dir, state) = proj.build_state_with_uploads();
    let router = create_router(state);

    post_multipart(
        &router,
        "/w-upload/files?w-redirect=/",
        vec![(
            "file",
            MultipartField::File {
                filename: "evil.html",
                content_type: "text/html",
                data: b"<script>alert(document.domain)</script>",
            },
        )],
    )
    .await;

    let uploads_dir = dir.path().join("uploads");
    let name = std::fs::read_dir(&uploads_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .next()
        .unwrap()
        .file_name();
    let resp = get(&router, &format!("/uploads/{}", name.to_str().unwrap())).await;
    assert_eq!(resp.status, StatusCode::OK);
    assert_eq!(
        resp.header("content-disposition"),
        Some("attachment"),
        "uploaded HTML must be forced to download"
    );
}

#[tokio::test]
async fn uploaded_image_renders_inline() {
    // A normal image upload must still be viewable inline (no forced download).
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>ok</h1>");
    let (dir, state) = proj.build_state_with_uploads();
    let router = create_router(state);

    post_multipart(
        &router,
        "/w-upload/photos?w-redirect=/",
        vec![(
            "file",
            MultipartField::File {
                filename: "pic.png",
                content_type: "image/png",
                data: b"\x89PNG\r\n\x1a\n fake",
            },
        )],
    )
    .await;

    let uploads_dir = dir.path().join("uploads");
    let name = std::fs::read_dir(&uploads_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .next()
        .unwrap()
        .file_name();
    let resp = get(&router, &format!("/uploads/{}", name.to_str().unwrap())).await;
    assert_eq!(resp.status, StatusCode::OK);
    assert!(
        resp.header("content-disposition").is_none(),
        "images should render inline, not download"
    );
}

#[tokio::test]
async fn upload_saves_file_to_uploads_dir() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>ok</h1>");
    let (dir, state) = proj.build_state_with_uploads();
    let router = create_router(state);

    post_multipart(
        &router,
        "/w-upload/files?w-redirect=/",
        vec![(
            "doc",
            MultipartField::File {
                filename: "readme.txt",
                content_type: "text/plain",
                data: b"Hello, world!",
            },
        )],
    )
    .await;

    // Verify the file was saved in the uploads directory
    let uploads_dir = dir.path().join("uploads");
    let entries: Vec<_> = std::fs::read_dir(&uploads_dir)
        .expect("uploads dir should exist")
        .filter_map(|e| e.ok())
        .collect();
    assert_eq!(entries.len(), 1, "Should have exactly one uploaded file");

    // Verify file content
    let saved_path = entries[0].path();
    let content = std::fs::read_to_string(&saved_path).unwrap();
    assert_eq!(content, "Hello, world!");

    // Verify filename has UUID and original extension
    let fname = saved_path.file_name().unwrap().to_str().unwrap();
    assert!(
        fname.ends_with(".txt"),
        "Should preserve .txt extension, got: {}",
        fname
    );
    assert!(fname.len() > 10, "Should have UUID prefix");
}

#[tokio::test]
async fn upload_file_served_at_uploads_path() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>ok</h1>");
    let (dir, state) = proj.build_state_with_uploads();
    let router = create_router(state);

    // Upload a file
    post_multipart(
        &router,
        "/w-upload/docs?w-redirect=/",
        vec![(
            "file",
            MultipartField::File {
                filename: "hello.txt",
                content_type: "text/plain",
                data: b"file-content-here",
            },
        )],
    )
    .await;

    // Find the saved file
    let uploads_dir = dir.path().join("uploads");
    let entries: Vec<_> = std::fs::read_dir(&uploads_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();
    let saved_name = entries[0].file_name();

    // Fetch via /uploads/ path
    let resp = get(
        &router,
        &format!("/uploads/{}", saved_name.to_str().unwrap()),
    )
    .await;
    assert_eq!(resp.status, StatusCode::OK);
    assert_eq!(resp.body, "file-content-here");
}

#[tokio::test]
async fn upload_rejects_oversized_file() {
    let proj = TestProject::new();
    proj.add_page("form.html", r##"<p>#flash.error|default:"no-error"#</p>"##);
    let mut config = what_core::Config::default();
    config.uploads.enabled = true;
    config.uploads.max_size = "100".to_string(); // 100 bytes max
    let (_dir, state) = proj.build_state_with_config(config);
    let router = create_router(state);

    // Upload a file larger than 100 bytes
    let big_data = vec![0u8; 200];
    let resp = post_multipart_with_headers(
        &router,
        "/w-upload/files?w-redirect=/form",
        vec![(
            "file",
            MultipartField::File {
                filename: "big.bin",
                content_type: "application/octet-stream",
                data: &big_data,
            },
        )],
        vec![("referer", "/form")],
    )
    .await;

    assert_eq!(resp.status, StatusCode::SEE_OTHER);
    let cookie = resp.set_cookie().expect("should set session cookie");

    let resp = get_with_headers(&router, "/form", vec![("cookie", cookie)]).await;
    resp.assert_contains("exceeds maximum size");
}

#[tokio::test]
async fn upload_rejects_disallowed_type() {
    let proj = TestProject::new();
    proj.add_page("form.html", r##"<p>#flash.error|default:"no-error"#</p>"##);
    let mut config = what_core::Config::default();
    config.uploads.enabled = true;
    config.uploads.allowed_types = vec!["image/*".to_string()];
    let (_dir, state) = proj.build_state_with_config(config);
    let router = create_router(state);

    let resp = post_multipart_with_headers(
        &router,
        "/w-upload/files?w-redirect=/form",
        vec![(
            "file",
            MultipartField::File {
                filename: "script.js",
                content_type: "application/javascript",
                data: b"alert('hi')",
            },
        )],
        vec![("referer", "/form")],
    )
    .await;

    assert_eq!(resp.status, StatusCode::SEE_OTHER);
    let cookie = resp.set_cookie().expect("should set session cookie");

    let resp = get_with_headers(&router, "/form", vec![("cookie", cookie)]).await;
    resp.assert_contains("not allowed");
}

#[tokio::test]
async fn upload_allows_matching_type() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>ok</h1>");
    let mut config = what_core::Config::default();
    config.uploads.enabled = true;
    config.uploads.allowed_types = vec!["image/*".to_string()];
    let (_dir, state) = proj.build_state_with_config(config);
    let router = create_router(state);

    let resp = post_multipart(
        &router,
        "/w-upload/photos?w-redirect=/",
        vec![(
            "file",
            MultipartField::File {
                filename: "photo.jpg",
                content_type: "image/jpeg",
                data: b"fake-jpeg",
            },
        )],
    )
    .await;

    assert_eq!(resp.status, StatusCode::SEE_OTHER);
    assert_eq!(resp.location(), Some("/"));
}

#[tokio::test]
async fn upload_with_multiple_files() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>ok</h1>");
    let (dir, state) = proj.build_state_with_uploads();
    let router = create_router(state);

    post_multipart(
        &router,
        "/w-upload/gallery?w-redirect=/",
        vec![
            ("title", MultipartField::Text("My Gallery")),
            (
                "photo1",
                MultipartField::File {
                    filename: "a.png",
                    content_type: "image/png",
                    data: b"data-a",
                },
            ),
            (
                "photo2",
                MultipartField::File {
                    filename: "b.jpg",
                    content_type: "image/jpeg",
                    data: b"data-b",
                },
            ),
        ],
    )
    .await;

    // Should have 2 files in uploads
    let uploads_dir = dir.path().join("uploads");
    let entries: Vec<_> = std::fs::read_dir(&uploads_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();
    assert_eq!(entries.len(), 2, "Should have two uploaded files");
}

#[tokio::test]
async fn upload_empty_file_field_skipped() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>ok</h1>");
    let (dir, state) = proj.build_state_with_uploads();
    let router = create_router(state);

    let resp = post_multipart(
        &router,
        "/w-upload/items?w-redirect=/",
        vec![
            ("title", MultipartField::Text("No file")),
            (
                "file",
                MultipartField::File {
                    filename: "",
                    content_type: "application/octet-stream",
                    data: b"",
                },
            ),
        ],
    )
    .await;

    assert_eq!(resp.status, StatusCode::SEE_OTHER);

    // No files should be in uploads
    let uploads_dir = dir.path().join("uploads");
    let entries: Vec<_> = std::fs::read_dir(&uploads_dir)
        .unwrap()
        .filter_map(|e| e.ok())
        .collect();
    assert_eq!(entries.len(), 0, "Empty file fields should be skipped");
}