cratefield-ui 0.4.2

Cratefield harness UI renderer: pages and fragments from the module surface, in-process dispatch, the cf-* markup contract
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! The admin pages against the real modules (issue #74): login with the
//! token, the signed session cookie, the index, a table over the export,
//! the two-step delete, logout, and the switched-off state.

use std::sync::Arc;

use axum::body::Body;
use axum::http::{Method, Request, StatusCode, header};
use cratefield_module_email_signup::EmailSignup;
use cratefield_module_waitlist::Waitlist;
use cratefield_testing::TestHarness;
use cratefield_ui::Ui;
use tower::ServiceExt;

const TOKEN: &str = "test-admin-token-with-enough-entropy";

fn kit(with_token: bool) -> TestHarness {
    TestHarness::with_builder(
        vec![
            Box::new(EmailSignup::new().double_opt_in(false)),
            Box::new(Waitlist::new().products(["kontinuum"])),
        ],
        |builder| builder.ui(Ui::new()),
        move |ports| {
            let mut pairs = vec![("HARNESS_SECRET", cratefield_testing::TEST_HARNESS_SECRET)];
            if with_token {
                pairs.push(("ADMIN_TOKEN", TOKEN));
            }
            ports.config = Arc::new(cratefield_core::MapConfig::from_pairs(pairs));
        },
    )
}

struct Reply {
    status: StatusCode,
    headers: axum::http::HeaderMap,
    body: String,
}

impl Reply {
    fn header(&self, name: header::HeaderName) -> String {
        self.headers
            .get(name)
            .map(|v| v.to_str().unwrap().to_owned())
            .unwrap_or_default()
    }
}

async fn send(
    kit: &TestHarness,
    method: Method,
    uri: &str,
    headers: &[(&str, &str)],
    form: Option<&str>,
) -> Reply {
    let mut builder = Request::builder()
        .method(method)
        .uri(uri)
        .header(header::HOST, "api.test.example")
        .header("cf-connecting-ip", "203.0.113.7");
    for (name, value) in headers {
        builder = builder.header(*name, *value);
    }
    let body = match form {
        Some(form) => {
            builder = builder.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
            Body::from(form.to_owned())
        }
        None => Body::empty(),
    };
    let response = kit
        .router
        .clone()
        .oneshot(builder.body(body).unwrap())
        .await
        .unwrap();
    let (parts, body) = response.into_parts();
    let bytes = axum::body::to_bytes(body, 1024 * 1024).await.unwrap();
    Reply {
        status: parts.status,
        headers: parts.headers,
        body: String::from_utf8(bytes.to_vec()).unwrap(),
    }
}

const ORIGIN: (&str, &str) = ("origin", "https://api.test.example");

/// Logs in and returns the `Cookie` header value to send back.
async fn login(kit: &TestHarness) -> String {
    let reply = send(
        kit,
        Method::POST,
        "/ui/admin/login",
        &[ORIGIN],
        Some(&format!("token={TOKEN}")),
    )
    .await;
    assert_eq!(reply.status, StatusCode::SEE_OTHER, "{}", reply.body);
    assert_eq!(reply.header(header::LOCATION), "/ui/admin");
    let set = reply.header(header::SET_COOKIE);
    for attr in [
        "HttpOnly",
        "Secure",
        "SameSite=Strict",
        "Path=/ui/admin",
        "Max-Age=43200",
    ] {
        assert!(set.contains(attr), "cookie lacks {attr}: {set}");
    }
    set.split(';').next().unwrap().to_owned()
}

#[pollster::test]
async fn unauthenticated_admin_pages_redirect_to_login() {
    let kit = kit(true);
    for uri in ["/ui/admin", "/ui/admin/waitlist/export"] {
        let reply = send(&kit, Method::GET, uri, &[], None).await;
        assert_eq!(reply.status, StatusCode::SEE_OTHER, "{uri}");
        assert_eq!(reply.header(header::LOCATION), "/ui/admin/login");
    }
    // A tampered cookie is no session either.
    let reply = send(
        &kit,
        Method::GET,
        "/ui/admin",
        &[("cookie", "cf_admin=eyJ.forged")],
        None,
    )
    .await;
    assert_eq!(reply.status, StatusCode::SEE_OTHER);
    // Posting an admin action without a session goes to login too.
    let reply = send(
        &kit,
        Method::POST,
        "/ui/admin/email-signup/delete",
        &[ORIGIN],
        Some("id=x"),
    )
    .await;
    assert_eq!(reply.status, StatusCode::SEE_OTHER);
}

#[pollster::test]
async fn login_form_and_failures() {
    let kit = kit(true);
    let page = send(&kit, Method::GET, "/ui/admin/login", &[], None).await;
    assert_eq!(page.status, StatusCode::OK);
    assert!(page.body.contains(r#"<input class="cf-input" type="password" id="cf-admin-login-token" name="token" required autocomplete="off">"#), "{}", page.body);
    assert_eq!(page.header(header::CACHE_CONTROL), "private, no-store");
    assert_eq!(
        page.header(header::HeaderName::from_static("x-frame-options")),
        "DENY"
    );
    assert!(!page.body.contains("cf-logout"), "no nav before login");

    let wrong = send(
        &kit,
        Method::POST,
        "/ui/admin/login",
        &[ORIGIN],
        Some("token=nope"),
    )
    .await;
    assert_eq!(wrong.status, StatusCode::FORBIDDEN);
    assert!(
        wrong
            .body
            .contains(r#"cf-field--invalid" data-cf-field="token""#)
    );
    assert!(wrong.header(header::SET_COOKIE).is_empty());

    let cross = send(
        &kit,
        Method::POST,
        "/ui/admin/login",
        &[("origin", "https://evil.example")],
        Some(&format!("token={TOKEN}")),
    )
    .await;
    assert_eq!(cross.status, StatusCode::FORBIDDEN);
    assert_eq!(
        cross.header(header::CONTENT_TYPE),
        "application/problem+json"
    );

    let no_origin = send(
        &kit,
        Method::POST,
        "/ui/admin/login",
        &[],
        Some(&format!("token={TOKEN}")),
    )
    .await;
    assert_eq!(no_origin.status, StatusCode::FORBIDDEN);
}

#[pollster::test]
async fn index_lists_tables_and_a_session_reaches_them() {
    let kit = kit(true);
    let cookie = login(&kit).await;
    let index = send(&kit, Method::GET, "/ui/admin", &[("cookie", &cookie)], None).await;
    assert_eq!(index.status, StatusCode::OK);
    assert!(
        index.body.contains(
            r#"<a class="cf-admin-link" href="/ui/admin/email-signup/export">Export table</a>"#
        ),
        "{}",
        index.body
    );
    assert!(index.body.contains(r#"href="/ui/admin/waitlist/export""#));
    assert!(
        index
            .body
            .contains(r#"<form class="cf-logout" method="post" action="/ui/admin/logout">"#)
    );
    // The public page keeps admin actions off its map.
    let public = send(&kit, Method::GET, "/ui/email-signup/export", &[], None).await;
    assert_eq!(public.status, StatusCode::NOT_FOUND);
}

#[pollster::test]
async fn table_shows_rows_and_delete_takes_two_posts() {
    let kit = kit(true);
    let cookie = login(&kit).await;
    // A subscriber through the public API (single opt-in: confirmed at once).
    let reply = cratefield_testing::request(
        &kit.router,
        Method::POST,
        "/v1/email-signup",
        Some(r#"{"email":"ada@example.com","captchaToken":"tok"}"#),
    )
    .await;
    assert_eq!(reply.status, StatusCode::ACCEPTED);

    let table = send(
        &kit,
        Method::GET,
        "/ui/admin/email-signup/export",
        &[("cookie", &cookie)],
        None,
    )
    .await;
    assert_eq!(table.status, StatusCode::OK, "{}", table.body);
    assert!(table.body.contains(
        r#"<table class="cf-table" data-cf-module="email-signup" data-cf-action="export">"#
    ));
    assert!(
        table
            .body
            .contains(r#"<th class="cf-table-head" scope="col">Email</th>"#)
    );
    assert!(
        table
            .body
            .contains(r#"<td class="cf-table-cell">ada@example.com</td>"#)
    );
    // The row action posts the opaque id, never the email (issue #135).
    let marker = r#"<input type="hidden" name="id" value=""#;
    let start = table.body.find(marker).expect("row form carries the id") + marker.len();
    let end = start + table.body[start..].find('"').expect("id value closes");
    let id = table.body[start..end].to_owned();
    assert!(!id.is_empty() && !id.contains('@'), "id is opaque: {id}");
    assert!(
        table.body.contains(&format!(
            r#"<form class="cf-row-action" method="post" action="/ui/admin/email-signup/delete"><input type="hidden" name="id" value="{id}"><button class="cf-submit cf-submit--row" type="submit">Delete</button></form>"#
        )),
        "{}",
        table.body
    );
    assert!(
        !table.body.contains(r#"name="email""#),
        "no email travels in the delete flow: {}",
        table.body
    );

    // First post: the confirm step, nothing deleted.
    let confirm = send(
        &kit,
        Method::POST,
        "/ui/admin/email-signup/delete",
        &[ORIGIN, ("cookie", &cookie)],
        Some(&format!("id={id}")),
    )
    .await;
    assert_eq!(confirm.status, StatusCode::OK, "{}", confirm.body);
    assert!(
        confirm.body.contains(&format!("Delete {id}?")),
        "{}",
        confirm.body
    );
    assert!(
        confirm
            .body
            .contains(r#"<input type="hidden" name="confirm" value="1">"#)
    );
    assert!(
        confirm
            .body
            .contains(r#"<a class="cf-cancel" href="/ui/admin/email-signup/export">Cancel</a>"#)
    );
    let still = send(
        &kit,
        Method::GET,
        "/ui/admin/email-signup/export",
        &[("cookie", &cookie)],
        None,
    )
    .await;
    assert!(still.body.contains("ada@example.com"));

    // Second post: deleted, back to the table, row gone.
    let done = send(
        &kit,
        Method::POST,
        "/ui/admin/email-signup/delete",
        &[ORIGIN, ("cookie", &cookie)],
        Some(&format!("id={id}&confirm=1")),
    )
    .await;
    assert_eq!(done.status, StatusCode::SEE_OTHER, "{}", done.body);
    assert_eq!(
        done.header(header::LOCATION),
        "/ui/admin/email-signup/export"
    );
    let after = send(
        &kit,
        Method::GET,
        "/ui/admin/email-signup/export",
        &[("cookie", &cookie)],
        None,
    )
    .await;
    assert!(!after.body.contains("ada@example.com"));
    assert!(after.body.contains(r#"<td class="cf-table-empty""#));

    // Cross-origin posts are refused even with a session.
    let cross = send(
        &kit,
        Method::POST,
        "/ui/admin/email-signup/delete",
        &[("origin", "https://evil.example"), ("cookie", &cookie)],
        Some("id=x&confirm=1"),
    )
    .await;
    assert_eq!(cross.status, StatusCode::FORBIDDEN);
}

#[pollster::test]
async fn logout_clears_the_cookie() {
    let kit = kit(true);
    let cookie = login(&kit).await;
    let out = send(
        &kit,
        Method::POST,
        "/ui/admin/logout",
        &[ORIGIN, ("cookie", &cookie)],
        None,
    )
    .await;
    assert_eq!(out.status, StatusCode::SEE_OTHER);
    assert_eq!(out.header(header::LOCATION), "/ui/admin/login");
    assert!(out.header(header::SET_COOKIE).contains("Max-Age=0"));
}

#[pollster::test]
async fn without_admin_token_the_admin_ui_is_off() {
    let kit = kit(false);
    let page = send(&kit, Method::GET, "/ui/admin/login", &[], None).await;
    assert_eq!(page.status, StatusCode::OK);
    assert!(page.body.contains("Admin is switched off"));
    assert!(!page.body.contains(r#"type="password""#));
    let post = send(
        &kit,
        Method::POST,
        "/ui/admin/login",
        &[ORIGIN],
        Some("token=anything"),
    )
    .await;
    assert!(post.header(header::SET_COOKIE).is_empty());
    assert!(post.body.contains("Admin is switched off"));
}

/// Issue #130: hiding an admin action from the public UI is visibility,
/// not authorization — invoking it directly on the public route must not
/// reach the module, and presenting the admin token there must not
/// unlock it either. The doors to an admin action are the session-gated
/// admin UI and a direct `/v1` request with the bearer.
#[pollster::test]
async fn hidden_admin_actions_are_not_executable_through_the_public_ui() {
    let kit = kit(true);
    // A subscriber a successful delete would remove.
    let reply = cratefield_testing::request(
        &kit.router,
        Method::POST,
        "/v1/email-signup",
        Some(r#"{"email":"ada@example.com","captchaToken":"tok"}"#),
    )
    .await;
    assert_eq!(reply.status, StatusCode::ACCEPTED);

    // The destructive row action posted to the public route: 404 like
    // any unknown action, session or no session.
    let posted = send(
        &kit,
        Method::POST,
        "/ui/email-signup/delete",
        &[],
        Some("email=ada%40example.com&confirm=1"),
    )
    .await;
    assert_eq!(posted.status, StatusCode::NOT_FOUND, "{}", posted.body);
    assert_eq!(
        posted.header(header::CONTENT_TYPE),
        "application/problem+json"
    );

    // The admin export is hidden the same way, for GET and POST.
    let exported = send(&kit, Method::GET, "/ui/email-signup/export", &[], None).await;
    assert_eq!(exported.status, StatusCode::NOT_FOUND);
    let posted_export = send(&kit, Method::POST, "/ui/email-signup/export", &[], Some("")).await;
    assert_eq!(posted_export.status, StatusCode::NOT_FOUND);

    // A valid admin bearer on the public route changes nothing: the
    // action stays hidden there.
    let with_bearer = send(
        &kit,
        Method::POST,
        "/ui/email-signup/delete",
        &[("authorization", &format!("Bearer {TOKEN}"))],
        Some("email=ada%40example.com&confirm=1"),
    )
    .await;
    assert_eq!(with_bearer.status, StatusCode::NOT_FOUND);

    // Proof nothing executed: the direct admin export still lists the
    // subscriber, and the bearer works on the real `/v1` route.
    let export = send(
        &kit,
        Method::GET,
        "/v1/email-signup/admin/export.csv",
        &[("authorization", &format!("Bearer {TOKEN}"))],
        None,
    )
    .await;
    assert_eq!(export.status, StatusCode::OK);
    assert!(export.body.contains("ada@example.com"), "{}", export.body);
}

/// Issue #130: the session is a cookie credential, so every admin POST
/// needs its same-origin proof — a missing `Origin`/`Referer` is refused
/// like a foreign one (the browsers that strip `Origin`), and a matching
/// `Referer` is accepted. The check runs before any dispatch, so a
/// refused post cannot have side effects.
#[pollster::test]
async fn admin_posts_need_same_origin_proof_beyond_the_cookie() {
    let kit = kit(true);
    let cookie = login(&kit).await;

    // The delete action takes the opaque row id, never the email (issue #135),
    // so the same-origin proof is exercised against a real seeded row.
    let reply = cratefield_testing::request(
        &kit.router,
        Method::POST,
        "/v1/email-signup",
        Some(r#"{"email":"ada@example.com","captchaToken":"tok"}"#),
    )
    .await;
    assert_eq!(reply.status, StatusCode::ACCEPTED);
    let table = send(
        &kit,
        Method::GET,
        "/ui/admin/email-signup/export",
        &[("cookie", &cookie)],
        None,
    )
    .await;
    assert_eq!(table.status, StatusCode::OK, "{}", table.body);
    let marker = r#"<input type="hidden" name="id" value=""#;
    let start = table.body.find(marker).expect("row form carries the id") + marker.len();
    let end = start + table.body[start..].find('"').expect("id value closes");
    let id = table.body[start..end].to_owned();

    let no_proof = send(
        &kit,
        Method::POST,
        "/ui/admin/email-signup/delete",
        &[("cookie", &cookie)],
        Some(&format!("id={id}&confirm=1")),
    )
    .await;
    assert_eq!(no_proof.status, StatusCode::FORBIDDEN);
    assert_eq!(
        no_proof.header(header::CONTENT_TYPE),
        "application/problem+json"
    );

    // The same post with a matching Referer reaches the confirm step.
    let referer = send(
        &kit,
        Method::POST,
        "/ui/admin/email-signup/delete",
        &[
            ("cookie", &cookie),
            (
                "referer",
                "https://api.test.example/ui/admin/email-signup/export",
            ),
        ],
        Some(&format!("id={id}")),
    )
    .await;
    assert_eq!(referer.status, StatusCode::OK, "{}", referer.body);
    assert!(
        referer.body.contains(&format!("Delete {id}?")),
        "{}",
        referer.body
    );
}

/// A limiter whose transport is down: the login post must be denied, not
/// waved through to the token compare (issue #437).
struct DownLimiter;

#[async_trait::async_trait]
impl cratefield_core::RateLimiter for DownLimiter {
    async fn limit(
        &self,
        _key: &str,
    ) -> Result<cratefield_core::Decision, cratefield_core::RateLimitError> {
        Err(cratefield_core::RateLimitError::Transport(
            "limiter down".to_owned(),
        ))
    }
}

fn down_limiter_kit() -> TestHarness {
    TestHarness::with_builder(
        vec![
            Box::new(EmailSignup::new().double_opt_in(false)),
            Box::new(Waitlist::new().products(["kontinuum"])),
        ],
        |builder| builder.ui(Ui::new()),
        |ports| {
            ports.config = Arc::new(cratefield_core::MapConfig::from_pairs(vec![
                ("HARNESS_SECRET", cratefield_testing::TEST_HARNESS_SECRET),
                ("ADMIN_TOKEN", TOKEN),
            ]));
            ports.rate_limiter = Some(Arc::new(DownLimiter));
        },
    )
}

#[pollster::test]
async fn a_limiter_error_denies_the_login_instead_of_failing_open() {
    let kit = down_limiter_kit();
    let reply = send(
        &kit,
        Method::POST,
        "/ui/admin/login",
        &[ORIGIN],
        Some(&format!("token={TOKEN}")),
    )
    .await;
    assert_eq!(
        reply.status,
        StatusCode::TOO_MANY_REQUESTS,
        "{}",
        reply.body
    );
    assert!(
        reply
            .body
            .contains("Too many attempts. Please try again later."),
        "{}",
        reply.body
    );
    // The post never reached the token compare, so no session is minted
    // even though the presented token was the right one.
    assert!(reply.header(header::SET_COOKIE).is_empty());
}