kellnr-settings 7.0.0

Kellnr is a self-hosted registry for Rust crates with support for rustdocs and crates.io caching.
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
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use clap::{CommandFactory, Parser, Subcommand};

use crate::compile_time_config;
use crate::settings::{
    Settings, SettingsArgs, SettingsError, SettingsPartial, SettingsProv, build_prov_with_cli,
    settings_from_prov,
};

#[derive(Parser)]
#[command(name = "kellnr", version, about)]
pub struct Cli {
    /// Path to configuration file
    #[arg(id = "config", short = 'c', long = "config", global = true)]
    pub config_file: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Subcommand)]
#[allow(clippy::large_enum_variant)]
pub enum Command {
    /// Start the kellnr server
    Start {
        /// All section flags live on `SettingsArgs`, which is generated by
        /// `provcfg-clap::ClapArgs`. Each section is flattened in, so flags
        /// like `--registry-data-dir` and `--log-level` appear under `start`.
        #[command(flatten)]
        server: SettingsArgs,
    },
    /// Configuration management commands
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Build the rustdoc of an unpacked crate. Used internally by the docs
    /// queue to run untrusted builds in a separate process.
    #[command(name = DOC_BUILD_SUBCOMMAND, hide = true)]
    DocBuild {
        /// Path to the unpacked crate
        crate_path: PathBuf,

        /// Sparse index URL that replaces the crates.io source
        #[arg(long = DOC_BUILD_CRATESIO_INDEX_ARG)]
        cratesio_index: Option<String>,
    },
}

/// Name of the hidden subcommand that builds the docs of a single crate.
pub const DOC_BUILD_SUBCOMMAND: &str = "doc-build";
/// Long flag of [`DOC_BUILD_SUBCOMMAND`] for the crates.io index override.
pub const DOC_BUILD_CRATESIO_INDEX_ARG: &str = "cratesio-index";

#[derive(Subcommand)]
pub enum ConfigAction {
    /// Show the current configuration
    Show {
        /// Hide settings that have their default value
        #[arg(long = "no-defaults")]
        no_defaults: bool,

        /// Show the source (toml, env, cli) for each setting
        #[arg(long = "sources")]
        show_sources: bool,
    },
    /// Initialize a new configuration file with default values
    Init {
        /// Output file path (default: ./kellnr.toml)
        #[arg(short = 'o', long = "output")]
        output: Option<PathBuf>,
    },
}

/// Options for the `config show` command
#[derive(Debug, Clone, Default)]
pub struct ShowConfigOptions {
    /// Hide settings that have their default value
    pub no_defaults: bool,
    /// Show the source (toml, env, cli) for each setting
    pub show_sources: bool,
}

/// A `Settings` paired with its per-leaf `SettingsProv`. Bundled because every
/// non-init `CliResult` variant needs both, the active values for runtime use
/// and the provenance for source attribution (`/settings` API and
/// `config show`). `prov` is `Arc` so it can move into the app state without a
/// re-allocation; `SettingsProv` is also large enough that an inline owned
/// value would balloon `CliResult`.
pub struct ResolvedSettings {
    pub settings: Settings,
    pub prov: Arc<SettingsProv>,
}

pub enum CliResult {
    RunServer(ResolvedSettings),
    ShowConfig {
        resolved: ResolvedSettings,
        options: ShowConfigOptions,
    },
    /// `config init` writes a fresh `Settings::default()` to `output`; no
    /// settings field is carried because there's nothing to vary per call.
    InitConfig {
        output: PathBuf,
    },
    ShowHelp,
    /// Build the docs of a crate in the current process and exit.
    BuildDocs {
        crate_path: PathBuf,
        cratesio_index: Option<String>,
    },
}

pub fn parse_cli() -> Result<CliResult, SettingsError> {
    let cli = Cli::parse();

    match cli.command {
        // No subcommand → print help and exit without touching the config
        // pipeline. Doing this before any file/env resolution means
        // `kellnr` with no args always succeeds, even if `KELLNR_CONFIG_FILE`
        // happens to point at a missing path.
        None => {
            Cli::command().print_help().ok();
            Ok(CliResult::ShowHelp)
        }

        // `config init` doesn't need to merge sources, it writes the
        // compiled-in defaults.
        Some(Command::Config {
            action: ConfigAction::Init { output },
        }) => Ok(CliResult::InitConfig {
            output: output.unwrap_or_else(|| PathBuf::from("kellnr.toml")),
        }),

        // The docs build runs untrusted code and gets no settings on purpose.
        Some(Command::DocBuild {
            crate_path,
            cratesio_index,
        }) => Ok(CliResult::BuildDocs {
            crate_path,
            cratesio_index,
        }),

        Some(ref command) => build_from_command(cli.config_file, command),
    }
}

/// Settings of the running `kellnr start`, resolved from the same command
/// line, environment and config file as at startup. For code that runs before
/// the settings are passed around, like the database migrations. `None` if the
/// process was not started with valid `kellnr` arguments, for example in tests.
#[must_use]
pub fn settings_from_process() -> Option<Settings> {
    let cli = Cli::try_parse().ok()?;
    let command = cli.command?;
    let prov = build_prov(cli.config_file, &command).ok()?;
    Some(settings_from_prov(&prov))
}

fn build_prov(
    cli_config_file: Option<PathBuf>,
    command: &Command,
) -> Result<SettingsProv, SettingsError> {
    // Config file priority: CLI > env var > compile-time > None.
    let env_config_file = std::env::var("KELLNR_CONFIG_FILE").ok();
    let config_file: Option<PathBuf> = cli_config_file
        .or(env_config_file.map(PathBuf::from))
        .or(compile_time_config::KELLNR_COMPTIME__CONFIG_FILE.map(PathBuf::from));

    // `SettingsPartial::from(&SettingsArgs)` is macro-generated by
    // `provcfg-clap`: it walks every section and copies the user-supplied
    // `Some(...)` values from clap. Unset flags stay `None`, so the CLI
    // source contributes provenance only for fields explicitly passed.
    let cli_partial: Option<SettingsPartial> = match command {
        Command::Start { server } => Some(SettingsPartial::from(server)),
        Command::Config { .. } | Command::DocBuild { .. } => None,
    };

    build_prov_with_cli(config_file.as_deref(), cli_partial)
}

fn build_from_command(
    cli_config_file: Option<PathBuf>,
    command: &Command,
) -> Result<CliResult, SettingsError> {
    let prov = build_prov(cli_config_file, command)?;
    let resolved = ResolvedSettings {
        settings: settings_from_prov(&prov),
        prov: Arc::new(prov),
    };

    match command {
        Command::Start { .. } => Ok(CliResult::RunServer(resolved)),
        Command::Config {
            action:
                ConfigAction::Show {
                    no_defaults,
                    show_sources,
                },
        } => Ok(CliResult::ShowConfig {
            resolved,
            options: ShowConfigOptions {
                no_defaults: *no_defaults,
                show_sources: *show_sources,
            },
        }),
        Command::Config {
            action: ConfigAction::Init { .. },
        } => unreachable!("`Init` is handled by `parse_cli` before this point"),
        Command::DocBuild { .. } => {
            unreachable!("`DocBuild` is handled by `parse_cli` before this point")
        }
    }
}

/// Map every settings leaf (dotted path) to its user-facing CLI flag(s).
///
/// Walks `start`'s flattened `SettingsArgs` via clap reflection so the
/// `/settings` UI doesn't have to hand-maintain a parallel table that drifts
/// from the actual flags. Output format: `"--registry-data-dir, -d"` (long,
/// then short if any). Args whose id doesn't follow the `<prefix>-<field>`
/// convention (e.g. the top-level `--config` flag, clap's built-in `--help`)
/// are skipped, they don't correspond to a settings leaf.
#[must_use]
pub fn cli_flag_map() -> HashMap<String, String> {
    let cmd = Cli::command();
    let Some(start) = cmd.find_subcommand("start") else {
        return HashMap::new();
    };

    let mut map = HashMap::new();
    for arg in start.get_arguments() {
        let id = arg.get_id().as_str();
        let Some(path) = id_to_dotted_path(id) else {
            continue;
        };
        let mut flag = String::new();
        if let Some(long) = arg.get_long() {
            flag.push_str("--");
            flag.push_str(long);
        }
        if let Some(short) = arg.get_short() {
            if !flag.is_empty() {
                flag.push_str(", ");
            }
            flag.push('-');
            flag.push(short);
        }
        if !flag.is_empty() {
            map.insert(path, flag);
        }
    }
    map
}

/// Convert a clap arg id like `registry-data-dir` into its `SettingsProv`
/// dotted path `registry.data_dir`. Returns `None` for ids without at least
/// one `-` (those don't come from a `clap_prefix`-ed section and so don't
/// map to a leaf).
fn id_to_dotted_path(id: &str) -> Option<String> {
    // Sections whose name contains "_" have a prefix with "-", so the first
    // "-" does not end the section for them.
    const MULTI_WORD_SECTIONS: &[&str] = &["cratesio-filter", "registry-filter"];

    let (section, rest) = MULTI_WORD_SECTIONS
        .iter()
        .find_map(|s| Some((*s, id.strip_prefix(s)?.strip_prefix('-')?)))
        .or_else(|| id.split_once('-'))?;
    Some(format!(
        "{}.{}",
        section.replace('-', "_"),
        rest.replace('-', "_")
    ))
}

#[cfg(test)]
mod tests {
    use std::io::Write;
    use std::path::Path;

    use provcfg::Category;
    use tempfile::NamedTempFile;

    use super::*;
    use crate::protocol::Protocol;

    // Env-source precedence (env wins over TOML, CLI wins over env) is covered
    // by provcfg's own suite, `full_layered_stack_defaults_toml_env_cli` in
    // `provcfg/src/tests/defaults.rs`. Re-asserting it here would require
    // mutating `KELLNR_*` process env vars, which means `unsafe` (edition 2024)
    // and is forbidden workspace-wide. These tests instead pin down the
    // kellnr-level wiring, TOML and CLI, through the same `parse_cli` path,
    // and the `build_prov_with_cli` body documents the env layer's position.

    fn write_toml(contents: &str) -> NamedTempFile {
        let mut file = NamedTempFile::new().expect("tempfile");
        file.write_all(contents.as_bytes()).expect("write toml");
        file
    }

    /// Drive `Cli::try_parse_from` + `build_from_command` end-to-end, the
    /// same code path `parse_cli` takes once `Cli::parse()` has read argv.
    fn run_start(config_file: Option<&Path>, extra_args: &[&str]) -> CliResult {
        let mut argv: Vec<&str> = vec!["kellnr", "start"];
        argv.extend(extra_args.iter().copied());
        let cli = Cli::try_parse_from(&argv).expect("clap should accept argv");
        let command = cli.command.expect("start subcommand present");
        build_from_command(config_file.map(PathBuf::from), &command).expect("build")
    }

    #[test]
    fn toml_only_marks_overridden_leaves_with_file_provenance() {
        let file = write_toml("[registry]\ndata_dir = \"/tmp/from-toml\"\n");
        let CliResult::RunServer(resolved) = run_start(Some(file.path()), &[]) else {
            panic!("expected RunServer");
        };

        assert_eq!(resolved.settings.registry.data_dir, "/tmp/from-toml");
        assert_eq!(
            resolved.prov.registry.data_dir.source().category(),
            Category::File,
        );
    }

    #[test]
    fn cli_flag_overrides_toml_with_cli_provenance() {
        let file = write_toml("[registry]\ndata_dir = \"/tmp/from-toml\"\n");
        let CliResult::RunServer(resolved) =
            run_start(Some(file.path()), &["--registry-data-dir", "/tmp/from-cli"])
        else {
            panic!("expected RunServer");
        };

        assert_eq!(resolved.settings.registry.data_dir, "/tmp/from-cli");
        assert_eq!(
            resolved.prov.registry.data_dir.source().category(),
            Category::Cli,
        );
    }

    #[test]
    fn cookie_secure_defaults_to_unset_and_reads_from_toml_and_cli() {
        let file = write_toml("[registry]\ndata_dir = \"/tmp/x\"\n");
        let CliResult::RunServer(resolved) = run_start(Some(file.path()), &[]) else {
            panic!("expected RunServer");
        };
        assert_eq!(resolved.settings.origin.cookie_secure, None);

        let file = write_toml("[origin]\ncookie_secure = true\n");
        let CliResult::RunServer(resolved) = run_start(Some(file.path()), &[]) else {
            panic!("expected RunServer");
        };
        assert_eq!(resolved.settings.origin.cookie_secure, Some(true));

        let CliResult::RunServer(resolved) =
            run_start(Some(file.path()), &["--origin-cookie-secure", "false"])
        else {
            panic!("expected RunServer");
        };
        assert_eq!(resolved.settings.origin.cookie_secure, Some(false));
    }

    #[test]
    fn origin_protocol_reads_from_cli() {
        let CliResult::RunServer(resolved) = run_start(None, &["--origin-protocol", "https"])
        else {
            panic!("expected RunServer");
        };

        assert_eq!(resolved.settings.origin.protocol, Protocol::Https);
        assert_eq!(
            resolved.prov.origin.protocol.source().category(),
            Category::Cli,
        );
    }

    #[test]
    fn filter_flags_reach_the_settings() {
        let CliResult::RunServer(resolved) = run_start(
            None,
            &[
                "--cratesio-filter-license-enabled",
                "true",
                "--cratesio-filter-license-allowed",
                "MIT,Apache-2.0",
                "--cratesio-filter-license-unknown",
                "allow",
                "--registry-filter-license-exempt-crates",
                "ring,openssl",
            ],
        ) else {
            panic!("expected RunServer");
        };

        let cratesio = &resolved.settings.cratesio_filter;
        assert!(cratesio.license_enabled);
        assert_eq!(vec!["MIT", "Apache-2.0"], cratesio.license_allowed);
        assert_eq!(crate::LicenseUnknown::Allow, cratesio.license_unknown);
        assert_eq!(
            vec!["ring", "openssl"],
            resolved.settings.registry_filter.license_exempt_crates
        );
        assert_eq!(
            resolved
                .prov
                .cratesio_filter
                .license_allowed
                .source()
                .category(),
            Category::Cli,
        );
        assert_eq!(
            resolved
                .prov
                .registry_filter
                .license_enabled
                .source()
                .category(),
            Category::Default,
        );
    }

    #[test]
    fn invalid_license_unknown_flag_is_rejected() {
        let result = Cli::try_parse_from([
            "kellnr",
            "start",
            "--registry-filter-license-unknown",
            "deneay",
        ]);

        assert!(result.is_err());
    }

    #[test]
    fn config_show_returns_show_config_variant_with_options() {
        // `config show --sources` flows through `build_from_command` like
        // `start` does, so it must also produce a usable `SettingsProv`.
        let file = write_toml("[registry]\ndata_dir = \"/tmp/from-toml\"\n");
        let argv = ["kellnr", "config", "show", "--sources"];
        let cli = Cli::try_parse_from(argv).expect("clap parse");
        let command = cli.command.expect("config subcommand present");

        let result = build_from_command(Some(file.path().to_path_buf()), &command).unwrap();
        let CliResult::ShowConfig { resolved, options } = result else {
            panic!("expected ShowConfig variant");
        };
        assert!(options.show_sources);
        assert!(!options.no_defaults);
        assert_eq!(resolved.settings.registry.data_dir, "/tmp/from-toml");
        assert_eq!(
            resolved.prov.registry.data_dir.source().category(),
            Category::File,
        );
    }

    #[test]
    fn id_to_dotted_path_converts_dashes_after_first_segment() {
        assert_eq!(
            id_to_dotted_path("registry-data-dir"),
            Some("registry.data_dir".to_string())
        );
        assert_eq!(
            id_to_dotted_path("registry-token-cache-ttl-seconds"),
            Some("registry.token_cache_ttl_seconds".to_string())
        );
        // Single-segment ids (top-level flags like `--config`, clap's --help)
        // don't map to a settings leaf.
        assert_eq!(id_to_dotted_path("config"), None);
        assert_eq!(id_to_dotted_path("help"), None);
    }

    #[test]
    fn cli_flag_map_covers_every_section_with_correct_paths() {
        let map = cli_flag_map();

        // A long-only flag: clap auto-derives `--registry-data-dir` from the
        // `clap_prefix = "registry"` section and field name `data_dir`.
        assert_eq!(
            map.get("registry.data_dir").map(String::as_str),
            Some("--registry-data-dir, -d"),
            "registry.data_dir must surface its auto-derived long plus the manual `-d` short"
        );
        // A user-supplied `#[arg(long = "...")]` overrides the auto-derive
        // while the id (and therefore our lookup key) still follows the
        // section.field convention.
        assert_eq!(
            map.get("registry.token_cache_ttl_seconds")
                .map(String::as_str),
            Some("--registry-token-cache-ttl"),
        );
        // Spot-check leaves from other sections so a missing wiring on any
        // single section shows up here.
        assert_eq!(
            map.get("docs.enabled").map(String::as_str),
            Some("--docs-enabled")
        );
        assert_eq!(
            map.get("s3.allow_http").map(String::as_str),
            Some("--s3-allow-http")
        );
        assert_eq!(
            map.get("local.port").map(String::as_str),
            Some("--local-port, -p")
        );
        // Sections with a multi-word name keep it together.
        assert_eq!(
            map.get("cratesio_filter.license_allowed")
                .map(String::as_str),
            Some("--cratesio-filter-license-allowed")
        );
        assert_eq!(
            map.get("registry_filter.license_unknown")
                .map(String::as_str),
            Some("--registry-filter-license-unknown")
        );
        // The top-level `--config` arg is not a settings leaf, must not leak in.
        assert!(
            !map.contains_key("config"),
            "top-level `--config` is not a leaf"
        );
    }

    #[test]
    fn doc_build_subcommand_is_hidden_and_parses_arguments() {
        let cli = Cli::try_parse_from([
            "kellnr",
            DOC_BUILD_SUBCOMMAND,
            "/tmp/crate",
            "--cratesio-index",
            "https://proxy/index/",
        ])
        .expect("clap should accept argv");

        let Some(Command::DocBuild {
            crate_path,
            cratesio_index,
        }) = cli.command
        else {
            panic!("expected DocBuild");
        };
        assert_eq!(crate_path, PathBuf::from("/tmp/crate"));
        assert_eq!(cratesio_index.as_deref(), Some("https://proxy/index/"));
        assert!(
            Cli::command()
                .find_subcommand(DOC_BUILD_SUBCOMMAND)
                .unwrap()
                .is_hide_set()
        );
    }
}