soap-server 0.1.1

A WSDL-driven SOAP 1.1/1.2 server library for Rust — document/RPC dispatch, WS-Security UsernameToken, axum-based (the transport under onvif-server)
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
// WS-Security UsernameToken parsing and verification
use crate::fault::SoapFault;
use crate::wssec::nonce_cache::RotatingNonceCache;
use crate::wssec::timestamp::{check_freshness, parse_created};
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use chrono::{DateTime, Utc};
use quick_xml::events::Event;
use quick_xml::Reader;
use sha1::{Digest, Sha1};
use std::collections::HashMap;
use subtle::ConstantTimeEq;

// WS-Security namespaces
const WSSE_NS: &str =
    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
const WSU_NS: &str =
    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
const PASSWORD_DIGEST_TYPE: &str = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest";
const PASSWORD_TEXT_TYPE: &str = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText";

/// The type of password in a UsernameToken.
#[derive(Debug, Clone, PartialEq)]
pub enum PasswordType {
    Digest,
    Text,
}

/// A parsed WS-Security UsernameToken.
#[derive(Debug, Clone)]
pub struct UsernameToken {
    pub username: String,
    pub password: String,
    pub password_type: PasswordType,
    pub nonce: Option<String>,
    pub created: Option<String>,
}

/// Compute PasswordDigest per OASIS WS-Security UsernameToken Profile 1.1 spec:
/// `digest = Base64( SHA-1( Base64Decode(Nonce) ++ Created_UTF8 ++ Password_UTF8 ) )`
///
/// # Arguments
/// - `nonce_b64`: the **base64-encoded** nonce string (as it appears in the XML `<wsse:Nonce>` element).
///   This function decodes it internally. Passing raw nonce bytes (not base64-encoded) will produce
///   an incorrect digest.
/// - `created`: the ISO 8601 Created timestamp string (e.g. `"2024-01-01T00:00:00.000Z"`).
/// - `password`: the plaintext password.
///
/// Returns `Err(SoapFault)` if `nonce_b64` is not valid base64.
///
/// # Note
/// This function is part of soap-server's internal WS-Security implementation.
/// It is exported for testing convenience but is not intended as a stable public API.
/// Prefer using [`validate_username_token`] for full token validation.
#[doc(hidden)]
pub fn compute_digest(nonce_b64: &str, created: &str, password: &str) -> Result<String, SoapFault> {
    // Add padding if needed for base64 decoding
    let padded = add_base64_padding(nonce_b64);
    let nonce_bytes = BASE64
        .decode(padded.as_str())
        .map_err(|e| SoapFault::sender(format!("Invalid nonce encoding: {e}")))?;
    let mut hasher = Sha1::new();
    hasher.update(&nonce_bytes);
    hasher.update(created.as_bytes());
    hasher.update(password.as_bytes());
    Ok(BASE64.encode(hasher.finalize()))
}

/// Add base64 padding `=` chars if missing.
fn add_base64_padding(s: &str) -> String {
    let remainder = s.len() % 4;
    if remainder == 0 {
        s.to_string()
    } else {
        let padding = 4 - remainder;
        format!("{}{}", s, "=".repeat(padding))
    }
}

/// Parse a WS-Security UsernameToken from XML bytes (the wsse:Security header content).
pub fn parse_username_token(xml_bytes: &[u8]) -> Result<UsernameToken, SoapFault> {
    let mut reader = Reader::from_reader(xml_bytes);
    reader.config_mut().trim_text(true);

    let mut username: Option<String> = None;
    let mut password: Option<String> = None;
    let mut password_type = PasswordType::Digest;
    let mut nonce: Option<String> = None;
    let mut created: Option<String> = None;

    // Track namespace prefix -> URI mappings (global across the document)
    let mut ns_map: HashMap<String, String> = HashMap::new();

    let mut in_username_token = false;
    let mut in_username_elem = false;
    let mut in_password_elem = false;
    let mut in_nonce_elem = false;
    let mut in_created_elem = false;
    let mut found_token = false;

    let mut buf = Vec::new();
    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref e)) => {
                // Update ns_map from xmlns attributes on this element
                collect_ns_attrs(e.attributes(), &mut ns_map);

                let name = e.name();
                let (prefix, local) = split_name(name.as_ref());
                let ns = resolve_ns(prefix, &ns_map);

                match (local, ns.as_deref()) {
                    ("UsernameToken", Some(WSSE_NS)) => {
                        in_username_token = true;
                        found_token = true;
                    }
                    ("Username", Some(WSSE_NS)) if in_username_token => {
                        in_username_elem = true;
                    }
                    ("Password", Some(WSSE_NS)) if in_username_token => {
                        in_password_elem = true;
                        // Read the Type attribute
                        for attr in e.attributes().flatten() {
                            let key = std::str::from_utf8(attr.key.as_ref()).unwrap_or("");
                            if key == "Type" {
                                let val = String::from_utf8_lossy(&attr.value).to_string();
                                password_type = if val == PASSWORD_DIGEST_TYPE {
                                    PasswordType::Digest
                                } else if val == PASSWORD_TEXT_TYPE {
                                    PasswordType::Text
                                } else {
                                    PasswordType::Digest
                                };
                            }
                        }
                    }
                    ("Nonce", Some(WSSE_NS)) if in_username_token => {
                        in_nonce_elem = true;
                    }
                    ("Created", Some(WSU_NS)) if in_username_token => {
                        in_created_elem = true;
                    }
                    _ => {}
                }
            }
            Ok(Event::Empty(ref e)) => {
                collect_ns_attrs(e.attributes(), &mut ns_map);
                let name = e.name();
                let (prefix, local) = split_name(name.as_ref());
                let ns = resolve_ns(prefix, &ns_map);
                if local == "UsernameToken" && ns.as_deref() == Some(WSSE_NS) {
                    found_token = true;
                }
            }
            Ok(Event::Text(ref e)) => {
                let text = String::from_utf8_lossy(e.as_ref()).to_string();
                if in_username_elem {
                    username = Some(text);
                    in_username_elem = false;
                } else if in_password_elem {
                    password = Some(text);
                    in_password_elem = false;
                } else if in_nonce_elem {
                    nonce = Some(text);
                    in_nonce_elem = false;
                } else if in_created_elem {
                    created = Some(text);
                    in_created_elem = false;
                }
            }
            Ok(Event::End(ref e)) => {
                let name = e.name();
                let (_, local) = split_name(name.as_ref());
                match local {
                    "UsernameToken" => {
                        in_username_token = false;
                    }
                    "Username" => {
                        in_username_elem = false;
                    }
                    "Password" => {
                        in_password_elem = false;
                    }
                    "Nonce" => {
                        in_nonce_elem = false;
                    }
                    "Created" => {
                        in_created_elem = false;
                    }
                    _ => {}
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(SoapFault::sender(format!(
                    "WS-Security XML parse error: {e}"
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    if !found_token {
        return Err(SoapFault::sender("Missing UsernameToken"));
    }

    let username =
        username.ok_or_else(|| SoapFault::sender("Missing Username in UsernameToken"))?;
    let password =
        password.ok_or_else(|| SoapFault::sender("Missing Password in UsernameToken"))?;

    Ok(UsernameToken {
        username,
        password,
        password_type,
        nonce,
        created,
    })
}

/// Validate a WS-Security UsernameToken from a raw `<wsse:Security>` XML element.
///
/// Returns the authenticated username on success, or a [`SoapFault`] on failure.
///
/// # Arguments
/// - `security_bytes`: raw XML bytes of the `<wsse:Security>` header child element.
/// - `get_password`: closure mapping a username to its stored plaintext password,
///   or `None` if the user is unknown. Called with the username from the token.
/// - `nonce_cache`: replay-detection cache. Takes `&mut self` — the caller must hold
///   an exclusive lock (e.g. via `tokio::sync::Mutex`) when calling this in an async
///   context. See [`RotatingNonceCache`] for thread-safety guidance.
/// - `tolerance_secs`: maximum age in seconds for the `<wsu:Created>` timestamp.
///   Requests older than this are rejected as expired.
/// - `now`: current UTC time, used for timestamp freshness checks. Pass `Utc::now()`
///   in production; inject a fixed value in tests.
///
/// # Validation steps
/// 1. Parse the `<wsse:UsernameToken>` from `security_bytes`.
/// 2. Look up the stored password via `get_password`.
/// 3. Verify the password (PasswordDigest or PasswordText).
/// 4. Check that `<wsu:Created>` is within `tolerance_secs` of `now`.
/// 5. Check the nonce for replay via `nonce_cache`.
pub fn validate_username_token(
    security_bytes: &[u8],
    get_password: &dyn Fn(&str) -> Option<String>,
    nonce_cache: &mut RotatingNonceCache,
    tolerance_secs: i64,
    now: DateTime<Utc>,
) -> Result<String, SoapFault> {
    let token = parse_username_token(security_bytes)?;

    // Normalize unknown-user to the same generic fault as a wrong password so
    // that callers cannot enumerate valid usernames from the fault reason (Finding #12).
    let stored_password =
        get_password(&token.username).ok_or_else(|| SoapFault::sender("Authentication failed"))?;

    // Verify password
    match token.password_type {
        PasswordType::Digest => {
            let nonce = token
                .nonce
                .as_deref()
                .ok_or_else(|| SoapFault::sender("Missing Nonce for PasswordDigest"))?;
            let created = token
                .created
                .as_deref()
                .ok_or_else(|| SoapFault::sender("Missing Created for PasswordDigest"))?;
            let expected = compute_digest(nonce, created, &stored_password)?;
            // Use constant-time comparison to avoid timing side-channels (Finding #9).
            if expected
                .as_bytes()
                .ct_eq(token.password.as_bytes())
                .unwrap_u8()
                == 0
            {
                return Err(SoapFault::sender("Authentication failed"));
            }
            // Require freshness for Digest tokens (Created was already required above).
            let created_dt = parse_created(created)?;
            check_freshness(now, created_dt, tolerance_secs)?;
        }
        PasswordType::Text => {
            // Require Created timestamp for PasswordText (Finding #9).
            let created_str = token
                .created
                .as_deref()
                .ok_or_else(|| SoapFault::sender("Missing Created for PasswordText"))?;
            let created_dt = parse_created(created_str)?;
            check_freshness(now, created_dt, tolerance_secs)?;

            // Plain string equality is fine for text passwords; constant-time
            // comparison would also be acceptable but offers negligible benefit
            // given that text passwords are inherently weak without TLS.
            if token.password != stored_password {
                return Err(SoapFault::sender("Authentication failed"));
            }
        }
    }

    // Check nonce for replay
    if let Some(nonce) = &token.nonce {
        nonce_cache.check_and_insert(nonce)?;
    }

    Ok(token.username)
}

/// Collect namespace prefix -> URI bindings from element attributes.
fn collect_ns_attrs(
    attrs: quick_xml::events::attributes::Attributes<'_>,
    ns_map: &mut HashMap<String, String>,
) {
    for attr in attrs.flatten() {
        let key = std::str::from_utf8(attr.key.as_ref()).unwrap_or("");
        let val = String::from_utf8_lossy(&attr.value).to_string();
        if let Some(prefix) = key.strip_prefix("xmlns:") {
            ns_map.insert(prefix.to_string(), val);
        } else if key == "xmlns" {
            ns_map.insert(String::new(), val);
        }
    }
}

/// Split a qualified element name into (prefix, local_name).
fn split_name(name: &[u8]) -> (Option<&str>, &str) {
    let s = std::str::from_utf8(name).unwrap_or("");
    match s.find(':') {
        Some(pos) => (Some(&s[..pos]), &s[pos + 1..]),
        None => (None, s),
    }
}

/// Resolve a namespace prefix to its URI using the ns_map.
fn resolve_ns(prefix: Option<&str>, ns_map: &HashMap<String, String>) -> Option<String> {
    match prefix {
        Some(p) => ns_map.get(p).cloned(),
        None => ns_map.get("").cloned(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::wssec::nonce_cache::RotatingNonceCache;
    use chrono::TimeZone;

    // Known test vector — self-consistent, independently verified with Python hashlib/base64.
    // Nonce raw bytes: [0x00, 0x01, ..., 0x0f] (16 bytes), base64-encoded.
    // Verified: base64.b64encode(sha1(base64.b64decode(NONCE) + CREATED + PASSWORD)) == DIGEST
    const TEST_NONCE: &str = "AAECAwQFBgcICQoLDA0ODw==";
    const TEST_CREATED: &str = "2010-09-09T14:18:30.000Z";
    const TEST_PASSWORD: &str = "userpassword";
    const TEST_EXPECTED_DIGEST: &str = "QPgtSBfcw764Vty2h0+LsasXgxo=";

    fn test_now() -> DateTime<Utc> {
        // 1 second after the created timestamp — within tolerance
        Utc.with_ymd_and_hms(2010, 9, 9, 14, 18, 31).unwrap()
    }

    fn make_nonce_cache() -> RotatingNonceCache {
        RotatingNonceCache::new(150)
    }

    fn security_xml_digest(nonce: &str, created: &str, digest: &str) -> Vec<u8> {
        format!(r#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <wsse:UsernameToken>
    <wsse:Username>admin</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">{digest}</wsse:Password>
    <wsse:Nonce>{nonce}</wsse:Nonce>
    <wsu:Created>{created}</wsu:Created>
  </wsse:UsernameToken>
</wsse:Security>"#).into_bytes()
    }

    fn security_xml_text(password: &str) -> Vec<u8> {
        // Includes a Created timestamp so freshness checks pass.
        format!(r#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <wsse:UsernameToken>
    <wsse:Username>admin</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">{password}</wsse:Password>
    <wsu:Created>{TEST_CREATED}</wsu:Created>
  </wsse:UsernameToken>
</wsse:Security>"#).into_bytes()
    }

    fn security_xml_text_no_created(password: &str) -> Vec<u8> {
        format!(r#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  <wsse:UsernameToken>
    <wsse:Username>admin</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">{password}</wsse:Password>
  </wsse:UsernameToken>
</wsse:Security>"#).into_bytes()
    }

    fn security_xml_no_token() -> Vec<u8> {
        br#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
</wsse:Security>"#.to_vec()
    }

    fn security_xml_no_password() -> Vec<u8> {
        br#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
  <wsse:UsernameToken>
    <wsse:Username>admin</wsse:Username>
  </wsse:UsernameToken>
</wsse:Security>"#.to_vec()
    }

    // ---- compute_digest tests ----

    #[test]
    fn known_vector_digest_matches_expected() {
        let result = compute_digest(TEST_NONCE, TEST_CREATED, TEST_PASSWORD).unwrap();
        assert_eq!(
            result, TEST_EXPECTED_DIGEST,
            "PasswordDigest known vector failed: got {result}, expected {TEST_EXPECTED_DIGEST}"
        );
    }

    #[test]
    fn compute_digest_invalid_base64_nonce_returns_err() {
        let result = compute_digest("not!!!valid_base64!!!", TEST_CREATED, TEST_PASSWORD);
        assert!(result.is_err());
    }

    // ---- parse_username_token tests ----

    #[test]
    fn parse_digest_token_extracts_all_fields() {
        let xml = security_xml_digest(TEST_NONCE, TEST_CREATED, TEST_EXPECTED_DIGEST);
        let token = parse_username_token(&xml).unwrap();
        assert_eq!(token.username, "admin");
        assert_eq!(token.password, TEST_EXPECTED_DIGEST);
        assert_eq!(token.password_type, PasswordType::Digest);
        assert_eq!(token.nonce.as_deref(), Some(TEST_NONCE));
        assert_eq!(token.created.as_deref(), Some(TEST_CREATED));
    }

    #[test]
    fn parse_text_token_extracts_fields() {
        let xml = security_xml_text("secret");
        let token = parse_username_token(&xml).unwrap();
        assert_eq!(token.username, "admin");
        assert_eq!(token.password, "secret");
        assert_eq!(token.password_type, PasswordType::Text);
        assert!(token.nonce.is_none());
    }

    #[test]
    fn parse_missing_username_token_returns_err() {
        let xml = security_xml_no_token();
        let result = parse_username_token(&xml);
        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert!(
            fault.reason.contains("Missing UsernameToken"),
            "got: {}",
            fault.reason
        );
    }

    #[test]
    fn parse_missing_password_returns_err() {
        let xml = security_xml_no_password();
        let result = parse_username_token(&xml);
        assert!(result.is_err());
    }

    // ---- validate_username_token tests ----

    fn get_password(username: &str) -> Option<String> {
        if username == "admin" {
            Some(TEST_PASSWORD.to_string())
        } else {
            None
        }
    }

    #[test]
    fn validate_correct_digest_returns_username() {
        let xml = security_xml_digest(TEST_NONCE, TEST_CREATED, TEST_EXPECTED_DIGEST);
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert_eq!(result.unwrap(), "admin");
    }

    #[test]
    fn validate_wrong_password_returns_auth_failed() {
        // Compute digest with wrong password
        let bad_digest = compute_digest(TEST_NONCE, TEST_CREATED, "wrongpassword").unwrap();
        let xml = security_xml_digest(TEST_NONCE, TEST_CREATED, &bad_digest);
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert!(
            fault.reason.contains("Authentication failed"),
            "got: {}",
            fault.reason
        );
    }

    #[test]
    fn validate_unknown_user_returns_err() {
        let xml = format!(
            r#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <wsse:UsernameToken>
    <wsse:Username>unknownuser</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">{TEST_EXPECTED_DIGEST}</wsse:Password>
    <wsse:Nonce>{TEST_NONCE}</wsse:Nonce>
    <wsu:Created>{TEST_CREATED}</wsu:Created>
  </wsse:UsernameToken>
</wsse:Security>"#
        );
        let mut cache = make_nonce_cache();
        let result =
            validate_username_token(xml.as_bytes(), &get_password, &mut cache, 300, test_now());
        assert!(result.is_err());
        let fault = result.unwrap_err();
        // Unknown user is normalized to the same generic message (Finding #12).
        assert!(
            fault.reason.contains("Authentication failed"),
            "got: {}",
            fault.reason
        );
    }

    #[test]
    fn validate_expired_timestamp_returns_err() {
        // Use a 'now' that is 400 seconds after the created timestamp
        let expired_now = Utc.with_ymd_and_hms(2010, 9, 9, 14, 25, 30).unwrap();
        let xml = security_xml_digest(TEST_NONCE, TEST_CREATED, TEST_EXPECTED_DIGEST);
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, expired_now);
        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert!(fault.reason.contains("expired"), "got: {}", fault.reason);
    }

    #[test]
    fn validate_replayed_nonce_returns_err() {
        let xml = security_xml_digest(TEST_NONCE, TEST_CREATED, TEST_EXPECTED_DIGEST);
        let mut cache = make_nonce_cache();
        // First call succeeds
        validate_username_token(&xml, &get_password, &mut cache, 300, test_now()).unwrap();
        // Second call with same nonce should fail (replay)
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert!(fault.reason.contains("replay"), "got: {}", fault.reason);
    }

    #[test]
    fn validate_text_password_correct() {
        let xml = security_xml_text(TEST_PASSWORD);
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert_eq!(result.unwrap(), "admin");
    }

    #[test]
    fn validate_text_password_wrong_returns_err() {
        let xml = security_xml_text("wrongpassword");
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert!(
            fault.reason.contains("Authentication failed"),
            "got: {}",
            fault.reason
        );
    }

    #[test]
    fn validate_missing_username_token_returns_err() {
        let xml = security_xml_no_token();
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert!(
            fault.reason.contains("Missing UsernameToken"),
            "got: {}",
            fault.reason
        );
    }

    // ── Finding #9: PasswordText without Created is rejected ─────────────────

    #[test]
    fn validate_text_password_without_created_is_rejected() {
        let xml = security_xml_text_no_created(TEST_PASSWORD);
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert!(
            result.is_err(),
            "PasswordText without Created must be rejected"
        );
        let fault = result.unwrap_err();
        assert!(
            fault.reason.contains("Missing Created"),
            "Expected 'Missing Created' fault, got: {}",
            fault.reason
        );
    }

    // ── Finding #9: Digest compare still validates a correct token ────────────
    // (constant-time path)

    #[test]
    fn validate_correct_digest_constant_time_path_returns_username() {
        // Re-run the known-vector test to confirm the constant-time path is correct.
        let xml = security_xml_digest(TEST_NONCE, TEST_CREATED, TEST_EXPECTED_DIGEST);
        let mut cache = make_nonce_cache();
        let result = validate_username_token(&xml, &get_password, &mut cache, 300, test_now());
        assert_eq!(
            result.unwrap(),
            "admin",
            "Constant-time digest path must succeed"
        );
    }

    // ── Finding #12: Unknown user and bad digest produce identical fault reason ─

    #[test]
    fn unknown_user_and_bad_digest_produce_same_fault_reason() {
        // Auth failure due to unknown user.
        let xml_unknown = format!(
            r#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <wsse:UsernameToken>
    <wsse:Username>no_such_user</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">{TEST_EXPECTED_DIGEST}</wsse:Password>
    <wsse:Nonce>{TEST_NONCE}</wsse:Nonce>
    <wsu:Created>{TEST_CREATED}</wsu:Created>
  </wsse:UsernameToken>
</wsse:Security>"#
        );
        // Auth failure due to wrong digest (correct user).
        let bad_digest = compute_digest(TEST_NONCE, TEST_CREATED, "wrongpassword").unwrap();
        let xml_bad_digest = security_xml_digest(TEST_NONCE, TEST_CREATED, &bad_digest);

        let mut cache1 = make_nonce_cache();
        let fault_unknown = validate_username_token(
            xml_unknown.as_bytes(),
            &get_password,
            &mut cache1,
            300,
            test_now(),
        )
        .unwrap_err();

        let mut cache2 = make_nonce_cache();
        let fault_bad =
            validate_username_token(&xml_bad_digest, &get_password, &mut cache2, 300, test_now())
                .unwrap_err();

        assert_eq!(
            fault_unknown.reason, fault_bad.reason,
            "Unknown user and bad digest must produce the same public fault reason (Finding #12). \
             Got unknown={:?} bad_digest={:?}",
            fault_unknown.reason, fault_bad.reason
        );
    }
}