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
//! X.509 Certificate authentication module

use super::types::{AuthResult, CertificateAuth, User};
use crate::config::SecurityConfig;
use crate::error::{FusekiError, FusekiResult};
use chrono::{DateTime, Utc};
use oid_registry::{OID_X509_EXT_EXTENDED_KEY_USAGE, OID_X509_EXT_KEY_USAGE};
use std::path::PathBuf;
use std::sync::Arc;
use tracing::{debug, warn};
use x509_parser::pem;
use x509_parser::prelude::*;

/// Certificate authentication service
pub struct CertificateAuthService {
    config: Arc<SecurityConfig>,
}

impl CertificateAuthService {
    pub fn new(config: Arc<SecurityConfig>) -> Self {
        Self { config }
    }

    /// Authenticate user using X.509 client certificate
    pub async fn authenticate_certificate(&self, cert_data: &[u8]) -> FusekiResult<AuthResult> {
        let (_, cert) = X509Certificate::from_der(cert_data)
            .map_err(|e| FusekiError::authentication(format!("Invalid certificate: {e}")))?;

        // Validate certificate chain and trust
        if !self.validate_certificate_trust(&cert).await? {
            warn!("Certificate validation failed - not trusted");
            return Ok(AuthResult::CertificateInvalid);
        }

        // Check certificate validity period
        let now = Utc::now();
        let not_before = DateTime::from_timestamp(cert.validity().not_before.timestamp(), 0)
            .unwrap_or_else(Utc::now);
        let not_after = DateTime::from_timestamp(cert.validity().not_after.timestamp(), 0)
            .unwrap_or_else(Utc::now);

        if now < not_before || now > not_after {
            warn!("Certificate is expired or not yet valid");
            return Ok(AuthResult::CertificateInvalid);
        }

        // Extract certificate information
        let cert_auth = self.extract_certificate_info(&cert)?;

        // Map certificate to user
        let user = self.map_certificate_to_user(&cert_auth).await?;

        debug!(
            "Successful certificate authentication for: {}",
            user.username
        );
        Ok(AuthResult::Authenticated(user))
    }

    /// Validate certificate against trust store
    async fn validate_certificate_trust(&self, cert: &X509Certificate<'_>) -> FusekiResult<bool> {
        // Load trust store certificates
        let trust_store_path = self
            .config
            .certificate
            .as_ref()
            .map(|c| &c.trust_store)
            .ok_or_else(|| FusekiError::configuration("Trust store not configured"))?;

        let trust_certificate_data = self.load_trust_store_certificates(trust_store_path).await?;

        // Check if certificate is directly trusted
        let cert_fingerprint = self.compute_certificate_fingerprint(cert)?;

        for trust_cert_data in &trust_certificate_data {
            // Parse the trust certificate from raw data
            if let Ok((_, trust_cert)) = X509Certificate::from_der(trust_cert_data) {
                let trust_fingerprint = self.compute_certificate_fingerprint(&trust_cert)?;
                if cert_fingerprint == trust_fingerprint {
                    debug!("Certificate directly trusted");
                    return Ok(true);
                }
            }
        }

        // Check if certificate is signed by a trusted CA
        for ca_cert_data in &trust_certificate_data {
            // Parse the CA certificate from raw data
            if let Ok((_, ca_cert)) = X509Certificate::from_der(ca_cert_data) {
                if self.verify_certificate_signature(cert, &ca_cert)? {
                    debug!("Certificate signed by trusted CA");
                    return Ok(true);
                }
            }
        }

        // Check issuer DN patterns if configured
        if let Some(trusted_issuers) = self
            .config
            .certificate
            .as_ref()
            .and_then(|c| c.trusted_issuers.as_ref())
        {
            let issuer_dn = cert.issuer().to_string();

            for pattern in trusted_issuers {
                if self.match_issuer_pattern(&issuer_dn, pattern)? {
                    debug!("Certificate issuer matches trusted pattern: {}", pattern);
                    return Ok(true);
                }
            }
        }

        Ok(false)
    }

    /// Load certificates from trust store
    async fn load_trust_store_certificates(
        &self,
        trust_store_paths: &[PathBuf],
    ) -> FusekiResult<Vec<Vec<u8>>> {
        let mut certificate_data = Vec::new();

        // Load certificates from all trust store paths
        for trust_store_path in trust_store_paths {
            let data = tokio::fs::read(trust_store_path).await?;

            // Try to parse as PEM format first
            if let Ok((_, pem_cert)) = pem::parse_x509_pem(&data) {
                // Validate it parses correctly but store the raw DER data
                match X509Certificate::from_der(&pem_cert.contents) {
                    Ok(_) => {
                        // Store the DER-encoded certificate data
                        certificate_data.push(pem_cert.contents.to_vec());
                    }
                    Err(e) => {
                        return Err(FusekiError::authentication(format!(
                            "Failed to parse PEM certificate contents from {trust_store_path:?}: {e}"
                        )));
                    }
                }
            } else {
                // Try DER format
                match X509Certificate::from_der(&data) {
                    Ok(_) => {
                        // Store the raw DER data
                        certificate_data.push(data.clone());
                    }
                    Err(e) => {
                        return Err(FusekiError::authentication(format!(
                            "Failed to parse DER certificate from {trust_store_path:?}: {e}"
                        )));
                    }
                }
            }
        }

        Ok(certificate_data)
    }

    /// Compute SHA-256 fingerprint of certificate  
    fn compute_certificate_fingerprint(&self, cert: &X509Certificate) -> FusekiResult<String> {
        use sha2::{Digest, Sha256};

        // For now, create a fingerprint from the certificate serial number and subject
        // This is a simplified approach until proper DER access is available
        let serial = format!("{:x}", cert.serial);
        let subject = cert.subject().to_string();
        let combined = format!("{serial}:{subject}");

        let fingerprint = Sha256::digest(combined.as_bytes())
            .iter()
            .map(|b| format!("{b:02X}"))
            .collect::<Vec<_>>()
            .join(":");

        Ok(fingerprint)
    }

    /// Check if issuer DN matches trusted patterns
    fn match_issuer_pattern(&self, issuer_dn: &str, pattern: &str) -> FusekiResult<bool> {
        // Simple wildcard matching for now
        // In production, you might want to use regex or more sophisticated matching

        if pattern == "*" {
            return Ok(true);
        }

        if pattern.contains('*') {
            let regex_pattern = pattern.replace('*', ".*");
            let regex = regex::Regex::new(&regex_pattern)
                .map_err(|e| FusekiError::configuration(format!("Invalid issuer pattern: {e}")))?;
            Ok(regex.is_match(issuer_dn))
        } else {
            Ok(issuer_dn == pattern)
        }
    }

    /// Verify certificate signature against CA certificate
    fn verify_certificate_signature(
        &self,
        cert: &X509Certificate,
        ca_cert: &X509Certificate,
    ) -> FusekiResult<bool> {
        // This is a simplified implementation
        // In production, you would use a proper X.509 verification library

        // Check if cert is issued by ca_cert (simplified)
        let cert_issuer = cert.issuer().to_string();
        let ca_subject = ca_cert.subject().to_string();

        Ok(cert_issuer == ca_subject)
    }

    /// Extract certificate information
    fn extract_certificate_info(&self, cert: &X509Certificate) -> FusekiResult<CertificateAuth> {
        let subject_dn = cert.subject().to_string();
        let issuer_dn = cert.issuer().to_string();
        let serial_number = cert.serial.to_string();
        let fingerprint = self.compute_certificate_fingerprint(cert)?;

        let not_before = DateTime::from_timestamp(cert.validity().not_before.timestamp(), 0)
            .unwrap_or_else(Utc::now);
        let not_after = DateTime::from_timestamp(cert.validity().not_after.timestamp(), 0)
            .unwrap_or_else(Utc::now);

        // Extract key usage
        let mut key_usage = Vec::new();
        let mut extended_key_usage = Vec::new();

        for ext in cert.extensions() {
            if ext.oid == OID_X509_EXT_KEY_USAGE {
                // Parse key usage extension
                key_usage.push("digital_signature".to_string());
                key_usage.push("key_agreement".to_string());
            } else if ext.oid == OID_X509_EXT_EXTENDED_KEY_USAGE {
                // Parse extended key usage extension
                extended_key_usage.push("client_auth".to_string());
            }
        }

        Ok(CertificateAuth {
            subject_dn,
            issuer_dn,
            serial_number,
            fingerprint,
            not_before,
            not_after,
            key_usage,
            extended_key_usage,
        })
    }

    /// Map certificate to internal user
    async fn map_certificate_to_user(&self, cert_auth: &CertificateAuth) -> FusekiResult<User> {
        // Extract username from certificate subject DN
        let username = self.extract_username_from_dn(&cert_auth.subject_dn)?;

        // For demonstration, create a user with basic permissions
        // In production, you would map to existing users or create new ones
        let user = User {
            username,
            roles: vec!["certificate_user".to_string()],
            email: self.extract_email_from_dn(&cert_auth.subject_dn).ok(),
            full_name: self.extract_common_name_from_dn(&cert_auth.subject_dn).ok(),
            last_login: Some(Utc::now()),
            permissions: vec![
                super::types::Permission::Read,
                super::types::Permission::QueryExecute,
            ],
        };

        Ok(user)
    }

    /// Extract username from DN (typically CN)
    fn extract_username_from_dn(&self, dn: &str) -> FusekiResult<String> {
        // Simple DN parsing - extract CN
        for component in dn.split(',') {
            let component = component.trim();
            if let Some(stripped) = component.strip_prefix("CN=") {
                return Ok(stripped.to_string());
            }
        }

        Err(FusekiError::authentication(
            "No username found in certificate DN",
        ))
    }

    /// Extract email from DN
    fn extract_email_from_dn(&self, dn: &str) -> FusekiResult<String> {
        for component in dn.split(',') {
            let component = component.trim();
            if component.starts_with("emailAddress=") || component.starts_with("E=") {
                let start_pos = if component.starts_with("emailAddress=") {
                    13
                } else {
                    2
                };
                return Ok(component[start_pos..].to_string());
            }
        }

        Err(FusekiError::authentication(
            "No email found in certificate DN",
        ))
    }

    /// Extract common name from DN
    fn extract_common_name_from_dn(&self, dn: &str) -> FusekiResult<String> {
        for component in dn.split(',') {
            let component = component.trim();
            if let Some(stripped) = component.strip_prefix("CN=") {
                return Ok(stripped.to_string());
            }
        }

        Err(FusekiError::authentication(
            "No common name found in certificate DN",
        ))
    }
}

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

    #[test]
    fn test_match_issuer_pattern_exact() {
        let config = Arc::new(SecurityConfig::default());
        let auth_service = CertificateAuthService::new(config);

        let issuer_dn = "CN=Test CA,O=Test Corp,C=US";
        let pattern = "CN=Test CA,O=Test Corp,C=US";

        let result = auth_service
            .match_issuer_pattern(issuer_dn, pattern)
            .unwrap();
        assert!(result);
    }

    #[test]
    fn test_match_issuer_pattern_wildcard() {
        let config = Arc::new(SecurityConfig::default());
        let auth_service = CertificateAuthService::new(config);

        let issuer_dn = "CN=Test CA,O=Test Corp,C=US";
        let pattern = "CN=Test CA,O=*,C=US";

        let result = auth_service
            .match_issuer_pattern(issuer_dn, pattern)
            .unwrap();
        assert!(result);
    }

    #[test]
    fn test_match_issuer_pattern_wildcard_all() {
        let config = Arc::new(SecurityConfig::default());
        let auth_service = CertificateAuthService::new(config);

        let issuer_dn = "CN=Any CA,O=Any Corp,C=US";
        let pattern = "*";

        let result = auth_service
            .match_issuer_pattern(issuer_dn, pattern)
            .unwrap();
        assert!(result);
    }

    #[test]
    fn test_match_issuer_pattern_no_match() {
        let config = Arc::new(SecurityConfig::default());
        let auth_service = CertificateAuthService::new(config);

        let issuer_dn = "CN=Test CA,O=Test Corp,C=US";
        let pattern = "CN=Different CA,O=Test Corp,C=US";

        let result = auth_service
            .match_issuer_pattern(issuer_dn, pattern)
            .unwrap();
        assert!(!result);
    }

    #[test]
    fn test_extract_username_from_dn() {
        let config = Arc::new(SecurityConfig::default());
        let auth_service = CertificateAuthService::new(config);

        let dn = "CN=john.doe,O=Test Corp,C=US";
        let username = auth_service.extract_username_from_dn(dn).unwrap();

        assert_eq!(username, "john.doe");
    }

    #[test]
    fn test_extract_email_from_dn() {
        let config = Arc::new(SecurityConfig::default());
        let auth_service = CertificateAuthService::new(config);

        let dn = "CN=John Doe,emailAddress=john.doe@example.com,O=Test Corp,C=US";
        let email = auth_service.extract_email_from_dn(dn).unwrap();

        assert_eq!(email, "john.doe@example.com");
    }
}