hammerwork-web 2.1.0

Web-based admin dashboard for Hammerwork job queues with real-time monitoring, webhook management, event streaming, and comprehensive job queue administration
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
//! Main binary entry point for the Hammerwork Web Dashboard.

use anyhow::{Context, Result, anyhow};
use clap::{Arg, ArgMatches, Command};
use hammerwork_web::{DashboardConfig, WebDashboard};
use std::path::PathBuf;
use tracing::{error, info, warn};
use tracing_subscriber::EnvFilter;

/// The command line of `hammerwork-web`.
///
/// `--bind`, `--port` and `--static-dir` have no clap defaults on purpose: a default would be
/// indistinguishable from an explicit value and would override the configuration file. The
/// defaults come from [`DashboardConfig`].
fn cli() -> Command {
    Command::new("hammerwork-web")
        .version(env!("CARGO_PKG_VERSION"))
        .author("CodingAnarchy <noreply@codinganarchy.com>")
        .about("Web-based admin dashboard for Hammerwork job queues")
        .arg(
            Arg::new("config")
                .short('c')
                .long("config")
                .value_name("FILE")
                .help("Path to configuration file"),
        )
        .arg(
            Arg::new("database-url")
                .short('d')
                .long("database-url")
                .value_name("URL")
                .help("Database connection URL (default: $DATABASE_URL)"),
        )
        .arg(
            Arg::new("bind")
                .short('b')
                .long("bind")
                .value_name("ADDRESS")
                .help("Server bind address [default: 127.0.0.1]"),
        )
        .arg(
            Arg::new("port")
                .short('p')
                .long("port")
                .value_name("PORT")
                .value_parser(clap::value_parser!(u16))
                .help("Server port [default: 8080]"),
        )
        .arg(
            Arg::new("static-dir")
                .long("static-dir")
                .value_name("DIR")
                .help("Directory containing static assets [default: ./assets]"),
        )
        .arg(
            Arg::new("cors")
                .long("cors")
                .help("Enable CORS for the origins given with --allowed-origin")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("allowed-origin")
                .long("allowed-origin")
                .value_name("ORIGIN")
                .action(clap::ArgAction::Append)
                .help(
                    "Another origin (scheme://host[:port]) whose pages may change data and \
                     open WebSockets, and with --cors read the API; repeatable",
                ),
        )
        .arg(
            Arg::new("auth")
                .long("auth")
                .help("Enable basic authentication")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("username")
                .long("username")
                .value_name("USER")
                .help("Username for authentication (requires --auth) [default: admin]"),
        )
        .arg(
            Arg::new("password")
                .long("password")
                .value_name("PASS")
                .help("Password for authentication (requires --auth)"),
        )
        .arg(
            Arg::new("password-file")
                .long("password-file")
                .value_name("FILE")
                .help("File containing the bcrypt hash of the password (requires --auth)"),
        )
        .arg(
            Arg::new("no-auth")
                .long("no-auth")
                .help("Run without authentication: anyone who can reach the dashboard can manage jobs")
                .action(clap::ArgAction::SetTrue)
                .conflicts_with("auth"),
        )
}

/// The configuration the server runs with, and notes for the operator.
#[derive(Debug)]
struct Resolved {
    config: DashboardConfig,
    /// Things worth a warning in the log.
    warnings: Vec<String>,
}

/// Combine the configuration file (if any), the environment and the command line.
///
/// Precedence, highest first: command-line arguments given explicitly, the configuration file,
/// then built-in defaults. `DATABASE_URL` stands in for the database URL only when neither
/// `--database-url` nor `--config` is used.
fn resolve_config(matches: &ArgMatches, env_database_url: Option<&str>) -> Result<Resolved> {
    let mut warnings = Vec::new();

    let mut config = if let Some(config_file) = matches.get_one::<String>("config") {
        info!("Loading configuration from: {}", config_file);
        DashboardConfig::from_file(config_file)
            .with_context(|| format!("Cannot load configuration file {config_file}"))?
    } else {
        let mut config = DashboardConfig::new();
        if let Some(url) = env_database_url.filter(|u| !u.is_empty()) {
            config.database_url = url.to_string();
        }
        config
    };

    if let Some(db_url) = matches.get_one::<String>("database-url") {
        config.database_url = db_url.clone();
    }
    if config.database_url.is_empty() {
        return Err(anyhow!(
            "Database URL is required. Use --database-url or set DATABASE_URL environment variable."
        ));
    }

    if let Some(bind) = matches.get_one::<String>("bind") {
        config.bind_address = bind.clone();
    }
    if let Some(port) = matches.get_one::<u16>("port") {
        config.port = *port;
    }
    if let Some(static_dir) = matches.get_one::<String>("static-dir") {
        config.static_dir = PathBuf::from(static_dir);
    }
    if matches.get_flag("cors") {
        config.enable_cors = true;
    }
    if let Some(origins) = matches.get_many::<String>("allowed-origin") {
        config.allowed_origins.extend(origins.cloned());
    }

    // Handle authentication
    if matches.get_flag("auth") {
        config.auth.enabled = true;

        if let Some(username) = matches.get_one::<String>("username") {
            config.auth.username = username.clone();
        }

        // Handle password or password file
        let password_hash = if let Some(password_file) = matches.get_one::<String>("password-file")
        {
            std::fs::read_to_string(password_file)
                .with_context(|| format!("Cannot read password file {password_file}"))?
                .trim()
                .to_string()
        } else if let Some(password) = matches.get_one::<String>("password") {
            hash_password(password)?
        } else if !config.auth.password_hash.is_empty() {
            // The configuration file already holds a hash.
            config.auth.password_hash.clone()
        } else {
            return Err(anyhow!(
                "Authentication enabled but no password provided. Use --password or --password-file"
            ));
        };
        if password_hash.is_empty() {
            return Err(anyhow!("The password hash must not be empty"));
        }

        config.auth.password_hash = password_hash;
    } else if matches.get_one::<String>("username").is_some()
        || matches.get_one::<String>("password").is_some()
        || matches.get_one::<String>("password-file").is_some()
    {
        warnings.push(
            "--username, --password and --password-file have no effect without --auth".into(),
        );
    }

    if matches.get_flag("no-auth") {
        config.auth.enabled = false;
    }

    // The built-in default enables authentication but cannot know a password. Fail closed:
    // running open must be an explicit choice.
    if config.auth.enabled && config.auth.password_hash.is_empty() {
        return Err(anyhow!(
            "Authentication is enabled but no password is configured. Use --auth with \
             --password or --password-file, set auth.password_hash in the config file, or pass \
             --no-auth to run the dashboard without authentication"
        ));
    }
    if !config.auth.enabled {
        warnings.push(
            "Authentication is disabled: anyone who can reach the dashboard can manage jobs".into(),
        );
    }

    config.validate()?;
    Ok(Resolved { config, warnings })
}

/// The stored form of a command-line password.
fn hash_password(password: &str) -> Result<String> {
    #[cfg(feature = "auth")]
    {
        Ok(bcrypt::hash(password, bcrypt::DEFAULT_COST)?)
    }
    #[cfg(not(feature = "auth"))]
    {
        let _ = password;
        Err(anyhow!(
            "Authentication feature not enabled. Rebuild with --features auth"
        ))
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    // Initialize logging
    tracing_subscriber::fmt()
        .with_env_filter(
            EnvFilter::from_default_env().add_directive("hammerwork_web=info".parse()?),
        )
        .init();

    let matches = cli().get_matches();

    let env_database_url = std::env::var("DATABASE_URL").ok();
    let Resolved { config, warnings } = match resolve_config(&matches, env_database_url.as_deref())
    {
        Ok(resolved) => resolved,
        Err(e) => {
            error!("{:#}", e);
            std::process::exit(1);
        }
    };
    for warning in &warnings {
        warn!("{}", warning);
    }

    info!("Starting Hammerwork Web Dashboard");
    info!("Server: http://{}", config.bind_addr());
    info!("Database: {}", mask_database_url(&config.database_url));
    info!("Static assets: {}", config.static_dir.display());

    if config.auth.enabled {
        info!("Authentication: enabled (user: {})", config.auth.username);
    } else {
        info!("Authentication: disabled");
    }

    // Create and start the web dashboard
    let dashboard = WebDashboard::new(config).await?;

    // Handle graceful shutdown
    let shutdown_signal = async {
        tokio::signal::ctrl_c()
            .await
            .expect("Failed to install CTRL+C signal handler");
        info!("Shutdown signal received");
    };

    tokio::select! {
        result = dashboard.start() => {
            if let Err(e) = result {
                error!("Dashboard error: {}", e);
                std::process::exit(1);
            }
        }
        _ = shutdown_signal => {
            info!("Shutting down gracefully...");
        }
    }

    Ok(())
}

/// Mask sensitive parts of database URL for logging
fn mask_database_url(url: &str) -> String {
    if let Some(at_pos) = url.rfind('@') {
        if let Some(scheme_pos) = url.find("://") {
            let scheme = &url[..scheme_pos + 3];
            let host_and_path = &url[at_pos..];
            format!("{}***{}", scheme, host_and_path)
        } else {
            "***".to_string()
        }
    } else {
        url.to_string()
    }
}

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

    fn resolve(args: &[&str], env: Option<&str>) -> Result<Resolved> {
        let mut argv = vec!["hammerwork-web"];
        argv.extend_from_slice(args);
        let matches = cli()
            .try_get_matches_from(argv)
            .map_err(|e| anyhow!("{e}"))?;
        resolve_config(&matches, env)
    }

    #[test]
    fn test_mask_database_url() {
        assert_eq!(
            mask_database_url("postgresql://user:pass@localhost/db"),
            "postgresql://***@localhost/db"
        );
        assert_eq!(
            mask_database_url("mysql://root:secret@127.0.0.1:3306/hammerwork"),
            "mysql://***@127.0.0.1:3306/hammerwork"
        );
        assert_eq!(
            mask_database_url("postgresql://localhost/db"),
            "postgresql://localhost/db"
        );
        assert_eq!(mask_database_url("weird@thing"), "***");
    }

    #[test]
    fn the_command_line_definition_is_consistent() {
        cli().debug_assert();
    }

    #[test]
    fn defaults_come_from_the_dashboard_config() {
        let resolved = resolve(&["--no-auth"], None).unwrap();
        let defaults = DashboardConfig::new();
        assert_eq!(resolved.config.bind_address, defaults.bind_address);
        assert_eq!(resolved.config.port, defaults.port);
        assert_eq!(resolved.config.static_dir, defaults.static_dir);
        assert_eq!(resolved.config.database_url, defaults.database_url);
        assert!(!resolved.config.enable_cors);
    }

    #[test]
    fn explicit_arguments_override_the_defaults() {
        let resolved = resolve(
            &[
                "--no-auth",
                "-d",
                "mysql://root@db/app",
                "-b",
                "0.0.0.0",
                "-p",
                "9191",
                "--static-dir",
                "/srv/www",
                "--cors",
                "--allowed-origin",
                "https://ops.example.com",
                "--allowed-origin",
                "http://localhost:3000",
            ],
            None,
        )
        .unwrap();
        let config = resolved.config;
        assert_eq!(config.database_url, "mysql://root@db/app");
        assert_eq!(config.bind_addr(), "0.0.0.0:9191");
        assert_eq!(config.static_dir, PathBuf::from("/srv/www"));
        assert!(config.enable_cors);
        assert_eq!(
            config.allowed_origins,
            ["https://ops.example.com", "http://localhost:3000"]
        );
    }

    #[test]
    fn cors_needs_explicit_origins() {
        // M16: CORS is never granted to every origin.
        let err = resolve(&["--no-auth", "--cors"], None).unwrap_err();
        assert!(err.to_string().contains("allowed_origins"), "{err}");
        let err = resolve(&["--no-auth", "--allowed-origin", "*"], None).unwrap_err();
        assert!(err.to_string().contains("invalid origin"), "{err}");
        // An allowed origin without --cors only relaxes the cross-origin write check.
        let resolved = resolve(
            &["--no-auth", "--allowed-origin", "https://a.example"],
            None,
        )
        .unwrap();
        assert!(!resolved.config.enable_cors);
        assert_eq!(resolved.config.allowed_origins, ["https://a.example"]);
    }

    #[test]
    fn invalid_ports_are_rejected() {
        for port in ["abc", "70000", "-1"] {
            assert!(resolve(&["--no-auth", "-p", port], None).is_err(), "{port}");
        }
    }

    #[test]
    fn the_environment_supplies_the_database_url_unless_a_flag_or_file_does() {
        let from_env = resolve(&["--no-auth"], Some("postgres://env/db")).unwrap();
        assert_eq!(from_env.config.database_url, "postgres://env/db");

        let flag_wins = resolve(
            &["--no-auth", "-d", "mysql://flag/db"],
            Some("postgres://env/db"),
        )
        .unwrap();
        assert_eq!(flag_wins.config.database_url, "mysql://flag/db");

        // An empty variable is as good as unset.
        let empty = resolve(&["--no-auth"], Some("")).unwrap();
        assert_eq!(
            empty.config.database_url,
            DashboardConfig::new().database_url
        );
    }

    fn write_config(dir: &tempfile::TempDir, content: &str) -> String {
        let path = dir.path().join("dashboard.toml");
        std::fs::write(&path, content).unwrap();
        path.to_str().unwrap().to_string()
    }

    #[test]
    fn the_config_file_is_not_overridden_by_unset_arguments() {
        let dir = tempfile::tempdir().unwrap();
        let mut file_config = DashboardConfig::new()
            .with_bind_address("10.1.2.3", 9999)
            .with_database_url("mysql://file/db")
            .with_static_dir(PathBuf::from("/from/file"))
            .with_cors(true)
            .with_allowed_origin("https://ops.example.com");
        file_config.auth.enabled = false;
        let path = dir.path().join("dashboard.toml");
        file_config.save_to_file(path.to_str().unwrap()).unwrap();
        let path = path.to_str().unwrap();

        // The environment does not replace what the file says.
        let resolved = resolve(&["-c", path], Some("postgres://env/db")).unwrap();
        let config = resolved.config;
        assert_eq!(config.bind_addr(), "10.1.2.3:9999");
        assert_eq!(config.database_url, "mysql://file/db");
        assert_eq!(config.static_dir, PathBuf::from("/from/file"));
        assert!(config.enable_cors, "the file's CORS setting survives");

        // Explicit arguments win over the file.
        let resolved = resolve(&["-c", path, "-p", "1234", "-b", "127.0.0.9"], None).unwrap();
        assert_eq!(resolved.config.bind_addr(), "127.0.0.9:1234");
        assert_eq!(resolved.config.database_url, "mysql://file/db");
    }

    #[test]
    fn bad_config_files_are_reported() {
        let dir = tempfile::tempdir().unwrap();
        let err = resolve(&["-c", "/no/such/file.toml"], None).unwrap_err();
        assert!(format!("{err:#}").contains("/no/such/file.toml"), "{err:#}");

        let broken = write_config(&dir, "port = \"not a number\"");
        assert!(resolve(&["-c", &broken], None).is_err());

        let empty_url = write_config(
            &dir,
            &toml::to_string(&DashboardConfig {
                database_url: String::new(),
                auth: hammerwork_web::AuthConfig {
                    enabled: false,
                    ..Default::default()
                },
                ..DashboardConfig::new()
            })
            .unwrap(),
        );
        let err = resolve(&["-c", &empty_url], None).unwrap_err();
        assert!(
            err.to_string().contains("Database URL is required"),
            "{err}"
        );
    }

    #[cfg(feature = "auth")]
    #[test]
    fn authentication_needs_a_password_or_an_explicit_opt_out() {
        // By default there is no password: refuse to start rather than run open.
        let err = resolve(&[], None).unwrap_err();
        assert!(err.to_string().contains("--no-auth"), "{err}");

        // --no-auth runs open, with a warning.
        let open = resolve(&["--no-auth"], None).unwrap();
        assert!(!open.config.auth.enabled);
        assert!(
            open.warnings
                .iter()
                .any(|w| w.contains("Authentication is disabled"))
        );
        let err = resolve(&["--no-auth", "--auth"], None).unwrap_err();
        assert!(err.to_string().contains("cannot be used with"), "{err}");

        // --auth without any password is an error.
        let err = resolve(&["--auth"], None).unwrap_err();
        assert!(err.to_string().contains("no password provided"), "{err}");

        // A password file holds the hash.
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("hash.txt");
        std::fs::write(&file, "  $2b$12$abcdefghijklmnopqrstuv  \n").unwrap();
        let resolved = resolve(
            &[
                "--auth",
                "--username",
                "ops",
                "--password-file",
                file.to_str().unwrap(),
            ],
            None,
        )
        .unwrap();
        assert!(resolved.config.auth.enabled);
        assert_eq!(resolved.config.auth.username, "ops");
        assert_eq!(
            resolved.config.auth.password_hash,
            "$2b$12$abcdefghijklmnopqrstuv"
        );
        assert!(resolved.warnings.is_empty());

        let err = resolve(&["--auth", "--password-file", "/no/such/hash"], None).unwrap_err();
        assert!(format!("{err:#}").contains("/no/such/hash"));
        let blank = dir.path().join("blank.txt");
        std::fs::write(&blank, "\n").unwrap();
        let err = resolve(
            &["--auth", "--password-file", blank.to_str().unwrap()],
            None,
        )
        .unwrap_err();
        assert!(err.to_string().contains("must not be empty"), "{err}");

        // Credentials without --auth are ignored, and the user is told.
        let ignored = resolve(&["--no-auth", "--username", "x", "--password", "y"], None).unwrap();
        assert!(!ignored.config.auth.enabled);
        assert!(
            ignored
                .warnings
                .iter()
                .any(|w| w.contains("no effect without --auth"))
        );
    }

    #[cfg(feature = "auth")]
    #[test]
    fn a_hash_in_the_config_file_is_used_by_auth() {
        let dir = tempfile::tempdir().unwrap();
        let mut file_config = DashboardConfig::new();
        file_config.auth.enabled = true;
        file_config.auth.password_hash = "$2b$12$fromfile".to_string();
        let path = dir.path().join("dashboard.toml");
        file_config.save_to_file(path.to_str().unwrap()).unwrap();
        let path = path.to_str().unwrap();

        // Enabled in the file with a hash: stays enabled without --auth.
        let resolved = resolve(&["-c", path], None).unwrap();
        assert!(resolved.config.auth.enabled);
        assert_eq!(resolved.config.auth.password_hash, "$2b$12$fromfile");
        // And --auth reuses it instead of demanding another password.
        let resolved = resolve(&["-c", path, "--auth"], None).unwrap();
        assert_eq!(resolved.config.auth.password_hash, "$2b$12$fromfile");
    }

    #[cfg(feature = "auth")]
    #[test]
    fn a_command_line_password_is_stored_as_a_bcrypt_hash() {
        let resolved = resolve(&["--auth", "--password", "hunter2"], None).unwrap();
        let hash = &resolved.config.auth.password_hash;
        assert!(hash.starts_with("$2"));
        assert!(bcrypt::verify("hunter2", hash).unwrap());
    }

    /// H5: without bcrypt a stored hash cannot be verified, so authentication refuses to start
    /// instead of comparing the hash to passwords as text.
    #[cfg(not(feature = "auth"))]
    #[test]
    fn authentication_needs_the_auth_feature() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("hash.txt");
        std::fs::write(&file, "$2b$12$abcdefghijklmnopqrstuv").unwrap();
        let err =
            resolve(&["--auth", "--password-file", file.to_str().unwrap()], None).unwrap_err();
        assert!(err.to_string().contains("`auth` feature"), "{err}");
        assert!(resolve(&["--no-auth"], None).is_ok());
    }

    #[cfg(not(feature = "auth"))]
    #[test]
    fn a_command_line_password_needs_the_auth_feature() {
        let err = resolve(&["--auth", "--password", "hunter2"], None).unwrap_err();
        assert!(err.to_string().contains("--features auth"), "{err}");
    }
}