xml-sec 0.1.23

Pure Rust XML Security: XMLDSig, XMLEnc, C14N. Drop-in replacement for libxmlsec1.
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
//! Continuations over the original verified document and operation state.

use super::*;
use structured_asn1::memory::{MemoryError, OwnedMap, OwnedText, OwnedVec, Work};

mod hash_uses;
pub use hash_uses::*;
mod key_receipt;
pub use key_receipt::*;

type RetainedOperation<'scope, 'inputs, W> = CapturedOperation<
    &'scope crate::policy::VerificationPolicy,
    &'scope VerificationOperationBudgets<'inputs>,
    ScopedCapture<'scope, W>,
>;

/// A verified request's scoped continuation. No document, policy, resolver or
/// budget is reconstructed when selecting a signature or replaying a reference.
pub struct VerifiedSession<'view, 'scope, 'inputs, W: Work> {
    view: DocumentView<'view>,
    context: &'scope VerifyContext<'inputs>,
    budgets: &'scope VerificationOperationBudgets<'inputs>,
    evidence: VerifyEvidence<OwnedVec<SignatureEvidence, W>>,
    operations: OwnedVec<RetainedOperation<'scope, 'inputs, W>, W>,
    resolver: UriReferenceResolver<'view>,
    work: &'scope W,
    replay_active: Cell<bool>,
}

/// Verify once, then continue within the same document generation, selected
/// provider, immutable policy, captured inputs and remaining operation budgets.
/// The callback cannot return document- or operation-borrowing handles.
pub fn with_verified_request<'inputs, W: Work, R>(
    document: &XmlDocument,
    context: &VerifyContext<'inputs>,
    request: &VerificationRequest<'inputs>,
    work: &W,
    continuation: impl for<'view, 'scope> FnOnce(
        VerifiedSession<'view, 'scope, 'inputs, W>,
    ) -> Result<R, DsigError>,
) -> Result<R, DsigError> {
    with_verified_document(
        document,
        context,
        request,
        ScopedRequestStorage(work),
        |view, context, budgets, evidence, operations, resolver| {
            continuation(VerifiedSession {
                view,
                context,
                budgets,
                evidence,
                operations,
                resolver,
                work,
                replay_active: Cell::new(false),
            })
        },
    )
}

/// The exact authenticated parent of a reference instruction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReferenceParent {
    /// Direct child of this selected Signature's SignedInfo.
    SignedInfo(NodeIdentity),
    /// Direct child of an authenticated original Manifest.
    Manifest(NodeIdentity),
}

/// Original reference metadata. Authentication of the instruction is separate
/// from the historical target digest result and conservative content coverage.
#[derive(Debug)]
pub struct AuthenticatedReference<'a> {
    /// Original document/generation-bound Reference identity.
    pub identity: NodeIdentity,
    /// Exact original SignedInfo or Manifest parent.
    pub parent: ReferenceParent,
    /// Original URI attribute, preserving omitted versus empty.
    pub uri: Option<&'a str>,
    /// Original Type attribute; not inferred from target shape.
    pub reference_type: Option<&'a str>,
    /// Historical result, absent when target execution was not completed.
    pub result: Option<&'a ReferenceResult>,
    /// Observed resource provenance, not a guess from URI spelling or a missing target.
    pub location: ReferenceLocation,
}

/// The original admitted resource route. `Unchecked` does not mean detached.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReferenceLocation {
    /// Original same-document target observed by reference verification.
    SameDocument(NodeIdentity),
    /// Admitted external lookup, with fingerprint only when bytes were supplied.
    Detached(Option<[u8; 32]>),
    /// No completed resource provenance was recorded.
    Unchecked,
}

/// Instruction discovery completeness, not a claim that every target is valid.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CatalogueCompleteness {
    /// All authenticated original instructions were visited.
    Complete,
    /// Original authenticated instructions were not processed by verification.
    Unchecked(NodeIdentity),
    /// An authenticated Manifest has not completed discovery/processing.
    Incomplete(NodeIdentity),
}

/// Visitor refusal remains distinct from XML/policy/resource processing errors.
#[derive(Debug)]
pub enum CatalogueError<E> {
    /// Original processing failure.
    Processing(DsigError),
    /// Original caller cause, without string conversion or boxing.
    Visitor(E),
}

fn flatten_catalogue<T, E>(
    result: Result<T, CatalogueError<CatalogueError<E>>>,
) -> Result<T, CatalogueError<E>> {
    match result {
        Ok(value) => Ok(value),
        Err(CatalogueError::Processing(error)) => Err(CatalogueError::Processing(error)),
        Err(CatalogueError::Visitor(error)) => Err(error),
    }
}

/// Where the original property supplies its URI. Attribute lookup uses an
/// expanded name; simple content joins only direct text/CDATA in source order.
#[derive(Clone, Copy, Debug)]
pub enum LexicalSource<'a> {
    /// Exact original attribute; absence is not an empty URI.
    Attribute {
        /// Namespace URI, or no namespace (default namespaces do not apply to attributes).
        namespace: Option<&'a str>,
        /// Local name within that namespace.
        local_name: &'a str,
    },
    /// Simple content; nested elements are malformed, comments/PIs contribute no text.
    SimpleContent,
}

/// Semantic resolution facts, independent of terminal processing failures.
#[derive(Debug)]
pub enum ReferenceResolution<'a> {
    /// The selected attribute is absent.
    Absent,
    /// Simple content contains an element child.
    Malformed,
    /// The original URI is outside the implemented same-document grammar.
    /// Policy and resource refusal are processing errors, not this disposition.
    Unsupported,
    /// The admitted URI selects caller-owned external data, not an original XML Reference.
    Detached,
    /// The ID is missing or ambiguous under the operation's ID registrations.
    Unresolved,
    /// Original target is not a ds:Reference.
    NotReference(NodeIdentity),
    /// Original target instruction is not authenticated by this selected Signature.
    Unauthenticated(NodeIdentity),
    /// Original authenticated instruction, including exact parent and historical status.
    Reference(AuthenticatedReference<'a>),
}

enum LexicalValue<'a, W: Work> {
    Borrowed(&'a str),
    Joined(OwnedText<W>),
}
impl<W: Work> LexicalValue<'_, W> {
    fn as_str(&self) -> &str {
        match self {
            Self::Borrowed(value) => value,
            // Appending original semantic str fragments preserves UTF-8. This
            // view must not perform another unadmitted full-prefix validation.
            Self::Joined(value) => value.as_str(),
        }
    }
}

/// A selected signature, bound to this request rather than an aggregate boolean.
pub struct SelectedSignature<'session, 'view, 'scope, 'inputs, W: Work, Q: Work = W> {
    session: &'session VerifiedSession<'view, 'scope, 'inputs, W>,
    index: usize,
    work: &'session Q,
    results: OwnedMap<NodeIdentity, (ReferenceSet, usize), Q>,
    replays: RefCell<OwnedVec<ReplayRecord, Q>>,
}

impl<'view, 'scope, 'inputs, W: Work> VerifiedSession<'view, 'scope, 'inputs, W> {
    /// Original immutable view; identities never cross a second parse/projection.
    pub fn view(&self) -> DocumentView<'view> {
        self.view
    }
    /// Results of the original verification. Inspect errors and target status
    /// independently of selected instruction authentication.
    pub fn evidence(&self) -> &VerifyEvidence<OwnedVec<SignatureEvidence, W>> {
        &self.evidence
    }

    /// Transfer independently owned result facts with their retained account.
    /// This transfers no document or operation borrow and no replay capability.
    pub fn into_evidence(self) -> VerifyEvidence<OwnedVec<SignatureEvidence, W>> {
        self.evidence
    }

    /// Select only a Signature whose original cryptographic decision succeeded.
    /// A failed child Manifest digest does not erase that decision.
    pub fn select_signature(
        &self,
        identity: NodeIdentity,
    ) -> Result<SelectedSignature<'_, 'view, 'scope, 'inputs, W>, DsigError> {
        self.select_signature_in(identity, self.work)
    }

    /// Continue an original authenticated signature with a separate current
    /// execution. Query scratch cannot escape the callback; the document,
    /// provider, policy, authentication and retained storage remain original.
    /// Selection, inspection, resolution and transform replay spend `work`;
    /// the original compiled policy's cumulative allowances are not reset.
    /// Use `select_signature` instead to retain producer-funded execution.
    pub fn with_query<Q: Work, R, E>(
        &self,
        identity: NodeIdentity,
        work: &Q,
        visitor: impl for<'query> FnOnce(
            SelectedSignature<'query, 'view, 'scope, 'inputs, W, Q>,
        ) -> Result<R, E>,
    ) -> Result<R, CatalogueError<E>> {
        let selected = self
            .select_signature_in(identity, work)
            .map_err(CatalogueError::Processing)?;
        visitor(selected).map_err(CatalogueError::Visitor)
    }

    fn select_signature_in<'query, Q: Work>(
        &'query self,
        identity: NodeIdentity,
        work: &'query Q,
    ) -> Result<SelectedSignature<'query, 'view, 'scope, 'inputs, W, Q>, DsigError> {
        let index = self.authenticated_signature_in(identity, work)?;
        let entry = &self.evidence.signatures()[index];
        let mut results = work.map();
        if let Ok(result) = &entry.result {
            for (set, entries) in [
                (ReferenceSet::SignedInfo, &result.signed_info_references),
                (ReferenceSet::Manifest, &result.manifest_references),
            ] {
                for (ordinal, reference) in entries.iter().enumerate() {
                    work.charge_work(1)?;
                    if let Some(node) = reference.reference_identity
                        && results.try_insert(node, (set, ordinal))?.is_some()
                    {
                        return Err(DsigError::InvalidRequest {
                            reason: "ambiguous original Reference evidence",
                        });
                    }
                }
            }
        }
        Ok(SelectedSignature {
            session: self,
            index,
            work,
            results,
            replays: RefCell::new(work.vector()),
        })
    }

    // Key-only queries reuse authentication without allocating a Reference
    // index or charging the completed verification's producer-local execution.
    fn authenticated_signature_in<Q: Work>(
        &self,
        identity: NodeIdentity,
        work: &Q,
    ) -> Result<usize, DsigError> {
        work.charge_work(1)?;
        self.view.resolve_node(identity)?;
        for (index, entry) in self.evidence.signatures().iter().enumerate() {
            work.charge_work(1)?;
            if entry.identity != identity {
                continue;
            }
            let retained = &self.operations[index];
            if let Some(error) = retained.capture.failure.get() {
                return Err(error.into());
            }
            let operation = &retained.operation;
            operation.validate_document_view(self.view)?;
            work.charge_work(
                u64::try_from(operation.decision_count()).map_err(|_| MemoryError::WorkExceeded)?,
            )?;
            if operation.accepted_signature().is_none() {
                return Err(DsigError::InvalidRequest {
                    reason: "selected Signature is not authenticated",
                });
            }
            return Ok(index);
        }
        Err(DsigError::InvalidRequest {
            reason: "Signature is not part of this request",
        })
    }

    fn signature_method_in<Q: Work>(
        &self,
        index: usize,
        work: &Q,
    ) -> Result<SelectedSignatureMethod, DsigError> {
        work.charge_work(1)?;
        let retained = &self.operations[index];
        retained.operation.validate_document_view(self.view)?;
        if let Some(error) = retained.capture.failure.get() {
            return Err(error.into());
        }
        retained
            .capture
            .method
            .get()
            .ok_or(DsigError::InvalidRequest {
                reason: "selected Signature has no original method receipt",
            })
    }
}

impl<'session, 'view, 'scope, 'inputs, W: Work, Q: Work>
    SelectedSignature<'session, 'view, 'scope, 'inputs, W, Q>
{
    fn operation(
        &self,
    ) -> &OperationExecutionContext<
        &'scope crate::policy::VerificationPolicy,
        &'scope VerificationOperationBudgets<'inputs>,
    > {
        &self.session.operations[self.index].operation
    }
    fn signature(&self) -> Result<Node<'_, '_>, DsigError> {
        Ok(self
            .session
            .view
            .resolve_node(self.session.evidence.signatures()[self.index].identity)?)
    }
    fn authenticates_element(&self, node: Node<'_, '_>) -> Result<bool, DsigError> {
        let signature = self.signature()?;
        for ancestor in node.ancestors() {
            self.work.charge_work(1)?;
            if ancestor.has_tag_name((XMLDSIG_NS, "SignedInfo"))
                && ancestor.parent() == Some(signature)
            {
                return Ok(true);
            }
            if self
                .operation()
                .is_authenticated(self.session.view.node_identity(ancestor))
            {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Resolve from the authenticated original property's lexical source, using
    /// this request's URI grammar, ID registrations, policy and XML Base budget.
    /// No network fetch, independent ID scan or fabricated Reference is involved.
    pub fn resolve_reference(
        &self,
        property: NodeIdentity,
        source: LexicalSource<'_>,
    ) -> Result<ReferenceResolution<'_>, DsigError> {
        self.work.charge_work(1)?;
        self.operation().validate_document_view(self.session.view)?;
        let node = self.session.view.resolve_node(property)?;
        if !node.is_element() {
            return Err(DsigError::InvalidRequest {
                reason: "reference property must be an element",
            });
        }
        if !self.authenticates_element(node)? {
            return Ok(ReferenceResolution::Unauthenticated(property));
        }
        let value = match source {
            LexicalSource::Attribute {
                namespace,
                local_name,
            } => {
                let mut value = None;
                for attribute in node.attributes() {
                    let bytes = attribute
                        .name()
                        .len()
                        .checked_add(attribute.namespace().map_or(0, str::len))
                        .and_then(|n| n.checked_add(1))
                        .ok_or(MemoryError::WorkExceeded)?;
                    self.work.charge_work(
                        u64::try_from(bytes).map_err(|_| MemoryError::WorkExceeded)?,
                    )?;
                    if attribute.name() == local_name && attribute.namespace() == namespace {
                        value = Some(attribute.value());
                        break;
                    }
                }
                let Some(value) = value else {
                    return Ok(ReferenceResolution::Absent);
                };
                LexicalValue::Borrowed(value)
            }
            LexicalSource::SimpleContent => {
                let mut value = LexicalValue::Borrowed("");
                for child in node.children() {
                    self.work.charge_work(1)?;
                    if child.is_element() {
                        return Ok(ReferenceResolution::Malformed);
                    }
                    let Some(text) = child.text().filter(|_| child.is_text()) else {
                        continue;
                    };
                    match &mut value {
                        LexicalValue::Borrowed(first) if first.is_empty() => *first = text,
                        LexicalValue::Borrowed(first) => {
                            let mut joined = OwnedText::try_from_str(first, self.work)?;
                            joined.try_push_str(text)?;
                            value = LexicalValue::Joined(joined);
                        }
                        LexicalValue::Joined(joined) => joined.try_push_str(text)?,
                    }
                }
                value
            }
        };
        let uri = value.as_str();
        self.work
            .charge_work(u64::try_from(uri.len()).map_err(|_| MemoryError::WorkExceeded)?)?;
        if !self.session.context.policy.uris.references.allows(uri) {
            return Err(crate::policy::PolicyViolation::Uri {
                operation: "extension reference resolution",
                reason: "reference URI class is not permitted",
            }
            .into());
        }
        if !uri.is_empty() && !uri.starts_with('#') {
            crate::c14n::xml_base::resolve_uri_from_node_in(
                node,
                uri,
                None,
                self.session.budgets.transforms.xml_base_resolution(),
                &crate::c14n::scratch::Accounted(self.work),
            )
            .map_err(super::super::uri::map_xml_base_execution_error)
            .map_err(|error| {
                DsigError::Reference(ReferenceProcessingError::UriDereference(error))
            })?;
            return Ok(ReferenceResolution::Detached);
        }
        let target = self.session.resolver.node_for_same_document_reference_in(
            uri,
            Some(self.session.budgets.transforms.node_set_materialization()),
            &crate::c14n::scratch::Accounted(self.work),
        );
        let target = match target {
            Ok(target) => target,
            Err(
                TransformError::UnsupportedUri(_)
                | TransformError::AccountedUnsupportedUri(_)
                | TransformError::InvalidFragment,
            ) => return Ok(ReferenceResolution::Unsupported),
            Err(error) => {
                return Err(DsigError::Reference(
                    ReferenceProcessingError::UriDereference(error),
                ));
            }
        };
        let Some(target) = target else {
            return Ok(ReferenceResolution::Unresolved);
        };
        let identity = self.session.view.node_identity(target);
        if !target.has_tag_name((XMLDSIG_NS, "Reference")) {
            return Ok(ReferenceResolution::NotReference(identity));
        }
        match self.descriptor(identity)? {
            Some(reference) => Ok(ReferenceResolution::Reference(reference)),
            None => Ok(ReferenceResolution::Unauthenticated(identity)),
        }
    }
    fn parent(&self, reference: Node<'_, '_>) -> Result<Option<ReferenceParent>, DsigError> {
        if !reference.has_tag_name((XMLDSIG_NS, "Reference")) {
            return Ok(None);
        }
        let Some(parent) = reference.parent() else {
            return Ok(None);
        };
        let signature = self.signature()?;
        let view = self.session.view;
        if parent.has_tag_name((XMLDSIG_NS, "SignedInfo")) && parent.parent() == Some(signature) {
            return Ok(Some(ReferenceParent::SignedInfo(
                view.node_identity(parent),
            )));
        }
        if !parent.has_tag_name((XMLDSIG_NS, "Manifest")) {
            return Ok(None);
        }
        for ancestor in parent.ancestors() {
            self.work.charge_work(1)?;
            if self
                .operation()
                .is_authenticated(view.node_identity(ancestor))
            {
                return Ok(Some(ReferenceParent::Manifest(view.node_identity(parent))));
            }
        }
        Ok(None)
    }
    fn descriptor(
        &self,
        reference: NodeIdentity,
    ) -> Result<Option<AuthenticatedReference<'_>>, DsigError> {
        self.work.charge_work(1)?;
        self.operation().validate_document_view(self.session.view)?;
        let node = self.session.view.resolve_node(reference)?;
        let Some(parent) = self.parent(node)? else {
            return Ok(None);
        };
        self.descriptor_in_parent(node, parent).map(Some)
    }

    fn descriptor_in_parent<'a>(
        &'a self,
        node: Node<'a, 'a>,
        parent: ReferenceParent,
    ) -> Result<AuthenticatedReference<'a>, DsigError> {
        let reference = self.session.view.node_identity(node);
        let result = match self.results.get(&reference, self.work)? {
            Some((set, index)) => self.session.evidence.signatures()[self.index]
                .result
                .as_ref()
                .ok()
                .map(|result| match set {
                    ReferenceSet::SignedInfo => &result.signed_info_references[*index],
                    ReferenceSet::Manifest => &result.manifest_references[*index],
                }),
            None => None,
        };
        // Admit both URI/Type attribute lookups before performing them. Their
        // fixed names bound each comparison; values themselves remain borrowed.
        for _ in node.attributes() {
            self.work.charge_work(9)?;
        }
        Ok(AuthenticatedReference {
            identity: reference,
            parent,
            uri: node.attribute("URI"),
            reference_type: node.attribute("Type"),
            result,
            location: if let Some(target) = result.and_then(|result| result.target_identity) {
                ReferenceLocation::SameDocument(target)
            } else {
                match self
                    .session
                    .budgets
                    .resolved_reference_resources
                    .borrow()
                    .get(&node.id())
                {
                    Some(OperationResourceIdentity::External { fingerprint, .. }) => {
                        ReferenceLocation::Detached(Some(*fingerprint))
                    }
                    Some(OperationResourceIdentity::MissingExternal) => {
                        ReferenceLocation::Detached(None)
                    }
                    _ => ReferenceLocation::Unchecked,
                }
            },
        })
    }

    /// Paid, single-pass original catalogue. No repeated ordinal rescanning;
    /// callbacks borrow descriptors and may retain only copied stable identities.
    pub fn visit_authenticated_references<E>(
        &self,
        mut visitor: impl for<'a> FnMut(AuthenticatedReference<'a>) -> Result<(), E>,
    ) -> Result<CatalogueCompleteness, CatalogueError<E>> {
        flatten_catalogue(self.visit_reference_instructions(|node, parent, _| {
            let reference = self
                .descriptor_in_parent(node, parent)
                .map_err(CatalogueError::Processing)?;
            visitor(reference).map_err(CatalogueError::Visitor)
        }))
    }

    fn visit_reference_instructions<E>(
        &self,
        mut visitor: impl for<'a> FnMut(
            Node<'a, 'a>,
            ReferenceParent,
            Option<Node<'a, 'a>>,
        ) -> Result<(), E>,
    ) -> Result<CatalogueCompleteness, CatalogueError<E>> {
        let mut completeness = CatalogueCompleteness::Complete;
        let mut references = 0;
        let maximum = self.session.context.policy.resources.max_references;
        self.operation()
            .validate_document_view(self.session.view)
            .map_err(|error| CatalogueError::Processing(error.into()))?;
        for node in self.session.view.document().descendants() {
            self.work
                .charge_work(1)
                .map_err(|error| CatalogueError::Processing(error.into()))?;
            if node.has_tag_name((XMLDSIG_NS, "Manifest"))
                && self
                    .authenticates_element(node)
                    .map_err(CatalogueError::Processing)?
            {
                let mut count = 0;
                let mut malformed = false;
                for child in node.children() {
                    self.work
                        .charge_work(1)
                        .map_err(|error| CatalogueError::Processing(error.into()))?;
                    if child.has_tag_name((XMLDSIG_NS, "Reference")) {
                        count += 1;
                    } else if child.is_element() {
                        malformed = true;
                    } else if child.is_text() {
                        let text = child.text().unwrap_or_default();
                        self.work
                            .charge_work(text.len() as u64)
                            .map_err(|error| CatalogueError::Processing(error.into()))?;
                        if !is_xml_whitespace_only(text) {
                            malformed = true;
                        }
                    }
                }
                if (malformed || count == 0)
                    && !matches!(completeness, CatalogueCompleteness::Incomplete(_))
                {
                    completeness =
                        CatalogueCompleteness::Incomplete(self.session.view.node_identity(node));
                }
            }
            if !node.has_tag_name((XMLDSIG_NS, "Reference")) {
                continue;
            }
            let Some(parent) = self.parent(node).map_err(CatalogueError::Processing)? else {
                continue;
            };
            let identity = self.session.view.node_identity(node);
            if references == maximum {
                return Err(CatalogueError::Processing(
                    crate::policy::PolicyViolation::ResourceLimit {
                        resource: crate::policy::resource_name::SIGNATURE_REFERENCES,
                        maximum,
                        actual: references + 1,
                    }
                    .into(),
                ));
            }
            references += 1;
            self.work
                .charge_work(128)
                .map_err(|error| CatalogueError::Processing(error.into()))?;
            for child in node.children() {
                let text = child.text().filter(|_| child.is_text()).map_or(0, str::len);
                let cost = u64::try_from(text)
                    .ok()
                    .and_then(|length| length.checked_add(128))
                    .ok_or_else(|| CatalogueError::Processing(MemoryError::WorkExceeded.into()))?;
                self.work
                    .charge_work(cost)
                    .map_err(|error| CatalogueError::Processing(error.into()))?;
            }
            let method = super::super::parse::inspect_reference_layout(node)
                .ok()
                .map(|(_, method, _)| method);
            if method.is_none() {
                if !matches!(completeness, CatalogueCompleteness::Incomplete(_)) {
                    completeness = CatalogueCompleteness::Incomplete(identity);
                }
            } else if let ReferenceParent::Manifest(parent) = parent
                && matches!(completeness, CatalogueCompleteness::Complete)
                && self.session.context.policy.manifest_processing
                    == crate::policy::ManifestProcessing::Ignore
            {
                completeness = CatalogueCompleteness::Unchecked(parent);
            }
            visitor(node, parent, method).map_err(CatalogueError::Visitor)?;
        }
        Ok(completeness)
    }
}

/// Final node-set coercion. Explicit final C14N transforms already produce
/// octets and therefore take precedence over either implicit mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReplayMode {
    /// XMLDSig 1.1 §4.3.3.2 implicit C14N 1.0.
    ReferenceOutput,
    /// Original timestamp CanonicalizationMethod node, including parameters.
    Timestamp(NodeIdentity),
}

/// Missing explicitly supplied external bytes are diagnostic, not a successful
/// empty output. Policy, malformed XML and processing failures remain errors.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReplayOutcome {
    /// The receiver obtained the entire output.
    Complete,
    /// The request did not supply this admitted external resource.
    Unavailable(ExternalResourceUnavailable),
}

/// The admitted external lookup was absent from the captured caller map.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExternalResourceUnavailable {
    /// Original authenticated Reference whose lookup was absent.
    pub reference: NodeIdentity,
}

/// Typed sticky receiver failure, independent of XML processing failure.
#[derive(Debug)]
pub enum ReplayError<E> {
    /// XML, policy, provenance or resource failure.
    Processing(DsigError),
    /// Original receiver error.
    Receiver(E),
}
impl<E> From<TransformError> for ReplayError<E> {
    fn from(error: TransformError) -> Self {
        Self::Processing(match error {
            TransformError::C14n(crate::c14n::C14nError::SharedExecution(error)) => error.into(),
            error => ReferenceProcessingError::Transform(error).into(),
        })
    }
}
impl<E> From<OperationPlanError> for ReplayError<E> {
    fn from(error: OperationPlanError) -> Self {
        Self::Processing(error.into())
    }
}

struct ReplayWriter<'a, W: Work, E, F> {
    work: &'a W,
    budget: &'a TransformExecutionBudget,
    canonicalizing: bool,
    receiver: &'a mut F,
    failure: Option<ReplayError<E>>,
}

struct ReplayTerminal<'a, W: Work, E, F> {
    work: &'a W,
    receiver: &'a mut F,
    timestamp: Option<(crate::c14n::C14nAlgorithm, Option<&'a str>)>,
    error: std::marker::PhantomData<fn() -> E>,
}

impl<'a, W: Work, E, F: FnMut(&[u8]) -> Result<(), E>>
    super::super::transforms::TransformTerminal<crate::c14n::scratch::Accounted<'a, W>>
    for ReplayTerminal<'a, W, E, F>
{
    type Output = ();
    type Error = ReplayError<E>;

    fn finish<D: crate::xml::dom::storage::Storage>(
        self,
        data: super::super::transforms::ExecutionData<
            '_,
            crate::c14n::scratch::Accounted<'a, W>,
            D,
        >,
        explicit: Option<(&crate::c14n::C14nAlgorithm, Option<&str>)>,
        budget: &TransformExecutionBudget,
    ) -> Result<(), ReplayError<E>> {
        let mut output = ReplayWriter {
            work: self.work,
            budget,
            canonicalizing: data.nodes().is_some(),
            receiver: self.receiver,
            failure: None,
        };
        let result = if let Some(bytes) = data.binary() {
            use std::io::Write;
            output.write_all(bytes).map_err(crate::c14n::C14nError::Io)
        } else {
            let nodes = data.nodes().expect("execution has nodes or bytes");
            let implicit = crate::c14n::C14nAlgorithm::from_uri(DEFAULT_IMPLICIT_C14N_URI)
                .expect("constant C14N URI");
            let algorithm = explicit
                .map(|(algorithm, _)| algorithm)
                .or(self.timestamp.as_ref().map(|(algorithm, _)| algorithm))
                .unwrap_or(&implicit);
            let prefixes = if explicit.is_none() {
                self.timestamp.as_ref().and_then(|(_, prefixes)| *prefixes)
            } else {
                explicit.and_then(|(_, prefixes)| prefixes)
            };
            crate::c14n::canonicalize_visible_to_writer_accounted(
                nodes.document(),
                Some(nodes),
                algorithm,
                super::super::transforms::replay_output_limit(budget),
                budget.xml_base_resolution(),
                &mut output,
                self.work,
                prefixes,
            )
        };
        if let Some(error) = output.failure {
            return Err(error);
        }
        result.map_err(|error| match error {
            crate::c14n::C14nError::SharedExecution(error) => ReplayError::Processing(error.into()),
            error => super::super::transforms::replay_c14n_error(error, budget).into(),
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ReplayState {
    Pending,
    Complete,
    Unavailable,
    Rejected,
}
struct ReplayRecord {
    signature: NodeIdentity,
    reference: NodeIdentity,
    state: ReplayState,
}

struct AdmittedReplay<'a, W: Work> {
    records: &'a RefCell<OwnedVec<ReplayRecord, W>>,
    active: &'a Cell<bool>,
    index: usize,
}
impl<W: Work> AdmittedReplay<'_, W> {
    fn finish<E>(&self, result: &Result<ReplayOutcome, ReplayError<E>>) {
        self.records.borrow_mut()[self.index].state = match result {
            Ok(ReplayOutcome::Complete) => ReplayState::Complete,
            Ok(ReplayOutcome::Unavailable(_)) => ReplayState::Unavailable,
            Err(_) => ReplayState::Rejected,
        };
    }
}
impl<W: Work> Drop for AdmittedReplay<'_, W> {
    fn drop(&mut self) {
        let mut records = self.records.borrow_mut();
        if records[self.index].state == ReplayState::Pending {
            records[self.index].state = ReplayState::Rejected;
        }
        self.active.set(false);
    }
}
impl<W: Work, E, F: FnMut(&[u8]) -> Result<(), E>> std::io::Write for ReplayWriter<'_, W, E, F> {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        if self.failure.is_some() {
            return Err(std::io::ErrorKind::Other.into());
        }
        let result = (|| {
            let units = u64::try_from(bytes.len())
                .map_err(|_| ReplayError::Processing(MemoryError::WorkExceeded.into()))?;
            self.work
                .charge_work(units)
                .map_err(|error| ReplayError::Processing(error.into()))?;
            if self.canonicalizing {
                super::super::transforms::charge_replay_output(self.budget, bytes.len())?;
            }
            (self.receiver)(bytes).map_err(ReplayError::Receiver)
        })();
        match result {
            Ok(()) => Ok(bytes.len()),
            Err(error) => {
                self.failure = Some(error);
                Err(std::io::ErrorKind::Other.into())
            }
        }
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl<W: Work, Q: Work> SelectedSignature<'_, '_, '_, '_, W, Q> {
    /// Re-execute an authenticated instruction, not its historical digest test.
    /// EN 319 132-1 V1.3.1 §5.5.3 steps 3/6 and Note 2 deliberately permit
    /// renewal without recomputing the original digest algorithm.
    /// <https://www.etsi.org/deliver/etsi_en/319100_319199/31913201/01.03.01_60/en_31913201v010301p.pdf>
    pub fn replay_reference<E>(
        &self,
        reference: NodeIdentity,
        mode: ReplayMode,
        receiver: &mut impl FnMut(&[u8]) -> Result<(), E>,
    ) -> Result<ReplayOutcome, ReplayError<E>> {
        self.work
            .charge_work(
                u64::try_from(self.operation().decision_count())
                    .map_err(|_| ReplayError::Processing(MemoryError::WorkExceeded.into()))?,
            )
            .map_err(|error| ReplayError::Processing(error.into()))?;
        self.operation()
            .run_reference_replay(self.session.view, reference, || {
                self.replay_admitted(reference, mode, receiver)
            })
    }

    fn replay_admitted<E>(
        &self,
        reference: NodeIdentity,
        mode: ReplayMode,
        receiver: &mut impl FnMut(&[u8]) -> Result<(), E>,
    ) -> Result<ReplayOutcome, ReplayError<E>> {
        let processing = ReplayError::Processing;
        let descriptor = self
            .descriptor(reference)
            .map_err(processing)?
            .ok_or_else(|| {
                processing(DsigError::InvalidRequest {
                    reason: "Reference instruction is not authenticated by selected Signature",
                })
            })?;
        if matches!(descriptor.parent, ReferenceParent::Manifest(_))
            && self.session.context.policy.manifest_processing
                == crate::policy::ManifestProcessing::Ignore
        {
            return Err(processing(
                crate::policy::PolicyViolation::ManifestProcessingDisabled.into(),
            ));
        }
        if self.session.replay_active.get() {
            return Err(processing(DsigError::InvalidRequest {
                reason: "reentrant replay would reset the active transform chain",
            }));
        }
        let index = {
            let mut records = self.replays.borrow_mut();
            let index = records.len();
            records
                .try_push(ReplayRecord {
                    signature: self.session.evidence.signatures()[self.index].identity,
                    reference,
                    state: ReplayState::Pending,
                })
                .map_err(|error| processing(error.into()))?;
            debug_assert_eq!(records[index].reference, reference);
            debug_assert_eq!(
                records[index].signature,
                self.session.evidence.signatures()[self.index].identity
            );
            index
        };
        self.session.replay_active.set(true);
        let admission = AdmittedReplay {
            records: &self.replays,
            active: &self.session.replay_active,
            index,
        };
        let result = self.replay_instruction(descriptor, mode, receiver);
        admission.finish(&result);
        result
    }

    fn replay_instruction<E>(
        &self,
        descriptor: AuthenticatedReference<'_>,
        mode: ReplayMode,
        receiver: &mut impl FnMut(&[u8]) -> Result<(), E>,
    ) -> Result<ReplayOutcome, ReplayError<E>> {
        let processing = ReplayError::Processing;
        let node = self
            .session
            .view
            .resolve_node(descriptor.identity)
            .map_err(|error| processing(error.into()))?;
        let uri = descriptor.uri.ok_or_else(|| {
            processing(DsigError::Reference(ReferenceProcessingError::MissingUri))
        })?;
        if !self.session.context.policy.uris.references.allows(uri) {
            return Err(processing(
                crate::policy::PolicyViolation::Uri {
                    operation: "reference replay",
                    reason: "reference URI class is not permitted",
                }
                .into(),
            ));
        }
        let allowed = self
            .session
            .context
            .policy
            .transforms
            .allowed_algorithms
            .as_ref();
        let maximum = self
            .session
            .context
            .policy
            .resources
            .max_transforms_per_reference;
        let mut transform_count = 0;
        self.work
            .charge_work(node.children().len() as u64)
            .map_err(|error| processing(error.into()))?;
        for transforms in node
            .children()
            .filter(|child| child.has_tag_name((XMLDSIG_NS, "Transforms")))
        {
            self.work
                .charge_work(transforms.children().len() as u64)
                .map_err(|error| processing(error.into()))?;
            for transform in transforms.children().filter(Node::is_element) {
                self.work
                    .charge_work(1)
                    .map_err(|error| processing(error.into()))?;
                transform_count += 1;
                if transform_count > maximum {
                    return Err(processing(
                        crate::policy::PolicyViolation::ResourceLimit {
                            resource: crate::policy::resource_name::REFERENCE_TRANSFORMS,
                            maximum,
                            actual: transform_count,
                        }
                        .into(),
                    ));
                }
                self.work
                    .charge_work(transform.attributes().len() as u64)
                    .map_err(|error| processing(error.into()))?;
                if let Some(algorithm) = transform.attribute("Algorithm") {
                    self.work
                        .charge_work(algorithm.len() as u64)
                        .map_err(|error| processing(error.into()))?;
                    enforce_current_transform_allowed(allowed, algorithm, self.work)
                        .map_err(processing)?;
                }
            }
        }
        let parse_failure = |error| match error {
            super::super::parse::ParseError::Transform(TransformError::C14n(
                crate::c14n::C14nError::SharedExecution(error),
            )) => processing(error.into()),
            error => processing(DsigError::ParseManifestReference(error)),
        };
        let transforms = super::super::parse::parse_replay_transforms(
            node,
            &mut self.session.budgets.xpath_parse.borrow_mut(),
            &crate::c14n::scratch::Accounted(self.work),
        )
        .map_err(parse_failure)?;
        if matches!(mode, ReplayMode::ReferenceOutput)
            && !transform_chain_produces_binary(
                classify_uri(uri) == UriClass::External,
                &transforms,
            )
        {
            enforce_transform_allowed(allowed, DEFAULT_IMPLICIT_C14N_URI).map_err(processing)?;
        }
        let timestamp = match mode {
            ReplayMode::ReferenceOutput => None,
            ReplayMode::Timestamp(method) => {
                let method = self
                    .session
                    .view
                    .resolve_node(method)
                    .map_err(|error| processing(error.into()))?;
                let uri = method.attribute("Algorithm").ok_or_else(|| {
                    processing(DsigError::InvalidStructure {
                        reason: "timestamp method has no Algorithm",
                    })
                })?;
                self.work
                    .charge_work(uri.len() as u64)
                    .map_err(|error| processing(error.into()))?;
                enforce_current_transform_allowed(allowed, uri, self.work).map_err(processing)?;
                let algorithm = super::super::parse::parse_replay_canonicalization_method(
                    method,
                    &crate::c14n::scratch::Accounted(self.work),
                )
                .map_err(parse_failure)?;
                Some(algorithm)
            }
        };
        let budget = &self.session.budgets.transforms;
        let Some(data) = self.session.resolver.replay_input_from_with_budget(
            uri,
            node,
            budget.node_set_materialization(),
            budget.xml_base_resolution(),
            &crate::c14n::scratch::Accounted(self.work),
        )?
        else {
            return Ok(ReplayOutcome::Unavailable(ExternalResourceUnavailable {
                reference: descriptor.identity,
            }));
        };
        let enveloped_signature =
            super::super::transforms::enveloped_signature_for_reference(node, &transforms, || {
                self.work
                    .charge_work(1)
                    .map_err(|error| processing(error.into()))
            })?;
        super::super::transforms::replay_reference_transforms(
            node,
            enveloped_signature,
            data,
            &transforms,
            super::super::transforms::ReplayExecution {
                options: self.session.context.transform_options(),
                budget,
                work: self.work,
            },
            ReplayTerminal {
                work: self.work,
                receiver,
                timestamp,
                error: std::marker::PhantomData,
            },
        )?;
        Ok(ReplayOutcome::Complete)
    }
}