Police uniqueness of ExtendedKeyUsage (#90)

* We don’t need to maintain uniqueness

* Police uniqueness of `ExtendedKeyUsage`

* use new error case

* call `insert` from `append`

* refactor duplication finding algorithm into reusable method
This commit is contained in:
David Nadoba authored and GitHub committed 2023-06-02 13:30:51 +01:00
1 parent 1b747c3295
commit 99814e7cdd
8 files changed
+220 -22

No files matched your search

@@ -73,7 +73,6 @@ extension AuthorityInformationAccess: RandomAccessCollection {
@inlinable
public subscript(position: Int) -> AccessDescription {
// TODO(cory): Maintain uniqueness
get {
self.descriptions[position]
}
@@ -26,8 +26,13 @@ public struct ExtendedKeyUsage {
///
/// - Parameter usages: The purposes for which the certificate may be used.
@inlinable
public init<Usages: Sequence>(_ usages: Usages) where Usages.Element == Usage {
public init<Usages: Sequence>(_ usages: Usages) throws where Usages.Element == Usage {
self.usages = Array(usages)
if let (firstIndex, secondIndex) = self.usages.findDuplicates(by: ==) {
let usage = self.usages[firstIndex]
throw CertificateError.duplicateOID(reason: "duplicate \(usage) usage. First at \(firstIndex) and second at \(secondIndex)")
}
}
/// Create a new ``ExtendedKeyUsage`` object
@@ -43,7 +48,36 @@ public struct ExtendedKeyUsage {
}
let asn1EKU = try ASN1ExtendedKeyUsage(derEncoded: ext.value)
self.usages = asn1EKU.usages.map { Usage(oid: $0) }
try self.init(asn1EKU.usages.map { Usage(oid: $0) })
}
/// Create a new empty ``ExtendedKeyUsage`` object with no usages.
@inlinable
public init() {
self.usages = []
}
}
extension Array {
@inlinable
/// Searches for duplicates using a linear scan.
/// This is more performant compared to hashing if we have less than ~64 usages
/// - Parameter areEqual: a predicate that returns true if the first and second arguments are considered equal
/// - Returns: a tuple of the first two indices duplicates found in `self`. `nil` is returned if no duplicates are found.
func findDuplicates(
by areEqual: (Element, Element) -> Bool
) -> (first: Index, second: Index)? {
for index in self.indices {
let usage = self[index]
for currentIndex in self.indices[index...].dropFirst() {
let currentUsage = self[currentIndex]
if areEqual(usage, currentUsage) {
return (index, currentIndex)
}
}
}
return nil
}
}
@@ -70,13 +104,61 @@ extension ExtendedKeyUsage: RandomAccessCollection {
}
public subscript(position: Int) -> Usage {
// TODO(cory): Maintain uniqueness
get {
self.usages[position]
}
set {
self.usages[position] = newValue
}
}
extension ExtendedKeyUsage {
/// Append a new `usage` to the end of the ``ExtendedKeyUsage``, if it doesn't
/// already contain it.
///
/// - Parameter usage: The ``Usage`` to add to the set.
///
/// - Returns: A pair `(inserted, index)`, where `inserted` is a Boolean value
/// indicating whether the operation added a new element, and `index` is
/// the index of `usage` in the resulting ``ExtendedKeyUsage``.
@inlinable
@discardableResult
public mutating func append(_ usage: Element) -> (inserted: Bool, index: Int) {
self.insert(usage, at: self.endIndex)
}
/// Insert a new `usage` to this set at the specified index, if `self` doesn't
/// already contain it.
///
/// - Parameters:
/// - usage: The ``Usage`` to insert if not already present.
/// - index: The index to insert `usage` if not already present.
///
/// - Returns: A pair `(inserted, index)`, where `inserted` is a Boolean value
/// indicating whether the operation added a new element, and `index` is
/// the index of `item` in the resulting set. If `inserted` is false, then
/// the returned `index` may be different from the index requested.
@inlinable
@discardableResult
public mutating func insert(
_ usage: Element,
at index: Int
) -> (inserted: Bool, index: Int) {
guard let index = self.usages.firstIndex(of: usage) else {
self.usages.insert(usage, at: index)
return (true, index)
}
return (false, index)
}
/// Removes the given `usage` from `self`, if present.
/// - Parameter usage: The ``Usage`` to remove.
/// - Returns: The ``Usage`` that was removed or `nil` if `usage` was not present.
@inlinable
@discardableResult
public mutating func remove(_ usage: Element) -> Element? {
guard let index = self.usages.firstIndex(where: { $0 == usage }) else {
return nil
}
return self.usages.remove(at: index)
}
}
+4 -10
View File
@@ -89,16 +89,10 @@ extension Certificate {
public init<Elements>(_ extensions: Elements) throws where Elements: Sequence, Elements.Element == Extension {
self._extensions = Array(extensions)
// check for duplicates using a linear scan
// this is more performant compared to hashing if we have less than ~64 extensions
for index in self._extensions.indices {
let ext = self._extensions[index]
for currentIndex in self._extensions.indices.dropFirst(index + 1) {
let currentExt = self._extensions[currentIndex]
if ext.oid == currentExt.oid {
throw CertificateError.duplicateOID(reason: "duplicate extension for OID \(ext.oid). First extension \(ext) at \(index) and second extension \(currentExt) at \(currentIndex)")
}
}
if let (firstIndex, secondIndex) = self._extensions.findDuplicates(by: { $0.oid == $1.oid }) {
let firstExt = self._extensions[firstIndex]
let secondExt = self._extensions[secondIndex]
throw CertificateError.duplicateOID(reason: "duplicate extension for OID \(firstExt.oid). First extension \(firstExt) at \(firstIndex) and second extension \(secondExt) at \(secondIndex)")
}
}
+1 -1
View File
@@ -66,7 +66,7 @@ struct OCSPResponderSigningPolicy: VerifierPolicy {
return .failsToMeetPolicy(reason: "OCSP response certificate has no extended key usages")
}
guard extendedKeyUsage.usages.contains(.init(oid: .ExtendedKeyUsage.ocspSigning)) else {
guard extendedKeyUsage.usages.contains(.ocspSigning) else {
return .failsToMeetPolicy(reason: "OCSP response certificate does not have OCSP signing extended key usage set")
}
+2 -2
View File
@@ -216,7 +216,7 @@ final class CertificateDERTests: XCTestCase {
)
XCTAssertEqual(
try cert.extensions.extendedKeyUsage,
.init([.serverAuth, .clientAuth])
try .init([.serverAuth, .clientAuth])
)
XCTAssertEqual(
try cert.extensions.basicConstraints,
@@ -243,7 +243,7 @@ final class CertificateDERTests: XCTestCase {
KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true)
)
ExtendedKeyUsage([.serverAuth, .clientAuth])
try ExtendedKeyUsage([.serverAuth, .clientAuth])
Critical(
BasicConstraints.isCertificateAuthority(maxPathLength: 0)
+1 -1
View File
@@ -242,7 +242,7 @@ final class CertificateTests: XCTestCase {
}
func testPrintingEKU() throws {
let eku = ExtendedKeyUsage([
let eku = try ExtendedKeyUsage([
.any,
.certificateTransparency,
.timeStamping,
+122
View File
@@ -0,0 +1,122 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCertificates open source project
//
// Copyright (c) 2023 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 XCTest
import X509
final class ExtendedKeyUsageTests: XCTestCase {
func testInit() {
XCTAssertThrowsError(try ExtendedKeyUsage([
.serverAuth,
.serverAuth,
])) { error in
XCTAssertEqual((error as? CertificateError)?.code, .duplicateOID, "wrong error \(error)")
}
XCTAssertThrowsError(try ExtendedKeyUsage([
.clientAuth,
.serverAuth,
.clientAuth,
])) { error in
XCTAssertEqual((error as? CertificateError)?.code, .duplicateOID, "wrong error \(error)")
}
}
func testInsert() throws {
var usages = try ExtendedKeyUsage([
.serverAuth,
])
XCTAssertTrue(usages.insert(.clientAuth, at: 1) == (true, 1))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.clientAuth,
]))
XCTAssertTrue(usages.insert(.clientAuth, at: 1) == (false, 1))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.clientAuth,
]))
XCTAssertTrue(usages.insert(.ocspSigning, at: 1) == (true, 1))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
.clientAuth,
]))
XCTAssertTrue(usages.insert(.codeSigning, at: 0) == (true, 0))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.codeSigning,
.serverAuth,
.ocspSigning,
.clientAuth,
]))
}
func testAppend() throws {
var usages = ExtendedKeyUsage()
usages.append(.clientAuth)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.clientAuth,
]))
usages.append(.clientAuth)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.clientAuth,
]))
usages.append(.ocspSigning)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.clientAuth,
.ocspSigning,
]))
}
func testRemove() throws {
var usages = try ExtendedKeyUsage([
.clientAuth,
.serverAuth,
.ocspSigning,
])
XCTAssertNil(usages.remove(.emailProtection))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.clientAuth,
.serverAuth,
.ocspSigning,
]))
XCTAssertEqual(usages.remove(.clientAuth), .clientAuth)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
]))
XCTAssertNil(usages.remove(.clientAuth))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
]))
XCTAssertEqual(usages.remove(.ocspSigning), .ocspSigning)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
]))
XCTAssertEqual(usages.remove(.serverAuth), .serverAuth)
XCTAssertEqual(usages, ExtendedKeyUsage())
XCTAssertNil(usages.remove(.serverAuth))
XCTAssertEqual(usages, ExtendedKeyUsage())
}
}
+3 -2
View File
@@ -183,12 +183,13 @@ final class ExtensionBuilderTests: XCTestCase {
}
XCTAssertThrowsError(try Certificate.Extensions {
ExtendedKeyUsage([.serverAuth])
ExtendedKeyUsage([.clientAuth])
try ExtendedKeyUsage([.serverAuth])
try ExtendedKeyUsage([.clientAuth])
}) { error in
XCTAssertEqual((error as? CertificateError)?.code, .duplicateOID, "wrong error \(error)")
}
}
func testAppend() {
var extensions = Certificate.Extensions()
XCTAssertNoThrow(try extensions.append(.init(oid: [1], critical: false, value: [1])))