ironvault 8.0.1

Universal cross-platform XDG-compliant secure vault for AI model formats (Neural and Neurosymbolic)
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
//! Axum HTTP server for IronVault.
//!
//! Start with [`serve`] or build a router with [`create_router`].
//!
//! ## TLS / HTTPS
//!
//! Loopback binds serve plain HTTP; **any other address requires TLS** and the
//! server refuses to start without it. Set `tls_cert` and `tls_key` to PEM paths
//! and it terminates TLS itself via `rustls`.
//!
//! This is enforced rather than advised because `POST /api/v1/auth/token`
//! carries the vault passphrase — the value the encryption key is derived from.
//! Disclosing it is not comparable to leaking a session token: it never expires,
//! revocation cannot reach it, it decrypts any copy of the vault taken at any
//! time, and using it offline leaves no audit record.
//!
//! To terminate TLS at a reverse proxy (nginx, Caddy, an ALB), run the proxy on
//! this host and leave the server bound to `127.0.0.1`. A proxy on a different
//! host is a real network hop and needs TLS of its own, which is why there is no
//! flag to disable this check.

use axum::routing::{delete, get, post, put};
use axum::Router;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tower_http::cors::CorsLayer;
use tower_http::limit::RequestBodyLimitLayer;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;

use crate::config::VaultConfig;
use crate::error::{Result, VaultError};
use crate::vault::Vault;

use super::routes;
use super::ApiConfig;

/// Shared application state.
pub struct AppState {
    /// Thread-safe vault handle.
    pub vault: RwLock<Vault>,
    /// API configuration.
    pub config: ApiConfig,
    /// Per-IP rate limiter for auth endpoints.
    pub auth_rate_limiter: RateLimiter,
    /// Vault configuration, kept for the settings the federation endpoints
    /// consult on every request (accepted peer keys, sealing).
    pub vault_config: VaultConfig,
    /// Federation manifest generator; `None` when federation is disabled.
    pub federation: Option<crate::federation::FederationManager>,
}

/// Simple sliding-window rate limiter keyed by IP address.
pub struct RateLimiter {
    /// Map of IP → (attempt count, window start).
    state: std::sync::Mutex<HashMap<std::net::IpAddr, (u32, Instant)>>,
    /// Maximum attempts per window.
    max_attempts: u32,
    /// Window duration.
    window: Duration,
}

impl RateLimiter {
    /// Create a new rate limiter.
    pub fn new(max_attempts: u32, window: Duration) -> Self {
        Self {
            state: std::sync::Mutex::new(HashMap::new()),
            max_attempts,
            window,
        }
    }

    /// Check if the given IP is allowed. Returns `true` if under the limit.
    pub fn check(&self, ip: std::net::IpAddr) -> bool {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        let now = Instant::now();

        let entry = state.entry(ip).or_insert((0, now));

        // Reset window if expired
        if now.duration_since(entry.1) >= self.window {
            *entry = (0, now);
        }

        entry.0 += 1;
        entry.0 <= self.max_attempts
    }

    /// Prune expired entries to prevent unbounded memory growth.
    pub fn prune(&self) {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        let now = Instant::now();
        state.retain(|_, (_, start)| now.duration_since(*start) < self.window);
    }
}

/// Build the axum [`Router`] with all API routes.
pub fn create_router(state: Arc<AppState>) -> Router {
    // CORS: only permissive when explicitly configured; default is restrictive
    let cors = if state.config.cors_permissive {
        CorsLayer::permissive()
    } else {
        // Restrictive CORS: no cross-origin requests allowed by default.
        // Configure allowed_origins in ApiConfig for specific trusted domains.
        CorsLayer::new()
    };

    let api = Router::new()
        .route("/health", get(routes::health))
        .route("/auth/token", post(routes::auth_token))
        .route("/auth/logout", post(routes::auth_logout))
        .route("/models", get(routes::list_models))
        .route(
            "/models/:name",
            get(routes::get_model).post(routes::store_model),
        )
        .route(
            "/models/:name/card",
            get(routes::get_model_card).post(routes::create_model_card),
        )
        .route("/models/:name/versions", get(routes::list_versions))
        .route(
            "/models/:name/versions/:version",
            get(routes::get_version).delete(routes::delete_version),
        )
        .route("/models/:name/lineage/:version", get(routes::get_lineage))
        .route("/conversions", get(routes::list_conversions))
        .route("/convert", post(routes::convert))
        .route("/compliance", get(routes::compliance))
        .route("/rag/search", post(routes::rag_search))
        .route("/rag/documents", post(routes::rag_add_document))
        .route("/stats", get(routes::stats))
        .route("/audit", get(routes::audit_log))
        .route("/metrics", get(routes::metrics))
        .route("/events", get(routes::events))
        .route("/openapi.json", get(routes::openapi_json))
        // v1.4.0 endpoints
        .route(
            "/models/:name/tags",
            get(routes::get_tags)
                .post(routes::add_tags)
                .delete(routes::remove_tags),
        )
        .route("/search", post(routes::search_models))
        .route(
            "/acl",
            get(routes::acl_list)
                .post(routes::acl_grant)
                .delete(routes::acl_revoke),
        )
        .route(
            "/webhooks",
            get(routes::webhook_list).post(routes::webhook_add),
        )
        .route("/webhooks/:id", delete(routes::webhook_remove))
        .route("/models/:name/validate", post(routes::validate_model))
        .route("/gc", post(routes::garbage_collect))
        .route("/models/:name/policy", put(routes::policy_set))
        .route("/policies", get(routes::policy_list))
        .route(
            "/profiles",
            get(routes::profile_list).post(routes::profile_create),
        )
        .route("/profiles/:name/activate", post(routes::profile_activate))
        .route(
            "/lineage-graph",
            get(routes::lineage_graph_show).post(routes::lineage_graph_add),
        )
        .route("/plugins", get(routes::plugin_list))
        // v1.5.0 endpoints
        .route(
            "/quantization/profiles",
            get(routes::quant_profile_list).post(routes::quant_profile_set),
        )
        .route("/quantization/estimate", post(routes::quant_estimate))
        .route(
            "/evaluations",
            get(routes::eval_list).post(routes::eval_record),
        )
        .route("/evaluations/suites", get(routes::eval_suites))
        .route(
            "/backups/schedules",
            get(routes::backup_schedule_list).post(routes::backup_schedule_set),
        )
        .route("/backups/history", get(routes::backup_history))
        .route(
            "/vaults",
            get(routes::vault_list).post(routes::vault_register),
        )
        .route("/vaults/:name/activate", post(routes::vault_activate))
        // 5.1.0 — paths the OpenAPI spec documented from 1.x on but that had
        // no handler, so generated clients called them and got 404s.
        .route("/introspect", get(routes::introspect))
        .route("/telemetry/status", get(routes::telemetry_status))
        .route("/license-scan", post(routes::license_scan))
        .route("/models/diff", post(routes::diff_models))
        .route("/models/pull", post(routes::pull_model))
        .route("/models/:name/sign", post(routes::sign_model))
        .route("/models/:name/verify", post(routes::verify_model))
        .route("/models/:name/scan", post(routes::scan_model))
        .route("/models/:name/register", post(routes::register_model))
        .route("/models/:name/card/validate", post(routes::card_validate))
        .route("/models/:name/card/generate", post(routes::card_generate))
        .route(
            "/models/:name/benchmarks",
            get(routes::benchmarks_list).post(routes::benchmarks_record),
        )
        .route("/vault/export", post(routes::vault_export))
        .route("/vault/import", post(routes::vault_import))
        .with_state(state.clone());

    // Registered only when federation is enabled, so a default server does not
    // expose model-serving paths at all — an unauthenticated 404 rather than a
    // 401 that confirms the endpoint exists.
    let federation_routes = if state.vault_config.federation.enabled {
        Router::new()
            .route(
                "/federation/manifest",
                get(super::federation_routes::manifest),
            )
            .route(
                "/federation/models/:name/versions/:checkpoint_id",
                get(super::federation_routes::get_version)
                    .put(super::federation_routes::put_version),
            )
            .with_state(state.clone())
    } else {
        Router::new()
    };

    let api = api.merge(federation_routes);

    let dashboard = if state.config.enable_dashboard {
        Router::new().route("/", get(routes::dashboard_index))
    } else {
        Router::new()
    };

    #[cfg(feature = "graphql")]
    let graphql_routes = {
        use super::graphql;
        let schema = graphql::build_schema(state.clone());
        Router::new()
            .route(
                "/graphql",
                get(graphql::graphql_playground).post(graphql::graphql_handler),
            )
            .with_state(schema)
    };
    #[cfg(not(feature = "graphql"))]
    let graphql_routes = Router::new();

    dashboard
        .merge(graphql_routes)
        .nest("/api/v1", api)
        .layer(axum::middleware::from_fn(track_request))
        .layer(cors)
        .layer(RequestBodyLimitLayer::new(state.config.max_body_size))
        .layer(TimeoutLayer::with_status_code(
            axum::http::StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(300),
        ))
        .layer(TraceLayer::new_for_http())
}

/// Record one API call: route template, method, status, and duration.
///
/// The endpoint reported is [`MatchedPath`] — the *template* axum matched,
/// such as `/api/v1/models/{name}` — and never `uri().path()`, which is the
/// resolved path and therefore contains the model name. That distinction is
/// the whole reason this is a middleware rather than something sprinkled
/// through the handlers: `MatchedPath` is only available here, and it is a
/// literal from the router table, so no request data can reach the event.
///
/// A request that matches no route (a 404) has no `MatchedPath`. It is
/// reported as the constant `"<no match>"` rather than the path the client
/// asked for, which is attacker-controlled and frequently a probe string.
async fn track_request(
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    use axum::extract::MatchedPath;

    let route = req
        .extensions()
        .get::<MatchedPath>()
        .map_or("<no match>", |m| m.as_str())
        .to_string();
    let method = req.method().as_str().to_string();

    let started = Instant::now();
    let response = next.run(req).await;

    crate::telemetry::track_api_call(
        &route,
        &method,
        response.status().as_u16(),
        started.elapsed(),
    );

    response
}

/// Minimum HS256 signing key length.
///
/// RFC 7518 §3.2: an HMAC key "of the same size as the hash output (for
/// instance, 256 bits for HS256) or larger MUST be used".
pub const MIN_JWT_SECRET_BYTES: usize = 32;

/// Reject a JWT signing secret too weak for HS256.
///
/// Tokens are signed with HS256, so anyone holding a single issued token can
/// brute-force a short secret offline and then mint tokens for any subject.
/// Only emptiness was checked before, which accepted `--jwt-secret hunter2`.
pub fn validate_jwt_secret(secret: &str) -> Result<()> {
    if secret.is_empty() {
        return Err(VaultError::ConfigError(
            "JWT secret must not be empty. Set --jwt-secret or IRONVAULT_JWT_SECRET.".into(),
        ));
    }

    if secret.len() < MIN_JWT_SECRET_BYTES {
        return Err(VaultError::ConfigError(format!(
            "JWT secret is {} bytes; HS256 requires at least {MIN_JWT_SECRET_BYTES} \
             (RFC 7518 §3.2). A shorter secret can be recovered offline from a \
             single issued token. Generate one with: openssl rand -base64 48",
            secret.len(),
        )));
    }

    Ok(())
}

/// Start the API server.
///
/// This is a blocking call that runs until the process is terminated.
pub async fn serve(vault_config: VaultConfig, api_config: ApiConfig) -> Result<()> {
    validate_jwt_secret(&api_config.jwt_secret)?;

    // Load persisted revocations before the listener binds, so no request can
    // be served against an empty list. A corrupt or unreadable store aborts
    // startup rather than starting with revocations silently dropped.
    if let Some(path) = &api_config.revocation_store {
        super::auth::configure_revocation_store(path).map_err(VaultError::IoError)?;
    } else {
        eprintln!(
            "warning: no revocation_store configured — revoked tokens will be \
             honoured only until this process restarts"
        );
    }

    // Build the federation manager before the vault takes ownership of the
    // config. Resolving peer keys here means a bad KMS reference aborts
    // startup instead of failing the first sync at 3am.
    let federation = if vault_config.federation.enabled {
        let manager_config =
            crate::federation_transport::to_manager_config(&vault_config.federation)?;
        let state_dir = vault_config.dirs.data_dir.join("federation");
        let peers = manager_config.peers.len();
        let manager = crate::federation::FederationManager::new(manager_config, state_dir)?;
        eprintln!(
            "federation: enabled, serving /api/v1/federation/* to {peers} configured peer(s)"
        );
        if !vault_config.federation.seal_transfers {
            eprintln!(
                "warning: federation.seal_transfers is off — models will be sent to peers \
                 unencrypted, protected only by the transport"
            );
        }
        Some(manager)
    } else {
        None
    };

    let state_config = vault_config.clone();
    let mut vault = Vault::new(Some(vault_config))?;

    // Unlock at startup when federation is on and a passphrase is available.
    //
    // Peers authenticate with the shared federation key and never hold the
    // vault passphrase, so without this every peer request 500s until a human
    // POSTs to /auth/token. Scoped to federation deliberately: a plain `iv
    // serve` keeps the existing behaviour of starting locked.
    if state_config.federation.enabled {
        match crate::federation_transport::startup_passphrase()? {
            Some(passphrase) => {
                vault.unlock(passphrase.as_bytes().to_vec())?;
                eprintln!("federation: vault unlocked at startup to serve peer requests");
            }
            None => eprintln!(
                "warning: federation is enabled but ${} is unset — the vault starts \
                 locked and peer requests will fail until it is unlocked via /auth/token",
                crate::federation_transport::VAULT_PASSPHRASE_ENV
            ),
        }
    }
    let state = Arc::new(AppState {
        vault: RwLock::new(vault),
        config: api_config.clone(),
        auth_rate_limiter: RateLimiter::new(5, Duration::from_secs(60)),
        vault_config: state_config,
        federation,
    });

    let router = create_router(state.clone()).into_make_service_with_connect_info::<SocketAddr>();

    // Spawn periodic cleanup of expired rate-limiter entries
    let limiter = state.clone();
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(Duration::from_secs(300)).await;
            limiter.auth_rate_limiter.prune();
        }
    });

    let addr: SocketAddr = format!("{}:{}", api_config.host, api_config.port)
        .parse()
        .map_err(|e| VaultError::ConfigError(format!("Invalid bind address: {e}")))?;

    // Resolved before the banner, not after: printing "Listening on
    // http://0.0.0.0:8080" and *then* refusing to serve tells the operator the
    // server started when it did not.
    let tls = resolve_tls(
        &addr,
        api_config.tls_cert.as_deref(),
        api_config.tls_key.as_deref(),
    )?;

    let scheme = if tls.is_some() { "https" } else { "http" };
    println!("IronVault API v{}", env!("CARGO_PKG_VERSION"));
    println!("  Listening on {scheme}://{addr}");
    println!("  Dashboard:   {scheme}://{addr}/");
    println!("  OpenAPI:     {scheme}://{addr}/api/v1/openapi.json");
    println!();

    if let Some((cert, key)) = tls {
        let config = axum_server::tls_rustls::RustlsConfig::from_pem_file(&cert, &key)
            .await
            .map_err(|e| {
                VaultError::ConfigError(format!(
                    "Failed to load TLS certificate {} / key {}: {e}",
                    cert.display(),
                    key.display()
                ))
            })?;
        axum_server::bind_rustls(addr, config)
            .serve(router)
            .await
            .map_err(|e| VaultError::IoError(std::io::Error::other(e.to_string())))?;
    } else {
        let listener = tokio::net::TcpListener::bind(addr)
            .await
            .map_err(VaultError::IoError)?;
        axum::serve(listener, router)
            .await
            .map_err(|e| VaultError::IoError(std::io::Error::other(e.to_string())))?;
    }

    Ok(())
}

/// Decide whether this bind runs over TLS, refusing the combination that would
/// put the vault passphrase on a wire in the clear.
///
/// `POST /api/v1/auth/token` takes the vault passphrase in its body. That is the
/// value the encryption key is derived from, so disclosing it is not like
/// leaking a session token: it does not expire, revocation cannot reach it, it
/// decrypts any copy of the vault taken at any time, and using it offline
/// produces no audit record. One packet capture on a shared segment during a
/// single unlock is a permanent, silent compromise.
///
/// Loopback is exempt because those packets never reach a network. Everything
/// else requires a certificate and key. There is deliberately no bypass flag: a
/// "trust me, this network is fine" switch is precisely what gets set during
/// debugging and never unset. Operators terminating TLS at a reverse proxy
/// should run the proxy on this host and leave the server on loopback — a proxy
/// on another host is a real network hop and needs real TLS.
fn resolve_tls(
    addr: &SocketAddr,
    cert: Option<&std::path::Path>,
    key: Option<&std::path::Path>,
) -> Result<Option<(std::path::PathBuf, std::path::PathBuf)>> {
    match (cert, key) {
        (Some(c), Some(k)) => Ok(Some((c.to_path_buf(), k.to_path_buf()))),
        (None, None) if addr.ip().is_loopback() => Ok(None),
        (None, None) => Err(VaultError::ConfigError(format!(
            "Refusing to serve {addr} without TLS.\n\n\
             `POST /api/v1/auth/token` carries the vault passphrase, which derives the \
             encryption key. Over plain HTTP anyone who can observe the traffic can \
             decrypt the vault permanently, and revoking a token does not help.\n\n\
             Either:\n  \
             - set `tls_cert` and `tls_key` (PEM paths) to serve HTTPS directly, or\n  \
             - bind 127.0.0.1 and terminate TLS at a reverse proxy on this host."
        ))),
        (Some(_), None) => Err(VaultError::ConfigError(
            "`tls_cert` is set but `tls_key` is not; TLS needs both".into(),
        )),
        (None, Some(_)) => Err(VaultError::ConfigError(
            "`tls_key` is set but `tls_cert` is not; TLS needs both".into(),
        )),
    }
}

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

    #[test]
    fn test_rate_limiter_allows_under_limit() {
        let limiter = RateLimiter::new(3, Duration::from_secs(60));
        let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap();
        assert!(limiter.check(ip));
        assert!(limiter.check(ip));
        assert!(limiter.check(ip));
    }

    #[test]
    fn test_rate_limiter_blocks_over_limit() {
        let limiter = RateLimiter::new(2, Duration::from_secs(60));
        let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap();
        assert!(limiter.check(ip));
        assert!(limiter.check(ip));
        assert!(!limiter.check(ip)); // 3rd attempt blocked
    }

    #[test]
    fn test_rate_limiter_separate_ips() {
        let limiter = RateLimiter::new(1, Duration::from_secs(60));
        let ip1: std::net::IpAddr = "10.0.0.1".parse().unwrap();
        let ip2: std::net::IpAddr = "10.0.0.2".parse().unwrap();
        assert!(limiter.check(ip1));
        assert!(limiter.check(ip2));
        assert!(!limiter.check(ip1)); // ip1 blocked
        assert!(!limiter.check(ip2)); // ip2 blocked
    }

    #[test]
    fn test_rate_limiter_window_reset() {
        let limiter = RateLimiter::new(1, Duration::from_millis(1));
        let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap();
        assert!(limiter.check(ip));
        assert!(!limiter.check(ip));
        std::thread::sleep(Duration::from_millis(5));
        assert!(limiter.check(ip)); // window expired, reset
    }

    #[test]
    fn test_rate_limiter_prune_expired() {
        let limiter = RateLimiter::new(5, Duration::from_millis(1));
        let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap();
        limiter.check(ip);
        std::thread::sleep(Duration::from_millis(5));
        limiter.prune();
        // State should be empty after prune
        let state = limiter.state.lock().unwrap();
        assert!(state.is_empty());
    }

    #[test]
    fn test_rate_limiter_prune_keeps_active() {
        let limiter = RateLimiter::new(5, Duration::from_secs(60));
        let ip: std::net::IpAddr = "127.0.0.1".parse().unwrap();
        limiter.check(ip);
        limiter.prune();
        let state = limiter.state.lock().unwrap();
        assert_eq!(state.len(), 1); // still active
    }
    /// A short JWT secret must be refused at startup.
    ///
    /// Tokens are HS256; RFC 7518 §3.2 requires a key at least as large as
    /// the hash output. Only emptiness used to be checked, so
    /// `--jwt-secret hunter2` started a server whose secret could be
    /// recovered offline from one issued token.
    #[test]
    fn test_weak_jwt_secrets_are_rejected() {
        for weak in [
            "",
            "hunter2",
            "secret",
            "0123456789abcdef0123456789abcde", // 31 bytes — one short
        ] {
            let err = validate_jwt_secret(weak).expect_err(&format!("{weak:?} must be refused"));
            assert!(
                matches!(err, VaultError::ConfigError(_)),
                "expected ConfigError for {weak:?}, got {err:?}"
            );
        }
    }

    #[test]
    fn test_sufficient_jwt_secret_is_accepted() {
        let exact = "0123456789abcdef0123456789abcdef";
        assert_eq!(exact.len(), MIN_JWT_SECRET_BYTES);
        assert!(validate_jwt_secret(exact).is_ok());

        let longer = "0123456789abcdef0123456789abcdef0123456789";
        assert!(validate_jwt_secret(longer).is_ok());
    }

    /// The message must tell the operator what to do about it.
    #[test]
    fn test_weak_secret_error_is_actionable() {
        let err = validate_jwt_secret("short").unwrap_err().to_string();
        assert!(err.contains("RFC 7518"), "got: {err}");
        assert!(err.contains("openssl rand"), "got: {err}");
    }

    // ── TLS enforcement ──────────────────────────────────────────────────
    //
    // The rule these pin: loopback may serve plain HTTP, anything else must
    // present a certificate and key. `POST /auth/token` carries the vault
    // passphrase, so a cleartext bind on a real interface discloses the value
    // the encryption key is derived from.

    fn sock(s: &str) -> SocketAddr {
        s.parse().expect("test address parses")
    }

    #[test]
    fn loopback_may_serve_plain_http() {
        for addr in ["127.0.0.1:8080", "[::1]:8080", "127.0.0.5:9999"] {
            let got = resolve_tls(&sock(addr), None, None);
            assert!(
                matches!(got, Ok(None)),
                "{addr} should be allowed without TLS"
            );
        }
    }

    #[test]
    fn non_loopback_without_tls_is_refused() {
        for addr in [
            "0.0.0.0:8080",
            "192.168.1.10:8080",
            "10.0.0.4:443",
            "[::]:8080",
        ] {
            let err = resolve_tls(&sock(addr), None, None)
                .expect_err("{addr} must be refused without TLS")
                .to_string();
            assert!(err.contains("Refusing to serve"), "got: {err}");
            // The message has to say *why*, or an operator will just look for a
            // flag to silence it.
            assert!(err.contains("passphrase"), "got: {err}");
            assert!(err.contains("tls_cert"), "got: {err}");
        }
    }

    #[test]
    fn non_loopback_with_tls_is_allowed() {
        let got = resolve_tls(
            &sock("0.0.0.0:8443"),
            Some(std::path::Path::new("/etc/ssl/cert.pem")),
            Some(std::path::Path::new("/etc/ssl/key.pem")),
        );
        assert!(matches!(got, Ok(Some(_))), "TLS bind should be allowed");
    }

    #[test]
    fn half_configured_tls_is_refused_even_on_loopback() {
        let cert = Some(std::path::Path::new("/etc/ssl/cert.pem"));
        let key = Some(std::path::Path::new("/etc/ssl/key.pem"));
        // Silently downgrading to plain HTTP because one path was missing is
        // exactly the failure this whole change exists to prevent.
        assert!(resolve_tls(&sock("127.0.0.1:8080"), cert, None).is_err());
        assert!(resolve_tls(&sock("127.0.0.1:8080"), None, key).is_err());
    }
}