pmcp-server-toolkit 0.1.0

Runtime library for config-driven MCP servers — auth, secrets, static resources/prompts, [[tools]] synthesizer, code-mode wiring
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
//! Authentication providers for OUTGOING HTTP requests (OAPI-03 / D-05 / H1).
//!
//! This module is the OUTBOUND counterpart to the inbound
//! [`crate::auth::AuthProvider`] (`pmcp::server::auth::AuthProvider`, which
//! authenticates an INCOMING MCP request). The two are kept deliberately
//! distinct (Pitfall 1): the trait here is [`HttpAuthProvider`] and its method
//! is [`apply`](HttpAuthProvider::apply) — it MUTATES the headers / query of a
//! request the toolkit is about to SEND to a REST backend. This module does NOT
//! re-implement the inbound request-validation surface.
//!
//! # The six auth modes (D-05) split into two construction strategies
//!
//! [`AuthConfig`] has SIX variants — `None` + five authenticated ones. They
//! split by HOW the credential is obtained:
//!
//! - **Static** (`None`/`ApiKey`/`Bearer`/`Basic`/`OAuth2ClientCredentials`):
//!   fully determined by `config.toml` (operator credentials / `${ENV}` secrets).
//!   Built ONCE at startup via [`create_auth_provider`] and shared as
//!   `Arc<dyn HttpAuthProvider>`. They IGNORE any inbound MCP client token.
//! - **Per-request passthrough** (`OAuthPassthrough`): needs the INCOMING MCP
//!   client token for EACH request, so it cannot be fully built at startup.
//!   [`apply`](HttpAuthProvider::apply) accepts an OPTIONAL `inbound_token` so a
//!   SINGLE trait serves both strategies — static providers ignore it,
//!   [`OAuthPassthroughAuth`] forwards it. Plan 04 carries the per-request token
//!   to `apply`; Plan 06 wires the inbound `TokenCaptureAuthProvider` so the
//!   captured token lands in `AuthContext` and is threaded into this `apply`.
//!
//! # Ownership
//!
//! [`AuthConfig`] and the provider types are OWNED HERE so Plan 01 and Plan 02
//! changes stay confined — Plan 02 RE-EXPORTS
//! `pmcp_server_toolkit::http::auth::AuthConfig` rather than redefining it.

use super::HttpConnectorError;
use async_trait::async_trait;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// Default `required` flag (true) for authenticated [`AuthConfig`] variants.
fn default_true() -> bool {
    true
}

/// Default outgoing header for [`AuthConfig::OAuthPassthrough`].
fn default_auth_header() -> String {
    "Authorization".to_string()
}

/// Outgoing-HTTP authentication configuration (OAPI-03 / D-05).
///
/// Lifted near-verbatim from the pmcp-run reference `AuthConfig`. The
/// `#[serde(tag = "type", rename_all = "snake_case")]` shape means a
/// `config.toml` `[backend.auth]` block selects the variant via `type = "..."`
/// (`none`, `api_key`, `bearer`, `basic`, `oauth2_client_credentials`,
/// `oauth_passthrough`). [`Default`] is [`AuthConfig::None`].
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthConfig {
    /// No authentication.
    #[default]
    None,

    /// API key passed as query parameters and/or headers.
    ApiKey {
        /// API key values carried as query parameters.
        #[serde(default)]
        query_params: HashMap<String, String>,
        /// API key values carried as headers.
        #[serde(default)]
        headers: HashMap<String, String>,
        /// Whether authentication is required.
        #[serde(default = "default_true")]
        required: bool,
    },

    /// Bearer token (`Authorization: Bearer <token>`).
    Bearer {
        /// Token value. Supports a `${VAR}` or `env:VAR` reference resolved from
        /// the process environment at provider-build time (an unset reference
        /// collapses to no-auth; the literal placeholder never reaches the wire).
        token: String,
        /// Whether authentication is required.
        #[serde(default = "default_true")]
        required: bool,
    },

    /// HTTP Basic auth (`Authorization: Basic <base64(user:pass)>`).
    Basic {
        /// Username. Supports a `${VAR}` / `env:VAR` reference (resolved at
        /// provider-build time) for symmetry with `password`.
        username: String,
        /// Password. Supports a `${VAR}` or `env:VAR` reference resolved from the
        /// process environment at provider-build time (the literal placeholder
        /// never reaches the wire).
        password: String,
        /// Whether authentication is required.
        #[serde(default = "default_true")]
        required: bool,
    },

    /// OAuth2 client-credentials grant.
    ///
    /// `rename_all = "snake_case"` derives the tag `o_auth2_client_credentials`,
    /// but the documented config form (README, line-56 doc comment) is
    /// `type = "oauth2_client_credentials"`. The alias accepts the documented
    /// spelling so `[backend.auth]` configs deserialize as documented.
    #[serde(alias = "oauth2_client_credentials")]
    OAuth2ClientCredentials {
        /// Token endpoint URL.
        token_url: String,
        /// Client ID. Supports a `${VAR}` / `env:VAR` reference resolved at
        /// provider-build time.
        client_id: String,
        /// Client secret. Supports a `${VAR}` or `env:VAR` reference resolved from
        /// the process environment at provider-build time (the literal
        /// placeholder never reaches the token endpoint).
        client_secret: String,
        /// Requested scopes.
        #[serde(default)]
        scopes: Vec<String>,
        /// Whether authentication is required.
        #[serde(default = "default_true")]
        required: bool,
    },

    /// Forward the INCOMING MCP client token to the backend (SSO passthrough, H1).
    ///
    /// `rename_all = "snake_case"` derives the tag `o_auth_passthrough`, but the
    /// documented config form (README, line-56 doc comment) is
    /// `type = "oauth_passthrough"`. The alias accepts the documented spelling so
    /// `[backend.auth]` configs deserialize as documented.
    #[serde(alias = "oauth_passthrough")]
    OAuthPassthrough {
        /// Outgoing header to set (default `Authorization`).
        #[serde(default = "default_auth_header")]
        target_header: String,
        /// Whether to fail when no inbound token is present.
        #[serde(default = "default_true")]
        required: bool,
    },
}

impl AuthConfig {
    /// Whether this configuration requires authentication to succeed.
    #[must_use]
    pub fn is_required(&self) -> bool {
        match self {
            Self::None => false,
            Self::ApiKey { required, .. }
            | Self::Bearer { required, .. }
            | Self::Basic { required, .. }
            | Self::OAuth2ClientCredentials { required, .. }
            | Self::OAuthPassthrough { required, .. } => *required,
        }
    }
}

/// Outbound HTTP authentication provider (OAPI-03).
///
/// DISTINCT from the inbound [`crate::auth::AuthProvider`] (Pitfall 1): this
/// MUTATES the outgoing request. [`apply`](HttpAuthProvider::apply) accepts an
/// OPTIONAL `inbound_token` — the per-request MCP client token captured via the
/// `AuthContext` bridge (H1). Static providers ignore it; the passthrough
/// provider forwards it.
#[async_trait]
pub trait HttpAuthProvider: Send + Sync + 'static {
    /// Apply credentials to the outgoing request's `headers` and `query`.
    ///
    /// `inbound_token` is the per-request MCP client token (when present). Static
    /// providers MUST ignore it; [`OAuthPassthroughAuth`] forwards it.
    ///
    /// # Errors
    ///
    /// Returns [`HttpConnectorError::Auth`] when a required credential is absent,
    /// or [`HttpConnectorError::InvalidHeader`] when a header name/value cannot be
    /// constructed. No error message echoes the token or credential value.
    async fn apply(
        &self,
        headers: &mut HeaderMap,
        query: &mut HashMap<String, String>,
        inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError>;
}

/// No authentication — a no-op provider.
pub struct NoAuth;

#[async_trait]
impl HttpAuthProvider for NoAuth {
    async fn apply(
        &self,
        _headers: &mut HeaderMap,
        _query: &mut HashMap<String, String>,
        _inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError> {
        Ok(())
    }
}

/// Provider that always fails — used when a required passthrough token is absent.
pub struct MissingTokenAuth;

#[async_trait]
impl HttpAuthProvider for MissingTokenAuth {
    async fn apply(
        &self,
        _headers: &mut HeaderMap,
        _query: &mut HashMap<String, String>,
        inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError> {
        // Honour a late-arriving per-request token if the static constructor was
        // built without one (the passthrough construction-time fallback).
        if inbound_token.map(str::is_empty) == Some(false) {
            return Ok(());
        }
        Err(HttpConnectorError::Auth(
            "authentication required but no inbound token was provided".to_string(),
        ))
    }
}

/// API key authentication (query params and/or headers). STATIC: ignores `inbound_token`.
pub struct ApiKeyAuth {
    query_params: HashMap<String, String>,
    headers: HashMap<String, String>,
}

#[async_trait]
impl HttpAuthProvider for ApiKeyAuth {
    async fn apply(
        &self,
        headers: &mut HeaderMap,
        query: &mut HashMap<String, String>,
        _inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError> {
        for (key, value) in &self.query_params {
            query.insert(key.clone(), value.clone());
        }
        for (key, value) in &self.headers {
            let name = HeaderName::try_from(key.as_str()).map_err(|_| {
                HttpConnectorError::InvalidHeader("invalid header name".to_string())
            })?;
            let val = HeaderValue::try_from(value.as_str()).map_err(|_| {
                HttpConnectorError::InvalidHeader("invalid header value".to_string())
            })?;
            headers.insert(name, val);
        }
        Ok(())
    }
}

/// Bearer token authentication. STATIC: ignores `inbound_token`.
pub struct BearerAuth {
    token: String,
}

#[async_trait]
impl HttpAuthProvider for BearerAuth {
    async fn apply(
        &self,
        headers: &mut HeaderMap,
        _query: &mut HashMap<String, String>,
        _inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError> {
        let value = format!("Bearer {}", self.token);
        let header_value = HeaderValue::try_from(value)
            .map_err(|_| HttpConnectorError::InvalidHeader("invalid bearer token".to_string()))?;
        headers.insert(reqwest::header::AUTHORIZATION, header_value);
        Ok(())
    }
}

/// HTTP Basic authentication. STATIC: ignores `inbound_token`.
pub struct BasicAuth {
    username: String,
    password: String,
}

#[async_trait]
impl HttpAuthProvider for BasicAuth {
    async fn apply(
        &self,
        headers: &mut HeaderMap,
        _query: &mut HashMap<String, String>,
        _inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError> {
        use base64::Engine;
        let credentials = format!("{}:{}", self.username, self.password);
        let encoded = base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes());
        let value = format!("Basic {encoded}");
        let header_value = HeaderValue::try_from(value).map_err(|_| {
            HttpConnectorError::InvalidHeader("invalid basic credentials".to_string())
        })?;
        headers.insert(reqwest::header::AUTHORIZATION, header_value);
        Ok(())
    }
}

/// OAuth2 client-credentials authentication. STATIC config; ignores `inbound_token`.
///
/// The token is fetched lazily from `token_url` on first `apply` and cached. The
/// fetch uses a fresh `reqwest::Client` (mirrors the reference). The cached token
/// is stored under a `tokio::sync::RwLock`.
pub struct OAuth2ClientCredentialsAuth {
    token_url: String,
    client_id: String,
    client_secret: String,
    scopes: Vec<String>,
    cached: tokio::sync::RwLock<Option<String>>,
}

impl OAuth2ClientCredentialsAuth {
    /// Construct a client-credentials provider (no network until first `apply`).
    #[must_use]
    pub fn new(
        token_url: String,
        client_id: String,
        client_secret: String,
        scopes: Vec<String>,
    ) -> Self {
        Self {
            token_url,
            client_id,
            client_secret,
            scopes,
            cached: tokio::sync::RwLock::new(None),
        }
    }

    async fn fetch_token(&self) -> Result<String, HttpConnectorError> {
        let client = reqwest::Client::new();
        let mut params = vec![
            ("grant_type", "client_credentials".to_string()),
            ("client_id", self.client_id.clone()),
            ("client_secret", self.client_secret.clone()),
        ];
        if !self.scopes.is_empty() {
            params.push(("scope", self.scopes.join(" ")));
        }
        let response = client
            .post(&self.token_url)
            .form(&params)
            .send()
            .await
            .map_err(|_| HttpConnectorError::Auth("oauth2 token request failed".to_string()))?;
        if !response.status().is_success() {
            return Err(HttpConnectorError::Auth(format!(
                "oauth2 token endpoint returned status {}",
                response.status().as_u16()
            )));
        }
        #[derive(Deserialize)]
        struct TokenResponse {
            access_token: String,
        }
        let token: TokenResponse = response.json().await.map_err(|_| {
            HttpConnectorError::Auth("oauth2 token response unparseable".to_string())
        })?;
        Ok(token.access_token)
    }
}

#[async_trait]
impl HttpAuthProvider for OAuth2ClientCredentialsAuth {
    async fn apply(
        &self,
        headers: &mut HeaderMap,
        _query: &mut HashMap<String, String>,
        _inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError> {
        {
            let cached = self.cached.read().await;
            if cached.is_none() {
                drop(cached);
                let fetched = self.fetch_token().await?;
                *self.cached.write().await = Some(fetched);
            }
        }
        let cached = self.cached.read().await;
        if let Some(access_token) = cached.as_ref() {
            let value = format!("Bearer {access_token}");
            let header_value = HeaderValue::try_from(value).map_err(|_| {
                HttpConnectorError::InvalidHeader("invalid oauth2 access token".to_string())
            })?;
            headers.insert(reqwest::header::AUTHORIZATION, header_value);
        }
        Ok(())
    }
}

/// OAuth passthrough — forwards the INCOMING MCP client token to the backend (H1).
///
/// PER-REQUEST: prefers the per-request `inbound_token` arg to `apply`; falls back
/// to the construction-time captured `incoming_token` (via
/// [`create_passthrough_auth_provider`]). When neither is present and the config
/// is `required`, `apply` returns [`HttpConnectorError::Auth`].
///
/// # Trust boundary (WR-04)
///
/// This provider relays a **client-controlled** value into an
/// **operator-controlled** destination — the trust posture is intentional and
/// must stay visible at the type:
///
/// - The MCP **client controls the forwarded token VALUE**: it is the raw
///   inbound `Authorization` header captured by `TokenCaptureAuthProvider` and
///   forwarded verbatim (bare tokens are prefixed with `Bearer ` in [`apply`]).
/// - The **operator controls the destination header NAME** (`target_header`),
///   fixed in the committed config; the client cannot redirect the token to a
///   different header.
///
/// Relaying the client's own credential to the backend is the **intended**
/// SSO-passthrough behavior — use it only when the backend should receive the
/// MCP client's own identity. The `HeaderValue::try_from` control-character
/// rejection in [`apply`] is the protection against header injection; a
/// malformed token value is rejected, not relayed.
///
/// [`apply`]: OAuthPassthroughAuth::apply
pub struct OAuthPassthroughAuth {
    target_header: String,
    incoming_token: Option<String>,
    required: bool,
}

#[async_trait]
impl HttpAuthProvider for OAuthPassthroughAuth {
    async fn apply(
        &self,
        headers: &mut HeaderMap,
        _query: &mut HashMap<String, String>,
        inbound_token: Option<&str>,
    ) -> Result<(), HttpConnectorError> {
        // Prefer the per-request token; fall back to the construction-time capture.
        let token: Option<&str> = inbound_token
            .filter(|t| !t.is_empty())
            .or_else(|| self.incoming_token.as_deref().filter(|t| !t.is_empty()));

        match token {
            Some(tok) => {
                let header_name =
                    HeaderName::try_from(self.target_header.as_str()).map_err(|_| {
                        HttpConnectorError::InvalidHeader(
                            "invalid passthrough target header".to_string(),
                        )
                    })?;
                // Forward the token verbatim if it already carries a scheme,
                // otherwise prefix with "Bearer ".
                let value = if tok.starts_with("Bearer ") || tok.starts_with("Basic ") {
                    tok.to_string()
                } else {
                    format!("Bearer {tok}")
                };
                let header_value = HeaderValue::try_from(value).map_err(|_| {
                    HttpConnectorError::InvalidHeader("invalid passthrough token value".to_string())
                })?;
                // TRUST BOUNDARY (WR-04): we relay a CLIENT-controlled value
                // (`tok`, the raw inbound Authorization header captured by
                // TokenCaptureAuthProvider) into an OPERATOR-controlled
                // destination (`header_name`, from the committed `target_header`).
                // Forwarding the client's own credential is INTENDED SSO
                // passthrough — use only when the backend should receive the MCP
                // client's identity. The HeaderValue::try_from guard above is the
                // protection: it rejects control chars, so a malformed token is
                // rejected rather than injected. See the type doc-comment.
                headers.insert(header_name, header_value);
                Ok(())
            },
            None if self.required => Err(HttpConnectorError::Auth(
                "passthrough authentication required but no inbound token was provided".to_string(),
            )),
            None => Ok(()),
        }
    }
}

/// Build a STATIC auth provider from `cfg`, shared as `Arc<dyn HttpAuthProvider>`.
///
/// For [`AuthConfig::OAuthPassthrough`], use [`create_passthrough_auth_provider`]
/// instead — without a token this returns a [`MissingTokenAuth`] (if required) or
/// [`NoAuth`], since the per-request token is not yet known at startup.
///
/// # Errors
///
/// This constructor never fails today (returns `Ok`) — the fallible signature is
/// reserved so a future variant requiring construction-time validation can error
/// without a breaking change.
/// The single brace/env-ref parse core shared by EVERY credential-resolution
/// path (api_key, bearer token, basic password, oauth2 client_secret).
///
/// Returns `Some(var_name)` when `raw` is a secret REFERENCE — either the
/// `"env:VAR"` or the `"${VAR}"` form — and `None` for a plain literal (which the
/// caller uses verbatim). A malformed brace reference (e.g. `"${}"`) is treated
/// as a reference to an empty name, i.e. `Some("")`, so the caller resolves it to
/// the empty string (omission) rather than shipping the literal `${}`.
///
/// This consolidates the two brace parsers that previously existed (the inline
/// `${`-strip in the old api_key resolver here and `expand_braced_var` in
/// `crate::code_mode`): all credential resolution now flows through this one
/// chokepoint so the env-ref discipline cannot drift per-variant.
fn parse_env_ref(raw: &str) -> Option<&str> {
    if let Some(v) = raw.strip_prefix("env:") {
        Some(v)
    } else {
        // `${...}` → the inner name (possibly empty for the malformed `${}` form).
        raw.strip_prefix("${").and_then(|s| s.strip_suffix('}'))
    }
}

/// Resolve a single credential value, expanding a `${VAR}` or `env:VAR` reference
/// from the process environment — the ONE chokepoint applied to every credential
/// field (api_key, bearer `token`, basic `password`, oauth2 `client_secret`) as
/// it enters [`create_auth_provider`].
///
/// A credential frequently holds a secret reference (`"${GITHUB_PAT}"`) rather
/// than a literal — mirroring the `token_secret` convention in
/// [`crate::code_mode`]. Without expansion the LITERAL `${GITHUB_PAT}` would be
/// sent to the backend, so 100% of authenticated calls would fail (this is a
/// correctness requirement, not a convenience).
///
/// Resolution rules (matching the `token_secret` env-ref discipline):
/// - `"${VAR}"` / `"env:VAR"` → the value of `VAR` from the process env.
/// - An UNSET or set-but-empty/whitespace `VAR` resolves to an empty string, so
///   a `required = false` credential is OMITTED rather than sent as a degenerate
///   empty/placeholder value (each variant's existing empty→`NoAuth` check then
///   collapses the provider to no-auth — the correct failure mode, NOT shipping
///   the literal `${...}`).
/// - A plain literal (no `${...}` / `env:` prefix) is returned verbatim.
/// - A malformed reference (e.g. `"${}"`) resolves to an empty string.
///
/// No error path: an unresolvable reference yields an empty string (omission),
/// never a panic and never the literal `${...}` reaching the wire.
fn resolve_secret_ref(raw: &str) -> String {
    match parse_env_ref(raw) {
        // Plain literal — used verbatim.
        None => raw.to_string(),
        // Malformed reference (e.g. `"${}"`) → empty (omitted).
        Some(name) if name.is_empty() => String::new(),
        Some(name) => std::env::var(name)
            .ok()
            .filter(|v| !v.trim().is_empty())
            .unwrap_or_default(),
    }
}

/// Expand every value in an api_key map, dropping entries that resolve to empty
/// (an unset `required = false` reference is omitted, not sent empty).
fn expand_api_key_map(map: &HashMap<String, String>) -> HashMap<String, String> {
    map.iter()
        .filter_map(|(k, v)| {
            let resolved = resolve_secret_ref(v);
            (!resolved.is_empty()).then(|| (k.clone(), resolved))
        })
        .collect()
}

pub fn create_auth_provider(
    cfg: &AuthConfig,
) -> Result<Arc<dyn HttpAuthProvider>, HttpConnectorError> {
    let provider: Arc<dyn HttpAuthProvider> = match cfg {
        AuthConfig::None => Arc::new(NoAuth),
        AuthConfig::ApiKey {
            query_params,
            headers,
            ..
        } => {
            // Expand `${VAR}` / `env:VAR` references BEFORE building the provider
            // so the RESOLVED secret (not the literal placeholder) is applied to
            // outgoing requests. Unset references are dropped (omitted).
            let query_params = expand_api_key_map(query_params);
            let headers = expand_api_key_map(headers);
            let has_values = query_params.values().any(|v| !v.is_empty())
                || headers.values().any(|v| !v.is_empty());
            if has_values {
                Arc::new(ApiKeyAuth {
                    query_params,
                    headers,
                })
            } else {
                Arc::new(NoAuth)
            }
        },
        AuthConfig::Bearer { token, .. } => {
            // Resolve `${VAR}` / `env:VAR` BEFORE the empty-check so the RESOLVED
            // token (never the literal placeholder) reaches the wire; an unset
            // ref collapses to NoAuth (the correct failure mode).
            let token = resolve_secret_ref(token);
            if token.is_empty() {
                Arc::new(NoAuth)
            } else {
                Arc::new(BearerAuth { token })
            }
        },
        AuthConfig::Basic {
            username, password, ..
        } => {
            // Resolve both fields (username typically not a secret, but support
            // `${VAR}` for symmetry) BEFORE the empty-check.
            let username = resolve_secret_ref(username);
            let password = resolve_secret_ref(password);
            if username.is_empty() && password.is_empty() {
                Arc::new(NoAuth)
            } else {
                Arc::new(BasicAuth { username, password })
            }
        },
        AuthConfig::OAuth2ClientCredentials {
            token_url,
            client_id,
            client_secret,
            scopes,
            ..
        } => {
            // Resolve client_id + client_secret BEFORE the empty-check so the
            // RESOLVED secret (never the literal placeholder) is sent to the token
            // endpoint; an unset ref collapses to NoAuth.
            let client_id = resolve_secret_ref(client_id);
            let client_secret = resolve_secret_ref(client_secret);
            if client_id.is_empty() || client_secret.is_empty() {
                Arc::new(NoAuth)
            } else {
                Arc::new(OAuth2ClientCredentialsAuth::new(
                    token_url.clone(),
                    client_id,
                    client_secret,
                    scopes.clone(),
                ))
            }
        },
        AuthConfig::OAuthPassthrough { required, .. } => {
            if *required {
                Arc::new(MissingTokenAuth)
            } else {
                Arc::new(NoAuth)
            }
        },
    };
    Ok(provider)
}

/// Build an auth provider, capturing an `incoming_token` for the
/// [`AuthConfig::OAuthPassthrough`] per-request path (H1).
///
/// For passthrough configs the captured token is stored and forwarded by
/// [`OAuthPassthroughAuth::apply`] (preferring a per-request `inbound_token` when
/// one is also passed to `apply`). For all other configs this delegates to
/// [`create_auth_provider`].
///
/// # Errors
///
/// Propagates any error from [`create_auth_provider`] for non-passthrough configs.
pub fn create_passthrough_auth_provider(
    cfg: &AuthConfig,
    incoming_token: Option<String>,
) -> Result<Arc<dyn HttpAuthProvider>, HttpConnectorError> {
    match cfg {
        AuthConfig::OAuthPassthrough {
            target_header,
            required,
        } => Ok(Arc::new(OAuthPassthroughAuth {
            target_header: target_header.clone(),
            incoming_token: incoming_token.filter(|t| !t.is_empty()),
            required: *required,
        })),
        other => create_auth_provider(other),
    }
}

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

    #[tokio::test]
    async fn test_no_auth() {
        let auth = create_auth_provider(&AuthConfig::None).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert!(headers.is_empty());
        assert!(query.is_empty());
    }

    #[tokio::test]
    async fn test_bearer_auth() {
        let cfg = AuthConfig::Bearer {
            token: "my_token".to_string(),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        // inbound_token is ignored by a static provider.
        auth.apply(&mut headers, &mut query, Some("client-tok"))
            .await
            .unwrap();
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            "Bearer my_token"
        );
        assert!(query.is_empty());
    }

    #[tokio::test]
    async fn test_basic_auth() {
        let cfg = AuthConfig::Basic {
            username: "user".to_string(),
            password: "pass".to_string(),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        // base64("user:pass") = "dXNlcjpwYXNz"
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            "Basic dXNlcjpwYXNz"
        );
    }

    #[tokio::test]
    async fn test_api_key_query_param() {
        // D-04 london-tube path: api key carried as a query param (app_key).
        let cfg = AuthConfig::ApiKey {
            query_params: [("app_key".to_string(), "secret123".to_string())]
                .into_iter()
                .collect(),
            headers: HashMap::new(),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert_eq!(query.get("app_key"), Some(&"secret123".to_string()));
        assert!(
            headers.is_empty(),
            "api-key-in-query must not touch headers"
        );
    }

    #[tokio::test]
    async fn test_api_key_query_param_expands_braced_env_ref() {
        // The RESOLVED ${VAR} value (not the literal `${...}`) reaches the wire.
        let var = "PMCP_TEST_TFL_APP_KEY_BRACED";
        std::env::set_var(var, "dummy");
        let cfg = AuthConfig::ApiKey {
            query_params: [("app_key".to_string(), format!("${{{var}}}"))]
                .into_iter()
                .collect(),
            headers: HashMap::new(),
            required: false,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert_eq!(
            query.get("app_key"),
            Some(&"dummy".to_string()),
            "resolved env value lands on the query, not the literal ${{...}}"
        );
        std::env::remove_var(var);
    }

    #[tokio::test]
    async fn test_api_key_query_param_unset_ref_is_omitted() {
        // required=false + an UNSET ${VAR} → the param is omitted (not sent
        // empty, not the literal placeholder).
        let var = "PMCP_TEST_TFL_APP_KEY_UNSET";
        std::env::remove_var(var);
        let cfg = AuthConfig::ApiKey {
            query_params: [("app_key".to_string(), format!("${{{var}}}"))]
                .into_iter()
                .collect(),
            headers: HashMap::new(),
            required: false,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert!(
            !query.contains_key("app_key"),
            "an unset required=false api_key ref is omitted, not sent empty/literal"
        );
    }

    #[test]
    fn test_resolve_api_key_value_forms() {
        // api_key now resolves through the shared `resolve_secret_ref` chokepoint.
        let var = "PMCP_TEST_RESOLVE_API_KEY_FORM";
        std::env::set_var(var, "resolved");
        assert_eq!(resolve_secret_ref(&format!("${{{var}}}")), "resolved");
        assert_eq!(resolve_secret_ref(&format!("env:{var}")), "resolved");
        assert_eq!(resolve_secret_ref("plain-literal"), "plain-literal");
        std::env::remove_var(var);
        assert_eq!(resolve_secret_ref(&format!("${{{var}}}")), "");
        assert_eq!(resolve_secret_ref("${}"), "");
    }

    #[tokio::test]
    async fn test_passthrough_forwards_inbound_token() {
        // H1 per-request path: passthrough forwards the inbound token.
        let cfg = AuthConfig::OAuthPassthrough {
            target_header: "Authorization".to_string(),
            required: true,
        };
        let auth = create_passthrough_auth_provider(&cfg, None).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, Some("client-tok"))
            .await
            .unwrap();
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            "Bearer client-tok"
        );
    }

    #[tokio::test]
    async fn test_passthrough_custom_target_header() {
        let cfg = AuthConfig::OAuthPassthrough {
            target_header: "X-Forwarded-Token".to_string(),
            required: true,
        };
        let auth = create_passthrough_auth_provider(&cfg, None).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, Some("client-tok"))
            .await
            .unwrap();
        assert_eq!(
            headers.get("X-Forwarded-Token").unwrap(),
            "Bearer client-tok"
        );
    }

    #[tokio::test]
    async fn test_passthrough_uses_construction_time_token() {
        // Construction-time capture path: inbound_token=None falls back to stored.
        let cfg = AuthConfig::OAuthPassthrough {
            target_header: "Authorization".to_string(),
            required: true,
        };
        let auth =
            create_passthrough_auth_provider(&cfg, Some("captured-tok".to_string())).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            "Bearer captured-tok"
        );
    }

    #[tokio::test]
    async fn test_passthrough_required_missing_token_errors() {
        let cfg = AuthConfig::OAuthPassthrough {
            target_header: "Authorization".to_string(),
            required: true,
        };
        let auth = create_passthrough_auth_provider(&cfg, None).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        let err = auth
            .apply(&mut headers, &mut query, None)
            .await
            .unwrap_err();
        assert!(matches!(err, HttpConnectorError::Auth(_)));
    }

    #[test]
    fn test_oauth_passthrough_documented_tag_deserializes() {
        // The documented `[backend.auth]` form is `type = "oauth_passthrough"`,
        // but `rename_all = "snake_case"` derives the tag `o_auth_passthrough`.
        // The `#[serde(alias)]` must accept the documented spelling.
        let cfg: AuthConfig = toml::from_str(r#"type = "oauth_passthrough""#)
            .expect("documented oauth_passthrough tag must deserialize via the serde alias");
        assert!(matches!(cfg, AuthConfig::OAuthPassthrough { .. }));
    }

    #[test]
    fn test_oauth2_client_credentials_documented_tag_deserializes() {
        let cfg: AuthConfig = toml::from_str(
            r#"
            type = "oauth2_client_credentials"
            token_url = "https://example.test/token"
            client_id = "${CID}"
            client_secret = "${CSECRET}"
            "#,
        )
        .expect("documented oauth2_client_credentials tag must deserialize via the serde alias");
        assert!(matches!(cfg, AuthConfig::OAuth2ClientCredentials { .. }));
    }

    #[test]
    fn test_snake_case_tag_still_deserializes_after_alias() {
        // The alias is ADDITIVE — the rename_all-derived `o_auth_passthrough`
        // tag (the canonical serialized form) must still round-trip.
        let cfg: AuthConfig = toml::from_str(r#"type = "o_auth_passthrough""#)
            .expect("canonical snake_case tag must still deserialize");
        assert!(matches!(cfg, AuthConfig::OAuthPassthrough { .. }));
    }

    #[tokio::test]
    async fn test_static_provider_ignores_inbound_token() {
        // T-90-01-06: a static provider must NOT leak the inbound token into its
        // output — it applies ONLY its configured credential.
        let bearer = create_auth_provider(&AuthConfig::Bearer {
            token: "static-tok".to_string(),
            required: true,
        })
        .unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        bearer
            .apply(&mut headers, &mut query, Some("client-tok"))
            .await
            .unwrap();
        let rendered = headers
            .get(reqwest::header::AUTHORIZATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(rendered, "Bearer static-tok");
        assert!(
            !rendered.contains("client-tok"),
            "static provider must not forward the inbound token"
        );

        // Same for api-key-in-query.
        let apikey = create_auth_provider(&AuthConfig::ApiKey {
            query_params: [("app_key".to_string(), "kkk".to_string())]
                .into_iter()
                .collect(),
            headers: HashMap::new(),
            required: true,
        })
        .unwrap();
        let mut headers2 = HeaderMap::new();
        let mut query2 = HashMap::new();
        apikey
            .apply(&mut headers2, &mut query2, Some("client-tok"))
            .await
            .unwrap();
        assert_eq!(query2.get("app_key"), Some(&"kkk".to_string()));
        assert!(
            !query2.values().any(|v| v.contains("client-tok")),
            "static api-key provider must not forward the inbound token"
        );
        assert!(headers2.is_empty());
    }

    #[tokio::test]
    async fn test_auth_error_display_no_secret() {
        // The error surfaced when a required token is missing must not echo a token.
        let cfg = AuthConfig::OAuthPassthrough {
            target_header: "Authorization".to_string(),
            required: true,
        };
        let auth = create_passthrough_auth_provider(&cfg, None).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        let err = auth
            .apply(&mut headers, &mut query, None)
            .await
            .unwrap_err();
        let rendered = err.to_string();
        for forbidden in ["Bearer", "client-tok", "app_key", "https://"] {
            assert!(
                !rendered.contains(forbidden),
                "auth error Display must not echo {forbidden:?}; got {rendered:?}"
            );
        }
    }

    #[test]
    fn test_auth_config_deserializes_snake_case_tag() {
        let toml_src = r#"type = "bearer"
token = "abc"
"#;
        let cfg: AuthConfig = toml::from_str(toml_src).unwrap();
        assert!(matches!(cfg, AuthConfig::Bearer { .. }));
        assert!(cfg.is_required());
    }

    #[test]
    fn test_auth_config_default_is_none() {
        assert!(matches!(AuthConfig::default(), AuthConfig::None));
        assert!(!AuthConfig::None.is_required());
    }

    // -------------------------------------------------------------------------
    // Plan 90-11: single secret-resolution chokepoint across ALL variants.
    // -------------------------------------------------------------------------

    #[test]
    fn test_resolve_secret_ref_forms() {
        let var = "PMCP_TEST_RESOLVE_SECRET_REF_FORM";
        std::env::set_var(var, "secret");
        assert_eq!(resolve_secret_ref(&format!("${{{var}}}")), "secret");
        assert_eq!(resolve_secret_ref(&format!("env:{var}")), "secret");
        assert_eq!(resolve_secret_ref("plain-literal"), "plain-literal");
        std::env::remove_var(var);
        // Unset / malformed → empty (omitted), never the literal.
        assert_eq!(resolve_secret_ref(&format!("${{{var}}}")), "");
        assert_eq!(resolve_secret_ref("${}"), "");
    }

    #[test]
    fn test_parse_env_ref_distinguishes_literal_from_reference() {
        assert_eq!(parse_env_ref("env:FOO"), Some("FOO"));
        assert_eq!(parse_env_ref("${FOO}"), Some("FOO"));
        assert_eq!(parse_env_ref("${}"), Some("")); // malformed-but-a-reference
        assert_eq!(parse_env_ref("plain"), None);
        assert_eq!(parse_env_ref("${FOO"), None); // unterminated → literal
    }

    #[tokio::test]
    async fn test_bearer_resolves_braced_env_ref() {
        let var = "PMCP_TEST_BEARER_BRACED_PAT";
        std::env::set_var(var, "ghp_abc");
        let cfg = AuthConfig::Bearer {
            token: format!("${{{var}}}"),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        let rendered = headers
            .get(reqwest::header::AUTHORIZATION)
            .unwrap()
            .to_str()
            .unwrap();
        assert_eq!(rendered, "Bearer ghp_abc");
        assert!(
            !rendered.contains("${"),
            "the literal ${{...}} must never reach the Authorization header"
        );
        std::env::remove_var(var);
    }

    #[tokio::test]
    async fn test_bearer_resolves_env_prefix_ref() {
        let var = "PMCP_TEST_BEARER_ENV_PAT";
        std::env::set_var(var, "ghp_xyz");
        let cfg = AuthConfig::Bearer {
            token: format!("env:{var}"),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            "Bearer ghp_xyz"
        );
        std::env::remove_var(var);
    }

    #[tokio::test]
    async fn test_bearer_unset_ref_collapses_to_no_auth() {
        let var = "PMCP_TEST_BEARER_UNSET_PAT";
        std::env::remove_var(var);
        let cfg = AuthConfig::Bearer {
            token: format!("${{{var}}}"),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        // Unset ref → NoAuth: no Authorization header, and CERTAINLY not the literal.
        assert!(headers.is_empty());
        assert!(query.is_empty());
    }

    #[tokio::test]
    async fn test_basic_resolves_password_braced_env_ref() {
        use base64::Engine;
        let var = "PMCP_TEST_BASIC_BRACED_PW";
        std::env::set_var(var, "s3cr3t");
        let cfg = AuthConfig::Basic {
            username: "u".to_string(),
            password: format!("${{{var}}}"),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        let rendered = headers
            .get(reqwest::header::AUTHORIZATION)
            .unwrap()
            .to_str()
            .unwrap();
        let expected = format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode("u:s3cr3t")
        );
        assert_eq!(rendered, expected);
        assert!(
            !rendered.contains("${"),
            "the literal ${{...}} must never reach the Basic credential"
        );
        std::env::remove_var(var);
    }

    #[tokio::test]
    async fn test_basic_resolves_password_env_prefix_ref() {
        use base64::Engine;
        let var = "PMCP_TEST_BASIC_ENV_PW";
        std::env::set_var(var, "p4ss");
        let cfg = AuthConfig::Basic {
            username: "user".to_string(),
            password: format!("env:{var}"),
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        let expected = format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode("user:p4ss")
        );
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            expected.as_str()
        );
        std::env::remove_var(var);
    }

    #[tokio::test]
    async fn test_oauth2_resolves_client_secret_via_token_endpoint() {
        // Drive fetch_token against a wiremock token endpoint asserting the
        // RESOLVED client_secret (not the literal `${...}`) is in the form body.
        use wiremock::matchers::{body_string_contains, method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let var = "PMCP_TEST_OAUTH2_BRACED_CS";
        std::env::set_var(var, "xyz");

        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/token"))
            .and(body_string_contains("client_secret=xyz"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "access_token": "issued-token"
            })))
            .mount(&server)
            .await;

        let cfg = AuthConfig::OAuth2ClientCredentials {
            token_url: format!("{}/token", server.uri()),
            client_id: "cid".to_string(),
            client_secret: format!("${{{var}}}"),
            scopes: vec![],
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        // apply() triggers fetch_token; the wiremock body matcher (client_secret=xyz)
        // FAILS the request (404) unless the resolved secret was sent — so success
        // proves the resolved `xyz` (not the literal `${VAR}`) reached the wire.
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            "Bearer issued-token"
        );
        std::env::remove_var(var);
    }

    #[tokio::test]
    async fn test_oauth2_unset_secret_collapses_to_no_auth() {
        let var = "PMCP_TEST_OAUTH2_UNSET_CS";
        std::env::remove_var(var);
        let cfg = AuthConfig::OAuth2ClientCredentials {
            token_url: "http://127.0.0.1:1/token".to_string(),
            client_id: "cid".to_string(),
            client_secret: format!("${{{var}}}"),
            scopes: vec![],
            required: true,
        };
        let auth = create_auth_provider(&cfg).unwrap();
        let mut headers = HeaderMap::new();
        let mut query = HashMap::new();
        // Unset secret → NoAuth: apply does NOT attempt any network fetch.
        auth.apply(&mut headers, &mut query, None).await.unwrap();
        assert!(headers.is_empty());
        assert!(query.is_empty());
    }
}