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
//! RFC 4158 certification path building for [`pkix_path`].
//!
//! Accepts an unordered collection of certificates ([`CertPool`]) and
//! constructs a valid ordered chain suitable for [`pkix_path::validate_path`].
//!
//! # Relationship to `pkix-path`
//!
//! `pkix-path` validates a caller-ordered `&[Certificate]`. This crate
//! handles the prior step: discovering and ordering that chain from a bag
//! of certificates when the caller does not know the chain order in advance.
//! Cross-certificates and bridge CA topologies are handled here, not in
//! `pkix-path`.
//!
//! # Algorithm
//!
//! [`build_path`] and [`build_path_with_config`] perform a single-pass
//! depth-first search up to [`PathBuilderConfig::max_depth`] (default
//! [`DEFAULT_MAX_DEPTH`] = 10). At each step, candidates are ranked by
//! AKI/SKI match tier (RFC 4158 §3.2) so the most-likely issuer is tried
//! first. Memory is bounded to O(depth) stack frames.
//!
//! Shortest-first is **not** guaranteed: for typical pools the first chain
//! found is the shortest, but adversarial pools may yield a deeper chain
//! first. See [`PathCandidates`] for the full enumeration contract.
//!
//! # Spec references
//!
//! - RFC 4158 — Internet X.509 PKI: Certification Path Building
//! - RFC 5280 §6.1 — the validation algorithm this crate feeds into
//!
//! # `no_std`
//!
//! This crate is `no_std` but requires the `alloc` crate. The `extern crate alloc`
//! declaration is provided automatically; you do not need to add it yourself, but
//! your target must supply a global allocator (e.g., `#[global_allocator]`).
//!
//! # Limitations
//!
//! - **Caller supplies the candidate set.** [`CertPool`] takes a pool of
//! already-loaded certificates. This crate does not fetch missing
//! intermediates from `AuthorityInfoAccess` URIs; the optional
//! `pkix-aia` / `pkix-aia-http` cascade handles that (tracked under
//! `PKIX-zkjb`).
//! - **Output feeds `pkix-path`.** The validation algorithm (RFC 5280 §6.1
//! signature chain walk, name constraints, policy machinery, revocation)
//! lives in `pkix-path` and `pkix-revocation`. This crate's job ends
//! when it returns an ordered candidate chain.
//! - **Known residual divergence.** A single bettertls path-building
//! corner case (`pathbuilding::tc60`) is documented as a known
//! divergence; closing it is a 1.0 release blocker tracked under
//! `PKIX-lwr9.4`. See `pkix-difftest/baseline-limbo-analysis.md`.
extern crate alloc;
use Vec;
use Decode as _;
use Certificate;
/// An unordered collection of certificates used as input to path building.
///
/// Certificates are stored by DER bytes and decoded on demand. Add all
/// candidate intermediate certificates here; the path builder will select
/// and order the subset that forms a valid path to a trust anchor.
///
/// Note: `Hash` is not derived because `x509_cert::Certificate` does not
/// currently implement `Hash` (upstream limitation); `CertPool` cannot be
/// used as a hash-map key until that changes.
///
/// Note: `PartialEq`/`Eq` are not derived. `CertPool` is documented as an
/// unordered bag, so a derived implementation (which compares the internal
/// `Vec` in insertion order) would be semantically wrong.
/// Errors returned by path building.
/// Result alias for this crate.
pub type Result<T> = Result;
/// Returns `true` if `cert` has `BasicConstraints` with `cA = TRUE`,
/// `false` if the extension is absent, has `cA = FALSE`, or cannot be
/// DER-decoded.
///
/// Malformed `BasicConstraints` is treated as `false` (skip-not-fail):
/// a single malformed certificate in a CMS `SignedData.certificates` bag
/// must not poison verification of an otherwise-valid chain.
/// OID `id-ce-authorityKeyIdentifier` (RFC 5280 §4.2.1.1).
const OID_AUTHORITY_KEY_IDENTIFIER: ObjectIdentifier =
new_unwrap;
/// OID `id-ce-subjectKeyIdentifier` (RFC 5280 §4.2.1.2).
const OID_SUBJECT_KEY_IDENTIFIER: ObjectIdentifier =
new_unwrap;
/// Return the bytes of `cert`'s `AuthorityKeyIdentifier::keyIdentifier`
/// extension, or `None` if the extension is absent, the `keyIdentifier`
/// field is absent, or the extension cannot be DER-decoded.
///
/// **Fail-soft semantics**: a malformed AKI is treated as if absent rather
/// than propagated as an error. The AKI keyIdentifier is used purely as
/// an *ordering heuristic* for candidate selection; it is not a security
/// gate (the actual signature check happens downstream in
/// [`pkix_path::validate_path`]). A malformed AKI on the target should
/// degrade builder selection to DN-only ranking, not abort path building.
///
/// RFC 5280 §4.2.1.1: AKI's `keyIdentifier` is normally the SHA-1 hash of
/// the issuer's `subjectPublicKey` BIT STRING (method 1). This is compared
/// byte-for-byte against candidate certs' `SubjectKeyIdentifier`; we do
/// not recompute hashes here — only opaque-byte equality matters.
///
/// **Note:** Returns `Vec<u8>` (owned) rather than `&[u8]` because
/// `AuthorityKeyIdentifier::from_der` produces an owned intermediate
/// whose lifetime cannot be tied to the input `cert` reference; the
/// inner `OctetString` bytes do not borrow from the cert's DER.
/// Return the bytes of `cert`'s `SubjectKeyIdentifier` extension, or
/// `None` if the extension is absent or cannot be DER-decoded.
///
/// **Fail-soft semantics**: see [`cert_aki_key_id`] for rationale. A cert
/// without a parseable SKI ranks below SKI-bearing candidates in the
/// AKI-matching tier but is still considered for the DN-only fallback
/// tier.
///
/// RFC 5280 §4.2.1.2: SKI is conventionally the SHA-1 hash of the cert's
/// own `subjectPublicKey` BIT STRING; we do not recompute, we only return
/// the bytes the cert claims.
///
/// **Note:** Returns `Vec<u8>` (owned) for the same reason as
/// [`cert_aki_key_id`]: `SubjectKeyIdentifier::from_der` produces an
/// owned `OctetString` that does not borrow from the cert's DER.
/// Compute the DN-matching candidates of `cur` from `pool`, ordered by
/// AKI/SKI matching tier (RFC 5280 §4.2.1.1, RFC 4158 §3.2).
///
/// Returns a vector of `(tier, pool_index)` pairs:
///
/// - **Tier 0**: candidate's `SubjectKeyIdentifier` matches `cur`'s
/// `AuthorityKeyIdentifier.keyIdentifier`. This is the §4.2.1.1 method-1
/// disambiguator: in bridge-CA and key-rollover topologies, multiple CA
/// certs share an issuer DN; AKI/SKI is the only deterministic way to
/// pick the cert that actually signed `cur`.
/// - **Tier 1**: any DN-matching candidate. Used when `cur` has no AKI,
/// no candidate SKI matches, or AKI/SKI parsing failed (fail-soft — see
/// [`cert_aki_key_id`]/[`cert_ski_key_id`]).
///
/// The result is sorted **stably** by tier so candidates within the same
/// tier preserve pool insertion order. This is the documented contract for
/// the no-AKI-signal case.
///
/// **Not currently used:** the AKI `authorityCertIssuer` /
/// `authorityCertSerialNumber` fields. They are rare in practice and
/// parsing `GeneralNames` for that signal is more work than the marginal
/// disambiguation benefit justifies. Documented as a deferred enhancement.
/// SPKI-based cycle detection: does `path` already contain a cert with the
/// same `SubjectPublicKeyInfo` algorithm OID and raw public-key bits as
/// `candidate`?
///
/// Algorithm parameters are deliberately excluded from the comparison to
/// tolerate the RFC 8017 ambiguity between absent and explicit-NULL
/// `parameters` in rsaEncryption SPKIs (one cert may encode
/// `AlgorithmIdentifier { oid: rsaEncryption, params: NULL }` while another
/// encodes the same key with `params: absent`; both represent the same
/// public key). DN-based cycle detection is intentionally NOT used: in
/// key-rollover or bridge-CA topologies multiple certs may share a subject
/// DN with different keys, and treating them as the same node would
/// incorrectly prune valid paths.
/// Default DFS node-visit budget per search pass.
///
/// Sufficient for legitimate chains (real-world PKI hierarchies have at most
/// a handful of intermediates and small pools); prevents exponential blow-up
/// against adversarially constructed pools of O(N) CA certificates with
/// identical subject/issuer names.
pub const DEFAULT_DFS_BUDGET: usize = 10_000;
/// Default maximum number of intermediate certificates considered.
pub const DEFAULT_MAX_DEPTH: usize = 10;
/// Tunable parameters for path building.
///
/// Use [`PathBuilderConfig::default`] (or [`PathBuilderConfig::new`]) for the
/// production defaults. Embedded callers, callers with restricted compute,
/// and callers handling adversarial pools can tighten these values.
///
/// # Stability
///
/// Constructed via [`PathBuilderConfig::new`] / `Default`; the struct is
/// `#[non_exhaustive]` so additional knobs can be added without breaking
/// existing callers.
// =========================================================================
// PathCandidates iterator (PKIX-mszo)
// =========================================================================
/// Per-frame DFS state held by [`PathCandidates`].
///
/// Each [`Frame`] mirrors one stack frame of the recursive DFS: it holds
/// the AKI-ranked candidate list for the cert at this depth and a cursor
/// into that list, plus state-machine flags so a paused-and-resumed DFS
/// can pick up where it left off without re-running the anchor check or
/// re-yielding the same chain twice.
/// Iterator over topologically-valid certification paths from a target
/// cert through a candidate pool to one of a set of trust anchors.
///
/// Each [`Iterator::next`] call returns either:
/// - `Some(Ok(chain))` — the next leaf-first chain `[target, ...,
/// anchor-issued]` that is topologically valid (DN chain links,
/// `BasicConstraints cA=TRUE` on every intermediate, no SPKI cycles).
/// Signatures are NOT verified; downstream callers must run the
/// returned chain through [`pkix_path::validate_path`].
/// - `Some(Err(e))` — a fatal error (see [`Error`]). The iterator is
/// exhausted; subsequent calls return `None`.
/// - `None` — DFS has been exhausted; no more chains exist within the
/// configured `max_depth`.
///
/// **Resumable DFS**: candidates are explored in AKI-ranked
/// order (`rank_candidates`); when a chain is yielded, the next call
/// resumes from the same DFS state and explores alternate paths. This
/// is the contract S/MIME callers depend on for build-then-validate
/// retry loops in adversarial pools (CMS bags, federal-bridge cross-cert
/// topologies, etc.) where the topologically-first chain may not be the
/// cryptographically-verifying one.
///
/// **Bounded enumeration**: a single shared budget (initial value
/// [`PathBuilderConfig::dfs_budget`]) is decremented once per DFS frame
/// entry across all `next()` calls. When the budget is exhausted, the
/// next call returns `Some(Err(`[`Error::BudgetExceeded`]`))` and the
/// iterator becomes exhausted. This bounds worst-case work to
/// `O(dfs_budget)` total across the entire iterator's lifetime,
/// preventing an adversarial pool from causing unbounded enumeration.
///
/// **No iterative deepening**: unlike legacy `build_path`, this iterator
/// performs a single DFS at `max_depth`. Paths are yielded in DFS order
/// (depth-first, AKI-tier-ordered, then pool insertion order within a
/// tier). Shortest-first is no longer guaranteed; for typical pools the
/// first yielded chain is still the shortest, but adversarial pools can
/// produce a deeper chain first if its branch is explored before a
/// shallower alternative.
///
/// # Examples
///
/// Build-then-validate retry loop:
///
/// ```ignore
/// let mut candidates = pkix_path_builder::build_path_candidates(
/// &target, &pool, &anchors,
/// );
/// loop {
/// match candidates.next() {
/// None => break Err(NoVerifiableChain),
/// Some(Err(e)) => break Err(e.into()),
/// Some(Ok(chain)) => match pkix_path::validate_path(
/// &chain, &anchors, &policy, &verifier,
/// ) {
/// Ok(vp) => break Ok(vp),
/// Err(_) => continue, // try next candidate
/// },
/// }
/// }
/// ```
///
/// The pattern above is exactly what [`build_first_valid_path`] wraps:
/// callers that only need "find any chain that validates" should prefer
/// the helper. Drop down to this iterator when you need per-candidate
/// diagnostics, want to limit the number of candidates tried, or are
/// composing the retry loop with additional per-candidate policy
/// (e.g., per-candidate revocation checks).
/// Construct a [`PathCandidates`] iterator using the workspace defaults
/// ([`DEFAULT_MAX_DEPTH`], [`DEFAULT_DFS_BUDGET`]).
///
/// See [`PathCandidates`] for usage and semantics.
/// Construct a [`PathCandidates`] iterator with caller-provided budget
/// and depth tunables.
///
/// See [`PathCandidates`] for usage and semantics, and
/// [`PathBuilderConfig`] for the individual knobs.
// =========================================================================
// build_path / build_path_with_config — single-shot wrappers
// =========================================================================
/// Build a certification path from `target` through certificates in `pool`
/// to one of the provided trust anchors.
///
/// Returns the ordered chain `[target, intermediate..., anchor-issued]` ready
/// for [`pkix_path::validate_path`]. Signatures are **not** verified here;
/// that is the responsibility of the caller via [`pkix_path::validate_path`].
///
/// # Algorithm
///
/// Single-pass depth-first search at the configured `max_depth`. Candidates
/// at each frame are ordered by AKI/SKI tier (RFC 5280 §4.2.1.1) so
/// disambiguating bridge-CA / cross-cert topologies succeeds on the first
/// candidate when AKI/SKI bindings are well-formed. Cycles are detected by
/// `SubjectPublicKeyInfo` algorithm OID + raw public-key bits; algorithm
/// parameters are excluded so RFC 8017 absent-vs-NULL ambiguity in
/// rsaEncryption SPKIs does not break detection.
///
/// This is a thin wrapper over the [`PathCandidates`] iterator: it returns
/// the iterator's first yield, or invokes a depth+1 probe (with fresh
/// budget) on `None` to distinguish [`Error::NoPathFound`] from
/// [`Error::DepthExceeded`].
///
/// # Errors
///
/// - [`Error::NoPathFound`] — no topologically valid path through `pool` leads
/// to any of the given trust anchors.
/// - [`Error::DepthExceeded`] — a path exists topologically but requires more
/// than [`PathBuilderConfig::max_depth`] intermediate certificates.
/// - [`Error::BudgetExceeded`] — the DFS frame-entry budget was exhausted
/// before a path was found; the pool may be adversarially large or
/// structured to produce exponential search.
///
/// # Choosing between `build_path`, the iterator, and `build_first_valid_path`
///
/// Use this single-shot API when:
/// - the pool is from a trusted source (in-house cert store, configured
/// intermediate bundle), and
/// - finding any topologically valid chain is sufficient (the caller does
/// not need to retry with alternate chains if signature verification
/// fails downstream).
///
/// Use [`build_path_candidates`] (or its `_with_config` sibling) when you
/// want full control over candidate iteration — for adversarial pools (CMS
/// `SignedData.certificates` bags, federal-bridge cross-cert topologies,
/// anywhere the wire-order of certs is not under your control) so failed
/// signature verification can be retried against the next candidate path.
/// See [`PathCandidates`] for the build-then-validate retry-loop pattern.
///
/// Use [`build_first_valid_path`] (or its `_with_config` sibling) for the
/// common case of "iterate candidates until one validates": it wraps the
/// iterator + [`pkix_path::validate_path`] retry loop and returns the
/// first chain that survives both topological build and signature
/// verification. Prefer this over `build_path` when the pool contains
/// alternatives whose signatures may be rejected by the verifier (e.g.,
/// cross-signed intermediates using algorithms outside the verifier's
/// dispatch table).
///
/// # Limitations
///
/// **Candidate selection uses AKI/SKI as an ordering heuristic, not a
/// security gate.** When the cert seeking an issuer carries an
/// `AuthorityKeyIdentifier` extension with a `keyIdentifier` field
/// (RFC 5280 §4.2.1.1), pool candidates whose `SubjectKeyIdentifier`
/// (§4.2.1.2) matches are tried before DN-only matches. This is
/// best-effort disambiguation for bridge-CA and key-rollover topologies
/// where multiple CA certs share an issuer DN. The signature itself is
/// **not** verified by this crate — that happens downstream in
/// [`pkix_path::validate_path`]. Consequences:
///
/// - When the AKI heuristic picks the wrong candidate (e.g., AKI is
/// absent or malformed, multiple candidates share the same SKI, or
/// the AKI/SKI binding is wrong), the returned chain may fail
/// `validate_path` with `SignatureInvalid` rather than
/// [`Error::NoPathFound`] here. Callers handling adversarial pools
/// should use [`build_path_candidates`] to retry alternate chains.
/// - Malformed AKI or SKI extensions are treated as if absent (fail-soft).
/// They do not cause path building to abort; they simply degrade
/// selection to DN-only ranking for that cert.
/// - The AKI `authorityCertIssuer` + `authorityCertSerialNumber` fields
/// (the rare alternative to `keyIdentifier`) are not currently used for
/// ranking. Only the `keyIdentifier` field participates.
///
/// **Anchor matching is by DN only.** When a candidate's issuer DN matches
/// any anchor in `anchors`, path building terminates immediately with that
/// chain — the anchor's `SubjectPublicKeyInfo` is **not** verified against
/// what the chain expects.
///
/// **Shortest-first is no longer guaranteed.** Earlier versions of this
/// crate used iterative-deepening DFS to return the shortest topology
/// first. The single-pass DFS used now (which shares state with the
/// `PathCandidates` iterator) yields paths in depth-first order. For
/// typical pools the first yielded chain is still the shortest; for
/// adversarial pools, a deeper chain may be returned first if its branch
/// is explored before a shallower alternative. If shortest-first matters,
/// inspect the returned chain length and (rarely) re-run with a tightened
/// `max_depth`.
///
/// # Security
///
/// Pool contents should be from a trusted source. The DFS frame-entry
/// budget enforces a hard cap on search work to prevent denial-of-service
/// via oversized or crafted pools.
/// Build a certification path with caller-provided budget and depth tunables.
///
/// Behaves identically to [`build_path`] but uses the limits in `config`
/// instead of the workspace defaults. See [`PathBuilderConfig`] for the
/// individual knobs and [`build_path`] for full semantics.
///
/// # Errors
///
/// Same as [`build_path`].
// =========================================================================
// build_first_valid_path — candidate iteration + signature verification
// =========================================================================
/// Build a certification path that both **(a)** is topologically valid through
/// `pool` to one of `anchors` and **(b)** passes
/// [`pkix_path::validate_path`] under `policy` and `verifier`.
///
/// Iterates [`build_path_candidates`] until the first candidate chain
/// validates. Returns the validating chain. If every candidate is rejected
/// by `validate_path`, returns [`Error::NoValidPath`] carrying the count of
/// candidates tried and the `Display` rendering of the last
/// [`pkix_path::Error`].
///
/// # When to use this over [`build_path`]
///
/// [`build_path`] is single-shot: it returns the first DFS candidate without
/// any knowledge of which signature algorithms `verifier` actually dispatches
/// or which intermediates are within their validity window at `policy`'s
/// validation time. In adversarial pools — for example, cross-signed graphs
/// that include an alternative intermediate signed under
/// `ecdsa-with-SHA1` (RFC 5758 §3.2 legacy OID, not dispatched by
/// [`pkix_path::DefaultVerifier`]) — the first DFS yield can be rejected by
/// `validate_path` even though a SHA-256-only path exists in the same pool.
///
/// `build_first_valid_path` closes this gap: it iterates
/// [`build_path_candidates`] and tries `validate_path` per yielded chain,
/// returning the first chain that survives both passes.
///
/// # Errors
///
/// - [`Error::NoPathFound`] — the underlying iterator yielded no candidates
/// at all (no topologically valid chain through `pool` to any anchor).
/// Matches [`build_path`]'s behaviour for that case.
/// - [`Error::DepthExceeded`] / [`Error::BudgetExceeded`] — propagated from
/// [`build_path_candidates`] when the iterator surfaces them.
/// - [`Error::NoValidPath`] — at least one candidate was yielded but none
/// passed `validate_path`. Carries `tried` (>= 1) and the last
/// `validate_path` error rendering.
///
/// # Out of scope
///
/// - Async / parallel candidate evaluation. Candidates are tried sequentially.
/// - Caching of `validate_path` failures across candidates. Each yielded
/// chain is freshly validated.
/// - Promoting [`build_path`] itself to iterate. The single-shot helper is
/// retained verbatim for backward compatibility; callers opt in to the
/// iterating semantics by using this function.
///
/// # Relationship to other path-builder entry points
///
/// | Entry point | Verifier? | Returns |
/// |------------------------------|-----------|----------------------------------------------|
/// | [`build_path`] | No | First DFS topological candidate (one-shot) |
/// | [`build_path_candidates`] | No | Iterator of topological candidates |
/// | [`build_first_valid_path`] | Yes | First candidate that passes `validate_path` |
/// Build a verifier-validated certification path with caller-provided
/// budget and depth tunables.
///
/// Behaves identically to [`build_first_valid_path`] but uses the limits
/// in `config` instead of the workspace defaults. See
/// [`PathBuilderConfig`] for the individual knobs and
/// [`build_first_valid_path`] for full semantics.
///
/// # Errors
///
/// Same as [`build_first_valid_path`].