entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! OAuth 2.0 Device Authorization Grant (RFC 8628).
//!
//! The device grant lets an input-constrained device (a TV, a console, a
//! first-run OS setup running in kiosk mode) obtain tokens without a
//! browser or keyboard on the device itself: the device shows a short
//! `user_code` and a `verification_uri`, the user visits that URL on a
//! phone or laptop and approves, and the device polls the token endpoint
//! until authorization completes.
//!
//! This module follows the same design as the rest of [`crate::oauth`]:
//! it **builds requests and parses responses only** — the caller supplies
//! the HTTP transport and drives the polling loop. This avoids coupling to
//! any particular HTTP library and keeps the crate `std`-only.
//!
//! # Client type
//!
//! These builders target **public clients** (native / desktop apps), which
//! per RFC 8628 §3.1 and RFC 6749 §2.1 have no client secret. Only
//! `client_id` is sent. The `device_authorization_endpoint` is typically
//! discovered from the provider's OIDC metadata
//! ([`crate::oidc`]), not statically configured, so it is passed in rather
//! than read from [`OAuthConfig`](super::OAuthConfig).
//!
//! # Flow
//!
//! 1. Build a [`DeviceAuthorizationRequest`] and POST it to the device
//!    authorization endpoint.
//! 2. Parse the JSON with [`DeviceAuthorizationResponse::parse`]; show the
//!    `user_code` + `verification_uri` (or `verification_uri_complete`) to
//!    the user.
//! 3. Poll: build a [`DeviceAccessTokenRequest`] and POST it to the token
//!    endpoint every [`DeviceAuthorizationResponse::interval`] seconds.
//! 4. Classify each poll with [`DeviceTokenOutcome::parse`]:
//!    - [`DeviceTokenOutcome::Pending`] — keep waiting.
//!    - [`DeviceTokenOutcome::SlowDown`] — increase the interval by 5s
//!      (RFC 8628 §3.5) and keep waiting.
//!    - [`DeviceTokenOutcome::Authorized`] — done; contains the tokens.
//!    - a terminal [`DeviceFlowError`] (`access_denied`, `expired_token`, …).
//!
//! # Security
//!
//! SECURITY: `device_code` is a bearer credential for the pending
//! authorization — it is wrapped in [`Zeroizing`] and redacted from
//! `Debug`. The poll request body (which contains it) is likewise wrapped
//! and redacted. `user_code` is user-facing and not secret.
//!
//! [`Zeroizing`]: crate::crypto::zeroize::Zeroizing

use std::fmt;

use crate::crypto::zeroize::Zeroizing;
use crate::encoding::url_encode_component;
use crate::json::JsonValue;
use crate::util::log::{debug, info, warn};

use super::{TokenResponse, TokenResponseError};

/// RFC 8628 §3.4 device-code grant type.
const DEVICE_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:device_code";

/// RFC 8628 §3.2 default polling interval (seconds) when the authorization
/// response omits `interval`.
pub const DEFAULT_POLL_INTERVAL_SECS: u64 = 5;

/// RFC 8628 §3.5 amount (seconds) to increase the polling interval by on a
/// `slow_down` error.
pub const SLOW_DOWN_INCREMENT_SECS: u64 = 5;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// The category of device-flow failure.
#[derive(Debug, Clone, PartialEq, Eq)]
enum DeviceFlowErrorKind {
    /// The response body was not valid JSON.
    InvalidJson,
    /// The device authorization response was missing `device_code`.
    MissingDeviceCode,
    /// The device authorization response was missing `user_code`.
    MissingUserCode,
    /// The device authorization response was missing `verification_uri`.
    MissingVerificationUri,
    /// The device authorization response was missing `expires_in`.
    MissingExpiresIn,
    /// `expires_in` was present but not a non-negative integer.
    InvalidExpiresIn,
    /// `interval` was present but not a non-negative integer.
    InvalidInterval,
    /// Terminal poll error: the user denied the authorization
    /// (`access_denied`).
    AccessDenied,
    /// Terminal poll error: the `device_code` expired before the user
    /// approved (`expired_token`).
    ExpiredToken,
    /// Terminal poll error: some other OAuth error code from the endpoint.
    ServerError {
        /// The OAuth error code.
        error: String,
        /// Optional human-readable description.
        description: Option<String>,
    },
    /// The authorized poll response could not be parsed as a token response.
    TokenResponse(TokenResponseError),
}

/// Error returned by the device authorization grant.
///
/// Represents a malformed device authorization response, or a terminal
/// failure while polling the token endpoint. Non-terminal poll states
/// (`authorization_pending`, `slow_down`) are **not** errors — they are
/// returned as [`DeviceTokenOutcome`] variants so the caller can keep
/// polling.
///
/// Error messages never contain secret material (`device_code` and tokens
/// are excluded from all diagnostic output).
#[doc(alias = "device_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeviceFlowError {
    kind: DeviceFlowErrorKind,
}

impl DeviceFlowError {
    const fn new(kind: DeviceFlowErrorKind) -> Self {
        Self { kind }
    }

    /// Returns `true` if this is the terminal `access_denied` error — the
    /// user rejected the authorization request.
    #[must_use]
    #[inline]
    pub fn is_access_denied(&self) -> bool {
        matches!(self.kind, DeviceFlowErrorKind::AccessDenied)
    }

    /// Returns `true` if this is the terminal `expired_token` error — the
    /// `device_code` expired before the user approved. The caller should
    /// restart the flow to obtain a fresh code.
    #[must_use]
    #[inline]
    pub fn is_expired(&self) -> bool {
        matches!(self.kind, DeviceFlowErrorKind::ExpiredToken)
    }
}

impl fmt::Display for DeviceFlowError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            DeviceFlowErrorKind::InvalidJson => write!(f, "device flow: invalid JSON"),
            DeviceFlowErrorKind::MissingDeviceCode => {
                write!(f, "device flow: missing device_code")
            }
            DeviceFlowErrorKind::MissingUserCode => {
                write!(f, "device flow: missing user_code")
            }
            DeviceFlowErrorKind::MissingVerificationUri => {
                write!(f, "device flow: missing verification_uri")
            }
            DeviceFlowErrorKind::MissingExpiresIn => {
                write!(f, "device flow: missing expires_in")
            }
            DeviceFlowErrorKind::InvalidExpiresIn => {
                write!(f, "device flow: invalid expires_in value")
            }
            DeviceFlowErrorKind::InvalidInterval => {
                write!(f, "device flow: invalid interval value")
            }
            DeviceFlowErrorKind::AccessDenied => {
                write!(f, "device flow: authorization denied by user")
            }
            DeviceFlowErrorKind::ExpiredToken => {
                write!(f, "device flow: device_code expired")
            }
            DeviceFlowErrorKind::ServerError { error, description } => {
                write!(f, "device flow: OAuth error: {error}")?;
                if let Some(desc) = description {
                    write!(f, " ({desc})")?;
                }
                Ok(())
            }
            DeviceFlowErrorKind::TokenResponse(err) => {
                write!(f, "device flow: {err}")
            }
        }
    }
}

impl std::error::Error for DeviceFlowError {}

// ---------------------------------------------------------------------------
// DeviceAuthorizationRequest
// ---------------------------------------------------------------------------

/// A device authorization request (RFC 8628 §3.1).
///
/// Contains the pre-built `application/x-www-form-urlencoded` POST body and
/// the target endpoint URL. The caller POSTs the [`body`](Self::body) to the
/// [`endpoint`](Self::endpoint) using their HTTP transport.
#[doc(alias = "device_authorization")]
pub struct DeviceAuthorizationRequest {
    endpoint: String,
    body: String,
    content_type: &'static str,
}

impl DeviceAuthorizationRequest {
    /// Builds a device authorization request for a public client.
    ///
    /// # Parameters
    ///
    /// * `device_authorization_endpoint` — the provider's device
    ///   authorization endpoint (typically from OIDC discovery).
    /// * `client_id` — the public client identifier.
    /// * `scope` — a space-delimited scope string (e.g. `"openid profile"`),
    ///   or empty to omit the `scope` parameter.
    #[must_use]
    pub fn new(device_authorization_endpoint: &str, client_id: &str, scope: &str) -> Self {
        let mut body = String::with_capacity(128);
        body.push_str("client_id=");
        body.push_str(&url_encode_component(client_id));
        if !scope.is_empty() {
            body.push_str("&scope=");
            body.push_str(&url_encode_component(scope));
        }

        debug!(
            endpoint = %device_authorization_endpoint,
            "oauth: device authorization request built"
        );

        Self {
            endpoint: device_authorization_endpoint.to_owned(),
            body,
            content_type: "application/x-www-form-urlencoded",
        }
    }

    /// Returns the endpoint URL to POST this request to.
    #[must_use]
    #[inline]
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }

    /// Returns the URL-encoded POST body.
    #[must_use]
    #[inline]
    pub fn body(&self) -> &str {
        &self.body
    }

    /// Returns the `Content-Type` header value for this request.
    #[must_use]
    #[inline]
    pub fn content_type(&self) -> &str {
        self.content_type
    }
}

impl fmt::Debug for DeviceAuthorizationRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The device authorization request body carries no secret (public
        // client, client_id only) but is redacted for consistency.
        f.debug_struct("DeviceAuthorizationRequest")
            .field("endpoint", &self.endpoint)
            .field("body", &"[REDACTED]")
            .field("content_type", &self.content_type)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// DeviceAuthorizationResponse
// ---------------------------------------------------------------------------

/// A parsed device authorization response (RFC 8628 §3.2).
///
/// # Security
///
/// SECURITY: `device_code` is a bearer credential and is stored in a
/// [`Zeroizing`](crate::crypto::zeroize::Zeroizing) wrapper that clears
/// memory on drop; [`Debug`] redacts it. `user_code` is user-facing.
#[doc(alias = "device_authorization_response")]
pub struct DeviceAuthorizationResponse {
    device_code: Zeroizing<String>,
    user_code: String,
    verification_uri: String,
    verification_uri_complete: Option<String>,
    expires_in: u64,
    interval: u64,
}

impl DeviceAuthorizationResponse {
    /// Parses a JSON device authorization response body.
    ///
    /// # Errors
    ///
    /// Returns [`DeviceFlowError`] if the JSON is invalid, a required field
    /// (`device_code`, `user_code`, `verification_uri`, `expires_in`) is
    /// missing, or `expires_in` / `interval` is present but not a
    /// non-negative integer.
    #[must_use = "parsing may fail; handle the Result"]
    pub fn parse(json: &str) -> Result<Self, DeviceFlowError> {
        let value = JsonValue::parse(json).map_err(|_| {
            warn!("oauth: device authorization response parse failed: invalid JSON");
            DeviceFlowError::new(DeviceFlowErrorKind::InvalidJson)
        })?;

        // SECURITY: wrap device_code in Zeroizing immediately.
        let device_code = Zeroizing::new(
            value
                .get_str("device_code")
                .ok_or_else(|| DeviceFlowError::new(DeviceFlowErrorKind::MissingDeviceCode))?
                .to_owned(),
        );

        let user_code = value
            .get_str("user_code")
            .ok_or_else(|| DeviceFlowError::new(DeviceFlowErrorKind::MissingUserCode))?
            .to_owned();

        let verification_uri = value
            .get_str("verification_uri")
            .ok_or_else(|| DeviceFlowError::new(DeviceFlowErrorKind::MissingVerificationUri))?
            .to_owned();

        let verification_uri_complete =
            value.get_str("verification_uri_complete").map(String::from);

        let expires_in = match parse_non_negative(&value, "expires_in") {
            NumField::Value(v) => v,
            NumField::Absent => {
                return Err(DeviceFlowError::new(DeviceFlowErrorKind::MissingExpiresIn));
            }
            NumField::Invalid => {
                return Err(DeviceFlowError::new(DeviceFlowErrorKind::InvalidExpiresIn));
            }
        };

        // `interval` is optional; default to 5s per RFC 8628 §3.2.
        let interval = match parse_non_negative(&value, "interval") {
            NumField::Value(v) => v,
            NumField::Absent => DEFAULT_POLL_INTERVAL_SECS,
            NumField::Invalid => {
                return Err(DeviceFlowError::new(DeviceFlowErrorKind::InvalidInterval));
            }
        };

        info!(
            user_code = %user_code,
            expires_in,
            interval,
            "oauth: device authorization response parsed"
        );

        Ok(Self {
            device_code,
            user_code,
            verification_uri,
            verification_uri_complete,
            expires_in,
            interval,
        })
    }

    /// Returns the device verification code (bearer credential for polling).
    ///
    /// # Security
    ///
    /// SECURITY: The caller must not log this value.
    #[must_use]
    #[inline]
    pub fn device_code(&self) -> &str {
        &self.device_code
    }

    /// Returns the end-user code to display (e.g. `"WDJB-MJHT"`).
    #[must_use]
    #[inline]
    pub fn user_code(&self) -> &str {
        &self.user_code
    }

    /// Returns the verification URI the user visits to approve.
    #[must_use]
    #[inline]
    pub fn verification_uri(&self) -> &str {
        &self.verification_uri
    }

    /// Returns the verification URI with the `user_code` pre-filled, if the
    /// provider supplied one (RFC 8628 §3.2). Ideal for a QR code.
    #[must_use]
    #[inline]
    pub fn verification_uri_complete(&self) -> Option<&str> {
        self.verification_uri_complete.as_deref()
    }

    /// Returns the lifetime in seconds of the `device_code` / `user_code`.
    #[must_use]
    #[inline]
    pub fn expires_in(&self) -> u64 {
        self.expires_in
    }

    /// Returns the minimum polling interval in seconds (defaults to
    /// [`DEFAULT_POLL_INTERVAL_SECS`] when the provider omits it).
    #[must_use]
    #[inline]
    pub fn interval(&self) -> u64 {
        self.interval
    }
}

impl fmt::Debug for DeviceAuthorizationResponse {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // SECURITY: redact device_code.
        f.debug_struct("DeviceAuthorizationResponse")
            .field("device_code", &"[REDACTED]")
            .field("user_code", &self.user_code)
            .field("verification_uri", &self.verification_uri)
            .field("verification_uri_complete", &self.verification_uri_complete)
            .field("expires_in", &self.expires_in)
            .field("interval", &self.interval)
            .finish()
    }
}

/// The three outcomes of reading a non-negative integer field, letting
/// callers distinguish a missing field from a malformed one.
enum NumField {
    /// The field was absent or JSON `null`.
    Absent,
    /// The field was present but not a non-negative integer.
    Invalid,
    /// A valid non-negative value.
    Value(u64),
}

/// Reads a non-negative integer field from a JSON object.
fn parse_non_negative(value: &JsonValue, key: &str) -> NumField {
    match value.get(key) {
        None => NumField::Absent,
        Some(v) if v.is_null() => NumField::Absent,
        Some(v) => match v.as_i64() {
            Some(n) if n >= 0 =>
            {
                #[allow(clippy::cast_sign_loss)]
                NumField::Value(n as u64)
            }
            _ => NumField::Invalid,
        },
    }
}

// ---------------------------------------------------------------------------
// DeviceAccessTokenRequest
// ---------------------------------------------------------------------------

/// A device access token (poll) request (RFC 8628 §3.4).
///
/// Built once per poll and sent to the token endpoint via POST. Contains
/// the device-code grant body.
///
/// # Security
///
/// SECURITY: The body contains the `device_code` bearer credential; it is
/// wrapped in [`Zeroizing`](crate::crypto::zeroize::Zeroizing) and redacted
/// from [`Debug`].
#[doc(alias = "device_token_request")]
pub struct DeviceAccessTokenRequest {
    endpoint: String,
    body: Zeroizing<String>,
    content_type: &'static str,
}

impl DeviceAccessTokenRequest {
    /// Builds a device access token poll request for a public client.
    ///
    /// # Parameters
    ///
    /// * `token_endpoint` — the provider's token endpoint.
    /// * `client_id` — the public client identifier.
    /// * `device_code` — the `device_code` from the authorization response.
    #[must_use]
    pub fn new(token_endpoint: &str, client_id: &str, device_code: &str) -> Self {
        let mut body = String::with_capacity(256);
        body.push_str("grant_type=");
        body.push_str(&url_encode_component(DEVICE_GRANT_TYPE));
        body.push_str("&device_code=");
        body.push_str(&url_encode_component(device_code));
        body.push_str("&client_id=");
        body.push_str(&url_encode_component(client_id));

        // SECURITY: never log the device_code.
        debug!(endpoint = %token_endpoint, "oauth: device token poll request built");

        Self {
            endpoint: token_endpoint.to_owned(),
            body: Zeroizing::new(body),
            content_type: "application/x-www-form-urlencoded",
        }
    }

    /// Returns the endpoint URL to POST this request to.
    #[must_use]
    #[inline]
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }

    /// Returns the URL-encoded POST body.
    #[must_use]
    #[inline]
    pub fn body(&self) -> &str {
        &self.body
    }

    /// Returns the `Content-Type` header value for this request.
    #[must_use]
    #[inline]
    pub fn content_type(&self) -> &str {
        self.content_type
    }
}

impl fmt::Debug for DeviceAccessTokenRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // SECURITY: redact body which contains the device_code.
        f.debug_struct("DeviceAccessTokenRequest")
            .field("endpoint", &self.endpoint)
            .field("body", &"[REDACTED]")
            .field("content_type", &self.content_type)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// DeviceTokenOutcome
// ---------------------------------------------------------------------------

/// The classified result of a single device-token poll (RFC 8628 §3.5).
///
/// The non-terminal states ([`Pending`](Self::Pending),
/// [`SlowDown`](Self::SlowDown)) are returned as `Ok` so the caller keeps
/// polling; terminal failures (`access_denied`, `expired_token`, other
/// server errors, malformed tokens) are returned as [`DeviceFlowError`].
#[derive(Debug)]
#[non_exhaustive]
pub enum DeviceTokenOutcome {
    /// Authorization complete — carries the issued tokens.
    Authorized(TokenResponse),
    /// The user has not yet approved. Wait `interval` seconds and poll again.
    Pending,
    /// Polling too fast. Increase the interval by
    /// [`SLOW_DOWN_INCREMENT_SECS`] and poll again.
    SlowDown,
}

impl DeviceTokenOutcome {
    /// Classifies a JSON token-endpoint response received while polling.
    ///
    /// # Errors
    ///
    /// Returns [`DeviceFlowError`] for terminal conditions: `access_denied`,
    /// `expired_token`, any other OAuth error code, invalid JSON, or an
    /// authorized response whose token payload fails to parse. The
    /// non-terminal `authorization_pending` and `slow_down` states are
    /// returned as `Ok` variants.
    #[must_use = "the poll outcome determines whether to keep waiting"]
    pub fn parse(json: &str) -> Result<Self, DeviceFlowError> {
        let value = JsonValue::parse(json).map_err(|_| {
            warn!("oauth: device token poll parse failed: invalid JSON");
            DeviceFlowError::new(DeviceFlowErrorKind::InvalidJson)
        })?;

        // RFC 6749 §5.2 / RFC 8628 §3.5: an error response is identified by
        // the presence of `error`. Gate on presence (not on it being a
        // string) so a hostile non-string `error` can't slip through as a
        // success alongside a forged `access_token`.
        if value.get("error").is_some() {
            let error = value.get_str("error").unwrap_or("invalid_error");
            return match error {
                "authorization_pending" => Ok(Self::Pending),
                "slow_down" => Ok(Self::SlowDown),
                "access_denied" => Err(DeviceFlowError::new(DeviceFlowErrorKind::AccessDenied)),
                "expired_token" => Err(DeviceFlowError::new(DeviceFlowErrorKind::ExpiredToken)),
                other => {
                    let description = value.get_str("error_description").map(String::from);
                    warn!(code = %other, "oauth: device token poll error");
                    Err(DeviceFlowError::new(DeviceFlowErrorKind::ServerError {
                        error: other.to_owned(),
                        description,
                    }))
                }
            };
        }

        // No error field: this should be a successful token response. Reuse
        // the shared token-response parser.
        let token = TokenResponse::parse(json)
            .map_err(|e| DeviceFlowError::new(DeviceFlowErrorKind::TokenResponse(e)))?;
        Ok(Self::Authorized(token))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // --- DeviceAuthorizationRequest ---

    #[test]
    fn auth_request_contains_client_id_and_scope() {
        let req = DeviceAuthorizationRequest::new(
            "https://idp.example.com/device",
            "my-client",
            "openid profile",
        );
        assert_eq!(req.endpoint(), "https://idp.example.com/device");
        assert!(req.body().contains("client_id=my-client"));
        // space in scope is URL-encoded
        assert!(
            req.body().contains("scope=openid%20profile"),
            "{}",
            req.body()
        );
        assert_eq!(req.content_type(), "application/x-www-form-urlencoded");
    }

    #[test]
    fn auth_request_omits_empty_scope() {
        let req = DeviceAuthorizationRequest::new("https://idp.example.com/device", "c", "");
        assert!(!req.body().contains("scope="));
    }

    #[test]
    fn auth_request_debug_redacts_body() {
        let req = DeviceAuthorizationRequest::new("https://idp.example.com/device", "c", "openid");
        assert!(format!("{req:?}").contains("[REDACTED]"));
    }

    // --- DeviceAuthorizationResponse::parse ---

    fn full_auth_response() -> &'static str {
        r#"{
            "device_code": "dev-code-abc",
            "user_code": "WDJB-MJHT",
            "verification_uri": "https://idp.example.com/activate",
            "verification_uri_complete": "https://idp.example.com/activate?user_code=WDJB-MJHT",
            "expires_in": 1800,
            "interval": 5
        }"#
    }

    #[test]
    fn parses_full_authorization_response() {
        let r = DeviceAuthorizationResponse::parse(full_auth_response()).unwrap();
        assert_eq!(r.device_code(), "dev-code-abc");
        assert_eq!(r.user_code(), "WDJB-MJHT");
        assert_eq!(r.verification_uri(), "https://idp.example.com/activate");
        assert_eq!(
            r.verification_uri_complete(),
            Some("https://idp.example.com/activate?user_code=WDJB-MJHT")
        );
        assert_eq!(r.expires_in(), 1800);
        assert_eq!(r.interval(), 5);
    }

    #[test]
    fn interval_defaults_to_five_when_absent() {
        let json = r#"{"device_code":"d","user_code":"U","verification_uri":"https://x/a","expires_in":900}"#;
        let r = DeviceAuthorizationResponse::parse(json).unwrap();
        assert_eq!(r.interval(), DEFAULT_POLL_INTERVAL_SECS);
        assert_eq!(r.verification_uri_complete(), None);
    }

    #[test]
    fn missing_device_code_is_error() {
        let json = r#"{"user_code":"U","verification_uri":"https://x/a","expires_in":900}"#;
        assert!(DeviceAuthorizationResponse::parse(json).is_err());
    }

    #[test]
    fn missing_expires_in_is_error() {
        let json = r#"{"device_code":"d","user_code":"U","verification_uri":"https://x/a"}"#;
        assert!(DeviceAuthorizationResponse::parse(json).is_err());
    }

    #[test]
    fn negative_expires_in_is_error() {
        let json = r#"{"device_code":"d","user_code":"U","verification_uri":"https://x/a","expires_in":-1}"#;
        assert!(DeviceAuthorizationResponse::parse(json).is_err());
    }

    #[test]
    fn invalid_json_is_error() {
        assert!(DeviceAuthorizationResponse::parse("not json").is_err());
    }

    #[test]
    fn auth_response_debug_redacts_device_code() {
        let r = DeviceAuthorizationResponse::parse(full_auth_response()).unwrap();
        let dbg = format!("{r:?}");
        assert!(dbg.contains("[REDACTED]"));
        assert!(!dbg.contains("dev-code-abc"));
    }

    // --- DeviceAccessTokenRequest ---

    #[test]
    fn token_request_has_device_grant_and_encoded_fields() {
        let req = DeviceAccessTokenRequest::new(
            "https://idp.example.com/token",
            "my-client",
            "dev-code-abc",
        );
        assert_eq!(req.endpoint(), "https://idp.example.com/token");
        // grant_type urn is URL-encoded (colons -> %3A)
        assert!(
            req.body()
                .contains("grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Adevice_code"),
            "{}",
            req.body()
        );
        assert!(req.body().contains("device_code=dev-code-abc"));
        assert!(req.body().contains("client_id=my-client"));
    }

    #[test]
    fn token_request_debug_redacts_body() {
        let req =
            DeviceAccessTokenRequest::new("https://idp.example.com/token", "c", "secret-code");
        let dbg = format!("{req:?}");
        assert!(dbg.contains("[REDACTED]"));
        assert!(!dbg.contains("secret-code"));
    }

    // --- DeviceTokenOutcome::parse ---

    #[test]
    fn poll_authorization_pending_is_pending() {
        let out = DeviceTokenOutcome::parse(r#"{"error":"authorization_pending"}"#).unwrap();
        assert!(matches!(out, DeviceTokenOutcome::Pending));
    }

    #[test]
    fn poll_slow_down_is_slow_down() {
        let out = DeviceTokenOutcome::parse(r#"{"error":"slow_down"}"#).unwrap();
        assert!(matches!(out, DeviceTokenOutcome::SlowDown));
    }

    #[test]
    fn poll_access_denied_is_terminal_error() {
        let err = DeviceTokenOutcome::parse(r#"{"error":"access_denied"}"#).unwrap_err();
        assert!(err.is_access_denied());
    }

    #[test]
    fn poll_expired_token_is_terminal_error() {
        let err = DeviceTokenOutcome::parse(r#"{"error":"expired_token"}"#).unwrap_err();
        assert!(err.is_expired());
    }

    #[test]
    fn poll_unknown_error_is_server_error() {
        let err = DeviceTokenOutcome::parse(r#"{"error":"invalid_client"}"#).unwrap_err();
        assert!(!err.is_access_denied() && !err.is_expired());
    }

    #[test]
    fn poll_success_is_authorized() {
        let json = r#"{"access_token":"at-123","token_type":"Bearer","expires_in":3600}"#;
        let out = DeviceTokenOutcome::parse(json).unwrap();
        match out {
            DeviceTokenOutcome::Authorized(t) => {
                assert_eq!(t.access_token(), "at-123");
                assert_eq!(t.token_type(), "Bearer");
            }
            _ => panic!("expected Authorized"),
        }
    }

    #[test]
    fn poll_invalid_json_is_error() {
        assert!(DeviceTokenOutcome::parse("nope").is_err());
    }
}