oxirs-fuseki 0.2.4

SPARQL 1.1/1.2 HTTP protocol server with Fuseki-compatible configuration
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! OAuth2/OIDC authentication handlers for OxiRS Fuseki
//!
//! This module provides HTTP endpoints for OAuth2 and OpenID Connect authentication flows.

use crate::{auth::AuthResult, error::FusekiError, server::AppState};
use axum::{
    extract::{Query, State},
    http::{header::SET_COOKIE, HeaderMap, StatusCode},
    response::{IntoResponse, Json, Response},
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tracing::{error, info, instrument, warn};

/// OAuth2 authorization request parameters
#[derive(Debug, Deserialize)]
pub struct OAuth2AuthParams {
    pub redirect_uri: Option<String>,
    pub scope: Option<String>,
    pub state: Option<String>,
    pub use_pkce: Option<bool>,
}

/// OAuth2 callback parameters
#[derive(Debug, Deserialize)]
pub struct OAuth2CallbackParams {
    pub code: Option<String>,
    pub state: Option<String>,
    pub error: Option<String>,
    pub error_description: Option<String>,
}

/// OAuth2 token refresh request
#[derive(Debug, Deserialize)]
pub struct OAuth2RefreshRequest {
    pub refresh_token: String,
}

/// OAuth2 authentication response
#[derive(Debug, Serialize)]
pub struct OAuth2AuthResponse {
    pub success: bool,
    pub authorization_url: Option<String>,
    pub state: Option<String>,
    pub message: String,
}

/// OAuth2 token response
#[derive(Debug, Serialize)]
pub struct OAuth2TokenResponse {
    pub success: bool,
    pub access_token: Option<String>,
    pub token_type: Option<String>,
    pub expires_in: Option<u64>,
    pub refresh_token: Option<String>,
    pub user: Option<crate::auth::User>,
    pub message: String,
}

/// OAuth2 user info response
#[derive(Debug, Serialize)]
pub struct OAuth2UserInfoResponse {
    pub success: bool,
    pub user_info: Option<crate::auth::oauth::OIDCUserInfo>,
    pub message: String,
}

/// Initiate OAuth2 authorization flow
#[instrument(skip(state))]
pub async fn initiate_oauth2_flow(
    State(state): State<Arc<AppState>>,
    Query(params): Query<OAuth2AuthParams>,
) -> Result<Json<OAuth2AuthResponse>, FusekiError> {
    let auth_service = state
        .auth_service
        .as_ref()
        .ok_or_else(|| FusekiError::service_unavailable("Authentication service not available"))?;

    // Check if OAuth2 is enabled
    if !auth_service.is_oauth2_enabled() {
        return Ok(Json(OAuth2AuthResponse {
            success: false,
            authorization_url: None,
            state: None,
            message: "OAuth2 authentication not configured".to_string(),
        }));
    }

    // Determine redirect URI
    let redirect_uri = params.redirect_uri.unwrap_or_else(|| {
        format!(
            "{}://{}:{}/auth/oauth2/callback",
            if state.config.server.tls.is_some() {
                "https"
            } else {
                "http"
            },
            state.config.server.host,
            state.config.server.port
        )
    });

    // Parse scopes
    let scopes = params
        .scope
        .map(|s| {
            s.split(' ')
                .map(|scope| scope.to_string())
                .collect::<Vec<_>>()
        })
        .unwrap_or_else(|| {
            vec![
                "openid".to_string(),
                "profile".to_string(),
                "email".to_string(),
            ]
        });

    let use_pkce = params.use_pkce.unwrap_or(true);

    // Generate OAuth2 authorization URL
    match auth_service
        .generate_oauth2_auth_url(&redirect_uri, &scopes, use_pkce)
        .await
    {
        Ok((authorization_url, state_param)) => {
            info!(
                "Generated OAuth2 authorization URL with state: {}",
                state_param
            );

            Ok(Json(OAuth2AuthResponse {
                success: true,
                authorization_url: Some(authorization_url),
                state: Some(state_param),
                message: "OAuth2 authorization URL generated successfully".to_string(),
            }))
        }
        Err(e) => {
            error!("Failed to generate OAuth2 authorization URL: {}", e);
            Err(e)
        }
    }
}

/// Handle OAuth2 authorization callback
#[instrument(skip(state))]
pub async fn handle_oauth2_callback(
    State(state): State<Arc<AppState>>,
    Query(params): Query<OAuth2CallbackParams>,
) -> Result<Response, FusekiError> {
    let auth_service = state
        .auth_service
        .as_ref()
        .ok_or_else(|| FusekiError::service_unavailable("Authentication service not available"))?;

    // Check for OAuth2 errors
    if let Some(error) = params.error {
        warn!(
            "OAuth2 authorization error: {} - {}",
            error,
            params.error_description.unwrap_or_default()
        );

        let error_response = OAuth2TokenResponse {
            success: false,
            access_token: None,
            token_type: None,
            expires_in: None,
            refresh_token: None,
            user: None,
            message: format!("OAuth2 authorization failed: {error}"),
        };

        return Ok((StatusCode::BAD_REQUEST, Json(error_response)).into_response());
    }

    let _code = params
        .code
        .ok_or_else(|| FusekiError::bad_request("Missing authorization code"))?;

    let _state_param = params
        .state
        .ok_or_else(|| FusekiError::bad_request("Missing state parameter"))?;

    // Determine redirect URI (should match the one used in authorization)
    let _redirect_uri = format!(
        "{}://{}:{}/auth/oauth2/callback",
        if state.config.server.tls.is_some() {
            "https"
        } else {
            "http"
        },
        state.config.server.host,
        state.config.server.port
    );

    // Complete OAuth2 authentication flow
    match auth_service
        .complete_oauth2_authentication(&_code, &_state_param, &_redirect_uri)
        .await
    {
        Ok(AuthResult::Authenticated(user)) => {
            info!(
                "OAuth2 authentication successful for user: {}",
                user.username
            );

            // Create session for the user
            let session_id = auth_service.create_session(user.clone()).await?;

            // Set session cookie
            let cookie_value = format!(
                "session_id={}; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
                session_id, state.config.security.session.timeout_secs
            );

            let response = OAuth2TokenResponse {
                success: true,
                access_token: Some(session_id),
                token_type: Some("Bearer".to_string()),
                expires_in: Some(state.config.security.session.timeout_secs),
                refresh_token: None,
                user: Some(user),
                message: "OAuth2 authentication successful".to_string(),
            };

            let mut resp = (StatusCode::OK, Json(response)).into_response();
            resp.headers_mut().insert(
                SET_COOKIE,
                cookie_value
                    .parse()
                    .expect("cookie value should be valid header"),
            );

            Ok(resp)
        }
        Ok(_) => {
            warn!("OAuth2 authentication failed");

            let response = OAuth2TokenResponse {
                success: false,
                access_token: None,
                token_type: None,
                expires_in: None,
                refresh_token: None,
                user: None,
                message: "OAuth2 authentication failed".to_string(),
            };

            Ok((StatusCode::UNAUTHORIZED, Json(response)).into_response())
        }
        Err(e) => {
            error!("OAuth2 callback processing failed: {}", e);
            Err(e)
        }
    }
}

/// Refresh OAuth2 access token
#[instrument(skip(state, _request))]
pub async fn refresh_oauth2_token(
    State(state): State<Arc<AppState>>,
    Json(_request): Json<OAuth2RefreshRequest>,
) -> Result<Json<OAuth2TokenResponse>, FusekiError> {
    let auth_service = state
        .auth_service
        .as_ref()
        .ok_or_else(|| FusekiError::service_unavailable("Authentication service not available"))?;

    // Check if OAuth2 is enabled
    if !auth_service.is_oauth2_enabled() {
        return Ok(Json(OAuth2TokenResponse {
            success: false,
            access_token: None,
            token_type: None,
            expires_in: None,
            refresh_token: None,
            user: None,
            message: "OAuth2 authentication not configured".to_string(),
        }));
    }

    // Refresh the access token
    match auth_service
        .refresh_oauth2_token(&_request.refresh_token)
        .await
    {
        Ok(token) => {
            info!("Successfully refreshed OAuth2 access token");
            Ok(Json(OAuth2TokenResponse {
                success: true,
                access_token: Some(token.access_token),
                token_type: Some(token.token_type),
                expires_in: Some(token.expires_in),
                refresh_token: token.refresh_token,
                user: None, // User info not included in token refresh
                message: "Token refreshed successfully".to_string(),
            }))
        }
        Err(e) => {
            warn!("Failed to refresh OAuth2 token: {}", e);
            Err(e)
        }
    }
}

/// Get OAuth2 user information
#[instrument(skip(state, _headers))]
pub async fn get_oauth2_user_info(
    State(state): State<Arc<AppState>>,
    _headers: HeaderMap,
) -> Result<Json<OAuth2UserInfoResponse>, FusekiError> {
    let auth_service = state
        .auth_service
        .as_ref()
        .ok_or_else(|| FusekiError::service_unavailable("Authentication service not available"))?;

    // Check if OAuth2 is enabled
    if !auth_service.is_oauth2_enabled() {
        return Ok(Json(OAuth2UserInfoResponse {
            success: false,
            user_info: None,
            message: "OAuth2 authentication not configured".to_string(),
        }));
    }

    // Extract access token from Authorization header
    let access_token = extract_bearer_token(&_headers)
        .ok_or_else(|| FusekiError::authentication("Missing or invalid authorization header"))?;

    // Get user info from OAuth2 provider
    match auth_service.get_oauth2_user_info(&access_token).await {
        Ok(user_info) => {
            info!(
                "Successfully retrieved OAuth2 user info for user: {}",
                user_info.sub
            );
            Ok(Json(OAuth2UserInfoResponse {
                success: true,
                user_info: Some(user_info),
                message: "User information retrieved successfully".to_string(),
            }))
        }
        Err(e) => {
            warn!("Failed to retrieve OAuth2 user info: {}", e);
            Ok(Json(OAuth2UserInfoResponse {
                success: false,
                user_info: None,
                message: format!("Failed to retrieve user information: {e}"),
            }))
        }
    }
}

/// Validate OAuth2 access token
#[instrument(skip(state, _headers))]
pub async fn validate_oauth2_token(
    State(state): State<Arc<AppState>>,
    _headers: HeaderMap,
) -> Result<Json<serde_json::Value>, FusekiError> {
    let auth_service = state
        .auth_service
        .as_ref()
        .ok_or_else(|| FusekiError::service_unavailable("Authentication service not available"))?;

    // Check if OAuth2 is enabled
    if !auth_service.is_oauth2_enabled() {
        return Err(FusekiError::service_unavailable(
            "OAuth2 authentication not configured",
        ));
    }

    // Extract access token from Authorization header
    let access_token = extract_bearer_token(&_headers)
        .ok_or_else(|| FusekiError::authentication("Missing or invalid authorization header"))?;

    // Validate the access token
    match auth_service.validate_access_token(&access_token).await {
        Ok(valid) => {
            if valid {
                Ok(Json(serde_json::json!({
                    "valid": true,
                    "message": "Token is valid"
                })))
            } else {
                Ok(Json(serde_json::json!({
                    "valid": false,
                    "message": "Token is invalid or expired"
                })))
            }
        }
        Err(e) => {
            warn!("OAuth2 token validation failed: {}", e);
            Err(e)
        }
    }
}

/// Get OAuth2 configuration and capabilities
#[instrument(skip(state))]
pub async fn get_oauth2_config(
    State(state): State<Arc<AppState>>,
) -> Result<Json<serde_json::Value>, FusekiError> {
    let auth_service = state
        .auth_service
        .as_ref()
        .ok_or_else(|| FusekiError::service_unavailable("Authentication service not available"))?;

    // Check if OAuth2 is enabled
    if !auth_service.is_oauth2_enabled() {
        return Ok(Json(serde_json::json!({
            "enabled": false,
            "message": "OAuth2 authentication not configured"
        })));
    }

    // Get OAuth2 configuration from the server config (without sensitive data)
    let oauth_config = &state.config.security.oauth;

    if let Some(oauth_config) = oauth_config {
        let config_info = serde_json::json!({
            "enabled": true,
            "provider": oauth_config.provider,
            "authorization_endpoint": oauth_config.auth_url,
            "supported_scopes": oauth_config.scopes,
            "client_id": oauth_config.client_id,
            "token_endpoint": oauth_config.token_url,
            "user_info_endpoint": oauth_config.user_info_url,
            // Don't expose client_secret for security reasons
        });

        Ok(Json(config_info))
    } else {
        Ok(Json(serde_json::json!({
            "enabled": false,
            "message": "OAuth2 not configured"
        })))
    }
}

/// OAuth2 discovery endpoint (OpenID Connect Discovery)
#[instrument(skip(state))]
pub async fn oauth2_discovery(
    State(state): State<Arc<AppState>>,
) -> Result<Json<serde_json::Value>, FusekiError> {
    let auth_service = state
        .auth_service
        .as_ref()
        .ok_or_else(|| FusekiError::service_unavailable("Authentication service not available"))?;

    // Get OAuth configuration from the auth service
    let oauth_config = auth_service
        .get_oauth_config()
        .ok_or_else(|| FusekiError::service_unavailable("OAuth2 authentication not configured"))?;

    // Construct the server base URL from the request
    let base_url = format!(
        "http://{}:{}",
        state.config.server.host, state.config.server.port
    );

    // Build OIDC discovery document according to RFC 8414
    let discovery_doc = serde_json::json!({
        "issuer": base_url,
        "authorization_endpoint": oauth_config.auth_url,
        "token_endpoint": oauth_config.token_url,
        "userinfo_endpoint": oauth_config.user_info_url,
        "jwks_uri": format!("{}/auth/oauth2/jwks", base_url),
        "scopes_supported": oauth_config.scopes,
        "response_types_supported": ["code", "token", "id_token", "code id_token", "code token", "id_token token", "code id_token token"],
        "grant_types_supported": ["authorization_code", "refresh_token"],
        "subject_types_supported": ["public"],
        "id_token_signing_alg_values_supported": ["RS256"],
        "code_challenge_methods_supported": ["S256"],
        "claims_supported": ["sub", "iss", "aud", "exp", "iat", "auth_time", "nonce", "email", "email_verified", "name", "given_name", "family_name"],
        "token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"],
        "revocation_endpoint": format!("{}/auth/oauth2/revoke", base_url),
        "introspection_endpoint": format!("{}/auth/oauth2/introspect", base_url),
        "end_session_endpoint": format!("{}/auth/oauth2/logout", base_url)
    });

    Ok(Json(discovery_doc))
}

/// Extract Bearer token from Authorization header
fn extract_bearer_token(headers: &HeaderMap) -> Option<String> {
    let auth_header = headers.get("authorization")?;
    let auth_str = auth_header.to_str().ok()?;

    auth_str
        .strip_prefix("Bearer ")
        .map(|stripped| stripped.to_string())
}

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

    #[test]
    fn test_bearer_token_extraction() {
        let mut headers = HeaderMap::new();
        headers.insert(
            "authorization",
            HeaderValue::from_static("Bearer test_token_123"),
        );

        let token = extract_bearer_token(&headers);
        assert_eq!(token, Some("test_token_123".to_string()));

        // Test invalid format
        headers.insert("authorization", HeaderValue::from_static("Basic dGVzdA=="));
        let token = extract_bearer_token(&headers);
        assert_eq!(token, None);

        // Test missing header
        headers.remove("authorization");
        let token = extract_bearer_token(&headers);
        assert_eq!(token, None);
    }

    #[test]
    fn test_oauth2_response_serialization() {
        let response = OAuth2AuthResponse {
            success: true,
            authorization_url: Some("https://provider.example.com/auth".to_string()),
            state: Some("state123".to_string()),
            message: "Success".to_string(),
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("authorization_url"));
        assert!(json.contains("state123"));
    }
}