1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
//! Target-agnostic validation of OAuth 2.0 authorization SERVER DISCOVERY and
//! of the authorization RESPONSE (RFC 9207 `iss`, plus the CSRF `state`
//! comparison).
//!
//! This module provides the pure decision logic a client must run on the query
//! string it receives at its redirect URI, before it exchanges anything. It
//! performs no I/O: no socket, no browser, no environment read, no clock. It is
//! a function from `(query string, per-request record)` to `Result<code>`.
//!
//! It also holds the pure half of authorization server metadata discovery: the
//! hardened issuer parse
//! ([`validate_issuer_url`](crate::shared::oauth_validation::validate_issuer_url)),
//! SEP-2351's ORDERED candidate list
//! ([`discovery_url_candidates`](crate::shared::oauth_validation::discovery_url_candidates)),
//! RFC 8414 §3.3's anchor comparison
//! ([`issuer_matches_metadata`](crate::shared::oauth_validation::issuer_matches_metadata))
//! and the failure matrix every probe loop shares
//! ([`classify_discovery_failure`](crate::shared::oauth_validation::classify_discovery_failure)).
//! The PROBING — and therefore the network — belongs to the callers; that split
//! is what makes a MUST-ordered probe sequence testable offline. The same
//! module derives OpenID Connect's `application_type` from a client's
//! `redirect_uris`
//! ([`derive_application_type`](crate::shared::oauth_validation::derive_application_type)),
//! which is the value SEP-837 makes an MCP client MUST send at Dynamic Client
//! Registration.
//!
//! # Why it is ungated
//!
//! The native CLI flow in [`crate::client::oauth`] is
//! `#[cfg(all(not(target_arch = "wasm32"), feature = "oauth"))]`, and the
//! `oauth` feature pulls `webbrowser`, `dirs` and `rand` — none of which exist
//! on a Cloudflare Workers or AWS Lambda redirect handler, and none of which
//! build for `wasm32-unknown-unknown`. A platform handler that only ever sees a
//! query string must still be able to validate it, so this module is
//! **ungated**, exactly like [`crate::shared::pkce`] (contrast the
//! `#[cfg(not(target_arch = "wasm32"))]` peer/stdio entries in
//! [`crate::shared`]). Its only imports are the crate's own error type and
//! [`url`], which is a non-optional dependency and is already the callback
//! parser. **Do not add a `cfg` to this module**, and do not reach for anything
//! else: a second implementation of this table is how a platform handler and a
//! CLI come to disagree about what "valid" means.
//!
//! # The normative table this implements
//!
//! From the MCP specification's *Authorization Response Validation* section,
//! which restates RFC 9207 §2.4:
//!
//! Intra-doc links below are FULLY QUALIFIED on purpose: this module carries an
//! outer `///` rationale on its `pub mod` declaration in [`crate::shared`] as
//! well as this inner `//!` block, and rustdoc resolves the merged result in the
//! DECLARING module's scope — so a bare `IssPresence` here does not resolve and
//! `make doc-check` (which runs with `-D warnings`) fails on it.
//!
//! | `authorization_response_iss_parameter_supported` | `iss` in response | Client action |
//! |---|---|---|
//! | `true` ([`Required`](crate::shared::oauth_validation::IssPresence::Required)) | present | compare, simple string comparison |
//! | `true` | absent | **reject** |
//! | `false`/absent ([`Optional`](crate::shared::oauth_validation::IssPresence::Optional)) | present | compare, simple string comparison |
//! | `false`/absent | absent | proceed |
//!
//! Note rows 1 and 3 are the SAME action. An `iss` that is present is *always*
//! compared; the only thing the advertised flag changes is whether ABSENCE is
//! fatal. That is why
//! [`IssPresence`](crate::shared::oauth_validation::IssPresence) has no
//! "disabled" variant.
//!
//! The specification also forbids normalizing before comparison: "clients MUST
//! NOT apply scheme or host case folding, default-port elision, trailing-slash,
//! or percent-encoding normalization (RFC 3986 Sections 6.2.2-6.2.3) before
//! comparison". Comparison here is `==` on the decoded strings and nothing
//! else.
//!
//! # Examples
//!
//! ```
//! use pmcp::shared::oauth_validation::{
//! validate_authorization_response, AuthorizationRequestRecord, IssPresence,
//! };
//!
//! let record = AuthorizationRequestRecord::new(
//! "https://as.example",
//! "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
//! "opaque-csrf-state",
//! IssPresence::Required,
//! );
//!
//! let code = validate_authorization_response(
//! "code=abc123&state=opaque-csrf-state&iss=https%3A%2F%2Fas.example",
//! &record,
//! )?;
//! assert_eq!(code, "abc123");
//!
//! // A different issuer is refused, and the refusal is programmatically typed.
//! let err = validate_authorization_response(
//! "code=abc123&state=opaque-csrf-state&iss=https%3A%2F%2Fevil.example",
//! &record,
//! )
//! .unwrap_err();
//! assert!(err.is_iss_mismatch());
//! assert_eq!(err.iss_actual(), Some("https://evil.example"));
//! # Ok::<(), pmcp::Error>(())
//! ```
use crate;
use ;
/// The largest authorization-callback query this module will parse, in bytes.
///
/// The callback query is peer-controlled and unbounded on the wire — the
/// loopback listener reads it straight off a socket, and a platform handler
/// gets whatever the user-agent sent. 8 KiB is roughly an order of magnitude
/// above the largest legitimate response (a `code` and a `state` are each
/// well under 100 bytes, and `error_description` is prose), so a query over it
/// is refused BEFORE parsing rather than allocated and then measured.
pub const MAX_CALLBACK_QUERY_BYTES: usize = 8192;
/// The parameters whose repetition is refused, in the order they are reported.
///
/// Documented as a constant so the rustdoc, the refusal and the tests cannot
/// drift apart.
const SECURITY_PARAMETERS: & = &;
/// Whether the authorization server's metadata promised an `iss` parameter.
///
/// This is the ONLY configurable part of the decision table. An `iss` that is
/// present is always compared against the recorded issuer whatever this says —
/// that floor is unconditional — so there is deliberately no `Disabled`
/// variant. The choice is only whether ABSENCE of `iss` is fatal.
///
/// `#[non_exhaustive]` because a future specification revision may add a third
/// state (for example, a "required by policy regardless of metadata" tier), and
/// adding an enum variant to an exhaustive public enum is a MAJOR semver break.
/// The per-request record the specification requires a client to keep.
///
/// > "Before redirecting the user-agent, the client MUST record the `issuer`
/// > value from the selected authorization server's validated metadata document
/// > ... and associate it with the same per-request record used to store the
/// > PKCE code verifier (and the `state` value, if used)."
///
/// **One record, not three locals.** The specification's "same per-request
/// record" is a structural requirement, not a stylistic one: when the issuer,
/// the verifier and the state live in three separate variables, nothing stops a
/// flow from validating one request's `state` against another request's record,
/// and nothing makes it a compile error to forget one of them entirely. Binding
/// them into a single value is what makes the validation checkable.
///
/// The fields are PRIVATE and the type is constructed through
/// [`AuthorizationRequestRecord::new`]. That is a semver choice rather than a
/// style one: an all-public-field struct that is not `#[non_exhaustive]` is
/// exhaustively constructible downstream, so adding a field to it is a MAJOR
/// break (`constructible_struct_adds_field`) — which is precisely the trap
/// `OAuthConfig`, `DcrRequest` and `OidcDiscoveryMetadata` already sit in.
/// (Deliberately NOT linked: those three live behind feature gates this ungated
/// module must not assume are enabled.) With private fields, a future field is
/// a minor change.
///
/// The validation is only as good as the recorded issuer: it "provides no
/// protection if the expected issuer was obtained from an unvalidated source".
/// Redacts the two secrets so a `{:?}` of a record — in a log line, a panic
/// message or a caller's own error type — cannot leak the CSRF `state` or the
/// PKCE verifier. Every field is still named, so the shape stays legible.
/// The five security parameters, extracted at most once each.
/// Validate an authorization response and return its authorization `code`.
///
/// `raw_query` is the RAW query component with no leading `?` — the form a
/// platform redirect handler receives directly, so a Workers or Lambda function
/// can call this without reconstructing a URL. It is decoded with
/// `application/x-www-form-urlencoded` rules, as RFC 9207 §2.4 REQUIRES before
/// any comparison; never hand-roll that percent-decode.
///
/// # Evaluation order, which is load-bearing
///
/// 1. **`state`** — must be present and equal the recorded value, else
/// [`Error::state_mismatch`].
/// 2. **`iss`** — the four-row table of the module doc, compared with `==` and
/// NO normalization of any kind, else [`Error::iss_mismatch`].
/// 3. **`error`** — only now may an authorization-server-supplied `error` be
/// surfaced. The specification's prohibition is explicit: on an `iss`
/// mismatch the client "MUST NOT act on or display `error`,
/// `error_description`, or `error_uri`". Surfacing it earlier would let an
/// unauthenticated party choose text the client displays.
/// 4. **`code`** — present means success; absent with no `error` is a protocol
/// error naming the missing parameter.
///
/// # Two fail-closed input guards, applied before step 1
///
/// - **Size.** A `raw_query` longer than [`MAX_CALLBACK_QUERY_BYTES`] is
/// refused without being parsed. The refusal names the limit and the observed
/// length and reproduces none of the query.
/// - **Duplicates.** Any of `state`, `iss`, `code`, `error` or
/// `error_description` appearing more than once is refused. A "first wins"
/// rule on a security parameter is a request-smuggling primitive: a proxy or
/// server that takes the LAST occurrence and a client that takes the FIRST
/// disagree about what was validated. Unknown and vendor parameters may
/// repeat freely — they are ignored either way.
///
/// # Errors
///
/// Returns [`Error::state_mismatch`] for a missing or non-matching `state`,
/// [`Error::iss_mismatch`] for a failing `iss` row, and a protocol error for an
/// oversize query, a duplicated security parameter, an authorization-server
/// error response that survived steps 1-2, or a response carrying neither
/// `code` nor `error`.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::{
/// validate_authorization_response, AuthorizationRequestRecord, IssPresence,
/// };
///
/// let record = AuthorizationRequestRecord::new(
/// "https://as.example",
/// "verifier",
/// "st4te",
/// IssPresence::Optional,
/// );
///
/// // Row 4: nothing advertised, nothing sent — proceed.
/// assert_eq!(
/// validate_authorization_response("code=abc&state=st4te", &record)?,
/// "abc",
/// );
///
/// // A forged state is refused, and the refusal names neither value.
/// let err = validate_authorization_response("code=abc&state=wrong", &record).unwrap_err();
/// assert!(err.is_state_mismatch());
/// assert!(!err.to_string().contains("st4te"));
/// # Ok::<(), pmcp::Error>(())
/// ```
/// Refuse an oversize query before a single byte of it is parsed.
/// Decode the query once, taking each security parameter at most once.
///
/// The single pass is both the extraction and the duplicate check: a second
/// occurrence of an already-filled slot is the refusal, so there is no window
/// in which a "first wins" value has been adopted.
/// The refusal for a repeated security parameter.
///
/// The key is safe to name: this is only ever reached for one of
/// [`SECURITY_PARAMETERS`], so no attacker-chosen text reaches the message.
/// Step 1: the CSRF `state` comparison (the specification's D-12 obligation).
///
/// Absence is a mismatch, not a skip: a response that simply omits `state` must
/// not be treated as one that matched.
/// Step 2: the four-row `iss` table, with no normalization whatsoever.
/// Step 3: surface an authorization server's own error, once it has earned the
/// right to be displayed by surviving steps 1 and 2.
/// Step 4: neither outcome parameter was present.
/// Parse the operator-supplied `iss` validation setting, or reject it.
///
/// Accepts `"strict"` ([`IssPresence::Required`]) and `"lenient"`
/// ([`IssPresence::Optional`]), compared case-insensitively after trimming.
/// Everything else — including `"true"`, `"1"` and `"yes"`, which a reasonable
/// operator might well type — returns `None`.
///
/// # Why this is separate from [`iss_presence_from`]
///
/// With a single resolver taking `Option<&str>`, an UNRECOGNIZED value would be
/// indistinguishable from an unset variable, so an operator who wrote
/// `PMCP_OAUTH_ISS_VALIDATION=true` believing they had enabled strictness would
/// get silence and lenient behaviour. Keeping the parse separate lets the call
/// site see `Some(raw)` with a `None` parse and warn — naming the variable and
/// its two accepted values — before falling through to the next precedence
/// tier. **Do not merge these two functions.**
///
/// The environment variable's NAME is read at the call site, never here: this
/// module performs no environment access at all.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::{parse_iss_env_value, IssPresence};
///
/// assert_eq!(parse_iss_env_value(" STRICT "), Some(IssPresence::Required));
/// assert_eq!(parse_iss_env_value("lenient"), Some(IssPresence::Optional));
/// // A plausible-but-wrong value is rejected LOUDLY rather than failing open.
/// assert_eq!(parse_iss_env_value("true"), None);
/// ```
/// Resolve the effective [`IssPresence`] from the three precedence tiers.
///
/// Precedence is **environment override > builder setting > discovery flag**.
/// `env_override` is ALREADY PARSED — see [`parse_iss_env_value`] for why the
/// parse is deliberately not folded in here. `discovery_flag` is the
/// authorization server metadata's
/// `authorization_response_iss_parameter_supported`: `Some(true)` means
/// [`IssPresence::Required`]; `Some(false)` and `None` both mean
/// [`IssPresence::Optional`], because the specification treats "false" and
/// "absent" identically.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::{iss_presence_from, IssPresence};
///
/// // The environment wins over both lower tiers.
/// assert_eq!(
/// iss_presence_from(Some(IssPresence::Required), Some(IssPresence::Optional), Some(false)),
/// IssPresence::Required,
/// );
/// // With no override, an advertising authorization server makes it required.
/// assert_eq!(
/// iss_presence_from(None, None, Some(true)),
/// IssPresence::Required,
/// );
/// // Silence all the way down is the lenient floor.
/// assert_eq!(iss_presence_from(None, None, None), IssPresence::Optional);
/// ```
/// RFC 8414 §3.1's default well-known URI suffix, which MCP adopts explicitly
/// and which pmcp does not try today.
const WELL_KNOWN_OAUTH_AUTHORIZATION_SERVER: &str = "oauth-authorization-server";
/// `OpenID` Connect Discovery 1.0 §4.1's well-known URI suffix.
const WELL_KNOWN_OPENID_CONFIGURATION: &str = "openid-configuration";
/// Parse an authorization server issuer identifier, enforcing RFC 8414 §2.
///
/// Parsing as an absolute [`Url`] is **not** sufficient, which is why this
/// function exists rather than a bare `Url::parse` at each call site. Every
/// rule below is enforced, and every rejection names the rule it enforced:
///
/// | Rule | Reason |
/// |---|---|
/// | scheme MUST be `https` | an issuer identified over cleartext can be swapped in transit |
/// | except `http` on a loopback host | pmcp's own development and test flows use loopback, and RFC 8252 §7.3 blesses it |
/// | userinfo MUST be absent | `https://honest.example@evil.example` reads as the honest host to a human and resolves to the attacker's; no legitimate issuer has userinfo |
/// | fragment MUST be absent | RFC 8414 §2 |
/// | query MUST be absent | RFC 8414 §2, and a query would survive into the built candidate URL |
/// | host MUST be present and non-empty | there is nothing to connect to otherwise |
///
/// The loopback exception accepts the three spellings a real flow produces: an
/// IPv4 loopback literal (canonically `127.0.0.1`), the IPv6 literal `::1` in
/// its bracketed authority form `[::1]`, and the name `localhost`. A listener
/// that binds IPv4 while a browser resolves `localhost` to `::1` is precisely
/// why all three must be accepted.
///
/// The parsed [`Url`] is returned so callers do not re-parse. Every other
/// function in this family calls this one first.
///
/// # Errors
///
/// Returns [`Error::Validation`] naming the specific rule violated — never a
/// generic "invalid URL". The refusal deliberately does **not** reproduce the
/// offending issuer string: an issuer can carry a userinfo password, and an
/// error message ends up in logs. The scheme and host are named instead, since
/// neither is a credential.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::validate_issuer_url;
///
/// let parsed = validate_issuer_url("https://auth.example.com/tenant1")?;
/// assert_eq!(parsed.host_str(), Some("auth.example.com"));
///
/// // The loopback development exception is the ONLY permitted `http`.
/// assert!(validate_issuer_url("http://127.0.0.1:8080").is_ok());
/// assert!(validate_issuer_url("http://auth.example.com").is_err());
///
/// // Userinfo is authority confusion, and is refused outright.
/// assert!(validate_issuer_url("https://honest.example@evil.example").is_err());
/// # Ok::<(), pmcp::Error>(())
/// ```
/// `https` always, `http` only on a loopback host.
/// Whether the authority is one of the loopback spellings RFC 8252 §7.3 blesses.
/// The refusal for a string that is not an absolute URL at all.
/// The refusal for a scheme outside the `https` rule and its loopback exception.
/// The refusal for a userinfo component, which never names the value.
/// The refusal for a fragment or a query, both forbidden by RFC 8414 §2.
/// Derive SEP-2351's ORDERED list of authorization server metadata endpoints.
///
/// # This is an ordered probe sequence, not a replacement
///
/// RFC 8414 §3.1 specifies **insertion** of the well-known segment for the
/// `oauth-authorization-server` suffix; `OpenID` Connect Discovery 1.0 §4.1
/// specifies **appending** for `openid-configuration`; RFC 8414 §5 reconciles
/// the two with a fallback order, and the MCP specification makes that order a
/// client MUST. The caller probes the candidates in the order returned and uses
/// the first that yields a valid document.
///
/// The appended form — candidate 3 for a path-bearing issuer, candidate 2 for a
/// path-less one — is today's only pmcp behaviour and it MUST remain in the
/// list. Measured 2026-08-02 against Microsoft Entra ID, whose URL appears in
/// this SDK's own doctests: the appended form returns **200**, and both
/// inserted forms return **404**. An implementation that "fixed" discovery by
/// replacing append with insert would break every authorization server of that
/// shape.
///
/// For an issuer WITH a path component, e.g. `https://auth.example.com/tenant1`:
///
/// 1. `https://auth.example.com/.well-known/oauth-authorization-server/tenant1`
/// 2. `https://auth.example.com/.well-known/openid-configuration/tenant1`
/// 3. `https://auth.example.com/tenant1/.well-known/openid-configuration`
///
/// For an issuer WITHOUT one, e.g. `https://auth.example.com`, candidates 2 and
/// 3 coincide, so the list is exactly two:
///
/// 1. `https://auth.example.com/.well-known/oauth-authorization-server`
/// 2. `https://auth.example.com/.well-known/openid-configuration`
///
/// # Why the probing is NOT here
///
/// This function derives candidates only. The network belongs to the callers,
/// and that split is what makes a MUST-ordered sequence testable offline and in
/// a `wasm32` build. The failure-handling half of the probe loop is
/// [`classify_discovery_failure`].
///
/// # Errors
///
/// Returns whatever
/// [`validate_issuer_url`]
/// rejects. A hostile issuer never reaches candidate construction, so no
/// partially-formed URL is ever produced.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::discovery_url_candidates;
///
/// let candidates = discovery_url_candidates("https://auth.example.com/tenant1")?;
/// let rendered: Vec<&str> = candidates.iter().map(|url| url.as_str()).collect();
/// assert_eq!(
/// rendered,
/// vec![
/// "https://auth.example.com/.well-known/oauth-authorization-server/tenant1",
/// "https://auth.example.com/.well-known/openid-configuration/tenant1",
/// "https://auth.example.com/tenant1/.well-known/openid-configuration",
/// ],
/// );
///
/// // A path-less issuer has exactly two candidates, and a trailing slash is
/// // a formatting difference rather than a path component.
/// assert_eq!(
/// discovery_url_candidates("https://auth.example.com/")?,
/// discovery_url_candidates("https://auth.example.com")?,
/// );
/// # Ok::<(), pmcp::Error>(())
/// ```
/// RFC 8414 §3.1's insertion form: the well-known segment goes between the host
/// and the issuer's path.
/// `OpenID` Connect Discovery 1.0 §4.1's appended form, and pmcp's only form
/// before SEP-2351.
/// Compare a discovery document's `issuer` against the issuer used to build the
/// URL it came from — RFC 8414 §3.3 / `OpenID` Connect Discovery §4.3.
///
/// The comparison is a simple string comparison with **no normalization**: the
/// same rule, from the same family of specifications, as the RFC 9207 `iss`
/// comparison in
/// [`validate_authorization_response`].
///
/// # Why this function exists at all
///
/// The specification's own worked example: a document fetched from
/// `https://attacker.example/.well-known/oauth-authorization-server` that
/// contains `"issuer": "https://honest.example"` MUST be rejected.
///
/// Without this check, the `iss` validation is anchored on a value the
/// authorization server chose for itself, so an attacker who can influence
/// discovery serves a document naming any issuer they like and the RFC 9207
/// comparison then trivially succeeds against it. The authorization
/// specification says so directly: the `iss` validation "provides no protection
/// if the expected issuer was obtained from an unvalidated source".
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::issuer_matches_metadata;
///
/// assert!(issuer_matches_metadata("https://as.example", "https://as.example"));
///
/// // The specification's worked attack.
/// assert!(!issuer_matches_metadata("https://attacker.example", "https://honest.example"));
///
/// // No normalization of any kind — a trailing slash is a different issuer.
/// assert!(!issuer_matches_metadata("https://as.example", "https://as.example/"));
/// ```
/// Whether two URLs share an origin: scheme, host and EFFECTIVE port.
///
/// The effective port is what makes `https://as.example` and
/// `https://as.example:443` the same origin. The path is deliberately not part
/// of the comparison, because an origin is not a location.
///
/// Callers use this to judge a discovery HTTP redirect: a redirect that stays
/// within the issuer's origin is ordinary server routing, while one that leaves
/// it hands document authorship to a different host and must be refused.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::same_origin;
/// use url::Url;
///
/// let a = Url::parse("https://as.example/.well-known/openid-configuration")?;
/// let b = Url::parse("https://as.example:443/elsewhere")?;
/// assert!(same_origin(&a, &b));
///
/// let elsewhere = Url::parse("https://cdn.example/.well-known/openid-configuration")?;
/// assert!(!same_origin(&a, &elsewhere));
/// # Ok::<(), url::ParseError>(())
/// ```
/// Why one discovery candidate did not yield a usable metadata document.
///
/// The distinction the enum draws is not "which error" but "what the failure
/// says about the endpoint": whether nothing usable ARRIVED, or whether bytes
/// arrived and cannot be trusted. That is the distinction
/// [`classify_discovery_failure`]
/// turns into an outcome.
///
/// `#[non_exhaustive]` because a future revision may name a failure class this
/// one does not, and adding a variant to an exhaustive public enum is a MAJOR
/// semver break.
/// What a caller does about a [`DiscoveryFailure`].
///
/// # How the three compose in a probe loop
///
/// `Retry` means "re-attempt **this** candidate within the existing
/// `max_retries` budget, and once that budget is exhausted treat it as
/// `Fallback`". `Fallback` means "move to the next candidate; if there is none,
/// discovery has failed". `Terminal` means "abort discovery outright — do not
/// retry, do not try another candidate, and do not use any document".
///
/// Both discovery call sites implement that same loop, which is why the rule is
/// written here rather than in either of them.
///
/// `#[non_exhaustive]` for the same semver reason as
/// [`DiscoveryFailure`].
/// The discovery outcome matrix, as one pure function.
///
/// | Failure | Outcome | Why |
/// |---|---|---|
/// | `NotFound` (404) | `Fallback` | the ordinary "not this form" answer; the whole reason there is an ordered list |
/// | `HttpStatus(4xx)` other than 404 | `Fallback` | the endpoint answered and refused; another form may still serve |
/// | `HttpStatus(5xx)` | `Retry` | the endpoint is the right one and is temporarily unwell |
/// | `Transport` | `Retry` | nothing arrived; a retry is the only way to distinguish transient from permanent |
/// | `InvalidJson` | `Fallback` | this endpoint does not serve the document; another form may |
/// | `IssuerMismatch` | `Terminal` | a document ARRIVED and lied about its issuer |
/// | `BodyOverCap` | `Terminal` | a peer sent more than a metadata document can legitimately be |
/// | `MalformedSecurityMetadata` | `Terminal` | a document ARRIVED with a broken security member |
///
/// # Why three of the rows are terminal
///
/// Falling through to a later candidate on "any" failure turns an issuer
/// mismatch, malformed metadata or an oversized body into a silent DOWNGRADE:
/// an attacker who can make candidate 1 fail in a security-relevant way gets
/// the client to accept candidate 3 instead. The three terminal rows are the
/// whole point of the matrix — they are never a fallback trigger, and no
/// peer-chosen status code can make an availability failure terminal either.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::{
/// classify_discovery_failure, DiscoveryFailure, DiscoveryOutcome,
/// };
///
/// // A 404 is what the ordered probe is FOR.
/// assert_eq!(
/// classify_discovery_failure(DiscoveryFailure::NotFound),
/// DiscoveryOutcome::Fallback,
/// );
/// // A document that lied about its issuer aborts discovery; it never causes
/// // the client to quietly accept a later candidate instead.
/// assert_eq!(
/// classify_discovery_failure(DiscoveryFailure::IssuerMismatch),
/// DiscoveryOutcome::Terminal,
/// );
/// ```
/// `OpenID` Connect's `application_type` client metadata value.
///
/// SEP-837 makes an MCP client MUST specify this at Dynamic Client
/// Registration: "Omitting it defaults to `web` under OIDC, which can conflict
/// with native-style redirect URIs; non-OIDC servers safely ignore the
/// parameter."
///
/// `#[non_exhaustive]` because `OpenID` Connect permits an authorization server
/// to define further values, and adding a variant to an exhaustive public enum
/// is a MAJOR semver break.
/// Derive [`ApplicationType`] from the `redirect_uris` a client is about to
/// register, requiring UNANIMITY.
///
/// | Redirect URI shape | Classification |
/// |---|---|
/// | loopback host (`127.0.0.1`, `::1` including the bracketed `[::1]` form, `localhost`) | `Native` |
/// | a scheme that is neither `http` nor `https` (a private-use scheme) | `Native` |
/// | `https` with a non-loopback host | `Web` |
/// | `http` with a non-loopback host | **error** |
///
/// # This is a heuristic for the common case, not the specification's rule
///
/// SEP-837 classifies by application NATURE — "desktop applications, mobile
/// apps, CLI tools, and locally-hosted web applications accessed via
/// `localhost`" are native; "remote browser-based applications served from a
/// non-local host" are web. This function instead derives from
/// `redirect_uris`, because that is the value a caller has in hand at the
/// registration site.
///
/// The two agree for every case pmcp produces: pmcp's own DCR call hardcodes
/// `http://127.0.0.1:{port}/callback` (RFC 8252 §7.3) and therefore derives
/// `native`, while a platform `oauth-proxy` with an https redirect derives
/// `web`. Where they disagree, `DcrRequest::set_application_type` remains the
/// authoritative override — it deliberately performs no validation precisely so
/// that it can override this derivation.
///
/// # Why a mixed vector is an error rather than a pick
///
/// Picking one classification for a vector that contains both would register a
/// client whose declared type contradicts some of its own redirect URIs. An
/// authorization server enforcing OIDC's redirect-URI constraints per type will
/// then either reject the registration (best case) or accept a redirect URI it
/// should have refused — which is an open-redirect primitive. The refusal names
/// both offending URIs and both classifications, because the operator's next
/// action is to decide which one the client actually is.
///
/// # Errors
///
/// Returns [`Error::Validation`] for an empty `redirect_uris`, an unparseable
/// redirect URI, a cleartext `http` redirect to a non-loopback host, and a
/// mixed classification. Never a silent default: every one of those is a case
/// where guessing decides where an authorization code is delivered.
///
/// # Examples
///
/// ```
/// use pmcp::shared::oauth_validation::{derive_application_type, ApplicationType};
///
/// // What pmcp's own Dynamic Client Registration call registers.
/// let native = vec!["http://127.0.0.1:8080/callback".to_string()];
/// assert_eq!(derive_application_type(&native)?, ApplicationType::Native);
/// assert_eq!(derive_application_type(&native)?.as_str(), "native");
///
/// // A remote, browser-based deployment.
/// let web = vec!["https://app.example.com/callback".to_string()];
/// assert_eq!(derive_application_type(&web)?, ApplicationType::Web);
///
/// // A mixed vector is refused, and the refusal names both offenders.
/// let mixed = vec![native[0].clone(), web[0].clone()];
/// let err = derive_application_type(&mixed).unwrap_err();
/// assert!(err.to_string().contains("app.example.com"));
/// # Ok::<(), pmcp::Error>(())
/// ```
/// Classify one redirect URI, in the rule order documented on
/// [`derive_application_type`].
/// The refusal for `redirect_uris: []`.
/// The refusal for a redirect URI that is not a URI.
/// The refusal for cleartext `http` to a host that is not loopback.
/// The refusal for a `redirect_uris` vector that classifies both ways.