pas-external 0.8.0-beta.1

Ppoppo Accounts System (PAS) external SDK — OAuth2 PKCE, JWT verification port, Axum middleware, session liveness
Documentation
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
use serde::{Deserialize, Serialize};
use url::Url;

use crate::error::Error;
use crate::pkce;
use crate::types::{Ppnum, PpnumId};

const DEFAULT_AUTH_URL: &str = "https://accounts.ppoppo.com/oauth/authorize";
const DEFAULT_TOKEN_URL: &str = "https://accounts.ppoppo.com/oauth/token";
const DEFAULT_USERINFO_URL: &str = "https://accounts.ppoppo.com/oauth/userinfo";

/// Ppoppo Accounts `OAuth2` configuration.
///
/// Required fields are constructor parameters — no runtime "missing field" errors.
///
/// ```rust,ignore
/// use ppoppo_sdk::OAuthConfig;
///
/// let config = OAuthConfig::new("my-client-id", "https://my-app.com/callback".parse()?);
/// // Optional overrides via chaining:
/// let config = config
///     .with_auth_url("https://custom.example.com/authorize".parse()?);
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct OAuthConfig {
    pub(crate) client_id: String,
    pub(crate) auth_url: Url,
    pub(crate) token_url: Url,
    pub(crate) userinfo_url: Url,
    pub(crate) redirect_uri: Url,
    pub(crate) scopes: Vec<String>,
}

impl OAuthConfig {
    /// Create a new OAuth2 configuration.
    ///
    /// Required fields are parameters — compile-time enforcement, no `Result`.
    #[must_use]
    #[allow(clippy::expect_used)] // Infallible parse — URLs are compile-time constants
    pub fn new(client_id: impl Into<String>, redirect_uri: Url) -> Self {
        Self {
            client_id: client_id.into(),
            redirect_uri,
            auth_url: DEFAULT_AUTH_URL.parse().expect("valid default URL"),
            token_url: DEFAULT_TOKEN_URL.parse().expect("valid default URL"),
            userinfo_url: DEFAULT_USERINFO_URL.parse().expect("valid default URL"),
            scopes: vec!["profile".into()],
        }
    }

    /// Override the PAS authorization endpoint.
    #[must_use]
    pub fn with_auth_url(mut self, url: Url) -> Self {
        self.auth_url = url;
        self
    }

    /// Override the PAS token endpoint.
    #[must_use]
    pub fn with_token_url(mut self, url: Url) -> Self {
        self.token_url = url;
        self
    }

    /// Override the PAS userinfo endpoint.
    #[must_use]
    pub fn with_userinfo_url(mut self, url: Url) -> Self {
        self.userinfo_url = url;
        self
    }

    /// Override the OAuth2 scopes (default: `["profile"]`).
    #[must_use]
    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
        self.scopes = scopes;
        self
    }

    /// `OAuth2` client ID.
    #[must_use]
    pub fn client_id(&self) -> &str {
        &self.client_id
    }

    /// Authorization endpoint URL.
    #[must_use]
    pub fn auth_url(&self) -> &Url {
        &self.auth_url
    }

    /// Token exchange endpoint URL.
    #[must_use]
    pub fn token_url(&self) -> &Url {
        &self.token_url
    }

    /// User info endpoint URL.
    #[must_use]
    pub fn userinfo_url(&self) -> &Url {
        &self.userinfo_url
    }

    /// `OAuth2` redirect URI.
    #[must_use]
    pub fn redirect_uri(&self) -> &Url {
        &self.redirect_uri
    }

    /// Requested `OAuth2` scopes.
    #[must_use]
    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }
}

/// `OAuth2` authorization client for Ppoppo Accounts.
pub struct AuthClient {
    config: OAuthConfig,
    http: reqwest::Client,
}

/// Authorization URL with PKCE parameters to store in session.
#[non_exhaustive]
pub struct AuthorizationRequest {
    pub url: String,
    pub state: String,
    pub code_verifier: String,
}

/// Token response from PAS token endpoint.
///
/// `id_token` is OIDC-only (RFC 6749 token responses carry only
/// access + refresh; OIDC Core §3.1.3.3 adds `id_token` when scope
/// includes `openid`). [`crate::oidc::RelyingParty<S>`] reads it
/// internally; OAuth-only consumers ignore it.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
pub struct TokenResponse {
    pub access_token: String,
    pub token_type: String,
    #[serde(default)]
    pub expires_in: Option<u64>,
    #[serde(default)]
    pub refresh_token: Option<String>,
    #[serde(default)]
    pub id_token: Option<String>,
}

/// User info from Ppoppo Accounts userinfo endpoint.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct UserInfo {
    pub sub: PpnumId,
    #[serde(default)]
    pub email: Option<String>,
    pub ppnum: Ppnum,
    #[serde(default)]
    pub email_verified: Option<bool>,
    #[serde(default, with = "time::serde::rfc3339::option")]
    pub created_at: Option<time::OffsetDateTime>,
}

impl UserInfo {
    /// Create a new `UserInfo` with required fields.
    #[must_use]
    pub fn new(sub: PpnumId, ppnum: Ppnum) -> Self {
        Self {
            sub,
            ppnum,
            email: None,
            email_verified: None,
            created_at: None,
        }
    }

    /// Set the email.
    #[must_use]
    pub fn with_email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// Set the email_verified flag.
    #[must_use]
    pub fn with_email_verified(mut self, verified: bool) -> Self {
        self.email_verified = Some(verified);
        self
    }
}

impl AuthClient {
    /// Create a new Ppoppo Accounts auth client.
    ///
    /// Returns an error iff `reqwest::Client::builder()` cannot construct a
    /// client with the configured timeouts (TLS init failure, OS-level
    /// resource exhaustion). The previous `unwrap_or_default()` path silently
    /// substituted a no-timeout client, which converted a startup failure
    /// into a runtime hang on the first PAS call — fail loudly instead.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Http`] if the underlying HTTP client cannot be built.
    pub fn try_new(config: OAuthConfig) -> Result<Self, Error> {
        let builder = reqwest::Client::builder();
        #[cfg(not(target_arch = "wasm32"))]
        let builder = builder
            .timeout(std::time::Duration::from_secs(10))
            .connect_timeout(std::time::Duration::from_secs(5));
        Ok(Self {
            config,
            http: builder.build()?,
        })
    }

    /// Build with a caller-supplied HTTP client.
    ///
    /// Use this when sharing a `reqwest::Client` across multiple SDK clients
    /// for connection-pool reuse, or when you need custom TLS / proxy / timeout
    /// configuration. This constructor never fails.
    #[must_use]
    pub fn with_http_client(config: OAuthConfig, client: reqwest::Client) -> Self {
        Self {
            config,
            http: client,
        }
    }

    /// Generate an authorization URL with PKCE parameters.
    #[must_use]
    pub fn authorization_url(&self) -> AuthorizationRequest {
        let state = pkce::generate_state();
        let code_verifier = pkce::generate_code_verifier();
        let code_challenge = pkce::generate_code_challenge(&code_verifier);
        let scope = self.config.scopes.join(" ");

        let mut url = self.config.auth_url.clone();
        url.query_pairs_mut()
            .append_pair("response_type", "code")
            .append_pair("client_id", &self.config.client_id)
            .append_pair("redirect_uri", self.config.redirect_uri.as_str())
            .append_pair("state", &state)
            .append_pair("code_challenge", &code_challenge)
            .append_pair("code_challenge_method", "S256")
            .append_pair("scope", &scope);

        AuthorizationRequest {
            url: url.into(),
            state,
            code_verifier,
        }
    }

    /// Exchange an authorization code for tokens using PKCE.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Http`] on network failure, or
    /// [`Error::OAuth`] if the token endpoint returns an error.
    pub async fn exchange_code(
        &self,
        code: &str,
        code_verifier: &str,
    ) -> Result<TokenResponse, Error> {
        let params = [
            ("grant_type", "authorization_code"),
            ("code", code),
            ("redirect_uri", self.config.redirect_uri.as_str()),
            ("client_id", self.config.client_id.as_str()),
            ("code_verifier", code_verifier),
        ];

        self.send_classified(
            self.http.post(self.config.token_url.clone()).form(&params),
        )
        .await
        .map_err(|f| f.into_legacy_error("token exchange"))
    }

    /// The single place in this module that reads HTTP status codes
    /// from PAS token / userinfo / exchange-code responses. The
    /// `PasAuthPort` impl methods (`refresh`, `userinfo`) consume the
    /// resulting [`PasFailure`] directly; the legacy-signature
    /// inherent method `exchange_code` converts via
    /// [`PasFailure::into_legacy_error`].
    ///
    /// Note: `keyset::fetch_document` performs its own status-reading
    /// for the well-known keyset document and does not route through
    /// here. Future RFCs may unify those paths.
    async fn send_classified<T: serde::de::DeserializeOwned>(
        &self,
        request: reqwest::RequestBuilder,
    ) -> Result<T, crate::pas_port::PasFailure> {
        use crate::pas_port::PasFailure;

        let response = request
            .send()
            .await
            .map_err(|e| PasFailure::Transport { detail: e.to_string() })?;

        let status = response.status();
        if status.is_server_error() {
            let body = response.text().await.unwrap_or_default();
            return Err(PasFailure::ServerError { status: status.as_u16(), detail: body });
        }
        if !status.is_success() {
            let body = response.text().await.unwrap_or_default();
            return Err(PasFailure::Rejected { status: status.as_u16(), detail: body });
        }

        response.json::<T>().await.map_err(|e| PasFailure::Transport {
            detail: format!("response deserialization failed: {e}"),
        })
    }
}

impl crate::pas_port::PasAuthPort for AuthClient {
    async fn refresh(
        &self,
        refresh_token: &str,
    ) -> Result<TokenResponse, crate::pas_port::PasFailure> {
        let params = [
            ("grant_type", "refresh_token"),
            ("refresh_token", refresh_token),
            ("client_id", self.config.client_id.as_str()),
        ];

        self.send_classified(
            self.http.post(self.config.token_url.clone()).form(&params),
        )
        .await
    }

    async fn userinfo(
        &self,
        access_token: &str,
    ) -> Result<UserInfo, crate::pas_port::PasFailure> {
        self.send_classified(
            self.http
                .get(self.config.userinfo_url.clone())
                .bearer_auth(access_token),
        )
        .await
    }
}

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

    fn test_config() -> OAuthConfig {
        OAuthConfig::new(
            "test-client",
            "https://example.com/callback".parse().unwrap(),
        )
    }

    #[test]
    fn test_authorization_url_contains_pkce() {
        let client = AuthClient::try_new(test_config()).unwrap();
        let req = client.authorization_url();

        assert!(req.url.contains("code_challenge="));
        assert!(req.url.contains("code_challenge_method=S256"));
        assert!(req.url.contains("state="));
        assert!(req.url.contains("response_type=code"));
        assert!(req.url.contains("client_id=test-client"));
        assert!(!req.code_verifier.is_empty());
        assert!(!req.state.is_empty());
    }

    #[test]
    fn test_authorization_url_unique_per_call() {
        let client = AuthClient::try_new(test_config()).unwrap();
        let req1 = client.authorization_url();
        let req2 = client.authorization_url();

        assert_ne!(req1.state, req2.state);
        assert_ne!(req1.code_verifier, req2.code_verifier);
    }

    #[test]
    fn test_config_constructor() {
        let config = OAuthConfig::new("my-app", "https://my-app.com/callback".parse().unwrap());

        assert_eq!(config.client_id(), "my-app");
        assert_eq!(
            config.redirect_uri().as_str(),
            "https://my-app.com/callback"
        );
        assert_eq!(
            config.auth_url().as_str(),
            "https://accounts.ppoppo.com/oauth/authorize"
        );
    }

    #[test]
    fn test_config_with_overrides() {
        let config = OAuthConfig::new("my-app", "https://my-app.com/callback".parse().unwrap())
            .with_auth_url("https://custom.example.com/authorize".parse().unwrap())
            .with_scopes(vec!["profile".into(), "email".into()]);

        assert_eq!(
            config.auth_url().as_str(),
            "https://custom.example.com/authorize"
        );
        assert_eq!(config.scopes(), &["profile", "email"]);
    }
}