cookcli 0.37.0

A command-line interface for managing and working with Cooklang recipes
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
use crate::server::AppState;
use crate::web::language::FeatureFlags;
use crate::web::templates::*;
use axum::{
    extract::{Extension, Path, Query, State},
    http::{header, HeaderMap, StatusCode, Uri},
    response::IntoResponse,
    routing::get,
    Form, Router,
};
use camino::Utf8PathBuf;
use serde::Deserialize;
use std::sync::Arc;
use unic_langid::LanguageIdentifier;

fn error_page(
    lang: LanguageIdentifier,
    prefix: &str,
    msg: impl std::fmt::Display,
    features: FeatureFlags,
) -> axum::response::Response {
    let template = ErrorTemplate {
        active: String::new(),
        error_message: msg.to_string(),
        tr: Tr::new(lang),
        prefix: prefix.to_string(),
        static_mode: false,
        repo_url: None,
        features,
    };
    template.into_response()
}

pub fn ui() -> Router<Arc<AppState>> {
    Router::new()
        .route("/", get(recipes_page))
        .route("/directory/{*path}", get(recipes_directory))
        .route("/recipe/{*path}", get(recipe_page))
        .route("/edit/{*path}", get(edit_page))
        .route("/new", get(new_page).post(create_recipe))
        .route("/shopping-list", get(shopping_list_page))
        .route("/pantry", get(pantry_page))
        .route("/preferences", get(preferences_page))
        .route("/api-docs", get(api_docs_page))
        .route("/atom.xml", get(atom_feed))
        .route("/rss.xml", get(rss_feed))
}

async fn recipes_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> axum::response::Response {
    recipes_handler(state, None, lang, features).await
}

async fn recipes_directory(
    Path(path): Path<String>,
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> axum::response::Response {
    recipes_handler(state, Some(path), lang, features).await
}

async fn recipes_handler(
    state: Arc<AppState>,
    path: Option<String>,
    lang: LanguageIdentifier,
    features: FeatureFlags,
) -> axum::response::Response {
    let input = crate::web::builders::RecipesBuildInput {
        base_path: &state.base_path,
        url_prefix: &state.url_prefix,
        sub_path: path.as_deref(),
        lang: lang.clone(),
        static_mode: false,
        repo_url: None,
        features,
    };
    match crate::web::builders::build_recipes_template(input) {
        Ok(template) => template.into_response(),
        Err(e) => {
            tracing::error!("Failed to build recipes template: {:?}", e);
            error_page(lang, &state.url_prefix, &e, features)
        }
    }
}

#[derive(Deserialize)]
struct RecipeQuery {
    scale: Option<f64>,
}

async fn recipe_page(
    Path(path): Path<String>,
    Query(query): Query<RecipeQuery>,
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> axum::response::Response {
    let scale = query.scale.unwrap_or(1.0);

    let input = crate::web::builders::RecipeBuildInput {
        base_path: &state.base_path,
        url_prefix: &state.url_prefix,
        recipe_path: &path,
        aisle_path: state.aisle_path.as_ref(),
        scale,
        lang: lang.clone(),
        static_mode: false,
        repo_url: None,
        features,
    };

    match crate::web::builders::build_recipe_template(input) {
        Ok(crate::web::builders::RecipeBuildOutput::Recipe(template)) => template.into_response(),
        Ok(crate::web::builders::RecipeBuildOutput::Menu(template)) => template.into_response(),
        Err(e) => {
            tracing::error!("Failed to build recipe template: {:?}", e);
            error_page(lang, &state.url_prefix, &e, features)
        }
    }
}

async fn edit_page(
    Path(path): Path<String>,
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> axum::response::Response {
    tracing::info!("Edit page requested for path: {}", path);

    // Validate path to prevent directory traversal
    if !crate::util::is_safe_relative_path(&path) {
        tracing::error!("Invalid path: {path}");
        return error_page(
            lang,
            &state.url_prefix,
            format!("Invalid path: {path}"),
            features,
        );
    }

    let recipe_path = Utf8PathBuf::from(&path);

    // Find the actual file
    let entry = match cooklang_find::get_recipe(vec![&state.base_path], &recipe_path) {
        Ok(entry) => entry,
        Err(e) => {
            tracing::error!("Recipe not found: {path}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Recipe not found: {path}: {e}"),
                features,
            );
        }
    };

    let file_path = match entry.path() {
        Some(p) => p,
        None => {
            tracing::error!("Recipe has no file path: {path}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Recipe has no file path: {path}"),
                features,
            );
        }
    };

    // Read raw content
    let content = match tokio::fs::read_to_string(file_path).await {
        Ok(content) => content,
        Err(e) => {
            tracing::error!("Failed to read recipe file: {e}");
            return error_page(
                lang,
                &state.url_prefix,
                format!("Failed to read recipe file: {e}"),
                features,
            );
        }
    };

    // Get recipe name from path
    let recipe_name = path
        .split('/')
        .next_back()
        .unwrap_or(&path)
        .replace(".cook", "")
        .replace(".menu", "");

    let template = crate::web::templates::EditTemplate {
        active: "recipes".to_string(),
        recipe_name,
        recipe_path: path,
        content,
        base_path: state.base_path.to_string(),
        tr: crate::web::templates::Tr::new(lang),
        prefix: state.url_prefix.clone(),
        static_mode: false,
        repo_url: None,
        features,
    };

    template.into_response()
}

#[derive(Deserialize, Default)]
struct NewPageQuery {
    error: Option<String>,
    filename: Option<String>,
}

async fn new_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
    Query(query): Query<NewPageQuery>,
) -> impl IntoResponse {
    crate::web::templates::NewTemplate {
        active: "recipes".to_string(),
        tr: Tr::new(lang),
        error: query.error,
        filename: query.filename,
        prefix: state.url_prefix.clone(),
        static_mode: false,
        repo_url: None,
        features,
    }
}

#[derive(Deserialize)]
struct NewRecipeForm {
    filename: String,
}

/// Helper to build redirect URL with error message
fn new_page_error(prefix: &str, error: &str, filename: &str) -> axum::response::Response {
    let encoded_error = urlencoding::encode(error);
    let encoded_filename = urlencoding::encode(filename);
    axum::response::Redirect::to(&format!(
        "{prefix}/new?error={}&filename={}",
        encoded_error, encoded_filename
    ))
    .into_response()
}

/// Validates that the request originated from the same host (CSRF protection)
fn validate_same_origin(headers: &HeaderMap, host: &str) -> bool {
    // Origin first: it is the header a browser always sends on a form POST,
    // and the one an attacker cannot forge.
    if let Some(origin) = headers.get(header::ORIGIN) {
        return origin
            .to_str()
            .is_ok_and(|origin| super::cors::origin_matches_host(origin, host));
    }

    // Referer is less reliable but better than nothing.
    if let Some(referer) = headers.get(header::REFERER) {
        return referer
            .to_str()
            .is_ok_and(|referer| super::cors::origin_matches_host(referer, host));
    }

    // Neither header: reject. Browsers always send one for a form submission,
    // unlike the API, where a missing Origin just means a non-browser client.
    false
}

async fn create_recipe(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    Form(form): Form<NewRecipeForm>,
) -> impl IntoResponse {
    // The raw `Host` header, not axum-extra's `Host` extractor: that one
    // prefers `X-Forwarded-Host`, which any client can set.
    let host = super::cors::host_header(&headers).unwrap_or_default();
    if state.csrf_check && !validate_same_origin(&headers, host) {
        tracing::warn!("CSRF validation failed for create_recipe request");
        return (StatusCode::FORBIDDEN, "Invalid request origin").into_response();
    }

    let original_filename = form.filename.clone();

    // Validate input before sanitization
    if form.filename.trim().is_empty() {
        return new_page_error(
            &state.url_prefix,
            "Recipe name cannot be empty",
            &original_filename,
        );
    }

    // Sanitize path - allow alphanumeric, space, dash, underscore, and forward slash
    let recipe_path: String = form
        .filename
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == ' ' || *c == '-' || *c == '_' || *c == '/')
        .collect();

    // Clean up path: remove leading/trailing slashes, collapse multiple slashes
    let recipe_path = recipe_path
        .trim_matches('/')
        .split('/')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("/");

    if recipe_path.is_empty() {
        return new_page_error(
            &state.url_prefix,
            "Recipe name cannot be empty",
            &original_filename,
        );
    }

    let file_path = state.base_path.join(format!("{}.cook", recipe_path));

    // Security: Validate path structure before any filesystem operations
    // Check that the constructed path, when normalized, stays within base_path
    let base_path_clone = state.base_path.clone();
    let base_canonical =
        match tokio::task::spawn_blocking(move || base_path_clone.canonicalize_utf8()).await {
            Ok(Ok(p)) => p,
            _ => {
                return new_page_error(
                    &state.url_prefix,
                    "Internal error: invalid base path",
                    &original_filename,
                );
            }
        };

    // Validate parent path components don't escape base_path
    // We do this by checking the joined path doesn't contain .. after normalization
    let normalized_path = file_path.as_str().replace("\\", "/");
    if normalized_path.contains("/../") || normalized_path.ends_with("/..") {
        tracing::warn!("Path traversal attempt detected in: {}", recipe_path);
        return new_page_error(&state.url_prefix, "Invalid recipe path", &original_filename);
    }

    // For the file path, we check the parent directory
    if let Some(parent) = file_path.parent() {
        // Create parent directories if they don't exist
        if !parent.exists() {
            if let Err(e) = tokio::fs::create_dir_all(parent).await {
                tracing::error!("Failed to create directories: {}", e);
                return new_page_error(&state.url_prefix, "Failed to create directory. Check that the recipes folder has write permissions.", &original_filename);
            }
        }

        // Now verify the created parent is under base_path
        let parent_owned = parent.to_owned();
        match tokio::task::spawn_blocking(move || parent_owned.canonicalize_utf8()).await {
            Ok(Ok(parent_canonical)) => {
                if !parent_canonical.starts_with(&base_canonical) {
                    tracing::warn!(
                        "Path traversal attempt: {} not under {}",
                        parent_canonical,
                        base_canonical
                    );
                    // Clean up the created directory if it's outside base_path
                    let _ = tokio::fs::remove_dir_all(parent).await;
                    return new_page_error(
                        &state.url_prefix,
                        "Invalid recipe path",
                        &original_filename,
                    );
                }
            }
            _ => {
                return new_page_error(
                    &state.url_prefix,
                    "Invalid recipe path",
                    &original_filename,
                );
            }
        }
    }

    // Get the recipe name (last component of path) for the title
    let recipe_name = recipe_path
        .split('/')
        .next_back()
        .unwrap_or(&recipe_path)
        .replace(['-', '_'], " ");

    // Create recipe with YAML frontmatter
    let template = format!("---\ntitle: {}\n---\n\n", recipe_name);

    // Use OpenOptions with create_new to atomically check existence and create
    // This prevents TOCTOU race conditions
    use tokio::io::AsyncWriteExt;
    let file = tokio::fs::OpenOptions::new()
        .write(true)
        .create_new(true) // Fails if file exists - atomic check + create
        .open(&file_path)
        .await;

    match file {
        Ok(mut f) => {
            if let Err(e) = f.write_all(template.as_bytes()).await {
                tracing::error!("Failed to write recipe: {}", e);
                return new_page_error(
                    &state.url_prefix,
                    "Failed to write recipe file",
                    &original_filename,
                );
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            return new_page_error(
                &state.url_prefix,
                "A recipe with this name already exists",
                &original_filename,
            );
        }
        Err(e) => {
            tracing::error!("Failed to create recipe file: {}", e);
            return new_page_error(
                &state.url_prefix,
                "Failed to create recipe file",
                &original_filename,
            );
        }
    }

    // Redirect to editor
    axum::response::Redirect::to(&format!("{}/edit/{}.cook", state.url_prefix, recipe_path))
        .into_response()
}

async fn shopping_list_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> impl IntoResponse {
    ShoppingListTemplate {
        active: "shopping".to_string(),
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
        static_mode: false,
        repo_url: None,
        features,
    }
}

async fn pantry_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> Result<impl IntoResponse, StatusCode> {
    // Load pantry configuration
    let pantry_path = state.pantry_path.as_ref();

    let mut sections = Vec::new();

    if let Some(path) = pantry_path {
        if let Ok(content) = tokio::fs::read_to_string(path).await {
            let result = cooklang::pantry::parse_lenient(&content);

            if let Some(pantry_conf) = result.output() {
                // Convert pantry data to template format
                for (section_name, items) in &pantry_conf.sections {
                    let mut pantry_items = Vec::new();

                    for item in items {
                        pantry_items.push(crate::web::templates::PantryItem {
                            name: item.name().to_string(),
                            quantity: item.quantity().map(|q| q.to_string()),
                            bought: item.bought().map(|b| b.to_string()),
                            expire: item.expire().map(|e| e.to_string()),
                            low: item.low().map(|l| l.to_string()),
                        });
                    }

                    sections.push(crate::web::templates::PantrySection {
                        name: section_name.clone(),
                        items: pantry_items,
                    });
                }
            }
        }
    }

    Ok(PantryTemplate {
        active: "pantry".to_string(),
        configured: pantry_path.is_some(),
        sections,
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
        static_mode: false,
        repo_url: None,
        features,
    })
}

async fn preferences_page(
    State(state): State<Arc<AppState>>,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> impl IntoResponse {
    #[cfg(feature = "sync")]
    let (sync_logged_in, sync_email, sync_syncing, _sync_reason) = state.sync_status().await;
    #[cfg(not(feature = "sync"))]
    let (sync_logged_in, sync_email, sync_syncing) = (false, None, false);

    PreferencesTemplate {
        active: "preferences".to_string(),
        aisle_path: state
            .aisle_path
            .as_ref()
            .map(|p| p.to_string())
            .unwrap_or_else(|| "Not configured".to_string()),
        pantry_path: state
            .pantry_path
            .as_ref()
            .map(|p| p.to_string())
            .unwrap_or_else(|| "Not configured".to_string()),
        base_path: state.base_path.to_string(),
        version: format!("{} - in food we trust", env!("CARGO_PKG_VERSION")),
        tr: Tr::new(lang),
        sync_enabled: cfg!(feature = "sync"),
        sync_logged_in,
        sync_email,
        sync_syncing,
        prefix: state.url_prefix.clone(),
        static_mode: false,
        repo_url: None,
        features,
    }
}

async fn atom_feed(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    uri: Uri,
    Extension(lang): Extension<LanguageIdentifier>,
) -> axum::response::Response {
    feed_response(
        crate::build::feed::FeedFormat::Atom,
        &state,
        &headers,
        &uri,
        lang,
    )
    .await
}

async fn rss_feed(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    uri: Uri,
    Extension(lang): Extension<LanguageIdentifier>,
) -> axum::response::Response {
    feed_response(
        crate::build::feed::FeedFormat::Rss,
        &state,
        &headers,
        &uri,
        lang,
    )
    .await
}

/// Absolute URL of the site root for links in a feed.
///
/// Feeds need absolute links. Like `api_docs_page`, the host is the authority
/// the request was addressed to, never `X-Forwarded-Host` (see
/// `cors::request_authority`). `X-Forwarded-Proto: https` is honoured so a
/// TLS-terminating proxy yields https links; it can only change the scheme
/// of the response sent back to the same client.
fn feed_base_url(headers: &HeaderMap, uri: &Uri, url_prefix: &str) -> Option<String> {
    let host = super::cors::request_authority(headers, uri)?;
    let https = headers
        .get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.split(',').next())
        .is_some_and(|v| v.trim().eq_ignore_ascii_case("https"));
    let scheme = if https { "https" } else { "http" };
    let base = format!("{scheme}://{host}{url_prefix}/");
    // Reject a Host that would smuggle a path, query or credentials into the
    // links: it must parse back to exactly scheme + authority + prefix.
    let parsed = url::Url::parse(&base).ok()?;
    let clean = parsed.host().is_some()
        && parsed.username().is_empty()
        && parsed.query().is_none()
        && parsed.fragment().is_none()
        && parsed.path() == format!("{url_prefix}/");
    clean.then_some(base)
}

async fn feed_response(
    format: crate::build::feed::FeedFormat,
    state: &AppState,
    headers: &HeaderMap,
    uri: &Uri,
    lang: LanguageIdentifier,
) -> axum::response::Response {
    use fluent_templates::Loader;

    let Some(base) = feed_base_url(headers, uri, &state.url_prefix) else {
        return (StatusCode::BAD_REQUEST, "Missing or invalid Host header").into_response();
    };
    let title = crate::web::i18n::LOCALES.lookup(&lang, "recipes-title");
    let lang_tag = lang.to_string();
    let base_path = state.base_path.clone();

    // Walking the recipe tree reads every file: keep it off the async runtime.
    let rendered = tokio::task::spawn_blocking(move || {
        let tree = cooklang_find::build_tree(&base_path)
            .map_err(|e| anyhow::anyhow!("Failed to build recipe tree: {e}"))?;
        Ok::<_, anyhow::Error>(crate::build::feed::render_feed(
            format,
            &tree,
            crate::build::feed::PageUrls::Server,
            &base,
            &title,
            &lang_tag,
        ))
    })
    .await;

    match rendered {
        Ok(Ok(xml)) => ([(header::CONTENT_TYPE, format.content_type())], xml).into_response(),
        Ok(Err(e)) => {
            tracing::error!("Failed to render feed: {e:#}");
            (StatusCode::INTERNAL_SERVER_ERROR, "Failed to render feed").into_response()
        }
        Err(e) => {
            tracing::error!("Feed task failed: {e}");
            (StatusCode::INTERNAL_SERVER_ERROR, "Failed to render feed").into_response()
        }
    }
}

async fn api_docs_page(
    State(state): State<Arc<AppState>>,
    headers: HeaderMap,
    uri: Uri,
    Extension(lang): Extension<LanguageIdentifier>,
    Extension(features): Extension<FeatureFlags>,
) -> impl IntoResponse {
    // Rendered so integrators can copy a working URL rather than a relative
    // path. The authority the request was addressed to, not `Forwarded` /
    // `X-Forwarded-Host`: see `cors::request_authority`. Behind a proxy that
    // rewrites `Host` this shows the internal name, which is the same
    // trade-off the CSRF guard makes. A request that carries no usable
    // authority at all is malformed under HTTP/1.1, so fall back to the
    // relative path rather than printing `http:///api`.
    let base_url = match super::cors::request_authority(&headers, &uri) {
        Some(host) => format!("http://{host}{}/api", state.url_prefix),
        None => format!("{}/api", state.url_prefix),
    };

    ApiDocsTemplate {
        active: "preferences".to_string(),
        base_url,
        preamble: crate::web::api_docs::preamble(),
        sections: crate::web::api_docs::sections(),
        tr: Tr::new(lang),
        prefix: state.url_prefix.clone(),
        static_mode: false,
        repo_url: None,
        features,
    }
}

#[cfg(test)]
mod feed_url_tests {
    use super::feed_base_url;
    use axum::http::{HeaderMap, HeaderValue, Uri};

    fn headers(pairs: &[(&'static str, &'static str)]) -> HeaderMap {
        let mut map = HeaderMap::new();
        for (name, value) in pairs {
            map.append(*name, HeaderValue::from_static(value));
        }
        map
    }

    fn uri() -> Uri {
        "/atom.xml".parse().unwrap()
    }

    #[test]
    fn uses_host_and_prefix() {
        let h = headers(&[("host", "cook.lan:9080")]);
        assert_eq!(
            feed_base_url(&h, &uri(), "").as_deref(),
            Some("http://cook.lan:9080/")
        );
        assert_eq!(
            feed_base_url(&h, &uri(), "/cook").as_deref(),
            Some("http://cook.lan:9080/cook/")
        );
    }

    #[test]
    fn honours_forwarded_proto_but_not_forwarded_host() {
        let h = headers(&[
            ("host", "cook.example.com"),
            ("x-forwarded-proto", "https"),
            ("x-forwarded-host", "evil.test"),
        ]);
        assert_eq!(
            feed_base_url(&h, &uri(), "").as_deref(),
            Some("https://cook.example.com/")
        );
    }

    #[test]
    fn rejects_missing_or_smuggling_hosts() {
        assert_eq!(feed_base_url(&headers(&[]), &uri(), ""), None);
        for bad in [
            "evil.test/path",
            "user@evil.test",
            "evil.test?x=1",
            "evil.test#x",
        ] {
            let h = headers(&[("host", bad)]);
            assert_eq!(feed_base_url(&h, &uri(), ""), None, "{bad}");
        }
    }
}