xjp-oidc 1.1.0

OIDC/OAuth2 SDK for Rust - Server and WASM support
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
//! Authorization code exchange implementation (server-only)

#[cfg(not(target_arch = "wasm32"))]
use crate::{
    discovery::discover,
    errors::{Error, Result},
    http::HttpClient,
    types::{ExchangeCode, TokenResponse},
};
#[cfg(not(target_arch = "wasm32"))]
use base64::{engine::general_purpose, Engine as _};

/// Exchange authorization code for tokens
///
/// This is a server-only function that exchanges an authorization code
/// for access token, refresh token (optional), and ID token (if openid scope).
///
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use xjp_oidc::{exchange_code, ExchangeCode, http::ReqwestHttpClient};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let http = ReqwestHttpClient::default();
///
/// let tokens = exchange_code(ExchangeCode {
///     issuer: "https://auth.example.com".into(),
///     client_id: "my-client".into(),
///     code: "auth_code".into(),
///     redirect_uri: "https://app.example.com/callback".into(),
///     code_verifier: Some("pkce_verifier".into()),
///     client_secret: None, // For public clients
///     token_endpoint_auth_method: None,
/// }, &http).await?;
/// # Ok(())
/// # }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn exchange_code(params: ExchangeCode, http: &dyn HttpClient) -> Result<TokenResponse> {
    // Validate parameters
    validate_exchange_params(&params)?;

    // Get token endpoint from discovery
    let cache = crate::cache::NoOpCache;
    let metadata = discover(&params.issuer, http, &cache).await?;

    // Build form data
    let mut form = vec![
        ("grant_type".to_string(), "authorization_code".to_string()),
        ("code".to_string(), params.code.clone()),
        ("redirect_uri".to_string(), params.redirect_uri.clone()),
    ];

    // Add PKCE verifier if provided
    if let Some(verifier) = &params.code_verifier {
        if !verifier.is_empty() {
            form.push(("code_verifier".to_string(), verifier.clone()));
        }
    }

    // Determine authentication method based on token_endpoint_auth_method
    let auth_method = params.token_endpoint_auth_method
        .as_deref()
        .unwrap_or(if params.client_secret.is_some() {
            "client_secret_basic"
        } else {
            "none"
        });

    let auth_header = match auth_method {
        "client_secret_basic" => {
            if let Some(client_secret) = &params.client_secret {
                let credentials = format!("{}:{}", params.client_id, client_secret);
                let encoded = general_purpose::STANDARD.encode(credentials.as_bytes());
                Some(("Authorization".to_string(), format!("Basic {}", encoded)))
            } else {
                return Err(Error::InvalidParam("client_secret_basic requires client_secret"));
            }
        },
        "client_secret_post" => {
            // Add client credentials to form data
            form.push(("client_id".to_string(), params.client_id.clone()));
            if let Some(client_secret) = &params.client_secret {
                form.push(("client_secret".to_string(), client_secret.clone()));
            } else {
                return Err(Error::InvalidParam("client_secret_post requires client_secret"));
            }
            None
        },
        "none" | "public" => {
            // Public client - include client_id in form
            form.push(("client_id".to_string(), params.client_id.clone()));
            None
        },
        "private_key_jwt" | "client_secret_jwt" => {
            // TODO: Implement JWT-based authentication
            // For now, return error indicating it's not supported
            return Err(Error::InvalidParam(
                "JWT-based authentication methods are not yet supported"
            ));
        },
        _ => {
            return Err(Error::InvalidParam(
                "Unknown authentication method"
            ));
        }
    };

    // Make the token request
    let response = http
        .post_form_value(
            &metadata.token_endpoint,
            &form,
            auth_header.as_ref().map(|(k, v)| (k.as_str(), v.as_str())),
        )
        .await
        .map_err(|e| {
            // Try to parse OAuth error from response
            if let crate::http::HttpClientError::InvalidStatus { status: _, message } = &e {
                if let Ok(oauth_error) = serde_json::from_str::<OAuthError>(&message) {
                    return Error::oauth(oauth_error.error, oauth_error.error_description);
                }
            }
            Error::Network(format!("Token exchange failed: {}", e))
        })?;

    // Parse token response
    let tokens: TokenResponse = serde_json::from_value(response)?;

    Ok(tokens)
}

/// Validate exchange parameters
#[cfg(not(target_arch = "wasm32"))]
fn validate_exchange_params(params: &ExchangeCode) -> Result<()> {
    if params.issuer.is_empty() {
        return Err(Error::InvalidParam("issuer cannot be empty"));
    }
    if params.client_id.is_empty() {
        return Err(Error::InvalidParam("client_id cannot be empty"));
    }
    if params.code.is_empty() {
        return Err(Error::InvalidParam("code cannot be empty"));
    }
    if params.redirect_uri.is_empty() {
        return Err(Error::InvalidParam("redirect_uri cannot be empty"));
    }
    // PKCE is required for public clients, but optional for confidential clients
    if params.client_secret.is_none() && params.code_verifier.as_ref().map_or(true, |v| v.is_empty()) {
        return Err(Error::InvalidParam("code_verifier is required for public clients"));
    }
    Ok(())
}

/// OAuth error response
#[cfg(not(target_arch = "wasm32"))]
#[derive(serde::Deserialize)]
struct OAuthError {
    error: String,
    error_description: Option<String>,
}

/// Exchange code with explicit token endpoint
#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
pub async fn exchange_code_with_endpoint(
    params: ExchangeCode,
    token_endpoint: &str,
    http: &dyn HttpClient,
) -> Result<TokenResponse> {
    // Validate parameters
    validate_exchange_params(&params)?;

    // Build form data
    let mut form = vec![
        ("grant_type".to_string(), "authorization_code".to_string()),
        ("code".to_string(), params.code.clone()),
        ("redirect_uri".to_string(), params.redirect_uri.clone()),
    ];

    // Add PKCE verifier if provided
    if let Some(verifier) = &params.code_verifier {
        if !verifier.is_empty() {
            form.push(("code_verifier".to_string(), verifier.clone()));
        }
    }

    // Determine authentication method
    let auth_header = if let Some(client_secret) = &params.client_secret {
        // Check if we should use client_secret_post instead
        let use_post = params
            .token_endpoint_auth_method
            .as_ref()
            .map(|m| m == "client_secret_post")
            .unwrap_or(false);

        if use_post {
            form.push(("client_id".to_string(), params.client_id.clone()));
            form.push(("client_secret".to_string(), client_secret.clone()));
            None
        } else {
            // Use client_secret_basic (default)
            let credentials = format!("{}:{}", params.client_id, client_secret);
            let encoded = general_purpose::STANDARD.encode(credentials.as_bytes());
            Some(("Authorization".to_string(), format!("Basic {}", encoded)))
        }
    } else {
        // Public client
        form.push(("client_id".to_string(), params.client_id.clone()));
        None
    };

    // Make the token request
    let response = http
        .post_form_value(
            token_endpoint,
            &form,
            auth_header.as_ref().map(|(k, v)| (k.as_str(), v.as_str())),
        )
        .await
        .map_err(|e| {
            // Try to parse OAuth error from response
            if let crate::http::HttpClientError::InvalidStatus { status: _, message } = &e {
                if let Ok(oauth_error) = serde_json::from_str::<OAuthError>(&message) {
                    return Error::oauth(oauth_error.error, oauth_error.error_description);
                }
            }
            Error::Network(format!("Token exchange failed: {}", e))
        })?;

    // Parse token response
    let tokens: TokenResponse = serde_json::from_value(response)?;

    Ok(tokens)
}


/// Refresh an access token using a refresh token
///
/// This exchanges a refresh token for a new access token and optionally
/// a new refresh token.
///
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use xjp_oidc::{refresh_token, RefreshTokenRequest, http::ReqwestHttpClient};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let http = ReqwestHttpClient::default();
///
/// let tokens = refresh_token(RefreshTokenRequest {
///     issuer: "https://auth.example.com".into(),
///     client_id: "my-client".into(),
///     client_secret: Some("my-secret".into()),
///     refresh_token: "refresh_token_here".into(),
///     scope: Some("openid profile email".into()),
///     token_endpoint_auth_method: None,
/// }, &http).await?;
///
/// println!("New access token: {}", tokens.access_token);
/// # Ok(())
/// # }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn refresh_token(
    params: crate::types::RefreshTokenRequest,
    http: &dyn HttpClient,
) -> Result<TokenResponse> {
    // Validate parameters
    if params.issuer.is_empty() {
        return Err(Error::InvalidParam("issuer cannot be empty"));
    }
    if params.client_id.is_empty() {
        return Err(Error::InvalidParam("client_id cannot be empty"));
    }
    if params.refresh_token.is_empty() {
        return Err(Error::InvalidParam("refresh_token cannot be empty"));
    }

    // Get token endpoint from discovery
    let cache = crate::cache::NoOpCache;
    let metadata = discover(&params.issuer, http, &cache).await?;

    // Build form data
    let mut form = vec![
        ("grant_type".to_string(), "refresh_token".to_string()),
        ("refresh_token".to_string(), params.refresh_token.clone()),
    ];

    // Add scope if provided
    if let Some(scope) = &params.scope {
        if !scope.is_empty() {
            form.push(("scope".to_string(), scope.clone()));
        }
    }

    // Determine authentication method based on token_endpoint_auth_method
    let auth_method = params.token_endpoint_auth_method
        .as_deref()
        .unwrap_or(if params.client_secret.is_some() {
            "client_secret_basic"
        } else {
            "none"
        });

    let auth_header = match auth_method {
        "client_secret_basic" => {
            if let Some(client_secret) = &params.client_secret {
                let credentials = format!("{}:{}", params.client_id, client_secret);
                let encoded = general_purpose::STANDARD.encode(credentials.as_bytes());
                Some(("Authorization".to_string(), format!("Basic {}", encoded)))
            } else {
                return Err(Error::InvalidParam("client_secret_basic requires client_secret"));
            }
        },
        "client_secret_post" => {
            // Add client credentials to form data
            form.push(("client_id".to_string(), params.client_id.clone()));
            if let Some(client_secret) = &params.client_secret {
                form.push(("client_secret".to_string(), client_secret.clone()));
            } else {
                return Err(Error::InvalidParam("client_secret_post requires client_secret"));
            }
            None
        },
        "none" | "public" => {
            // Public client - include client_id in form
            form.push(("client_id".to_string(), params.client_id.clone()));
            None
        },
        "private_key_jwt" | "client_secret_jwt" => {
            // TODO: Implement JWT-based authentication
            return Err(Error::InvalidParam(
                "JWT-based authentication methods are not yet supported"
            ));
        },
        _ => {
            return Err(Error::InvalidParam(
                "Unknown authentication method"
            ));
        }
    };

    // Make the token request
    let response = http
        .post_form_value(
            &metadata.token_endpoint,
            &form,
            auth_header.as_ref().map(|(k, v)| (k.as_str(), v.as_str())),
        )
        .await
        .map_err(|e| {
            // Try to parse OAuth error from response
            if let crate::http::HttpClientError::InvalidStatus { status: _, message } = &e {
                if let Ok(oauth_error) = serde_json::from_str::<OAuthError>(&message) {
                    return Error::oauth(oauth_error.error, oauth_error.error_description);
                }
            }
            Error::Network(format!("Token refresh failed: {}", e))
        })?;

    // Parse token response
    let tokens: TokenResponse = serde_json::from_value(response)?;

    Ok(tokens)
}

// WASM stubs
#[cfg(target_arch = "wasm32")]
pub async fn exchange_code(
    _params: crate::types::ExchangeCode,
    _http: &dyn crate::http::HttpClient,
) -> crate::errors::Result<crate::types::TokenResponse> {
    Err(crate::errors::Error::ServerOnly)
}

#[cfg(target_arch = "wasm32")]
pub async fn refresh_token(
    _params: crate::types::RefreshTokenRequest,
    _http: &dyn crate::http::HttpClient,
) -> crate::errors::Result<crate::types::TokenResponse> {
    Err(crate::errors::Error::ServerOnly)
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    #[test]
    fn test_validate_exchange_params() {
        let valid = ExchangeCode {
            issuer: "https://auth.example.com".into(),
            client_id: "test-client".into(),
            code: "auth_code".into(),
            redirect_uri: "https://app.example.com/callback".into(),
            code_verifier: Some("verifier".into()),
            client_secret: None,
            token_endpoint_auth_method: None,
        };
        assert!(validate_exchange_params(&valid).is_ok());

        let invalid = ExchangeCode { issuer: "".into(), ..valid.clone() };
        assert!(validate_exchange_params(&invalid).is_err());
    }
}