what-core 1.7.2

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
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Integration tests for collection authorization policies (v1.4).
//!
//! These prove the security properties end-to-end through the HTTP layer:
//! cross-session isolation, ownership on update/delete, read scoping, tenant
//! filters, role rules, upload gating, w-set role gating, and the legacy
//! (unowned record) compatibility path.

mod common;

use axum::http::StatusCode;
use common::*;
use serde_json::json;
use what_core::server::create_router;
use what_core::{CollectionPolicyConfig, Config};

fn future_exp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
        + 3600
}

/// A Config with a single collection policy.
fn config_with_policy(name: &str, policy: CollectionPolicyConfig) -> Config {
    let mut config = Config::default();
    config.collections.insert(name.to_string(), policy);
    config
}

/// Auth config that extracts common claims, with a policy on `name`.
fn auth_config_with_policy(secret: &str, name: &str, policy: CollectionPolicyConfig) -> Config {
    let mut config = auth_config_with_secret(secret);
    config.auth.jwt_claims.push("roles".to_string());
    config.auth.jwt_claims.push("org_id".to_string());
    config.collections.insert(name.to_string(), policy);
    config
}

// ---------------------------------------------------------------------------
// Default posture: cross-session isolation on update/delete
// ---------------------------------------------------------------------------

#[tokio::test]
async fn default_denies_cross_session_update() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "notes.html",
        "<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    let (_dir, state) = proj.build_state();
    let router = create_router(state);

    // Visitor A creates a note.
    let created = post_form(&router, "/w-action/notes?w-redirect=/", "title=Mine").await;
    let cookie_a = created.session_cookie().expect("session cookie");

    // Visitor B (fresh session) tries to update it by id — must be denied.
    let resp = post_form(&router, "/w-action/notes/1?w-redirect=/", "title=Hacked").await;
    // Denied → redirect back (flash error), record unchanged.
    assert_eq!(resp.status, StatusCode::SEE_OTHER);

    // The note still reads "Mine" (fetched as visitor A).
    let page = get_with_headers(&router, "/notes", vec![("cookie", &cookie_a)]).await;
    page.assert_contains("Mine");
    page.assert_not_contains("Hacked");
}

#[tokio::test]
async fn default_denies_cross_session_delete() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "notes.html",
        "<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    let (_dir, state) = proj.build_state();
    let router = create_router(state);

    let created = post_form(&router, "/w-action/notes?w-redirect=/", "title=Keep").await;
    let cookie_a = created.session_cookie().expect("session cookie");

    // Fresh session attempts delete by id.
    post_form(&router, "/w-action/notes/1?w-action=delete&w-redirect=/", "").await;

    // Owner still sees the record.
    let page = get_with_headers(&router, "/notes", vec![("cookie", &cookie_a)]).await;
    page.assert_contains("Keep");
}

// ---------------------------------------------------------------------------
// Legacy (unowned) records remain modifiable under the implicit default
// ---------------------------------------------------------------------------

#[tokio::test]
async fn legacy_unowned_record_is_modifiable() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "notes.html",
        "<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    let (_dir, state) = proj.build_state();

    // Seed a record directly in the store (no _owner — predates ownership).
    state
        .store
        .create("notes", json!({ "title": "Legacy" }))
        .await
        .unwrap();

    let router = create_router(state);

    // Any visitor may update it (legacy compatibility).
    post_form(&router, "/w-action/notes/1?w-redirect=/", "title=Edited").await;

    let page = get(&router, "/notes").await;
    page.assert_contains("Edited");
}

// ---------------------------------------------------------------------------
// Explicit policy locks unowned records
// ---------------------------------------------------------------------------

#[tokio::test]
async fn explicit_policy_locks_unowned_record() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "notes.html",
        "<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        update: Some("owner".to_string()),
        ..Default::default()
    };
    let (_dir, state) = proj.build_state_with_config(config_with_policy("notes", policy));

    // Seed an unowned record.
    state
        .store
        .create("notes", json!({ "title": "Locked" }))
        .await
        .unwrap();
    let router = create_router(state);

    // Anonymous update is denied (explicit policy is strict).
    post_form(&router, "/w-action/notes/1?w-redirect=/", "title=Changed").await;

    let page = get(&router, "/notes").await;
    page.assert_contains("Locked");
    page.assert_not_contains("Changed");
}

// ---------------------------------------------------------------------------
// Owner stamping + spoof/readonly stripping
// ---------------------------------------------------------------------------

#[tokio::test]
async fn owner_stamped_and_spoof_and_readonly_stripped() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "items.html",
        "<loop data=\"#items#\" as=\"i\"><li>#i.name# owner=#i._owner# price=#i.price#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        fields: what_core::FieldRulesConfig {
            readonly: vec!["price".to_string()],
            private: vec![],
        },
        ..Default::default()
    };
    let (_dir, state) = proj.build_state_with_config(config_with_policy("items", policy));
    let router = create_router(state);

    // Client tries to spoof _owner and set a readonly field.
    let created = post_form(
        &router,
        "/w-action/items?w-redirect=/",
        "name=Widget&_owner=user:evil&price=999",
    )
    .await;
    let cookie = created.session_cookie().expect("session cookie");

    let page = get_with_headers(&router, "/items", vec![("cookie", &cookie)]).await;
    page.assert_contains("Widget");
    // _owner is the session key, not the spoofed value.
    page.assert_contains("owner=session:");
    page.assert_not_contains("user:evil");
    // readonly price was dropped.
    page.assert_not_contains("price=999");
}

// ---------------------------------------------------------------------------
// read = "owner" scopes fetches per session
// ---------------------------------------------------------------------------

#[tokio::test]
async fn read_owner_scopes_per_session() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "notes.html",
        "<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    // fetch directive so the page reads the scoped collection.
    proj.add_page(
        "list.html",
        "<what>\nfetch.notes = \"local:notes\"\n</what>\n<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        read: Some("owner".to_string()),
        ..Default::default()
    };
    let (_dir, state) = proj.build_state_with_config(config_with_policy("notes", policy));
    let router = create_router(state);

    // Visitor A creates "AlphaNote".
    let a = post_form(&router, "/w-action/notes?w-redirect=/", "title=AlphaNote").await;
    let cookie_a = a.session_cookie().expect("session cookie");
    // Visitor B creates "BetaNote".
    let b = post_form(&router, "/w-action/notes?w-redirect=/", "title=BetaNote").await;
    let cookie_b = b.session_cookie().expect("session cookie");

    // A sees only their own note.
    let page_a = get_with_headers(&router, "/list", vec![("cookie", &cookie_a)]).await;
    page_a.assert_contains("AlphaNote");
    page_a.assert_not_contains("BetaNote");

    // B sees only theirs.
    let page_b = get_with_headers(&router, "/list", vec![("cookie", &cookie_b)]).await;
    page_b.assert_contains("BetaNote");
    page_b.assert_not_contains("AlphaNote");
}

#[tokio::test]
async fn read_scoped_collection_absent_from_base_context() {
    let proj = TestProject::new();
    // Page loops the collection WITHOUT a fetch directive — it would read the
    // base context (whole store). A read-scoped collection must be scrubbed.
    proj.add_page(
        "leak.html",
        "<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        read: Some("owner".to_string()),
        ..Default::default()
    };
    let (_dir, state) = proj.build_state_with_config(config_with_policy("notes", policy));
    state
        .store
        .create("notes", json!({ "title": "SecretNote", "_owner": "user:someone" }))
        .await
        .unwrap();
    let router = create_router(state);

    // A visitor who is not the owner sees nothing (base context scrubbed).
    let page = get(&router, "/leak").await;
    page.assert_not_contains("SecretNote");
}

// ---------------------------------------------------------------------------
// Private fields stripped from render
// ---------------------------------------------------------------------------

#[tokio::test]
async fn private_fields_stripped_from_render() {
    let proj = TestProject::new();
    proj.add_page(
        "users.html",
        "<what>\nfetch.users = \"local:users\"\n</what>\n<loop data=\"#users#\" as=\"u\"><li>#u.name# / #u.email#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        read: Some("all".to_string()),
        fields: what_core::FieldRulesConfig {
            readonly: vec![],
            private: vec!["email".to_string()],
        },
        ..Default::default()
    };
    let (_dir, state) = proj.build_state_with_config(config_with_policy("users", policy));
    state
        .store
        .create("users", json!({ "name": "Ada", "email": "ada@secret.com" }))
        .await
        .unwrap();
    let router = create_router(state);

    let page = get(&router, "/users").await;
    page.assert_contains("Ada");
    page.assert_not_contains("ada@secret.com");
}

// ---------------------------------------------------------------------------
// Tenant filter: read scope + mutation-by-id gating
// ---------------------------------------------------------------------------

#[tokio::test]
async fn tenant_filter_scopes_reads_and_mutations() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "orders.html",
        "<what>\nfetch.orders = \"local:orders\"\n</what>\n<loop data=\"#orders#\" as=\"o\"><li>#o.item#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        owner: Some("none".to_string()),
        create: Some("user".to_string()),
        update: Some("user".to_string()),
        read: Some("all".to_string()),
        filter: Some("org_id=#user.org_id#".to_string()),
        ..Default::default()
    };
    let (_dir, state) =
        proj.build_state_with_config(auth_config_with_policy("secret", "orders", policy));
    // Seed two orders in different orgs.
    state
        .store
        .create("orders", json!({ "item": "AcmeOrder", "org_id": "acme" }))
        .await
        .unwrap();
    state
        .store
        .create("orders", json!({ "item": "OtherOrder", "org_id": "other" }))
        .await
        .unwrap();
    let router = create_router(state);

    let acme_token = create_test_jwt(
        &json!({ "sub": "u1", "org_id": "acme", "exp": future_exp() }),
        "secret",
    );
    let acme_cookie = format!("w_token={}", acme_token);

    // Acme user reads only their org's order.
    let page = get_with_headers(&router, "/orders", vec![("cookie", &acme_cookie)]).await;
    page.assert_contains("AcmeOrder");
    page.assert_not_contains("OtherOrder");

    // Acme user cannot mutate the other org's order by id (id=2).
    post_form_with_headers(
        &router,
        "/w-action/orders/2?w-redirect=/",
        "item=Hijacked",
        vec![("cookie", &acme_cookie)],
    )
    .await;
    // Read back as an "other" user to confirm it's unchanged.
    let other_token = create_test_jwt(
        &json!({ "sub": "u2", "org_id": "other", "exp": future_exp() }),
        "secret",
    );
    let other_cookie = format!("w_token={}", other_token);
    let page2 = get_with_headers(&router, "/orders", vec![("cookie", &other_cookie)]).await;
    page2.assert_contains("OtherOrder");
    page2.assert_not_contains("Hijacked");
}

// ---------------------------------------------------------------------------
// Role rules
// ---------------------------------------------------------------------------

#[tokio::test]
async fn role_delete_rule_allows_and_denies() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "posts.html",
        "<loop data=\"#posts#\" as=\"p\"><li>#p.title#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        owner: Some("none".to_string()),
        create: Some("all".to_string()),
        delete: Some("admin".to_string()),
        read: Some("all".to_string()),
        ..Default::default()
    };
    let (_dir, state) =
        proj.build_state_with_config(auth_config_with_policy("secret", "posts", policy));
    state
        .store
        .create("posts", json!({ "title": "Hello" }))
        .await
        .unwrap();
    let router = create_router(state);

    // Non-admin cannot delete.
    let editor = create_test_jwt(
        &json!({ "sub": "e1", "roles": ["editor"], "exp": future_exp() }),
        "secret",
    );
    post_form_with_headers(
        &router,
        "/w-action/posts/1?w-action=delete&w-redirect=/",
        "",
        vec![("cookie", &format!("w_token={}", editor))],
    )
    .await;
    get(&router, "/posts").await.assert_contains("Hello");

    // Admin can delete.
    let admin = create_test_jwt(
        &json!({ "sub": "a1", "roles": ["admin"], "exp": future_exp() }),
        "secret",
    );
    post_form_with_headers(
        &router,
        "/w-action/posts/1?w-action=delete&w-redirect=/",
        "",
        vec![("cookie", &format!("w_token={}", admin))],
    )
    .await;
    get(&router, "/posts").await.assert_not_contains("Hello");
}

// ---------------------------------------------------------------------------
// create = "user" denies anonymous
// ---------------------------------------------------------------------------

#[tokio::test]
async fn create_user_rule_denies_anonymous() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_page(
        "notes.html",
        "<loop data=\"#notes#\" as=\"n\"><li>#n.title#</li></loop>",
    );
    let policy = CollectionPolicyConfig {
        create: Some("user".to_string()),
        ..Default::default()
    };
    let (_dir, state) =
        proj.build_state_with_config(auth_config_with_policy("secret", "notes", policy));
    let router = create_router(state);

    // Anonymous create denied.
    post_form(&router, "/w-action/notes?w-redirect=/", "title=Nope").await;
    get(&router, "/notes").await.assert_not_contains("Nope");
}

// ---------------------------------------------------------------------------
// Partial (AJAX) denial → 403 + X-What-Policy in dev
// ---------------------------------------------------------------------------

#[tokio::test]
async fn partial_denial_is_403_with_policy_header() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    let policy = CollectionPolicyConfig {
        create: Some("user".to_string()),
        ..Default::default()
    };
    // Dev mode so the X-What-Policy header is emitted.
    let (_dir, state) =
        proj.build_state_dev_with_config(auth_config_with_policy("secret", "notes", policy));
    let router = create_router(state);

    let resp = post_form_with_headers(
        &router,
        "/w-action/notes",
        "title=Nope",
        vec![("X-Requested-With", "What")],
    )
    .await;
    assert_eq!(resp.status, StatusCode::FORBIDDEN);
    assert!(resp.header("x-what-policy").is_some());
}

// ---------------------------------------------------------------------------
// w-set role gating (wired + app)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn w_set_wired_role_gating() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_app_config(".", "data.wired = [\"revenue [admin]\"]\n");
    let (_dir, state) = proj.build_state_with_config({
        let mut c = auth_config_with_secret("secret");
        c.auth.jwt_claims.push("roles".to_string());
        c
    });
    state.rebuild_wired_scopes().await;
    let router = create_router(state);

    // Non-admin denied.
    let editor = create_test_jwt(
        &json!({ "sub": "e1", "roles": ["editor"], "exp": future_exp() }),
        "secret",
    );
    let resp = post_form_with_headers(
        &router,
        "/w-set",
        "expr=wired.revenue+%2B%3D+1",
        vec![("cookie", &format!("w_token={}", editor))],
    )
    .await;
    assert_eq!(resp.status, StatusCode::FORBIDDEN);

    // Admin allowed — full-page w-set redirects (303) on success.
    let admin = create_test_jwt(
        &json!({ "sub": "a1", "roles": ["admin"], "exp": future_exp() }),
        "secret",
    );
    let resp = post_form_with_headers(
        &router,
        "/w-set",
        "expr=wired.revenue+%2B%3D+1",
        vec![("cookie", &format!("w_token={}", admin))],
    )
    .await;
    assert_ne!(
        resp.status,
        StatusCode::FORBIDDEN,
        "admin should not be denied"
    );
    assert!(resp.status.is_redirection() || resp.status.is_success());
}

#[tokio::test]
async fn w_set_app_role_gating() {
    let proj = TestProject::new();
    proj.add_page("index.html", "<h1>Home</h1>");
    proj.add_app_config(".", "data.application = [\"mrr [admin]\"]\n");
    let (_dir, state) = proj.build_state_with_config({
        let mut c = auth_config_with_secret("secret");
        c.auth.jwt_claims.push("roles".to_string());
        c
    });
    state.rebuild_wired_scopes().await;
    let router = create_router(state);

    let editor = create_test_jwt(
        &json!({ "sub": "e1", "roles": ["editor"], "exp": future_exp() }),
        "secret",
    );
    let resp = post_form_with_headers(
        &router,
        "/w-set",
        "expr=app.mrr+%2B%3D+1",
        vec![("cookie", &format!("w_token={}", editor))],
    )
    .await;
    assert_eq!(resp.status, StatusCode::FORBIDDEN);
}