auth-framework 0.4.2

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
// Pure Rust SAML XML Signature Validation
// Implementation of XML-DSIG using ring, x509-parser, and quick-xml

#![allow(clippy::needless_borrows_for_generic_args)]
#![allow(clippy::needless_borrow)]

use crate::errors::{AuthError, Result};
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use quick_xml::{Reader, Writer, events::Event};
use ring::signature;
use std::collections::BTreeMap;
use std::io::Cursor;
use x509_parser::{parse_x509_certificate, public_key::PublicKey};

/// XML Canonicalizer implementing C14N (Canonical XML) per W3C specification
pub struct XmlCanonicalizer;

impl Default for XmlCanonicalizer {
    fn default() -> Self {
        Self::new()
    }
}

impl XmlCanonicalizer {
    /// Create a new XML canonicalizer
    pub fn new() -> Self {
        Self
    }

    /// Canonicalize XML according to W3C C14N specification
    pub fn canonicalize_xml(&self, xml: &str) -> Result<String> {
        let mut reader = Reader::from_str(xml);
        reader.config_mut().trim_text(true);

        let mut canonical = Vec::new();
        let mut writer = Writer::new(Cursor::new(&mut canonical));

        let mut namespace_stack: Vec<BTreeMap<String, String>> = vec![BTreeMap::new()];

        loop {
            match reader.read_event() {
                Ok(Event::Start(ref e)) => {
                    // Push new namespace context
                    let mut ns_ctx = namespace_stack.last().unwrap().clone();

                    // Process namespace declarations
                    for attr in e.attributes() {
                        let attr = attr.map_err(|e| {
                            AuthError::validation(&format!("XML attribute error: {}", e))
                        })?;
                        let key = std::str::from_utf8(attr.key.as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in attribute key: {}", e))
                        })?;
                        let value = std::str::from_utf8(&attr.value).map_err(|e| {
                            AuthError::validation(&format!(
                                "Invalid UTF-8 in attribute value: {}",
                                e
                            ))
                        })?;

                        if key.starts_with("xmlns:") || key == "xmlns" {
                            let prefix = if key == "xmlns" {
                                String::new()
                            } else {
                                key[6..].to_string()
                            };
                            ns_ctx.insert(prefix, value.to_string());
                        }
                    }
                    namespace_stack.push(ns_ctx);

                    // Write canonicalized start element
                    let canonicalized_element = self.canonicalize_element(e, &namespace_stack)?;
                    writer
                        .write_event(Event::Start(canonicalized_element))
                        .map_err(|e| AuthError::validation(&format!("XML write error: {}", e)))?;
                }
                Ok(Event::End(ref e)) => {
                    // Pop namespace context
                    namespace_stack.pop();
                    writer
                        .write_event(Event::End(e.clone()))
                        .map_err(|e| AuthError::validation(&format!("XML write error: {}", e)))?;
                }
                Ok(Event::Text(ref e)) => {
                    let text = e.xml_content().map_err(|e| {
                        AuthError::validation(&format!("XML text decode error: {}", e))
                    })?;
                    if !text.trim().is_empty() {
                        writer
                            .write_event(Event::Text(quick_xml::events::BytesText::new(&text)))
                            .map_err(|e| {
                                AuthError::validation(&format!("XML write error: {}", e))
                            })?;
                    }
                }
                Ok(Event::Empty(ref e)) => {
                    let canonicalized_element = self.canonicalize_element(e, &namespace_stack)?;
                    writer
                        .write_event(Event::Empty(canonicalized_element))
                        .map_err(|e| AuthError::validation(&format!("XML write error: {}", e)))?;
                }
                Ok(Event::Eof) => break,
                // Skip comments, processing instructions, and CDATA as per C14N
                Ok(Event::Comment(_)) | Ok(Event::PI(_)) | Ok(Event::CData(_)) => continue,
                Ok(Event::Decl(_)) => continue, // Skip XML declaration
                Ok(Event::DocType(_)) => continue, // Skip DOCTYPE declarations
                Ok(Event::GeneralRef(_)) => continue, // Skip general references
                Err(e) => return Err(AuthError::validation(&format!("XML parsing error: {}", e))),
            }
        }

        String::from_utf8(canonical).map_err(|e| {
            AuthError::validation(&format!("Invalid UTF-8 in canonicalized XML: {}", e))
        })
    }

    /// Canonicalize element attributes (sort lexicographically)
    fn canonicalize_element(
        &self,
        element: &quick_xml::events::BytesStart,
        _namespace_stack: &[BTreeMap<String, String>],
    ) -> Result<quick_xml::events::BytesStart<'static>> {
        let mut attrs: BTreeMap<String, String> = BTreeMap::new();

        // Collect all attributes
        for attr in element.attributes() {
            let attr =
                attr.map_err(|e| AuthError::validation(&format!("XML attribute error: {}", e)))?;
            let key = std::str::from_utf8(attr.key.as_ref()).map_err(|e| {
                AuthError::validation(&format!("Invalid UTF-8 in attribute key: {}", e))
            })?;
            let value = std::str::from_utf8(&attr.value).map_err(|e| {
                AuthError::validation(&format!("Invalid UTF-8 in attribute value: {}", e))
            })?;
            attrs.insert(key.to_string(), value.to_string());
        }

        // Create element name as owned string
        let element_name = std::str::from_utf8(element.name().as_ref())
            .map_err(|e| AuthError::validation(&format!("Invalid UTF-8 in element name: {}", e)))?
            .to_string();

        // Store length before moving the string
        let element_name_len = element_name.len();

        // Create new element with sorted attributes using owned data
        let mut new_element =
            quick_xml::events::BytesStart::from_content(element_name, element_name_len);

        // Add attributes in lexicographical order
        for (key, value) in attrs {
            new_element.push_attribute((key.as_str(), value.as_str()));
        }

        Ok(new_element)
    }
}

/// SAML XML Digital Signature Validator
pub struct SamlSignatureValidator;

impl SamlSignatureValidator {
    /// Validate XML signature using pure Rust cryptography
    pub fn validate_xml_signature(&self, xml: &str, cert_der: &[u8]) -> Result<bool> {
        // 1. Parse certificate and extract public key
        let (_, cert) = parse_x509_certificate(cert_der)
            .map_err(|e| AuthError::validation(&format!("Certificate parsing error: {}", e)))?;

        let public_key_info = cert.public_key();

        // 2. Extract SignedInfo element from XML
        let signed_info = self.extract_signed_info(xml)?;

        // 3. Canonicalize SignedInfo
        let canonicalizer = XmlCanonicalizer::new();
        let canonical_signed_info = canonicalizer.canonicalize_xml(&signed_info)?;

        // 4. Extract signature value from XML
        let signature_value = self.extract_signature_value(xml)?;
        let signature_bytes = BASE64
            .decode(&signature_value)
            .map_err(|e| AuthError::validation(&format!("Invalid base64 signature: {}", e)))?;

        // 5. Verify signature using Ring - handle different algorithm types
        match &public_key_info.algorithm.algorithm {
            // RSA with SHA-256
            oid if oid.to_string() == "1.2.840.113549.1.1.1" => {
                let public_key_bytes = match &public_key_info.parsed() {
                    Ok(PublicKey::RSA(rsa_key)) => self.construct_rsa_public_key(&rsa_key)?,
                    _ => {
                        return Err(AuthError::validation("Invalid RSA public key"));
                    }
                };
                let public_key = signature::UnparsedPublicKey::new(
                    &signature::RSA_PKCS1_2048_8192_SHA256,
                    &public_key_bytes,
                );
                match public_key.verify(canonical_signed_info.as_bytes(), &signature_bytes) {
                    Ok(_) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            // ECDSA with SHA-256 (P-256)
            oid if oid.to_string() == "1.2.840.10045.2.1" => {
                let public_key_bytes = match &public_key_info.parsed() {
                    Ok(PublicKey::EC(ec_key)) => self.construct_ecdsa_public_key(&ec_key)?,
                    _ => {
                        return Err(AuthError::validation("Invalid ECDSA public key"));
                    }
                };
                let public_key = signature::UnparsedPublicKey::new(
                    &signature::ECDSA_P256_SHA256_ASN1,
                    &public_key_bytes,
                );
                match public_key.verify(canonical_signed_info.as_bytes(), &signature_bytes) {
                    Ok(_) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
            oid => Err(AuthError::validation(&format!(
                "Unsupported signature algorithm: {}",
                oid
            ))),
        }
    }

    /// Extract SignedInfo element from SAML assertion
    fn extract_signed_info(&self, xml: &str) -> Result<String> {
        let mut reader = Reader::from_str(xml);
        let mut signed_info = String::new();
        let mut inside_signed_info = false;
        let mut depth = 0;

        loop {
            match reader.read_event() {
                Ok(Event::Start(ref e)) if e.name().as_ref() == b"SignedInfo" => {
                    inside_signed_info = true;
                    depth = 1;
                    signed_info.push_str(&format!(
                        "<{}>",
                        std::str::from_utf8(e.name().as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in element name: {}", e))
                        })?
                    ));

                    // Add attributes
                    for attr in e.attributes() {
                        let attr = attr.map_err(|e| {
                            AuthError::validation(&format!("XML attribute error: {}", e))
                        })?;
                        let key = std::str::from_utf8(attr.key.as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in attribute key: {}", e))
                        })?;
                        let value = std::str::from_utf8(&attr.value).map_err(|e| {
                            AuthError::validation(&format!(
                                "Invalid UTF-8 in attribute value: {}",
                                e
                            ))
                        })?;
                        signed_info.push_str(&format!(" {}=\"{}\"", key, value));
                    }
                    signed_info.push('>');
                }
                Ok(Event::Start(ref e)) if inside_signed_info => {
                    depth += 1;
                    signed_info.push_str(&format!(
                        "<{}>",
                        std::str::from_utf8(e.name().as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in element name: {}", e))
                        })?
                    ));

                    // Add attributes
                    for attr in e.attributes() {
                        let attr = attr.map_err(|e| {
                            AuthError::validation(&format!("XML attribute error: {}", e))
                        })?;
                        let key = std::str::from_utf8(attr.key.as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in attribute key: {}", e))
                        })?;
                        let value = std::str::from_utf8(&attr.value).map_err(|e| {
                            AuthError::validation(&format!(
                                "Invalid UTF-8 in attribute value: {}",
                                e
                            ))
                        })?;
                        signed_info.push_str(&format!(" {}=\"{}\"", key, value));
                    }
                    signed_info.push('>');
                }
                Ok(Event::End(ref e)) if inside_signed_info => {
                    depth -= 1;
                    signed_info.push_str(&format!(
                        "</{}>",
                        std::str::from_utf8(e.name().as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in element name: {}", e))
                        })?
                    ));

                    if depth == 0 {
                        break;
                    }
                }
                Ok(Event::Text(ref e)) if inside_signed_info => {
                    let text = e.xml_content().map_err(|e| {
                        AuthError::validation(&format!("XML text decode error: {}", e))
                    })?;
                    signed_info.push_str(&text);
                }
                Ok(Event::Empty(ref e)) if inside_signed_info => {
                    signed_info.push_str(&format!(
                        "<{}",
                        std::str::from_utf8(e.name().as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in element name: {}", e))
                        })?
                    ));

                    // Add attributes
                    for attr in e.attributes() {
                        let attr = attr.map_err(|e| {
                            AuthError::validation(&format!("XML attribute error: {}", e))
                        })?;
                        let key = std::str::from_utf8(attr.key.as_ref()).map_err(|e| {
                            AuthError::validation(&format!("Invalid UTF-8 in attribute key: {}", e))
                        })?;
                        let value = std::str::from_utf8(&attr.value).map_err(|e| {
                            AuthError::validation(&format!(
                                "Invalid UTF-8 in attribute value: {}",
                                e
                            ))
                        })?;
                        signed_info.push_str(&format!(" {}=\"{}\"", key, value));
                    }
                    signed_info.push_str(" />");
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(AuthError::validation(&format!("XML parsing error: {}", e))),
                _ => continue,
            }
        }

        if signed_info.is_empty() {
            return Err(AuthError::validation("SignedInfo element not found"));
        }

        Ok(signed_info)
    }

    /// Extract signature value from SAML assertion
    fn extract_signature_value(&self, xml: &str) -> Result<String> {
        let mut reader = Reader::from_str(xml);
        let mut inside_signature_value = false;
        let mut signature_value = String::new();

        loop {
            match reader.read_event() {
                Ok(Event::Start(ref e)) if e.name().as_ref() == b"SignatureValue" => {
                    inside_signature_value = true;
                }
                Ok(Event::Text(ref e)) if inside_signature_value => {
                    let text = e.xml_content().map_err(|e| {
                        AuthError::validation(&format!("XML text decode error: {}", e))
                    })?;
                    signature_value.push_str(&text);
                }
                Ok(Event::End(ref e)) if e.name().as_ref() == b"SignatureValue" => {
                    break;
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(AuthError::validation(&format!("XML parsing error: {}", e))),
                _ => continue,
            }
        }

        if signature_value.is_empty() {
            return Err(AuthError::validation("SignatureValue element not found"));
        }

        // Remove whitespace and newlines
        Ok(signature_value
            .chars()
            .filter(|c| !c.is_whitespace())
            .collect())
    }

    /// Construct RSA public key in PKCS#1 format for Ring
    fn construct_rsa_public_key(
        &self,
        rsa_key: &x509_parser::public_key::RSAPublicKey,
    ) -> Result<Vec<u8>> {
        // For RSA, Ring expects the raw public key data
        // This is a simplified implementation - in production, you'd want proper ASN.1 encoding
        let mut key_data = Vec::new();
        key_data.extend_from_slice(rsa_key.modulus);
        key_data.extend_from_slice(rsa_key.exponent);
        Ok(key_data)
    }

    fn construct_ecdsa_public_key(
        &self,
        ec_key: &x509_parser::public_key::ECPoint,
    ) -> Result<Vec<u8>> {
        // For ECDSA, extract the public key point data
        Ok(ec_key.data().to_vec())
    }
}

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

    #[test]
    fn test_xml_canonicalization() {
        let xml = r#"<test xmlns:ns="http://example.com" attr2="value2" attr1="value1">
            <child>content</child>
        </test>"#;

        let canonicalizer = XmlCanonicalizer::new();
        let result = canonicalizer.canonicalize_xml(xml);
        assert!(result.is_ok());

        let canonical = result.unwrap();
        // Should have sorted attributes and normalized whitespace
        assert!(canonical.contains("attr1"));
        assert!(canonical.contains("attr2"));
    }

    #[test]
    fn test_signed_info_extraction() {
        let xml = r#"
        <Assertion>
            <Signature>
                <SignedInfo>
                    <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
                    <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
                    <Reference URI="">
                        <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
                        <DigestValue>base64digest</DigestValue>
                    </Reference>
                </SignedInfo>
                <SignatureValue>base64signature</SignatureValue>
            </Signature>
        </Assertion>"#;

        let validator = SamlSignatureValidator;
        let result = validator.extract_signed_info(xml);
        assert!(result.is_ok());

        let signed_info = result.unwrap();
        assert!(signed_info.contains("SignedInfo"));
        assert!(signed_info.contains("CanonicalizationMethod"));
        assert!(signed_info.contains("SignatureMethod"));
        assert!(signed_info.contains("Reference"));
    }

    #[test]
    fn test_signature_value_extraction() {
        let xml = r#"
        <Signature>
            <SignatureValue>
                YmFzZTY0c2lnbmF0dXJl
            </SignatureValue>
        </Signature>"#;

        let validator = SamlSignatureValidator;
        let result = validator.extract_signature_value(xml);
        assert!(result.is_ok());

        let signature_value = result.unwrap();
        assert_eq!(signature_value, "YmFzZTY0c2lnbmF0dXJl");
    }
}