wyrd-spec 0.1.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
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
//! OIDC login contracts and URL newtypes.

use std::fmt;
use std::str::FromStr;

use schemars::JsonSchema;
use schemars::r#gen::SchemaGenerator;
use schemars::schema::{InstanceType, Metadata, Schema, SchemaObject, StringValidation};
use serde::{Deserialize, Deserializer, Serialize};
use sha2::Digest as _;
#[cfg(feature = "server")]
use utoipa::openapi::schema::{ObjectBuilder, Schema as OpenApiSchema, Type};
use uuid::Uuid;

use crate::auth::{OAuthClientId, PrincipalId, PrincipalKindTag, SecretBearer};
use crate::error::WyrdError;

/// Absolute URL used by auth contracts.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct AbsoluteUrl(String);

impl AbsoluteUrl {
    /// Build a validated absolute URL.
    ///
    /// # Errors
    /// Returns [`UrlParseError`] when the value is not an absolute `https` or `http` URL with an authority.
    pub fn new(value: impl Into<String>) -> Result<Self, UrlParseError> {
        let value = value.into();
        validate_absolute_url(&value)?;
        Ok(Self(value))
    }

    /// Borrow the URL string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for AbsoluteUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for AbsoluteUrl {
    type Err = UrlParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl<'de> Deserialize<'de> for AbsoluteUrl {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

impl JsonSchema for AbsoluteUrl {
    fn schema_name() -> String {
        "AbsoluteUrl".to_owned()
    }

    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
        url_schema(
            "Absolute URL with a scheme and authority.",
            Some("^https?://"),
        )
    }
}

#[cfg(feature = "server")]
impl utoipa::PartialSchema for AbsoluteUrl {
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        openapi_url_schema("Absolute URL with a scheme and authority.")
    }
}

#[cfg(feature = "server")]
impl utoipa::ToSchema for AbsoluteUrl {}

/// Trusted OIDC issuer URL.
///
/// The constructor validates the URL and removes trailing slashes so issuer
/// comparisons use one canonical string form.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct IssuerUrl(String);

impl IssuerUrl {
    /// Build a normalized issuer URL.
    ///
    /// # Errors
    /// Returns [`UrlParseError`] when the value is not an absolute `https` URL with an authority.
    pub fn new(value: impl Into<String>) -> Result<Self, UrlParseError> {
        let value = value.into();
        validate_issuer_url(&value)?;
        Ok(Self(normalize_issuer(&value)))
    }

    /// Borrow the normalized issuer string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Build a normalized issuer URL accepting `http://` scheme.
    ///
    /// Only for use in test harnesses against local containers (Keycloak, Dex).
    /// Production code must use [`IssuerUrl::new`] which enforces `https://`.
    #[cfg(any(test, feature = "test-utils"))]
    pub fn new_for_tests(value: impl Into<String>) -> Self {
        let value = value.into();
        Self(normalize_issuer(&value))
    }
}

impl fmt::Display for IssuerUrl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for IssuerUrl {
    type Err = UrlParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

impl<'de> Deserialize<'de> for IssuerUrl {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

impl JsonSchema for IssuerUrl {
    fn schema_name() -> String {
        "IssuerUrl".to_owned()
    }

    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
        url_schema(
            "Absolute OIDC issuer URL. Trailing slashes are normalized away.",
            Some("^https://"),
        )
    }
}

#[cfg(feature = "server")]
impl utoipa::PartialSchema for IssuerUrl {
    fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
        openapi_url_schema("Absolute OIDC issuer URL. Trailing slashes are normalized away.")
    }
}

#[cfg(feature = "server")]
impl utoipa::ToSchema for IssuerUrl {}

/// Platform-administrator login initiation response.
///
/// The platform plane posts the provider's `code` and `state` back itself, so
/// it receives the state here. Tenant human login never does: the browser
/// carries it to the provider inside the authorization redirect.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct LoginInitResponse {
    /// Authorization URL used as the redirect target.
    pub authorization_url: AbsoluteUrl,
    /// Opaque login state echoed for SDK correlation.
    pub state: String,
}

/// A SHA-256 digest in its canonical wire form: exactly 64 lowercase
/// hexadecimal characters.
///
/// Used where the server records only the digest of a secret it handed out,
/// such as a login state, authorization code, or device code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Sha256Hex([u8; 32]);

impl Sha256Hex {
    /// Parse a canonical digest.
    ///
    /// # Errors
    /// Returns [`Sha256HexError`] when the value is not exactly 64 lowercase
    /// hexadecimal characters. Uppercase is refused rather than normalized so
    /// one digest has one wire form.
    pub fn new(value: &str) -> Result<Self, Sha256HexError> {
        if value.len() != 64
            || !value
                .bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
        {
            return Err(Sha256HexError);
        }
        let mut digest = [0_u8; 32];
        hex::decode_to_slice(value, &mut digest).map_err(|_| Sha256HexError)?;
        Ok(Self(digest))
    }

    /// Digest `bytes` with SHA-256.
    #[must_use]
    pub fn digest(bytes: &[u8]) -> Self {
        Self(sha2::Sha256::digest(bytes).into())
    }

    /// The raw 32-byte digest.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }
}

impl From<[u8; 32]> for Sha256Hex {
    /// Wrap an already-computed raw digest, such as one read back from storage.
    fn from(digest: [u8; 32]) -> Self {
        Self(digest)
    }
}

impl fmt::Display for Sha256Hex {
    /// Write the canonical wire form: the 32 raw bytes as 64 lowercase
    /// hexadecimal characters, the only form [`Sha256Hex::new`] accepts.
    ///
    /// # Errors
    /// Returns [`fmt::Error`] only when the underlying formatter's writer
    /// fails; encoding itself cannot fail.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&hex::encode(self.0))
    }
}

impl Serialize for Sha256Hex {
    /// Serialize as the canonical lowercase-hex string produced by
    /// [`fmt::Display`], so the wire form round-trips through
    /// [`Deserialize`].
    ///
    /// # Errors
    /// Returns the serializer's error when it cannot accept a string.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'de> Deserialize<'de> for Sha256Hex {
    /// Deserialize from a string and validate it with [`Sha256Hex::new`], so
    /// the wire accepts exactly the canonical lowercase-hex form.
    ///
    /// # Errors
    /// Returns the deserializer's error when the input is not a string, and a
    /// custom error carrying [`Sha256HexError`] when the string is not exactly
    /// 64 lowercase hexadecimal characters.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(&value).map_err(serde::de::Error::custom)
    }
}

impl JsonSchema for Sha256Hex {
    /// Name the schema `Sha256Hex` so generated contracts reference one shared
    /// definition.
    fn schema_name() -> String {
        "Sha256Hex".to_owned()
    }

    /// Describe the canonical wire form as a 64-character string constrained
    /// by [`SHA256_HEX_PATTERN`], mirroring the validation in
    /// [`Sha256Hex::new`] and the `OpenAPI` projection.
    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
        Schema::Object(SchemaObject {
            metadata: Some(Box::new(Metadata {
                description: Some(SHA256_HEX_DESCRIPTION.to_owned()),
                ..Default::default()
            })),
            instance_type: Some(InstanceType::String.into()),
            string: Some(Box::new(StringValidation {
                min_length: Some(64),
                max_length: Some(64),
                pattern: Some(SHA256_HEX_PATTERN.to_owned()),
            })),
            ..Default::default()
        })
    }
}

#[cfg(feature = "server")]
impl utoipa::PartialSchema for Sha256Hex {
    /// Describe the canonical wire form for `OpenAPI` with the same length,
    /// pattern, and description as the JSON Schema projection, so both
    /// generated contracts agree with [`Sha256Hex::new`].
    fn schema() -> utoipa::openapi::RefOr<OpenApiSchema> {
        utoipa::openapi::RefOr::T(OpenApiSchema::Object(
            ObjectBuilder::new()
                .schema_type(Type::String)
                .min_length(Some(64))
                .max_length(Some(64))
                .pattern(Some(SHA256_HEX_PATTERN))
                .description(Some(SHA256_HEX_DESCRIPTION))
                .build(),
        ))
    }
}

#[cfg(feature = "server")]
impl utoipa::ToSchema for Sha256Hex {}

/// Description shared by the JSON Schema and `OpenAPI` projections of
/// [`Sha256Hex`].
const SHA256_HEX_DESCRIPTION: &str =
    "SHA-256 digest as exactly 64 lowercase hexadecimal characters.";

/// Pattern shared by the JSON Schema and `OpenAPI` projections of
/// [`Sha256Hex`].
const SHA256_HEX_PATTERN: &str = "^[0-9a-f]{64}$";

/// A value that is not a canonical [`Sha256Hex`] digest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("expected a SHA-256 digest as 64 lowercase hexadecimal characters")]
pub struct Sha256HexError;

/// How a tenant human login was initiated: what its verified sign-in grants.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoginInitiation {
    /// An OAuth authorization request (RFC 6749 ยง4.1.1): the sign-in issues
    /// that client an authorization code.
    Authorize(ClientAuthorization),
    /// A device-code login (RFC 8628) bound to its device authorization id:
    /// the sign-in records the device's approval.
    Device(Uuid),
    /// A candidate connection test begun by this principal. Its sign-in marks
    /// the bound candidate revision tested and issues nothing.
    ConnectionTest(ConnectionTester),
}

/// The validated authorization request (RFC 6749 ยง4.1.1) a login answers.
///
/// Recorded on the login state, so the authorization code the callback issues
/// is bound to exactly this client, redirect URI, and PKCE challenge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientAuthorization {
    /// The requesting client.
    pub client: OAuthClientId,
    /// The client's registered redirect URI the request named exactly.
    pub redirect_uri: String,
    /// The PKCE S256 code challenge (RFC 7636 ยง4.3).
    pub code_challenge: String,
    /// The client's opaque `state`, echoed on the redirect.
    pub state: Option<String>,
}

/// The authorized caller a candidate connection test was begun by.
///
/// Recorded on the test's login state so the callback can re-check that
/// principal's authority before it marks the candidate tested.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnectionTester {
    /// The principal that began the test.
    pub principal_id: PrincipalId,
    /// That principal's kind, which names where its roles are stored.
    pub principal_kind: PrincipalKindTag,
}

/// `GET /auth/callback` query: the provider's redirect back to the common
/// callback. It carries no tenant selector.
///
/// `state` is required, with exactly one of the success `code` (RFC 6749
/// ยง4.1.2) or the provider's `error` (ยง4.1.2.1); [`Self::response`] names
/// which. The RFC 9207 `iss` response parameter is retained when present so
/// the callback can bind the response to the issuer the login state recorded
/// before any token-endpoint request. Other provider response parameters
/// (`error_description`, Keycloak's `session_state`) are ignored, as RFC 6749
/// ยง4.1.2 requires of the client, so no provider text is ever reflected.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct CallbackQuery {
    /// Authorization code from the identity provider, on success.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code: Option<SecretBearer>,
    /// The provider's RFC 6749 ยง4.1.2.1 error code, when it refused.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    /// Opaque login state generated by Wyrd.
    #[schemars(schema_with = "state_key_schema")]
    pub state: String,
    /// RFC 9207 authorization-response issuer identifier, when the provider
    /// sends one. It must equal the login's recorded issuer exactly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub iss: Option<String>,
}

impl CallbackQuery {
    /// The provider's answer: its code or its error, never both or neither.
    ///
    /// # Errors
    /// Returns [`WyrdError::Validation`] when the query carries both `code`
    /// and `error`, or neither.
    pub fn response(&self) -> Result<ProviderResponse, WyrdError> {
        match (&self.code, &self.error) {
            (Some(code), None) => Ok(ProviderResponse::Code(code.clone())),
            (None, Some(error)) => Ok(ProviderResponse::Error(error.clone())),
            _ => Err(WyrdError::Validation {
                message: "the callback carries exactly one of `code` or `error`".to_owned(),
                details: serde_json::json!({}),
            }),
        }
    }
}

/// What the identity provider's authorization response answered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProviderResponse {
    /// RFC 6749 ยง4.1.2: the authorization code to redeem.
    Code(SecretBearer),
    /// RFC 6749 ยง4.1.2.1: the provider's error code, such as
    /// `access_denied`.
    Error(String),
}

/// URL validation failure.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum UrlParseError {
    /// The string is not a valid URL.
    #[error("URL failed to parse: {0}")]
    ParseFailed(String),
    /// The URL has no authority (host) component.
    #[error("URL must have an authority (host)")]
    NoHost,
    /// The URL scheme is not permitted by this validator.
    #[error("URL scheme '{0}' is not allowed")]
    DisallowedScheme(String),
}

fn validate_absolute_url(value: &str) -> Result<(), UrlParseError> {
    let parsed = url::Url::parse(value).map_err(|e| UrlParseError::ParseFailed(e.to_string()))?;
    if !parsed.has_host() {
        return Err(UrlParseError::NoHost);
    }
    match parsed.scheme() {
        "https" | "http" => Ok(()),
        scheme => Err(UrlParseError::DisallowedScheme(scheme.to_owned())),
    }
}

fn validate_issuer_url(value: &str) -> Result<(), UrlParseError> {
    let parsed = url::Url::parse(value).map_err(|e| UrlParseError::ParseFailed(e.to_string()))?;
    if !parsed.has_host() {
        return Err(UrlParseError::NoHost);
    }
    match parsed.scheme() {
        "https" => Ok(()),
        // `http` is permitted only for loopback issuers (local Keycloak/Dex
        // e2e fixtures). Every non-loopback host stays https-only.
        "http" if is_loopback_host(&parsed) => Ok(()),
        scheme => Err(UrlParseError::DisallowedScheme(scheme.to_owned())),
    }
}

fn is_loopback_host(parsed: &url::Url) -> bool {
    match parsed.host() {
        Some(url::Host::Domain(host)) => host == "localhost",
        Some(url::Host::Ipv4(addr)) => addr.is_loopback(),
        Some(url::Host::Ipv6(addr)) => addr.is_loopback(),
        None => false,
    }
}

fn normalize_issuer(value: &str) -> String {
    value.trim_end_matches('/').to_owned()
}

fn url_schema(description: &'static str, pattern: Option<&'static str>) -> Schema {
    Schema::Object(SchemaObject {
        metadata: Some(Box::new(Metadata {
            description: Some(description.to_owned()),
            ..Default::default()
        })),
        instance_type: Some(InstanceType::String.into()),
        format: Some("uri".to_owned()),
        string: pattern.map(|p| {
            Box::new(StringValidation {
                pattern: Some(p.to_owned()),
                ..Default::default()
            })
        }),
        ..Default::default()
    })
}

fn state_key_schema(_gen: &mut SchemaGenerator) -> Schema {
    Schema::Object(SchemaObject {
        instance_type: Some(InstanceType::String.into()),
        string: Some(Box::new(StringValidation {
            min_length: Some(1),
            max_length: Some(512),
            pattern: None,
        })),
        ..Default::default()
    })
}

#[cfg(feature = "server")]
fn openapi_url_schema(
    description: &'static str,
) -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {
    use utoipa::openapi::schema::{ObjectBuilder, Schema, SchemaFormat, Type};

    utoipa::openapi::RefOr::T(Schema::Object(
        ObjectBuilder::new()
            .schema_type(Type::String)
            .format(Some(SchemaFormat::Custom("uri".to_owned())))
            .description(Some(description))
            .build(),
    ))
}

#[cfg(test)]
mod tests {
    use super::{
        AbsoluteUrl, CallbackQuery, IssuerUrl, LoginInitResponse, ProviderResponse, Sha256Hex,
        UrlParseError,
    };
    use crate::auth::SecretBearer;

    #[test]
    fn issuer_url_normalizes_trailing_slash() {
        let issuer =
            IssuerUrl::new("https://idp.example.com/realms/acme/").expect("issuer URL is valid");

        assert_eq!(issuer.as_str(), "https://idp.example.com/realms/acme");
    }

    #[test]
    fn issuer_url_rejects_non_url_input() {
        assert!(IssuerUrl::new("not a url").is_err());
        assert!(IssuerUrl::new("/relative/path").is_err());
    }

    #[test]
    fn issuer_url_accepts_https_any_host() {
        assert!(IssuerUrl::new("https://idp.example.com/realms/acme").is_ok());
        assert!(IssuerUrl::new("https://localhost:8443/realms/wyrd-test").is_ok());
    }

    #[test]
    fn issuer_url_accepts_http_loopback() {
        assert!(IssuerUrl::new("http://localhost:8080/realms/wyrd-test").is_ok());
        assert!(IssuerUrl::new("http://127.0.0.1:8080/realms/wyrd-test").is_ok());
        assert!(IssuerUrl::new("http://[::1]:8080/realms/wyrd-test").is_ok());
    }

    #[test]
    fn issuer_url_rejects_http_non_loopback() {
        assert!(matches!(
            IssuerUrl::new("http://idp.example.com"),
            Err(UrlParseError::DisallowedScheme(scheme)) if scheme == "http"
        ));
        assert!(matches!(
            IssuerUrl::new("http://10.0.0.1:8080"),
            Err(UrlParseError::DisallowedScheme(scheme)) if scheme == "http"
        ));
    }

    #[test]
    fn issuer_url_rejects_non_https() {
        assert!(IssuerUrl::new("http://insecure.example.com").is_err());
        assert!(IssuerUrl::new("ftp://files.example.com").is_err());
        assert!(matches!(
            IssuerUrl::new("ftp://localhost"),
            Err(UrlParseError::DisallowedScheme(scheme)) if scheme == "ftp"
        ));
    }

    #[test]
    fn issuer_url_rejects_bad_url_and_no_host() {
        assert!(matches!(
            IssuerUrl::new("not a url"),
            Err(UrlParseError::ParseFailed(_))
        ));
        assert!(matches!(
            IssuerUrl::new("mailto:user@example.com"),
            Err(UrlParseError::NoHost)
        ));
    }

    #[test]
    fn url_rejects_non_url_input() {
        assert!(AbsoluteUrl::new("not a url").is_err());
        assert!(AbsoluteUrl::new("urn:example:login").is_err());
    }

    #[test]
    fn url_rejects_disallowed_schemes() {
        assert!(AbsoluteUrl::new("ftp://files.example.com").is_err());
        assert!(AbsoluteUrl::new("file://localhost/etc/passwd").is_err());
    }

    #[test]
    fn url_accepts_valid_absolute_url() {
        let url = AbsoluteUrl::new("https://idp.example.com/authorize").expect("valid");
        assert_eq!(url.as_str(), "https://idp.example.com/authorize");
        let from_str: AbsoluteUrl = "https://idp.example.com/authorize"
            .parse()
            .expect("FromStr");
        assert_eq!(from_str, url);
    }

    #[test]
    fn url_deserialize_rejects_invalid() {
        assert!(serde_json::from_str::<AbsoluteUrl>("\"not a url\"").is_err());
        assert!(serde_json::from_str::<AbsoluteUrl>("\"/relative/path\"").is_err());
        assert!(serde_json::from_str::<AbsoluteUrl>("\"ftp://files.example.com\"").is_err());
    }

    #[test]
    fn issuer_url_deserialize_rejects_invalid() {
        assert!(serde_json::from_str::<IssuerUrl>("\"not a url\"").is_err());
        assert!(serde_json::from_str::<IssuerUrl>("\"/relative/path\"").is_err());
        assert!(serde_json::from_str::<IssuerUrl>("\"http://insecure.example.com\"").is_err());
    }

    #[test]
    fn login_init_response_roundtrips() {
        let resp = LoginInitResponse {
            authorization_url: AbsoluteUrl::new("https://idp.example.com/authorize").unwrap(),
            state: "opaque-state".to_owned(),
        };
        let value = serde_json::to_value(&resp).unwrap();
        assert_eq!(
            value["authorization_url"],
            "https://idp.example.com/authorize"
        );
        assert_eq!(
            serde_json::from_value::<LoginInitResponse>(value).unwrap(),
            resp
        );
    }

    /// A callback carrying the RFC 9207 `iss` parameter retains it typed,
    /// and one without it parses with no issuer; `state` remains mandatory.
    #[test]
    fn callback_query_retains_the_response_issuer() {
        let json = serde_json::json!({
            "code": "auth-code",
            "state": "state-123",
            "iss": "https://idp.example.com/realms/acme"
        });
        let query = serde_json::from_value::<CallbackQuery>(json).expect("callback parses");
        assert_eq!(query.state, "state-123");
        assert_eq!(
            query.iss.as_deref(),
            Some("https://idp.example.com/realms/acme")
        );
        let bare = serde_json::from_value::<CallbackQuery>(
            serde_json::json!({ "code": "auth-code", "state": "state-123" }),
        )
        .expect("callback without iss parses");
        assert_eq!(bare.iss, None);
        assert!(
            serde_json::from_value::<CallbackQuery>(serde_json::json!({ "code": "auth-code" }))
                .is_err()
        );
    }

    /// A callback answers exactly one of the provider's `code` or `error`;
    /// both or neither is refused, and `error_description` is never kept.
    ///
    /// # Panics
    /// Panics when a response is classified differently.
    #[test]
    fn callback_query_carries_exactly_one_provider_response() {
        let parse = |json| {
            serde_json::from_value::<CallbackQuery>(json)
                .expect("callback parses")
                .response()
        };
        assert_eq!(
            parse(serde_json::json!({ "code": "auth-code", "state": "s" })).expect("code"),
            ProviderResponse::Code(SecretBearer::new("auth-code".to_owned()))
        );
        assert_eq!(
            parse(serde_json::json!({
                "error": "access_denied",
                "error_description": "<script>",
                "state": "s"
            }))
            .expect("error"),
            ProviderResponse::Error("access_denied".to_owned())
        );
        assert!(parse(serde_json::json!({ "state": "s" })).is_err());
        assert!(
            parse(serde_json::json!({ "code": "c", "error": "access_denied", "state": "s" }))
                .is_err()
        );
    }

    /// Unrelated provider response parameters (Keycloak's `session_state`)
    /// are tolerated and ignored, as RFC 6749 ยง4.1.2 requires.
    #[test]
    fn callback_query_tolerates_unrelated_provider_parameters() {
        let json = serde_json::json!({
            "code": "auth-code",
            "state": "state-123",
            "session_state": "kc-session",
            "iss": "https://idp.example.com/realms/acme"
        });
        let query = serde_json::from_value::<CallbackQuery>(json).expect("callback parses");
        assert_eq!(query.state, "state-123");
        assert_eq!(
            query.iss.as_deref(),
            Some("https://idp.example.com/realms/acme")
        );
    }

    /// A digest parses only in its canonical lowercase 64-hex form and
    /// serializes back to it.
    #[test]
    fn sha256_hex_accepts_only_the_canonical_form() {
        let digest = Sha256Hex::digest(b"flow");
        let wire = digest.to_string();
        assert_eq!(wire.len(), 64);
        assert_eq!(Sha256Hex::new(&wire), Ok(digest));
        assert!(Sha256Hex::new(&wire.to_uppercase()).is_err());
        assert!(Sha256Hex::new(&wire[..63]).is_err());
        assert!(Sha256Hex::new(&format!("{}g", &wire[..63])).is_err());
        assert_eq!(
            serde_json::to_value(digest).expect("serializes"),
            serde_json::json!(wire)
        );
    }
}