volga-oauth-core 0.9.7

Shared OAuth 2.1/OIDC foundation types for Volga Web Framework
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
//! Shared OAuth utilities
//!
//! * [`BearerChallenge`] - builder and parser for `WWW-Authenticate: Bearer ...`
//!   challenges per [RFC 6750 Section 3](https://www.rfc-editor.org/rfc/rfc6750#section-3)
//!   and [RFC 9728 Section 5.1](https://www.rfc-editor.org/rfc/rfc9728#section-5.1)
//! * [`canonicalize_resource_uri`] - resource indicator normalization per
//!   [RFC 8707 Section 2](https://www.rfc-editor.org/rfc/rfc8707#section-2)

use crate::error::{OAuthError, OAuthErrorCode};
use crate::metadata::{
    WELL_KNOWN_AUTHORIZATION_SERVER, WELL_KNOWN_OPENID_CONFIGURATION, WELL_KNOWN_PROTECTED_RESOURCE,
};
use std::fmt::{self, Display, Formatter, Write};
use std::net::Ipv6Addr;
use std::str::FromStr;

/// Builder and parser for a `WWW-Authenticate: Bearer` challenge header value
///
/// Parameters are emitted in a stable order: `realm`, `error`,
/// `error_description`, `scope`, `resource_metadata`. All values are
/// quoted; embedded `"` and `\` are escaped and control characters are
/// replaced with spaces so the result is always a valid header value.
///
/// The inverse operation - extracting a `Bearer` challenge from a received
/// `WWW-Authenticate` header value - is available via
/// [`BearerChallenge::parse`] (also exposed through [`FromStr`]).
///
/// # Example
/// ```
/// use volga_oauth_core::{BearerChallenge, OAuthErrorCode};
///
/// let challenge = BearerChallenge::new()
///     .with_error(OAuthErrorCode::InvalidToken)
///     .with_description("Token has expired")
///     .to_string();
///
/// assert_eq!(
///     challenge,
///     r#"Bearer error="invalid_token", error_description="Token has expired""#
/// );
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct BearerChallenge {
    realm: Option<String>,
    error: Option<OAuthErrorCode>,
    error_description: Option<String>,
    scope: Option<String>,
    resource_metadata: Option<String>,
}

impl BearerChallenge {
    /// Creates an empty challenge (renders as `Bearer`)
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the `realm` parameter
    pub fn with_realm(mut self, realm: impl Into<String>) -> Self {
        self.realm = Some(realm.into());
        self
    }

    /// Sets the `error` parameter (RFC 6750 Section 3.1)
    pub fn with_error(mut self, error: OAuthErrorCode) -> Self {
        self.error = Some(error);
        self
    }

    /// Sets the `error_description` parameter
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.error_description = Some(description.into());
        self
    }

    /// Sets the `scope` parameter listing the scopes required to access the resource
    pub fn with_scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }

    /// Sets the `resource_metadata` parameter pointing to the protected
    /// resource metadata document (RFC 9728 Section 5.1)
    pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
        self.resource_metadata = Some(url.into());
        self
    }

    /// Returns the `realm` parameter, if set
    #[inline]
    pub fn realm(&self) -> Option<&str> {
        self.realm.as_deref()
    }

    /// Returns the `error` parameter, if set
    #[inline]
    pub fn error(&self) -> Option<&OAuthErrorCode> {
        self.error.as_ref()
    }

    /// Returns the `error_description` parameter, if set
    #[inline]
    pub fn description(&self) -> Option<&str> {
        self.error_description.as_deref()
    }

    /// Returns the `scope` parameter, if set
    #[inline]
    pub fn scope(&self) -> Option<&str> {
        self.scope.as_deref()
    }

    /// Returns the `resource_metadata` parameter, if set
    #[inline]
    pub fn resource_metadata(&self) -> Option<&str> {
        self.resource_metadata.as_deref()
    }

    /// Parses a `WWW-Authenticate` header value and extracts the `Bearer`
    /// challenge from it
    ///
    /// The header may carry several comma-separated challenges
    /// ([RFC 9110 Section 11.6.1](https://www.rfc-editor.org/rfc/rfc9110#section-11.6.1));
    /// the first `Bearer` challenge is used and the auth scheme is matched
    /// case-insensitively. Parameter names are matched case-insensitively
    /// as well, values may be given as tokens or quoted strings
    /// (quoted-pair escapes are decoded), and unrecognized parameters are
    /// ignored for forward compatibility.
    ///
    /// Returns an [`OAuthError`] with code `invalid_request` when the value
    /// contains no `Bearer` challenge or is malformed: an invalid scheme or
    /// parameter name, a value that is neither a token nor a quoted string,
    /// an unterminated quoted string, a control character, a duplicated
    /// recognized parameter, or a `token68` payload, which the Bearer scheme
    /// does not use ([RFC 6750 Section 3](https://www.rfc-editor.org/rfc/rfc6750#section-3)).
    ///
    /// # Example
    /// ```
    /// use volga_oauth_core::{BearerChallenge, OAuthErrorCode};
    ///
    /// let challenge = BearerChallenge::parse(
    ///     r#"Basic realm="legacy", Bearer error="invalid_token", error_description="Token has expired""#,
    /// ).unwrap();
    ///
    /// assert_eq!(challenge.error(), Some(&OAuthErrorCode::InvalidToken));
    /// assert_eq!(challenge.description(), Some("Token has expired"));
    /// ```
    pub fn parse(header: &str) -> Result<Self, OAuthError> {
        let mut bearer: Option<Self> = None;
        let mut seen_scheme = false;
        for element in split_list_elements(header)? {
            // Empty list elements (`Bearer, , Basic`) are legal per RFC 9110 Section 5.6.1
            if element.is_empty() {
                continue;
            }

            match classify_element(element) {
                Element::Scheme { scheme, param } => {
                    // The Bearer challenge ends where the next challenge begins
                    if bearer.is_some() {
                        break;
                    }

                    if !scheme.bytes().all(is_tchar) {
                        return Err(invalid_challenge("auth scheme is not a valid token"));
                    }

                    seen_scheme = true;

                    if scheme.eq_ignore_ascii_case("Bearer") {
                        let mut challenge = Self::new();
                        if let Some(param) = param {
                            let (name, value) = parse_auth_param(param)?;
                            challenge.set_param(&name, value)?;
                        }
                        bearer = Some(challenge);
                    }
                }
                Element::Param => {
                    if let Some(challenge) = &mut bearer {
                        let (name, value) = parse_auth_param(element)?;
                        challenge.set_param(&name, value)?;
                    } else if !seen_scheme {
                        return Err(invalid_challenge(
                            "auth parameter appears before any challenge scheme",
                        ));
                    }
                    // Parameters of other schemes are skipped
                }
            }
        }
        bearer.ok_or_else(|| invalid_challenge("no Bearer challenge found"))
    }

    /// Stores a parsed auth parameter; `name` must already be lowercased.
    /// Unknown parameters are ignored for forward compatibility, duplicates
    /// of recognized ones are rejected (RFC 7235 Section 2.1).
    fn set_param(&mut self, name: &str, value: String) -> Result<(), OAuthError> {
        let slot = match name {
            "realm" => &mut self.realm,
            "error_description" => &mut self.error_description,
            "scope" => &mut self.scope,
            "resource_metadata" => &mut self.resource_metadata,
            "error" => {
                return if self.error.replace(OAuthErrorCode::from(value)).is_some() {
                    Err(invalid_challenge("duplicate parameter in Bearer challenge"))
                } else {
                    Ok(())
                };
            }
            _ => return Ok(()),
        };

        if slot.replace(value).is_some() {
            return Err(invalid_challenge("duplicate parameter in Bearer challenge"));
        }

        Ok(())
    }
}

impl FromStr for BearerChallenge {
    type Err = OAuthError;

    #[inline]
    fn from_str(header: &str) -> Result<Self, Self::Err> {
        Self::parse(header)
    }
}

impl Display for BearerChallenge {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("Bearer")?;
        let mut first = true;
        if let Some(realm) = &self.realm {
            write_param(f, &mut first, "realm", realm)?;
        }
        if let Some(error) = &self.error {
            write_param(f, &mut first, "error", error.as_str())?;
        }
        if let Some(description) = &self.error_description {
            write_param(f, &mut first, "error_description", description)?;
        }
        if let Some(scope) = &self.scope {
            write_param(f, &mut first, "scope", scope)?;
        }
        if let Some(url) = &self.resource_metadata {
            write_param(f, &mut first, "resource_metadata", url)?;
        }
        Ok(())
    }
}

/// Writes a single `name="value"` auth parameter, escaping the value as an
/// RFC 7235 quoted-string and replacing control characters with spaces.
fn write_param(f: &mut Formatter<'_>, first: &mut bool, name: &str, value: &str) -> fmt::Result {
    if *first {
        f.write_char(' ')?;
        *first = false;
    } else {
        f.write_str(", ")?;
    }
    f.write_str(name)?;
    f.write_str("=\"")?;
    for symbol in value.chars() {
        match symbol {
            '"' | '\\' => {
                f.write_char('\\')?;
                f.write_char(symbol)?;
            }
            symbol if symbol.is_control() => f.write_char(' ')?,
            symbol => f.write_char(symbol)?,
        }
    }
    f.write_char('"')
}

/// A single comma-separated element of a `WWW-Authenticate` header value:
/// either the start of a challenge (a bare scheme, optionally followed by
/// its first space-separated item) or an auth parameter belonging to the
/// current challenge.
enum Element<'a> {
    Scheme {
        scheme: &'a str,
        param: Option<&'a str>,
    },
    Param,
}

/// Classifies a non-empty, trimmed list element. An element starts a new
/// challenge when it is a bare token or a token separated from the rest by
/// whitespace; `name=value` pairs (with optional bad whitespace around `=`,
/// RFC 9110 Section 5.6.3) are parameters of the current challenge.
fn classify_element(element: &str) -> Element<'_> {
    match element.split_once([' ', '\t']) {
        None if !element.contains('=') => Element::Scheme {
            scheme: element,
            param: None,
        },
        Some((scheme, rest)) if !scheme.contains('=') && !rest.trim_start().starts_with('=') => {
            Element::Scheme {
                scheme,
                param: Some(rest.trim_start()),
            }
        }
        _ => Element::Param,
    }
}

/// Splits a header value at top-level commas, leaving commas inside quoted
/// strings (including escaped quotes) intact. Elements are trimmed but may
/// be empty - the `#challenge` list grammar allows empty elements.
fn split_list_elements(header: &str) -> Result<Vec<&str>, OAuthError> {
    let bytes = header.as_bytes();
    let mut elements = Vec::new();
    let (mut start, mut index, mut in_quotes) = (0, 0, false);
    while index < bytes.len() {
        match bytes[index] {
            b'"' => in_quotes = !in_quotes,
            // Skip the escaped byte; multi-byte characters are left alone
            // since only ASCII `"` and `,` are meaningful here
            b'\\' if in_quotes => index += 1,
            b',' if !in_quotes => {
                elements.push(header[start..index].trim());
                start = index + 1;
            }
            _ => {}
        }
        index += 1;
    }
    if in_quotes {
        return Err(invalid_challenge("quoted string is not terminated"));
    }
    elements.push(header[start..].trim());
    Ok(elements)
}

/// Parses a single `name=value` auth parameter (RFC 9110 Section 11.2): the name
/// is lowercased, the value is either a token or a quoted string with
/// quoted-pair escapes decoded. Bad whitespace around `=` is tolerated.
fn parse_auth_param(element: &str) -> Result<(String, String), OAuthError> {
    let Some((name, value)) = element.split_once('=') else {
        return Err(invalid_challenge("auth parameter is missing '='"));
    };

    let name = name.trim_end();
    if name.is_empty() || !name.bytes().all(is_tchar) {
        return Err(invalid_challenge(
            "auth parameter name is not a valid token",
        ));
    }

    let value = value.trim_start();
    let value = if let Some(quoted) = value.strip_prefix('"') {
        unquote(quoted)?
    } else if !value.is_empty() && value.bytes().all(is_tchar) {
        value.to_owned()
    } else {
        return Err(invalid_challenge(
            "auth parameter value must be a token or a quoted string",
        ));
    };

    Ok((name.to_ascii_lowercase(), value))
}

/// Decodes the remainder of a quoted string (the opening `"` already
/// stripped): `\x` escapes are unquoted, control characters other than
/// HTAB are rejected, and nothing may follow the closing quote.
fn unquote(quoted: &str) -> Result<String, OAuthError> {
    let mut value = String::with_capacity(quoted.len());
    let mut symbols = quoted.chars();

    while let Some(symbol) = symbols.next() {
        match symbol {
            '"' => {
                return if symbols.as_str().trim().is_empty() {
                    Ok(value)
                } else {
                    Err(invalid_challenge(
                        "unexpected content after a quoted string",
                    ))
                };
            }
            '\\' => match symbols.next() {
                Some(escaped) if escaped == '\t' || !escaped.is_control() => value.push(escaped),
                _ => return Err(invalid_challenge("invalid escape in a quoted string")),
            },
            symbol if symbol.is_control() && symbol != '\t' => {
                return Err(invalid_challenge("control character in a quoted string"));
            }
            symbol => value.push(symbol),
        }
    }
    Err(invalid_challenge("quoted string is not terminated"))
}

/// Checks the RFC 9110 Section 5.6.2 `tchar` grammar (token characters)
fn is_tchar(byte: u8) -> bool {
    byte.is_ascii_alphanumeric()
        || matches!(
            byte,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'.'
                | b'^'
                | b'_'
                | b'`'
                | b'|'
                | b'~'
        )
}

#[inline]
fn invalid_challenge(description: &str) -> OAuthError {
    OAuthError::new(OAuthErrorCode::InvalidRequest).with_description(description)
}

/// Canonicalizes an OAuth 2.0 resource indicator (RFC 8707) so that
/// equivalent URIs compare equal as strings (e.g. for `aud` matching).
///
/// Normalization applied:
/// * the scheme and host are lowercased;
/// * default ports are removed (`http`/`ws`: 80, `https`/`wss`: 443);
/// * for web schemes (`http`, `https`, `ws`, `wss`) a lone root path is
///   dropped, both bare (`https://example.com/` -> `https://example.com`)
///   and before a query (`.../?q=1` -> `...?q=1`); for other schemes the path is
///   preserved verbatim, as the empty-path/`/` equivalence is
///   scheme-specific (RFC 3986 Section 6.2.3). Non-root paths and query strings
///   are always preserved.
///
/// Returns an [`OAuthError`] with code `invalid_target` when the URI is not
/// an absolute URI, contains a fragment, userinfo, whitespace, control or
/// non-ASCII characters, uses a web scheme (`http`, `https`, `ws`, `wss`)
/// without an authority (`https:api.example.com`), has a bracketed host that
/// is not a valid IPv6/IPvFuture literal, an unbracketed host with
/// characters outside the RFC 3986 `reg-name` grammar, or a path/query with
/// characters outside the `pchar` / `query` grammar (including incomplete
/// percent-escapes). Percent-encoding and dot-segment normalization are
/// not performed.
///
/// # Example
/// ```
/// use volga_oauth_core::canonicalize_resource_uri;
///
/// let uri = canonicalize_resource_uri("HTTPS://API.Example.COM:443/v1").unwrap();
/// assert_eq!(uri, "https://api.example.com/v1");
/// ```
pub fn canonicalize_resource_uri(uri: &str) -> Result<String, OAuthError> {
    if uri.is_empty() {
        return Err(invalid_target("resource URI must not be empty"));
    }

    if uri.bytes().any(|b| !(0x21..=0x7e).contains(&b)) {
        return Err(invalid_target(
            "resource URI must not contain whitespace, control or non-ASCII characters",
        ));
    }

    if uri.contains('#') {
        return Err(invalid_target("resource URI must not contain a fragment"));
    }

    let Some((scheme, rest)) = uri.split_once(':') else {
        return Err(invalid_target("resource URI must be an absolute URI"));
    };

    let valid_scheme = scheme
        .chars()
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic())
        && scheme
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));

    if !valid_scheme {
        return Err(invalid_target("resource URI scheme is invalid"));
    }

    let scheme = scheme.to_ascii_lowercase();
    let is_web_scheme = matches!(scheme.as_str(), "http" | "https" | "ws" | "wss");

    let Some(after_scheme) = rest.strip_prefix("//") else {
        // Web schemes always carry an authority: `https:api.example.com`
        // or `https:/api` is a mistyped resource, not a URN-style URI
        if is_web_scheme {
            return Err(invalid_target("resource URI must have an authority"));
        }
        // No authority component (e.g. `urn:example:resource`) - the
        // scheme-specific part is pchar-based too (`hier-part [ "?" query ]`,
        // RFC 3986 Section 3.3), and only the scheme is subject to normalization
        if !is_valid_uri_component(rest, b":@/?") {
            return Err(invalid_target("resource URI contains invalid characters"));
        }
        return Ok(format!("{scheme}:{rest}"));
    };

    let authority_end = after_scheme.find(['/', '?']).unwrap_or(after_scheme.len());
    let (authority, path_and_query) = after_scheme.split_at(authority_end);
    if authority.contains('@') {
        return Err(invalid_target("resource URI must not contain userinfo"));
    }
    // `pchar` plus the `/` and `?` delimiters (RFC 3986 Section 3.3-3.4); `#` was
    // already rejected above, so everything after the first `?` is the query
    if !is_valid_uri_component(path_and_query, b":@/?") {
        return Err(invalid_target(
            "resource URI path or query contains invalid characters",
        ));
    }

    let (host, port) = split_host_port(authority)?;
    if host.is_empty() {
        return Err(invalid_target("resource URI must have a host"));
    }

    let host = host.to_ascii_lowercase();

    let port = match port {
        // An empty port (`https://example.com:`) is dropped
        None | Some("") => None,
        Some(port) => {
            if !port.bytes().all(|b| b.is_ascii_digit()) {
                return Err(invalid_target("resource URI port is invalid"));
            }
            match (scheme.as_str(), port) {
                ("http" | "ws", "80") | ("https" | "wss", "443") => None,
                _ => Some(port),
            }
        }
    };

    let mut result = format!("{scheme}://{host}");
    if let Some(port) = port {
        result.push(':');
        result.push_str(port);
    }
    // Empty-path/`/` equivalence is scheme-based normalization
    // (RFC 3986 Section 6.2.3) - only apply it to schemes we know. The lone root
    // slash is dropped both bare (`/`) and before a query (`/?q=1`)
    if is_web_scheme && (path_and_query == "/" || path_and_query.starts_with("/?")) {
        result.push_str(&path_and_query[1..]);
    } else {
        result.push_str(path_and_query);
    }

    Ok(result)
}

/// Derives the Protected Resource Metadata URL for a resource identifier
/// per [RFC 9728 Section 3.1](https://www.rfc-editor.org/rfc/rfc9728#section-3.1):
/// the well-known path is inserted between the host and the path components
/// of the canonicalized resource identifier.
///
/// Returns an [`OAuthError`] with code `invalid_target` when the resource
/// identifier is not a valid `http`/`https` URI or contains a query.
///
/// # Example
/// ```
/// use volga_oauth_core::protected_resource_metadata_url;
///
/// let url = protected_resource_metadata_url("https://api.example.com").unwrap();
/// assert_eq!(url, "https://api.example.com/.well-known/oauth-protected-resource");
///
/// let url = protected_resource_metadata_url("https://api.example.com/v1").unwrap();
/// assert_eq!(url, "https://api.example.com/.well-known/oauth-protected-resource/v1");
/// ```
pub fn protected_resource_metadata_url(resource: &str) -> Result<String, OAuthError> {
    insert_well_known_path(resource, WELL_KNOWN_PROTECTED_RESOURCE)
}

/// Derives the Authorization Server Metadata URL for an issuer identifier
/// per [RFC 8414 Section 3.1](https://www.rfc-editor.org/rfc/rfc8414#section-3.1):
/// the well-known path is inserted between the host and the path components
/// of the canonicalized issuer identifier.
///
/// Returns an [`OAuthError`] with code `invalid_target` when the issuer
/// identifier is not a valid `http`/`https` URI or contains a query
/// (RFC 8414 Section 2 forbids query and fragment components in the issuer).
///
/// # Example
/// ```
/// use volga_oauth_core::authorization_server_metadata_url;
///
/// let url = authorization_server_metadata_url("https://auth.example.com/tenant1").unwrap();
/// assert_eq!(url, "https://auth.example.com/.well-known/oauth-authorization-server/tenant1");
/// ```
pub fn authorization_server_metadata_url(issuer: &str) -> Result<String, OAuthError> {
    insert_well_known_path(issuer, WELL_KNOWN_AUTHORIZATION_SERVER)
}

/// Derives the OpenID Connect Discovery metadata URL for an issuer identifier
/// per [OpenID Connect Discovery 1.0 Section 4](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig):
/// unlike the RFC 8414 rule, the well-known path is appended **after** the
/// issuer's path component (a trailing slash in the issuer is dropped first).
///
/// Returns an [`OAuthError`] with code `invalid_target` when the issuer
/// identifier is not a valid `http`/`https` URI or contains a query.
///
/// # Example
/// ```
/// use volga_oauth_core::openid_configuration_url;
///
/// let url = openid_configuration_url("https://auth.example.com").unwrap();
/// assert_eq!(url, "https://auth.example.com/.well-known/openid-configuration");
///
/// let url = openid_configuration_url("https://auth.example.com/tenant1").unwrap();
/// assert_eq!(url, "https://auth.example.com/tenant1/.well-known/openid-configuration");
/// ```
pub fn openid_configuration_url(issuer: &str) -> Result<String, OAuthError> {
    let canonical = canonical_metadata_base(issuer)?;
    let base = canonical.strip_suffix('/').unwrap_or(&canonical);
    let mut url = String::with_capacity(base.len() + WELL_KNOWN_OPENID_CONFIGURATION.len());

    url.push_str(base);
    url.push_str(WELL_KNOWN_OPENID_CONFIGURATION);

    Ok(url)
}

/// Canonicalizes a resource/issuer identifier and validates that a metadata
/// URL can be derived from it: an `http`/`https` URI without a query.
fn canonical_metadata_base(uri: &str) -> Result<String, OAuthError> {
    let canonical = canonicalize_resource_uri(uri)?;
    if !canonical.starts_with("https://") && !canonical.starts_with("http://") {
        return Err(invalid_target(
            "metadata URL can only be derived from an http(s) URI",
        ));
    }

    if canonical.contains('?') {
        return Err(invalid_target("metadata URL base must not contain a query"));
    }

    Ok(canonical)
}

/// Inserts a well-known path between the authority and the path of a
/// canonicalized `http`/`https` URI (the insertion rule shared by
/// RFC 8414 Section 3.1 and RFC 9728 Section 3.1).
fn insert_well_known_path(uri: &str, well_known: &str) -> Result<String, OAuthError> {
    let canonical = canonical_metadata_base(uri)?;
    let after_scheme = canonical.find("://").expect("scheme checked above") + 3;
    let path_start = canonical[after_scheme..]
        .find('/')
        .map_or(canonical.len(), |i| after_scheme + i);

    let mut url = String::with_capacity(canonical.len() + well_known.len());

    url.push_str(&canonical[..path_start]);
    url.push_str(well_known);
    url.push_str(&canonical[path_start..]);

    Ok(url)
}

/// Splits a URI authority (without userinfo) into host and optional port,
/// keeping IP literals (`[::1]`) intact and validating their content.
fn split_host_port(authority: &str) -> Result<(&str, Option<&str>), OAuthError> {
    if let Some(inner) = authority.strip_prefix('[') {
        let Some(close) = inner.find(']') else {
            return Err(invalid_target("resource URI IPv6 literal is not closed"));
        };

        if !is_valid_ip_literal(&inner[..close]) {
            return Err(invalid_target(
                "resource URI bracketed host must be a valid IP literal",
            ));
        }

        let host_end = close + 2; // '[' + literal + ']'
        let host = &authority[..host_end];
        let after_host = &authority[host_end..];

        match after_host.strip_prefix(':') {
            Some(port) => Ok((host, Some(port))),
            None if after_host.is_empty() => Ok((host, None)),
            None => Err(invalid_target("resource URI authority is invalid")),
        }
    } else {
        let (host, port) = match authority.rsplit_once(':') {
            Some((host, _)) if host.contains(':') => {
                return Err(invalid_target(
                    "resource URI IPv6 literal must be enclosed in brackets",
                ));
            }
            Some((host, port)) => (host, Some(port)),
            None => (authority, None),
        };
        // `reg-name = *( unreserved / pct-encoded / sub-delims )` (Section 3.2.2)
        if !is_valid_uri_component(host, b"") {
            return Err(invalid_target(
                "resource URI host contains invalid characters",
            ));
        }
        Ok((host, port))
    }
}

/// Checks that a string consists of RFC 3986 `unreserved` / `sub-delims`
/// characters, complete percent-escapes (`%` followed by two hex digits;
/// their decoding is not performed) and the given extra delimiter bytes.
///
/// With no extras this is exactly the `reg-name` grammar (Section 3.2.2); with
/// `b":@/?"` it covers a path with an optional query (Section 3.3-3.4).
fn is_valid_uri_component(component: &str, extra: &[u8]) -> bool {
    let mut bytes = component.bytes();

    while let Some(byte) = bytes.next() {
        match byte {
            b'%' => {
                let valid_escape = matches!(
                    (bytes.next(), bytes.next()),
                    (Some(hi), Some(lo)) if hi.is_ascii_hexdigit() && lo.is_ascii_hexdigit()
                );
                if !valid_escape {
                    return false;
                }
            }
            byte if byte.is_ascii_alphanumeric() => {}
            b'-' | b'.' | b'_' | b'~' | b'!' | b'$' | b'&' | b'\'' | b'(' | b')' | b'*' | b'+'
            | b',' | b';' | b'=' => {}
            byte if extra.contains(&byte) => {}
            _ => return false,
        }
    }
    true
}

/// Checks that the content of a bracketed host is an IP literal per
/// RFC 3986 Section 3.2.2: an IPv6 address or an IPvFuture
/// (`"v" 1*HEXDIG "." 1*(unreserved / sub-delims / ":")`).
///
/// Zone identifiers (RFC 6874, `[fe80::1%25eth0]`) are rejected: link-local
/// addresses are not meaningful as resource indicators.
fn is_valid_ip_literal(literal: &str) -> bool {
    if let Some(rest) = literal.strip_prefix(['v', 'V']) {
        let Some((version, addr)) = rest.split_once('.') else {
            return false;
        };
        !version.is_empty()
            && version.bytes().all(|b| b.is_ascii_hexdigit())
            && !addr.is_empty()
            && addr.bytes().all(|b| {
                b.is_ascii_alphanumeric()
                    || matches!(
                        b,
                        b'-' | b'.'
                            | b'_'
                            | b'~'
                            | b'!'
                            | b'$'
                            | b'&'
                            | b'\''
                            | b'('
                            | b')'
                            | b'*'
                            | b'+'
                            | b','
                            | b';'
                            | b'='
                            | b':'
                    )
            })
    } else {
        literal.parse::<Ipv6Addr>().is_ok()
    }
}

#[inline]
fn invalid_target(description: &str) -> OAuthError {
    OAuthError::new(OAuthErrorCode::InvalidTarget).with_description(description)
}

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

    #[test]
    fn it_renders_empty_challenge() {
        assert_eq!(BearerChallenge::new().to_string(), "Bearer");
    }

    #[test]
    fn it_renders_error_and_description() {
        let challenge = BearerChallenge::new()
            .with_error(OAuthErrorCode::InvalidToken)
            .with_description("Token has expired");
        assert_eq!(
            challenge.to_string(),
            r#"Bearer error="invalid_token", error_description="Token has expired""#
        );
    }

    #[test]
    fn it_renders_all_parameters_in_stable_order() {
        let challenge = BearerChallenge::new()
            .with_resource_metadata("https://api.example.com/.well-known/oauth-protected-resource")
            .with_scope("read write")
            .with_description("Insufficient privileges")
            .with_error(OAuthErrorCode::InsufficientScope)
            .with_realm("api");
        assert_eq!(
            challenge.to_string(),
            r#"Bearer realm="api", error="insufficient_scope", error_description="Insufficient privileges", scope="read write", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource""#
        );
    }

    #[test]
    fn it_escapes_quotes_and_backslashes() {
        let challenge = BearerChallenge::new().with_description(r#"a "quoted" \ value"#);
        assert_eq!(
            challenge.to_string(),
            r#"Bearer error_description="a \"quoted\" \\ value""#
        );
    }

    #[test]
    fn it_replaces_control_characters_with_spaces() {
        let challenge = BearerChallenge::new().with_description("line\r\nbreak\tand tab");
        assert_eq!(
            challenge.to_string(),
            r#"Bearer error_description="line  break and tab""#
        );
    }

    #[test]
    fn it_renders_custom_error_code() {
        let challenge = BearerChallenge::new().with_error(OAuthErrorCode::from("use_dpop_nonce"));
        assert_eq!(challenge.to_string(), r#"Bearer error="use_dpop_nonce""#);
    }

    #[test]
    fn it_parses_full_challenge() {
        let challenge = BearerChallenge::parse(
            r#"Bearer realm="api", error="insufficient_scope", error_description="Insufficient privileges", scope="read write", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource""#,
        )
        .unwrap();
        assert_eq!(challenge.realm(), Some("api"));
        assert_eq!(challenge.error(), Some(&OAuthErrorCode::InsufficientScope));
        assert_eq!(challenge.description(), Some("Insufficient privileges"));
        assert_eq!(challenge.scope(), Some("read write"));
        assert_eq!(
            challenge.resource_metadata(),
            Some("https://api.example.com/.well-known/oauth-protected-resource")
        );
    }

    #[test]
    fn it_roundtrips_built_challenge() {
        let original = BearerChallenge::new()
            .with_realm("api")
            .with_error(OAuthErrorCode::InvalidToken)
            .with_description(r#"a "quoted" \ value"#)
            .with_scope("read write")
            .with_resource_metadata("https://api.example.com/.well-known/oauth-protected-resource");
        let parsed = BearerChallenge::parse(&original.to_string()).unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn it_parses_empty_bearer_challenge() {
        assert_eq!(
            BearerChallenge::parse("Bearer").unwrap(),
            BearerChallenge::new()
        );
        assert_eq!(
            BearerChallenge::parse("  bearer  ").unwrap(),
            BearerChallenge::new()
        );
    }

    #[test]
    fn it_parses_case_insensitively_and_accepts_token_values() {
        let challenge = BearerChallenge::parse("BEARER ERROR=invalid_token, Realm=api").unwrap();
        assert_eq!(challenge.error(), Some(&OAuthErrorCode::InvalidToken));
        assert_eq!(challenge.realm(), Some("api"));
    }

    #[test]
    fn it_tolerates_bad_whitespace_around_equals() {
        let challenge = BearerChallenge::parse(r#"Bearer realm = "api", scope= read"#).unwrap();
        assert_eq!(challenge.realm(), Some("api"));
        assert_eq!(challenge.scope(), Some("read"));
    }

    #[test]
    fn it_picks_bearer_among_multiple_challenges() {
        let challenge = BearerChallenge::parse(
            r#"Negotiate Zm9vYmFyCg==, Newauth title="Login, please", Bearer realm="api", Basic realm="other""#,
        )
        .unwrap();
        assert_eq!(challenge.realm(), Some("api"));
        assert_eq!(challenge.error(), None);
    }

    #[test]
    fn it_ignores_unknown_parameters() {
        let challenge =
            BearerChallenge::parse(r#"Bearer nonce="abc", error="use_dpop_nonce""#).unwrap();
        assert_eq!(
            challenge.error(),
            Some(&OAuthErrorCode::from("use_dpop_nonce"))
        );
        assert_eq!(challenge.realm(), None);
    }

    #[test]
    fn it_skips_empty_list_elements() {
        let challenge = BearerChallenge::parse(r#", Bearer realm="api", ,"#).unwrap();
        assert_eq!(challenge.realm(), Some("api"));
    }

    #[test]
    fn it_parses_via_from_str() {
        let challenge: BearerChallenge = r#"Bearer scope="read""#.parse().unwrap();
        assert_eq!(challenge.scope(), Some("read"));
    }

    #[test]
    fn it_rejects_malformed_challenges() {
        let cases = [
            "",
            "   ",
            r#"Basic realm="api""#,           // no Bearer challenge
            r#"realm="api", Bearer"#,         // parameter before any scheme
            r#"Bearer realm="api"#,           // unterminated quoted string
            "Bearer realm=",                  // empty value
            r#"Bearer realm="a" junk"#,       // content after a quoted string
            "Bearer foo bar",                 // missing '='
            "Bearer Zm9vYmFyCg==",            // token68 payload
            "Bearer =x",                      // parameter with an empty name
            r#"Bearer re alm="x""#,           // invalid parameter name
            r#"Bearer realm="a", realm="b""#, // duplicate parameter
            r#"Bearer error="a", error="b""#, // duplicate error
            "Bearer realm=\"a\u{1}b\"",       // control character in a value
            r#"Bearer realm=\"#,              // bare backslash value
            r#"foo/bar, Bearer realm="x""#,   // malformed auth scheme
        ];
        for header in cases {
            let err = BearerChallenge::parse(header).unwrap_err();
            assert_eq!(err.error, OAuthErrorCode::InvalidRequest, "case: {header}");
        }
    }

    #[test]
    fn it_canonicalizes_scheme_and_host_case() {
        assert_eq!(
            canonicalize_resource_uri("HTTPS://API.Example.COM/Path/Sub").unwrap(),
            "https://api.example.com/Path/Sub"
        );
    }

    #[test]
    fn it_strips_default_ports() {
        assert_eq!(
            canonicalize_resource_uri("https://example.com:443/api").unwrap(),
            "https://example.com/api"
        );
        assert_eq!(
            canonicalize_resource_uri("http://example.com:80/api").unwrap(),
            "http://example.com/api"
        );
        assert_eq!(
            canonicalize_resource_uri("wss://example.com:443/socket").unwrap(),
            "wss://example.com/socket"
        );
    }

    #[test]
    fn it_keeps_non_default_ports() {
        assert_eq!(
            canonicalize_resource_uri("https://example.com:8443/api").unwrap(),
            "https://example.com:8443/api"
        );
    }

    #[test]
    fn it_drops_root_path_and_empty_port() {
        assert_eq!(
            canonicalize_resource_uri("https://example.com/").unwrap(),
            "https://example.com"
        );
        assert_eq!(
            canonicalize_resource_uri("https://example.com").unwrap(),
            "https://example.com"
        );
        assert_eq!(
            canonicalize_resource_uri("https://example.com:").unwrap(),
            "https://example.com"
        );
    }

    #[test]
    fn it_preserves_query_and_non_root_trailing_slash() {
        assert_eq!(
            canonicalize_resource_uri("https://example.com/api/?page=1").unwrap(),
            "https://example.com/api/?page=1"
        );
    }

    #[test]
    fn it_normalizes_root_path_before_query() {
        assert_eq!(
            canonicalize_resource_uri("https://example.com/?q=1").unwrap(),
            "https://example.com?q=1"
        );
        assert_eq!(
            canonicalize_resource_uri("https://example.com?q=1").unwrap(),
            "https://example.com?q=1"
        );
        // Not scheme-equivalent for custom schemes - both forms are kept
        assert_eq!(
            canonicalize_resource_uri("foo://api/?q=1").unwrap(),
            "foo://api/?q=1"
        );
        assert_eq!(
            canonicalize_resource_uri("foo://api?q=1").unwrap(),
            "foo://api?q=1"
        );
    }

    #[test]
    fn it_canonicalizes_ipv6_literals() {
        assert_eq!(
            canonicalize_resource_uri("https://[2001:DB8::1]:443/api").unwrap(),
            "https://[2001:db8::1]/api"
        );
        assert_eq!(
            canonicalize_resource_uri("https://[::1]:8443").unwrap(),
            "https://[::1]:8443"
        );
    }

    #[test]
    fn it_keeps_pct_encoded_and_sub_delim_hosts() {
        assert_eq!(
            canonicalize_resource_uri("https://ex%41mple.com/api").unwrap(),
            "https://ex%41mple.com/api"
        );
        assert_eq!(
            canonicalize_resource_uri("https://api.ex-ample_1.com").unwrap(),
            "https://api.ex-ample_1.com"
        );
    }

    #[test]
    fn it_keeps_ip_vfuture_literals() {
        assert_eq!(
            canonicalize_resource_uri("https://[v1.FE:x]:8443/api").unwrap(),
            "https://[v1.fe:x]:8443/api"
        );
    }

    #[test]
    fn it_keeps_valid_pchar_and_query_characters() {
        assert_eq!(
            canonicalize_resource_uri("https://api.example.com/a%20b/v1:x@y?q=?&r=/").unwrap(),
            "https://api.example.com/a%20b/v1:x@y?q=?&r=/"
        );
    }

    #[test]
    fn it_preserves_root_path_and_port_for_custom_schemes() {
        assert_eq!(
            canonicalize_resource_uri("FOO://API.Example.com/").unwrap(),
            "foo://api.example.com/"
        );
        assert_eq!(
            canonicalize_resource_uri("foo://api.example.com").unwrap(),
            "foo://api.example.com"
        );
        assert_eq!(
            canonicalize_resource_uri("foo://api.example.com:80/x").unwrap(),
            "foo://api.example.com:80/x"
        );
    }

    #[test]
    fn it_derives_metadata_urls() {
        assert_eq!(
            protected_resource_metadata_url("HTTPS://API.Example.com:443").unwrap(),
            "https://api.example.com/.well-known/oauth-protected-resource"
        );
        assert_eq!(
            protected_resource_metadata_url("https://api.example.com/v1").unwrap(),
            "https://api.example.com/.well-known/oauth-protected-resource/v1"
        );
        assert_eq!(
            protected_resource_metadata_url("http://localhost:8080/api").unwrap(),
            "http://localhost:8080/.well-known/oauth-protected-resource/api"
        );
        assert_eq!(
            authorization_server_metadata_url("https://auth.example.com/").unwrap(),
            "https://auth.example.com/.well-known/oauth-authorization-server"
        );
        assert_eq!(
            authorization_server_metadata_url("https://auth.example.com/tenant1").unwrap(),
            "https://auth.example.com/.well-known/oauth-authorization-server/tenant1"
        );
    }

    #[test]
    fn it_derives_openid_configuration_urls() {
        assert_eq!(
            openid_configuration_url("HTTPS://Auth.Example.com:443").unwrap(),
            "https://auth.example.com/.well-known/openid-configuration"
        );
        // OIDC appends after the path, unlike the RFC 8414 insertion rule
        assert_eq!(
            openid_configuration_url("https://auth.example.com/tenant1").unwrap(),
            "https://auth.example.com/tenant1/.well-known/openid-configuration"
        );
        assert_eq!(
            openid_configuration_url("https://auth.example.com/tenant1/").unwrap(),
            "https://auth.example.com/tenant1/.well-known/openid-configuration"
        );
    }

    #[test]
    fn it_rejects_underivable_metadata_urls() {
        let cases = [
            "urn:example:resource",           // no authority to insert after
            "https://api.example.com?x=1",    // query in the base URI
            "https://api.example.com/v1?x=1", // query in the base URI
            "wss://api.example.com",          // not an http(s) scheme
            "not a uri",
        ];
        for uri in cases {
            let err = protected_resource_metadata_url(uri).unwrap_err();
            assert_eq!(err.error, OAuthErrorCode::InvalidTarget, "case: {uri}");
            let err = openid_configuration_url(uri).unwrap_err();
            assert_eq!(err.error, OAuthErrorCode::InvalidTarget, "case: {uri}");
        }
    }

    #[test]
    fn it_keeps_urn_style_uris() {
        assert_eq!(
            canonicalize_resource_uri("URN:example:resource").unwrap(),
            "urn:example:resource"
        );
    }

    #[test]
    fn it_rejects_invalid_resource_uris() {
        let cases = [
            "",
            "not a uri",
            "/relative/path",
            "https://example.com/api#section",
            "https://user@example.com/api",
            "https://example.com:8o80/api",
            "https://",
            "https://[::1/api",
            "https://2001:db8::1/api",
            "1https://example.com",
            "https:api.example.com",
            "https:/api.example.com",
            "WS:example.com/socket",
            "https://[]",
            "https://[not-an-ip]/api",
            "https://[1.2.3.4]",
            "https://[fe80::1%25eth0]/api",
            "https://[v.abc]",
            "https://[v1.]",
            "https://exa[mple.com",
            "https://exa\\mple.com/api",
            "https://example.com|evil",
            "https://ex%2Gmple.com",
            "https://example.com%2",
            "https://api.example.com/%",
            "https://api.example.com/a%2",
            "https://api.example.com/|evil",
            "https://api.example.com/x?a=^b",
            "https://api.example.com/a\\b",
            "urn:example:res|ource",
            "urn:example:a%2",
        ];
        for uri in cases {
            let err = canonicalize_resource_uri(uri).unwrap_err();
            assert_eq!(err.error, OAuthErrorCode::InvalidTarget, "case: {uri}");
        }
    }
}