Skip to main content

pas_client/
oauth.rs

1use serde::{Deserialize, Serialize};
2use url::Url;
3
4use crate::error::Error;
5use crate::pkce;
6use crate::types::{Ppnum, PpnumId};
7
8const DEFAULT_AUTH_URL: &str = "https://accounts.ppoppo.com/oauth/authorize";
9const DEFAULT_TOKEN_URL: &str = "https://accounts.ppoppo.com/oauth/token";
10const DEFAULT_USERINFO_URL: &str = "https://accounts.ppoppo.com/oauth/userinfo";
11
12/// Ppoppo Accounts `OAuth2` configuration.
13///
14/// Required fields are constructor parameters — no runtime "missing field" errors.
15///
16/// ```rust,ignore
17/// use ppoppo_sdk::OAuthConfig;
18///
19/// let config = OAuthConfig::new("my-client-id", "https://my-app.com/callback".parse()?);
20/// // Optional overrides via chaining:
21/// let config = config
22///     .with_auth_url("https://custom.example.com/authorize".parse()?);
23/// ```
24#[derive(Debug, Clone)]
25#[non_exhaustive]
26pub struct OAuthConfig {
27    pub(crate) client_id: String,
28    pub(crate) auth_url: Url,
29    pub(crate) token_url: Url,
30    pub(crate) userinfo_url: Url,
31    pub(crate) redirect_uri: Url,
32    pub(crate) scopes: Vec<String>,
33}
34
35impl OAuthConfig {
36    /// Create a new OAuth2 configuration.
37    ///
38    /// Required fields are parameters — compile-time enforcement, no `Result`.
39    #[must_use]
40    #[allow(clippy::expect_used)] // Infallible parse — URLs are compile-time constants
41    pub fn new(client_id: impl Into<String>, redirect_uri: Url) -> Self {
42        Self {
43            client_id: client_id.into(),
44            redirect_uri,
45            auth_url: DEFAULT_AUTH_URL.parse().expect("valid default URL"),
46            token_url: DEFAULT_TOKEN_URL.parse().expect("valid default URL"),
47            userinfo_url: DEFAULT_USERINFO_URL.parse().expect("valid default URL"),
48            scopes: vec!["openid".into(), "profile".into()],
49        }
50    }
51
52    /// Override the PAS authorization endpoint.
53    #[must_use]
54    pub fn with_auth_url(mut self, url: Url) -> Self {
55        self.auth_url = url;
56        self
57    }
58
59    /// Override the PAS token endpoint.
60    #[must_use]
61    pub fn with_token_url(mut self, url: Url) -> Self {
62        self.token_url = url;
63        self
64    }
65
66    /// Override the PAS userinfo endpoint.
67    #[must_use]
68    pub fn with_userinfo_url(mut self, url: Url) -> Self {
69        self.userinfo_url = url;
70        self
71    }
72
73    /// Override the OAuth2 scopes (default: `["openid", "profile"]`).
74    #[must_use]
75    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
76        self.scopes = scopes;
77        self
78    }
79
80    /// `OAuth2` client ID.
81    #[must_use]
82    pub fn client_id(&self) -> &str {
83        &self.client_id
84    }
85
86    /// Authorization endpoint URL.
87    #[must_use]
88    pub fn auth_url(&self) -> &Url {
89        &self.auth_url
90    }
91
92    /// Token exchange endpoint URL.
93    #[must_use]
94    pub fn token_url(&self) -> &Url {
95        &self.token_url
96    }
97
98    /// User info endpoint URL.
99    #[must_use]
100    pub fn userinfo_url(&self) -> &Url {
101        &self.userinfo_url
102    }
103
104    /// `OAuth2` redirect URI.
105    #[must_use]
106    pub fn redirect_uri(&self) -> &Url {
107        &self.redirect_uri
108    }
109
110    /// Requested `OAuth2` scopes.
111    #[must_use]
112    pub fn scopes(&self) -> &[String] {
113        &self.scopes
114    }
115}
116
117/// `OAuth2` authorization client for Ppoppo Accounts.
118pub struct AuthClient {
119    config: OAuthConfig,
120    http: reqwest::Client,
121}
122
123/// Authorization URL with PKCE parameters to store in session.
124#[non_exhaustive]
125pub struct AuthorizationRequest {
126    pub url: String,
127    pub state: String,
128    pub code_verifier: String,
129}
130
131/// Token response from PAS token endpoint.
132#[derive(Debug, Clone, Deserialize)]
133#[non_exhaustive]
134pub struct TokenResponse {
135    pub access_token: String,
136    pub token_type: String,
137    #[serde(default)]
138    pub expires_in: Option<u64>,
139    #[serde(default)]
140    pub refresh_token: Option<String>,
141}
142
143/// User info from Ppoppo Accounts userinfo endpoint.
144#[derive(Debug, Clone, Serialize, Deserialize)]
145#[non_exhaustive]
146pub struct UserInfo {
147    pub sub: PpnumId,
148    #[serde(default)]
149    pub email: Option<String>,
150    pub ppnum: Ppnum,
151    #[serde(default)]
152    pub email_verified: Option<bool>,
153    #[serde(default, with = "time::serde::rfc3339::option")]
154    pub created_at: Option<time::OffsetDateTime>,
155}
156
157impl UserInfo {
158    /// Create a new `UserInfo` with required fields.
159    #[must_use]
160    pub fn new(sub: PpnumId, ppnum: Ppnum) -> Self {
161        Self {
162            sub,
163            ppnum,
164            email: None,
165            email_verified: None,
166            created_at: None,
167        }
168    }
169
170    /// Set the email.
171    #[must_use]
172    pub fn with_email(mut self, email: impl Into<String>) -> Self {
173        self.email = Some(email.into());
174        self
175    }
176
177    /// Set the email_verified flag.
178    #[must_use]
179    pub fn with_email_verified(mut self, verified: bool) -> Self {
180        self.email_verified = Some(verified);
181        self
182    }
183}
184
185impl AuthClient {
186    /// Create a new Ppoppo Accounts auth client.
187    #[must_use]
188    pub fn new(config: OAuthConfig) -> Self {
189        let builder = reqwest::Client::builder();
190        #[cfg(not(target_arch = "wasm32"))]
191        let builder = builder
192            .timeout(std::time::Duration::from_secs(10))
193            .connect_timeout(std::time::Duration::from_secs(5));
194        Self {
195            config,
196            http: builder.build().unwrap_or_default(),
197        }
198    }
199
200    /// Use a custom HTTP client (for connection pool reuse or testing).
201    #[must_use]
202    pub fn with_http_client(mut self, client: reqwest::Client) -> Self {
203        self.http = client;
204        self
205    }
206
207    /// Generate an authorization URL with PKCE parameters.
208    #[must_use]
209    pub fn authorization_url(&self) -> AuthorizationRequest {
210        let state = pkce::generate_state();
211        let code_verifier = pkce::generate_code_verifier();
212        let code_challenge = pkce::generate_code_challenge(&code_verifier);
213        let scope = self.config.scopes.join(" ");
214
215        let mut url = self.config.auth_url.clone();
216        url.query_pairs_mut()
217            .append_pair("response_type", "code")
218            .append_pair("client_id", &self.config.client_id)
219            .append_pair("redirect_uri", self.config.redirect_uri.as_str())
220            .append_pair("state", &state)
221            .append_pair("code_challenge", &code_challenge)
222            .append_pair("code_challenge_method", "S256")
223            .append_pair("scope", &scope);
224
225        AuthorizationRequest {
226            url: url.into(),
227            state,
228            code_verifier,
229        }
230    }
231
232    /// Exchange an authorization code for tokens using PKCE.
233    ///
234    /// # Errors
235    ///
236    /// Returns [`Error::Http`] on network failure, or
237    /// [`Error::OAuth`] if the token endpoint returns an error.
238    pub async fn exchange_code(
239        &self,
240        code: &str,
241        code_verifier: &str,
242    ) -> Result<TokenResponse, Error> {
243        let params = [
244            ("grant_type", "authorization_code"),
245            ("code", code),
246            ("redirect_uri", self.config.redirect_uri.as_str()),
247            ("client_id", self.config.client_id.as_str()),
248            ("code_verifier", code_verifier),
249        ];
250
251        self.send_and_deserialize(
252            self.http.post(self.config.token_url.clone()).form(&params),
253            "token exchange",
254        )
255        .await
256    }
257
258    /// Exchange a refresh token for new tokens.
259    ///
260    /// # Errors
261    ///
262    /// Returns [`Error::Http`] on network failure, or
263    /// [`Error::OAuth`] if the token endpoint returns an error.
264    pub async fn refresh_token(&self, refresh_token: &str) -> Result<TokenResponse, Error> {
265        let params = [
266            ("grant_type", "refresh_token"),
267            ("refresh_token", refresh_token),
268            ("client_id", self.config.client_id.as_str()),
269        ];
270
271        self.send_and_deserialize(
272            self.http.post(self.config.token_url.clone()).form(&params),
273            "token refresh",
274        )
275        .await
276    }
277
278    /// Fetch user info using an access token.
279    ///
280    /// # Errors
281    ///
282    /// Returns [`Error::Http`] on network failure, or
283    /// [`Error::OAuth`] if the userinfo endpoint returns an error.
284    pub async fn get_user_info(&self, access_token: &str) -> Result<UserInfo, Error> {
285        self.send_and_deserialize(
286            self.http
287                .get(self.config.userinfo_url.clone())
288                .bearer_auth(access_token),
289            "userinfo request",
290        )
291        .await
292    }
293
294    async fn send_and_deserialize<T: serde::de::DeserializeOwned>(
295        &self,
296        request: reqwest::RequestBuilder,
297        operation: &'static str,
298    ) -> Result<T, Error> {
299        let response = request.send().await?;
300
301        if !response.status().is_success() {
302            let status = response.status().as_u16();
303            let body = response.text().await.unwrap_or_default();
304            return Err(Error::OAuth {
305                operation,
306                status: Some(status),
307                detail: body,
308            });
309        }
310
311        response.json::<T>().await.map_err(|e| Error::OAuth {
312            operation,
313            status: None,
314            detail: format!("response deserialization failed: {e}"),
315        })
316    }
317}
318
319#[cfg(test)]
320#[allow(clippy::unwrap_used)]
321mod tests {
322    use super::*;
323
324    fn test_config() -> OAuthConfig {
325        OAuthConfig::new(
326            "test-client",
327            "https://example.com/callback".parse().unwrap(),
328        )
329    }
330
331    #[test]
332    fn test_authorization_url_contains_pkce() {
333        let client = AuthClient::new(test_config());
334        let req = client.authorization_url();
335
336        assert!(req.url.contains("code_challenge="));
337        assert!(req.url.contains("code_challenge_method=S256"));
338        assert!(req.url.contains("state="));
339        assert!(req.url.contains("response_type=code"));
340        assert!(req.url.contains("client_id=test-client"));
341        assert!(!req.code_verifier.is_empty());
342        assert!(!req.state.is_empty());
343    }
344
345    #[test]
346    fn test_authorization_url_unique_per_call() {
347        let client = AuthClient::new(test_config());
348        let req1 = client.authorization_url();
349        let req2 = client.authorization_url();
350
351        assert_ne!(req1.state, req2.state);
352        assert_ne!(req1.code_verifier, req2.code_verifier);
353    }
354
355    #[test]
356    fn test_config_constructor() {
357        let config = OAuthConfig::new("my-app", "https://my-app.com/callback".parse().unwrap());
358
359        assert_eq!(config.client_id(), "my-app");
360        assert_eq!(config.redirect_uri().as_str(), "https://my-app.com/callback");
361        assert_eq!(
362            config.auth_url().as_str(),
363            "https://accounts.ppoppo.com/oauth/authorize"
364        );
365    }
366
367    #[test]
368    fn test_config_with_overrides() {
369        let config = OAuthConfig::new("my-app", "https://my-app.com/callback".parse().unwrap())
370            .with_auth_url("https://custom.example.com/authorize".parse().unwrap())
371            .with_scopes(vec!["openid".into()]);
372
373        assert_eq!(
374            config.auth_url().as_str(),
375            "https://custom.example.com/authorize"
376        );
377        assert_eq!(config.scopes(), &["openid"]);
378    }
379}