apexe 0.6.0

Outside-In CLI-to-Agent Bridge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Transport authentication for the HTTP-family MCP transports.
//!
//! apexe wraps arbitrary local binaries. On a non-loopback bind that makes an
//! unauthenticated server not "an API without auth" but a remote-execution
//! entry point for every executable on the host, so the default here is *on*
//! rather than off, and the dangerous configuration has to name itself.
//!
//! The three transports have genuinely different trust boundaries, so they get
//! different defaults — see [`resolve_auth`]:
//!
//! | transport | default |
//! |---|---|
//! | stdio | no auth — the boundary is the parent/child process relationship, and whatever can spawn apexe already holds the user's privileges |
//! | HTTP/SSE on loopback | bearer token, generated and written to stderr at startup, so a local dev server needs no secret management |
//! | HTTP/SSE elsewhere | authentication required; `--auth none` refuses to start without a separate acknowledgement |
//!
//! A bearer token is the primary mechanism because the dominant deployment is
//! one desktop MCP client talking to one local server, where JWT's issuer, key
//! management, expiry and rotation buy nothing. JWT stays available as a mode
//! for multi-user deployments, where an identity-bearing credential is what
//! makes the ACL's `callers` field and the audit log's caller dimension
//! meaningful.

use std::collections::HashMap;
use std::sync::Arc;

use apcore::{ErrorCode, ModuleError};
use apcore_mcp::{Authenticator, Identity, JWTAuthenticator};
use async_trait::async_trait;

/// The `type` recorded on an [`Identity`] minted from a static bearer token.
const TOKEN_IDENTITY_TYPE: &str = "token";

/// The caller id every holder of the shared bearer token authenticates as.
///
/// One token means one principal; there is nothing to distinguish two holders
/// of the same secret. Naming it explicitly (rather than leaving the identity
/// anonymous) is what lets `caller_id` reach the audit log at all.
const TOKEN_IDENTITY_ID: &str = "apexe-token";

/// Which credential the HTTP transports accept.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthMode {
    /// A shared bearer token in `Authorization: Bearer <token>`.
    Token,
    /// A signed JWT in `Authorization: Bearer <jwt>`.
    Jwt,
    /// No credential is checked. Explicit opt-out.
    None,
}

impl AuthMode {
    /// Parse the `--auth` value. Returns `None` for an unrecognized mode so
    /// the caller can build the error with its own context.
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "token" => Some(Self::Token),
            "jwt" => Some(Self::Jwt),
            "none" => Some(Self::None),
            _ => None,
        }
    }

    /// The value as it is spelled on the command line.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Token => "token",
            Self::Jwt => "jwt",
            Self::None => "none",
        }
    }
}

/// What the operator asked for on the command line, before it is reconciled
/// with the transport and bind address.
#[derive(Debug, Clone, Default)]
pub struct AuthOptions {
    /// Explicit `--auth <mode>`. `None` means "use the per-transport default".
    pub mode: Option<AuthMode>,
    /// Explicit `--auth-token`, or `APEXE_AUTH_TOKEN`.
    pub token: Option<String>,
    /// Explicit `--jwt-secret`, or `APEXE_JWT_SECRET`.
    pub jwt_secret: Option<String>,
    /// The separate acknowledgement `--auth none` needs on a non-loopback
    /// bind. A `--disable-*` flag gets copied out of a tutorial once and then
    /// lives in everyone's startup script forever; requiring a second flag
    /// makes the dangerous configuration state its own name.
    pub allow_unauthenticated_bind: bool,
}

/// The authentication actually installed on the server.
pub enum ResolvedAuth {
    /// No authenticator is applied — stdio, or an acknowledged `--auth none`.
    Disabled,
    /// A bearer token is required.
    Token {
        authenticator: Arc<dyn Authenticator>,
        /// The token itself, so the caller can print a generated one.
        token: String,
        /// `true` when apexe minted the token rather than being given one.
        generated: bool,
    },
    /// A JWT is required.
    Jwt {
        authenticator: Arc<dyn Authenticator>,
    },
}

impl std::fmt::Debug for ResolvedAuth {
    /// Renders the mode only. The token is a live credential and this type
    /// ends up in server-assembly diagnostics.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Disabled => f.write_str("ResolvedAuth::Disabled"),
            Self::Token { generated, .. } => f
                .debug_struct("ResolvedAuth::Token")
                .field("token", &"<redacted>")
                .field("generated", generated)
                .finish(),
            Self::Jwt { .. } => f.write_str("ResolvedAuth::Jwt"),
        }
    }
}

impl ResolvedAuth {
    /// The authenticator to hand to apcore-mcp, if any.
    pub fn authenticator(&self) -> Option<Arc<dyn Authenticator>> {
        match self {
            Self::Disabled => None,
            Self::Token { authenticator, .. } | Self::Jwt { authenticator } => {
                Some(authenticator.clone())
            }
        }
    }

    /// Whether unauthenticated requests must be rejected.
    pub fn require_auth(&self) -> bool {
        !matches!(self, Self::Disabled)
    }
}

/// Whether `host` binds only to the local machine.
///
/// Anything else is reachable from the network and gets the strict default.
/// An unparseable host is treated as non-loopback: guessing wrong in that
/// direction only costs a flag, guessing wrong the other way costs the host.
pub fn is_loopback_host(host: &str) -> bool {
    if host == "localhost" {
        return true;
    }
    let trimmed = host.trim_start_matches('[').trim_end_matches(']');
    trimmed
        .parse::<std::net::IpAddr>()
        .is_ok_and(|ip| ip.is_loopback())
}

/// Reconcile the requested auth options with the transport and bind address.
///
/// Returns `Err` for the two configurations that must not start: an
/// unacknowledged `--auth none` on a non-loopback bind, and `--auth jwt`
/// without a secret.
#[allow(clippy::result_large_err)] // ModuleError is the crate-wide domain error
pub fn resolve_auth(
    transport: &str,
    host: &str,
    opts: &AuthOptions,
) -> Result<ResolvedAuth, ModuleError> {
    if transport == "stdio" {
        if opts.mode.is_some_and(|mode| mode != AuthMode::None) || opts.token.is_some() {
            tracing::warn!(
                "Ignoring --auth on the stdio transport: the trust boundary is the \
                 parent/child process relationship, and a token adds nothing to it"
            );
        }
        return Ok(ResolvedAuth::Disabled);
    }

    let loopback = is_loopback_host(host);
    let resolved = match opts.mode.unwrap_or(AuthMode::Token) {
        AuthMode::None => resolve_none(host, loopback, opts.allow_unauthenticated_bind),
        AuthMode::Token => Ok(resolve_token(opts.token.clone())),
        AuthMode::Jwt => resolve_jwt(opts.jwt_secret.as_deref()),
    }?;
    warn_if_credential_crosses_the_network(&resolved, host, loopback);
    Ok(resolved)
}

/// Warn that a credential on a non-loopback bind travels in cleartext.
///
/// apexe serves plain HTTP — apcore-mcp terminates no TLS, and neither does
/// apexe — so on a non-loopback bind the bearer token or JWT is readable by
/// anything on the path. Whoever reads it holds exactly the remote-execution
/// entry point the credential was added to close, which makes this the one
/// failure that silently undoes the whole of the auth default.
///
/// It is a warning rather than a refusal because the standard deployment is
/// correct and undetectable from here: apexe behind a TLS-terminating reverse
/// proxy sees a plain non-loopback bind and nothing distinguishes it from a
/// naked one. Refusing would break the right answer to force the wrong one.
///
/// Loopback is exempt because the traffic never reaches a network interface.
fn warn_if_credential_crosses_the_network(resolved: &ResolvedAuth, host: &str, loopback: bool) {
    if loopback || !resolved.require_auth() {
        return;
    }
    tracing::warn!(
        host,
        "This bind serves plain HTTP, so the credential it requires is sent in cleartext and \
         anything on the path can replay it. Put apexe behind a TLS-terminating reverse proxy, \
         or bind to 127.0.0.1 and reach it through a tunnel."
    );
}

/// `--auth none`: allowed on loopback with a warning, refused elsewhere unless
/// separately acknowledged.
#[allow(clippy::result_large_err)] // ModuleError is the crate-wide domain error
fn resolve_none(
    host: &str,
    loopback: bool,
    acknowledged: bool,
) -> Result<ResolvedAuth, ModuleError> {
    if !loopback && !acknowledged {
        return Err(ModuleError::new(
            ErrorCode::GeneralInvalidInput,
            format!(
                "Refusing to start: `--auth none` on the non-loopback bind '{host}' would expose \
                 every wrapped binary on this host to the network with no credential. apexe wraps \
                 arbitrary local commands, so this is a remote-execution entry point rather than \
                 an unauthenticated API. Bind to 127.0.0.1, use `--auth token`, or pass \
                 `--allow-unauthenticated-bind` to state that you mean it."
            ),
        ));
    }
    if !loopback {
        tracing::warn!(
            host,
            "Serving with NO authentication on a non-loopback bind, as explicitly acknowledged"
        );
    } else {
        tracing::warn!("Authentication disabled on a loopback bind (--auth none)");
    }
    Ok(ResolvedAuth::Disabled)
}

/// `--auth token`: use the supplied token, or mint one.
fn resolve_token(supplied: Option<String>) -> ResolvedAuth {
    // Trimmed before the emptiness check and before it is stored: the
    // presented side of the comparison in `StaticTokenAuthenticator::
    // authenticate` is already trimmed, so a configured value left
    // untrimmed here could never match anything a client presents. A
    // trailing newline or space is the common way this secret arrives (a
    // Docker --env-file, a Kubernetes secret created from a file, a
    // hand-edited systemd Environment= line).
    let (token, generated) = match supplied
        .map(|t| t.trim().to_string())
        .filter(|t| !t.is_empty())
    {
        Some(token) => (token, false),
        None => (generate_token(), true),
    };
    ResolvedAuth::Token {
        authenticator: Arc::new(StaticTokenAuthenticator::new(token.clone())),
        token,
        generated,
    }
}

/// `--auth jwt`: a secret is mandatory, since there is nothing sensible to
/// generate.
#[allow(clippy::result_large_err)] // ModuleError is the crate-wide domain error
fn resolve_jwt(secret: Option<&str>) -> Result<ResolvedAuth, ModuleError> {
    let secret = secret.filter(|s| !s.is_empty()).ok_or_else(|| {
        ModuleError::new(
            ErrorCode::GeneralInvalidInput,
            "`--auth jwt` needs a signing secret: pass `--jwt-secret <value>` or set \
             APEXE_JWT_SECRET."
                .to_string(),
        )
    })?;
    let authenticator = JWTAuthenticator::new(secret, None, None, None, None, None, Some(true));
    Ok(ResolvedAuth::Jwt {
        authenticator: Arc::new(authenticator),
    })
}

/// Mint a bearer token.
///
/// Two v4 UUIDs' worth of hex — 244 bits from the OS CSPRNG, well past what a
/// bearer token needs, and no new dependency beyond the `uuid` crate already
/// present in the dependency graph.
fn generate_token() -> String {
    format!(
        "{}{}",
        uuid::Uuid::new_v4().simple(),
        uuid::Uuid::new_v4().simple()
    )
}

/// Compare two byte strings without an early return on the first difference.
///
/// A `==` on the token would leak its prefix through response timing. The
/// length is not secret (it is fixed by the format), so comparing lengths
/// first is fine.
fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    if left.len() != right.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for (l, r) in left.iter().zip(right.iter()) {
        diff |= l ^ r;
    }
    diff == 0
}

/// Accepts one shared bearer token in the `Authorization` header.
///
/// The header map handed to an [`Authenticator`] has lowercased names, so only
/// `authorization` is looked up.
pub struct StaticTokenAuthenticator {
    token: String,
}

impl StaticTokenAuthenticator {
    /// Create an authenticator for `token`.
    pub fn new(token: String) -> Self {
        Self { token }
    }
}

impl std::fmt::Debug for StaticTokenAuthenticator {
    /// Never renders the token: this type ends up inside server config structs
    /// that get logged.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StaticTokenAuthenticator")
            .field("token", &"<redacted>")
            .finish()
    }
}

#[async_trait]
impl Authenticator for StaticTokenAuthenticator {
    async fn authenticate(&self, headers: &HashMap<String, String>) -> Option<Identity> {
        let presented = headers
            .get("authorization")?
            .strip_prefix("Bearer ")
            .or_else(|| headers.get("authorization")?.strip_prefix("bearer "))?
            .trim();
        if !constant_time_eq(presented.as_bytes(), self.token.as_bytes()) {
            return None;
        }
        Some(Identity::new(
            TOKEN_IDENTITY_ID.to_string(),
            TOKEN_IDENTITY_TYPE.to_string(),
            vec![],
            HashMap::new(),
        ))
    }
}

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

    fn bearer(value: &str) -> HashMap<String, String> {
        HashMap::from([("authorization".to_string(), format!("Bearer {value}"))])
    }

    #[test]
    fn test_is_loopback_host_recognizes_local_binds() {
        assert!(is_loopback_host("127.0.0.1"));
        assert!(is_loopback_host("127.0.0.53"));
        assert!(is_loopback_host("::1"));
        assert!(is_loopback_host("[::1]"));
        assert!(is_loopback_host("localhost"));
    }

    #[test]
    fn test_is_loopback_host_treats_unknown_as_remote() {
        assert!(!is_loopback_host("0.0.0.0"));
        assert!(!is_loopback_host("192.168.1.10"));
        // Unparseable must fail safe towards "reachable from the network".
        assert!(!is_loopback_host("example.com"));
    }

    #[test]
    fn test_resolve_auth_stdio_is_disabled() {
        let resolved = resolve_auth("stdio", "127.0.0.1", &AuthOptions::default()).unwrap();
        assert!(!resolved.require_auth());
        assert!(resolved.authenticator().is_none());
    }

    #[test]
    fn test_resolve_auth_http_defaults_to_generated_token() {
        let resolved = resolve_auth("http", "127.0.0.1", &AuthOptions::default()).unwrap();
        assert!(resolved.require_auth());
        match resolved {
            ResolvedAuth::Token {
                token, generated, ..
            } => {
                assert!(generated);
                assert_eq!(token.len(), 64);
            }
            _ => panic!("expected a generated token"),
        }
    }

    #[test]
    fn test_resolve_auth_uses_supplied_token() {
        let opts = AuthOptions {
            token: Some("supplied-secret".to_string()),
            ..AuthOptions::default()
        };
        match resolve_auth("http", "0.0.0.0", &opts).unwrap() {
            ResolvedAuth::Token {
                token, generated, ..
            } => {
                assert!(!generated);
                assert_eq!(token, "supplied-secret");
            }
            _ => panic!("expected the supplied token"),
        }
    }

    #[test]
    fn test_resolve_auth_trims_whitespace_from_a_supplied_token() {
        // Regression: a trailing newline or space is the classic way a
        // secret arrives from a Docker --env-file, a Kubernetes secret
        // created from a file, or a hand-edited systemd Environment= line.
        // The presented side is already trimmed in `authenticate` (below);
        // without trimming here too, the stored and presented values would
        // never match and every request would 401 with no diagnostic
        // mentioning whitespace.
        let opts = AuthOptions {
            token: Some(" supplied-secret\n".to_string()),
            ..AuthOptions::default()
        };
        match resolve_auth("http", "0.0.0.0", &opts).unwrap() {
            ResolvedAuth::Token { token, .. } => {
                assert_eq!(token, "supplied-secret");
            }
            _ => panic!("expected the supplied token"),
        }
    }

    #[test]
    fn test_resolve_auth_treats_a_whitespace_only_token_as_absent() {
        // A whitespace-only value must fall through to the generated-token
        // path rather than becoming an unusable stored secret nobody can
        // ever present a match for.
        let opts = AuthOptions {
            token: Some("   ".to_string()),
            ..AuthOptions::default()
        };
        match resolve_auth("http", "0.0.0.0", &opts).unwrap() {
            ResolvedAuth::Token {
                token, generated, ..
            } => {
                assert!(
                    generated,
                    "a whitespace-only token must be treated as absent"
                );
                assert_eq!(token.len(), 64);
            }
            _ => panic!("expected a generated token"),
        }
    }

    #[tokio::test]
    async fn test_a_configured_token_with_surrounding_whitespace_still_authenticates() {
        // End-to-end: APEXE_AUTH_TOKEN="abc123\n" must still let a client
        // presenting the clean "abc123" bearer token through.
        let opts = AuthOptions {
            token: Some(" abc123\n".to_string()),
            ..AuthOptions::default()
        };
        let resolved = resolve_auth("http", "0.0.0.0", &opts).unwrap();
        let authenticator = resolved.authenticator().expect("token mode installs one");
        let identity = authenticator
            .authenticate(&bearer("abc123"))
            .await
            .expect("the trimmed configured token must match the presented one");
        assert_eq!(identity.id(), TOKEN_IDENTITY_ID);
    }

    /// Collect the `tracing` output `run` emits on this thread.
    ///
    /// The subscriber is thread-local (`with_default`), so tests asserting on
    /// warnings stay independent under the parallel test harness.
    fn capture_warnings(run: impl FnOnce()) -> String {
        #[derive(Clone)]
        struct Buffer(Arc<Mutex<Vec<u8>>>);

        impl std::io::Write for Buffer {
            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
                self.0.lock().expect("test buffer").extend_from_slice(buf);
                Ok(buf.len())
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buffer {
            type Writer = Self;
            fn make_writer(&'a self) -> Self::Writer {
                self.clone()
            }
        }

        let buffer = Buffer(Arc::new(Mutex::new(Vec::new())));
        let subscriber = tracing_subscriber::fmt()
            .with_writer(buffer.clone())
            .with_ansi(false)
            .finish();
        tracing::subscriber::with_default(subscriber, run);
        let bytes = buffer.0.lock().expect("test buffer").clone();
        String::from_utf8(bytes).expect("tracing output is UTF-8")
    }

    /// A credential on a non-loopback bind is the one failure that silently
    /// undoes the whole auth default: apexe terminates no TLS, so the token
    /// that guards a remote-execution surface is readable on the wire, and
    /// whoever reads it holds the surface.
    #[test]
    fn test_resolve_auth_warns_that_a_remote_credential_is_sent_in_cleartext() {
        let warnings = capture_warnings(|| {
            resolve_auth("http", "0.0.0.0", &AuthOptions::default())
                .expect("a generated token needs no acknowledgement");
        });
        assert!(
            warnings.contains("cleartext"),
            "a token on a non-loopback bind must warn about the wire: {warnings}"
        );
        assert!(
            warnings.contains("reverse proxy"),
            "the warning must name the remedy: {warnings}"
        );
    }

    #[test]
    fn test_resolve_auth_warns_for_jwt_on_a_non_loopback_bind_too() {
        // The concern is the transport, not which credential format rides it.
        let opts = AuthOptions {
            mode: Some(AuthMode::Jwt),
            jwt_secret: Some("s3cret".to_string()),
            ..AuthOptions::default()
        };
        let warnings = capture_warnings(|| {
            resolve_auth("http", "0.0.0.0", &opts).expect("a supplied secret is enough");
        });
        assert!(
            warnings.contains("cleartext"),
            "JWT on a non-loopback bind must warn too: {warnings}"
        );
    }

    #[test]
    fn test_resolve_auth_stays_quiet_about_the_wire_on_loopback() {
        // Loopback traffic never reaches a network interface, so the warning
        // would be noise on every local dev server — the case the generated
        // token exists to make painless.
        let warnings = capture_warnings(|| {
            resolve_auth("http", "127.0.0.1", &AuthOptions::default())
                .expect("loopback defaults to a generated token");
        });
        assert!(
            !warnings.contains("cleartext"),
            "loopback must not warn about the wire: {warnings}"
        );
    }

    #[test]
    fn test_resolve_auth_does_not_claim_cleartext_when_no_credential_is_required() {
        // `--auth none` already refuses or warns on its own terms; adding a
        // warning about a credential there would name one that does not exist.
        let opts = AuthOptions {
            mode: Some(AuthMode::None),
            allow_unauthenticated_bind: true,
            ..AuthOptions::default()
        };
        let warnings = capture_warnings(|| {
            resolve_auth("http", "0.0.0.0", &opts).expect("acknowledged");
        });
        assert!(
            !warnings.contains("cleartext"),
            "there is no credential to send in cleartext: {warnings}"
        );
    }

    #[test]
    fn test_resolve_auth_refuses_none_on_non_loopback_bind() {
        let opts = AuthOptions {
            mode: Some(AuthMode::None),
            ..AuthOptions::default()
        };
        let err = resolve_auth("http", "0.0.0.0", &opts)
            .expect_err("--auth none on a public bind must refuse to start");
        assert_eq!(err.code, ErrorCode::GeneralInvalidInput);
        assert!(err.message.contains("--allow-unauthenticated-bind"));
    }

    #[test]
    fn test_resolve_auth_allows_acknowledged_none_on_non_loopback_bind() {
        let opts = AuthOptions {
            mode: Some(AuthMode::None),
            allow_unauthenticated_bind: true,
            ..AuthOptions::default()
        };
        let resolved = resolve_auth("http", "0.0.0.0", &opts).unwrap();
        assert!(!resolved.require_auth());
    }

    #[test]
    fn test_resolve_auth_allows_none_on_loopback_without_acknowledgement() {
        let opts = AuthOptions {
            mode: Some(AuthMode::None),
            ..AuthOptions::default()
        };
        assert!(resolve_auth("http", "127.0.0.1", &opts).is_ok());
    }

    #[test]
    fn test_resolve_auth_jwt_requires_secret() {
        let opts = AuthOptions {
            mode: Some(AuthMode::Jwt),
            ..AuthOptions::default()
        };
        let err = resolve_auth("http", "127.0.0.1", &opts)
            .expect_err("--auth jwt without a secret must refuse to start");
        assert!(err.message.contains("--jwt-secret"));
    }

    #[test]
    fn test_auth_mode_parse_roundtrip() {
        for mode in [AuthMode::Token, AuthMode::Jwt, AuthMode::None] {
            assert_eq!(AuthMode::parse(mode.as_str()), Some(mode));
        }
        assert_eq!(AuthMode::parse("basic"), None);
    }

    #[tokio::test]
    async fn test_static_token_authenticator_accepts_matching_token() {
        let auth = StaticTokenAuthenticator::new("s3cret".to_string());
        let identity = auth
            .authenticate(&bearer("s3cret"))
            .await
            .expect("matching token authenticates");
        assert_eq!(identity.id(), TOKEN_IDENTITY_ID);
    }

    #[tokio::test]
    async fn test_static_token_authenticator_rejects_wrong_or_missing_token() {
        let auth = StaticTokenAuthenticator::new("s3cret".to_string());
        assert!(auth.authenticate(&bearer("wrong")).await.is_none());
        // A prefix must not pass: the comparison is over the whole value.
        assert!(auth.authenticate(&bearer("s3cre")).await.is_none());
        assert!(auth.authenticate(&HashMap::new()).await.is_none());
        // A bare token with no scheme is not a Bearer credential.
        assert!(auth
            .authenticate(&HashMap::from([(
                "authorization".to_string(),
                "s3cret".to_string()
            )]))
            .await
            .is_none());
    }

    #[test]
    fn test_constant_time_eq_matches_equality() {
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd"));
        assert!(!constant_time_eq(b"abc", b"ab"));
    }

    #[test]
    fn test_generate_token_is_unique_and_long() {
        let first = generate_token();
        let second = generate_token();
        assert_ne!(first, second);
        assert_eq!(first.len(), 64);
        assert!(first.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_static_token_authenticator_debug_hides_token() {
        let auth = StaticTokenAuthenticator::new("s3cret".to_string());
        let rendered = format!("{auth:?}");
        assert!(!rendered.contains("s3cret"), "token leaked: {rendered}");
    }
}