basil-nats-bridge 0.7.1

NATS request/reply courier for Basil sealed invocation envelopes.
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
// SPDX-FileCopyrightText: 2026 OpenBasil Contributors
//
// SPDX-License-Identifier: Apache-2.0

//! NATS request/reply courier for Basil sealed invocation messages.
//!
//! The bridge treats invocation messages as opaque tagged `COSE` bytes. It
//! validates only transport shape, wraps bytes in [`SealedRequest`] for Basil's
//! invocation service, and never parses, decrypts, or authorizes actor payloads
//! locally.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use async_trait::async_trait;
use basil_proto::broker::v1::invocation_service_client::InvocationServiceClient;
use basil_proto::broker::v1::{SealedRequest, SealedResponse};
use bytes::Bytes;
use futures::StreamExt;
use hyper_util::rt::TokioIo;
use serde::Deserialize;
use thiserror::Error;
use tokio::net::UnixStream;
use tokio::task::JoinSet;
use tokio::time::timeout;
use tonic::transport::{Channel, Endpoint, Uri};
use tonic::{Code, Status};
use tower::service_fn;
use tracing::{debug, error, info, warn};

/// NATS header carrying the stable bridge error token.
pub const ERROR_HEADER: &str = "Basil-Bridge-Error";
/// NATS header carrying bridge error detail intended for logs/operators.
pub const MESSAGE_HEADER: &str = "Basil-Bridge-Message";
/// NATS header carrying `true` when the caller may retry unchanged.
pub const RETRYABLE_HEADER: &str = "Basil-Bridge-Retryable";

const DEFAULT_BASIL_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_CONCURRENCY_LIMIT: usize = 32;
const MAX_ALLOWED_MESSAGE_BYTES: usize = 64 * 1024 * 1024;

/// Command-line arguments for the `basil-nats-bridge` binary.
#[derive(Debug, clap::Parser)]
#[command(version, about = "NATS courier for Basil sealed invocation envelopes")]
pub struct Args {
    /// Path to bridge TOML config.
    #[arg(short, long, env = "BASIL_NATS_BRIDGE_CONFIG")]
    pub config: PathBuf,
}

/// Returns the fully assembled top-level clap [`Command`](clap::Command) for the
/// `basil-nats-bridge` binary, for tooling such as man-page generation.
#[must_use]
pub fn cli() -> clap::Command {
    <Args as clap::CommandFactory>::command()
}

/// Bridge configuration loaded from TOML.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Config {
    /// NATS connection settings.
    pub nats: NatsConfig,
    /// Basil socket settings.
    pub basil: BasilConfig,
    /// Bridge routing and bounds settings.
    pub bridge: BridgeConfig,
}

/// NATS connection settings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NatsConfig {
    /// NATS server URL.
    pub url: String,
    /// Optional NATS credentials file.
    pub creds: Option<PathBuf>,
}

/// Basil broker socket settings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BasilConfig {
    /// Unix-domain socket path for the Basil broker.
    pub socket: PathBuf,
}

/// Bridge routing and request size settings.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BridgeConfig {
    /// NATS subject accepting sealed invocation request bytes.
    pub request_subject: String,
    /// Optional NATS queue group for shared bridge workers.
    pub queue_group: Option<String>,
    /// Maximum accepted NATS payload size in bytes.
    pub max_message_bytes: usize,
    /// Maximum broker calls in flight at once.
    pub concurrency_limit: usize,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RawConfig {
    nats: RawNatsConfig,
    basil: RawBasilConfig,
    bridge: RawBridgeConfig,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RawNatsConfig {
    url: String,
    creds: Option<PathBuf>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RawBasilConfig {
    socket: PathBuf,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct RawBridgeConfig {
    request_subject: String,
    queue_group: Option<String>,
    max_message_bytes: usize,
    concurrency_limit: Option<usize>,
}

impl Config {
    /// Parse and validate bridge configuration from TOML bytes.
    ///
    /// # Errors
    ///
    /// Returns an error when TOML is malformed, a required field is empty, or
    /// `max-message-bytes` is outside the supported bounds.
    pub fn from_toml_str(input: &str) -> Result<Self, ConfigError> {
        let raw: RawConfig = toml::from_str(input)?;
        Self::try_from(raw)
    }

    /// Read, parse, and validate bridge configuration from a TOML file.
    ///
    /// # Errors
    ///
    /// Returns an error when the file cannot be read or validation fails.
    pub async fn from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let bytes = tokio::fs::read_to_string(path).await?;
        Self::from_toml_str(&bytes)
    }
}

impl TryFrom<RawConfig> for Config {
    type Error = ConfigError;

    fn try_from(raw: RawConfig) -> Result<Self, Self::Error> {
        let nats_url = non_empty(&raw.nats.url, "nats.url")?;
        let creds = raw
            .nats
            .creds
            .map(|path| non_empty_path(path, "nats.creds"))
            .transpose()?;
        let socket = non_empty_path(raw.basil.socket, "basil.socket")?;
        let request_subject = non_empty(&raw.bridge.request_subject, "bridge.request-subject")?;
        let queue_group = raw
            .bridge
            .queue_group
            .map(|value| non_empty(&value, "bridge.queue-group"))
            .transpose()?;
        validate_max_message_bytes(raw.bridge.max_message_bytes)?;
        let concurrency_limit = raw
            .bridge
            .concurrency_limit
            .unwrap_or(DEFAULT_CONCURRENCY_LIMIT);
        validate_concurrency_limit(concurrency_limit)?;

        Ok(Self {
            nats: NatsConfig {
                url: nats_url,
                creds,
            },
            basil: BasilConfig { socket },
            bridge: BridgeConfig {
                request_subject,
                queue_group,
                max_message_bytes: raw.bridge.max_message_bytes,
                concurrency_limit,
            },
        })
    }
}

fn non_empty(value: &str, field: &'static str) -> Result<String, ConfigError> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(ConfigError::EmptyField(field));
    }
    Ok(trimmed.to_owned())
}

fn non_empty_path(path: PathBuf, field: &'static str) -> Result<PathBuf, ConfigError> {
    if path.as_os_str().is_empty() {
        return Err(ConfigError::EmptyField(field));
    }
    Ok(path)
}

const fn validate_max_message_bytes(value: usize) -> Result<(), ConfigError> {
    if value == 0 {
        return Err(ConfigError::InvalidMaxMessageBytes {
            value,
            max: MAX_ALLOWED_MESSAGE_BYTES,
        });
    }
    if value > MAX_ALLOWED_MESSAGE_BYTES {
        return Err(ConfigError::InvalidMaxMessageBytes {
            value,
            max: MAX_ALLOWED_MESSAGE_BYTES,
        });
    }
    Ok(())
}

const fn validate_concurrency_limit(value: usize) -> Result<(), ConfigError> {
    if value == 0 {
        return Err(ConfigError::InvalidConcurrencyLimit { value });
    }
    Ok(())
}

/// Configuration parse and validation error.
#[derive(Debug, Error)]
pub enum ConfigError {
    /// TOML syntax or schema error.
    #[error("config TOML is invalid: {0}")]
    Toml(#[from] toml::de::Error),
    /// Config file read error.
    #[error("config file cannot be read: {0}")]
    Io(#[from] std::io::Error),
    /// Required field is empty.
    #[error("config field `{0}` must not be empty")]
    EmptyField(&'static str),
    /// Message size bound is unsupported.
    #[error("`bridge.max-message-bytes` must be in 1..={max}, got {value}")]
    InvalidMaxMessageBytes {
        /// Configured value.
        value: usize,
        /// Maximum supported value.
        max: usize,
    },
    /// Concurrency bound is unsupported.
    #[error("`bridge.concurrency-limit` must be >= 1, got {value}")]
    InvalidConcurrencyLimit {
        /// Configured value.
        value: usize,
    },
}

/// Inbound NATS request metadata and payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BridgeRequest {
    /// Request subject the bridge received.
    pub subject: String,
    /// Optional reply subject. Requests without this cannot receive an error.
    pub reply: Option<String>,
    /// Raw tagged `COSE` bytes.
    pub payload: Vec<u8>,
}

/// Outbound bridge action after handling a request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BridgeAction {
    /// Publish the reply payload and headers to the subject.
    Reply(BridgeReply),
    /// No reply subject was present; the runtime must not publish.
    NoReply(BridgeErrorReply),
}

/// A NATS reply emitted by the bridge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BridgeReply {
    /// Reply subject supplied by the requester.
    pub subject: String,
    /// Reply payload. Empty for bridge-level errors.
    pub payload: Vec<u8>,
    /// Reply headers. Empty for sealed Basil responses.
    pub headers: BridgeHeaders,
}

/// Small testable header map used before conversion to NATS headers.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BridgeHeaders {
    inner: BTreeMap<&'static str, String>,
}

impl BridgeHeaders {
    /// Return an empty header map.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Return true when no headers are present.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Get a header value by name.
    #[must_use]
    pub fn get(&self, name: &'static str) -> Option<&str> {
        self.inner.get(name).map(String::as_str)
    }

    fn insert(&mut self, name: &'static str, value: impl Into<String>) {
        self.inner.insert(name, value.into());
    }

    fn iter(&self) -> impl Iterator<Item = (&'static str, &str)> {
        self.inner
            .iter()
            .map(|(name, value)| (*name, value.as_str()))
    }
}

/// Stable bridge-level error token.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BridgeErrorCode {
    /// The request is not a valid bridge request.
    MalformedRequest,
    /// The request payload exceeds `max-message-bytes`.
    MessageTooLarge,
    /// Basil cannot be reached.
    BasilUnavailable,
    /// Basil rejected the invocation at gRPC/status level.
    BasilRejected,
    /// Basil did not respond before the bridge timeout.
    Timeout,
    /// Unexpected bridge failure.
    Internal,
}

impl BridgeErrorCode {
    /// Return the stable wire token.
    #[must_use]
    pub const fn as_token(self) -> &'static str {
        match self {
            Self::MalformedRequest => "MALFORMED_REQUEST",
            Self::MessageTooLarge => "MESSAGE_TOO_LARGE",
            Self::BasilUnavailable => "BASIL_UNAVAILABLE",
            Self::BasilRejected => "BASIL_REJECTED",
            Self::Timeout => "TIMEOUT",
            Self::Internal => "INTERNAL",
        }
    }
}

/// Bridge-level error metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BridgeErrorReply {
    /// Stable error token.
    pub code: BridgeErrorCode,
    /// Operator-facing detail.
    pub message: String,
    /// True when retrying the same request may succeed.
    pub retryable: bool,
}

impl BridgeErrorReply {
    /// Convert bridge error metadata to the required NATS headers.
    #[must_use]
    pub fn headers(&self) -> BridgeHeaders {
        let mut headers = BridgeHeaders::new();
        headers.insert(ERROR_HEADER, self.code.as_token());
        headers.insert(MESSAGE_HEADER, self.message.clone());
        headers.insert(
            RETRYABLE_HEADER,
            if self.retryable { "true" } else { "false" },
        );
        headers
    }
}

/// Basil invocation client abstraction.
#[async_trait]
pub trait BasilInvoker {
    /// Submit one sealed invocation message.
    ///
    /// # Errors
    ///
    /// Returns a transport/status error when Basil does not produce a sealed
    /// response.
    async fn invoke(&mut self, request: SealedRequest) -> Result<SealedResponse, BasilInvokeError>;
}

/// Basil invocation failure as seen by the bridge.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum BasilInvokeError {
    /// Basil could not be reached.
    #[error("Basil unavailable: {0}")]
    Unavailable(String),
    /// Basil rejected the request without a sealed response.
    #[error("Basil rejected invocation: {0}")]
    Rejected(String),
    /// Basil did not respond before the timeout.
    #[error("Basil invocation timed out")]
    Timeout,
    /// Unexpected bridge-side failure.
    #[error("internal bridge error: {0}")]
    Internal(String),
}

/// Handle one NATS request according to the sealed-message bridge contract.
///
/// # Errors
///
/// This function returns no process-level errors. All request and Basil failures
/// are represented as [`BridgeAction`] values so the runtime can respond over
/// NATS when a reply subject exists.
pub async fn handle_request(
    request: BridgeRequest,
    max_message_bytes: usize,
    basil: &mut impl BasilInvoker,
) -> BridgeAction {
    let Some(reply_subject) = request.reply.clone() else {
        return BridgeAction::NoReply(error_reply(
            BridgeErrorCode::MalformedRequest,
            "NATS request is missing a reply subject",
            false,
        ));
    };

    if request.payload.len() > max_message_bytes {
        return error_action(
            reply_subject,
            BridgeErrorCode::MessageTooLarge,
            format!(
                "request payload is {} bytes, exceeding the configured {} byte limit",
                request.payload.len(),
                max_message_bytes
            ),
            false,
        );
    }

    let sealed_request = SealedRequest {
        message: request.payload,
    };

    match basil.invoke(sealed_request).await {
        Ok(response) => match response_subject(&response, &reply_subject) {
            Ok(subject) => BridgeAction::Reply(BridgeReply {
                subject,
                payload: response.message,
                headers: BridgeHeaders::new(),
            }),
            Err(error) => error_action(
                reply_subject,
                BridgeErrorCode::MalformedRequest,
                error,
                false,
            ),
        },
        Err(error) => basil_error_action(reply_subject, error),
    }
}

fn response_subject(response: &SealedResponse, fallback_subject: &str) -> Result<String, String> {
    let Some(response_subject) = response.response_subject.as_deref() else {
        return Ok(fallback_subject.to_owned());
    };

    if response_subject.chars().any(|c| matches!(c, '*' | '>')) {
        return Err(format!(
            "Basil returned invalid `response_subject` `{response_subject}`: wildcard tokens are not publish subjects"
        ));
    }

    match async_nats::Subject::validated(response_subject) {
        Ok(subject) => Ok(subject.into_string()),
        Err(error) => Err(format!(
            "Basil returned invalid `response_subject` `{response_subject}`: {error}"
        )),
    }
}

fn basil_error_action(reply_subject: String, error: BasilInvokeError) -> BridgeAction {
    match error {
        BasilInvokeError::Unavailable(message) => error_action(
            reply_subject,
            BridgeErrorCode::BasilUnavailable,
            message,
            true,
        ),
        BasilInvokeError::Rejected(message) => error_action(
            reply_subject,
            BridgeErrorCode::BasilRejected,
            message,
            false,
        ),
        BasilInvokeError::Timeout => error_action(
            reply_subject,
            BridgeErrorCode::Timeout,
            "Basil invocation timed out",
            true,
        ),
        BasilInvokeError::Internal(message) => {
            error_action(reply_subject, BridgeErrorCode::Internal, message, true)
        }
    }
}

fn error_action(
    reply_subject: String,
    code: BridgeErrorCode,
    message: impl Into<String>,
    retryable: bool,
) -> BridgeAction {
    let error = error_reply(code, message, retryable);
    BridgeAction::Reply(BridgeReply {
        subject: reply_subject,
        payload: Vec::new(),
        headers: error.headers(),
    })
}

fn error_reply(
    code: BridgeErrorCode,
    message: impl Into<String>,
    retryable: bool,
) -> BridgeErrorReply {
    BridgeErrorReply {
        code,
        message: message.into(),
        retryable,
    }
}

/// gRPC client for Basil's invocation service over a Unix-domain socket.
#[derive(Debug, Clone)]
pub struct BasilGrpcInvoker {
    client: InvocationServiceClient<Channel>,
    timeout: Duration,
}

impl BasilGrpcInvoker {
    /// Connect to Basil over its Unix-domain socket.
    ///
    /// # Errors
    ///
    /// Returns a transport error when the socket cannot be reached.
    pub async fn connect(socket: &Path) -> Result<Self, RuntimeError> {
        let channel = uds_channel(socket, DEFAULT_CONNECT_TIMEOUT).await?;
        Ok(Self {
            client: InvocationServiceClient::new(channel),
            timeout: DEFAULT_BASIL_TIMEOUT,
        })
    }
}

#[async_trait]
impl BasilInvoker for BasilGrpcInvoker {
    async fn invoke(&mut self, request: SealedRequest) -> Result<SealedResponse, BasilInvokeError> {
        let response = timeout(self.timeout, self.client.invoke(request))
            .await
            .map_err(|_| BasilInvokeError::Timeout)?;

        response
            .map(tonic::Response::into_inner)
            .map_err(|status| classify_status(&status))
    }
}

fn classify_status(status: &Status) -> BasilInvokeError {
    match status.code() {
        Code::Unavailable => BasilInvokeError::Unavailable(status.message().to_owned()),
        Code::DeadlineExceeded => BasilInvokeError::Timeout,
        Code::Internal | Code::Unknown => BasilInvokeError::Internal(status.message().to_owned()),
        _ => BasilInvokeError::Rejected(status.message().to_owned()),
    }
}

async fn uds_channel(path: &Path, connect_timeout: Duration) -> Result<Channel, RuntimeError> {
    let path = path.to_path_buf();
    let endpoint = Endpoint::try_from("http://[::]:50051")?.connect_timeout(connect_timeout);
    endpoint
        .connect_with_connector(service_fn(move |_: Uri| {
            let path = path.clone();
            async move { UnixStream::connect(path).await.map(TokioIo::new) }
        }))
        .await
        .map_err(RuntimeError::Endpoint)
}

/// Run the bridge until the NATS subscription ends or a runtime error occurs.
///
/// Reply-publish failures are logged and do not stop the bridge.
///
/// # Errors
///
/// Returns an error when NATS/Basil setup fails, a request worker panics, or
/// the subscription stream ends ([`RuntimeError::SubscriptionEnded`]), so an
/// on-failure supervisor restarts the bridge instead of seeing a clean exit.
#[allow(clippy::significant_drop_tightening)]
pub async fn run(config: Config) -> Result<(), RuntimeError> {
    let nats = connect_nats(&config).await?;
    let basil = BasilGrpcInvoker::connect(&config.basil.socket).await?;
    let mut subscriber = subscribe(&nats, &config).await?;
    let concurrency_limit = config.bridge.concurrency_limit;

    info!(
        request_subject = %config.bridge.request_subject,
        queue_group = ?config.bridge.queue_group,
        concurrency_limit,
        "Basil NATS bridge listening",
    );

    let mut tasks = JoinSet::new();
    while let Some(message) = subscriber.next().await {
        while tasks.len() >= concurrency_limit {
            drain_one_task(&mut tasks).await?;
        }
        let request = BridgeRequest {
            subject: message.subject.to_string(),
            reply: message.reply.map(|subject| subject.to_string()),
            payload: message.payload.to_vec(),
        };
        let nats = nats.clone();
        let mut basil = basil.clone();
        let max_message_bytes = config.bridge.max_message_bytes;
        tasks.spawn(async move {
            let action = handle_request(request, max_message_bytes, &mut basil).await;
            publish_action(&nats, action).await;
        });
    }
    while !tasks.is_empty() {
        drain_one_task(&mut tasks).await?;
    }
    Err(RuntimeError::SubscriptionEnded)
}

async fn drain_one_task(tasks: &mut JoinSet<()>) -> Result<(), RuntimeError> {
    if let Some(result) = tasks.join_next().await {
        result.map_err(RuntimeError::WorkerJoin)?;
    }
    Ok(())
}

async fn connect_nats(config: &Config) -> Result<async_nats::Client, RuntimeError> {
    let options = match &config.nats.creds {
        Some(creds) => {
            async_nats::ConnectOptions::new()
                .credentials_file(creds)
                .await?
        }
        None => async_nats::ConnectOptions::new(),
    };
    options
        .connect(config.nats.url.clone())
        .await
        .map_err(RuntimeError::NatsConnect)
}

async fn subscribe(
    nats: &async_nats::Client,
    config: &Config,
) -> Result<async_nats::Subscriber, RuntimeError> {
    match &config.bridge.queue_group {
        Some(queue_group) => nats
            .queue_subscribe(config.bridge.request_subject.clone(), queue_group.clone())
            .await
            .map_err(RuntimeError::NatsSubscribe),
        None => nats
            .subscribe(config.bridge.request_subject.clone())
            .await
            .map_err(RuntimeError::NatsSubscribe),
    }
}

/// Publish a bridge action, logging (not propagating) publish failures so one
/// failed reply cannot take down the whole bridge.
async fn publish_action(nats: &async_nats::Client, action: BridgeAction) {
    let (subject, result) = match action {
        BridgeAction::Reply(reply) if reply.headers.is_empty() => {
            debug!(reply_subject = %reply.subject, "forwarding sealed Basil response");
            let subject = reply.subject.clone();
            let result = nats
                .publish(reply.subject, Bytes::from(reply.payload))
                .await;
            (subject, result)
        }
        BridgeAction::Reply(reply) => {
            warn!(
                reply_subject = %reply.subject,
                error = reply.headers.get(ERROR_HEADER).unwrap_or("UNKNOWN"),
                "replying with bridge-level error",
            );
            let subject = reply.subject.clone();
            let result = nats
                .publish_with_headers(reply.subject, to_nats_headers(&reply.headers), Bytes::new())
                .await;
            (subject, result)
        }
        BridgeAction::NoReply(error) => {
            warn!(
                error = error.code.as_token(),
                message = %error.message,
                "dropping request because no NATS reply subject was present",
            );
            return;
        }
    };
    if let Err(publish_error) = result {
        error!(
            reply_subject = %subject,
            error = %publish_error,
            "reply publish failed; dropping the reply and keeping the bridge alive",
        );
    }
}

fn to_nats_headers(headers: &BridgeHeaders) -> async_nats::HeaderMap {
    let mut nats_headers = async_nats::HeaderMap::new();
    for (name, value) in headers.iter() {
        nats_headers.insert(name, value);
    }
    nats_headers
}

/// Runtime setup and transport error.
#[derive(Debug, Error)]
pub enum RuntimeError {
    /// Basil gRPC endpoint construction failed.
    #[error("Basil endpoint configuration failed: {0}")]
    EndpointConfig(#[from] tonic::transport::Error),
    /// Basil gRPC Unix socket connection failed.
    #[error("Basil socket connection failed: {0}")]
    Endpoint(tonic::transport::Error),
    /// NATS credentials file could not be loaded.
    #[error("NATS credentials file could not be loaded: {0}")]
    NatsCredentials(#[from] std::io::Error),
    /// NATS connection failed.
    #[error("NATS connection failed: {0}")]
    NatsConnect(async_nats::ConnectError),
    /// NATS subscription failed.
    #[error("NATS subscription failed: {0}")]
    NatsSubscribe(async_nats::SubscribeError),
    /// The NATS subscription stream ended; the bridge can no longer serve
    /// requests and a supervisor should restart it.
    #[error("NATS subscription stream ended")]
    SubscriptionEnded,
    /// Request worker failed.
    #[error("bridge request worker failed: {0}")]
    WorkerJoin(tokio::task::JoinError),
}

#[cfg(test)]
mod tests {
    #![allow(clippy::missing_panics_doc, clippy::unwrap_used)]

    use super::*;
    use basil_proto::KeyType;
    use basil_proto::broker::v1::{GetSecretResponse, ImportRequest, KeyMaterial, key_material};

    const VALID_CONFIG: &str = r#"
[nats]
url = "nats://127.0.0.1:4222"
creds = "/run/basil/bridge.creds"

[basil]
socket = "/run/basil/basil.sock"

[bridge]
request-subject = "basil.invocation"
queue-group = "basil-bridge"
max-message-bytes = 1048576
concurrency-limit = 8
"#;

    #[derive(Debug)]
    struct FakeBasil {
        result: Result<SealedResponse, BasilInvokeError>,
        received: Vec<SealedRequest>,
    }

    impl FakeBasil {
        fn ok(response: SealedResponse) -> Self {
            Self {
                result: Ok(response),
                received: Vec::new(),
            }
        }

        fn err(error: BasilInvokeError) -> Self {
            Self {
                result: Err(error),
                received: Vec::new(),
            }
        }
    }

    #[async_trait]
    impl BasilInvoker for FakeBasil {
        async fn invoke(
            &mut self,
            request: SealedRequest,
        ) -> Result<SealedResponse, BasilInvokeError> {
            self.received.push(request);
            self.result.clone()
        }
    }

    #[test]
    fn parses_valid_config() {
        let config = Config::from_toml_str(VALID_CONFIG).unwrap();

        assert_eq!(config.nats.url, "nats://127.0.0.1:4222");
        assert_eq!(
            config.nats.creds.as_deref(),
            Some(Path::new("/run/basil/bridge.creds"))
        );
        assert_eq!(config.basil.socket, PathBuf::from("/run/basil/basil.sock"));
        assert_eq!(config.bridge.request_subject, "basil.invocation");
        assert_eq!(config.bridge.queue_group.as_deref(), Some("basil-bridge"));
        assert_eq!(config.bridge.max_message_bytes, 1_048_576);
        assert_eq!(config.bridge.concurrency_limit, 8);
    }

    #[test]
    fn parses_config_without_optional_creds_or_queue_group() {
        let config = Config::from_toml_str(
            r#"
[nats]
url = "nats://127.0.0.1:4222"

[basil]
socket = "/run/basil/basil.sock"

[bridge]
request-subject = "basil.invocation"
max-message-bytes = 4096
"#,
        )
        .unwrap();

        assert_eq!(config.nats.creds, None);
        assert_eq!(config.bridge.queue_group, None);
        assert_eq!(config.bridge.concurrency_limit, DEFAULT_CONCURRENCY_LIMIT);
    }

    #[test]
    fn rejects_zero_concurrency_limit() {
        let error = Config::from_toml_str(
            r#"
[nats]
url = "nats://127.0.0.1:4222"

[basil]
socket = "/run/basil/basil.sock"

[bridge]
request-subject = "basil.invocation"
max-message-bytes = 1024
concurrency-limit = 0
"#,
        )
        .unwrap_err();

        assert!(matches!(
            error,
            ConfigError::InvalidConcurrencyLimit { value: 0 }
        ));
    }

    #[test]
    fn rejects_empty_config_fields() {
        let error = Config::from_toml_str(
            r#"
[nats]
url = " "

[basil]
socket = "/run/basil/basil.sock"

[bridge]
request-subject = "basil.invocation"
max-message-bytes = 1024
"#,
        )
        .unwrap_err();

        assert!(matches!(error, ConfigError::EmptyField("nats.url")));
    }

    #[test]
    fn rejects_invalid_message_size_bounds() {
        let error = Config::from_toml_str(
            r#"
[nats]
url = "nats://127.0.0.1:4222"

[basil]
socket = "/run/basil/basil.sock"

[bridge]
request-subject = "basil.invocation"
max-message-bytes = 0
"#,
        )
        .unwrap_err();

        assert!(matches!(
            error,
            ConfigError::InvalidMaxMessageBytes { value: 0, .. }
        ));
    }

    #[tokio::test]
    async fn forwards_raw_bytes_and_returns_raw_response_without_error_headers() {
        let request_payload = b"\xd2\x84raw tagged cose request".to_vec();
        let response_payload = b"\xd2\x84raw tagged cose response".to_vec();
        let mut basil = FakeBasil::ok(sealed_response(&response_payload));

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.1".to_owned()),
                payload: request_payload.clone(),
            },
            1024,
            &mut basil,
        )
        .await;

        assert_eq!(basil.received, vec![sealed_request(&request_payload)]);
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.subject, "_INBOX.1");
        assert_eq!(reply.payload, response_payload);
        assert!(reply.headers.is_empty());
    }

    #[tokio::test]
    async fn response_subject_overrides_nats_reply_subject() {
        let mut basil = FakeBasil::ok(sealed_response_to(
            b"sealed response",
            Some("tenant.reply.inbox"),
        ));

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.original".to_owned()),
                payload: b"sealed request".to_vec(),
            },
            1024,
            &mut basil,
        )
        .await;

        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.subject, "tenant.reply.inbox");
        assert_eq!(reply.payload.as_slice(), b"sealed response");
        assert!(reply.headers.is_empty());
    }

    #[tokio::test]
    async fn import_key_request_body_is_forwarded_as_opaque_cose_payload() {
        let import_body = import_key_request_body();
        assert!(bytes_contain(
            &import_body,
            b"import-seed-material-remains-secret"
        ));
        let response = sealed_response(b"sealed response");
        let mut basil = FakeBasil::ok(response);

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.import".to_owned()),
                payload: import_body.clone(),
            },
            4096,
            &mut basil,
        )
        .await;

        assert_eq!(basil.received, vec![sealed_request(&import_body)]);
        let received = basil
            .received
            .first()
            .expect("bridge forwarded one request");
        assert_eq!(received.message, import_body);
        assert!(bytes_contain(
            &received.message,
            b"import-seed-material-remains-secret"
        ));
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert!(reply.headers.is_empty());
        assert_eq!(reply.payload.as_slice(), b"sealed response");
    }

    #[tokio::test]
    async fn get_secret_response_body_is_returned_as_opaque_cose_payload() {
        let secret_body = get_secret_response_body();
        assert!(bytes_contain(&secret_body, b"secret-response-value"));
        let mut basil = FakeBasil::ok(sealed_response(&secret_body));

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.secret".to_owned()),
                payload: b"sealed request".to_vec(),
            },
            4096,
            &mut basil,
        )
        .await;

        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert!(reply.headers.is_empty());
        assert_eq!(reply.payload, secret_body);
        assert!(bytes_contain(&reply.payload, b"secret-response-value"));
    }

    #[tokio::test]
    async fn preserves_routing_metadata_in_error_reply_subject() {
        let mut basil = FakeBasil::err(BasilInvokeError::Unavailable("down".to_owned()));
        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.route".to_owned()),
                payload: b"sealed request".to_vec(),
            },
            1024,
            &mut basil,
        )
        .await;

        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.subject, "_INBOX.route");
        assert_error(&reply, BridgeErrorCode::BasilUnavailable, true);
    }

    #[tokio::test]
    async fn non_protobuf_payload_is_forwarded_without_cose_parsing() {
        let payload = b"not protobuf and not cose".to_vec();
        let mut basil = FakeBasil::ok(sealed_response(b"body"));
        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.1".to_owned()),
                payload: payload.clone(),
            },
            1024,
            &mut basil,
        )
        .await;

        assert_eq!(basil.received, vec![sealed_request(&payload)]);
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.payload.as_slice(), b"body");
        assert!(reply.headers.is_empty());
    }

    #[tokio::test]
    async fn adversarial_cose_payload_is_forwarded_byte_exact_without_local_claims_parsing() {
        let payload = adversarial_cose_like_payload();
        let mut basil = FakeBasil::ok(sealed_response(b"sealed response"));

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.original".to_owned()),
                payload: payload.clone(),
            },
            4096,
            &mut basil,
        )
        .await;

        assert_eq!(basil.received, vec![sealed_request(&payload)]);
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.subject, "_INBOX.original");
        assert_eq!(reply.payload.as_slice(), b"sealed response");
        assert!(reply.headers.is_empty());
    }

    #[tokio::test]
    async fn embedded_reply_and_grant_hints_cannot_override_signed_response_subject() {
        let payload = adversarial_cose_like_payload();
        let response_payload = b"payload response_subject=attacker.payload.reply".to_vec();
        let mut basil = FakeBasil::ok(sealed_response_to(
            &response_payload,
            Some("tenant.signed.reply"),
        ));

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.attacker".to_owned()),
                payload: payload.clone(),
            },
            4096,
            &mut basil,
        )
        .await;

        assert_eq!(basil.received, vec![sealed_request(&payload)]);
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.subject, "tenant.signed.reply");
        assert_eq!(reply.payload, response_payload);
        assert!(reply.headers.is_empty());
    }

    #[tokio::test]
    async fn basil_authorization_rejection_is_not_masked_by_bridge_grants() {
        let payload = adversarial_cose_like_payload();
        let mut basil = FakeBasil::err(BasilInvokeError::Rejected(
            "permission denied for actor".to_owned(),
        ));

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.original".to_owned()),
                payload: payload.clone(),
            },
            4096,
            &mut basil,
        )
        .await;

        assert_eq!(basil.received, vec![sealed_request(&payload)]);
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.subject, "_INBOX.original");
        assert_error(&reply, BridgeErrorCode::BasilRejected, false);
        assert_eq!(
            reply.headers.get(MESSAGE_HEADER),
            Some("permission denied for actor")
        );
    }

    #[tokio::test]
    async fn invalid_response_subject_returns_error_on_original_reply_subject() {
        for response_subject in ["", "not a subject", "tenant.*"] {
            let mut basil = FakeBasil::ok(sealed_response_to(
                b"sealed response",
                Some(response_subject),
            ));
            let action = handle_request(
                BridgeRequest {
                    subject: "basil.invocation".to_owned(),
                    reply: Some("_INBOX.original".to_owned()),
                    payload: b"sealed request".to_vec(),
                },
                1024,
                &mut basil,
            )
            .await;

            let BridgeAction::Reply(reply) = action else {
                panic!("expected reply");
            };
            assert_eq!(reply.subject, "_INBOX.original");
            assert_error(&reply, BridgeErrorCode::MalformedRequest, false);
        }
    }

    #[tokio::test]
    async fn invalid_basil_response_subject_error_ignores_payload_routing_hint() {
        let payload = adversarial_cose_like_payload();
        let mut basil = FakeBasil::ok(sealed_response_to(
            b"response_subject=attacker.payload.reply",
            Some("tenant.>"),
        ));

        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.original".to_owned()),
                payload: payload.clone(),
            },
            4096,
            &mut basil,
        )
        .await;

        assert_eq!(basil.received, vec![sealed_request(&payload)]);
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_eq!(reply.subject, "_INBOX.original");
        assert_error(&reply, BridgeErrorCode::MalformedRequest, false);
    }

    #[tokio::test]
    async fn too_large_message_returns_error_headers_without_basil_call() {
        let mut basil = FakeBasil::ok(sealed_response(b"body"));
        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.1".to_owned()),
                payload: vec![7; 9],
            },
            8,
            &mut basil,
        )
        .await;

        assert!(basil.received.is_empty());
        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        assert_error(&reply, BridgeErrorCode::MessageTooLarge, false);
    }

    #[tokio::test]
    async fn missing_reply_subject_is_reported_as_no_reply_action() {
        let mut basil = FakeBasil::ok(sealed_response(b"body"));
        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: None,
                payload: b"body".to_vec(),
            },
            1024,
            &mut basil,
        )
        .await;

        assert!(basil.received.is_empty());
        let BridgeAction::NoReply(error) = action else {
            panic!("expected no-reply action");
        };
        assert_eq!(error.code, BridgeErrorCode::MalformedRequest);
        assert!(!error.retryable);
    }

    #[tokio::test]
    async fn basil_rejection_maps_to_stable_error_headers() {
        let mut basil = FakeBasil::err(BasilInvokeError::Rejected("denied".to_owned()));
        let reply = invoke_error_reply(&mut basil).await;

        assert_error(&reply, BridgeErrorCode::BasilRejected, false);
    }

    #[tokio::test]
    async fn basil_timeout_maps_to_retryable_error_headers() {
        let mut basil = FakeBasil::err(BasilInvokeError::Timeout);
        let reply = invoke_error_reply(&mut basil).await;

        assert_error(&reply, BridgeErrorCode::Timeout, true);
    }

    #[tokio::test]
    async fn basil_unavailable_maps_to_retryable_error_headers() {
        let mut basil = FakeBasil::err(BasilInvokeError::Unavailable("socket closed".to_owned()));
        let reply = invoke_error_reply(&mut basil).await;

        assert_error(&reply, BridgeErrorCode::BasilUnavailable, true);
    }

    async fn invoke_error_reply(basil: &mut FakeBasil) -> BridgeReply {
        let action = handle_request(
            BridgeRequest {
                subject: "basil.invocation".to_owned(),
                reply: Some("_INBOX.1".to_owned()),
                payload: b"body".to_vec(),
            },
            1024,
            basil,
        )
        .await;

        let BridgeAction::Reply(reply) = action else {
            panic!("expected reply");
        };
        reply
    }

    fn assert_error(reply: &BridgeReply, code: BridgeErrorCode, retryable: bool) {
        assert_eq!(reply.payload, Vec::<u8>::new());
        assert_eq!(reply.headers.get(ERROR_HEADER), Some(code.as_token()));
        assert_eq!(
            reply.headers.get(RETRYABLE_HEADER),
            Some(if retryable { "true" } else { "false" })
        );
        assert!(reply.headers.get(MESSAGE_HEADER).is_some());
    }

    fn sealed_request(body: &[u8]) -> SealedRequest {
        SealedRequest {
            message: body.to_vec(),
        }
    }

    fn sealed_response(body: &[u8]) -> SealedResponse {
        sealed_response_to(body, None)
    }

    fn sealed_response_to(body: &[u8], subject: Option<&str>) -> SealedResponse {
        SealedResponse {
            message: body.to_vec(),
            response_subject: subject.map(str::to_owned),
        }
    }

    fn import_key_request_body() -> Vec<u8> {
        encode_proto(&ImportRequest {
            key_id: "tenant.imported.signing".to_owned(),
            key_type: KeyType::Ed25519 as i32,
            material: Some(KeyMaterial {
                material: Some(key_material::Material::Ed25519Seed(
                    b"import-seed-material-remains-secret".to_vec(),
                )),
            }),
        })
    }

    fn get_secret_response_body() -> Vec<u8> {
        encode_proto(&GetSecretResponse {
            value: b"secret-response-value".to_vec(),
            version: 7,
        })
    }

    fn adversarial_cose_like_payload() -> Vec<u8> {
        [
            &[
                0xD2, 0x84, 0xA5, 0x01, 0x27, 0x04, 0x58, 0x20, 0xA5, 0x5A, 0xC3, 0x0E,
            ][..],
            b"issuer=spiffe://tenant/service-a;",
            b"content-type=application/x-basil.sign-request+cbor;",
            b"kid=tenant.signing-key;",
            b"ciphertext=must-remain-opaque;",
            b"response-key=tenant.response-key;",
            b"response_subject=attacker.reply;",
            b"bridge-grant=sign:tenant/*",
        ]
        .concat()
    }

    fn encode_proto(message: &impl prost::Message) -> Vec<u8> {
        let mut bytes = Vec::new();
        message.encode(&mut bytes).unwrap();
        bytes
    }

    fn bytes_contain(haystack: &[u8], needle: &[u8]) -> bool {
        haystack
            .windows(needle.len())
            .any(|window| window == needle)
    }
}