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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! Authorization URL building and callback parsing

use crate::{
    errors::{Error, Result},
    types::{AuthUrlResult, BuildAuthUrl, CallbackParams, EndSession, OidcProviderMetadata},
};
use rand::{distributions::Alphanumeric, Rng};
#[cfg(test)]
use std::collections::HashMap;
use url::Url;

/// Build an authorization URL for the OAuth2/OIDC flow
///
/// # Example
/// ```no_run
/// use xjp_oidc::{build_auth_url, BuildAuthUrl};
///
/// let result = build_auth_url(BuildAuthUrl {
///     issuer: "https://auth.example.com".into(),
///     client_id: "my-client".into(),
///     redirect_uri: "https://app.example.com/callback".into(),
///     scope: "openid profile email".into(),
///     code_challenge: "challenge".into(),
///     authorization_endpoint: Some("https://auth.example.com/oauth/authorize".into()),
///     ..Default::default()
/// }).unwrap();
/// let url = result.url;
/// let state = result.state; // Save for CSRF validation
/// let nonce = result.nonce; // Save for ID token validation
/// ```
pub fn build_auth_url(params: BuildAuthUrl) -> Result<AuthUrlResult> {
    // Validate required 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.redirect_uri.is_empty() {
        return Err(Error::InvalidParam("redirect_uri cannot be empty"));
    }
    if params.code_challenge.is_empty() {
        return Err(Error::InvalidParam("code_challenge cannot be empty"));
    }

    // Build authorization endpoint URL
    // Require authorization_endpoint to be provided
    let auth_endpoint = params
        .authorization_endpoint
        .ok_or_else(|| Error::InvalidParam("authorization_endpoint is required. Please use OIDC discovery to obtain the correct endpoint"))?;

    let mut url = Url::parse(&auth_endpoint)?;

    // Prepare state and nonce outside the query scope
    let scope = if params.scope.is_empty() { "openid profile email" } else { &params.scope };
    let state = params.state.unwrap_or_else(generate_state);
    let nonce = if scope.contains("openid") {
        Some(params.nonce.unwrap_or_else(generate_nonce))
    } else {
        None
    };

    // Add query parameters
    {
        let mut query = url.query_pairs_mut();
        query.append_pair("response_type", "code");
        query.append_pair("client_id", &params.client_id);
        query.append_pair("redirect_uri", &params.redirect_uri);

        // Scope
        query.append_pair("scope", scope);

        // State
        query.append_pair("state", &state);

        // PKCE
        query.append_pair("code_challenge", &params.code_challenge);
        query.append_pair("code_challenge_method", "S256");

        // Nonce
        if let Some(ref nonce) = nonce {
            query.append_pair("nonce", nonce);
        }

        // Prompt (optional)
        if let Some(prompt) = &params.prompt {
            query.append_pair("prompt", prompt);
        }

        // Tenant (optional)
        if let Some(tenant) = &params.tenant {
            query.append_pair("tenant", tenant);
        }

        // Extra parameters
        if let Some(extra) = &params.extra_params {
            for (key, value) in extra {
                query.append_pair(key, value);
            }
        }
    }

    Ok(AuthUrlResult { url, state, nonce })
}

/// Build an end session (logout) URL
///
/// # Example
/// ```no_run
/// use xjp_oidc::{build_end_session_url, EndSession};
///
/// let url = build_end_session_url(EndSession {
///     issuer: "https://auth.example.com".into(),
///     id_token_hint: "id_token_here".into(),
///     post_logout_redirect_uri: Some("https://app.example.com".into()),
///     state: None,
///     end_session_endpoint: None,
/// }).unwrap();
/// ```
pub fn build_end_session_url(params: EndSession) -> Result<Url> {
    // Validate required parameters
    if params.issuer.is_empty() {
        return Err(Error::InvalidParam("issuer cannot be empty"));
    }
    if params.id_token_hint.is_empty() {
        return Err(Error::InvalidParam("id_token_hint cannot be empty"));
    }

    // Build end session endpoint URL
    let end_session_endpoint = if let Some(endpoint) = &params.end_session_endpoint {
        // Use provided endpoint from discovery
        endpoint.clone()
    } else {
        // Fall back to default path
        if params.issuer.ends_with('/') {
            format!("{}oidc/end_session", params.issuer)
        } else {
            format!("{}/oidc/end_session", params.issuer)
        }
    };

    let mut url = Url::parse(&end_session_endpoint)?;

    // Add query parameters
    {
        let mut query = url.query_pairs_mut();
        query.append_pair("id_token_hint", &params.id_token_hint);

        if let Some(redirect_uri) = &params.post_logout_redirect_uri {
            query.append_pair("post_logout_redirect_uri", redirect_uri);
        }

        if let Some(state) = &params.state {
            query.append_pair("state", state);
        }
    }

    Ok(url)
}

/// Build an end session URL with discovery metadata
///
/// This is a convenience function that automatically uses the discovered end_session_endpoint.
///
/// # Example
/// ```no_run
/// # async fn example() -> xjp_oidc::errors::Result<()> {
/// use xjp_oidc::{build_end_session_url_with_discovery, EndSession, OidcProviderMetadata};
///
/// # let http_client = xjp_oidc::ReqwestHttpClient::default();
/// # let cache = xjp_oidc::NoOpCache;
/// let metadata = xjp_oidc::discover("https://auth.example.com", &http_client, &cache).await?;
/// let url = build_end_session_url_with_discovery(EndSession {
///     issuer: "https://auth.example.com".into(),
///     id_token_hint: "id_token_here".into(),
///     post_logout_redirect_uri: Some("https://app.example.com".into()),
///     state: None,
///     end_session_endpoint: None, // Will be filled from metadata
/// }, &metadata)?;
/// # Ok(())
/// # }
/// ```
pub fn build_end_session_url_with_discovery(
    mut params: EndSession,
    metadata: &OidcProviderMetadata,
) -> Result<Url> {
    // Use discovered endpoint if not already provided
    if params.end_session_endpoint.is_none() {
        params.end_session_endpoint = metadata.end_session_endpoint.clone();
    }

    build_end_session_url(params)
}

/// Parse callback parameters from the authorization response
///
/// # Example
/// ```
/// use xjp_oidc::parse_callback_params;
///
/// let params = parse_callback_params("https://app.example.com/callback?code=abc&state=xyz");
/// assert_eq!(params.code, Some("abc".to_string()));
/// assert_eq!(params.state, Some("xyz".to_string()));
/// ```
pub fn parse_callback_params(url: &str) -> CallbackParams {
    let mut params =
        CallbackParams { code: None, state: None, error: None, error_description: None };

    // Parse URL and extract query parameters
    if let Ok(parsed_url) = Url::parse(url) {
        for (key, value) in parsed_url.query_pairs() {
            match key.as_ref() {
                "code" => params.code = Some(value.into_owned()),
                "state" => params.state = Some(value.into_owned()),
                "error" => params.error = Some(value.into_owned()),
                "error_description" => params.error_description = Some(value.into_owned()),
                _ => {} // Ignore other parameters
            }
        }
    } else {
        // Try to parse as relative URL (e.g., "/callback?code=...")
        // or as a query string only (e.g., "code=test&state=state123")
        let query = if let Some(query_start) = url.find('?') {
            &url[query_start + 1..]
        } else if url.contains('=') {
            // Assume it's a query string without URL prefix
            url
        } else {
            ""
        };

        if !query.is_empty() {
            for pair in query.split('&') {
                if let Some(eq_pos) = pair.find('=') {
                    let key = &pair[..eq_pos];
                    let value = &pair[eq_pos + 1..];
                    let decoded_value = urlencoding::decode(value).unwrap_or_else(|_| value.into());

                    match key {
                        "code" => params.code = Some(decoded_value.into_owned()),
                        "state" => params.state = Some(decoded_value.into_owned()),
                        "error" => params.error = Some(decoded_value.into_owned()),
                        "error_description" => {
                            params.error_description = Some(decoded_value.into_owned())
                        }
                        _ => {} // Ignore other parameters
                    }
                }
            }
        }
    }

    params
}

/// Build authorization URL from provider metadata
#[allow(dead_code)]
pub fn build_auth_url_with_metadata(
    metadata: &OidcProviderMetadata,
    params: BuildAuthUrl,
) -> Result<AuthUrlResult> {
    let mut url = Url::parse(&metadata.authorization_endpoint)?;

    // Prepare state and nonce outside the query scope
    let state = params.state.unwrap_or_else(generate_state);
    let nonce = if params.scope.contains("openid") {
        Some(params.nonce.unwrap_or_else(generate_nonce))
    } else {
        None
    };

    // Add query parameters
    {
        let mut query = url.query_pairs_mut();
        query.append_pair("response_type", "code");
        query.append_pair("client_id", &params.client_id);
        query.append_pair("redirect_uri", &params.redirect_uri);
        query.append_pair("scope", &params.scope);

        // State
        query.append_pair("state", &state);

        // PKCE
        query.append_pair("code_challenge", &params.code_challenge);
        query.append_pair("code_challenge_method", "S256");

        // Nonce for OIDC
        if let Some(ref nonce) = nonce {
            query.append_pair("nonce", nonce);
        }

        // Optional parameters
        if let Some(prompt) = &params.prompt {
            query.append_pair("prompt", prompt);
        }

        if let Some(tenant) = &params.tenant {
            query.append_pair("tenant", tenant);
        }

        // Extra parameters
        if let Some(extra) = &params.extra_params {
            for (key, value) in extra {
                query.append_pair(key, value);
            }
        }
    }

    Ok(AuthUrlResult { url, state, nonce })
}

/// Generate a random state parameter
fn generate_state() -> String {
    rand::thread_rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect()
}

/// Generate a random nonce
fn generate_nonce() -> String {
    rand::thread_rng().sample_iter(&Alphanumeric).take(32).map(char::from).collect()
}

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

    #[test]
    fn test_build_auth_url() {
        let result = build_auth_url(BuildAuthUrl {
            issuer: "https://auth.example.com".into(),
            client_id: "test-client".into(),
            redirect_uri: "https://app.example.com/callback".into(),
            scope: "openid profile".into(),
            code_challenge: "test_challenge".into(),
            state: Some("test_state".into()),
            nonce: Some("test_nonce".into()),
            prompt: None,
            extra_params: None,
            tenant: None,
            authorization_endpoint: Some("https://auth.example.com/oauth/authorize".into()),
        })
        .unwrap();

        let url = result.url;
        assert_eq!(result.state, "test_state");
        assert_eq!(result.nonce, Some("test_nonce".to_string()));

        let query: HashMap<_, _> = url.query_pairs().into_owned().collect();

        assert_eq!(query.get("response_type"), Some(&"code".to_string()));
        assert_eq!(query.get("client_id"), Some(&"test-client".to_string()));
        assert_eq!(
            query.get("redirect_uri"),
            Some(&"https://app.example.com/callback".to_string())
        );
        assert_eq!(query.get("scope"), Some(&"openid profile".to_string()));
        assert_eq!(query.get("state"), Some(&"test_state".to_string()));
        assert_eq!(query.get("nonce"), Some(&"test_nonce".to_string()));
        assert_eq!(query.get("code_challenge"), Some(&"test_challenge".to_string()));
        assert_eq!(query.get("code_challenge_method"), Some(&"S256".to_string()));
    }

    #[test]
    fn test_build_auth_url_auto_state_nonce() {
        let result = build_auth_url(BuildAuthUrl {
            issuer: "https://auth.example.com".into(),
            client_id: "test-client".into(),
            redirect_uri: "https://app.example.com/callback".into(),
            scope: "openid profile".into(),
            code_challenge: "test_challenge".into(),
            state: None,
            nonce: None,
            prompt: None,
            extra_params: None,
            tenant: None,
            authorization_endpoint: Some("https://auth.example.com/oauth/authorize".into()),
        })
        .unwrap();

        let url = result.url;
        // Check that state and nonce were generated
        assert_eq!(result.state.len(), 32);
        assert_eq!(result.nonce.as_ref().unwrap().len(), 32);

        let query: HashMap<_, _> = url.query_pairs().into_owned().collect();

        // State and nonce should be auto-generated
        assert!(query.contains_key("state"));
        assert!(query.contains_key("nonce"));
        assert_eq!(query.get("state").unwrap().len(), 32);
        assert_eq!(query.get("nonce").unwrap().len(), 32);
    }

    #[test]
    fn test_build_auth_url_missing_authorization_endpoint() {
        let result = build_auth_url(BuildAuthUrl {
            issuer: "https://auth.example.com".into(),
            client_id: "test-client".into(),
            redirect_uri: "https://app.example.com/callback".into(),
            scope: "openid profile".into(),
            code_challenge: "test_challenge".into(),
            state: Some("test_state".into()),
            nonce: Some("test_nonce".into()),
            prompt: None,
            extra_params: None,
            tenant: None,
            authorization_endpoint: None,
        });

        assert!(result.is_err());
        match result {
            Err(Error::InvalidParam(msg)) => {
                assert!(msg.contains("authorization_endpoint is required"));
            }
            _ => panic!("Expected InvalidParam error"),
        }
    }

    #[test]
    fn test_parse_callback_params() {
        let params =
            parse_callback_params("https://app.example.com/callback?code=abc123&state=xyz456");

        assert_eq!(params.code, Some("abc123".to_string()));
        assert_eq!(params.state, Some("xyz456".to_string()));
        assert_eq!(params.error, None);
        assert_eq!(params.error_description, None);
    }

    #[test]
    fn test_parse_callback_params_error() {
        let params = parse_callback_params(
            "https://app.example.com/callback?error=access_denied&error_description=User%20denied%20access"
        );

        assert_eq!(params.code, None);
        assert_eq!(params.state, None);
        assert_eq!(params.error, Some("access_denied".to_string()));
        assert_eq!(params.error_description, Some("User denied access".to_string()));
    }

    #[test]
    fn test_parse_callback_params_relative_url() {
        let params = parse_callback_params("/callback?code=test&state=test");

        assert_eq!(params.code, Some("test".to_string()));
        assert_eq!(params.state, Some("test".to_string()));
    }

    #[test]
    fn test_build_end_session_url() {
        let url = build_end_session_url(EndSession {
            issuer: "https://auth.example.com".into(),
            id_token_hint: "test_token".into(),
            post_logout_redirect_uri: Some("https://app.example.com".into()),
            state: Some("logout_state".into()),
            end_session_endpoint: None,
        })
        .unwrap();

        let query: HashMap<_, _> = url.query_pairs().into_owned().collect();

        assert_eq!(query.get("id_token_hint"), Some(&"test_token".to_string()));
        assert_eq!(
            query.get("post_logout_redirect_uri"),
            Some(&"https://app.example.com".to_string())
        );
        assert_eq!(query.get("state"), Some(&"logout_state".to_string()));
    }
}