Skip to main content

rs_identity_model/token/
response.rs

1//! Typed OAuth 2.0 token endpoint response (RFC 6749 §5.1).
2
3use std::collections::HashMap;
4use std::fmt;
5
6use serde::{Deserialize, Deserializer};
7
8/// Placeholder printed in place of token material in `Debug` output (#24).
9const REDACTED: &str = "<redacted>";
10
11/// A successful OAuth 2.0 token endpoint response (RFC 6749 §5.1).
12///
13/// Standard parameters are modelled as typed fields; any additional
14/// provider-specific parameters are preserved in [`TokenResponse::extra`] so
15/// unknown fields are ignored, not rejected. `expires_in` is tolerated as a
16/// JSON number, a numeric string, or `null`, since some providers deviate from
17/// the RFC's number type (CC-001).
18///
19/// `Debug` is hand-written to redact the `access_token`, `refresh_token`, and
20/// `id_token` values so bearer tokens do not leak into logs (#24); the presence
21/// of the optional tokens is still shown.
22#[derive(Clone, Deserialize)]
23pub struct TokenResponse {
24    /// The issued access token (required).
25    pub access_token: String,
26    /// The token type, typically `Bearer` (required).
27    #[serde(default)]
28    pub token_type: String,
29    /// The access token lifetime in seconds, if provided. Absent, `null`, or an
30    /// empty value is reported as `0`.
31    #[serde(default, deserialize_with = "deserialize_flexible_expires_in")]
32    pub expires_in: i64,
33    /// The granted scope, if it differs from the request.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub scope: Option<String>,
36    /// The issued refresh token, if any.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub refresh_token: Option<String>,
39    /// The OIDC ID token, present for the authorization code grant when the
40    /// `openid` scope was requested.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub id_token: Option<String>,
43    /// The URI naming the type of the issued token, returned by the RFC 8693
44    /// token exchange grant (RFC 8693 §2.2, EXCH-005). REQUIRED in an exchange
45    /// response and absent from every other grant's, so it is modelled as an
46    /// `Option` rather than defaulted to an empty string. It MAY differ from
47    /// the `requested_token_type` that was asked for.
48    #[serde(default, skip_serializing_if = "Option::is_none")]
49    pub issued_token_type: Option<String>,
50    /// Any non-standard parameters returned by the provider.
51    #[serde(flatten)]
52    pub extra: HashMap<String, serde_json::Value>,
53}
54
55impl fmt::Debug for TokenResponse {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.debug_struct("TokenResponse")
58            .field("access_token", &REDACTED)
59            .field("token_type", &self.token_type)
60            .field("expires_in", &self.expires_in)
61            .field("scope", &self.scope)
62            .field(
63                "refresh_token",
64                &self.refresh_token.as_ref().map(|_| REDACTED),
65            )
66            .field("id_token", &self.id_token.as_ref().map(|_| REDACTED))
67            // Not token material: the issued type is a public URI and stays
68            // legible, since it is the field that identifies what an exchange
69            // actually handed back.
70            .field("issued_token_type", &self.issued_token_type)
71            .field("extra", &self.extra)
72            .finish()
73    }
74}
75
76/// Deserializes `expires_in` from a JSON number, numeric string, or `null`.
77///
78/// `expires_in` is an optional parameter (RFC 6749 §5.1), so `null`, an empty
79/// string, or a missing value is treated as absent (`0`) rather than an error:
80/// a valid token must not be discarded over a missing-but-present lifetime. A
81/// fractional value (e.g. `3600.0`, sent by some providers) is truncated toward
82/// zero; a value outside the `i64` range is rejected.
83fn deserialize_flexible_expires_in<'de, D>(deserializer: D) -> Result<i64, D::Error>
84where
85    D: Deserializer<'de>,
86{
87    use serde::de::Error;
88
89    let value = serde_json::Value::deserialize(deserializer)?;
90    match value {
91        serde_json::Value::Null => Ok(0),
92        serde_json::Value::Number(n) => number_to_seconds::<D>(&n),
93        serde_json::Value::String(s) => {
94            let s = s.trim();
95            if s.is_empty() {
96                return Ok(0);
97            }
98            if let Ok(i) = s.parse::<i64>() {
99                return Ok(i);
100            }
101            match s.parse::<f64>() {
102                Ok(f) => float_to_seconds::<D>(f),
103                Err(_) => Err(D::Error::custom(format!(
104                    "expires_in: expected numeric string, got {s:?}"
105                ))),
106            }
107        }
108        other => Err(D::Error::custom(format!(
109            "expires_in: expected number, numeric string, or null, got {other}"
110        ))),
111    }
112}
113
114/// Converts a JSON number to whole seconds, preferring an exact integer and
115/// falling back to a truncated float.
116fn number_to_seconds<'de, D>(n: &serde_json::Number) -> Result<i64, D::Error>
117where
118    D: Deserializer<'de>,
119{
120    use serde::de::Error;
121
122    if let Some(i) = n.as_i64() {
123        return Ok(i);
124    }
125    match n.as_f64() {
126        Some(f) => float_to_seconds::<D>(f),
127        None => Err(D::Error::custom(format!(
128            "expires_in: expected integer seconds, got {n}"
129        ))),
130    }
131}
132
133/// Truncates a fractional lifetime to whole seconds, rejecting values that
134/// cannot be represented as an `i64` (overflow, Inf, NaN) so a crafted or
135/// malformed `expires_in` cannot silently wrap to a garbage value.
136fn float_to_seconds<'de, D>(f: f64) -> Result<i64, D::Error>
137where
138    D: Deserializer<'de>,
139{
140    use serde::de::Error;
141
142    if !f.is_finite() || f >= i64::MAX as f64 || f < i64::MIN as f64 {
143        return Err(D::Error::custom(format!("expires_in out of range: {f}")));
144    }
145    Ok(f as i64)
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    // CC-001: a standard success body deserializes into typed fields.
153    #[test]
154    fn parses_standard_response() {
155        let json = r#"{
156            "access_token": "at-123",
157            "token_type": "Bearer",
158            "expires_in": 3600,
159            "scope": "openid profile",
160            "refresh_token": "rt-456",
161            "id_token": "id-789"
162        }"#;
163        let resp: TokenResponse = serde_json::from_str(json).expect("parse");
164        assert_eq!(resp.access_token, "at-123");
165        assert_eq!(resp.token_type, "Bearer");
166        assert_eq!(resp.expires_in, 3600);
167        assert_eq!(resp.scope.as_deref(), Some("openid profile"));
168        assert_eq!(resp.refresh_token.as_deref(), Some("rt-456"));
169        assert_eq!(resp.id_token.as_deref(), Some("id-789"));
170        assert!(resp.extra.is_empty());
171    }
172
173    // CC-001: unknown provider-specific fields are preserved in `extra`.
174    #[test]
175    fn preserves_extra_fields() {
176        let json = r#"{
177            "access_token": "at",
178            "token_type": "Bearer",
179            "custom_field": "keep-me",
180            "resource": "urn:test:api"
181        }"#;
182        let resp: TokenResponse = serde_json::from_str(json).expect("parse");
183        assert_eq!(
184            resp.extra.get("custom_field").and_then(|v| v.as_str()),
185            Some("keep-me")
186        );
187        assert_eq!(
188            resp.extra.get("resource").and_then(|v| v.as_str()),
189            Some("urn:test:api")
190        );
191    }
192
193    // expires_in as a numeric string (provider deviation) is accepted.
194    #[test]
195    fn parses_expires_in_numeric_string() {
196        let resp: TokenResponse =
197            serde_json::from_str(r#"{"access_token":"a","expires_in":"7200"}"#).expect("parse");
198        assert_eq!(resp.expires_in, 7200);
199    }
200
201    // A fractional expires_in is truncated to whole seconds.
202    #[test]
203    fn parses_expires_in_fractional() {
204        let resp: TokenResponse =
205            serde_json::from_str(r#"{"access_token":"a","expires_in":3600.9}"#).expect("parse");
206        assert_eq!(resp.expires_in, 3600);
207    }
208
209    // A null or missing expires_in is treated as absent (0), not an error.
210    #[test]
211    fn tolerates_null_and_missing_expires_in() {
212        let null_resp: TokenResponse =
213            serde_json::from_str(r#"{"access_token":"a","expires_in":null}"#).expect("parse null");
214        assert_eq!(null_resp.expires_in, 0);
215
216        let missing_resp: TokenResponse =
217            serde_json::from_str(r#"{"access_token":"a"}"#).expect("parse missing");
218        assert_eq!(missing_resp.expires_in, 0);
219    }
220
221    // An empty numeric string is treated as absent (0).
222    #[test]
223    fn tolerates_empty_expires_in_string() {
224        let resp: TokenResponse =
225            serde_json::from_str(r#"{"access_token":"a","expires_in":""}"#).expect("parse");
226        assert_eq!(resp.expires_in, 0);
227    }
228
229    // A non-numeric expires_in is a hard error.
230    #[test]
231    fn rejects_non_numeric_expires_in() {
232        let err =
233            serde_json::from_str::<TokenResponse>(r#"{"access_token":"a","expires_in":"soon"}"#);
234        assert!(err.is_err());
235    }
236
237    // #24: Debug output redacts bearer tokens and never prints their values,
238    // while still revealing that the optional tokens are present.
239    #[test]
240    fn debug_redacts_bearer_tokens() {
241        let resp: TokenResponse = serde_json::from_str(
242            r#"{
243                "access_token": "at-SECRET",
244                "token_type": "Bearer",
245                "expires_in": 3600,
246                "refresh_token": "rt-SECRET",
247                "id_token": "id-SECRET"
248            }"#,
249        )
250        .expect("parse");
251
252        let dbg = format!("{resp:?}");
253        assert!(!dbg.contains("at-SECRET"), "access_token leaked: {dbg}");
254        assert!(!dbg.contains("rt-SECRET"), "refresh_token leaked: {dbg}");
255        assert!(!dbg.contains("id-SECRET"), "id_token leaked: {dbg}");
256        assert!(dbg.contains(REDACTED), "no redaction marker: {dbg}");
257        // Presence of the optional tokens is still visible.
258        assert!(
259            dbg.contains("refresh_token: Some") && dbg.contains("id_token: Some"),
260            "token presence should be visible: {dbg}"
261        );
262    }
263
264    // An absent optional token shows as None, not a redaction marker.
265    #[test]
266    fn debug_shows_absent_optional_tokens_as_none() {
267        let resp: TokenResponse =
268            serde_json::from_str(r#"{"access_token":"a","token_type":"Bearer"}"#).expect("parse");
269        let dbg = format!("{resp:?}");
270        assert!(dbg.contains("refresh_token: None"), "{dbg}");
271        assert!(dbg.contains("id_token: None"), "{dbg}");
272    }
273}