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
470
471
472
473
474
475
476
477
478
479
480
//! Dynamic Client Registration (DCR) implementation (server-only)

#[cfg(not(target_arch = "wasm32"))]
use crate::{
    discovery::discover,
    errors::{Error, Result},
    http::HttpClient,
    types::{ClientRegistrationResult, ClientStatus, RegisterRequest},
};

/// Register a new client with the authorization server
///
/// This implements OAuth 2.0 Dynamic Client Registration (RFC 7591)
/// with support for the authorization server's approval workflow.
///
/// Note: This function always attempts to register a new client.
/// It does not check if a client already exists.
///
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use xjp_oidc::{register_client, RegisterRequest, http::ReqwestHttpClient};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let http = ReqwestHttpClient::default();
///
/// let result = register_client(
///     "https://auth.example.com",
///     "initial_access_token",
///     RegisterRequest {
///         application_type: Some("web".into()),
///         redirect_uris: vec!["https://app.example.com/callback".into()],
///         post_logout_redirect_uris: Some(vec!["https://app.example.com".into()]),
///         grant_types: vec!["authorization_code".into()],
///         token_endpoint_auth_method: "client_secret_basic".into(),
///         scope: "openid profile email".into(),
///         contacts: Some(vec!["admin@example.com".into()]),
///         software_id: Some("my-app".into()),
///         client_name: Some("My Application".into()),
///     },
///     &http
/// ).await?;
///
/// match result.status {
///     xjp_oidc::types::ClientStatus::Active => {
///         println!("Client registered and active!");
///     }
///     xjp_oidc::types::ClientStatus::Pending => {
///         println!("Client registered but pending approval");
///     }
///     _ => {}
/// }
/// # Ok(())
/// # }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn register_client(
    issuer: &str,
    initial_access_token: &str,
    req: RegisterRequest,
    http: &dyn HttpClient,
) -> Result<ClientRegistrationResult> {
    // Validate parameters
    validate_register_params(&req)?;

    if issuer.is_empty() {
        return Err(Error::InvalidParam("issuer cannot be empty"));
    }
    if initial_access_token.is_empty() {
        return Err(Error::InvalidParam("initial_access_token cannot be empty"));
    }

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

    let registration_endpoint = metadata
        .registration_endpoint
        .ok_or_else(|| Error::Discovery("Registration endpoint not found in metadata".into()))?;

    // Prepare request body
    let request_body = prepare_registration_request(req);

    // Make registration request
    let bearer_token = format!("Bearer {}", initial_access_token);
    let auth_header = Some(("Authorization", bearer_token.as_str()));

    let response = http
        .post_json_value(&registration_endpoint, &request_body, auth_header)
        .await
        .map_err(|e| {
        // Try to parse DCR-specific errors
        if let crate::http::HttpClientError::InvalidStatus { status: _, message } = &e {
            if let Ok(dcr_error) = serde_json::from_str::<DcrError>(&message) {
                return map_dcr_error(dcr_error);
            }
        }
        Error::Network(format!("Client registration failed: {}", e))
    })?;

    // Parse response
    parse_registration_response(response)
}

/// Validate registration parameters
#[cfg(not(target_arch = "wasm32"))]
fn validate_register_params(req: &RegisterRequest) -> Result<()> {
    if req.redirect_uris.is_empty() {
        return Err(Error::InvalidParam("redirect_uris cannot be empty"));
    }

    for uri in &req.redirect_uris {
        if uri.is_empty() {
            return Err(Error::InvalidParam("redirect_uri cannot be empty"));
        }
        // Validate URL format
        url::Url::parse(uri).map_err(|_| Error::InvalidParam("invalid redirect_uri format"))?;
    }

    if let Some(logout_uris) = &req.post_logout_redirect_uris {
        for uri in logout_uris {
            if !uri.is_empty() {
                url::Url::parse(uri)
                    .map_err(|_| Error::InvalidParam("invalid post_logout_redirect_uri format"))?;
            }
        }
    }

    if req.grant_types.is_empty() {
        return Err(Error::InvalidParam("grant_types cannot be empty"));
    }

    if req.token_endpoint_auth_method.is_empty() {
        return Err(Error::InvalidParam("token_endpoint_auth_method cannot be empty"));
    }

    Ok(())
}

/// Prepare registration request body
#[cfg(not(target_arch = "wasm32"))]
fn prepare_registration_request(req: RegisterRequest) -> serde_json::Value {
    let mut body = serde_json::json!({
        "redirect_uris": req.redirect_uris,
        "grant_types": req.grant_types,
        "token_endpoint_auth_method": req.token_endpoint_auth_method,
        "scope": req.scope,
        "response_types": ["code"], // Default to authorization code flow
    });

    let obj = body.as_object_mut().unwrap();

    if let Some(app_type) = req.application_type {
        obj.insert("application_type".to_string(), serde_json::json!(app_type));
    }

    if let Some(logout_uris) = req.post_logout_redirect_uris {
        obj.insert("post_logout_redirect_uris".to_string(), serde_json::json!(logout_uris));
    }

    if let Some(contacts) = req.contacts {
        obj.insert("contacts".to_string(), serde_json::json!(contacts));
    }

    if let Some(software_id) = req.software_id {
        obj.insert("software_id".to_string(), serde_json::json!(software_id));
    }

    if let Some(client_name) = req.client_name {
        obj.insert("client_name".to_string(), serde_json::json!(client_name));
    }

    body
}

/// Parse registration response
#[cfg(not(target_arch = "wasm32"))]
fn parse_registration_response(response: serde_json::Value) -> Result<ClientRegistrationResult> {
    // Extract required fields
    let client_id = response["client_id"]
        .as_str()
        .ok_or_else(|| Error::InvalidState("Missing client_id in response".into()))?
        .to_string();

    let client_secret = response["client_secret"].as_str().map(|s| s.to_string());

    // Determine status from response
    let status = if let Some(status_str) = response["status"].as_str() {
        match status_str {
            "active" => ClientStatus::Active,
            "pending" => ClientStatus::Pending,
            "suspended" => ClientStatus::Suspended,
            _ => ClientStatus::Pending, // Default to pending for unknown status
        }
    } else {
        // If no explicit status, assume active if client_secret is provided
        if client_secret.is_some() {
            ClientStatus::Active
        } else {
            ClientStatus::Pending
        }
    };

    let client_name = response["client_name"].as_str().unwrap_or(&client_id).to_string();

    let redirect_uris = response["redirect_uris"]
        .as_array()
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect())
        .unwrap_or_default();

    let post_logout_redirect_uris = response["post_logout_redirect_uris"]
        .as_array()
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect());

    let grant_types = response["grant_types"]
        .as_array()
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect())
        .unwrap_or_else(|| vec!["authorization_code".to_string()]);

    let token_endpoint_auth_method = response["token_endpoint_auth_method"]
        .as_str()
        .unwrap_or("client_secret_basic")
        .to_string();

    let scope = response["scope"].as_str().unwrap_or("openid profile email").to_string();

    Ok(ClientRegistrationResult {
        client_id,
        client_secret,
        status,
        client_name,
        redirect_uris,
        post_logout_redirect_uris,
        grant_types,
        token_endpoint_auth_method,
        scope,
    })
}

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

/// Map DCR errors to SDK errors
#[cfg(not(target_arch = "wasm32"))]
fn map_dcr_error(err: DcrError) -> Error {
    match err.error.as_str() {
        "invalid_client_metadata" => Error::InvalidParam("Invalid client metadata"),
        "unauthorized_client" => Error::oauth("unauthorized_client", err.error_description),
        "invalid_redirect_uri" => Error::InvalidParam("Invalid redirect URI"),
        "access_denied" => Error::oauth("access_denied", err.error_description),
        _ => Error::oauth(err.error, err.error_description),
    }
}

/// Get client configuration from the authorization server
///
/// This retrieves the configuration of a previously registered client
/// using the client ID and registration access token.
///
/// # Example
/// ```no_run
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use xjp_oidc::{get_client_config, http::ReqwestHttpClient};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let http = ReqwestHttpClient::default();
///
/// let config = get_client_config(
///     "https://auth.example.com",
///     "my-client-id",
///     "registration_access_token",
///     &http
/// ).await?;
///
/// println!("Client name: {}", config.client_name);
/// println!("Redirect URIs: {:?}", config.redirect_uris);
/// # Ok(())
/// # }
/// ```
#[cfg(not(target_arch = "wasm32"))]
pub async fn get_client_config(
    issuer: &str,
    client_id: &str,
    registration_access_token: &str,
    http: &dyn HttpClient,
) -> Result<crate::types::ClientConfig> {
    // Validate parameters
    if issuer.is_empty() {
        return Err(Error::InvalidParam("issuer cannot be empty"));
    }
    if client_id.is_empty() {
        return Err(Error::InvalidParam("client_id cannot be empty"));
    }
    if registration_access_token.is_empty() {
        return Err(Error::InvalidParam("registration_access_token cannot be empty"));
    }

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

    let registration_endpoint = metadata
        .registration_endpoint
        .ok_or_else(|| Error::Discovery("Registration endpoint not found in metadata".into()))?;

    // Build the client-specific URL
    let client_url = format!("{}/{}", registration_endpoint, client_id);

    // Prepare authorization header
    let bearer_token = format!("Bearer {}", registration_access_token);
    
    // Note: The HttpClient trait doesn't support GET with auth header
    // This is a known limitation that should be addressed in future versions
    // For now, we'll make a POST request with empty body as a workaround
    let empty_body = serde_json::json!({});
    let auth_header = Some(("Authorization", bearer_token.as_str()));

    let response = http
        .post_json_value(&client_url, &empty_body, auth_header)
        .await
        .map_err(|e| {
            // Handle specific error cases
            if let crate::http::HttpClientError::InvalidStatus { status, message } = &e {
                match *status {
                    401 => return Error::oauth("invalid_token", Some("Registration access token is invalid".to_string())),
                    404 => return Error::oauth("invalid_client", Some("Client not found".to_string())),
                    405 => {
                        // Method Not Allowed - the server might only support GET
                        return Error::Network(
                            "DCR endpoint does not support POST method for client retrieval. \
                             This is a known limitation - HttpClient trait needs to be extended \
                             to support GET requests with authorization headers.".to_string()
                        );
                    }
                    _ => {
                        if let Ok(dcr_error) = serde_json::from_str::<DcrError>(&message) {
                            return map_dcr_error(dcr_error);
                        }
                    }
                }
            }
            Error::Network(format!("Client configuration retrieval failed: {}", e))
        })?;

    // Parse response to ClientConfig
    parse_client_config_response(response)
}

/// Parse client configuration response
#[cfg(not(target_arch = "wasm32"))]
fn parse_client_config_response(response: serde_json::Value) -> Result<crate::types::ClientConfig> {
    // Extract required fields
    let client_id = response["client_id"]
        .as_str()
        .ok_or_else(|| Error::InvalidState("Missing client_id in response".into()))?
        .to_string();

    let client_secret = response["client_secret"].as_str().map(|s| s.to_string());
    
    let client_name = response["client_name"]
        .as_str()
        .unwrap_or(&client_id)
        .to_string();

    let redirect_uris = response["redirect_uris"]
        .as_array()
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect())
        .unwrap_or_default();

    let post_logout_redirect_uris = response["post_logout_redirect_uris"]
        .as_array()
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect());

    let grant_types = response["grant_types"]
        .as_array()
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect())
        .unwrap_or_else(|| vec!["authorization_code".to_string()]);

    let response_types = response["response_types"]
        .as_array()
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).map(|s| s.to_string()).collect())
        .unwrap_or_else(|| vec!["code".to_string()]);

    let token_endpoint_auth_method = response["token_endpoint_auth_method"]
        .as_str()
        .unwrap_or("client_secret_basic")
        .to_string();

    let scope = response["scope"]
        .as_str()
        .unwrap_or("openid profile email")
        .to_string();

    let client_secret_expires_at = response["client_secret_expires_at"].as_i64();

    Ok(crate::types::ClientConfig {
        client_id,
        client_secret,
        client_name,
        redirect_uris,
        post_logout_redirect_uris,
        grant_types,
        response_types,
        token_endpoint_auth_method,
        scope,
        client_secret_expires_at,
    })
}

// WASM stubs
#[cfg(target_arch = "wasm32")]
pub async fn register_if_needed(
    _issuer: &str,
    _initial_access_token: &str,
    _req: crate::types::RegisterRequest,
    _http: &dyn crate::http::HttpClient,
) -> crate::errors::Result<crate::types::ClientRegistrationResult> {
    Err(crate::errors::Error::ServerOnly)
}

#[cfg(target_arch = "wasm32")]
pub async fn get_client_config(
    _issuer: &str,
    _client_id: &str,
    _registration_access_token: &str,
    _http: &dyn crate::http::HttpClient,
) -> crate::errors::Result<crate::types::ClientConfig> {
    Err(crate::errors::Error::ServerOnly)
}

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

    #[test]
    fn test_validate_register_params() {
        let valid = RegisterRequest {
            application_type: Some("web".into()),
            redirect_uris: vec!["https://app.example.com/callback".into()],
            post_logout_redirect_uris: None,
            grant_types: vec!["authorization_code".into()],
            token_endpoint_auth_method: "client_secret_basic".into(),
            scope: "openid profile".into(),
            contacts: None,
            software_id: None,
            client_name: None,
        };
        assert!(validate_register_params(&valid).is_ok());

        let invalid = RegisterRequest { redirect_uris: vec![], ..valid.clone() };
        assert!(validate_register_params(&invalid).is_err());
    }

    #[test]
    fn test_prepare_registration_request() {
        let req = RegisterRequest {
            application_type: Some("web".into()),
            redirect_uris: vec!["https://app.example.com/callback".into()],
            post_logout_redirect_uris: Some(vec!["https://app.example.com".into()]),
            grant_types: vec!["authorization_code".into()],
            token_endpoint_auth_method: "client_secret_basic".into(),
            scope: "openid profile email".into(),
            contacts: Some(vec!["admin@example.com".into()]),
            software_id: Some("my-app".into()),
            client_name: Some("My Application".into()),
        };

        let body = prepare_registration_request(req);

        assert_eq!(body["application_type"], "web");
        assert_eq!(body["redirect_uris"][0], "https://app.example.com/callback");
        assert_eq!(body["grant_types"][0], "authorization_code");
        assert_eq!(body["client_name"], "My Application");
    }
}