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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
//! SAML 2.0 authentication support

#[cfg(feature = "saml")]
use async_trait::async_trait;
#[cfg(feature = "saml")]
use base64::{engine::general_purpose, Engine as _};
#[cfg(feature = "saml")]
use chrono::{DateTime, Utc};
#[cfg(feature = "saml")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "saml")]
use std::{
    collections::HashMap,
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};
#[cfg(feature = "saml")]
use tokio::sync::RwLock;
#[cfg(feature = "saml")]
use url::Url;
#[cfg(feature = "saml")]
use uuid::Uuid;
// TODO: Uncomment when xmlsec crate is added and XML parsing is implemented
// #[cfg(feature = "saml")]
// use xmlsec::{XmlSecKey, XmlSecKeyFormat, XmlSecSignatureContext};

use crate::{
    auth::{AuthResult, User},
    error::{FusekiError, FusekiResult},
};

/// SAML 2.0 configuration
#[derive(Debug, Clone)]
pub struct SamlConfig {
    /// Service Provider (SP) configuration
    pub sp: ServiceProviderConfig,
    /// Identity Provider (IdP) configuration
    pub idp: IdentityProviderConfig,
    /// Attribute mapping configuration
    pub attribute_mapping: AttributeMapping,
    /// Session configuration
    pub session: SessionConfig,
}

/// Type alias for handler compatibility
pub type SamlSpConfig = ServiceProviderConfig;

/// Type alias for handler compatibility  
pub type SamlAttributeMappings = AttributeMapping;

/// Service Provider configuration
#[derive(Debug, Clone)]
pub struct ServiceProviderConfig {
    /// SP Entity ID
    pub entity_id: String,
    /// Assertion Consumer Service URL
    pub acs_url: Url,
    /// Single Logout Service URL
    pub sls_url: Option<Url>,
    /// SP Certificate for signing
    pub certificate: Option<String>,
    /// SP Private key for signing
    pub private_key: Option<String>,
}

/// Identity Provider configuration
#[derive(Debug, Clone)]
pub struct IdentityProviderConfig {
    /// IdP Entity ID
    pub entity_id: String,
    /// Single Sign-On Service URL
    pub sso_url: Url,
    /// Single Logout Service URL
    pub slo_url: Option<Url>,
    /// IdP Certificate for signature verification
    pub certificate: String,
    /// Metadata URL (optional)
    pub metadata_url: Option<Url>,
}

/// Attribute mapping from SAML assertions to user properties
#[derive(Debug, Clone)]
pub struct AttributeMapping {
    /// Username attribute name
    pub username: String,
    /// Email attribute name
    pub email: Option<String>,
    /// Display name attribute name
    pub display_name: Option<String>,
    /// Groups/roles attribute name
    pub groups: Option<String>,
    /// Additional custom attributes
    pub custom: HashMap<String, String>,
}

impl Default for AttributeMapping {
    fn default() -> Self {
        Self {
            username: "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name".to_string(),
            email: Some(
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress".to_string(),
            ),
            display_name: Some(
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname".to_string(),
            ),
            groups: Some("http://schemas.xmlsoap.org/claims/Group".to_string()),
            custom: HashMap::new(),
        }
    }
}

/// SAML session configuration
#[derive(Debug, Clone)]
pub struct SessionConfig {
    /// Session timeout duration
    pub timeout: Duration,
    /// Allow IdP-initiated SSO
    pub allow_idp_initiated: bool,
    /// Force authentication
    pub force_authn: bool,
    /// Session index tracking
    pub track_session_index: bool,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(3600), // 1 hour
            allow_idp_initiated: false,
            force_authn: false,
            track_session_index: true,
        }
    }
}

/// SAML 2.0 authentication provider
pub struct SamlProvider {
    pub config: SamlConfig,
    sessions: Arc<RwLock<HashMap<String, SamlSession>>>,
    pending_requests: Arc<RwLock<HashMap<String, PendingRequest>>>,
}

/// Active SAML session
#[derive(Debug, Clone)]
struct SamlSession {
    /// User information
    user: User,
    /// Session index from IdP
    session_index: Option<String>,
    /// Session creation time
    created_at: SystemTime,
    /// Session expiry time
    expires_at: SystemTime,
    /// SAML attributes
    attributes: HashMap<String, Vec<String>>,
}

/// Pending authentication request
#[derive(Debug, Clone)]
struct PendingRequest {
    /// Request ID
    id: String,
    /// Relay state
    relay_state: Option<String>,
    /// Request timestamp
    timestamp: SystemTime,
}

/// SAML AuthN request
#[derive(Debug, Serialize)]
pub struct AuthnRequest {
    /// Request ID
    pub id: String,
    /// Issue instant
    pub issue_instant: DateTime<Utc>,
    /// Destination URL
    pub destination: Url,
    /// Issuer (SP entity ID)
    pub issuer: String,
    /// Assertion Consumer Service URL
    pub acs_url: Url,
    /// Protocol binding
    pub protocol_binding: String,
    /// Force authentication
    pub force_authn: bool,
}

impl AuthnRequest {
    /// Create a new authentication request
    pub fn new(config: &SamlConfig) -> Self {
        Self {
            id: format!("_{}", Uuid::new_v4()),
            issue_instant: Utc::now(),
            destination: config.idp.sso_url.clone(),
            issuer: config.sp.entity_id.clone(),
            acs_url: config.sp.acs_url.clone(),
            protocol_binding: "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST".to_string(),
            force_authn: config.session.force_authn,
        }
    }

    /// Generate XML for the request
    pub fn to_xml(&self) -> String {
        format!(
            r#"<samlp:AuthnRequest 
                xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
                xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
                ID="{}"
                Version="2.0"
                IssueInstant="{}"
                Destination="{}"
                ProtocolBinding="{}"
                AssertionConsumerServiceURL="{}"
                ForceAuthn="{}">
                <saml:Issuer>{}</saml:Issuer>
            </samlp:AuthnRequest>"#,
            self.id,
            self.issue_instant.to_rfc3339(),
            self.destination,
            self.protocol_binding,
            self.acs_url,
            self.force_authn,
            self.issuer
        )
    }
}

/// SAML Response
#[derive(Debug, Deserialize)]
pub struct SamlResponse {
    /// Response status
    pub status: ResponseStatus,
    /// Assertions
    pub assertions: Vec<Assertion>,
    /// In response to request ID
    pub in_response_to: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct ResponseStatus {
    /// Status code
    pub code: String,
    /// Status message
    pub message: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Assertion {
    /// Subject information
    pub subject: Subject,
    /// Attributes
    pub attributes: Vec<Attribute>,
    /// Conditions
    pub conditions: Option<Conditions>,
    /// Authentication statement
    pub authn_statement: Option<AuthnStatement>,
}

#[derive(Debug, Deserialize)]
pub struct Subject {
    /// Name ID
    pub name_id: String,
    /// Name ID format
    pub format: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Attribute {
    /// Attribute name
    pub name: String,
    /// Attribute values
    pub values: Vec<String>,
}

#[derive(Debug, Deserialize)]
pub struct Conditions {
    /// Not before time
    pub not_before: Option<DateTime<Utc>>,
    /// Not on or after time
    pub not_on_or_after: Option<DateTime<Utc>>,
}

#[derive(Debug, Deserialize)]
pub struct AuthnStatement {
    /// Session index
    pub session_index: Option<String>,
    /// Authentication instant
    pub authn_instant: DateTime<Utc>,
}

impl SamlProvider {
    /// Create a new SAML provider
    pub fn new(config: SamlConfig) -> Self {
        Self {
            config,
            sessions: Arc::new(RwLock::new(HashMap::new())),
            pending_requests: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Generate login URL
    pub async fn generate_login_url(&self, relay_state: Option<String>) -> FusekiResult<Url> {
        let request = AuthnRequest::new(&self.config);
        let request_xml = request.to_xml();

        // Store pending request
        let pending = PendingRequest {
            id: request.id.clone(),
            relay_state,
            timestamp: SystemTime::now(),
        };

        let relay_state_clone = pending.relay_state.clone();
        let mut pending_requests = self.pending_requests.write().await;
        pending_requests.insert(request.id.clone(), pending);

        // Encode request
        let encoded = general_purpose::STANDARD.encode(request_xml.as_bytes());

        // Build redirect URL
        let mut url = self.config.idp.sso_url.clone();
        url.query_pairs_mut().append_pair("SAMLRequest", &encoded);

        if let Some(relay) = &relay_state_clone {
            url.query_pairs_mut().append_pair("RelayState", relay);
        }

        Ok(url)
    }

    /// Process SAML response
    pub async fn process_response(
        &self,
        saml_response: &str,
        relay_state: Option<&str>,
    ) -> FusekiResult<User> {
        // Decode response
        let decoded = general_purpose::STANDARD
            .decode(saml_response)
            .map_err(|e| {
                FusekiError::authentication(format!("Failed to decode SAML response: {}", e))
            })?;

        let response_xml = String::from_utf8(decoded).map_err(|e| {
            FusekiError::authentication(format!("Invalid UTF-8 in SAML response: {}", e))
        })?;

        // Parse and validate response
        let response = self.parse_response(&response_xml)?;
        self.validate_response(&response)?;

        // Extract user information
        let user = self.extract_user_info(&response)?;

        // Create session
        let session = SamlSession {
            user: user.clone(),
            session_index: response
                .assertions
                .first()
                .and_then(|a| a.authn_statement.as_ref())
                .and_then(|s| s.session_index.clone()),
            created_at: SystemTime::now(),
            expires_at: SystemTime::now() + self.config.session.timeout,
            attributes: self.extract_attributes(&response),
        };

        // Store session
        let session_id = Uuid::new_v4().to_string();
        let mut sessions = self.sessions.write().await;
        sessions.insert(session_id, session);

        // Clean up pending request
        if let Some(in_response_to) = &response.in_response_to {
            let mut pending = self.pending_requests.write().await;
            pending.remove(in_response_to);
        }

        Ok(user)
    }

    /// Parse SAML response XML
    fn parse_response(&self, _xml: &str) -> FusekiResult<SamlResponse> {
        // TODO: Implement proper XML parsing with xmlsec
        // For now, return a dummy response
        Err(FusekiError::service_unavailable(
            "SAML response parsing not yet implemented",
        ))
    }

    /// Validate SAML response
    fn validate_response(&self, response: &SamlResponse) -> FusekiResult<()> {
        // Check status
        if response.status.code != "urn:oasis:names:tc:SAML:2.0:status:Success" {
            return Err(FusekiError::authentication(format!(
                "SAML authentication failed: {}",
                response
                    .status
                    .message
                    .as_ref()
                    .unwrap_or(&"Unknown error".to_string())
            )));
        }

        // Validate assertions
        if response.assertions.is_empty() {
            return Err(FusekiError::authentication(
                "No assertions in SAML response",
            ));
        }

        // Check conditions
        for assertion in &response.assertions {
            if let Some(conditions) = &assertion.conditions {
                let now = Utc::now();

                if let Some(not_before) = &conditions.not_before {
                    if now < *not_before {
                        return Err(FusekiError::authentication("SAML assertion not yet valid"));
                    }
                }

                if let Some(not_after) = &conditions.not_on_or_after {
                    if now >= *not_after {
                        return Err(FusekiError::authentication("SAML assertion expired"));
                    }
                }
            }
        }

        // TODO: Verify signature

        Ok(())
    }

    /// Extract user information from SAML response
    fn extract_user_info(&self, response: &SamlResponse) -> FusekiResult<User> {
        let assertion = response
            .assertions
            .first()
            .ok_or_else(|| FusekiError::authentication("No assertion found"))?;

        let mut user = User {
            username: assertion.subject.name_id.clone(),
            email: None,
            full_name: None,
            roles: vec!["user".to_string()],
            last_login: Some(chrono::Utc::now()),
            permissions: vec![],
        };

        // Map attributes
        for attr in &assertion.attributes {
            if attr.name == self.config.attribute_mapping.username && !attr.values.is_empty() {
                user.username = attr.values[0].clone();
            }

            if let Some(email_attr) = &self.config.attribute_mapping.email {
                if attr.name == *email_attr && !attr.values.is_empty() {
                    user.email = Some(attr.values[0].clone());
                }
            }

            if let Some(display_attr) = &self.config.attribute_mapping.display_name {
                if attr.name == *display_attr && !attr.values.is_empty() {
                    user.full_name = Some(attr.values[0].clone());
                }
            }

            if let Some(groups_attr) = &self.config.attribute_mapping.groups {
                if attr.name == *groups_attr {
                    // Map groups to roles
                    for group in &attr.values {
                        match group.as_str() {
                            "admin" | "administrators" => user.roles.push("admin".to_string()),
                            "editor" | "editors" => user.roles.push("editor".to_string()),
                            _ => {}
                        }
                    }
                }
            }

            // Note: User struct doesn't have attributes field, so we skip storing them
        }

        Ok(user)
    }

    /// Extract all attributes from response
    fn extract_attributes(&self, response: &SamlResponse) -> HashMap<String, Vec<String>> {
        let mut attributes = HashMap::new();

        for assertion in &response.assertions {
            for attr in &assertion.attributes {
                attributes.insert(attr.name.clone(), attr.values.clone());
            }
        }

        attributes
    }

    /// Generate logout URL
    pub async fn generate_logout_url(&self, user: &User) -> FusekiResult<Option<Url>> {
        if let Some(slo_url) = &self.config.idp.slo_url {
            // TODO: Generate proper logout request
            Ok(Some(slo_url.clone()))
        } else {
            Ok(None)
        }
    }

    /// Clean up expired sessions
    pub async fn cleanup_sessions(&self) {
        let mut sessions = self.sessions.write().await;
        let now = SystemTime::now();

        sessions.retain(|_, session| session.expires_at > now);

        // Also clean up old pending requests
        let mut pending = self.pending_requests.write().await;
        let timeout = Duration::from_secs(300); // 5 minutes

        pending.retain(|_, request| {
            now.duration_since(request.timestamp)
                .unwrap_or(Duration::MAX)
                < timeout
        });
    }

    /// Get session ID by SAML session index
    pub async fn get_session_by_index(&self, session_index: &str) -> FusekiResult<Option<String>> {
        let sessions = self.sessions.read().await;

        for (session_id, session) in sessions.iter() {
            if let Some(index) = &session.session_index {
                if index == session_index {
                    return Ok(Some(session_id.clone()));
                }
            }
        }

        Ok(None)
    }

    /// Generate SAML logout request
    pub async fn generate_logout_request(
        &self,
        session_index: &str,
        name_id: &str,
    ) -> FusekiResult<String> {
        let slo_url = self
            .config
            .idp
            .slo_url
            .as_ref()
            .ok_or_else(|| FusekiError::configuration("SAML SLO not configured"))?;

        // Generate logout request XML
        let request_id = format!("_{}", Uuid::new_v4());
        let logout_request = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<samlp:LogoutRequest
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="{}"
    Version="2.0"
    IssueInstant="{}"
    Destination="{}">
    <saml:Issuer>{}</saml:Issuer>
    <saml:NameID>{}</saml:NameID>
    <samlp:SessionIndex>{}</samlp:SessionIndex>
</samlp:LogoutRequest>"#,
            request_id,
            chrono::Utc::now().to_rfc3339(),
            slo_url,
            self.config.sp.entity_id,
            name_id,
            session_index
        );

        // Encode the request
        let encoded = general_purpose::STANDARD.encode(logout_request.as_bytes());

        // Build the logout URL
        let mut logout_url = slo_url.clone();
        logout_url
            .query_pairs_mut()
            .append_pair("SAMLRequest", &encoded);

        Ok(logout_url.to_string())
    }

    /// Get SAML metadata XML
    pub fn get_metadata(&self) -> String {
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
                     entityID="{}">
  <md:SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="true"
                      protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
    <md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat>
    <md:AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
                                 Location="{}" index="1" isDefault="true"/>
    {}
  </md:SPSSODescriptor>
</md:EntityDescriptor>"#,
            self.config.sp.entity_id,
            self.config.sp.acs_url,
            self.config.sp.sls_url.as_ref()
                .map(|url| format!(r#"<md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="{}"/>"#, url))
                .unwrap_or_default()
        )
    }
}

impl SamlProvider {
    /// Authenticate user with username/password (not applicable for SAML)
    pub async fn authenticate(&self, _username: &str, _password: &str) -> FusekiResult<AuthResult> {
        // SAML doesn't use username/password authentication
        Ok(AuthResult::Invalid)
    }

    /// Validate SAML session token
    pub async fn validate_token(&self, token: &str) -> FusekiResult<AuthResult> {
        let sessions = self.sessions.read().await;

        if let Some(session) = sessions.get(token) {
            if session.expires_at > SystemTime::now() {
                Ok(AuthResult::Authenticated(session.user.clone()))
            } else {
                Ok(AuthResult::Expired)
            }
        } else {
            Ok(AuthResult::Invalid)
        }
    }

    /// Refresh token (not applicable for SAML)
    pub async fn refresh_token(&self, _token: &str) -> FusekiResult<String> {
        // SAML doesn't support token refresh - need to re-authenticate
        Err(FusekiError::bad_request(
            "SAML does not support token refresh",
        ))
    }
}

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

    #[test]
    fn test_authn_request_generation() {
        let config = SamlConfig {
            sp: ServiceProviderConfig {
                entity_id: "http://sp.example.com".to_string(),
                acs_url: Url::parse("http://sp.example.com/acs").unwrap(),
                sls_url: None,
                certificate: None,
                private_key: None,
            },
            idp: IdentityProviderConfig {
                entity_id: "http://idp.example.com".to_string(),
                sso_url: Url::parse("http://idp.example.com/sso").unwrap(),
                slo_url: None,
                certificate: "dummy-cert".to_string(),
                metadata_url: None,
            },
            attribute_mapping: AttributeMapping::default(),
            session: SessionConfig::default(),
        };

        let request = AuthnRequest::new(&config);
        let xml = request.to_xml();

        assert!(xml.contains(&config.sp.entity_id));
        assert!(xml.contains(&config.sp.acs_url.to_string()));
    }

    #[test]
    fn test_attribute_mapping() {
        let mapping = AttributeMapping::default();
        assert_eq!(
            mapping.username,
            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"
        );
        assert!(mapping.email.is_some());
    }
}