capsule-runtime 0.6.0

The runtime that executes Murmur capsules. Runs packaged AI agents in isolation, enforcing WASI capability grants on a Wasmtime component sandbox.
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! Who may call the A2A door: the tokens a capsule declaring `network.authentication` mints at
//! launch, the check every gated request passes, and the refusals it answers with.
//!
//! **A token is a pure bearer token.** It is a [`crate::mac_token`] token of the family
//! [`DOOR_TOKEN_TAG`], sealed with a [`MintKey`] generated in memory for one session and bound to
//! nothing, so holding it is the whole of what a caller must do. That is what lets a standard A2A
//! client given a token call the door. Its payload is `{"credential": "<name>", "scopes": [...]}`.
//! The key is never written anywhere, so a token dies with the session that minted it and a
//! restart mints new ones. There is no revocation list: dropping the key revokes every token.
//!
//! **The operator token always exists.** It holds every scope in [`DOOR_SCOPES`]. Each credential
//! the manifest declares mints one more token, carrying exactly that credential's scopes, so a
//! declared credential exists to hand out less than the operator token.
//!
//! **Verification order is fixed: header → MAC → payload.** A refusal never says why a token was
//! not accepted, so the door cannot be used as an oracle.
//!
//! **A formation member's door also takes formation tokens.** A door built with a
//! [`FormationVerifier`] lets in a [`crate::formation_credentials`] token issued to it as the
//! credential `member:<caller>`, with exactly [`FORMATION_CALL_SCOPES`]. A genuine token issued for
//! another member's door is `403 not_permitted`; any other token of that family is the same `401`
//! as any other invalid token. A door with no verifier refuses every formation token as invalid.
//!
//! **A scope limits methods, not tasks.** Every authenticated caller shares the session's one task
//! and context space, as every caller shares it on a public door.
//!
//! A token reaches no guest, no trace, no log, no error body and no `Debug` output. [`DoorToken`]
//! implements neither `Display` nor `Serialize`, and [`DoorToken::expose`] is the one way to read
//! it.

use murmur_artifact::{
    security_warning_link, NetworkAuthentication, RuntimeManifest, DOOR_SCOPES,
    OPERATOR_CREDENTIAL, W_SEC_032,
};
use serde_json::{json, Value};

use crate::formation_credentials::{
    FormationRefusal, FormationVerifier, FORMATION_CALL_SCOPES, FORMATION_CREDENTIAL_PREFIX,
    FORMATION_TOKEN_TAG,
};
use crate::mac_token::{self, MintKey};
use crate::resource_plane::ResourceResponse;

/// The version tag of a door token.
pub const DOOR_TOKEN_TAG: &str = "mdt1";

/// The MAC domain of a door token. Distinct from every other family's, so no other token this
/// process mints can verify at the door.
pub const DOOR_TOKEN_DOMAIN: &[u8] = b"murmur-door-token-v1";

/// The environment variable `mur cancel` and `mur watch` read a door token from when the capsule is
/// named by `--url` rather than by session address.
pub const DOOR_TOKEN_ENV: &str = "MURMUR_DOOR_TOKEN";

/// The scope that reaches the operator resource plane under `/resources/files`.
pub const RESOURCES_FILES_SCOPE: &str = "resources/files";

/// The scheme name in `Authorization`, matched without regard to case.
const BEARER_SCHEME: &str = "bearer";

// ── Tokens ────────────────────────────────────────────────────────────────────

/// One door token's text.
///
/// `Debug` prints `DoorToken(<redacted>)`. There is no `Display` and no `Serialize`, so the text
/// reaches a log line, a trace event or an error body by no route but [`Self::expose`].
#[derive(Clone, PartialEq, Eq)]
pub struct DoorToken(String);

impl DoorToken {
    pub fn new(token: String) -> Self {
        Self(token)
    }

    /// The token text, for an `Authorization` header, the running record, or `mur token`'s output.
    pub fn expose(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Debug for DoorToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("DoorToken(<redacted>)")
    }
}

/// The `Authorization` header value that presents `token`.
pub fn bearer_header(token: &DoorToken) -> String {
    format!("Bearer {}", token.expose())
}

/// The token an `Authorization` header value presents under the `Bearer` scheme, or `None` for
/// any other shape. The scheme is matched without regard to case (RFC 7235); the token is returned
/// as sent, because every token murmur mints is case-sensitive base64url.
pub(crate) fn bearer_token(authorization: &str) -> Option<&str> {
    let (scheme, token) = authorization
        .trim()
        .split_once(|c: char| c.is_ascii_whitespace())?;
    scheme
        .eq_ignore_ascii_case(BEARER_SCHEME)
        .then(|| token.trim())
}

// ── Minting and verifying ─────────────────────────────────────────────────────

/// One session's door key and the tokens minted with it, and — for a formation member — what its
/// door checks a formation token with.
pub struct DoorAuth {
    key: MintKey,
    /// Operator first, then the declared credentials in name order.
    tokens: Vec<(String, DoorToken)>,
    formation: Option<FormationVerifier>,
}

impl std::fmt::Debug for DoorAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DoorAuth")
            .field(
                "credentials",
                &self
                    .tokens
                    .iter()
                    .map(|(name, _)| name.as_str())
                    .collect::<Vec<_>>(),
            )
            .field("formation", &self.formation)
            .finish_non_exhaustive()
    }
}

impl DoorAuth {
    /// Generates this session's key and mints the operator token, holding every scope in
    /// [`DOOR_SCOPES`], and one token per declared credential with exactly its scopes.
    ///
    /// The `Err` is the operating system refusing randomness, and carries no key material.
    pub fn mint(authentication: &NetworkAuthentication) -> Result<Self, String> {
        let key = MintKey::generate()?;
        let operator_scopes: Vec<String> = DOOR_SCOPES.iter().map(|s| s.to_string()).collect();
        let mut tokens = vec![(
            OPERATOR_CREDENTIAL.to_string(),
            seal(&key, OPERATOR_CREDENTIAL, &operator_scopes),
        )];
        for credential in &authentication.credentials {
            tokens.push((
                credential.name.clone(),
                seal(&key, &credential.name, &credential.scopes),
            ));
        }
        Ok(Self {
            key,
            tokens,
            formation: None,
        })
    }

    /// This door, also taking formation tokens issued to the member `verifier` names.
    pub fn with_formation(mut self, verifier: FormationVerifier) -> Self {
        self.formation = Some(verifier);
        self
    }

    /// The token holding every scope.
    pub fn operator_token(&self) -> &DoorToken {
        &self.tokens[0].1
    }

    /// Every token this session minted, operator first, then the declared credentials by name.
    pub fn tokens(&self) -> &[(String, DoorToken)] {
        &self.tokens
    }

    /// The grant `authorization_headers` present: every `Authorization` header value on the
    /// request, as sent.
    ///
    /// No header is [`AuthRefusal::Missing`]. More than one, a scheme other than `Bearer`, a token
    /// this key did not seal, and a payload naming a scope outside [`DOOR_SCOPES`] are all
    /// [`AuthRefusal::Invalid`], indistinguishably. So is a formation token that does not verify,
    /// and every formation token at a door with no verifier. A genuine formation token issued for
    /// another door is [`AuthRefusal::NotPermitted`].
    pub fn verify(&self, authorization_headers: &[&str]) -> Result<DoorGrant, AuthRefusal> {
        let header = match authorization_headers {
            [] => return Err(AuthRefusal::Missing),
            [header] => header,
            _ => return Err(AuthRefusal::Invalid),
        };
        let token = bearer_token(header).ok_or(AuthRefusal::Invalid)?;
        if token.split('.').next() == Some(FORMATION_TOKEN_TAG) {
            return self.verify_formation(token);
        }
        let payload = mac_token::open(&self.key, DOOR_TOKEN_TAG, DOOR_TOKEN_DOMAIN, token, &[])
            .map_err(|_| AuthRefusal::Invalid)?;
        let payload: Value = serde_json::from_slice(&payload).map_err(|_| AuthRefusal::Invalid)?;
        let credential = payload["credential"]
            .as_str()
            .ok_or(AuthRefusal::Invalid)?
            .to_string();
        let scopes = payload["scopes"]
            .as_array()
            .ok_or(AuthRefusal::Invalid)?
            .iter()
            .map(|scope| {
                scope
                    .as_str()
                    .filter(|scope| DOOR_SCOPES.contains(scope))
                    .map(str::to_string)
                    .ok_or(AuthRefusal::Invalid)
            })
            .collect::<Result<Vec<_>, _>>()?;
        Ok(DoorGrant {
            credential,
            scopes,
            formation_caller: None,
        })
    }

    fn verify_formation(&self, token: &str) -> Result<DoorGrant, AuthRefusal> {
        let verifier = self.formation.as_ref().ok_or(AuthRefusal::Invalid)?;
        match verifier.verify(token) {
            Ok(caller) => Ok(DoorGrant {
                credential: format!("{FORMATION_CREDENTIAL_PREFIX}{}", caller.from()),
                scopes: FORMATION_CALL_SCOPES
                    .iter()
                    .map(|s| s.to_string())
                    .collect(),
                formation_caller: Some(caller.from().to_string()),
            }),
            Err(FormationRefusal::Invalid) => Err(AuthRefusal::Invalid),
            Err(FormationRefusal::NotPermitted { caller }) => {
                Err(AuthRefusal::NotPermitted { caller })
            }
        }
    }
}

fn seal(key: &MintKey, credential: &str, scopes: &[String]) -> DoorToken {
    let payload = json!({"credential": credential, "scopes": scopes});
    DoorToken(mac_token::seal(
        key,
        DOOR_TOKEN_TAG,
        DOOR_TOKEN_DOMAIN,
        payload.to_string().as_bytes(),
        &[],
    ))
}

/// What a verified token reaches.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DoorGrant {
    credential: String,
    scopes: Vec<String>,
    /// The member a formation token was issued to, for a grant from one.
    formation_caller: Option<String>,
}

impl DoorGrant {
    /// The credential the token was minted for: `operator`, a declared name, or `member:<name>`
    /// for a formation token.
    pub fn credential(&self) -> &str {
        &self.credential
    }

    /// The calling member's roster name when this grant came from a formation token, and `None`
    /// for every door token.
    pub fn formation_caller(&self) -> Option<&str> {
        self.formation_caller.as_deref()
    }

    /// Whether the token carries `scope`.
    pub fn allows(&self, scope: &str) -> bool {
        self.scopes.iter().any(|held| held == scope)
    }

    /// `Ok` when the token carries `scope`, and the `403` refusal naming both otherwise.
    pub fn require(&self, scope: &str) -> Result<(), AuthRefusal> {
        if self.allows(scope) {
            Ok(())
        } else {
            Err(AuthRefusal::InsufficientScope {
                credential: self.credential.clone(),
                scope: scope.to_string(),
            })
        }
    }
}

/// Why the door refused a request before looking at what it asked for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AuthRefusal {
    /// No `Authorization` header.
    Missing,
    /// An `Authorization` header that does not present a token this session minted, for any
    /// reason at all.
    Invalid,
    /// A valid token whose credential does not carry the scope the request needs.
    InsufficientScope { credential: String, scope: String },
    /// A genuine formation token issued for another member's door: `caller` is a member of this
    /// formation that the roster does not let call this one.
    NotPermitted { caller: String },
}

impl AuthRefusal {
    pub fn status(&self) -> u16 {
        match self {
            AuthRefusal::Missing | AuthRefusal::Invalid => 401,
            AuthRefusal::InsufficientScope { .. } | AuthRefusal::NotPermitted { .. } => 403,
        }
    }

    /// The body's `error` code.
    pub fn code(&self) -> &'static str {
        match self {
            AuthRefusal::Missing => "unauthenticated",
            AuthRefusal::Invalid => "invalid_token",
            AuthRefusal::InsufficientScope { .. } => "insufficient_scope",
            AuthRefusal::NotPermitted { .. } => "not_permitted",
        }
    }

    /// The `www-authenticate` challenge, in RFC 6750's terms, for a door whose realm is `realm`.
    pub fn challenge(&self, realm: &str) -> String {
        match self {
            AuthRefusal::Missing => format!("Bearer realm=\"{realm}\""),
            AuthRefusal::Invalid => format!("Bearer realm=\"{realm}\", error=\"invalid_token\""),
            AuthRefusal::InsufficientScope { scope, .. } => {
                format!("Bearer realm=\"{realm}\", error=\"insufficient_scope\", scope=\"{scope}\"")
            }
            AuthRefusal::NotPermitted { .. } => {
                format!("Bearer realm=\"{realm}\", error=\"insufficient_scope\"")
            }
        }
    }

    /// The body's `message`. The `403`s name the credential or the member that presented the
    /// token, and go only to its holder; neither `401` says why. `not_permitted` names nothing
    /// else — not this member, not the one the token was issued for.
    pub fn message(&self) -> String {
        match self {
            AuthRefusal::Missing => "this door takes a token this capsule's runtime minted, as \
                                     Authorization: Bearer <token>"
                .to_string(),
            AuthRefusal::Invalid => {
                "the Authorization header does not present a token this session minted".to_string()
            }
            AuthRefusal::InsufficientScope { credential, scope } => {
                format!("credential '{credential}' does not reach {scope}")
            }
            AuthRefusal::NotPermitted { caller } => {
                format!("member '{caller}' may not call this capsule")
            }
        }
    }

    /// The refusal as an HTTP response: status, challenge, and the
    /// `{"error": <code>, "message": <sentence>}` body the resource plane also answers with.
    pub fn response(&self, realm: &str) -> ResourceResponse {
        let body = json!({"error": self.code(), "message": self.message()});
        ResourceResponse::framed(
            self.status(),
            vec![
                ("content-type".to_string(), "application/json".to_string()),
                ("www-authenticate".to_string(), self.challenge(realm)),
            ],
            serde_json::to_vec(&body).unwrap_or_default(),
        )
    }
}

// ── The public-door warning ───────────────────────────────────────────────────

/// Whether a `--bind` address keeps the door on this host: an IPv4 address in `127.0.0.0/8`,
/// `::1`, or `localhost`. Every other address, `0.0.0.0` and `::` among them, and every other
/// hostname, exposes it.
pub fn is_loopback_bind(addr: &str) -> bool {
    let addr = addr.trim();
    if addr.eq_ignore_ascii_case("localhost") {
        return true;
    }
    let bare = addr
        .strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .unwrap_or(addr);
    match bare.parse::<std::net::IpAddr>() {
        Ok(std::net::IpAddr::V4(v4)) => v4.is_loopback(),
        Ok(std::net::IpAddr::V6(v6)) => v6 == std::net::Ipv6Addr::LOCALHOST,
        Err(_) => false,
    }
}

/// How the door is reachable off this host.
#[derive(Debug, Clone, Copy)]
pub enum DoorExposure<'a> {
    /// `mur run --bind <addr>` with a non-loopback address.
    Bound(&'a str),
    /// `mur deploy`, which publishes the loopback-bound port at this URL.
    Published(&'a str),
}

impl DoorExposure<'_> {
    fn phrase(&self) -> String {
        match self {
            DoorExposure::Bound(addr) => format!("bound to {addr}"),
            DoorExposure::Published(url) => format!("published at {url}"),
        }
    }
}

/// What a public door hands any caller, read from the manifest alone so that every surface
/// renders the same line for the same manifest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicDoorDisclosure {
    pub methods: Vec<&'static str>,
    pub tools: Vec<String>,
    pub shell: bool,
    pub network: bool,
    pub planes: Vec<&'static str>,
}

impl PublicDoorDisclosure {
    /// The disclosure of `manifest`'s door: the methods served under its
    /// `lifecycle.task_acceptance`, its LLM-visible artifacts, whether it grants shell and network
    /// egress, and its declared planes.
    pub fn of(manifest: &RuntimeManifest) -> Self {
        let acceptance = manifest
            .lifecycle
            .as_ref()
            .map(|lifecycle| lifecycle.task_acceptance.clone())
            .unwrap_or_default();
        let capabilities = manifest.capabilities.as_ref();
        let exports = manifest.exports.as_ref();
        let planes = [
            (exports.is_some_and(|e| e.files.is_some()), "files"),
            (
                exports.is_some_and(|e| e.peer_files.is_some()),
                "peer_files",
            ),
        ]
        .into_iter()
        .filter_map(|(declared, name)| declared.then_some(name))
        .collect();
        Self {
            methods: crate::identity::served_methods(&acceptance, false),
            tools: manifest
                .artifacts
                .iter()
                .filter(|artifact| artifact.runtime.is_llm_visible())
                .map(|artifact| artifact.name.clone())
                .collect(),
            shell: capabilities
                .and_then(|c| c.shell.as_ref())
                .is_some_and(|shell| !shell.allow.is_empty()),
            network: capabilities
                .and_then(|c| c.network.as_ref())
                .is_some_and(|network| !network.allow.is_empty()),
            planes,
        }
    }
}

/// The one `W-SEC-032` line.
pub fn render_public_door_warning(
    exposure: DoorExposure<'_>,
    disclosure: &PublicDoorDisclosure,
) -> String {
    format!(
        "warning[{W_SEC_032}]: the door is {} and network.authentication is not declared — any \
         caller that reaches it can call {}, and the agent card publishes to any A2A client the \
         session id, tools [{}], shell: {}, network: {} and planes [{}] ({})",
        exposure.phrase(),
        disclosure.methods.join(", "),
        disclosure.tools.join(", "),
        disclosure.shell,
        disclosure.network,
        disclosure.planes.join(", "),
        security_warning_link(W_SEC_032),
    )
}

/// The `W-SEC-032` line for `manifest` exposed as `exposure`, or `None` when the manifest declares
/// `network.authentication` or serves no door at all (no `inference:` block).
pub fn public_door_warning(
    manifest: &RuntimeManifest,
    exposure: DoorExposure<'_>,
) -> Option<String> {
    let authenticated = manifest
        .network
        .as_ref()
        .is_some_and(|network| network.authentication.is_some());
    if authenticated || manifest.inference.is_none() {
        return None;
    }
    Some(render_public_door_warning(
        exposure,
        &PublicDoorDisclosure::of(manifest),
    ))
}

/// The `W-SEC-032` line for `mur run --bind <bind_addr>` and `mur doctor --bind <bind_addr>`, or
/// `None` for a loopback bind.
pub fn public_door_bind_warning(manifest: &RuntimeManifest, bind_addr: &str) -> Option<String> {
    if is_loopback_bind(bind_addr) {
        return None;
    }
    public_door_warning(manifest, DoorExposure::Bound(bind_addr))
}

/// The one-line posture `mur doctor` prints for the door: `public (no network.authentication)`,
/// or `bearer — operator, <name> (<scopes>), …`.
pub fn door_posture(manifest: &RuntimeManifest) -> String {
    match manifest
        .network
        .as_ref()
        .and_then(|network| network.authentication.as_ref())
    {
        None => "door: public (no network.authentication)".to_string(),
        Some(authentication) => {
            let mut credentials = vec![OPERATOR_CREDENTIAL.to_string()];
            credentials.extend(authentication.credentials.iter().map(|credential| {
                format!("{} ({})", credential.name, credential.scopes.join(", "))
            }));
            format!("door: bearer — {}", credentials.join(", "))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use murmur_artifact::{AuthenticationScheme, DoorCredential};

    fn authentication() -> NetworkAuthentication {
        NetworkAuthentication {
            scheme: AuthenticationScheme::Bearer,
            credentials: vec![
                DoorCredential {
                    name: "reader".to_string(),
                    scopes: vec!["resources/files".to_string()],
                },
                DoorCredential {
                    name: "watcher".to_string(),
                    scopes: vec!["tasks/get".to_string(), "stream/watch".to_string()],
                },
            ],
        }
    }

    fn header(token: &DoorToken) -> String {
        bearer_header(token)
    }

    #[test]
    fn door_auth_mints_operator_first_then_declared_credentials_by_name() {
        let auth = DoorAuth::mint(&authentication()).unwrap();
        let names: Vec<&str> = auth.tokens().iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(names, ["operator", "reader", "watcher"]);
        assert_eq!(auth.operator_token(), &auth.tokens()[0].1);
        for (_, token) in auth.tokens() {
            assert!(token.expose().starts_with("mdt1."), "{}", token.expose());
        }
    }

    #[test]
    fn door_auth_token_payload_is_credential_and_scopes() {
        let auth = DoorAuth::mint(&authentication()).unwrap();
        let payload = |token: &DoorToken| -> Value {
            serde_json::from_slice(
                &mac_token::payload_segment(DOOR_TOKEN_TAG, token.expose()).unwrap(),
            )
            .unwrap()
        };
        assert_eq!(
            payload(auth.operator_token()),
            json!({"credential": "operator", "scopes": DOOR_SCOPES})
        );
        assert_eq!(
            payload(&auth.tokens()[2].1),
            json!({"credential": "watcher", "scopes": ["tasks/get", "stream/watch"]})
        );
        let raw = mac_token::payload_segment(DOOR_TOKEN_TAG, auth.tokens()[1].1.expose()).unwrap();
        assert_eq!(
            String::from_utf8(raw).unwrap(),
            r#"{"credential":"reader","scopes":["resources/files"]}"#
        );
    }

    #[test]
    fn door_auth_tokens_open_under_the_door_family_with_nothing_bound() {
        let auth = DoorAuth::mint(&authentication()).unwrap();
        let token = auth.operator_token().expose();
        assert!(mac_token::open(&auth.key, DOOR_TOKEN_TAG, DOOR_TOKEN_DOMAIN, token, &[]).is_ok());
        assert!(mac_token::open(
            &auth.key,
            DOOR_TOKEN_TAG,
            b"murmur-control-token-v1",
            token,
            &[]
        )
        .is_err());
    }

    #[test]
    fn door_auth_verify_grants_each_token_its_scopes() {
        let auth = DoorAuth::mint(&authentication()).unwrap();
        let operator = auth.verify(&[&header(auth.operator_token())]).unwrap();
        assert_eq!(operator.credential(), "operator");
        for scope in DOOR_SCOPES {
            assert!(operator.allows(scope), "{scope}");
        }
        let watcher = auth.verify(&[&header(&auth.tokens()[2].1)]).unwrap();
        assert_eq!(watcher.credential(), "watcher");
        assert!(watcher.allows("tasks/get"));
        assert!(watcher.allows("stream/watch"));
        assert!(!watcher.allows("message/send"));
        assert_eq!(
            watcher.require("message/send"),
            Err(AuthRefusal::InsufficientScope {
                credential: "watcher".to_string(),
                scope: "message/send".to_string(),
            })
        );
        assert_eq!(watcher.require("tasks/get"), Ok(()));
    }

    #[test]
    fn door_auth_verify_refusals() {
        let auth = DoorAuth::mint(&authentication()).unwrap();
        let other = DoorAuth::mint(&authentication()).unwrap();
        let token = auth.operator_token().expose().to_string();

        assert_eq!(auth.verify(&[]), Err(AuthRefusal::Missing));
        let good = format!("Bearer {token}");
        assert_eq!(auth.verify(&[&good, &good]), Err(AuthRefusal::Invalid));
        for header in [
            format!("Basic {token}"),
            format!("Token {token}"),
            token.clone(),
            "Bearer".to_string(),
            "Bearer ".to_string(),
            "Bearer garbage".to_string(),
            format!("Bearer {}", other.operator_token().expose()),
            format!("Bearer {}", token.to_uppercase()),
            format!("Bearer {}x", token),
        ] {
            assert_eq!(
                auth.verify(&[&header]),
                Err(AuthRefusal::Invalid),
                "{header}"
            );
        }
        // The scheme is matched without regard to case; the token verbatim.
        for scheme in ["bearer", "BEARER", "BeArEr"] {
            assert!(
                auth.verify(&[&format!("{scheme} {token}")]).is_ok(),
                "{scheme}"
            );
        }
    }

    #[test]
    fn door_auth_verify_refuses_a_sealed_payload_with_a_scope_outside_the_set() {
        let auth = DoorAuth::mint(&authentication()).unwrap();
        let forged = seal(&auth.key, "watcher", &["tasks/list".to_string()]);
        assert_eq!(auth.verify(&[&header(&forged)]), Err(AuthRefusal::Invalid));
        let not_json = mac_token::seal(&auth.key, DOOR_TOKEN_TAG, DOOR_TOKEN_DOMAIN, b"[]", &[]);
        assert_eq!(
            auth.verify(&[&format!("Bearer {not_json}")]),
            Err(AuthRefusal::Invalid)
        );
    }

    #[test]
    fn door_auth_debug_prints_no_token() {
        let auth = DoorAuth::mint(&authentication()).unwrap();
        let token = auth.operator_token().clone();
        assert_eq!(format!("{token:?}"), "DoorToken(<redacted>)");
        let debug = format!("{auth:?}");
        for (_, token) in auth.tokens() {
            assert!(!debug.contains(token.expose()), "{debug}");
        }
        assert!(debug.contains("watcher"), "{debug}");
    }

    #[test]
    fn door_auth_refusal_responses() {
        let realm = "my-agent";
        let cases = [
            (
                AuthRefusal::Missing,
                401,
                "Bearer realm=\"my-agent\"",
                "unauthenticated",
            ),
            (
                AuthRefusal::Invalid,
                401,
                "Bearer realm=\"my-agent\", error=\"invalid_token\"",
                "invalid_token",
            ),
            (
                AuthRefusal::InsufficientScope {
                    credential: "watcher".to_string(),
                    scope: "message/send".to_string(),
                },
                403,
                "Bearer realm=\"my-agent\", error=\"insufficient_scope\", scope=\"message/send\"",
                "insufficient_scope",
            ),
        ];
        for (refusal, status, challenge, code) in cases {
            let response = refusal.response(realm);
            assert_eq!(response.status, status);
            assert!(response
                .headers
                .contains(&("www-authenticate".to_string(), challenge.to_string())));
            let body: Value = serde_json::from_slice(&response.body).unwrap();
            assert_eq!(body["error"], code);
            assert!(body["message"].is_string());
        }
        let body: Value = serde_json::from_slice(
            &AuthRefusal::InsufficientScope {
                credential: "watcher".to_string(),
                scope: "message/send".to_string(),
            }
            .response(realm)
            .body,
        )
        .unwrap();
        assert_eq!(
            body["message"],
            "credential 'watcher' does not reach message/send"
        );
    }

    fn formation_door(
        authority: &crate::formation_credentials::FormationAuthority,
        member: &str,
    ) -> DoorAuth {
        DoorAuth::mint(&authentication())
            .unwrap()
            .with_formation(authority.verifier_for(member))
    }

    #[test]
    fn door_auth_formation_tokens_reach_their_audience_with_three_scopes() {
        let authority = crate::formation_credentials::FormationAuthority::for_test();
        let coder = formation_door(&authority, "coder");
        let token = authority.mint("planner", "coder");
        let grant = coder
            .verify(&[&format!("Bearer {}", token.expose())])
            .unwrap();
        assert_eq!(grant.credential(), "member:planner");
        assert_eq!(grant.formation_caller(), Some("planner"));
        assert_eq!(
            FORMATION_CALL_SCOPES,
            ["message/send", "tasks/get", "tasks/cancel"]
        );
        for scope in DOOR_SCOPES {
            assert_eq!(
                grant.allows(scope),
                FORMATION_CALL_SCOPES.contains(scope),
                "{scope}"
            );
        }
        assert_eq!(
            grant.require("session/stop"),
            Err(AuthRefusal::InsufficientScope {
                credential: "member:planner".to_string(),
                scope: "session/stop".to_string(),
            })
        );
        assert!(!grant.allows("message/stream"));
        assert_eq!(
            grant.require("message/stream"),
            Err(AuthRefusal::InsufficientScope {
                credential: "member:planner".to_string(),
                scope: "message/stream".to_string(),
            })
        );
        let operator = coder.verify(&[&header(coder.operator_token())]).unwrap();
        assert_eq!(operator.formation_caller(), None);

        let reviewer = formation_door(&authority, "reviewer");
        let refused = reviewer
            .verify(&[&format!("Bearer {}", token.expose())])
            .unwrap_err();
        assert_eq!(
            refused,
            AuthRefusal::NotPermitted {
                caller: "planner".to_string()
            }
        );
        let response = refused.response("reviewer-capsule");
        assert_eq!(response.status, 403);
        let body: Value = serde_json::from_slice(&response.body).unwrap();
        assert_eq!(body["error"], "not_permitted");
        assert_eq!(
            body["message"],
            "member 'planner' may not call this capsule"
        );
        assert!(response.headers.contains(&(
            "www-authenticate".to_string(),
            "Bearer realm=\"reviewer-capsule\", error=\"insufficient_scope\"".to_string()
        )));
    }

    /// A forged, foreign or tampered formation token, and any formation token at a door with no
    /// verifier, is the same `401` as a garbage token.
    #[test]
    fn door_auth_formation_forgeries_are_the_ordinary_invalid() {
        let authority = crate::formation_credentials::FormationAuthority::for_test();
        let other = crate::formation_credentials::FormationAuthority::for_test();
        let coder = formation_door(&authority, "coder");
        let garbage = coder.verify(&["Bearer garbage"]).unwrap_err();
        assert_eq!(garbage, AuthRefusal::Invalid);
        let genuine = authority.mint("planner", "coder");
        for header in [
            format!("Bearer {}", other.mint("planner", "coder").expose()),
            format!("Bearer {}x", genuine.expose()),
            "Bearer mft1.x.y".to_string(),
        ] {
            assert_eq!(
                coder.verify(&[&header]),
                Err(AuthRefusal::Invalid),
                "{header}"
            );
        }
        let plain = DoorAuth::mint(&authentication()).unwrap();
        assert_eq!(
            plain.verify(&[&format!("Bearer {}", genuine.expose())]),
            Err(AuthRefusal::Invalid)
        );
        assert_eq!(
            AuthRefusal::Invalid.response("r").body,
            garbage.response("r").body
        );
        let debug = format!("{coder:?}");
        assert!(!debug.contains("mft1."), "{debug}");
        assert!(!debug.contains(&authority.verify_key().render()), "{debug}");
        assert!(debug.contains("coder"), "{debug}");
    }

    /// The manifest's scope list and the door's method table cannot drift: every gated method is a
    /// scope, and every scope but the resource plane's is a gated method.
    #[test]
    fn door_auth_scopes_are_the_gated_methods_and_the_resource_plane() {
        use crate::identity::DoorMethod;
        let mut from_methods: Vec<&str> = DoorMethod::ALL
            .into_iter()
            .filter(|method| *method != DoorMethod::GetAuthenticatedExtendedCard)
            .map(DoorMethod::wire_name)
            .collect();
        from_methods.push(RESOURCES_FILES_SCOPE);
        for scope in &from_methods {
            assert!(DOOR_SCOPES.contains(scope), "{scope} is not in DOOR_SCOPES");
        }
        for scope in DOOR_SCOPES {
            assert!(
                from_methods.contains(scope),
                "{scope} names no gated method or plane"
            );
        }
        assert_eq!(from_methods.len(), DOOR_SCOPES.len());
        for method in DoorMethod::ALL {
            assert_eq!(
                method.scope(),
                (method != DoorMethod::GetAuthenticatedExtendedCard).then(|| method.wire_name())
            );
        }
    }

    #[test]
    fn public_door_warning_is_loopback_bind() {
        for addr in [
            "127.0.0.1",
            "127.1.2.3",
            "127.255.255.255",
            "::1",
            "[::1]",
            "localhost",
            "LOCALHOST",
        ] {
            assert!(is_loopback_bind(addr), "{addr}");
        }
        for addr in [
            "0.0.0.0",
            "::",
            "[::]",
            "10.0.0.1",
            "192.168.1.2",
            "128.0.0.1",
            "example.com",
            "localhost.localdomain",
            "::2",
            "",
        ] {
            assert!(!is_loopback_bind(addr), "{addr}");
        }
    }

    fn manifest(extra: &str) -> RuntimeManifest {
        RuntimeManifest::from_yaml_str(&format!(
            "name: my-agent\nversion: 0.1.0\nartifacts:\n  - name: bash\n    version: 1.0.0\n    \
             runtime: tool\n  - name: drv\n    version: 1.0.0\n    runtime: driver\n    gateway:\n      \
             endpoint: https://api.example.com\n      api_key: k\n\
             inference:\n  transport: http\n  model: m\n  driver:\n    artifact: drv\n\
             capabilities:\n  shell:\n    allow: [git]\n  network:\n    allow: [api.example.com]\n\
             exports:\n  files:\n    root: out\n    mode: read-only\n{extra}"
        ))
        .unwrap()
    }

    #[test]
    fn public_door_warning_text() {
        let line = public_door_bind_warning(&manifest(""), "0.0.0.0").expect("a warning");
        assert_eq!(
            line,
            format!(
                "warning[W-SEC-032]: the door is bound to 0.0.0.0 and network.authentication is \
                 not declared — any caller that reaches it can call message/send, message/stream, \
                 stream/watch, tasks/get, tasks/cancel, session/stop, and the agent card publishes \
                 to any A2A client the session id, tools [bash], shell: true, network: true and \
                 planes [files] ({})",
                security_warning_link(W_SEC_032)
            )
        );
        let published = public_door_warning(
            &manifest("lifecycle:\n  task_acceptance: none\n"),
            DoorExposure::Published("http://203.0.113.9:41873"),
        )
        .unwrap();
        assert!(
            published.contains("published at http://203.0.113.9:41873"),
            "{published}"
        );
        assert!(
            published.contains("can call stream/watch, tasks/get, tasks/cancel, session/stop,"),
            "{published}"
        );
    }

    #[test]
    fn public_door_warning_is_silent_for_loopback_and_authenticated_doors() {
        assert_eq!(public_door_bind_warning(&manifest(""), "127.0.0.1"), None);
        assert_eq!(public_door_bind_warning(&manifest(""), "localhost"), None);
        let authenticated = manifest("network:\n  authentication:\n    scheme: bearer\n");
        assert_eq!(public_door_bind_warning(&authenticated, "0.0.0.0"), None);
        assert_eq!(
            public_door_warning(&authenticated, DoorExposure::Published("http://h:1")),
            None
        );
    }

    #[test]
    fn public_door_warning_posture_line() {
        assert_eq!(
            door_posture(&manifest("")),
            "door: public (no network.authentication)"
        );
        let authenticated = manifest(
            "network:\n  authentication:\n    scheme: bearer\n    credentials:\n      \
             watcher: {scopes: [tasks/get, stream/watch]}\n      reader: {scopes: [resources/files]}\n",
        );
        assert_eq!(
            door_posture(&authenticated),
            "door: bearer — operator, reader (resources/files), watcher (tasks/get, stream/watch)"
        );
    }
}