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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
// ServerBuilder + SoapService — integration layer composing all components.
// Produces an axum::Router serving SOAP 1.2 requests.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use axum::{
    extract::{DefaultBodyLimit, MatchedPath, Query, State},
    http::{HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    routing::post,
    Router,
};
use bytes::Bytes;
use chrono::Utc;
use tokio::sync::Mutex;

use crate::dispatch::{self, DispatchError, DispatchTable};
use crate::envelope::{
    detect_soap_version, parse_envelope, response_content_type, serialize_envelope,
};
use crate::fault::SoapFault;
use crate::handler::SoapHandler;
use crate::qname::QName;
use crate::wsdl::definitions::SoapVersion;
use crate::wsdl::resolver::{
    resolve_wsdl, rewrite_wsdl_address, rewrite_wsdl_address_for_service, WsdlLoader,
};
use crate::wssec::{nonce_cache::RotatingNonceCache, username_token::validate_username_token};
use crate::xsd::types::TypeRegistry;

/// Default nonce cache half-window in seconds (150s → 300s total replay window).
const DEFAULT_NONCE_CACHE_HALF_WINDOW_SECS: u64 = 150;
/// Default timestamp tolerance in seconds (±300s).
const DEFAULT_TIMESTAMP_TOLERANCE_SECS: i64 = 300;
/// Default maximum request body size: 2 MiB.
const DEFAULT_MAX_BODY_BYTES: usize = 2 * 1024 * 1024;

/// Authentication function type: takes a raw Authorization header value and returns a username if valid.
type AuthFn = Option<Arc<dyn Fn(&str) -> Option<String> + Send + Sync + 'static>>;

// ── ServerBuilder ─────────────────────────────────────────────────────────────

/// Builder for a SoapService. Accumulates WSDL source, handlers, auth config, and routing.
pub struct ServerBuilder {
    wsdl_bytes: Option<Vec<u8>>,
    wsdl_path: Option<std::path::PathBuf>,
    custom_loader: Option<Arc<dyn WsdlLoader>>,
    handlers: HashMap<String, Arc<dyn SoapHandler>>,
    default_handler: Option<Arc<dyn SoapHandler>>,
    auth_fn: AuthFn,
    auth_bypass: HashSet<String>,
    mount_path: String,
    timestamp_tolerance_secs: i64,
    nonce_cache_half_window_secs: u64,
    max_body_bytes: usize,
}

impl ServerBuilder {
    fn new() -> Self {
        Self {
            wsdl_bytes: None,
            wsdl_path: None,
            custom_loader: None,
            handlers: HashMap::new(),
            default_handler: None,
            auth_fn: None,
            auth_bypass: HashSet::new(),
            mount_path: "/soap".to_string(),
            timestamp_tolerance_secs: DEFAULT_TIMESTAMP_TOLERANCE_SECS,
            nonce_cache_half_window_secs: DEFAULT_NONCE_CACHE_HALF_WINDOW_SECS,
            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
        }
    }

    /// Load WSDL from the given file path at build time.
    pub fn from_wsdl_file(path: impl Into<std::path::PathBuf>) -> Self {
        let mut builder = Self::new();
        builder.wsdl_path = Some(path.into());
        builder
    }

    /// Use the provided WSDL bytes directly (no file I/O).
    /// For WSDLs with external imports, use `from_wsdl_file` or `from_wsdl_bytes_with_loader`.
    pub fn from_wsdl_bytes(bytes: impl Into<Vec<u8>>) -> Self {
        let mut builder = Self::new();
        builder.wsdl_bytes = Some(bytes.into());
        builder
    }

    /// Use the provided WSDL bytes with a custom loader for resolving external imports.
    /// The loader is invoked for any `wsdl:import` or `xs:import` location strings.
    pub fn from_wsdl_bytes_with_loader(
        bytes: impl Into<Vec<u8>>,
        loader: impl WsdlLoader + 'static,
    ) -> Self {
        let mut builder = Self::new();
        builder.wsdl_bytes = Some(bytes.into());
        builder.custom_loader = Some(Arc::new(loader));
        builder
    }

    /// Register a handler for the named WSDL operation.
    pub fn handler(mut self, operation: impl Into<String>, handler: impl SoapHandler) -> Self {
        self.handlers.insert(operation.into(), Arc::new(handler));
        self
    }

    /// Register a catch-all handler invoked for any WSDL operation without a specific handler.
    /// When set, `build()` will not return `UnregisteredOperation` for unhandled operations.
    pub fn default_handler(mut self, handler: impl SoapHandler) -> Self {
        self.default_handler = Some(Arc::new(handler));
        self
    }

    /// Configure credential lookup, enabling WS-Security enforcement. The closure is called
    /// with a username and must return the stored password (plaintext) for that user, or
    /// `None` if the user does not exist.
    ///
    /// If `auth` is never called, the server runs **unauthenticated**: WS-Security headers
    /// are not required or validated on any operation. Calling `auth` enables WS-Security
    /// enforcement on all non-bypassed operations (see [`auth_bypass`](Self::auth_bypass)).
    pub fn auth<F>(mut self, f: F) -> Self
    where
        F: Fn(&str) -> Option<String> + Send + Sync + 'static,
    {
        self.auth_fn = Some(Arc::new(f));
        self
    }

    /// Mark the named operations as auth-bypassed (no WS-Security header required).
    /// Accepts any iterable of string-like values.
    pub fn auth_bypass<I, S>(mut self, ops: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for op in ops {
            self.auth_bypass.insert(op.into());
        }
        self
    }

    /// Override the mount path (default: "/soap").
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.mount_path = path.into();
        self
    }

    /// Override the WS-Security timestamp tolerance in seconds (default: 300).
    pub fn timestamp_tolerance_secs(mut self, secs: i64) -> Self {
        self.timestamp_tolerance_secs = secs;
        self
    }

    /// Set the maximum allowed request body size in bytes (default: 2 MiB).
    ///
    /// Requests whose body exceeds this limit are rejected before XML parsing
    /// begins, preventing memory exhaustion from oversized payloads.
    pub fn max_body_bytes(mut self, bytes: usize) -> Self {
        self.max_body_bytes = bytes;
        self
    }

    /// Build the SoapService, resolving the WSDL and building the dispatch table.
    /// Returns an error if the WSDL cannot be resolved or the dispatch table is inconsistent.
    pub fn build(self) -> Result<SoapService, BuildError> {
        // Step 1: Load WSDL bytes, preserving the file path for loader selection.
        let (wsdl_bytes, wsdl_file_path) = match (self.wsdl_bytes, self.wsdl_path) {
            (Some(bytes), _) => (bytes, None),
            (None, Some(path)) => {
                let bytes = std::fs::read(&path).map_err(|e| BuildError::WsdlIo(e.to_string()))?;
                (bytes, Some(path))
            }
            (None, None) => return Err(BuildError::MissingWsdl),
        };

        // Step 2: Resolve WSDL (pass 1 + pass 2).
        // Loader selection priority:
        //   1. custom_loader (explicitly provided via from_wsdl_bytes_with_loader)
        //   2. FileWsdlLoader (when loaded from a file path)
        //   3. NoOpLoader (embedded bytes — imports unsupported)
        let mut visited = HashSet::new();
        let resolved = if let Some(ref loader) = self.custom_loader {
            resolve_wsdl(&wsdl_bytes, loader.as_ref(), &mut visited)
                .map_err(|e| BuildError::WsdlParse(e.to_string()))?
        } else if let Some(ref path) = wsdl_file_path {
            let base_dir = path
                .parent()
                .unwrap_or_else(|| std::path::Path::new("."))
                .to_path_buf();
            let loader = FileWsdlLoader { base_dir };
            resolve_wsdl(&wsdl_bytes, &loader, &mut visited)
                .map_err(|e| BuildError::WsdlParse(e.to_string()))?
        } else {
            let loader = NoOpLoader;
            resolve_wsdl(&wsdl_bytes, &loader, &mut visited)
                .map_err(|e| BuildError::WsdlParse(e.to_string()))?
        };

        // Step 3: Build dispatch table(s).
        // If WSDL has multiple services, build per-service dispatch tables.
        // Otherwise, build a single dispatch table for backward compatibility.
        let service_names: Vec<String> = resolved.definition.services.keys().cloned().collect();
        let is_multi_service = service_names.len() > 1;

        let (dispatch_table, service_tables, service_path_names) = if is_multi_service {
            // Multi-service mode: build one table per service, mount at per-service path.
            // The handlers HashMap is shared across services — each service only uses the
            // handlers for operations it owns. We clone handlers for each service.
            let mut service_tables: HashMap<String, Arc<DispatchTable>> = HashMap::new();
            let mut service_path_names: HashMap<String, String> = HashMap::new();
            let mut all_ops_in_all_services: HashSet<String> = HashSet::new();

            // First pass: collect which ops belong to each service.
            for svc_name in &service_names {
                let svc = resolved
                    .definition
                    .services
                    .get(svc_name)
                    .ok_or_else(|| BuildError::UnknownService(svc_name.clone()))?;
                for port in &svc.ports {
                    let binding_local = &port.binding.local_name;
                    if let Some(binding) = resolved.definition.bindings.get(binding_local) {
                        for binding_op in &binding.operations {
                            all_ops_in_all_services.insert(binding_op.name.clone());
                        }
                    }
                }
            }

            // Verify no handlers registered for unknown operations.
            for handler_name in self.handlers.keys() {
                if !all_ops_in_all_services.contains(handler_name) {
                    return Err(BuildError::UnknownOperation(handler_name.clone()));
                }
            }

            for svc_name in &service_names {
                let svc = resolved
                    .definition
                    .services
                    .get(svc_name)
                    .ok_or_else(|| BuildError::UnknownService(svc_name.clone()))?;

                // Collect ops for this service and build handlers subset.
                let mut svc_op_names: Vec<String> = Vec::new();
                for port in &svc.ports {
                    let binding_local = &port.binding.local_name;
                    if let Some(binding) = resolved.definition.bindings.get(binding_local) {
                        for binding_op in &binding.operations {
                            svc_op_names.push(binding_op.name.clone());
                        }
                    }
                }

                // Build handlers for this service only.
                let mut svc_handlers: HashMap<String, Arc<dyn SoapHandler>> = HashMap::new();
                for op_name in &svc_op_names {
                    if let Some(h) = self.handlers.get(op_name) {
                        svc_handlers.insert(op_name.clone(), h.clone());
                    }
                }

                let table = dispatch::build_dispatch_table_for_service(
                    svc_name,
                    &resolved,
                    svc_handlers,
                    &self.auth_bypass,
                    self.default_handler.clone(),
                )
                .map_err(|e| match e {
                    DispatchError::UnregisteredOperation(op) => {
                        BuildError::UnregisteredOperation(op)
                    }
                    DispatchError::UnknownOperation(op) => BuildError::UnknownOperation(op),
                    DispatchError::UnresolvableInputType { op, element, type_ref } => {
                        BuildError::WsdlParse(format!(
                            "Operation '{op}' input element '{element}' references unresolvable type '{type_ref}'"
                        ))
                    }
                })?;

                // Derive the route path from the first port's address.
                let path = svc
                    .ports
                    .first()
                    .map(|p| extract_path_from_url(&p.address))
                    .unwrap_or_else(|| format!("/{}", svc_name.to_lowercase()));

                service_path_names.insert(path.clone(), svc_name.clone());
                service_tables.insert(path, Arc::new(table));
            }

            // Build a combined table for the dispatch_table field (used for single-route fallback).
            // Use the first service's table as the primary — in multi-service mode,
            // routing uses service_tables exclusively.
            let first_table = service_tables
                .values()
                .next()
                .cloned()
                .unwrap_or_else(|| Arc::new(DispatchTable::empty()));

            (first_table, service_tables, service_path_names)
        } else {
            // Single-service mode: build one dispatch table, no per-service tables.
            let table = dispatch::build_dispatch_table(
                &resolved,
                self.handlers,
                &self.auth_bypass,
                self.default_handler,
            )
            .map_err(|e| match e {
                DispatchError::UnregisteredOperation(op) => BuildError::UnregisteredOperation(op),
                DispatchError::UnknownOperation(op) => BuildError::UnknownOperation(op),
                DispatchError::UnresolvableInputType { op, element, type_ref } => {
                    BuildError::WsdlParse(format!(
                        "Operation '{op}' input element '{element}' references unresolvable type '{type_ref}'"
                    ))
                }
            })?;
            (Arc::new(table), HashMap::new(), HashMap::new())
        };

        let type_registry = Arc::new(resolved.type_registry);

        Ok(SoapService {
            dispatch_table,
            service_tables,
            service_path_names,
            type_registry,
            wsdl_raw: Arc::new(wsdl_bytes),
            auth_fn: self.auth_fn,
            nonce_cache: Arc::new(Mutex::new(RotatingNonceCache::new(
                self.nonce_cache_half_window_secs,
            ))),
            timestamp_tolerance_secs: self.timestamp_tolerance_secs,
            mount_path: self.mount_path,
            max_body_bytes: self.max_body_bytes,
        })
    }
}

// ── Build errors ──────────────────────────────────────────────────────────────

/// Errors that can occur during ServerBuilder::build().
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    #[error("No WSDL source provided — call from_wsdl_bytes() or from_wsdl_file()")]
    MissingWsdl,
    #[error("Failed to read WSDL file: {0}")]
    WsdlIo(String),
    #[error("Failed to parse or resolve WSDL: {0}")]
    WsdlParse(String),
    #[error("WSDL operation '{0}' has no registered handler")]
    UnregisteredOperation(String),
    #[error("Registered handler '{0}' has no matching WSDL operation")]
    UnknownOperation(String),
    #[error("WSDL service '{0}' not found in resolved definition")]
    UnknownService(String),
}

// ── WSDL loader (no-op for embedded/self-contained WSDLs) ────────────────────

struct NoOpLoader;

impl WsdlLoader for NoOpLoader {
    fn load(&self, location: &str) -> Result<Vec<u8>, crate::wsdl::parser::WsdlError> {
        Err(crate::wsdl::parser::WsdlError::MalformedXml(format!(
            "External WSDL import '{location}' not supported in embedded mode"
        )))
    }
}

/// A WsdlLoader that resolves import locations relative to a base directory on the filesystem.
/// Used automatically when ServerBuilder::from_wsdl_file() is called.
pub struct FileWsdlLoader {
    base_dir: std::path::PathBuf,
}

impl WsdlLoader for FileWsdlLoader {
    fn load(&self, location: &str) -> Result<Vec<u8>, crate::wsdl::parser::WsdlError> {
        // Resolve the location relative to the base directory, normalizing ".." components.
        let raw_path = self.base_dir.join(location);
        let path = normalize_path(&raw_path);
        std::fs::read(&path).map_err(|e| {
            crate::wsdl::parser::WsdlError::MalformedXml(format!(
                "Failed to load WSDL import '{location}' from '{}': {e}",
                path.display()
            ))
        })
    }
}

/// Normalize a path by resolving ".." components without requiring the path to exist.
/// This is needed because std::fs::canonicalize requires the path to exist on disk.
fn normalize_path(path: &std::path::Path) -> std::path::PathBuf {
    use std::path::Component;
    let mut normalized = std::path::PathBuf::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                normalized.pop();
            }
            Component::CurDir => {}
            other => {
                normalized.push(other);
            }
        }
    }
    normalized
}

/// Extract the path component from a URL string (e.g., "http://host/soap/ServiceA" → "/soap/ServiceA").
/// Falls back to "/" if the URL has no path.
fn extract_path_from_url(url: &str) -> String {
    if let Some(after_scheme) = url.split_once("://").map(|x| x.1) {
        if let Some(slash_pos) = after_scheme.find('/') {
            return after_scheme[slash_pos..].to_string();
        }
        return "/".to_string();
    }
    if url.starts_with('/') {
        url.to_string()
    } else {
        format!("/{url}")
    }
}

// ── SoapService ───────────────────────────────────────────────────────────────

/// A fully configured SOAP service that can be converted into an axum Router.
pub struct SoapService {
    dispatch_table: Arc<DispatchTable>,
    /// Per-service dispatch tables keyed by route path.
    /// Non-empty when the WSDL has multiple services (multi-service mode).
    /// Empty in single-service mode (backward-compat).
    service_tables: HashMap<String, Arc<DispatchTable>>,
    /// Maps route path → WSDL service name (for per-service WSDL address rewriting).
    /// Non-empty only in multi-service mode.
    service_path_names: HashMap<String, String>,
    type_registry: Arc<TypeRegistry>,
    wsdl_raw: Arc<Vec<u8>>,
    auth_fn: AuthFn,
    nonce_cache: Arc<Mutex<RotatingNonceCache>>,
    timestamp_tolerance_secs: i64,
    mount_path: String,
    max_body_bytes: usize,
}

impl std::fmt::Debug for SoapService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SoapService")
            .field("mount_path", &self.mount_path)
            .finish_non_exhaustive()
    }
}

impl SoapService {
    /// Convert this service into an axum Router with POST (SOAP) and GET (?wsdl) routes.
    /// The returned Router is composable with Router::merge().
    ///
    /// In multi-service mode: registers one POST route per service path (from service_tables).
    /// In single-service mode: registers a single POST + GET route at mount_path (backward-compat).
    pub fn into_router(self) -> Router {
        let max_body = self.max_body_bytes;
        if !self.service_tables.is_empty() {
            // Multi-service mode: each service gets its own POST + GET (?wsdl) route.
            let state = Arc::new(self);
            let mut router = Router::new();
            // Collect (path, table, service_name) triples before entering the loop to
            // avoid holding immutable borrows on `state` while we call `state.clone()`.
            let routes: Vec<(String, Arc<DispatchTable>, String)> = state
                .service_tables
                .iter()
                .map(|(path, table)| {
                    let svc_name = state
                        .service_path_names
                        .get(path)
                        .cloned()
                        .unwrap_or_default();
                    (path.clone(), table.clone(), svc_name)
                })
                .collect();
            for (path, table, service_name) in routes {
                let route_state = SoapServiceRoute {
                    svc: state.clone(),
                    table,
                    service_name,
                };
                router = router.route(
                    &path,
                    post(soap_post_handler_for_route)
                        .get(wsdl_get_handler_for_route)
                        .with_state(route_state),
                );
            }
            router.layer(DefaultBodyLimit::max(max_body))
        } else {
            // Single-service mode: single route (backward-compat).
            let mount_path = self.mount_path.clone();
            let state = Arc::new(self);
            Router::new()
                .route(&mount_path, post(soap_post_handler).get(wsdl_get_handler))
                .with_state(state)
                .layer(DefaultBodyLimit::max(max_body))
        }
    }
}

/// Thin wrapper for per-service route state in multi-service mode.
#[derive(Clone)]
struct SoapServiceRoute {
    svc: Arc<SoapService>,
    table: Arc<DispatchTable>,
    /// The WSDL service name this route belongs to (used for per-service WSDL address rewriting).
    service_name: String,
}

// ── Helper: return a 500 SOAP fault response ──────────────────────────────────

fn fault_response(fault: SoapFault, version: crate::wsdl::definitions::SoapVersion) -> Response {
    let bytes = fault.to_xml_bytes_versioned(&version);
    let ct = response_content_type(&version);
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        [("Content-Type", ct)],
        bytes,
    )
        .into_response()
}

// ── Helper: extract QName of the first element in body_element bytes ──────────

fn extract_body_qname(body_bytes: &[u8]) -> Result<QName, SoapFault> {
    use quick_xml::events::Event;
    use quick_xml::NsReader;

    let mut reader = NsReader::from_reader(body_bytes);
    reader.config_mut().trim_text(true);

    loop {
        match reader
            .read_resolved_event()
            .map_err(|e| SoapFault::sender(format!("XML parse error in body: {e}")))?
        {
            (_, Event::Eof) => {
                return Err(SoapFault::sender("Empty SOAP Body element"));
            }
            (resolved_ns, Event::Start(e)) | (resolved_ns, Event::Empty(e)) => {
                let local = std::str::from_utf8(e.local_name().as_ref())
                    .map_err(|e| SoapFault::sender(format!("Invalid UTF-8 in element name: {e}")))?
                    .to_string();
                let ns = match resolved_ns {
                    quick_xml::name::ResolveResult::Bound(ns) => std::str::from_utf8(ns.0)
                        .map_err(|e| SoapFault::sender(format!("Invalid UTF-8 in namespace: {e}")))?
                        .to_string(),
                    _ => String::new(),
                };
                if ns.is_empty() {
                    return Ok(QName::local(&local));
                } else {
                    return Ok(QName::new(&ns, &local));
                }
            }
            _ => {}
        }
    }
}

// ── Helper: find the wsse:Security header bytes from header_children ──────────

/// WS-Security namespace URI.
const WSSE_NS: &str =
    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";

/// Match a header child by WS-Security QName: local name `Security` in the
/// WS-Security namespace.  A header element whose root tag is merely named
/// `Security` in a different namespace is NOT selected.
fn find_security_header(header_children: &[Bytes]) -> Option<&Bytes> {
    use quick_xml::events::Event;
    use quick_xml::NsReader;

    for child in header_children {
        let mut reader = NsReader::from_reader(child.as_ref());
        reader.config_mut().trim_text(true);
        // We only need the first start/empty event to identify the root element.
        loop {
            match reader.read_resolved_event() {
                Ok((resolved_ns, Event::Start(e))) | Ok((resolved_ns, Event::Empty(e))) => {
                    let local = e.local_name();
                    let local_str = std::str::from_utf8(local.as_ref()).unwrap_or("");
                    if local_str == "Security" {
                        if let quick_xml::name::ResolveResult::Bound(ns) = resolved_ns {
                            if std::str::from_utf8(ns.0).unwrap_or("") == WSSE_NS {
                                return Some(child);
                            }
                        }
                    }
                    break; // Only examine the root element of each child.
                }
                Ok((_, Event::Eof)) | Err(_) => break,
                _ => {}
            }
        }
    }
    None
}

// ── axum handler: POST /soap ──────────────────────────────────────────────────

async fn soap_post_handler(
    State(svc): State<Arc<SoapService>>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    // Step 1: Detect SOAP version from Content-Type.
    let content_type = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    let soap_version = match detect_soap_version(content_type) {
        Ok(v) => v,
        Err(fault) => return fault_response(fault, crate::wsdl::definitions::SoapVersion::Soap12),
    };

    // Step 2: Parse envelope.
    let envelope = match parse_envelope(&body) {
        Ok(e) => e,
        Err(fault) => return fault_response(fault, soap_version),
    };

    // Step 3: Extract body first-child QName.
    let body_qname = match extract_body_qname(&envelope.body_element) {
        Ok(q) => q,
        Err(fault) => return fault_response(fault, envelope.soap_version.clone()),
    };

    // Step 4: Route to dispatch entry.
    let soap_action = headers
        .get("soapaction")
        .or_else(|| headers.get("SOAPAction"))
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim_matches('"'));

    let entry = match dispatch::route(&svc.dispatch_table, &body_qname, soap_action) {
        Ok(e) => e,
        Err(fault) => return fault_response(fault, envelope.soap_version.clone()),
    };

    // Step 5: If auth required, validate WS-Security UsernameToken.
    // Auth is only enforced when a credential validator (`auth_fn`) is configured
    // via `ServerBuilder::auth`. With no validator the server runs unauthenticated
    // — see the `auth` builder docs.
    if entry.auth_required && svc.auth_fn.is_some() {
        match find_security_header(&envelope.header_children) {
            None => {
                return fault_response(
                    SoapFault::sender("WS-Security header required but not provided"),
                    envelope.soap_version.clone(),
                );
            }
            Some(security_bytes) => {
                let auth_fn = match &svc.auth_fn {
                    Some(f) => f.clone(),
                    None => {
                        return fault_response(
                            SoapFault::sender(
                                "Authentication required but no credential store configured",
                            ),
                            envelope.soap_version.clone(),
                        );
                    }
                };
                let mut nonce_cache = svc.nonce_cache.lock().await;
                let now = Utc::now();
                if let Err(fault) = validate_username_token(
                    security_bytes,
                    auth_fn.as_ref(),
                    &mut nonce_cache,
                    svc.timestamp_tolerance_secs,
                    now,
                ) {
                    return fault_response(fault, envelope.soap_version.clone());
                }
            }
        }
    }

    // Step 6: XSD structural validation.
    if let Err(fault) = dispatch::validate_request(
        &envelope.body_element,
        &svc.type_registry,
        entry.validation_type.as_ref(),
    ) {
        return fault_response(fault, envelope.soap_version.clone());
    }

    // Step 7: Invoke handler (pass header fragments for WS-Addressing/WS-Security use).
    let response_body = match entry
        .handler
        .handle_with_headers(envelope.body_element, &envelope.header_children)
        .await
    {
        Ok(bytes) => bytes,
        Err(fault) => return fault_response(fault, envelope.soap_version.clone()),
    };

    // Step 8: Serialize into SOAP envelope.
    // Use the envelope namespace as the single authoritative SOAP version source for both
    // serialization and response Content-Type (BLOCK-SS-C04 fix). The Content-Type header
    // version is a hint; the envelope namespace is what actually identifies the SOAP version.
    let response_version = envelope.soap_version.clone();
    let envelope_bytes = serialize_envelope(response_body, response_version.clone());
    let content_type_value = response_content_type(&response_version);

    (
        StatusCode::OK,
        [("Content-Type", content_type_value)],
        envelope_bytes,
    )
        .into_response()
}

// ── axum handler: POST per-service route (multi-service mode) ─────────────────

async fn soap_post_handler_for_route(
    State(route_state): State<SoapServiceRoute>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    let svc = &route_state.svc;
    let table = &route_state.table;

    // Step 1: Detect SOAP version from Content-Type.
    let content_type = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    let soap_version = match detect_soap_version(content_type) {
        Ok(v) => v,
        Err(fault) => return fault_response(fault, SoapVersion::Soap12),
    };

    // Step 2: Parse envelope.
    let envelope = match parse_envelope(&body) {
        Ok(e) => e,
        Err(fault) => return fault_response(fault, soap_version),
    };

    // Step 3: Extract body first-child QName.
    let body_qname = match extract_body_qname(&envelope.body_element) {
        Ok(q) => q,
        Err(fault) => return fault_response(fault, envelope.soap_version.clone()),
    };

    // Step 4: Route using this service's specific dispatch table.
    let soap_action = headers
        .get("soapaction")
        .or_else(|| headers.get("SOAPAction"))
        .and_then(|v| v.to_str().ok())
        .map(|s| s.trim_matches('"'));

    let entry = match dispatch::route(table, &body_qname, soap_action) {
        Ok(e) => e,
        Err(fault) => return fault_response(fault, envelope.soap_version.clone()),
    };

    // Step 5: If auth required, validate WS-Security UsernameToken.
    // Auth is only enforced when a credential validator (`auth_fn`) is configured
    // via `ServerBuilder::auth`. With no validator the server runs unauthenticated
    // — see the `auth` builder docs.
    if entry.auth_required && svc.auth_fn.is_some() {
        match find_security_header(&envelope.header_children) {
            None => {
                return fault_response(
                    SoapFault::sender("WS-Security header required but not provided"),
                    envelope.soap_version.clone(),
                );
            }
            Some(security_bytes) => {
                let auth_fn = match &svc.auth_fn {
                    Some(f) => f.clone(),
                    None => {
                        return fault_response(
                            SoapFault::sender(
                                "Authentication required but no credential store configured",
                            ),
                            envelope.soap_version.clone(),
                        );
                    }
                };
                let mut nonce_cache = svc.nonce_cache.lock().await;
                let now = Utc::now();
                if let Err(fault) = validate_username_token(
                    security_bytes,
                    auth_fn.as_ref(),
                    &mut nonce_cache,
                    svc.timestamp_tolerance_secs,
                    now,
                ) {
                    return fault_response(fault, envelope.soap_version.clone());
                }
            }
        }
    }

    // Step 6: XSD structural validation.
    if let Err(fault) = dispatch::validate_request(
        &envelope.body_element,
        &svc.type_registry,
        entry.validation_type.as_ref(),
    ) {
        return fault_response(fault, envelope.soap_version.clone());
    }

    // Step 7: Invoke handler (pass header fragments for WS-Addressing/WS-Security use).
    let response_body = match entry
        .handler
        .handle_with_headers(envelope.body_element, &envelope.header_children)
        .await
    {
        Ok(bytes) => bytes,
        Err(fault) => return fault_response(fault, envelope.soap_version.clone()),
    };

    // Step 8: Serialize into SOAP envelope.
    // Use the envelope namespace as the single authoritative SOAP version source for both
    // serialization and response Content-Type (BLOCK-SS-C04 fix).
    let response_version = envelope.soap_version.clone();
    let envelope_bytes = serialize_envelope(response_body, response_version.clone());
    let content_type_value = response_content_type(&response_version);

    (
        StatusCode::OK,
        [("Content-Type", content_type_value)],
        envelope_bytes,
    )
        .into_response()
}

// ── axum handler: GET /soap?wsdl ──────────────────────────────────────────────

#[derive(serde::Deserialize)]
struct WsdlQuery {
    wsdl: Option<String>,
}

async fn wsdl_get_handler(
    matched_path: Option<MatchedPath>,
    State(svc): State<Arc<SoapService>>,
    Query(params): Query<WsdlQuery>,
    headers: HeaderMap,
) -> Response {
    // Only respond when ?wsdl query parameter is present.
    if params.wsdl.is_none() {
        return StatusCode::NOT_FOUND.into_response();
    }

    // Build the server URL from Host header (or X-Forwarded-Host).
    let host = headers
        .get("x-forwarded-host")
        .or_else(|| headers.get("host"))
        .and_then(|v| v.to_str().ok())
        .unwrap_or("localhost");

    // Use the matched route path (per-service in multi-service mode, mount_path in single-service).
    // MatchedPath is always present when registered via router.route() — use Option as fallback.
    let path = matched_path
        .as_ref()
        .map(|mp| mp.as_str())
        .unwrap_or(&svc.mount_path);

    let server_url = format!("http://{host}{path}");

    let rewritten = rewrite_wsdl_address(&svc.wsdl_raw, &server_url);

    (
        StatusCode::OK,
        [("Content-Type", "text/xml; charset=utf-8")],
        rewritten,
    )
        .into_response()
}

// ── axum handler: GET /soap?wsdl (per-service route in multi-service mode) ───

async fn wsdl_get_handler_for_route(
    matched_path: Option<MatchedPath>,
    State(route_state): State<SoapServiceRoute>,
    Query(params): Query<WsdlQuery>,
    headers: HeaderMap,
) -> Response {
    // Only respond when ?wsdl query parameter is present.
    if params.wsdl.is_none() {
        return StatusCode::NOT_FOUND.into_response();
    }

    let svc = &route_state.svc;

    // Build the server URL from Host header (or X-Forwarded-Host).
    let host = headers
        .get("x-forwarded-host")
        .or_else(|| headers.get("host"))
        .and_then(|v| v.to_str().ok())
        .unwrap_or("localhost");

    let path = matched_path
        .as_ref()
        .map(|mp| mp.as_str())
        .unwrap_or(&svc.mount_path);

    let server_url = format!("http://{host}{path}");

    // In multi-service mode, rewrite ONLY the address for the matched service/port.
    // Other services' addresses are preserved so that generated clients bind each service
    // to its own endpoint rather than all to the current request path.
    let rewritten =
        rewrite_wsdl_address_for_service(&svc.wsdl_raw, &server_url, &route_state.service_name);

    (
        StatusCode::OK,
        [("Content-Type", "text/xml; charset=utf-8")],
        rewritten,
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fault::SoapFault;
    use crate::handler::FnHandler;
    use bytes::Bytes;

    const MINIMAL_WSDL: &[u8] = br#"<?xml version="1.0" encoding="utf-8"?>
<wsdl:definitions
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap12/"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:tns="http://example.com/test"
    targetNamespace="http://example.com/test">
    <wsdl:types>
        <xs:schema targetNamespace="http://example.com/test" elementFormDefault="qualified">
            <xs:element name="Ping">
                <xs:complexType><xs:sequence/></xs:complexType>
            </xs:element>
            <xs:element name="PingResponse">
                <xs:complexType><xs:sequence/></xs:complexType>
            </xs:element>
        </xs:schema>
    </wsdl:types>
    <wsdl:message name="PingRequest">
        <wsdl:part name="parameters" element="tns:Ping"/>
    </wsdl:message>
    <wsdl:message name="PingResponse">
        <wsdl:part name="parameters" element="tns:PingResponse"/>
    </wsdl:message>
    <wsdl:portType name="TestPortType">
        <wsdl:operation name="Ping">
            <wsdl:input message="tns:PingRequest"/>
            <wsdl:output message="tns:PingResponse"/>
        </wsdl:operation>
    </wsdl:portType>
    <wsdl:binding name="TestBinding" type="tns:TestPortType">
        <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
        <wsdl:operation name="Ping">
            <soap:operation soapAction="http://example.com/test/Ping"/>
            <wsdl:input><soap:body use="literal"/></wsdl:input>
            <wsdl:output><soap:body use="literal"/></wsdl:output>
        </wsdl:operation>
    </wsdl:binding>
    <wsdl:service name="TestService">
        <wsdl:port name="TestPort" binding="tns:TestBinding">
            <soap:address location="http://localhost/soap"/>
        </wsdl:port>
    </wsdl:service>
</wsdl:definitions>"#;

    #[test]
    fn server_builder_builds_without_panic() {
        let svc = ServerBuilder::from_wsdl_bytes(MINIMAL_WSDL)
            .handler(
                "Ping",
                FnHandler::new(|_body: Bytes| async move {
                    Ok::<Bytes, SoapFault>(Bytes::from_static(b"<PingResponse/>"))
                }),
            )
            .auth_bypass(["Ping"])
            .build();
        assert!(svc.is_ok(), "build should succeed: {:?}", svc.err());
    }

    #[test]
    fn server_builder_into_router_returns_router() {
        let svc = ServerBuilder::from_wsdl_bytes(MINIMAL_WSDL)
            .handler(
                "Ping",
                FnHandler::new(|_body: Bytes| async move {
                    Ok::<Bytes, SoapFault>(Bytes::from_static(b"<PingResponse/>"))
                }),
            )
            .auth_bypass(["Ping"])
            .build()
            .unwrap();
        // into_router() must not panic
        let _router = svc.into_router();
    }

    #[test]
    fn server_builder_fails_with_unregistered_operation() {
        // WSDL has Ping but no handler is provided.
        let result = ServerBuilder::from_wsdl_bytes(MINIMAL_WSDL).build();
        assert!(result.is_err());
        match result.unwrap_err() {
            BuildError::UnregisteredOperation(op) => assert_eq!(op, "Ping"),
            other => panic!("Expected UnregisteredOperation, got: {other:?}"),
        }
    }

    #[test]
    fn server_builder_fails_with_unknown_handler_name() {
        let result = ServerBuilder::from_wsdl_bytes(MINIMAL_WSDL)
            .handler(
                "Ping",
                FnHandler::new(|_body: Bytes| async move {
                    Ok::<Bytes, SoapFault>(Bytes::from_static(b"<PingResponse/>"))
                }),
            )
            .handler(
                "NonExistentOp",
                FnHandler::new(|_body: Bytes| async move {
                    Ok::<Bytes, SoapFault>(Bytes::from_static(b"<resp/>"))
                }),
            )
            .auth_bypass(["Ping"])
            .build();
        assert!(result.is_err());
        match result.unwrap_err() {
            BuildError::UnknownOperation(op) => assert_eq!(op, "NonExistentOp"),
            other => panic!("Expected UnknownOperation, got: {other:?}"),
        }
    }

    #[test]
    fn fault_response_soap12_content_type() {
        use crate::wsdl::definitions::SoapVersion;
        let fault = SoapFault::sender("test");
        let response = fault_response(fault, SoapVersion::Soap12);
        let ct = response.headers().get("content-type").unwrap();
        assert_eq!(ct.to_str().unwrap(), "application/soap+xml; charset=utf-8");
    }

    #[test]
    fn fault_response_soap11_content_type() {
        use crate::wsdl::definitions::SoapVersion;
        let fault = SoapFault::sender("test");
        let response = fault_response(fault, SoapVersion::Soap11);
        let ct = response.headers().get("content-type").unwrap();
        assert_eq!(ct.to_str().unwrap(), "text/xml; charset=utf-8");
    }

    #[test]
    fn extract_body_qname_parses_namespaced_element() {
        let bytes = b"<tns:Ping xmlns:tns=\"http://example.com/test\"/>";
        let qname = extract_body_qname(bytes).unwrap();
        assert_eq!(qname.local_name, "Ping");
        assert_eq!(qname.namespace.as_deref(), Some("http://example.com/test"));
    }

    #[test]
    fn extract_body_qname_parses_unnamespaced_element() {
        let bytes = b"<Ping/>";
        let qname = extract_body_qname(bytes).unwrap();
        assert_eq!(qname.local_name, "Ping");
        assert_eq!(qname.namespace, None);
    }

    // ── find_security_header QName tests (Finding #9) ────────────────────────

    #[test]
    fn find_security_header_matches_wsse_namespace() {
        let wsse_header = Bytes::from_static(
            br#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:UsernameToken/></wsse:Security>"#,
        );
        let headers = [wsse_header.clone()];
        let result = find_security_header(&headers);
        assert!(
            result.is_some(),
            "Expected wsse:Security header to be found"
        );
        assert_eq!(result.unwrap(), &wsse_header);
    }

    #[test]
    fn find_security_header_ignores_non_wsse_security_element() {
        // A header element named "Security" but in a different namespace must NOT match.
        let fake_security = Bytes::from_static(
            br#"<ns:Security xmlns:ns="http://example.com/other">some content</ns:Security>"#,
        );
        let headers = [fake_security];
        let result = find_security_header(&headers);
        assert!(
            result.is_none(),
            "Security element in non-WSSE namespace should NOT be selected"
        );
    }

    #[test]
    fn find_security_header_ignores_element_containing_security_substring() {
        // An element that merely contains the word "Security" in its text must NOT match.
        let unrelated = Bytes::from_static(
            br#"<ns:Header xmlns:ns="http://example.com/other">Security policy here</ns:Header>"#,
        );
        let headers = [unrelated];
        let result = find_security_header(&headers);
        assert!(
            result.is_none(),
            "Header containing 'Security' substring but wrong QName should NOT be selected"
        );
    }

    #[test]
    fn find_security_header_returns_first_valid_wsse_header() {
        let fake_security = Bytes::from_static(
            br#"<ns:Security xmlns:ns="http://example.com/other">content</ns:Security>"#,
        );
        let real_security = Bytes::from_static(
            br#"<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"/>"#,
        );
        let headers = [fake_security, real_security.clone()];
        let result = find_security_header(&headers);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), &real_security);
    }

    // ── max_body_bytes builder option (Finding #10) ───────────────────────────

    #[test]
    fn server_builder_max_body_bytes_sets_field() {
        // Building with a custom max_body_bytes should succeed and produce a router.
        let svc = ServerBuilder::from_wsdl_bytes(MINIMAL_WSDL)
            .handler(
                "Ping",
                FnHandler::new(|_body: Bytes| async move {
                    Ok::<Bytes, SoapFault>(Bytes::from_static(b"<PingResponse/>"))
                }),
            )
            .auth_bypass(["Ping"])
            .max_body_bytes(512 * 1024) // 512 KiB
            .build()
            .expect("build should succeed");
        // Verify the field is stored correctly.
        assert_eq!(svc.max_body_bytes, 512 * 1024);
        // Router construction must not panic.
        let _router = svc.into_router();
    }

    #[test]
    fn server_builder_default_max_body_bytes_is_2mib() {
        let svc = ServerBuilder::from_wsdl_bytes(MINIMAL_WSDL)
            .handler(
                "Ping",
                FnHandler::new(|_body: Bytes| async move {
                    Ok::<Bytes, SoapFault>(Bytes::from_static(b"<PingResponse/>"))
                }),
            )
            .auth_bypass(["Ping"])
            .build()
            .expect("build should succeed");
        assert_eq!(svc.max_body_bytes, 2 * 1024 * 1024);
    }
}