File: NameConstraints.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (869 lines) | stat: -rw-r--r-- 30,866 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCertificates open source project
//
// Copyright (c) 2022 Apple Inc. and the SwiftCertificates project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

import SwiftASN1

/// Constraints the namespace within which all subject names issued by a given CA must reside.
///
/// These constraints apply both to the ``Certificate/subject`` and also to any
/// ``SubjectAlternativeNames`` that may be present. Restrictions are applied to
/// specific name _forms_, and when the form is not present then the restriction does not apply.
///
/// Restrictions are defined in terms of both permitted and forbidden subtrees. The forbidden trees
/// are consulted first, and if a name is matched in a forbidden tree then it does not matter whether
/// the same name is also matched in a permitted tree.
public struct NameConstraints {
    public struct DNSNames: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
        public typealias Element = String

        @inlinable
        public static func == (lhs: Self, rhs: Self) -> Bool {
            lhs.elementsEqual(rhs)
        }

        @usableFromInline
        var subtrees: [GeneralName]

        @inlinable
        public var description: String {
            "[\(self.joined(separator: ", "))]"
        }

        @inlinable
        init(subtrees: [GeneralName]) {
            self.subtrees = subtrees
        }

        @inlinable
        public init(_ elements: some Sequence<String>) {
            self.subtrees = elements.map { .dnsName($0) }
        }

        @inlinable
        public init(arrayLiteral elements: String...) {
            self.init(elements)
        }

        @inlinable
        public func hash(into hasher: inout Hasher) {
            hasher.combine(contentsOf: self)
        }

        public struct Index: Comparable {
            @inlinable
            public static func < (lhs: Self, rhs: Self) -> Bool {
                lhs.wrapped < rhs.wrapped
            }
            @usableFromInline
            var wrapped: Int

            @inlinable
            init(_ wrapped: Int) {
                self.wrapped = wrapped
            }
        }

        @inlinable
        public var startIndex: Index {
            Index(
                self.subtrees.firstIndex(where: {
                    guard case .dnsName = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public var endIndex: Index {
            Index(self.subtrees.endIndex)
        }

        @inlinable
        public func index(after i: Index) -> Index {
            Index(
                self.subtrees[i.wrapped...].dropFirst().firstIndex(where: {
                    guard case .dnsName = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public subscript(position: Index) -> String {
            guard case .dnsName(let name) = self.subtrees[position.wrapped] else {
                fatalError("index \(position) is not a valid index for \(Self.self)")
            }
            return name
        }

        @inlinable
        var filtered: some Sequence<GeneralName> {
            self.subtrees.lazy.filter {
                guard case .dnsName = $0 else {
                    return false
                }
                return true
            }
        }
    }

    public struct IPRanges: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
        @inlinable
        public static func == (lhs: Self, rhs: Self) -> Bool {
            lhs.elementsEqual(rhs)
        }

        @usableFromInline
        var subtrees: [GeneralName]

        @inlinable
        public var description: String {
            "[\(self.lazy.map { String(describing: $0.bytes) }.joined(separator: ", "))]"
        }

        @inlinable
        init(subtrees: [GeneralName]) {
            self.subtrees = subtrees
        }

        @inlinable
        public init(_ elements: some Sequence<ASN1OctetString>) {
            self.subtrees = elements.map { .ipAddress($0) }
        }

        @inlinable
        public init(arrayLiteral elements: ASN1OctetString...) {
            self.init(elements)
        }

        @inlinable
        public func hash(into hasher: inout Hasher) {
            hasher.combine(contentsOf: self)
        }

        public struct Index: Comparable {
            @inlinable
            public static func < (lhs: Self, rhs: Self) -> Bool {
                lhs.wrapped < rhs.wrapped
            }
            @usableFromInline
            var wrapped: Int

            @inlinable
            init(_ wrapped: Int) {
                self.wrapped = wrapped
            }
        }

        @inlinable
        public var startIndex: Index {
            Index(
                self.subtrees.firstIndex(where: {
                    guard case .ipAddress = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public var endIndex: Index {
            Index(self.subtrees.endIndex)
        }

        @inlinable
        public func index(after i: Index) -> Index {
            Index(
                self.subtrees[i.wrapped...].dropFirst().firstIndex(where: {
                    guard case .ipAddress = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public subscript(position: Index) -> ASN1OctetString {
            guard case .ipAddress(let ipAddress) = self.subtrees[position.wrapped] else {
                fatalError("index \(position) is not a valid index for \(Self.self)")
            }
            return ipAddress
        }

        @inlinable
        var filtered: some Sequence<GeneralName> {
            self.subtrees.lazy.filter {
                guard case .ipAddress = $0 else {
                    return false
                }
                return true
            }
        }
    }

    public struct EmailAddresses: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
        @inlinable
        public static func == (lhs: Self, rhs: Self) -> Bool {
            lhs.elementsEqual(rhs)
        }

        @usableFromInline
        var subtrees: [GeneralName]

        @inlinable
        public var description: String {
            "[\(self.joined(separator: ", "))]"
        }

        @inlinable
        init(subtrees: [GeneralName]) {
            self.subtrees = subtrees
        }

        @inlinable
        public init(_ elements: some Sequence<String>) {
            self.subtrees = elements.map { .rfc822Name($0) }
        }

        @inlinable
        public init(arrayLiteral elements: String...) {
            self.init(elements)
        }

        @inlinable
        public func hash(into hasher: inout Hasher) {
            hasher.combine(contentsOf: self)
        }

        public struct Index: Comparable {
            @inlinable
            public static func < (lhs: Self, rhs: Self) -> Bool {
                lhs.wrapped < rhs.wrapped
            }
            @usableFromInline
            var wrapped: Int

            @inlinable
            init(_ wrapped: Int) {
                self.wrapped = wrapped
            }
        }

        @inlinable
        public var startIndex: Index {
            Index(
                self.subtrees.firstIndex(where: {
                    guard case .rfc822Name = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public var endIndex: Index {
            Index(self.subtrees.endIndex)
        }

        @inlinable
        public func index(after i: Index) -> Index {
            Index(
                self.subtrees[i.wrapped...].dropFirst().firstIndex(where: {
                    guard case .rfc822Name = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public subscript(position: Index) -> String {
            guard case .rfc822Name(let emailAddress) = self.subtrees[position.wrapped] else {
                fatalError("index \(position) is not a valid index for \(Self.self)")
            }
            return emailAddress
        }

        @inlinable
        var filtered: some Sequence<GeneralName> {
            self.subtrees.lazy.filter {
                guard case .rfc822Name = $0 else {
                    return false
                }
                return true
            }
        }
    }

    public struct URIDomains: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
        @inlinable
        public static func == (lhs: Self, rhs: Self) -> Bool {
            lhs.elementsEqual(rhs)
        }

        @usableFromInline
        var subtrees: [GeneralName]

        @inlinable
        public var description: String {
            "[\(self.joined(separator: ", "))]"
        }

        @inlinable
        init(subtrees: [GeneralName]) {
            self.subtrees = subtrees
        }

        @inlinable
        public init(_ elements: some Sequence<String>) {
            self.subtrees = elements.map { .uniformResourceIdentifier($0) }
        }

        @inlinable
        public init(arrayLiteral elements: String...) {
            self.init(elements)
        }

        @inlinable
        public func hash(into hasher: inout Hasher) {
            hasher.combine(contentsOf: self)
        }

        public struct Index: Comparable {
            @inlinable
            public static func < (lhs: Self, rhs: Self) -> Bool {
                lhs.wrapped < rhs.wrapped
            }
            @usableFromInline
            var wrapped: Int

            @inlinable
            init(_ wrapped: Int) {
                self.wrapped = wrapped
            }
        }

        @inlinable
        public var startIndex: Index {
            Index(
                self.subtrees.firstIndex(where: {
                    guard case .uniformResourceIdentifier = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public var endIndex: Index {
            Index(self.subtrees.endIndex)
        }

        @inlinable
        public func index(after i: Index) -> Index {
            Index(
                self.subtrees[i.wrapped...].dropFirst().firstIndex(where: {
                    guard case .uniformResourceIdentifier = $0 else {
                        return false
                    }
                    return true
                }) ?? self.subtrees.endIndex
            )
        }

        @inlinable
        public subscript(position: Index) -> String {
            guard case .uniformResourceIdentifier(let uri) = self.subtrees[position.wrapped] else {
                fatalError("index \(position) is not a valid index for \(Self.self)")
            }
            return uri
        }

        @inlinable
        var filtered: some Sequence<GeneralName> {
            self.subtrees.lazy.filter {
                guard case .uniformResourceIdentifier = $0 else {
                    return false
                }
                return true
            }
        }
    }

    /// The DNS name trees that are permitted in certificates issued by this CA.
    ///
    /// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be
    /// constructed by adding zero or more labels to the left-hand side of the name satisfies the constraint.
    public internal(set) var permittedDNSDomains: DNSNames {
        get {
            DNSNames(subtrees: permittedSubtrees)
        }
        set {
            permittedSubtrees.removeAll {
                guard case .dnsName = $0 else {
                    return false
                }
                return true
            }
            permittedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The DNS name trees that are forbidden in certificates issued by this CA.
    ///
    /// These restrictions are expressed in forms like `host.example.com`. Any DNS name that can be
    /// constructed by adding zero or more labels to the left-hand side of the name satifies the constraint.
    public internal(set) var excludedDNSDomains: DNSNames {
        get {
            DNSNames(subtrees: excludedSubtrees)
        }
        set {
            excludedSubtrees.removeAll {
                guard case .dnsName = $0 else {
                    return false
                }
                return true
            }
            excludedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The IP ranges that are permitted in certificates issued by this CA.
    ///
    /// These restrictions are expressed as a subnet, represented in an ASN.1 octet string.
    /// Due to the absence of a currency subnet and IP address type in Swift, these are preserved
    /// as octet strings.
    ///
    /// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`.
    /// This represents a subnet root and its mask.
    ///
    /// Any IP address attested that falls within one of these subnets matches the constraint.
    public internal(set) var permittedIPRanges: IPRanges {
        get {
            IPRanges(subtrees: permittedSubtrees)
        }
        set {
            permittedSubtrees.removeAll {
                guard case .ipAddress = $0 else {
                    return false
                }
                return true
            }
            permittedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The IP ranges that are forbidden in certificates issued by this CA.
    ///
    /// These restrictions are expressed as a subnet, represented in an ASN.1 octet string.
    /// Due to the absence of a currency subnet and IP address type in Swift, these are preserved
    /// as octet strings.
    ///
    /// As an example, the subnet 192.0.2.0/24 is encoded as the bytes `0xC0, 0x00, 0x02, 0x00, 0xFF, 0xFF, 0xFF, 0x00`.
    /// This represents a subnet root and its mask.
    ///
    /// Any IP address attested that falls within one of these subnets matches the constraint.
    public internal(set) var excludedIPRanges: IPRanges {
        get {
            IPRanges(subtrees: excludedSubtrees)
        }
        set {
            excludedSubtrees.removeAll {
                guard case .ipAddress = $0 else {
                    return false
                }
                return true
            }
            excludedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The email addresses that are permitted in certificates issued by this CA.
    ///
    /// This form may contain a specific mailbox (e.g. `user@example.com`), all
    /// addresses on a given host (e.g. `example.com`), or all mailboxes within a
    /// given domain (e.g. `.example.com`).
    public internal(set) var permittedEmailAddresses: EmailAddresses {
        get {
            EmailAddresses(subtrees: permittedSubtrees)
        }
        set {
            permittedSubtrees.removeAll {
                guard case .rfc822Name = $0 else {
                    return false
                }
                return true
            }
            permittedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The email addresses that are permitted in certificates issued by this CA.
    ///
    /// This form may contain a specific mailbox (e.g. `user@example.com`), all
    /// addresses on a given host (e.g. `example.com`), or all mailboxes within a
    /// given domain (e.g. `.example.com`).
    public internal(set) var excludedEmailAddresses: EmailAddresses {
        get {
            EmailAddresses(subtrees: excludedSubtrees)
        }
        set {
            excludedSubtrees.removeAll {
                guard case .rfc822Name = $0 else {
                    return false
                }
                return true
            }
            excludedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The URI domains permitted in certificates issued by this CA.
    ///
    /// This constraint applies only to the host part of the URI. The constraint
    /// must be specified as a fully-qualified domain name and may specify either
    /// a host or a domain. When it specifies a domain the string will begin with a
    /// period, and matches any name that can be expanded with one or more labels to
    /// the left. Note that expanding with zero labels does not match: that is,
    /// `.example.com` matches `host.example.com`, but not `example.com`.
    public internal(set) var permittedURIDomains: URIDomains {
        get {
            URIDomains(subtrees: permittedSubtrees)
        }
        set {
            permittedSubtrees.removeAll {
                guard case .uniformResourceIdentifier = $0 else {
                    return false
                }
                return true
            }
            permittedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The URI domains forbidden in certificates issued by this CA.
    ///
    /// This constraint applies only to the host part of the URI. The constraint
    /// must be specified as a fully-qualified domain name and may specify either
    /// a host or a domain. When it specifies a domain the string will begin with a
    /// period, and matches any name that can be expanded with one or more labels to
    /// the left. Note that expanding with zero labels does not match: that is,
    /// `.example.com` matches `host.example.com`, but not `example.com`.
    public internal(set) var forbiddenURIDomains: URIDomains {
        get {
            URIDomains(subtrees: excludedSubtrees)
        }
        set {
            excludedSubtrees.removeAll {
                guard case .uniformResourceIdentifier = $0 else {
                    return false
                }
                return true
            }
            excludedSubtrees.append(contentsOf: newValue.filtered)
        }
    }

    /// The complete set of permitted subtrees in ``GeneralName`` form.
    ///
    /// This contains the same data as the broken out forms (``permittedIPRanges``, ``permittedDNSDomains``,
    /// ``permittedURIDomains``, ``permittedEmailAddresses``), but may also include other cases
    /// that those helpers do not represent.
    public var permittedSubtrees: [GeneralName]

    /// The complete set of forbidden subtrees in ``GeneralName`` form.
    ///
    /// This contains the same data as the broken out forms (``excludedIPRanges``, ``excludedDNSDomains``,
    /// ``forbiddenURIDomains``, ``excludedEmailAddresses``), but may also include other cases
    /// that those helpers do not represent.
    public var excludedSubtrees: [GeneralName]

    /// Construct an extension constraining the names a CA may issue.
    ///
    /// - Parameters:
    ///   - permittedDNSDomains: The DNS name trees that are permitted in certificates issued by this CA.
    ///   - excludedDNSDomains: The DNS name trees that are forbidden in certificates issued by this CA.
    ///   - permittedIPRanges: The IP address ranges that are permitted in certificates issued by this CA.
    ///   - excludedIPRanges: The IP address ranges that are forbidden in certificates issued by this CA.
    ///   - permittedEmailAddresses: The email address trees that are permitted in certificates issued by this CA.
    ///   - excludedEmailAddress: The email address trees that are forbidden in certificates issued by this CA.
    ///   - permittedURIDomains: The URI domains that are permitted in certificates issued by this CA.
    ///   - excludedURIDomains: The URI domains that are forbidden in certificates issued by this CA.
    @inlinable
    public init(
        permittedDNSDomains: some Sequence<String> = [],
        excludedDNSDomains: some Sequence<String> = [],
        permittedIPRanges: some Sequence<ASN1OctetString> = [],
        excludedIPRanges: some Sequence<ASN1OctetString> = [],
        permittedEmailAddresses: some Sequence<String> = [],
        excludedEmailAddresses: some Sequence<String> = [],
        permittedURIDomains: some Sequence<String> = [],
        forbiddenURIDomains: some Sequence<String> = []
    ) {
        self.permittedSubtrees = []
        self.permittedSubtrees.reserveCapacity(
            permittedDNSDomains.underestimatedCount + permittedIPRanges.underestimatedCount
                + permittedEmailAddresses.underestimatedCount + permittedURIDomains.underestimatedCount
        )
        self.permittedSubtrees.append(contentsOf: permittedDNSDomains.lazy.map { .dnsName($0) })
        self.permittedSubtrees.append(contentsOf: permittedIPRanges.lazy.map { .ipAddress($0) })
        self.permittedSubtrees.append(contentsOf: permittedEmailAddresses.lazy.map { .rfc822Name($0) })
        self.permittedSubtrees.append(contentsOf: permittedURIDomains.lazy.map { .uniformResourceIdentifier($0) })

        self.excludedSubtrees = []
        self.excludedSubtrees.reserveCapacity(
            excludedDNSDomains.underestimatedCount + excludedIPRanges.underestimatedCount
                + excludedEmailAddresses.underestimatedCount + forbiddenURIDomains.underestimatedCount
        )
        self.excludedSubtrees.append(contentsOf: excludedDNSDomains.lazy.map { .dnsName($0) })
        self.excludedSubtrees.append(contentsOf: excludedIPRanges.lazy.map { .ipAddress($0) })
        self.excludedSubtrees.append(contentsOf: excludedEmailAddresses.lazy.map { .rfc822Name($0) })
        self.excludedSubtrees.append(contentsOf: forbiddenURIDomains.lazy.map { .uniformResourceIdentifier($0) })
    }

    /// Construct an extension constraining the names a CA may issue.
    ///
    /// - Parameters:
    ///   - permittedSubtrees: The complete set of permitted subtrees in ``GeneralName`` form.
    ///   - excludedSubtrees: The complete set of excluded subtrees in ``GeneralName`` form.
    @inlinable
    public init(
        permittedSubtrees: [GeneralName] = [],
        excludedSubtrees: [GeneralName] = []
    ) {
        self.permittedSubtrees = permittedSubtrees
        self.excludedSubtrees = excludedSubtrees
    }

    /// Create a new ``NameConstraints`` object
    /// by unwrapping a ``Certificate/Extension``.
    ///
    /// - Parameter ext: The ``Certificate/Extension`` to unwrap
    /// - Throws: if the ``Certificate/Extension/oid`` is not equal to
    ///     `ASN1ObjectIdentifier.X509ExtensionID.nameConstraints`.
    @inlinable
    public init(_ ext: Certificate.Extension) throws {
        guard ext.oid == .X509ExtensionID.nameConstraints else {
            throw CertificateError.incorrectOIDForExtension(
                reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.nameConstraints), got \(ext.oid)"
            )
        }

        let nameConstraintsValue = try NameConstraintsValue(derEncoded: ext.value)
        guard nameConstraintsValue.permittedSubtrees != nil || nameConstraintsValue.excludedSubtrees != nil else {
            throw ASN1Error.invalidASN1Object(reason: "Name Constraints has no permitted or excluded subtrees")
        }

        self.permittedSubtrees = nameConstraintsValue.permittedSubtrees ?? []
        self.excludedSubtrees = nameConstraintsValue.excludedSubtrees ?? []
    }
}

extension Hasher {
    @inlinable
    mutating func combine(contentsOf elements: some Sequence<some Hashable>) {
        for element in elements {
            self.combine(element)
        }
    }
}

extension NameConstraints: Hashable {}

extension NameConstraints: Sendable {}

extension NameConstraints: CustomStringConvertible {
    public var description: String {
        var elements: [String] = []

        if self.permittedSubtrees.count > 0 {
            elements.append(
                "permittedSubtrees: [\(self.permittedSubtrees.map { String(reflecting: $0) }.joined(separator: ", "))]"
            )
        }
        if self.excludedSubtrees.count > 0 {
            elements.append(
                "excludedSubtrees: [\(self.excludedSubtrees.map { String(reflecting: $0) }.joined(separator: ", "))]"
            )
        }

        return elements.joined(separator: ", ")
    }
}

extension NameConstraints: CustomDebugStringConvertible {
    public var debugDescription: String {
        return "NameConstraints(\(String(describing: self)))"
    }
}

extension Certificate.Extension {
    /// Construct an opaque ``Certificate/Extension`` from this Name Constraints extension.
    ///
    /// - Parameters:
    ///   - nameConstraints: The extension to wrap
    ///   - critical: Whether this extension should have the critical bit set.
    @inlinable
    public init(_ nameConstraints: NameConstraints, critical: Bool) throws {
        let asn1Representation = NameConstraintsValue(nameConstraints)
        var serializer = DER.Serializer()
        try serializer.serialize(asn1Representation)
        self.init(oid: .X509ExtensionID.nameConstraints, critical: critical, value: serializer.serializedBytes[...])
    }
}

extension NameConstraints: CertificateExtensionConvertible {
    public func makeCertificateExtension() throws -> Certificate.Extension {
        return try .init(self, critical: false)
    }
}

// MARK: ASN1 Helpers
@usableFromInline
struct NameConstraintsValue: DERImplicitlyTaggable {
    @inlinable
    static var defaultIdentifier: ASN1Identifier {
        .sequence
    }

    @usableFromInline
    var permittedSubtrees: [GeneralName]?

    @usableFromInline
    var excludedSubtrees: [GeneralName]?

    @inlinable
    init(permittedSubtrees: [GeneralName]?, excludedSubtrees: [GeneralName]?) {
        self.permittedSubtrees = permittedSubtrees
        self.excludedSubtrees = excludedSubtrees
    }

    @inlinable
    init(_ ext: NameConstraints) {
        if !ext.permittedSubtrees.isEmpty {
            self.permittedSubtrees = ext.permittedSubtrees
        }
        if !ext.excludedSubtrees.isEmpty {
            self.excludedSubtrees = ext.excludedSubtrees
        }
    }

    @inlinable
    init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
        self = try DER.sequence(rootNode, identifier: identifier) { nodes in
            let permittedSubtrees: GeneralSubtrees? = try DER.optionalImplicitlyTagged(
                &nodes,
                tag: .init(tagWithNumber: 0, tagClass: .contextSpecific)
            )
            let excludedSubtrees: GeneralSubtrees? = try DER.optionalImplicitlyTagged(
                &nodes,
                tag: .init(tagWithNumber: 1, tagClass: .contextSpecific)
            )

            return NameConstraintsValue(
                permittedSubtrees: permittedSubtrees.map { $0.base },
                excludedSubtrees: excludedSubtrees.map { $0.base }
            )
        }
    }

    @inlinable
    func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
        try coder.appendConstructedNode(identifier: identifier) { coder in
            try coder.serializeOptionalImplicitlyTagged(
                self.permittedSubtrees.map { GeneralSubtrees($0) },
                withIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific)
            )

            try coder.serializeOptionalImplicitlyTagged(
                self.excludedSubtrees.map { GeneralSubtrees($0) },
                withIdentifier: .init(tagWithNumber: 1, tagClass: .contextSpecific)
            )
        }
    }
}

// This type does a weird cheat.
//
// Technically, NameConstraints is defined like this:
//
//       NameConstraints ::= SEQUENCE {
//            permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
//            excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
//
//       GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
//
//       GeneralSubtree ::= SEQUENCE {
//            base                    GeneralName,
//            minimum         [0]     BaseDistance DEFAULT 0,
//            maximum         [1]     BaseDistance OPTIONAL }
//
//       BaseDistance ::= INTEGER (0..MAX)
//
// We can disregard `BaseDistance`, because as a practical matter it is never used, and so it's as though those
// two fields were never there.
//
// The result is that each of the subtrees encodes as a sequence of sequence of single general name. We could
// literally mirror that in Swift land, but at the top level we want to hold [GeneralName], so producing
// [GeneralSubtree] will force a heap allocation. Instead, we inline the definition of GeneralSubtree into
// GeneralSubtrees, to avoid the extra allocation.
@usableFromInline
struct GeneralSubtrees: DERImplicitlyTaggable {
    @inlinable
    static var defaultIdentifier: ASN1Identifier {
        .sequence
    }

    @usableFromInline
    var base: [GeneralName]

    @inlinable
    init(_ base: [GeneralName]) {
        self.base = base
    }

    @inlinable
    init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
        self.base = try DER.sequence(rootNode, identifier: identifier) { nodes in
            var names: [GeneralName] = []
            while let node = nodes.next() {
                let name = try DER.sequence(node, identifier: .sequence) { nodes in
                    try GeneralName(derEncoded: &nodes)
                }
                names.append(name)
            }
            return names
        }
    }

    @inlinable
    func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
        try coder.appendConstructedNode(identifier: identifier) { coder in
            for name in self.base {
                try coder.appendConstructedNode(identifier: .sequence) { coder in
                    try coder.serialize(name)
                }
            }
        }
    }
}