faucet-cli 1.8.1

Config-driven CLI runner for faucet-stream pipelines (YAML / JSON, Meltano-style)
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
//! `ServeConfig` — the validated, runtime-ready server configuration built from
//! `ServeArgs`. The no-auth gate lives here so an unauthenticated server can
//! never start silently.

use crate::cli::ServeArgs;
use crate::error::{CliError, CliResult};
use crate::serve::cluster::ClusterConfig;
use crate::serve::rbac::{AuthContext, RbacConfig, Role};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

/// How `/v1/*` requests are authenticated.
#[derive(Clone)]
pub enum AuthMode {
    /// Require `Authorization: Bearer <token>` — a single implicit `admin`
    /// principal.
    Token(String),
    /// Multi-principal RBAC from `--auth-config`: bearer token → principal → role.
    Rbac(Arc<RbacConfig>),
    /// Authentication explicitly disabled via `--no-auth`.
    None,
}

// Hand-written so `{:?}` of an `AuthMode` (or the `ServeConfig` that embeds one)
// never prints the bearer token in clear. The token is also registered for
// redaction in `ServeConfig::from_args`, but masking here closes the Debug path
// directly.
impl std::fmt::Debug for AuthMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuthMode::Token(_) => f.debug_tuple("Token").field(&"***").finish(),
            AuthMode::Rbac(cfg) => f.debug_tuple("Rbac").field(cfg).finish(),
            AuthMode::None => f.write_str("None"),
        }
    }
}

impl AuthMode {
    /// Resolve a request's `Authorization: Bearer` token to its [`AuthContext`],
    /// or `None` if the credential is missing / invalid. `--no-auth` yields an
    /// implicit `anonymous` admin so downstream authz + audit are uniform.
    pub fn resolve(&self, bearer: Option<&str>) -> Option<AuthContext> {
        match self {
            AuthMode::None => Some(AuthContext {
                principal: "anonymous".to_string(),
                role: Role::Admin,
                source_ip: None,
            }),
            AuthMode::Token(expected) => bearer
                .filter(|t| crate::serve::auth::constant_time_eq(t.as_bytes(), expected.as_bytes()))
                .map(|_| AuthContext {
                    principal: "token".to_string(),
                    role: Role::Admin,
                    source_ip: None,
                }),
            AuthMode::Rbac(cfg) => bearer.and_then(|t| cfg.authenticate(t)),
        }
    }
}

/// Run-history storage backend selection (parsed from `--history`).
#[derive(Debug, Clone)]
pub enum HistoryBackendSpec {
    /// In-process `DashMap`; lost on restart (default).
    Memory,
    /// Postgres connection URL (stored verbatim, e.g. `postgres://host/db`).
    Postgres(String),
    /// SQLite connection URL, stored verbatim including the `sqlite:` scheme
    /// (e.g. `sqlite:runs.db`, `sqlite::memory:`) so the backend can hand it
    /// straight to `sqlx` without re-deriving the form.
    Sqlite(String),
}

/// Validated server configuration.
#[derive(Debug, Clone)]
pub struct ServeConfig {
    pub listen: SocketAddr,
    pub auth: AuthMode,
    pub max_concurrent_runs: usize,
    pub max_queued_runs: usize,
    pub default_config_path: Option<PathBuf>,
    pub history: HistoryBackendSpec,
    pub cors_origins: Vec<String>,
    pub body_limit_bytes: usize,
    pub shutdown_grace: Duration,
    pub retain_terminal_runs: Duration,
    pub idempotency_retention: Duration,
    /// Run-ownership lease TTL for multi-instance orphan fencing (#146 H7).
    pub lease_ttl: Duration,
    pub probe_timeout: Duration,
    pub env_file: Option<PathBuf>,
    pub no_env_file: bool,
    /// Tracing filter directive for serve's own subscriber. Set from the
    /// clap-resolved `--log-level` / `FAUCET_LOG`; defaults to `"info"`.
    pub log_level: String,
    /// Whether to serve the embedded web console. Built only when the `serve-ui`
    /// feature is on; this gates serving at runtime (`--no-ui`).
    #[cfg_attr(not(feature = "serve-ui"), allow(dead_code))]
    pub ui_enabled: bool,
    /// Clustered-execution settings (`--cluster*`). Disabled by default.
    pub cluster: ClusterConfig,
    /// Path to a `--triggers` file. `None` = no event-driven triggers. The file
    /// is loaded + validated at startup (gated on the `triggers` feature).
    pub triggers_path: Option<PathBuf>,
}

fn default_max_concurrent() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(4)
        .clamp(1, 16)
}

impl ServeConfig {
    /// Build + validate a `ServeConfig` from parsed CLI args. Enforces the
    /// no-auth gate: a server with neither a token nor `--no-auth` refuses to start.
    pub fn from_args(args: ServeArgs) -> CliResult<Self> {
        // RBAC (`--auth-config`) takes precedence and is mutually exclusive with
        // `--auth-token` / `--no-auth` (enforced by clap `conflicts_with`).
        let auth = if let Some(path) = args.auth_config {
            let rbac = RbacConfig::from_file(&path)?;
            // Register every principal token so the RedactingWriter scrubs it
            // from any tracing/log/error output for the process lifetime.
            for token in rbac.tokens() {
                crate::secrets::registry::register(token);
            }
            AuthMode::Rbac(Arc::new(rbac))
        } else {
            match (args.auth_token, args.no_auth) {
                (Some(t), _) if t.is_empty() => {
                    return Err(CliError::Serve(
                        "--auth-token / FAUCET_SERVE_AUTH_TOKEN must not be empty \
                         (use --no-auth to explicitly disable authentication)"
                            .into(),
                    ));
                }
                (Some(t), _) => {
                    // Register so the RedactingWriter scrubs the token from any
                    // tracing/log/error output for the lifetime of the process.
                    crate::secrets::registry::register(&t);
                    AuthMode::Token(t)
                }
                (None, true) => AuthMode::None,
                (None, false) => {
                    return Err(CliError::Serve(
                        "refusing to start without authentication: pass --auth-token \
                         (or FAUCET_SERVE_AUTH_TOKEN), --auth-config <file> for RBAC, \
                         or --no-auth to explicitly disable it"
                            .into(),
                    ));
                }
            }
        };

        let listen: SocketAddr = args
            .listen
            .parse()
            .map_err(|e| CliError::Serve(format!("invalid --listen '{}': {e}", args.listen)))?;

        let history = match args.history {
            None => HistoryBackendSpec::Memory,
            Some(u) if u.starts_with("postgres://") || u.starts_with("postgresql://") => {
                HistoryBackendSpec::Postgres(u)
            }
            Some(u) if u.starts_with("sqlite:") => HistoryBackendSpec::Sqlite(u),
            Some(u) => {
                return Err(CliError::Serve(format!(
                    "unrecognised --history '{u}': use a postgres:// URL or sqlite:<path>"
                )));
            }
        };

        if args.lease_ttl_secs == 0 {
            return Err(CliError::Serve(
                "--lease-ttl-secs must be > 0 (it gates multi-instance orphan recovery; \
                 0 would immediately expire every run's lease and let a maintenance tick \
                 fail in-flight runs)"
                    .into(),
            ));
        }

        // A zero drain window makes graceful shutdown `timeout(Duration::ZERO,
        // wait_drained())` time out instantly and cancel in-flight runs —
        // defeating the drain. Reject it (mirroring the lease-ttl gate).
        // `--idempotency-retention-secs == 0` is NOT rejected: it is an explicit
        // "dedup disabled" sentinel (every prior claim is immediately expired).
        if args.shutdown_grace_secs == 0 {
            return Err(CliError::Serve(
                "--shutdown-grace-secs must be > 0 (0 makes graceful shutdown cancel \
                 in-flight runs immediately instead of draining them; use a small \
                 value like 1)"
                    .into(),
            ));
        }

        let cluster = if args.cluster {
            if matches!(history, HistoryBackendSpec::Memory) {
                return Err(CliError::Serve(
                    "--cluster requires a persistent --history backend \
                     (postgres://… or sqlite:…); the in-memory store is single-process"
                        .into(),
                ));
            }
            if args.cluster_poll_secs == 0 {
                return Err(CliError::Serve(
                    "--cluster-poll-secs must be > 0 (0 would spin the claim loop \
                     with no back-off, saturating the history DB)"
                        .into(),
                ));
            }
            if args.cluster_max_attempts == 0 {
                return Err(CliError::Serve(
                    "--cluster-max-attempts must be > 0 (0 would never re-run \
                     orphaned runs, defeating failover)"
                        .into(),
                ));
            }
            ClusterConfig {
                enabled: true,
                poll: Duration::from_secs(args.cluster_poll_secs),
                max_attempts: args.cluster_max_attempts,
            }
        } else {
            ClusterConfig::disabled()
        };

        let max_concurrent_runs = args
            .max_concurrent_runs
            .unwrap_or_else(default_max_concurrent)
            .max(1);
        let max_queued_runs = args
            .max_queued_runs
            .unwrap_or_else(|| max_concurrent_runs.saturating_mul(8))
            .max(1);

        Ok(Self {
            listen,
            auth,
            max_concurrent_runs,
            max_queued_runs,
            default_config_path: args.default_config,
            history,
            cors_origins: args.cors_origin,
            body_limit_bytes: args.body_limit_bytes,
            shutdown_grace: Duration::from_secs(args.shutdown_grace_secs),
            retain_terminal_runs: Duration::from_secs(args.retain_terminal_runs_secs),
            idempotency_retention: Duration::from_secs(args.idempotency_retention_secs),
            lease_ttl: Duration::from_secs(args.lease_ttl_secs),
            probe_timeout: Duration::from_secs(args.probe_timeout_secs),
            env_file: args.env_file,
            no_env_file: args.no_env_file,
            log_level: "info".to_string(),
            ui_enabled: !args.no_ui,
            cluster,
            triggers_path: args.triggers,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::SocketAddr;

    fn base_args() -> crate::cli::ServeArgs {
        crate::cli::ServeArgs {
            listen: "127.0.0.1:8080".into(),
            auth_token: None,
            auth_config: None,
            no_auth: false,
            max_concurrent_runs: None,
            max_queued_runs: None,
            default_config: None,
            history: None,
            cors_origin: vec![],
            body_limit_bytes: 1_048_576,
            shutdown_grace_secs: 60,
            retain_terminal_runs_secs: 604_800,
            idempotency_retention_secs: 86_400,
            lease_ttl_secs: 30,
            probe_timeout_secs: 10,
            env_file: None,
            no_env_file: false,
            no_ui: false,
            cluster: false,
            cluster_poll_secs: 2,
            cluster_max_attempts: 3,
            triggers: None,
            mcp: false,
            mcp_allow_mutations: false,
        }
    }

    #[test]
    fn no_auth_gate_rejects_silent_unauthenticated_start() {
        let err = ServeConfig::from_args(base_args()).unwrap_err();
        assert!(err.to_string().contains("--no-auth"), "{err}");
    }

    #[test]
    fn explicit_no_auth_is_allowed() {
        let mut a = base_args();
        a.no_auth = true;
        let cfg = ServeConfig::from_args(a).unwrap();
        assert!(matches!(cfg.auth, AuthMode::None));
    }

    #[test]
    fn token_sets_token_auth() {
        let mut a = base_args();
        a.auth_token = Some("hunter2".into());
        let cfg = ServeConfig::from_args(a).unwrap();
        assert!(matches!(cfg.auth, AuthMode::Token(t) if t == "hunter2"));
    }

    #[test]
    fn resolve_none_is_anonymous_admin() {
        let ctx = AuthMode::None.resolve(None).unwrap();
        assert_eq!(ctx.principal, "anonymous");
        assert_eq!(ctx.role, Role::Admin);
    }

    #[test]
    fn resolve_token_matches_only_exact() {
        let mode = AuthMode::Token("s3cret".into());
        let ctx = mode.resolve(Some("s3cret")).unwrap();
        assert_eq!(ctx.principal, "token");
        assert_eq!(ctx.role, Role::Admin);
        assert!(mode.resolve(Some("wrong")).is_none());
        assert!(mode.resolve(None).is_none());
    }

    #[test]
    fn resolve_rbac_maps_token_to_principal() {
        use crate::serve::rbac::{PrincipalSpec, RbacConfig};
        let cfg = RbacConfig::new(vec![PrincipalSpec {
            name: "bob".into(),
            token: "viewer-tok".into(),
            role: Role::Viewer,
        }])
        .unwrap();
        let mode = AuthMode::Rbac(Arc::new(cfg));
        let ctx = mode.resolve(Some("viewer-tok")).unwrap();
        assert_eq!(ctx.principal, "bob");
        assert_eq!(ctx.role, Role::Viewer);
        assert!(mode.resolve(Some("nope")).is_none());
    }

    #[test]
    fn auth_config_file_builds_rbac_and_registers_tokens() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("auth.yaml");
        std::fs::write(
            &path,
            "principals:\n  - name: carol\n    token: rbacsecret12345\n    role: operator\n",
        )
        .unwrap();
        let mut a = base_args();
        a.auth_config = Some(path);
        let cfg = ServeConfig::from_args(a).unwrap();
        assert!(matches!(cfg.auth, AuthMode::Rbac(_)));
        // Every principal token must be registered for log redaction.
        let scrubbed = crate::secrets::registry::redact("t=rbacsecret12345 end").into_owned();
        assert!(!scrubbed.contains("rbacsecret12345"), "{scrubbed}");
    }

    #[test]
    fn auth_config_debug_masks_tokens() {
        use crate::serve::rbac::{PrincipalSpec, RbacConfig};
        let cfg = RbacConfig::new(vec![PrincipalSpec {
            name: "x".into(),
            token: "supersecretrbac".into(),
            role: Role::Admin,
        }])
        .unwrap();
        let s = format!("{:?}", AuthMode::Rbac(Arc::new(cfg)));
        assert!(!s.contains("supersecretrbac"), "rbac token leaked: {s}");
    }

    #[test]
    fn auth_mode_debug_masks_token() {
        // ServeConfig derives Debug and embeds AuthMode; a {:?} must not print
        // the bearer token in clear.
        let s = format!("{:?}", AuthMode::Token("supersecrettoken".into()));
        assert!(
            !s.contains("supersecrettoken"),
            "serve token leaked via Debug: {s}"
        );
        assert!(s.contains("***"), "token not masked: {s}");
    }

    #[test]
    fn token_is_registered_for_redaction() {
        let mut a = base_args();
        a.auth_token = Some("uniqueserveauthsecret987".into());
        let _cfg = ServeConfig::from_args(a).unwrap();
        // The token must be registered so the RedactingWriter scrubs it from logs.
        let scrubbed =
            crate::secrets::registry::redact("hdr=uniqueserveauthsecret987 end").into_owned();
        assert!(
            !scrubbed.contains("uniqueserveauthsecret987"),
            "serve token not registered for redaction: {scrubbed}"
        );
    }

    #[test]
    fn listen_parses_to_socket_addr() {
        let mut a = base_args();
        a.no_auth = true;
        a.listen = "0.0.0.0:9999".into();
        let cfg = ServeConfig::from_args(a).unwrap();
        assert_eq!(cfg.listen, "0.0.0.0:9999".parse::<SocketAddr>().unwrap());
    }

    #[test]
    fn history_url_selects_backend() {
        let mut a = base_args();
        a.no_auth = true;
        a.history = Some("postgres://localhost/db".into());
        assert!(matches!(
            ServeConfig::from_args(a.clone()).unwrap().history,
            HistoryBackendSpec::Postgres(_)
        ));
        // The `postgresql://` alias maps to the same backend.
        a.history = Some("postgresql://localhost/db".into());
        assert!(matches!(
            ServeConfig::from_args(a.clone()).unwrap().history,
            HistoryBackendSpec::Postgres(_)
        ));
        // SQLite is stored verbatim, scheme included (for direct sqlx use).
        a.history = Some("sqlite:runs.db".into());
        match ServeConfig::from_args(a).unwrap().history {
            HistoryBackendSpec::Sqlite(url) => assert_eq!(url, "sqlite:runs.db"),
            other => panic!("expected Sqlite, got {other:?}"),
        }
    }

    #[test]
    fn empty_token_is_rejected() {
        let mut a = base_args();
        a.auth_token = Some(String::new());
        let err = ServeConfig::from_args(a).unwrap_err();
        assert!(err.to_string().contains("must not be empty"), "{err}");
    }

    #[test]
    fn invalid_listen_returns_error() {
        let mut a = base_args();
        a.no_auth = true;
        a.listen = "not-a-socket".into();
        let err = ServeConfig::from_args(a).unwrap_err();
        assert!(err.to_string().contains("invalid --listen"), "{err}");
    }

    #[test]
    fn unrecognised_history_scheme_returns_error() {
        let mut a = base_args();
        a.no_auth = true;
        a.history = Some("mysql://localhost/db".into());
        let err = ServeConfig::from_args(a).unwrap_err();
        assert!(err.to_string().contains("unrecognised --history"), "{err}");
    }

    #[test]
    fn zero_lease_ttl_is_rejected() {
        let mut a = base_args();
        a.no_auth = true;
        a.lease_ttl_secs = 0;
        let err = ServeConfig::from_args(a).unwrap_err();
        assert!(err.to_string().contains("--lease-ttl-secs"), "{err}");
    }

    #[test]
    fn lease_ttl_maps_to_duration() {
        let mut a = base_args();
        a.no_auth = true;
        a.lease_ttl_secs = 45;
        let cfg = ServeConfig::from_args(a).unwrap();
        assert_eq!(cfg.lease_ttl, Duration::from_secs(45));
    }

    #[test]
    fn zero_shutdown_grace_is_rejected() {
        // A zero drain window makes graceful shutdown `timeout(Duration::ZERO,
        // wait_drained())` cancel in-flight runs instantly — defeating the
        // drain. Reject it the same way the lease-ttl gate does.
        let mut a = base_args();
        a.no_auth = true;
        a.shutdown_grace_secs = 0;
        let err = ServeConfig::from_args(a).unwrap_err();
        assert!(err.to_string().contains("--shutdown-grace-secs"), "{err}");
    }

    #[test]
    fn nonzero_shutdown_grace_is_accepted() {
        let mut a = base_args();
        a.no_auth = true;
        a.shutdown_grace_secs = 5;
        let cfg = ServeConfig::from_args(a).unwrap();
        assert_eq!(cfg.shutdown_grace, Duration::from_secs(5));
    }

    #[test]
    fn zero_idempotency_retention_is_accepted_as_dedup_disabled_sentinel() {
        // `idempotency_retention_secs == 0` is an explicit "dedup disabled"
        // sentinel (every prior claim is immediately expired), NOT an error.
        let mut a = base_args();
        a.no_auth = true;
        a.idempotency_retention_secs = 0;
        let cfg = ServeConfig::from_args(a).unwrap();
        assert_eq!(cfg.idempotency_retention, Duration::ZERO);
    }

    #[test]
    fn cluster_requires_persistent_history() {
        let mut a = base_args();
        a.no_auth = true;
        a.cluster = true; // history defaults to memory
        let err = ServeConfig::from_args(a).unwrap_err();
        assert!(err.to_string().contains("--cluster requires"), "{err}");
    }

    #[test]
    fn cluster_with_sqlite_is_enabled() {
        let mut a = base_args();
        a.no_auth = true;
        a.cluster = true;
        a.history = Some("sqlite:runs.db".into());
        let cfg = ServeConfig::from_args(a).unwrap();
        assert!(cfg.cluster.enabled);
        assert_eq!(cfg.cluster.max_attempts, 3);
    }

    #[test]
    fn cluster_disabled_by_default() {
        let mut a = base_args();
        a.no_auth = true;
        assert!(!ServeConfig::from_args(a).unwrap().cluster.enabled);
    }
}