Skip to main content

hyprstream_core/services/oauth/
oauth2_userinfo.rs

1//! Generic OAuth 2.0 userinfo endpoint fetch and claim normalization.
2//!
3//! Used by the `oauth2` and `github` provider kinds, which authenticate the user
4//! with an opaque access token rather than a signed id_token JWT.
5
6use std::time::Duration;
7
8use anyhow::{anyhow, Context, Result};
9
10use crate::config::ClaimMapping;
11
12/// Fetch the userinfo endpoint and return a normalized synthetic claims object.
13///
14/// The returned `serde_json::Value` always contains:
15/// - `"sub"` — stable string identifier (coerced from integer if needed)
16/// - `"name"` — display name or `null`
17/// - `"email"` — email address or `null`
18/// - `"email_verified"` — bool (`false` when the field is absent or null)
19///
20/// This object is structurally identical to what the OIDC path produces from a
21/// verified id_token, so all downstream code (identity mapping, provisioning)
22/// is unchanged.
23pub async fn fetch_oauth2_claims(
24    http_client: &reqwest::Client,
25    userinfo_endpoint: &str,
26    access_token: &str,
27    mapping: &ClaimMapping,
28) -> Result<serde_json::Value> {
29    let response = http_client
30        .get(userinfo_endpoint)
31        .header("Authorization", format!("Bearer {access_token}"))
32        .header("Accept", "application/json")
33        .header("User-Agent", "hyprstream")
34        .timeout(Duration::from_secs(10))
35        .send()
36        .await
37        .context("userinfo request failed")?;
38
39    if !response.status().is_success() {
40        let status = response.status();
41        let body = response.text().await.unwrap_or_default();
42        return Err(anyhow!("userinfo endpoint returned {status}: {body}"));
43    }
44
45    let raw: serde_json::Value = response
46        .json()
47        .await
48        .context("userinfo response is not valid JSON")?;
49
50    // Extract sub — required; coerce integer to string (e.g. GitHub numeric id).
51    let sub = match &raw[&mapping.sub] {
52        serde_json::Value::String(s) => s.clone(),
53        serde_json::Value::Number(n) => n.to_string(),
54        other if other.is_null() => {
55            return Err(anyhow!("userinfo '{}' field is null", mapping.sub));
56        }
57        _ => {
58            return Err(anyhow!(
59                "userinfo '{}' field missing or wrong type",
60                mapping.sub
61            ))
62        }
63    };
64
65    // Extract optional string fields — null is acceptable.
66    let name = mapping
67        .name
68        .as_deref()
69        .map(|field| raw[field].clone())
70        .unwrap_or(serde_json::Value::Null);
71
72    let email = mapping
73        .email
74        .as_deref()
75        .map(|field| raw[field].clone())
76        .unwrap_or(serde_json::Value::Null);
77
78    // Extract email_verified — absent or null field → false.
79    let email_verified: bool = mapping
80        .email_verified
81        .as_deref()
82        .and_then(|field| {
83            let v = &raw[field];
84            match v {
85                serde_json::Value::Bool(b) => Some(*b),
86                serde_json::Value::String(s) => Some(s.eq_ignore_ascii_case("true")),
87                _ => None,
88            }
89        })
90        .unwrap_or(false);
91
92    Ok(serde_json::json!({
93        "sub": sub,
94        "name": name,
95        "email": email,
96        "email_verified": email_verified,
97    }))
98}