Adopt apple/swift-format (#121)

* Adopt `apple/swift-format`

* install swift-format

* set `UseSynthesizedInitializer` to `false` until bug is fixed https://github.com/apple/swift-format/issues/591

* fix license header

* Fix license header
This commit is contained in:
David Nadoba authored and GitHub committed 2023-08-16 11:17:34 +01:00
1 parent 98e0f85457
commit 45ad9935c7
100 files changed
+4683 -2472

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
{
"fileScopedDeclarationPrivacy" : {
"accessLevel" : "private"
},
"indentation" : {
"spaces" : 4
},
"indentConditionalCompilationBlocks" : false,
"indentSwitchCaseLabels" : false,
"lineBreakAroundMultilineExpressionChainComponents" : false,
"lineBreakBeforeControlFlowKeywords" : false,
"lineBreakBeforeEachArgument" : true,
"lineBreakBeforeEachGenericRequirement" : true,
"lineLength" : 120,
"maximumBlankLines" : 1,
"prioritizeKeepingFunctionOutputTogether" : true,
"respectsExistingLineBreaks" : true,
"rules" : {
"AllPublicDeclarationsHaveDocumentation" : false,
"AlwaysUseLowerCamelCase" : false,
"AmbiguousTrailingClosureOverload" : true,
"BeginDocumentationCommentWithOneLineSummary" : false,
"DoNotUseSemicolons" : true,
"DontRepeatTypeInStaticProperties" : true,
"FileScopedDeclarationPrivacy" : true,
"FullyIndirectEnum" : true,
"GroupNumericLiterals" : true,
"IdentifiersMustBeASCII" : true,
"NeverForceUnwrap" : false,
"NeverUseForceTry" : false,
"NeverUseImplicitlyUnwrappedOptionals" : false,
"NoAccessLevelOnExtensionDeclaration" : false,
"NoAssignmentInExpressions" : true,
"NoBlockComments" : true,
"NoCasesWithOnlyFallthrough" : true,
"NoEmptyTrailingClosureParentheses" : true,
"NoLabelsInCasePatterns" : false,
"NoLeadingUnderscores" : false,
"NoParensAroundConditions" : true,
"NoVoidReturnOnFunctionSignature" : true,
"OneCasePerLine" : true,
"OneVariableDeclarationPerLine" : true,
"OnlyOneTrailingClosureArgument" : true,
"OrderedImports" : false,
"ReturnVoidInsteadOfEmptyTuple" : true,
"UseEarlyExits" : true,
"UseLetInEveryBoundCaseVariable" : false,
"UseShorthandTypeNames" : true,
"UseSingleLinePropertyGetter" : false,
"UseSynthesizedInitializer" : false,
"UseTripleSlashForDocumentationComments" : true,
"UseWhereClausesInForLoops" : false,
"ValidateDocumentationComments" : false
},
"spacesAroundRangeFormationOperators" : false,
"tabWidth" : 8,
"version" : 1
}
+8
View File
@@ -78,3 +78,11 @@ This product contains derivations of various scripts from SwiftNIO SSH.
* HOMEPAGE:
* https://github.com/apple/swift-nio-ssh
---
This product contains derivations of various scripts from Swift OpenAPI Generator.
* LICENSE (Apache License 2.0):
* https://www.apache.org/licenses/LICENSE-2.0
* HOMEPAGE:
* https://github.com/apple/swift-openapi-generator
+2 -2
View File
@@ -49,7 +49,7 @@ extension CertificateSigningRequest {
extension CertificateSigningRequest.Attribute: Hashable {
@inlinable
public static func ==(lhs: CertificateSigningRequest.Attribute, rhs: CertificateSigningRequest.Attribute) -> Bool {
public static func == (lhs: CertificateSigningRequest.Attribute, rhs: CertificateSigningRequest.Attribute) -> Bool {
if lhs.oid != rhs.oid { return false }
if lhs.values.count != rhs.values.count { return false }
@@ -78,7 +78,7 @@ extension CertificateSigningRequest.Attribute: Hashable {
}
}
extension CertificateSigningRequest.Attribute: Sendable { }
extension CertificateSigningRequest.Attribute: Sendable {}
extension CertificateSigningRequest.Attribute: CustomStringConvertible {
public var description: String {
+7 -5
View File
@@ -42,7 +42,7 @@ extension CertificateSigningRequest {
public struct Attributes {
@usableFromInline
var _attributes: [Attribute]
/// Produce a new Attributes container from a collection of ``CertificateSigningRequest/Attribute``.
///
/// - Parameter attributes: The base attributes.
@@ -59,9 +59,10 @@ extension CertificateSigningRequest {
extension CertificateSigningRequest.Attributes: Hashable {
@inlinable
public static func ==(lhs: CertificateSigningRequest.Attributes, rhs: CertificateSigningRequest.Attributes) -> Bool {
public static func == (lhs: CertificateSigningRequest.Attributes, rhs: CertificateSigningRequest.Attributes) -> Bool
{
if lhs.count != rhs.count { return false }
for element in lhs {
if !rhs.contains(element) { return false }
}
@@ -84,7 +85,7 @@ extension CertificateSigningRequest.Attributes: Hashable {
}
}
extension CertificateSigningRequest.Attributes: Sendable { }
extension CertificateSigningRequest.Attributes: Sendable {}
extension CertificateSigningRequest.Attributes: RandomAccessCollection {
@inlinable
@@ -127,7 +128,8 @@ extension CertificateSigningRequest.Attributes: RandomAccessCollection {
///
/// - Parameter extensions: The sequence of new ``Certificate/Attribute``s to insert.
@inlinable
public mutating func insert<Extensions: Sequence>(contentsOf extensions: Extensions) where Extensions.Element == CertificateSigningRequest.Attribute {
public mutating func insert<Extensions: Sequence>(contentsOf extensions: Extensions)
where Extensions.Element == CertificateSigningRequest.Attribute {
for element in extensions {
self[oid: element.oid] = element
}
+2 -2
View File
@@ -30,9 +30,9 @@ extension CertificateSigningRequest {
}
}
extension CertificateSigningRequest.Version: Hashable { }
extension CertificateSigningRequest.Version: Hashable {}
extension CertificateSigningRequest.Version: Sendable { }
extension CertificateSigningRequest.Version: Sendable {}
extension CertificateSigningRequest.Version: Comparable {
@inlinable
@@ -103,7 +103,9 @@ public struct CertificateSigningRequest {
self.signatureAlgorithm = signatureAlgorithm
self.signature = signature
self.infoBytes = try DER.Serializer.serialized(element: self.info)[...]
self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm))[...]
self.signatureAlgorithmBytes = try DER.Serializer.serialized(
element: AlgorithmIdentifier(self.signatureAlgorithm)
)[...]
self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...]
}
@@ -137,7 +139,9 @@ public struct CertificateSigningRequest {
let infoBytes = try DER.Serializer.serialized(element: self.info)
self.signature = try privateKey.sign(bytes: infoBytes, signatureAlgorithm: signatureAlgorithm)
self.infoBytes = infoBytes[...]
self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm))[...]
self.signatureAlgorithmBytes = try DER.Serializer.serialized(
element: AlgorithmIdentifier(self.signatureAlgorithm)
)[...]
self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...]
}
@@ -152,21 +156,25 @@ public struct CertificateSigningRequest {
) throws {
self.info = info
self.signatureAlgorithm = Certificate.SignatureAlgorithm(algorithmIdentifier: signatureAlgorithm)
self.signature = try Certificate.Signature(signatureAlgorithm: self.signatureAlgorithm, signatureBytes: signature)
self.signature = try Certificate.Signature(
signatureAlgorithm: self.signatureAlgorithm,
signatureBytes: signature
)
self.infoBytes = infoBytes
self.signatureAlgorithmBytes = signatureAlgorithmBytes
self.signatureBytes = signatureBytes
}
}
extension CertificateSigningRequest: Hashable { }
extension CertificateSigningRequest: Hashable {}
extension CertificateSigningRequest: Sendable { }
extension CertificateSigningRequest: Sendable {}
extension CertificateSigningRequest: CustomStringConvertible {
@inlinable
public var description: String {
return "CertificateSigningRequest(version: \(self.version), subject: \(self.subject), publicKey: \(self.publicKey), attributes: \(self.attributes), signatureAlgorithm: \(self.signatureAlgorithm), signature: \(self.signature)"
return
"CertificateSigningRequest(version: \(self.version), subject: \(self.subject), publicKey: \(self.publicKey), attributes: \(self.attributes), signatureAlgorithm: \(self.signatureAlgorithm), signature: \(self.signature)"
}
}
@@ -180,8 +188,8 @@ extension CertificateSigningRequest: DERImplicitlyTaggable {
public init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
guard let infoNode = nodes.next(),
let signatureAlgorithmNode = nodes.next(),
let signatureNode = nodes.next()
let signatureAlgorithmNode = nodes.next(),
let signatureNode = nodes.next()
else {
throw ASN1Error.invalidASN1Object(reason: "Invalid CSR object, insufficient ASN.1 nodes")
}
@@ -41,9 +41,9 @@ struct CertificationRequestInfo {
}
}
extension CertificationRequestInfo: Hashable { }
extension CertificationRequestInfo: Hashable {}
extension CertificationRequestInfo: Sendable { }
extension CertificationRequestInfo: Sendable {}
// CertificationRequestInfo ::= SEQUENCE {
// version INTEGER { v1(0) } (v1,...),
+10 -3
View File
@@ -39,11 +39,15 @@ public struct ExtensionRequest: Hashable, Sendable {
@inlinable
public init(_ attribute: CertificateSigningRequest.Attribute) throws {
guard attribute.oid == .CSRAttributes.extensionRequest else {
throw CertificateError.incorrectOIDForAttribute(reason: "Expected \(ASN1ObjectIdentifier.CSRAttributes.extensionRequest), got \(attribute.oid)")
throw CertificateError.incorrectOIDForAttribute(
reason: "Expected \(ASN1ObjectIdentifier.CSRAttributes.extensionRequest), got \(attribute.oid)"
)
}
guard attribute.values.count == 1 else {
throw CertificateError.invalidCSRAttribute(reason: "Invalid number of values for extension request attribute: \(attribute.values)")
throw CertificateError.invalidCSRAttribute(
reason: "Invalid number of values for extension request attribute: \(attribute.values)"
)
}
let extRequest = try ExtensionRequestAttribute(asn1Any: attribute.values.first!)
@@ -58,7 +62,10 @@ extension CertificateSigningRequest.Attribute {
/// - extensionRequest: The ``ExtensionRequest`` to wrap.
@inlinable
public init(_ extensionRequest: ExtensionRequest) throws {
self.init(oid: .CSRAttributes.extensionRequest, values: [try ASN1Any(erasing: ExtensionRequestAttribute(extensionRequest))])
self.init(
oid: .CSRAttributes.extensionRequest,
values: [try ASN1Any(erasing: ExtensionRequestAttribute(extensionRequest))]
)
}
}
+11 -6
View File
@@ -183,7 +183,10 @@ public struct Certificate {
serialNumber: serialNumber,
signature: signatureAlgorithm,
issuer: issuer,
validity: try Validity(notBefore: .makeTime(from: notValidBefore), notAfter: .makeTime(from: notValidAfter)),
validity: try Validity(
notBefore: .makeTime(from: notValidBefore),
notAfter: .makeTime(from: notValidAfter)
),
subject: subject,
publicKey: publicKey,
extensions: extensions
@@ -193,7 +196,9 @@ public struct Certificate {
let tbsCertificateBytes = try DER.Serializer.serialized(element: self.tbsCertificate)[...]
self.signature = try issuerPrivateKey.sign(bytes: tbsCertificateBytes, signatureAlgorithm: signatureAlgorithm)
self.tbsCertificateBytes = tbsCertificateBytes
self.signatureAlgorithmBytes = try DER.Serializer.serialized(element: AlgorithmIdentifier(self.signatureAlgorithm))[...]
self.signatureAlgorithmBytes = try DER.Serializer.serialized(
element: AlgorithmIdentifier(self.signatureAlgorithm)
)[...]
self.signatureBytes = try DER.Serializer.serialized(element: ASN1BitString(self.signature))[...]
}
@@ -215,9 +220,9 @@ public struct Certificate {
}
}
extension Certificate: Hashable { }
extension Certificate: Hashable {}
extension Certificate: Sendable { }
extension Certificate: Sendable {}
extension Certificate: CustomStringConvertible {
public var description: String {
@@ -247,8 +252,8 @@ extension Certificate: DERImplicitlyTaggable {
public init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
guard let tbsCertificateNode = nodes.next(),
let signatureAlgorithmNode = nodes.next(),
let signatureNode = nodes.next()
let signatureAlgorithmNode = nodes.next(),
let signatureNode = nodes.next()
else {
throw ASN1Error.invalidASN1Object(reason: "Invalid certificate object, insufficient ASN.1 nodes")
}
+44 -28
View File
@@ -62,7 +62,7 @@ extension Certificate {
public init(_ rsa: _RSA.Signing.PrivateKey) {
self.backing = .rsa(rsa)
}
#if canImport(Darwin)
/// Construct a private key wrapping a SecureEnclave.P256 private key.
/// - Parameter secureEnclaveP256: The SecureEnclave.P256 private key to wrap.
@@ -73,7 +73,10 @@ extension Certificate {
#endif
@inlinable
internal func sign<Bytes: DataProtocol>(bytes: Bytes, signatureAlgorithm: SignatureAlgorithm) throws -> Signature {
internal func sign<Bytes: DataProtocol>(
bytes: Bytes,
signatureAlgorithm: SignatureAlgorithm
) throws -> Signature {
try self.validateAlgorithmForKey(algorithm: signatureAlgorithm)
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
@@ -119,16 +122,22 @@ extension Certificate {
switch self.backing {
case .p256, .p384, .p521:
if !algorithm.isECDSA {
throw CertificateError.unsupportedSignatureAlgorithm(reason: "Cannot use \(algorithm) with ECDSA key \(self)")
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with ECDSA key \(self)"
)
}
case .rsa:
if !algorithm.isRSA {
throw CertificateError.unsupportedSignatureAlgorithm(reason: "Cannot use \(algorithm) with RSA key \(self)")
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with RSA key \(self)"
)
}
#if canImport(Darwin)
case .secureEnclaveP256:
if !algorithm.isECDSA {
throw CertificateError.unsupportedSignatureAlgorithm(reason: "Cannot use \(algorithm) with ECDSA key \(self)")
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot use \(algorithm) with ECDSA key \(self)"
)
}
#endif
}
@@ -137,9 +146,9 @@ extension Certificate {
}
}
extension Certificate.PrivateKey: Hashable { }
extension Certificate.PrivateKey: Hashable {}
extension Certificate.PrivateKey: Sendable { }
extension Certificate.PrivateKey: Sendable {}
extension Certificate.PrivateKey: CustomStringConvertible {
public var description: String {
@@ -159,7 +168,7 @@ extension Certificate.PrivateKey {
#endif
@inlinable
static func ==(lhs: BackingPrivateKey, rhs: BackingPrivateKey) -> Bool {
static func == (lhs: BackingPrivateKey, rhs: BackingPrivateKey) -> Bool {
switch (lhs, rhs) {
case (.p256(let l), .p256(let r)):
return l.rawRepresentation == r.rawRepresentation
@@ -206,52 +215,55 @@ extension Certificate.PrivateKey {
@available(macOS 11.0, iOS 14, tvOS 14, watchOS 7, *)
extension Certificate.PrivateKey {
@inlinable
static var pemDiscriminatorForRSAPrivateKey: String { "RSA PRIVATE KEY" }
static var pemDiscriminatorForRSA: String { "RSA PRIVATE KEY" }
@inlinable
static var pemDiscriminatorForSEC1PrivateKey: String { "EC PRIVATE KEY" }
static var pemDiscriminatorForSEC1: String { "EC PRIVATE KEY" }
@inlinable
static var pemDiscriminatorForPKCS8PrivateKey: String { "PRIVATE KEY" }
static var pemDiscriminatorForPKCS8: String { "PRIVATE KEY" }
@inlinable
public init(pemEncoded: String) throws {
try self.init(pemDocument: PEMDocument(pemString: pemEncoded))
}
@inlinable
public init(pemDocument: PEMDocument) throws {
switch pemDocument.discriminator {
case Self.pemDiscriminatorForRSAPrivateKey:
case Self.pemDiscriminatorForRSA:
self = try .init(_CryptoExtras._RSA.Signing.PrivateKey.init(derRepresentation: pemDocument.derBytes))
case Self.pemDiscriminatorForSEC1PrivateKey:
case Self.pemDiscriminatorForSEC1:
let sec1 = try SEC1PrivateKey(derEncoded: pemDocument.derBytes)
self = try .init(ecdsaAlgorithm: sec1.algorithm, rawEncodedPrivateKey: sec1.privateKey.bytes)
case Self.pemDiscriminatorForPKCS8PrivateKey:
case Self.pemDiscriminatorForPKCS8:
let pkcs8 = try PKCS8PrivateKey(derEncoded: pemDocument.derBytes)
switch pkcs8.algorithm {
case .ecdsaP256, .ecdsaP384, .ecdsaP521:
let sec1 = try SEC1PrivateKey(derEncoded: pkcs8.privateKey.bytes)
if let innerAlgorithm = sec1.algorithm, innerAlgorithm != pkcs8.algorithm {
throw ASN1Error.invalidASN1Object(reason: "algorithm missmatch. PKCS#8 is \(pkcs8.algorithm) but inner SEC1 is \(innerAlgorithm)")
throw ASN1Error.invalidASN1Object(
reason: "algorithm missmatch. PKCS#8 is \(pkcs8.algorithm) but inner SEC1 is \(innerAlgorithm)"
)
}
self = try .init(ecdsaAlgorithm: pkcs8.algorithm, rawEncodedPrivateKey: sec1.privateKey.bytes)
case .rsaKey:
self = try .init(_CryptoExtras._RSA.Signing.PrivateKey(derRepresentation: pkcs8.privateKey.bytes))
default:
throw CertificateError.unsupportedPrivateKey(reason: "unknown algorithm \(pkcs8.algorithm)")
}
default:
throw ASN1Error.invalidPEMDocument(
reason: "PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.pemDiscriminatorForPKCS8PrivateKey), \(Self.pemDiscriminatorForSEC1PrivateKey) or \(Self.pemDiscriminatorForRSAPrivateKey) instead"
reason:
"PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.pemDiscriminatorForPKCS8), \(Self.pemDiscriminatorForSEC1) or \(Self.pemDiscriminatorForRSA) instead"
)
}
}
@inlinable
init(ecdsaAlgorithm: AlgorithmIdentifier?, rawEncodedPrivateKey: ArraySlice<UInt8>) throws {
switch ecdsaAlgorithm {
@@ -262,10 +274,12 @@ extension Certificate.PrivateKey {
case .some(.ecdsaP521):
self = try .init(P521.Signing.PrivateKey(rawRepresentation: rawEncodedPrivateKey))
default:
throw CertificateError.unsupportedPrivateKey(reason: "unknown algorithm \(String(reflecting: ecdsaAlgorithm))")
throw CertificateError.unsupportedPrivateKey(
reason: "unknown algorithm \(String(reflecting: ecdsaAlgorithm))"
)
}
}
@inlinable
public func serializeAsPEM() throws -> PEMDocument {
switch backing {
@@ -275,7 +289,9 @@ extension Certificate.PrivateKey {
case .rsa(let key): return try PEMDocument(pemString: key.pemRepresentation)
#if canImport(Darwin)
case .secureEnclaveP256:
throw CertificateError.unsupportedPrivateKey(reason: "secure enclave private keys can not be serialised as PEM")
throw CertificateError.unsupportedPrivateKey(
reason: "secure enclave private keys can not be serialised as PEM"
)
#endif
}
}
+35 -26
View File
@@ -99,7 +99,11 @@ extension Certificate.PublicKey {
/// - Returns: Whether the signature was produced by signing `certificate` with the private key corresponding to this public key.
@inlinable
public func isValidSignature(_ signature: Certificate.Signature, for certificate: Certificate) -> Bool {
return self.isValidSignature(signature, for: certificate.tbsCertificateBytes, signatureAlgorithm: certificate.signatureAlgorithm)
return self.isValidSignature(
signature,
for: certificate.tbsCertificateBytes,
signatureAlgorithm: certificate.signatureAlgorithm
)
}
/// Confirms that `signature` is a valid signature for `csr`, created by the
@@ -118,7 +122,11 @@ extension Certificate.PublicKey {
}
@inlinable
internal func isValidSignature<Bytes: DataProtocol>(_ signature: Certificate.Signature, for bytes: Bytes, signatureAlgorithm: Certificate.SignatureAlgorithm) -> Bool {
internal func isValidSignature<Bytes: DataProtocol>(
_ signature: Certificate.Signature,
for bytes: Bytes,
signatureAlgorithm: Certificate.SignatureAlgorithm
) -> Bool {
let digest: Digest
do {
let digestAlgorithm = try AlgorithmIdentifier(digestAlgorithmFor: signatureAlgorithm)
@@ -147,9 +155,9 @@ extension Certificate.PublicKey {
}
}
extension Certificate.PublicKey: Hashable { }
extension Certificate.PublicKey: Hashable {}
extension Certificate.PublicKey: Sendable { }
extension Certificate.PublicKey: Sendable {}
extension Certificate.PublicKey: CustomStringConvertible {
public var description: String {
@@ -175,7 +183,7 @@ extension Certificate.PublicKey {
case rsa(_CryptoExtras._RSA.Signing.PublicKey)
@inlinable
static func ==(lhs: BackingPublicKey, rhs: BackingPublicKey) -> Bool {
static func == (lhs: BackingPublicKey, rhs: BackingPublicKey) -> Bool {
switch (lhs, rhs) {
case (.p256(let l), .p256(let r)):
return l.rawRepresentation == r.rawRepresentation
@@ -242,7 +250,7 @@ extension Certificate.PublicKey {
/// The `subjectPublicKeyInfoBytes` property represents the public key in its canonical form that is determined by the key's algorithm and common representation.
@inlinable
public var subjectPublicKeyInfoBytes: ArraySlice<UInt8> {
SubjectPublicKeyInfo(self).key.bytes
SubjectPublicKeyInfo(self).key.bytes
}
}
@@ -254,7 +262,9 @@ extension _RSA.Signing.Padding {
self = .insecurePKCS1v1_5
default:
// Either this is RSA PSS, or we hit a bug. Either way, unsupported.
throw CertificateError.unsupportedSignatureAlgorithm(reason: "Unable to determine RSA padding mode for \(signatureAlgorithm)")
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Unable to determine RSA padding mode for \(signatureAlgorithm)"
)
}
}
}
@@ -267,11 +277,10 @@ extension P256.Signing.PublicKey {
/// - parameters:
/// - key: The key to unwrap.
public init?(_ key: Certificate.PublicKey) {
if case .p256(let inner) = key.backing {
self = inner
} else {
guard case .p256(let inner) = key.backing else {
return nil
}
self = inner
}
}
@@ -283,11 +292,10 @@ extension P384.Signing.PublicKey {
/// - parameters:
/// - key: The key to unwrap.
public init?(_ key: Certificate.PublicKey) {
if case .p384(let inner) = key.backing {
self = inner
} else {
guard case .p384(let inner) = key.backing else {
return nil
}
self = inner
}
}
@@ -299,11 +307,10 @@ extension P521.Signing.PublicKey {
/// - parameters:
/// - key: The key to unwrap.
public init?(_ key: Certificate.PublicKey) {
if case .p521(let inner) = key.backing {
self = inner
} else {
guard case .p521(let inner) = key.backing else {
return nil
}
self = inner
}
}
@@ -315,32 +322,34 @@ extension _RSA.Signing.PublicKey {
/// - parameters:
/// - key: The key to unwrap.
public init?(_ key: Certificate.PublicKey) {
if case .rsa(let inner) = key.backing {
self = inner
} else {
guard case .rsa(let inner) = key.backing else {
return nil
}
self = inner
}
}
extension Certificate.PublicKey {
@inlinable
static var pemDiscriminatorForPublicKey: String { "PUBLIC KEY" }
static var pemDiscriminator: String { "PUBLIC KEY" }
@inlinable
public init(pemEncoded: String) throws {
try self.init(pemDocument: PEMDocument(pemString: pemEncoded))
}
@inlinable
public init(pemDocument: PEMDocument) throws {
guard pemDocument.discriminator == Self.pemDiscriminatorForPublicKey else {
throw ASN1Error.invalidPEMDocument(reason: "PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.pemDiscriminatorForPublicKey) instead")
guard pemDocument.discriminator == Self.pemDiscriminator else {
throw ASN1Error.invalidPEMDocument(
reason:
"PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.pemDiscriminator) instead"
)
}
try self.init(spki: try SubjectPublicKeyInfo(derEncoded: pemDocument.derBytes))
}
func serializeAsPEM() throws -> PEMDocument {
let spki = SubjectPublicKeyInfo(self)
let derBytes = try DER.Serializer.serialized(element: spki)
+7 -7
View File
@@ -72,7 +72,7 @@ extension Certificate {
var rng = SystemRandomNumberGenerator()
self.init(generator: &rng)
}
/// Construct a random 20-byte serial number.
///
/// Serial numbers should be generated randomly, and may contain up to 20 bytes. This
@@ -86,9 +86,9 @@ extension Certificate {
}
}
extension Certificate.SerialNumber: Hashable { }
extension Certificate.SerialNumber: Hashable {}
extension Certificate.SerialNumber: Sendable { }
extension Certificate.SerialNumber: Sendable {}
extension Certificate.SerialNumber: CustomStringConvertible {
public var description: String {
@@ -104,20 +104,20 @@ extension Certificate.SerialNumber: ExpressibleByIntegerLiteral {
/// - Parameter integerLiteral: The raw big-endian bytes of the serial number.
@inlinable
public init(integerLiteral number: StaticBigInt) {
var bytes = Array<UInt8>()
var bytes = [UInt8]()
let wordCount = (number.bitWidth - 1) / (MemoryLayout<UInt>.size * 8) + 1
bytes.reserveCapacity(wordCount / MemoryLayout<UInt>.size)
for wordIndex in (0..<wordCount).reversed() {
bytes.appendBigEndianBytes(number[wordIndex])
}
self.bytes = ArraySlice(normalisingToASN1IntegerForm: bytes)
}
}
#endif
extension Array<UInt8> {
extension [UInt8] {
@inlinable
mutating func appendBigEndianBytes(_ number: UInt) {
let number = number.bigEndian
+2 -2
View File
@@ -35,9 +35,9 @@ extension Certificate {
}
}
extension Certificate.Version: Hashable { }
extension Certificate.Version: Hashable {}
extension Certificate.Version: Sendable { }
extension Certificate.Version: Sendable {}
extension Certificate.Version: Comparable {
@inlinable
@@ -47,20 +47,23 @@ struct CMSEncapsulatedContentInfo: DERImplicitlyTaggable, Hashable, Sendable {
let eContent = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
try ASN1OctetString(derEncoded: node)
}
return .init(eContentType: eContentType, eContent: eContent)
}
}
@inlinable
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier, { coder in
try coder.serialize(eContentType)
if let eContent {
try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in
try coder.serialize(eContent)
try coder.appendConstructedNode(
identifier: identifier,
{ coder in
try coder.serialize(eContentType)
if let eContent {
try coder.serialize(explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific) { coder in
try coder.serialize(eContent)
}
}
}
})
)
}
}
@@ -28,7 +28,7 @@ struct CMSIssuerAndSerialNumber: DERImplicitlyTaggable, Hashable, Sendable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
@usableFromInline var issuer: DistinguishedName
@usableFromInline var serialNumber: Certificate.SerialNumber
@@ -106,8 +106,10 @@ public enum CMS {
// We have a bunch of very specific requirements here: in particular, we need to have only one signature. We also only want
// to tolerate v1 signatures and detached signatures.
guard signedData.version == .v1, signedData.signerInfos.count == 1, signedData.encapContentInfo.eContentType == .cmsData,
signedData.encapContentInfo.eContent == nil else {
guard signedData.version == .v1, signedData.signerInfos.count == 1,
signedData.encapContentInfo.eContentType == .cmsData,
signedData.encapContentInfo.eContent == nil
else {
return .failure(.init(invalidCMSBlockReason: "Invalid signed data: \(signedData)"))
}
@@ -145,9 +147,20 @@ public enum CMS {
// Ok at this point we've done the cheap stuff and we're fairly confident we have the entity who should have
// done the signing. Our next step is to confirm that they did in fact sign the data. For that we have to compute
// the digest and validate the signature.
let signature = try Certificate.Signature(signatureAlgorithm: signatureAlgorithm, signatureBytes: signer.signature)
guard signingCert.publicKey.isValidSignature(signature, for: dataBytes, signatureAlgorithm: signatureAlgorithm) else {
return .failure(.init(invalidCMSBlockReason: "Invalid signature from signing certificate: \(signingCert)"))
let signature = try Certificate.Signature(
signatureAlgorithm: signatureAlgorithm,
signatureBytes: signer.signature
)
guard
signingCert.publicKey.isValidSignature(
signature,
for: dataBytes,
signatureAlgorithm: signatureAlgorithm
)
else {
return .failure(
.init(invalidCMSBlockReason: "Invalid signature from signing certificate: \(signingCert)")
)
}
} catch {
return .failure(.invalidCMSBlock(.init(reason: String(describing: error))))
@@ -157,7 +170,7 @@ public enum CMS {
// This force-unwrap is safe: we know there are certificates because we've located at least one certificate from this set!
var untrustedIntermediates = CertificateStore(signedData.certificates!)
untrustedIntermediates.insert(contentsOf: additionalIntermediateCertificates)
var verifier = try Verifier(rootCertificates: trustRoots, policy: policy)
let result = await verifier.validate(leafCertificate: signingCert, intermediates: untrustedIntermediates)
@@ -207,7 +220,7 @@ public enum CMS {
public var reason: String
@inlinable
public init(reason: String){
public init(reason: String) {
self.reason = reason
}
}
@@ -225,7 +238,9 @@ extension Array where Element == Certificate {
switch signerInfo.signerIdentifier {
case .issuerAndSerialNumber(let issuerAndSerialNumber):
for cert in self {
if cert.issuer == issuerAndSerialNumber.issuer && cert.serialNumber == issuerAndSerialNumber.serialNumber {
if cert.issuer == issuerAndSerialNumber.issuer
&& cert.serialNumber == issuerAndSerialNumber.serialNumber
{
return cert
}
}
@@ -241,6 +256,9 @@ extension Array where Element == Certificate {
extension Certificate.Signature {
@inlinable
init(signatureAlgorithm: Certificate.SignatureAlgorithm, signatureBytes: ASN1OctetString) throws {
self = try Certificate.Signature(signatureAlgorithm: signatureAlgorithm, signatureBytes: ASN1BitString(bytes: signatureBytes.bytes))
self = try Certificate.Signature(
signatureAlgorithm: signatureAlgorithm,
signatureBytes: ASN1BitString(bytes: signatureBytes.bytes)
)
}
}
@@ -49,7 +49,9 @@ extension CMSSignature: DERImplicitlyTaggable {
@inlinable
public init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
guard let base = try CMSContentInfo(derEncoded: rootNode, withIdentifier: identifier).signedData, base.version == .v1 else {
guard let base = try CMSContentInfo(derEncoded: rootNode, withIdentifier: identifier).signedData,
base.version == .v1
else {
throw CMS.Error.unexpectedCMSType
}
@@ -47,7 +47,7 @@ struct CMSSignedData: DERImplicitlyTaggable, Hashable, Sendable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
@usableFromInline var version: CMSVersion
@usableFromInline var digestAlgorithms: [AlgorithmIdentifier]
@usableFromInline var encapContentInfo: CMSEncapsulatedContentInfo
@@ -74,17 +74,22 @@ struct CMSSignedData: DERImplicitlyTaggable, Hashable, Sendable {
self = try DER.sequence(derEncoded, identifier: identifier) { nodes in
let version = try CMSVersion(rawValue: Int.init(derEncoded: &nodes))
let digestAlgorithms = try DER.set(of: AlgorithmIdentifier.self, identifier: .set, nodes: &nodes)
let encapContentInfo = try CMSEncapsulatedContentInfo(derEncoded: &nodes)
let certificates = try DER.optionalImplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
try DER.set(of: Certificate.self, identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific), rootNode: node)
let certificates = try DER.optionalImplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
node in
try DER.set(
of: Certificate.self,
identifier: .init(tagWithNumber: 0, tagClass: .contextSpecific),
rootNode: node
)
}
// we need to skip this node even though we don't support it
_ = DER.optionalImplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { _ in }
let signerInfos = try DER.set(of: CMSSignerInfo.self, identifier: .set, nodes: &nodes)
return .init(
version: version,
digestAlgorithms: digestAlgorithms,
@@ -25,7 +25,7 @@ enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable, Sendable {
@usableFromInline
static let skiIdentifier = ASN1Identifier(tagWithNumber: 0, tagClass: .contextSpecific)
case issuerAndSerialNumber(CMSIssuerAndSerialNumber)
case subjectKeyIdentifier(SubjectKeyIdentifier)
@@ -36,7 +36,9 @@ enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable, Sendable {
self = try .issuerAndSerialNumber(.init(derEncoded: node))
case Self.skiIdentifier:
self = try .subjectKeyIdentifier(.init(keyIdentifier: .init(derEncoded: node, withIdentifier: Self.skiIdentifier)))
self = try .subjectKeyIdentifier(
.init(keyIdentifier: .init(derEncoded: node, withIdentifier: Self.skiIdentifier))
)
default:
throw ASN1Error.unexpectedFieldType(node.identifier)
@@ -51,7 +53,7 @@ enum CMSSignerIdentifier: DERParseable, DERSerializable, Hashable, Sendable {
case .subjectKeyIdentifier(let subjectKeyIdentifier):
try subjectKeyIdentifier.keyIdentifier.serialize(into: &coder, withIdentifier: Self.skiIdentifier)
}
}
@@ -44,7 +44,7 @@ struct CMSSignerInfo: DERImplicitlyTaggable, Hashable, Sendable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
@usableFromInline var version: CMSVersion
@usableFromInline var signerIdentifier: CMSSignerIdentifier
@usableFromInline var digestAlgorithm: AlgorithmIdentifier
@@ -93,24 +93,28 @@ struct CMSSignerInfo: DERImplicitlyTaggable, Hashable, Sendable {
switch signerIdentifier {
case .issuerAndSerialNumber:
guard version == .v1 else {
throw Error.versionAndSignerIdentifierMismatch("expected \(CMSVersion.v1) but got \(version) where signerIdentifier is \(signerIdentifier)")
throw Error.versionAndSignerIdentifierMismatch(
"expected \(CMSVersion.v1) but got \(version) where signerIdentifier is \(signerIdentifier)"
)
}
case .subjectKeyIdentifier:
guard version == .v3 else {
throw Error.versionAndSignerIdentifierMismatch("expected \(CMSVersion.v3) but got \(version) where signerIdentifier is \(signerIdentifier)")
throw Error.versionAndSignerIdentifierMismatch(
"expected \(CMSVersion.v3) but got \(version) where signerIdentifier is \(signerIdentifier)"
)
}
}
let digestAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes)
// we don't support signedAttrs yet but we still need to skip them
_ = DER.optionalImplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { _ in }
let signatureAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes)
let signature = try ASN1OctetString(derEncoded: &nodes)
// we don't support unsignedAttrs yet but we still need to skip them
_ = DER.optionalImplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { _ in }
return .init(
version: version,
signerIdentifier: signerIdentifier,
@@ -28,7 +28,7 @@ struct CMSVersion: RawRepresentable, Hashable, Sendable {
init(rawValue: Int) {
self.rawValue = rawValue
}
@usableFromInline static let v0 = Self(rawValue: 0)
@usableFromInline static let v1 = Self(rawValue: 1)
@usableFromInline static let v2 = Self(rawValue: 2)
+30 -10
View File
@@ -24,7 +24,10 @@ enum Digest {
case sha512(SHA512Digest)
@inlinable
static func computeDigest<Bytes: DataProtocol>(for bytes: Bytes, using digestIdentifier: AlgorithmIdentifier) throws -> Digest {
static func computeDigest<Bytes: DataProtocol>(
for bytes: Bytes,
using digestIdentifier: AlgorithmIdentifier
) throws -> Digest {
switch digestIdentifier {
case .sha1, .sha1UsingNil:
return .insecureSHA1(Insecure.SHA1.hash(data: bytes))
@@ -46,7 +49,7 @@ extension P256.Signing.PublicKey {
@inlinable
func isValidSignature(_ signature: Certificate.Signature, for digest: Digest) -> Bool {
guard case .ecdsa(let rawInnerSignature) = signature.backing,
let innerSignature = P256.Signing.ECDSASignature(rawInnerSignature)
let innerSignature = P256.Signing.ECDSASignature(rawInnerSignature)
else {
// Signature mismatch
return false
@@ -69,7 +72,7 @@ extension P384.Signing.PublicKey {
@inlinable
func isValidSignature(_ signature: Certificate.Signature, for digest: Digest) -> Bool {
guard case .ecdsa(let rawInnerSignature) = signature.backing,
let innerSignature = P384.Signing.ECDSASignature(rawInnerSignature)
let innerSignature = P384.Signing.ECDSASignature(rawInnerSignature)
else {
// Signature mismatch
return false
@@ -92,7 +95,7 @@ extension P521.Signing.PublicKey {
@inlinable
func isValidSignature(_ signature: Certificate.Signature, for digest: Digest) -> Bool {
guard case .ecdsa(let rawInnerSignature) = signature.backing,
let innerSignature = P521.Signing.ECDSASignature(rawInnerSignature)
let innerSignature = P521.Signing.ECDSASignature(rawInnerSignature)
else {
// Signature mismatch
return false
@@ -113,7 +116,8 @@ extension P521.Signing.PublicKey {
extension _RSA.Signing.PublicKey {
@inlinable
func isValidSignature(_ signature: Certificate.Signature, for digest: Digest, padding: _RSA.Signing.Padding) -> Bool {
func isValidSignature(_ signature: Certificate.Signature, for digest: Digest, padding: _RSA.Signing.Padding) -> Bool
{
guard case .rsa(let innerSignature) = signature.backing else {
// Signature mismatch
return false
@@ -136,7 +140,10 @@ extension _RSA.Signing.PublicKey {
extension P256.Signing.PrivateKey {
@inlinable
func signature<Bytes: DataProtocol>(for bytes: Bytes, digestAlgorithm: AlgorithmIdentifier) throws -> Certificate.Signature {
func signature<Bytes: DataProtocol>(
for bytes: Bytes,
digestAlgorithm: AlgorithmIdentifier
) throws -> Certificate.Signature {
let signature: P256.Signing.ECDSASignature
switch try Digest.computeDigest(for: bytes, using: digestAlgorithm) {
@@ -157,7 +164,10 @@ extension P256.Signing.PrivateKey {
#if canImport(Darwin)
extension SecureEnclave.P256.Signing.PrivateKey {
@inlinable
func signature<Bytes: DataProtocol>(for bytes: Bytes, digestAlgorithm: AlgorithmIdentifier) throws -> Certificate.Signature {
func signature<Bytes: DataProtocol>(
for bytes: Bytes,
digestAlgorithm: AlgorithmIdentifier
) throws -> Certificate.Signature {
let signature: P256.Signing.ECDSASignature
switch try Digest.computeDigest(for: bytes, using: digestAlgorithm) {
@@ -178,7 +188,10 @@ extension SecureEnclave.P256.Signing.PrivateKey {
extension P384.Signing.PrivateKey {
@inlinable
func signature<Bytes: DataProtocol>(for bytes: Bytes, digestAlgorithm: AlgorithmIdentifier) throws -> Certificate.Signature {
func signature<Bytes: DataProtocol>(
for bytes: Bytes,
digestAlgorithm: AlgorithmIdentifier
) throws -> Certificate.Signature {
let signature: P384.Signing.ECDSASignature
switch try Digest.computeDigest(for: bytes, using: digestAlgorithm) {
@@ -198,7 +211,10 @@ extension P384.Signing.PrivateKey {
extension P521.Signing.PrivateKey {
@inlinable
func signature<Bytes: DataProtocol>(for bytes: Bytes, digestAlgorithm: AlgorithmIdentifier) throws -> Certificate.Signature {
func signature<Bytes: DataProtocol>(
for bytes: Bytes,
digestAlgorithm: AlgorithmIdentifier
) throws -> Certificate.Signature {
let signature: P521.Signing.ECDSASignature
switch try Digest.computeDigest(for: bytes, using: digestAlgorithm) {
@@ -218,7 +234,11 @@ extension P521.Signing.PrivateKey {
extension _RSA.Signing.PrivateKey {
@inlinable
func signature<Bytes: DataProtocol>(for bytes: Bytes, digestAlgorithm: AlgorithmIdentifier, padding: _RSA.Signing.Padding) throws -> Certificate.Signature {
func signature<Bytes: DataProtocol>(
for bytes: Bytes,
digestAlgorithm: AlgorithmIdentifier,
padding: _RSA.Signing.Padding
) throws -> Certificate.Signature {
let signature: _RSA.Signing.RSASignature
switch try Digest.computeDigest(for: bytes, using: digestAlgorithm) {
+6 -4
View File
@@ -99,7 +99,8 @@ public struct DistinguishedName {
///
/// - Parameter attributes: The sequence of ``RelativeDistinguishedName/Attribute``s that make up the ``DistinguishedName``.
@inlinable
public init<AttributeSequence: Sequence>(_ attributes: AttributeSequence) throws where AttributeSequence.Element == RelativeDistinguishedName.Attribute {
public init<AttributeSequence: Sequence>(_ attributes: AttributeSequence) throws
where AttributeSequence.Element == RelativeDistinguishedName.Attribute {
self.rdns = attributes.map { RelativeDistinguishedName($0) }
}
@@ -130,9 +131,9 @@ public struct DistinguishedName {
}
}
extension DistinguishedName: Hashable { }
extension DistinguishedName: Hashable {}
extension DistinguishedName: Sendable { }
extension DistinguishedName: Sendable {}
extension DistinguishedName: RandomAccessCollection, MutableCollection, RangeReplaceableCollection {
@inlinable
@@ -156,7 +157,8 @@ extension DistinguishedName: RandomAccessCollection, MutableCollection, RangeRep
}
@inlinable
public mutating func replaceSubrange<NewElements>(_ subrange: Range<Int>, with newElements: NewElements) where NewElements: Collection, RelativeDistinguishedName == NewElements.Element {
public mutating func replaceSubrange<NewElements>(_ subrange: Range<Int>, with newElements: NewElements)
where NewElements: Collection, RelativeDistinguishedName == NewElements.Element {
self.rdns.replaceSubrange(subrange, with: newElements)
}
}
@@ -32,7 +32,9 @@
@resultBuilder
public struct DistinguishedNameBuilder {
@inlinable
public static func buildExpression<Extension: RelativeDistinguishedNameConvertible>(_ expression: Extension) -> DistinguishedName {
public static func buildExpression<Extension: RelativeDistinguishedNameConvertible>(
_ expression: Extension
) -> DistinguishedName {
// TODO: Remove the try!
try! DistinguishedName([expression.makeRDN()])
}
@@ -36,4 +36,3 @@ public struct OrganizationalUnitName: RelativeDistinguishedNameConvertible {
)
}
}
+68 -23
View File
@@ -63,11 +63,16 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible {
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/unsupportedSignatureAlgorithm``.
@inline(never)
public static func unsupportedSignatureAlgorithm(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .unsupportedSignatureAlgorithm, reason: reason, file: file, line: line
code: .unsupportedSignatureAlgorithm,
reason: reason,
file: file,
line: line
)
)
}
@@ -77,11 +82,16 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible {
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/unsupportedPublicKeyAlgorithm``.
@inline(never)
public static func unsupportedPublicKeyAlgorithm(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .unsupportedPublicKeyAlgorithm, reason: reason, file: file, line: line
code: .unsupportedPublicKeyAlgorithm,
reason: reason,
file: file,
line: line
)
)
}
@@ -91,11 +101,16 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible {
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/invalidSignatureForCertificate``.
@inline(never)
public static func invalidSignatureForCertificate(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .invalidSignatureForCertificate, reason: reason, file: file, line: line
code: .invalidSignatureForCertificate,
reason: reason,
file: file,
line: line
)
)
}
@@ -105,11 +120,16 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible {
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/incorrectOIDForExtension``.
@inline(never)
public static func incorrectOIDForExtension(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .incorrectOIDForExtension, reason: reason, file: file, line: line
code: .incorrectOIDForExtension,
reason: reason,
file: file,
line: line
)
)
}
@@ -119,25 +139,35 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible {
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/unsupportedDigestAlgorithm``.
@inline(never)
public static func unsupportedDigestAlgorithm(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .unsupportedDigestAlgorithm, reason: reason, file: file, line: line
code: .unsupportedDigestAlgorithm,
reason: reason,
file: file,
line: line
)
)
}
/// A digest private key isn't supported
/// - Parameter reason: A detailed reason indicating the unsupported private key.
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/unsupportedPrivateKey``.
@inline(never)
public static func unsupportedPrivateKey(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .unsupportedPrivateKey, reason: reason, file: file, line: line
code: .unsupportedPrivateKey,
reason: reason,
file: file,
line: line
)
)
}
@@ -147,11 +177,16 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible {
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/incorrectOIDForAttribute``.
@inline(never)
public static func incorrectOIDForAttribute(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .incorrectOIDForAttribute, reason: reason, file: file, line: line
code: .incorrectOIDForAttribute,
reason: reason,
file: file,
line: line
)
)
}
@@ -161,25 +196,35 @@ public struct CertificateError: Error, Hashable, CustomStringConvertible {
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/invalidCSRAttribute``.
@inline(never)
public static func invalidCSRAttribute(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .invalidCSRAttribute, reason: reason, file: file, line: line
code: .invalidCSRAttribute,
reason: reason,
file: file,
line: line
)
)
}
/// An OID is present twice.
/// - Parameter reason: A detailed reason detailing which OID is duplicate.
/// - Returns: A ``CertificateError`` with ``code`` set to ``ErrorCode/duplicateOID``.
@inline(never)
public static func duplicateOID(
reason: String, file: String = #fileID, line: UInt = #line
reason: String,
file: String = #fileID,
line: UInt = #line
) -> CertificateError {
return CertificateError(
backing: .init(
code: .duplicateOID, reason: reason, file: file, line: line
code: .duplicateOID,
reason: reason,
file: file,
line: line
)
)
}
@@ -224,7 +269,7 @@ extension CertificateError {
/// The digest algorithm isn't supported.
public static let unsupportedDigestAlgorithm = ErrorCode(.unsupportedDigestAlgorithm)
/// The private key isn't supported.
public static let unsupportedPrivateKey = ErrorCode(.unsupportedPrivateKey)
@@ -233,7 +278,7 @@ extension CertificateError {
/// A CSR attribute is invalid.
public static let invalidCSRAttribute = ErrorCode(.invalidCSRAttribute)
/// An OID is present twice.
public static let duplicateOID = ErrorCode(.duplicateOID)
@@ -266,7 +311,7 @@ extension CertificateError {
}
// Only the error code matters for equality.
static func ==(lhs: Backing, rhs: Backing) -> Bool {
static func == (lhs: Backing, rhs: Backing) -> Bool {
return lhs.code == rhs.code
}
@@ -22,7 +22,7 @@ import SwiftASN1
public struct AuthorityInformationAccess {
@usableFromInline
var descriptions: [AccessDescription]
/// Create a new empty ``AuthorityInformationAccess/`` object
/// containing no access descriptions.
public init() {
@@ -47,7 +47,9 @@ public struct AuthorityInformationAccess {
@inlinable
public init(_ ext: Certificate.Extension) throws {
guard ext.oid == .X509ExtensionID.authorityInformationAccess else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityInformationAccess), got \(ext.oid)"
)
}
let aiaSyntax = try AuthorityInfoAccessSyntax(derEncoded: ext.value)
@@ -55,9 +57,9 @@ public struct AuthorityInformationAccess {
}
}
extension AuthorityInformationAccess: Hashable { }
extension AuthorityInformationAccess: Hashable {}
extension AuthorityInformationAccess: Sendable { }
extension AuthorityInformationAccess: Sendable {}
extension AuthorityInformationAccess: CustomStringConvertible {
public var description: String {
@@ -125,9 +127,9 @@ extension AuthorityInformationAccess {
}
}
extension AuthorityInformationAccess.AccessDescription: Hashable { }
extension AuthorityInformationAccess.AccessDescription: Hashable {}
extension AuthorityInformationAccess.AccessDescription: Sendable { }
extension AuthorityInformationAccess.AccessDescription: Sendable {}
extension AuthorityInformationAccess.AccessDescription: CustomStringConvertible {
public var description: String {
@@ -181,9 +183,9 @@ extension AuthorityInformationAccess.AccessDescription {
}
}
extension AuthorityInformationAccess.AccessDescription.AccessMethod: Hashable { }
extension AuthorityInformationAccess.AccessDescription.AccessMethod: Hashable {}
extension AuthorityInformationAccess.AccessDescription.AccessMethod: Sendable { }
extension AuthorityInformationAccess.AccessDescription.AccessMethod: Sendable {}
extension AuthorityInformationAccess.AccessDescription.AccessMethod: CustomStringConvertible {
@inlinable
@@ -212,9 +214,9 @@ extension AuthorityInformationAccess.AccessDescription.AccessMethod: CustomDebug
}
}
extension AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Hashable { }
extension AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Hashable {}
extension AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Sendable { }
extension AuthorityInformationAccess.AccessDescription.AccessMethod.Backing: Sendable {}
extension Certificate.Extension {
/// Construct an opaque ``Certificate/Extension`` from this AIA extension.
@@ -227,7 +229,11 @@ extension Certificate.Extension {
let asn1Representation = AuthorityInfoAccessSyntax(aia)
var serializer = DER.Serializer()
try serializer.serialize(asn1Representation)
self.init(oid: .X509ExtensionID.authorityInformationAccess, critical: critical, value: serializer.serializedBytes[...])
self.init(
oid: .X509ExtensionID.authorityInformationAccess,
critical: critical,
value: serializer.serializedBytes[...]
)
}
}
@@ -36,7 +36,11 @@ public struct AuthorityKeyIdentifier {
/// - authorityCertIssuer: The name of the issuer of the issuing cert.
/// - authorityCertSerialNumber: The serial number of the issuing cert.
@inlinable
public init(keyIdentifier: ArraySlice<UInt8>? = nil, authorityCertIssuer: [GeneralName]? = nil, authorityCertSerialNumber: Certificate.SerialNumber? = nil) {
public init(
keyIdentifier: ArraySlice<UInt8>? = nil,
authorityCertIssuer: [GeneralName]? = nil,
authorityCertSerialNumber: Certificate.SerialNumber? = nil
) {
self.keyIdentifier = keyIdentifier
self.authorityCertIssuer = authorityCertIssuer
self.authorityCertSerialNumber = authorityCertSerialNumber
@@ -51,19 +55,23 @@ public struct AuthorityKeyIdentifier {
@inlinable
public init(_ ext: Certificate.Extension) throws {
guard ext.oid == .X509ExtensionID.authorityKeyIdentifier else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.authorityKeyIdentifier), got \(ext.oid)"
)
}
let asn1KeyIdentifier = try AuthorityKeyIdentifierValue(derEncoded: ext.value)
self.keyIdentifier = asn1KeyIdentifier.keyIdentifier.map { $0.bytes }
self.authorityCertIssuer = asn1KeyIdentifier.authorityCertIssuer
self.authorityCertSerialNumber = asn1KeyIdentifier.authorityCertSerialNumber.map { Certificate.SerialNumber(bytes: $0) }
self.authorityCertSerialNumber = asn1KeyIdentifier.authorityCertSerialNumber.map {
Certificate.SerialNumber(bytes: $0)
}
}
}
extension AuthorityKeyIdentifier: Hashable { }
extension AuthorityKeyIdentifier: Hashable {}
extension AuthorityKeyIdentifier: Sendable { }
extension AuthorityKeyIdentifier: Sendable {}
extension AuthorityKeyIdentifier: CustomStringConvertible {
public var description: String {
@@ -102,7 +110,11 @@ extension Certificate.Extension {
let asn1Representation = AuthorityKeyIdentifierValue(aki)
var serializer = DER.Serializer()
try serializer.serialize(asn1Representation)
self.init(oid: .X509ExtensionID.authorityKeyIdentifier, critical: critical, value: serializer.serializedBytes[...])
self.init(
oid: .X509ExtensionID.authorityKeyIdentifier,
critical: critical,
value: serializer.serializedBytes[...]
)
}
}
@@ -130,7 +142,11 @@ struct AuthorityKeyIdentifierValue: DERImplicitlyTaggable {
var authorityCertSerialNumber: ArraySlice<UInt8>?
@inlinable
init(keyIdentifier: ASN1OctetString?, authorityCertIssuer: [GeneralName]?, authorityCertSerialNumber: ArraySlice<UInt8>?) {
init(
keyIdentifier: ASN1OctetString?,
authorityCertIssuer: [GeneralName]?,
authorityCertSerialNumber: ArraySlice<UInt8>?
) {
self.keyIdentifier = keyIdentifier
self.authorityCertIssuer = authorityCertIssuer
self.authorityCertSerialNumber = authorityCertSerialNumber
@@ -146,12 +162,23 @@ struct AuthorityKeyIdentifierValue: DERImplicitlyTaggable {
@inlinable
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let keyIdentifier: ASN1OctetString? = try DER.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 0, tagClass: .contextSpecific))
let authorityCertIssuer: GeneralNames? = try DER.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 1, tagClass: .contextSpecific))
let authorityCertSerialNumber: ArraySlice<UInt8>? = try DER.optionalImplicitlyTagged(&nodes, tag: .init(tagWithNumber: 2, tagClass: .contextSpecific))
let keyIdentifier: ASN1OctetString? = try DER.optionalImplicitlyTagged(
&nodes,
tag: .init(tagWithNumber: 0, tagClass: .contextSpecific)
)
let authorityCertIssuer: GeneralNames? = try DER.optionalImplicitlyTagged(
&nodes,
tag: .init(tagWithNumber: 1, tagClass: .contextSpecific)
)
let authorityCertSerialNumber: ArraySlice<UInt8>? = try DER.optionalImplicitlyTagged(
&nodes,
tag: .init(tagWithNumber: 2, tagClass: .contextSpecific)
)
return AuthorityKeyIdentifierValue(
keyIdentifier: keyIdentifier, authorityCertIssuer: authorityCertIssuer?.names, authorityCertSerialNumber: authorityCertSerialNumber
keyIdentifier: keyIdentifier,
authorityCertIssuer: authorityCertIssuer?.names,
authorityCertSerialNumber: authorityCertSerialNumber
)
}
}
@@ -159,11 +186,18 @@ struct AuthorityKeyIdentifierValue: DERImplicitlyTaggable {
@inlinable
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serializeOptionalImplicitlyTagged(self.keyIdentifier, withIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific))
try coder.serializeOptionalImplicitlyTagged(
self.authorityCertIssuer.map { GeneralNames($0) }, withIdentifier: .init(tagWithNumber: 1, tagClass: .contextSpecific)
self.keyIdentifier,
withIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific)
)
try coder.serializeOptionalImplicitlyTagged(
self.authorityCertIssuer.map { GeneralNames($0) },
withIdentifier: .init(tagWithNumber: 1, tagClass: .contextSpecific)
)
try coder.serializeOptionalImplicitlyTagged(
self.authorityCertSerialNumber,
withIdentifier: .init(tagWithNumber: 2, tagClass: .contextSpecific)
)
try coder.serializeOptionalImplicitlyTagged(self.authorityCertSerialNumber, withIdentifier: .init(tagWithNumber: 2, tagClass: .contextSpecific))
}
}
}
@@ -38,7 +38,9 @@ public enum BasicConstraints {
@inlinable
public init(_ ext: Certificate.Extension) throws {
guard ext.oid == .X509ExtensionID.basicConstraints else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.basicConstraints), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.basicConstraints), got \(ext.oid)"
)
}
let basicConstraintsValue = try BasicConstraintsValue(derEncoded: ext.value)
@@ -50,9 +52,9 @@ public enum BasicConstraints {
}
}
extension BasicConstraints: Hashable { }
extension BasicConstraints: Hashable {}
extension BasicConstraints: Sendable { }
extension BasicConstraints: Sendable {}
extension BasicConstraints: CustomStringConvertible {
public var description: String {
@@ -115,7 +117,10 @@ struct BasicConstraintsValue: DERImplicitlyTaggable {
// CA's must not assert the path len constraint field unless isCA is true.
guard pathLenConstraint == nil || isCA else {
throw ASN1Error.invalidASN1Object(reason: "Invalid combination of isCA (\(isCA)) and path length constraint (\(String(describing: pathLenConstraint))")
throw ASN1Error.invalidASN1Object(
reason:
"Invalid combination of isCA (\(isCA)) and path length constraint (\(String(describing: pathLenConstraint))"
)
}
}
@@ -28,7 +28,7 @@ public struct ExtendedKeyUsage {
@inlinable
public init<Usages: Sequence>(_ usages: Usages) throws where Usages.Element == Usage {
self.usages = Array(usages)
// This limit is somewhat arbitrary. Linear search for under 32 elements
// is faster than hashing and fast enough to not be a significant performance bottleneck.
// We have this limit because a bad actor could increase the number of elements to an arbitrary number which
@@ -36,12 +36,16 @@ public struct ExtendedKeyUsage {
// This can be used for DoS attacks so we have added this limit.
let maxUsages = 32
guard self.usages.count <= maxUsages else {
throw ASN1Error.invalidASN1Object(reason: "Too many extended key usages. Found \(self.usages.count) but only \(maxUsages) are allowed.")
throw ASN1Error.invalidASN1Object(
reason: "Too many extended key usages. Found \(self.usages.count) but only \(maxUsages) are allowed."
)
}
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)")
throw CertificateError.duplicateOID(
reason: "duplicate \(usage) usage. First at \(firstIndex) and second at \(secondIndex)"
)
}
}
@@ -54,14 +58,15 @@ public struct ExtendedKeyUsage {
@inlinable
public init(_ ext: Certificate.Extension) throws {
guard ext.oid == .X509ExtensionID.extendedKeyUsage else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.extendedKeyUsage), got \(ext.oid)"
)
}
let asn1EKU = try ASN1ExtendedKeyUsage(derEncoded: ext.value)
try self.init(asn1EKU.usages.map { Usage(oid: $0) })
}
/// Create a new empty ``ExtendedKeyUsage`` object with no usages.
@inlinable
public init() {
@@ -91,9 +96,9 @@ extension Array {
}
}
extension ExtendedKeyUsage: Hashable { }
extension ExtendedKeyUsage: Hashable {}
extension ExtendedKeyUsage: Sendable { }
extension ExtendedKeyUsage: Sendable {}
extension ExtendedKeyUsage: CustomStringConvertible {
public var description: String {
@@ -139,7 +144,7 @@ extension ExtendedKeyUsage {
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.
///
@@ -163,7 +168,7 @@ extension ExtendedKeyUsage {
}
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.
@@ -256,9 +261,9 @@ extension ExtendedKeyUsage {
}
}
extension ExtendedKeyUsage.Usage: Hashable { }
extension ExtendedKeyUsage.Usage: Hashable {}
extension ExtendedKeyUsage.Usage: Sendable { }
extension ExtendedKeyUsage.Usage: Sendable {}
extension ExtendedKeyUsage.Usage: CustomStringConvertible {
public var description: String {
@@ -310,9 +315,9 @@ extension ExtendedKeyUsage.Usage: CustomDebugStringConvertible {
}
}
extension ExtendedKeyUsage.Usage.Backing: Hashable { }
extension ExtendedKeyUsage.Usage.Backing: Hashable {}
extension ExtendedKeyUsage.Usage.Backing: Sendable { }
extension ExtendedKeyUsage.Usage.Backing: Sendable {}
extension Certificate.Extension {
/// Construct an opaque ``Certificate/Extension`` from this Extended Key Usage extension.
+5 -3
View File
@@ -89,7 +89,9 @@ public struct KeyUsage {
@inlinable
public init(_ ext: Certificate.Extension) throws {
guard ext.oid == .X509ExtensionID.keyUsage else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.keyUsage), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.keyUsage), got \(ext.oid)"
)
}
let keyUsageValue = try ASN1BitString(derEncoded: ext.value)
@@ -272,9 +274,9 @@ public struct KeyUsage {
}
}
extension KeyUsage: Hashable { }
extension KeyUsage: Hashable {}
extension KeyUsage: Sendable { }
extension KeyUsage: Sendable {}
extension KeyUsage: CustomStringConvertible {
public var description: String {
+154 -128
View File
@@ -26,79 +26,83 @@ import SwiftASN1
public struct NameConstraints {
public struct DNSNames: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
public typealias Element = String
@inlinable
public static func ==(lhs: Self, rhs: Self) -> Bool {
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 {
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)
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)
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 {
@@ -106,7 +110,7 @@ public struct NameConstraints {
}
return name
}
@inlinable
var filtered: some Sequence<GeneralName> {
self.subtrees.lazy.filter {
@@ -120,77 +124,81 @@ public struct NameConstraints {
public struct IPRanges: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
@inlinable
public static func ==(lhs: Self, rhs: Self) -> Bool {
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 {
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)
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)
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 {
@@ -198,7 +206,7 @@ public struct NameConstraints {
}
return ipAddress
}
@inlinable
var filtered: some Sequence<GeneralName> {
self.subtrees.lazy.filter {
@@ -212,77 +220,81 @@ public struct NameConstraints {
public struct EmailAddresses: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
@inlinable
public static func ==(lhs: Self, rhs: Self) -> Bool {
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 {
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)
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)
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 {
@@ -290,7 +302,7 @@ public struct NameConstraints {
}
return emailAddress
}
@inlinable
var filtered: some Sequence<GeneralName> {
self.subtrees.lazy.filter {
@@ -304,77 +316,81 @@ public struct NameConstraints {
public struct URIDomains: Hashable, Sendable, Collection, ExpressibleByArrayLiteral, CustomStringConvertible {
@inlinable
public static func ==(lhs: Self, rhs: Self) -> Bool {
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 {
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)
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)
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 {
@@ -382,7 +398,7 @@ public struct NameConstraints {
}
return uri
}
@inlinable
var filtered: some Sequence<GeneralName> {
self.subtrees.lazy.filter {
@@ -393,8 +409,7 @@ public struct NameConstraints {
}
}
}
/// 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
@@ -607,22 +622,18 @@ public struct NameConstraints {
) {
self.permittedSubtrees = []
self.permittedSubtrees.reserveCapacity(
permittedDNSDomains.underestimatedCount +
permittedIPRanges.underestimatedCount +
permittedEmailAddresses.underestimatedCount +
permittedURIDomains.underestimatedCount
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
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) })
@@ -653,7 +664,9 @@ public struct 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)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.nameConstraints), got \(ext.oid)"
)
}
let nameConstraintsValue = try NameConstraintsValue(derEncoded: ext.value)
@@ -675,19 +688,23 @@ extension Hasher {
}
}
extension NameConstraints: Hashable { }
extension NameConstraints: Hashable {}
extension NameConstraints: Sendable { }
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: ", "))]")
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: ", "))]")
elements.append(
"excludedSubtrees: [\(self.excludedSubtrees.map { String(reflecting: $0) }.joined(separator: ", "))]"
)
}
return elements.joined(separator: ", ")
@@ -754,10 +771,19 @@ struct NameConstraintsValue: DERImplicitlyTaggable {
@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))
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 })
return NameConstraintsValue(
permittedSubtrees: permittedSubtrees.map { $0.base },
excludedSubtrees: excludedSubtrees.map { $0.base }
)
}
}
@@ -47,7 +47,9 @@ public struct SubjectAlternativeNames {
@inlinable
public init(_ ext: Certificate.Extension) throws {
guard ext.oid == .X509ExtensionID.subjectAlternativeName else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectAlternativeName), got \(ext.oid)"
)
}
let asn1SAN = try GeneralNames(derEncoded: ext.value)
@@ -55,9 +57,9 @@ public struct SubjectAlternativeNames {
}
}
extension SubjectAlternativeNames: Hashable { }
extension SubjectAlternativeNames: Hashable {}
extension SubjectAlternativeNames: Sendable { }
extension SubjectAlternativeNames: Sendable {}
extension SubjectAlternativeNames: CustomStringConvertible {
public var description: String {
@@ -93,7 +95,8 @@ extension SubjectAlternativeNames: RandomAccessCollection, MutableCollection, Ra
}
@inlinable
public mutating func replaceSubrange<NewElements>(_ subrange: Range<Int>, with newElements: NewElements) where NewElements: Collection, GeneralName == NewElements.Element {
public mutating func replaceSubrange<NewElements>(_ subrange: Range<Int>, with newElements: NewElements)
where NewElements: Collection, GeneralName == NewElements.Element {
self.names.replaceSubrange(subrange, with: newElements)
}
}
@@ -109,7 +112,11 @@ extension Certificate.Extension {
let asn1Representation = GeneralNames(san.names)
var serializer = DER.Serializer()
try serializer.serialize(asn1Representation)
self.init(oid: .X509ExtensionID.subjectAlternativeName, critical: critical, value: serializer.serializedBytes[...])
self.init(
oid: .X509ExtensionID.subjectAlternativeName,
critical: critical,
value: serializer.serializedBytes[...]
)
}
}
@@ -118,4 +125,3 @@ extension SubjectAlternativeNames: CertificateExtensionConvertible {
return try .init(self, critical: false)
}
}
@@ -42,7 +42,9 @@ public struct SubjectKeyIdentifier {
@inlinable
public init(_ ext: Certificate.Extension) throws {
guard ext.oid == .X509ExtensionID.subjectKeyIdentifier else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.X509ExtensionID.subjectKeyIdentifier), got \(ext.oid)"
)
}
let asn1KeyIdentifier = try ASN1OctetString(derEncoded: ext.value)
@@ -50,9 +52,9 @@ public struct SubjectKeyIdentifier {
}
}
extension SubjectKeyIdentifier: Hashable { }
extension SubjectKeyIdentifier: Hashable {}
extension SubjectKeyIdentifier: Sendable { }
extension SubjectKeyIdentifier: Sendable {}
extension SubjectKeyIdentifier: CustomStringConvertible {
public var description: String {
@@ -77,7 +79,11 @@ extension Certificate.Extension {
let asn1Representation = ASN1OctetString(contentBytes: ski.keyIdentifier)
var serializer = DER.Serializer()
try serializer.serialize(asn1Representation)
self.init(oid: .X509ExtensionID.subjectKeyIdentifier, critical: critical, value: serializer.serializedBytes[...])
self.init(
oid: .X509ExtensionID.subjectKeyIdentifier,
critical: critical,
value: serializer.serializedBytes[...]
)
}
}
+8 -8
View File
@@ -67,9 +67,9 @@ extension Certificate {
}
}
extension Certificate.Extension: Hashable { }
extension Certificate.Extension: Hashable {}
extension Certificate.Extension: Sendable { }
extension Certificate.Extension: Sendable {}
extension Certificate.Extension: CustomStringConvertible {
public var description: String {
@@ -91,12 +91,12 @@ extension Certificate.Extension: CustomStringConvertible {
return String(reflecting: knownExtension)
} else {
return """
Extension(\
oid: \(String(reflecting: self.oid)), \
critical: \(String(reflecting: self.critical)), \
value: \(self.value.count) bytes\
)
"""
Extension(\
oid: \(String(reflecting: self.oid)), \
critical: \(String(reflecting: self.critical)), \
value: \(self.value.count) bytes\
)
"""
}
}
}
+28 -22
View File
@@ -80,7 +80,7 @@ extension Certificate {
public struct Extensions {
@usableFromInline
var _extensions: [Certificate.Extension]
/// Produce a new Extensions container from a collection of ``Certificate/Extension``.
///
/// - Parameter extensions: The base extensions.
@@ -88,7 +88,7 @@ extension Certificate {
@inlinable
public init<Elements>(_ extensions: Elements) throws where Elements: Sequence, Elements.Element == Extension {
self._extensions = Array(extensions)
// This limit is somewhat arbitrary. Linear search for under 32 elements
// is faster than hashing and fast enough to not be a significant performance bottleneck.
// We have this limit because a bad actor could increase the number of elements to an arbitrary number which
@@ -96,13 +96,19 @@ extension Certificate {
// This can be used for DoS attacks so we have added this limit.
let maxExtensions = 32
guard self._extensions.count <= maxExtensions else {
throw ASN1Error.invalidASN1Object(reason: "Too many extensions. Found \(self._extensions.count) but only \(maxExtensions) are allowed.")
throw ASN1Error.invalidASN1Object(
reason:
"Too many extensions. Found \(self._extensions.count) but only \(maxExtensions) are allowed."
)
}
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)")
throw CertificateError.duplicateOID(
reason:
"duplicate extension for OID \(firstExt.oid). First extension \(firstExt) at \(firstIndex) and second extension \(secondExt) at \(secondIndex)"
)
}
}
@@ -137,9 +143,9 @@ extension Certificate {
}
}
extension Certificate.Extensions: Hashable { }
extension Certificate.Extensions: Hashable {}
extension Certificate.Extensions: Sendable { }
extension Certificate.Extensions: Sendable {}
extension Certificate.Extensions: RandomAccessCollection {
/// Produce a new empty Extensions container.
@@ -147,17 +153,17 @@ extension Certificate.Extensions: RandomAccessCollection {
public init() {
self._extensions = []
}
@inlinable
public var startIndex: Int {
self._extensions.startIndex
}
@inlinable
public var endIndex: Int {
self._extensions.endIndex
}
@inlinable
public subscript(position: Int) -> Certificate.Extension {
get {
@@ -166,7 +172,6 @@ extension Certificate.Extensions: RandomAccessCollection {
}
}
// MARK: Modifying methods
extension Certificate.Extensions {
@@ -177,12 +182,15 @@ extension Certificate.Extensions {
@inlinable
public mutating func append(_ extension: Certificate.Extension) throws {
if let oldExtension = self._extensions.first(where: { $0.oid == `extension`.oid }) {
throw CertificateError.duplicateOID(reason: "tried to append an extension for OID \(`extension`.oid) which is already present. Old extension: \(oldExtension) New extension: \(`extension`)")
throw CertificateError.duplicateOID(
reason:
"tried to append an extension for OID \(`extension`.oid) which is already present. Old extension: \(oldExtension) New extension: \(`extension`)"
)
} else {
self._extensions.append(`extension`)
}
}
/// Updates the ``Certificate/Extension`` stored in the dictionary for the ``Certificate/Extension/oid`` of the `extension`,
/// or appends `extension` if an ``Certificate/Extension`` with same ``Certificate/Extension/oid`` does not exist.
///
@@ -191,16 +199,15 @@ extension Certificate.Extensions {
@inlinable
@discardableResult
public mutating func update(_ extension: Certificate.Extension) -> Certificate.Extension? {
if let index = self._extensions.firstIndex(where: { $0.oid == `extension`.oid }) {
let oldExtension = self._extensions[index]
self._extensions[index] = `extension`
return oldExtension
} else {
guard let index = self._extensions.firstIndex(where: { $0.oid == `extension`.oid }) else {
self._extensions.append(`extension`)
return nil
}
let oldExtension = self._extensions[index]
self._extensions[index] = `extension`
return oldExtension
}
/// Removes the ``Certificate/Extension`` with the given `oid`.
/// - Parameter oid: The ``Certificate/Extension/oid`` of the``Certificate/Extension`` to remove.
/// - Returns: The ``Certificate/Extension`` that was removed,
@@ -218,11 +225,10 @@ extension Certificate.Extensions {
extension Certificate.Extensions: CustomStringConvertible {
@inlinable
public var description: String {
if self.isEmpty {
return "(none)"
} else {
guard self.isEmpty else {
return self._extensions.lazy.map { String(reflecting: $0) }.joined(separator: ", ")
}
return "(none)"
}
}
+27 -11
View File
@@ -41,58 +41,74 @@
@resultBuilder
public struct ExtensionsBuilder {
@inlinable
public static func buildExpression<Extension: CertificateExtensionConvertible>(_ expression: Extension) -> Result<Certificate.Extensions, any Error> {
public static func buildExpression<Extension: CertificateExtensionConvertible>(
_ expression: Extension
) -> Result<Certificate.Extensions, any Error> {
Result {
try Certificate.Extensions([expression.makeCertificateExtension()])
}
}
@inlinable
public static func buildExpression(_ expression: Certificate.Extensions) -> Result<Certificate.Extensions, any Error> {
public static func buildExpression(
_ expression: Certificate.Extensions
) -> Result<Certificate.Extensions, any Error> {
.success(expression)
}
@inlinable
public static func buildExpression() -> Result<Certificate.Extensions, any Error> {
.success(Certificate.Extensions())
}
@inlinable
public static func buildBlock() -> Result<Certificate.Extensions, any Error> {
.success(Certificate.Extensions())
}
@inlinable
public static func buildBlock(_ components: Result<Certificate.Extensions, any Error>...) -> Result<Certificate.Extensions, any Error> {
public static func buildBlock(
_ components: Result<Certificate.Extensions, any Error>...
) -> Result<Certificate.Extensions, any Error> {
Result {
try Certificate.Extensions(try components.lazy.flatMap { try $0.get() })
}
}
@inlinable
public static func buildOptional(_ component: Result<Certificate.Extensions, any Error>?) -> Result<Certificate.Extensions, any Error> {
public static func buildOptional(
_ component: Result<Certificate.Extensions, any Error>?
) -> Result<Certificate.Extensions, any Error> {
component ?? .success(Certificate.Extensions())
}
@inlinable
public static func buildEither(first component: Result<Certificate.Extensions, any Error>) -> Result<Certificate.Extensions, any Error> {
public static func buildEither(
first component: Result<Certificate.Extensions, any Error>
) -> Result<Certificate.Extensions, any Error> {
component
}
@inlinable
public static func buildEither(second component: Result<Certificate.Extensions, any Error>) -> Result<Certificate.Extensions, any Error> {
public static func buildEither(
second component: Result<Certificate.Extensions, any Error>
) -> Result<Certificate.Extensions, any Error> {
component
}
@inlinable
public static func buildArray(_ components: [Result<Certificate.Extensions, any Error>]) -> Result<Certificate.Extensions, any Error> {
public static func buildArray(
_ components: [Result<Certificate.Extensions, any Error>]
) -> Result<Certificate.Extensions, any Error> {
Result {
try Certificate.Extensions(try components.lazy.flatMap { try $0.get() })
}
}
@inlinable
public static func buildLimitedAvailability(_ component: Result<Certificate.Extensions, any Error>) -> Result<Certificate.Extensions, any Error> {
public static func buildLimitedAvailability(
_ component: Result<Certificate.Extensions, any Error>
) -> Result<Certificate.Extensions, any Error> {
component
}
}
+4 -1
View File
@@ -180,7 +180,10 @@ extension GeneralName {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.typeID)
if let value = self.value {
try coder.serialize(value, explicitlyTaggedWithIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific))
try coder.serialize(
value,
explicitlyTaggedWithIdentifier: .init(tagWithNumber: 0, tagClass: .contextSpecific)
)
}
}
}
+16 -5
View File
@@ -83,7 +83,7 @@ struct BasicOCSPResponse: DERImplicitlyTaggable, Hashable {
}
var responseData: OCSPResponseData
var responseDataBytes: ArraySlice<UInt8>
var signatureAlgorithm: AlgorithmIdentifier
@@ -92,7 +92,13 @@ struct BasicOCSPResponse: DERImplicitlyTaggable, Hashable {
var certs: [Certificate]?
init(responseData: OCSPResponseData, responseDataBytes: ArraySlice<UInt8>, signatureAlgorithm: AlgorithmIdentifier, signature: ASN1BitString, certs: [Certificate]?) {
init(
responseData: OCSPResponseData,
responseDataBytes: ArraySlice<UInt8>,
signatureAlgorithm: AlgorithmIdentifier,
signature: ASN1BitString,
certs: [Certificate]?
) {
self.responseData = responseData
self.responseDataBytes = responseDataBytes
self.signatureAlgorithm = signatureAlgorithm
@@ -108,15 +114,20 @@ struct BasicOCSPResponse: DERImplicitlyTaggable, Hashable {
let signatureAlgorithm = try AlgorithmIdentifier(derEncoded: &nodes)
let signature = try ASN1BitString(derEncoded: &nodes)
let certs = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
try DER.sequence(of: Certificate.self, identifier: .sequence, rootNode: node)
}
return .init(responseData: responseData, responseDataBytes: responseDataNode.encodedBytes, signatureAlgorithm: signatureAlgorithm, signature: signature, certs: certs)
return .init(
responseData: responseData,
responseDataBytes: responseDataNode.encodedBytes,
signatureAlgorithm: signatureAlgorithm,
signature: signature,
certs: certs
)
}
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
coder.serializeRawBytes(self.responseDataBytes)
+12 -8
View File
@@ -41,10 +41,12 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable {
.sequence
}
init(hashAlgorithm: AlgorithmIdentifier,
issuerNameHash: ASN1OctetString,
issuerKeyHash: ASN1OctetString,
serialNumber: Certificate.SerialNumber) {
init(
hashAlgorithm: AlgorithmIdentifier,
issuerNameHash: ASN1OctetString,
issuerKeyHash: ASN1OctetString,
serialNumber: Certificate.SerialNumber
) {
self.hashAlgorithm = hashAlgorithm
self.issuerNameHash = issuerNameHash
self.issuerKeyHash = issuerKeyHash
@@ -72,10 +74,12 @@ struct OCSPCertID: DERImplicitlyTaggable, Hashable {
let issuerKeyHash = try ASN1OctetString(derEncoded: &nodes)
let serialNumber = try ArraySlice<UInt8>(derEncoded: &nodes)
return .init(hashAlgorithm: hashAlgorithm,
issuerNameHash: issuerNameHash,
issuerKeyHash: issuerKeyHash,
serialNumber: .init(bytes: serialNumber))
return .init(
hashAlgorithm: hashAlgorithm,
issuerNameHash: issuerNameHash,
issuerKeyHash: issuerKeyHash,
serialNumber: .init(bytes: serialNumber)
)
}
}
+2 -1
View File
@@ -100,7 +100,8 @@ struct OCSPRevokedInfo: DERImplicitlyTaggable, Hashable {
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let revocationTime = try GeneralizedTime(derEncoded: &nodes)
let revocationReason = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
let revocationReason = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
node in
try CRLReason(derEncoded: node)
}
+11 -9
View File
@@ -14,7 +14,6 @@
import SwiftASN1
/// ``OCSPNonce`` is defined in ASN.1 as:
/// ```
/// Nonce ::= OCTET STRING(SIZE(1..32))
@@ -25,31 +24,35 @@ struct OCSPNonce: DERImplicitlyTaggable, Hashable, Sendable {
ASN1OctetString.defaultIdentifier
}
var rawValue: ASN1OctetString
init() {
var generator = SystemRandomNumberGenerator()
self.init(generator: &generator)
}
init(generator: inout some RandomNumberGenerator) {
self.rawValue = .init(contentBytes: generator.bytes(count: 32))
}
init(_ ext: Certificate.Extension) throws {
guard ext.oid == .OCSPExtensionID.nonceIdentifier else {
throw CertificateError.incorrectOIDForExtension(reason: "Expected \(ASN1ObjectIdentifier.OCSPExtensionID.nonceIdentifier), got \(ext.oid)")
throw CertificateError.incorrectOIDForExtension(
reason: "Expected \(ASN1ObjectIdentifier.OCSPExtensionID.nonceIdentifier), got \(ext.oid)"
)
}
try self.init(derEncoded: ext.value)
}
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self.rawValue = try ASN1OctetString(derEncoded: rootNode, withIdentifier: identifier)
guard (1...32).contains(self.rawValue.bytes.count) else {
throw ASN1Error.unsupportedFieldLength(reason: "OCSP Nonce has invalid number of bytes: \(self.rawValue.bytes.count)")
throw ASN1Error.unsupportedFieldLength(
reason: "OCSP Nonce has invalid number of bytes: \(self.rawValue.bytes.count)"
)
}
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try rawValue.serialize(into: &coder, withIdentifier: identifier)
}
@@ -78,7 +81,6 @@ extension OCSPNonce: CertificateExtensionConvertible {
}
}
extension Certificate.Extensions {
var ocspNonce: OCSPNonce? {
get throws {
+159 -95
View File
@@ -44,7 +44,7 @@ public struct OCSPRequesterQueryResult: Sendable {
}
@usableFromInline
var storage: Storage
@inlinable
init(_ storage: Storage) {
self.storage = storage
@@ -58,7 +58,7 @@ extension OCSPRequesterQueryResult {
public static func response(_ bytes: [UInt8]) -> Self {
.init(.success(bytes))
}
/// The OCSP query is considered unsuccessful but will **not** fail verification, neither in ``OCSPFailureMode/soft`` nor in ``OCSPFailureMode/hard`` failure mode.
/// The certificate is then considered to meet the ``OCSPVerifierPolicy``.
/// - Parameter reason: the reason why the OCSP query failed which may be used for diagnostics
@@ -67,7 +67,7 @@ extension OCSPRequesterQueryResult {
public static func nonTerminalError(_ reason: Error) -> Self {
.init(.nonTerminal(reason))
}
/// The OCSP query is considered unsuccessful and will fail verification in both ``OCSPFailureMode/soft`` and ``OCSPFailureMode/hard`` failure mode.
/// The certificate is then considered to not meet the ``OCSPVerifierPolicy`` and ``OCSPVerifierPolicy/chainMeetsPolicyRequirements(chain:)`` will return ``PolicyEvaluationResult/failsToMeetPolicy(reason:)`` with the given ``reason``.
/// - Parameter reason: the reason why the OCSP query failed
@@ -77,7 +77,6 @@ extension OCSPRequesterQueryResult {
}
}
extension ASN1ObjectIdentifier {
static let sha256NoSign: Self = [2, 16, 840, 1, 101, 3, 4, 2, 1]
static let sha1NoSign: Self = [1, 3, 14, 3, 2, 26]
@@ -85,21 +84,24 @@ extension ASN1ObjectIdentifier {
struct OCSPResponderSigningPolicy: VerifierPolicy {
let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []
/// direct issuer of the certificate for which we check the OCSP status for
var issuer: Certificate
mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
// The root of the chain is always guaranteed to be the issuer as the root certificate store only contains the issuer
guard chain.last == issuer else {
return .failsToMeetPolicy(reason: "OCSP response must be signed by the certificate issuer or a certificate that chains up to the issuer")
return .failsToMeetPolicy(
reason:
"OCSP response must be signed by the certificate issuer or a certificate that chains up to the issuer"
)
}
if chain.count == 1 {
// the leaf is the issuer which does not need to have the OCSP signing extended key usage
return .meetsPolicy
}
let leaf = chain.leaf
// RFC 6960 Section 4.2.2.2. Authorized Responders
// OCSP signing delegation SHALL be designated by the inclusion of
// id-kp-OCSPSigning in an extended key usage certificate extension
@@ -109,10 +111,11 @@ struct OCSPResponderSigningPolicy: VerifierPolicy {
}
guard extendedKeyUsage.usages.contains(.ocspSigning) else {
return .failsToMeetPolicy(reason: "OCSP response certificate does not have OCSP signing extended key usage set")
return .failsToMeetPolicy(
reason: "OCSP response certificate does not have OCSP signing extended key usage set"
)
}
return .meetsPolicy
}
}
@@ -121,7 +124,7 @@ enum OCSPRequestHashAlgorithm {
case insecureSha1
// we can't yet enable sha256 by default but we want in the future
case sha256
var oid: ASN1ObjectIdentifier {
switch self {
case .insecureSha1: return .sha1NoSign
@@ -140,7 +143,7 @@ enum OCSPRequestHashAlgorithm {
return Array(hashAlgorithm.finalize())[...]
}
}
fileprivate func issuerNameHashed(_ certificate: Certificate) throws -> ArraySlice<UInt8> {
/// issuerNameHash is the hash of the issuer's distinguished name
/// (DN). The hash shall be calculated over the DER encoding of the
@@ -149,7 +152,7 @@ enum OCSPRequestHashAlgorithm {
try serializer.serialize(certificate.subject)
return self.hashed(serializer.serializedBytes[...])
}
fileprivate func issuerPublicKeyHashed(_ certificate: Certificate) -> ArraySlice<UInt8> {
/// issuerKeyHash is the hash of the issuer's public key. The hash
/// shall be calculated over the value (excluding tag and length) of
@@ -158,7 +161,6 @@ enum OCSPRequestHashAlgorithm {
}
}
/// Defines the behaviour of ``OCSPVerifierPolicy`` in the event of a failure.
/// ``soft`` should be used most of the time and will only fail verification if a verified OCSP response reports a status of revoked.
public struct OCSPFailureMode: Hashable, Sendable {
@@ -169,37 +171,43 @@ public struct OCSPFailureMode: Hashable, Sendable {
/// Verification will succeed if the OCSP response status is good.
/// In addition, if the request fails or times out the certificate will still meet the policy though to allow the network to be down.
public static var hard: Self { .init(storage: .hard) }
enum Storage: Hashable, Sendable {
case soft
case hard
}
var storage: Storage
}
public struct OCSPVerifierPolicy<Requester: OCSPRequester>: VerifierPolicy {
public let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []
struct Storage: Sendable {
private var failureMode: OCSPFailureMode
private var requester: Requester
private var requestHashAlgorithm: OCSPRequestHashAlgorithm
/// max duration the policy verification is allowed in total
///
/// This is not the duration for a single OCSP request but the total duration of all OCSP requests.
private var maxDuration: TimeInterval
/// the time used to decide if the request is relatively recent
private var validationTime: Date
/// If true, a nonce is generated per OCSP request and attached to the request.
/// If the response contains a nonce, it must match with the initially send nonce.
/// currently only set to false for testing
fileprivate var nonceExtensionEnabled: Bool = true
fileprivate init(failureMode: OCSPFailureMode, requester: Requester, requestHashAlgorithm: OCSPRequestHashAlgorithm, maxDuration: TimeInterval, validationTime: Date) {
fileprivate init(
failureMode: OCSPFailureMode,
requester: Requester,
requestHashAlgorithm: OCSPRequestHashAlgorithm,
maxDuration: TimeInterval,
validationTime: Date
) {
self.requester = requester
self.requestHashAlgorithm = requestHashAlgorithm
self.maxDuration = maxDuration
@@ -207,7 +215,7 @@ public struct OCSPVerifierPolicy<Requester: OCSPRequester>: VerifierPolicy {
self.failureMode = failureMode
}
}
var nonceExtensionEnabled: Bool {
get {
self.storage.nonceExtensionEnabled
@@ -216,9 +224,9 @@ public struct OCSPVerifierPolicy<Requester: OCSPRequester>: VerifierPolicy {
self.storage.nonceExtensionEnabled = newValue
}
}
private var storage: Storage
public init(failureMode: OCSPFailureMode, requester: Requester, validationTime: Date) {
self.storage = .init(
failureMode: failureMode,
@@ -228,16 +236,17 @@ public struct OCSPVerifierPolicy<Requester: OCSPRequester>: VerifierPolicy {
validationTime: validationTime
)
}
// this method currently doesn't need to be mutating. However, we want to reserve the right to change our mind
// in the future and therefore still declare this method as mutating in the public API.
public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult
{
await self.storage.chainMeetsPolicyWithDeadline(chain: chain)
}
}
extension OCSPVerifierPolicy.Storage {
/// Returns `.meetsPolicy` if the `failureMode` is set to `.soft`.
/// If it is set to `.hard` it will return `.failsToMeetPolicy` with the given `reason`.
private func softFailure(reason: String) -> PolicyEvaluationResult {
@@ -248,14 +257,16 @@ extension OCSPVerifierPolicy.Storage {
return .failsToMeetPolicy(reason: reason)
}
}
fileprivate func chainMeetsPolicyWithDeadline(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
await withTimeout(maxDuration) {
await self.chainMeetsPolicyRequirementsWithoutDeadline(chain: chain)
}
}
private func chainMeetsPolicyRequirementsWithoutDeadline(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
private func chainMeetsPolicyRequirementsWithoutDeadline(
chain: UnverifiedCertificateChain
) async -> PolicyEvaluationResult {
for index in chain.dropLast().indices {
let certificate = chain[index]
let issuer = chain[chain.index(after: index)]
@@ -266,9 +277,10 @@ extension OCSPVerifierPolicy.Storage {
return .failsToMeetPolicy(reason: reason)
}
}
do {
let hasRootCertificateOCSPURI = try chain.last?.extensions.authorityInformationAccess?.contains { $0.method == .ocspServer } ?? false
let hasRootCertificateOCSPURI =
try chain.last?.extensions.authorityInformationAccess?.contains { $0.method == .ocspServer } ?? false
if hasRootCertificateOCSPURI {
return .failsToMeetPolicy(reason: "root certificate is not allowed to have an OCSP URI")
}
@@ -277,9 +289,12 @@ extension OCSPVerifierPolicy.Storage {
}
return .meetsPolicy
}
private func certificateMeetsPolicyRequirements(_ certificate: Certificate, issuer: Certificate) async -> PolicyEvaluationResult {
private func certificateMeetsPolicyRequirements(
_ certificate: Certificate,
issuer: Certificate
) async -> PolicyEvaluationResult {
let authorityInformationAccess: AuthorityInformationAccess?
do {
authorityInformationAccess = try certificate.extensions.authorityInformationAccess
@@ -290,13 +305,13 @@ extension OCSPVerifierPolicy.Storage {
// OCSP not necessary for certificate
return .meetsPolicy
}
let ocspAccessDescriptions = authorityInformationAccess.lazy.filter { $0.method == .ocspServer }
if ocspAccessDescriptions.isEmpty {
// OCSP not necessary for certificate
return .meetsPolicy
}
// We could find more than one ocsp server, where only one has a uri. We want to find the first one with a uri.
let responderURI = ocspAccessDescriptions.lazy.compactMap { description -> String? in
guard case .uniformResourceIdentifier(let responderURI) = description.location else {
@@ -307,18 +322,22 @@ extension OCSPVerifierPolicy.Storage {
guard let responderURI else {
return self.softFailure(reason: "expected OCSP location to be a URI but got \(ocspAccessDescriptions)")
}
let certID: OCSPCertID
do {
certID = try OCSPCertID(hashAlgorithm: requestHashAlgorithm, certificate: certificate, issuer: issuer)
} catch {
return self.softFailure(reason: "failed to create OCSPCertID \(error)")
}
return await self.queryAndVerifyCertificateStatus(for: certID, responderURI: responderURI, issuer: issuer)
}
private func queryAndVerifyCertificateStatus(for certID: OCSPCertID, responderURI: String, issuer: Certificate) async -> PolicyEvaluationResult {
private func queryAndVerifyCertificateStatus(
for certID: OCSPCertID,
responderURI: String,
issuer: Certificate
) async -> PolicyEvaluationResult {
let requestNonce = nonceExtensionEnabled ? OCSPNonce() : nil
let requestBytes: [UInt8]
do {
@@ -329,7 +348,7 @@ extension OCSPVerifierPolicy.Storage {
} catch {
return self.softFailure(reason: "failed to create OCSPRequest \(error)")
}
let responseDerEncoded: [UInt8]
switch await self.requester.query(request: requestBytes, uri: responderURI).storage {
case .success(let responseBytes):
@@ -340,55 +359,74 @@ extension OCSPVerifierPolicy.Storage {
case .terminal(let error):
return .failsToMeetPolicy(reason: String(describing: error))
}
let response: OCSPResponse
do {
response = try OCSPResponse(derEncoded: responseDerEncoded[...])
} catch {
return self.softFailure(reason: "OCSP deserialisation failed \(error)")
}
return await self.verifyResponse(response, requestedCertID: certID, requestNonce: requestNonce, issuer: issuer)
}
private func verifyResponse(_ response: OCSPResponse, requestedCertID: OCSPCertID, requestNonce: OCSPNonce?, issuer: Certificate) async -> PolicyEvaluationResult {
private func verifyResponse(
_ response: OCSPResponse,
requestedCertID: OCSPCertID,
requestNonce: OCSPNonce?,
issuer: Certificate
) async -> PolicyEvaluationResult {
switch response {
case .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError:
return self.softFailure(reason: "OCSP request failed \(OCSPResponseStatus(response))")
case .successful(let basicResponse):
return await self.verifySuccessfulResponse(basicResponse, requestedCertID: requestedCertID, requestNonce: requestNonce, issuer: issuer)
return await self.verifySuccessfulResponse(
basicResponse,
requestedCertID: requestedCertID,
requestNonce: requestNonce,
issuer: issuer
)
}
}
private func verifySuccessfulResponse(_ basicResponse: BasicOCSPResponse, requestedCertID: OCSPCertID, requestNonce: OCSPNonce?, issuer: Certificate) async -> PolicyEvaluationResult {
private func verifySuccessfulResponse(
_ basicResponse: BasicOCSPResponse,
requestedCertID: OCSPCertID,
requestNonce: OCSPNonce?,
issuer: Certificate
) async -> PolicyEvaluationResult {
guard let response = basicResponse.responseData.responses.first(where: { $0.certID == requestedCertID }) else {
return self.softFailure(reason: "OCSP response does not include a response for the queried certificate \(requestedCertID) - responses: \(basicResponse.responseData.responses)")
return self.softFailure(
reason:
"OCSP response does not include a response for the queried certificate \(requestedCertID) - responses: \(basicResponse.responseData.responses)"
)
}
switch await self.validateResponseSignature(basicResponse, issuer: issuer) {
case .meetsPolicy:
break
case .failsToMeetPolicy(let reason):
return self.softFailure(reason: reason)
}
guard basicResponse.responseData.version == .v1 else {
return self.softFailure(reason: "OCSP response version unsupported \(basicResponse.responseData.version)")
}
switch basicResponse.responseData.verifyTime(validationTime: self.validationTime) {
case .failsToMeetPolicy(reason: let reason):
return self.softFailure(reason: reason)
case .meetsPolicy:
break
}
do {
// if requestNonce is nil, `nonceExtensionEnabled` is set to false and we therefore skip nonce verification
if let requestNonce {
// OCSP responders are allowed to not include the nonce, but if they do it needs to match
if let responseNonce = try basicResponse.responseData.responseExtensions?.ocspNonce,
requestNonce != responseNonce {
requestNonce != responseNonce
{
return self.softFailure(reason: "OCSP response nonce does not match request nonce")
}
} else {
@@ -397,55 +435,57 @@ extension OCSPVerifierPolicy.Storage {
} catch {
return self.softFailure(reason: "failed to decode nonce response \(error)")
}
switch response.verifyTime(validationTime: self.validationTime) {
case .meetsPolicy:
break
case .failsToMeetPolicy(let reason):
return self.softFailure(reason: reason)
}
switch response.certStatus {
case .revoked(let info):
return .failsToMeetPolicy(reason: "revoked through OCSP, reason: \(info.revocationReason?.description ?? "nil")")
return .failsToMeetPolicy(
reason: "revoked through OCSP, reason: \(info.revocationReason?.description ?? "nil")"
)
case .unknown:
return self.softFailure(reason: "OCSP response returned as status unknown")
case .good:
return .meetsPolicy
}
}
private func validateResponseSignature(
_ basicResponse: BasicOCSPResponse,
issuer: Certificate
) async -> PolicyEvaluationResult {
let responderID = basicResponse.responseData.responderID
let leafCertificate: Certificate?
if issuer.matches(responderID) {
leafCertificate = issuer
} else {
leafCertificate = basicResponse.certs?.first(where: { $0.matches(responderID) })
}
guard let leafCertificate else {
return .failsToMeetPolicy(reason: "could not find OCSP responder certificate for id \(responderID)")
}
let signatureValidationResult = self.validateSignature(
certificate: leafCertificate,
tbsResponse: basicResponse.responseDataBytes,
signatureBytes: basicResponse.signature.bytes,
signatureAlgorithmIdentifier: basicResponse.signatureAlgorithm
)
switch signatureValidationResult {
case .meetsPolicy:
break
case .failsToMeetPolicy(let reason):
return .failsToMeetPolicy(reason: reason)
}
var verifier = Verifier(
rootCertificates: CertificateStore([issuer])
) {
@@ -453,8 +493,11 @@ extension OCSPVerifierPolicy.Storage {
RFC5280Policy(validationTime: validationTime)
}
let validationResult = await verifier.validate(leafCertificate: leafCertificate, intermediates: CertificateStore())
let validationResult = await verifier.validate(
leafCertificate: leafCertificate,
intermediates: CertificateStore()
)
switch validationResult {
case .couldNotValidate(let failures):
return .failsToMeetPolicy(reason: "could not validate OCSP responder certificates \(failures)")
@@ -462,7 +505,7 @@ extension OCSPVerifierPolicy.Storage {
return .meetsPolicy
}
}
private func validateSignature(
certificate: Certificate,
tbsResponse: ArraySlice<UInt8>,
@@ -472,16 +515,20 @@ extension OCSPVerifierPolicy.Storage {
let signatureAlgorithm = Certificate.SignatureAlgorithm(algorithmIdentifier: signatureAlgorithmIdentifier)
let signature: Certificate.Signature
do {
signature = try Certificate.Signature(signatureAlgorithm: signatureAlgorithm, signatureBytes: .init(bytes: signatureBytes))
signature = try Certificate.Signature(
signatureAlgorithm: signatureAlgorithm,
signatureBytes: .init(bytes: signatureBytes)
)
} catch {
return .failsToMeetPolicy(reason: "could not create signature for OCSP response \(error)")
}
if certificate.publicKey.isValidSignature(signature, for: tbsResponse, signatureAlgorithm: signatureAlgorithm) {
return .meetsPolicy
} else {
guard
certificate.publicKey.isValidSignature(signature, for: tbsResponse, signatureAlgorithm: signatureAlgorithm)
else {
return .failsToMeetPolicy(reason: "OCSP response signature is not valid")
}
return .meetsPolicy
}
}
@@ -498,38 +545,49 @@ extension OCSPCertID {
extension OCSPRequest {
init(certID: OCSPCertID, nonce: OCSPNonce?) throws {
self.init(tbsRequest: OCSPTBSRequest(
version: .v1,
requestList: [
OCSPSingleRequest(certID: certID)
],
requestExtensions: try .init(builder: {
if let nonce {
nonce
}
})
))
self.init(
tbsRequest: OCSPTBSRequest(
version: .v1,
requestList: [
OCSPSingleRequest(certID: certID)
],
requestExtensions: try .init(builder: {
if let nonce {
nonce
}
})
)
)
}
}
extension OCSPResponseData {
/// 1 hour to address time zone bugs and 15 min for clock skew of the responder/requester
static let defaultTrustTimeLeeway: TimeInterval = 4500.0
func verifyTime(validationTime: Date, trustTimeLeeway: TimeInterval = Self.defaultTrustTimeLeeway) -> PolicyEvaluationResult {
func verifyTime(
validationTime: Date,
trustTimeLeeway: TimeInterval = Self.defaultTrustTimeLeeway
) -> PolicyEvaluationResult {
let producedAt = Date(self.producedAt)
guard producedAt <= validationTime.advanced(by: trustTimeLeeway) else {
return .failsToMeetPolicy(reason: "OCSP response `producedAt` (\(self.producedAt) is in the future (+\(trustTimeLeeway) seconds leeway) but should be in the past")
return .failsToMeetPolicy(
reason:
"OCSP response `producedAt` (\(self.producedAt) is in the future (+\(trustTimeLeeway) seconds leeway) but should be in the past"
)
}
return .meetsPolicy
}
}
extension OCSPSingleResponse {
func verifyTime(validationTime: Date, trustTimeLeeway: TimeInterval = OCSPResponseData.defaultTrustTimeLeeway) -> PolicyEvaluationResult {
func verifyTime(
validationTime: Date,
trustTimeLeeway: TimeInterval = OCSPResponseData.defaultTrustTimeLeeway
) -> PolicyEvaluationResult {
/// Clients MUST check for the existence of the nextUpdate field and MUST
/// ensure the current time, expressed in GMT time as described in
/// Section 2.2.4, falls between the thisUpdate and nextUpdate times. Ifhttps://www.rfc-editor.org/rfc/rfc5019#section-4
@@ -543,13 +601,19 @@ extension OCSPSingleResponse {
let nextUpdate = Date(nextUpdateGeneralizedTime)
guard thisUpdate <= validationTime.advanced(by: trustTimeLeeway) else {
return .failsToMeetPolicy(reason: "OCSP response `thisUpdate` (\(self.thisUpdate) is in the future (+\(trustTimeLeeway) seconds leeway) but should be in the past")
return .failsToMeetPolicy(
reason:
"OCSP response `thisUpdate` (\(self.thisUpdate) is in the future (+\(trustTimeLeeway) seconds leeway) but should be in the past"
)
}
guard nextUpdate >= validationTime.advanced(by: -trustTimeLeeway) else {
return .failsToMeetPolicy(reason: "OCSP response `nextUpdate` (\(nextUpdateGeneralizedTime) is in the past (-\(trustTimeLeeway) seconds leeway) but should be in the future")
return .failsToMeetPolicy(
reason:
"OCSP response `nextUpdate` (\(nextUpdateGeneralizedTime) is in the past (-\(trustTimeLeeway) seconds leeway) but should be in the future"
)
}
return .meetsPolicy
}
}
+5 -8
View File
@@ -24,16 +24,16 @@ struct OCSPRequest: DERImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
var tbsRequest: OCSPTBSRequest
var signature: OCSPSignature?
init(tbsRequest: OCSPTBSRequest, signature: OCSPSignature? = nil) {
self.tbsRequest = tbsRequest
self.signature = signature
}
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let tbsRequest = try OCSPTBSRequest(derEncoded: &nodes)
@@ -43,7 +43,7 @@ struct OCSPRequest: DERImplicitlyTaggable, Hashable {
return .init(tbsRequest: tbsRequest, signature: signature)
}
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try coder.serialize(self.tbsRequest)
@@ -53,6 +53,3 @@ struct OCSPRequest: DERImplicitlyTaggable, Hashable {
}
}
}
+13 -9
View File
@@ -38,15 +38,19 @@ enum OCSPResponse: DERImplicitlyTaggable, Hashable {
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let responseStatus = try OCSPResponseStatus(derEncoded: &nodes)
let responseBytes = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
let responseBytes = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
node in
try OCSPResponseBytes(derEncoded: node)
}
switch responseStatus {
case .successful:
guard let responseBytes,
responseBytes.responseType == .OCSP.basicResponse
responseBytes.responseType == .OCSP.basicResponse
else {
throw ASN1Error.invalidASN1Object(reason: "Successful response does not have appropriate response bytes: \(String(describing: responseBytes))")
throw ASN1Error.invalidASN1Object(
reason:
"Successful response does not have appropriate response bytes: \(String(describing: responseBytes))"
)
}
return .successful(try BasicOCSPResponse(derEncoded: responseBytes.response.bytes))
case .malformedRequest:
@@ -62,7 +66,7 @@ enum OCSPResponse: DERImplicitlyTaggable, Hashable {
}
}
}
private init(unsuccessfulStatus: OCSPResponse, responseBytes: OCSPResponseBytes?) throws {
if case .successful = unsuccessfulStatus {
preconditionFailure("this init is not allowed to be called with a successful response status")
@@ -80,12 +84,12 @@ enum OCSPResponse: DERImplicitlyTaggable, Hashable {
case .successful(let basicResponse):
let responseBytes = try OCSPResponseBytes(encoding: basicResponse)
try coder.serialize(responseBytes, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
case .malformedRequest,
.internalError,
.tryLater,
.sigRequired,
.unauthorized:
.internalError,
.tryLater,
.sigRequired,
.unauthorized:
break
}
}
+22 -11
View File
@@ -42,11 +42,13 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable {
var responseExtensions: Certificate.Extensions?
init(version: OCSPVersion = .v1,
responderID: ResponderID,
producedAt: GeneralizedTime,
responses: [OCSPSingleResponse],
responseExtensions: Certificate.Extensions? = nil) {
init(
version: OCSPVersion = .v1,
responderID: ResponderID,
producedAt: GeneralizedTime,
responses: [OCSPSingleResponse],
responseExtensions: Certificate.Extensions? = nil
) {
self.version = version
self.responderID = responderID
self.producedAt = producedAt
@@ -56,18 +58,27 @@ struct OCSPResponseData: DERImplicitlyTaggable, Hashable {
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let version = try DER.decodeDefaultExplicitlyTagged(&nodes,
tagNumber: 0,
tagClass: .contextSpecific,
defaultValue: 0) { try Int(derEncoded: $0) }
let version = try DER.decodeDefaultExplicitlyTagged(
&nodes,
tagNumber: 0,
tagClass: .contextSpecific,
defaultValue: 0
) { try Int(derEncoded: $0) }
let responderID = try ResponderID(derEncoded: &nodes)
let producedAt = try GeneralizedTime(derEncoded: &nodes)
let responses = try DER.sequence(of: OCSPSingleResponse.self, identifier: .sequence, nodes: &nodes)
let responseExtensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
let responseExtensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific)
{ node in
try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node)
}
return .init(version: .init(rawValue: version), responderID: responderID, producedAt: producedAt, responses: responses, responseExtensions: try responseExtensions.map { try .init($0) })
return .init(
version: .init(rawValue: version),
responderID: responderID,
producedAt: producedAt,
responses: responses,
responseExtensions: try responseExtensions.map { try .init($0) }
)
}
}
+1 -1
View File
@@ -61,7 +61,7 @@ enum OCSPResponseStatus: DERImplicitlyTaggable, Hashable {
throw ASN1Error.invalidASN1Object(reason: "Unexpected OCSP response status: \(rawValue)")
}
}
var integerValue: Int {
switch self {
case .successful: return 0
+6 -6
View File
@@ -25,19 +25,19 @@ struct OCSPSignature: DERImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
var algorithmIIdentifier: AlgorithmIdentifier
var signature: ASN1BitString
var certs: [Certificate]?
init(algorithmIIdentifier: AlgorithmIdentifier, signature: ASN1BitString, certs: [Certificate]? = nil) {
self.algorithmIIdentifier = algorithmIIdentifier
self.signature = signature
self.certs = certs
}
init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(derEncoded, identifier: identifier) { nodes in
let algorithmIdentifier = try AlgorithmIdentifier(derEncoded: &nodes)
@@ -48,7 +48,7 @@ struct OCSPSignature: DERImplicitlyTaggable, Hashable {
return .init(algorithmIIdentifier: algorithmIdentifier, signature: signature, certs: certs)
}
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try self.algorithmIIdentifier.serialize(into: &coder)
+10 -6
View File
@@ -25,20 +25,24 @@ struct OCSPSingleRequest: DERImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
var certID: OCSPCertID
var singleRequestExtensions: Certificate.Extensions?
init(certID: OCSPCertID, singleRequestExtensions: Certificate.Extensions? = nil) {
self.certID = certID
self.singleRequestExtensions = singleRequestExtensions
}
init(derEncoded: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(derEncoded, identifier: identifier) { nodes in
let certID = try OCSPCertID(derEncoded: &nodes)
let singleRequestExtensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
let singleRequestExtensions = try DER.optionalExplicitlyTagged(
&nodes,
tagNumber: 0,
tagClass: .contextSpecific
) { node in
try Certificate.Extensions(
try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node)
)
@@ -46,7 +50,7 @@ struct OCSPSingleRequest: DERImplicitlyTaggable, Hashable {
return .init(certID: certID, singleRequestExtensions: singleRequestExtensions)
}
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
try self.certID.serialize(into: &coder)
+18 -12
View File
@@ -40,11 +40,13 @@ struct OCSPSingleResponse: DERImplicitlyTaggable, Hashable {
var extensions: Certificate.Extensions?
init(certID: OCSPCertID,
certStatus: OCSPCertStatus,
thisUpdate: GeneralizedTime,
nextUpdate: GeneralizedTime?,
extensions: Certificate.Extensions? = nil) {
init(
certID: OCSPCertID,
certStatus: OCSPCertStatus,
thisUpdate: GeneralizedTime,
nextUpdate: GeneralizedTime?,
extensions: Certificate.Extensions? = nil
) {
self.certID = certID
self.certStatus = certStatus
self.thisUpdate = thisUpdate
@@ -57,18 +59,22 @@ struct OCSPSingleResponse: DERImplicitlyTaggable, Hashable {
let certID = try OCSPCertID(derEncoded: &nodes)
let certStatus = try OCSPCertStatus(derEncoded: &nodes)
let thisUpdate = try GeneralizedTime(derEncoded: &nodes)
let nextUpdate = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
let nextUpdate = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
node in
try GeneralizedTime(derEncoded: node)
}
let extensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
let extensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) {
node in
try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: node)
}
return .init(certID: certID,
certStatus: certStatus,
thisUpdate: thisUpdate,
nextUpdate: nextUpdate,
extensions: try extensions.map { try .init($0) })
return .init(
certID: certID,
certStatus: certStatus,
thisUpdate: thisUpdate,
nextUpdate: nextUpdate,
extensions: try extensions.map { try .init($0) }
)
}
}
+20 -10
View File
@@ -28,25 +28,35 @@ struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable {
static var defaultIdentifier: ASN1Identifier {
.sequence
}
var version: OCSPVersion
var requestorName: GeneralName?
var requestList: [OCSPSingleRequest]
var requestExtensions: Certificate.Extensions?
init(version: OCSPVersion, requestorName: GeneralName? = nil, requestList: [OCSPSingleRequest], requestExtensions: Certificate.Extensions? = nil) {
init(
version: OCSPVersion,
requestorName: GeneralName? = nil,
requestList: [OCSPSingleRequest],
requestExtensions: Certificate.Extensions? = nil
) {
self.version = version
self.requestorName = requestorName
self.requestList = requestList
self.requestExtensions = requestExtensions
}
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let version = try DER.decodeDefaultExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific, defaultValue: Int(0))
let version = try DER.decodeDefaultExplicitlyTagged(
&nodes,
tagNumber: 0,
tagClass: .contextSpecific,
defaultValue: Int(0)
)
let requestorName = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) {
try GeneralName(derEncoded: $0)
}
@@ -54,7 +64,7 @@ struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable {
let extensions = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 2, tagClass: .contextSpecific) {
try DER.sequence(of: Certificate.Extension.self, identifier: .sequence, rootNode: $0)
}
return .init(
version: .init(rawValue: version),
requestorName: requestorName,
@@ -63,7 +73,7 @@ struct OCSPTBSRequest: DERImplicitlyTaggable, Hashable {
)
}
}
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
if self.version != .v1 {
+2 -2
View File
@@ -22,9 +22,9 @@ struct OCSPVersion {
static let v1 = Self(rawValue: 0)
}
extension OCSPVersion: Hashable { }
extension OCSPVersion: Hashable {}
extension OCSPVersion: Sendable { }
extension OCSPVersion: Sendable {}
extension OCSPVersion: Comparable {
static func < (lhs: Self, rhs: Self) -> Bool {
+40 -44
View File
@@ -37,10 +37,10 @@ extension RelativeDistinguishedName {
/// the custom `Hashable` conformance takes care of this and treats them as equal.
case any(ASN1Any)
}
@usableFromInline
var storage: Storage
@inlinable
init(storage: Storage) {
self.storage = storage
@@ -68,7 +68,7 @@ extension RelativeDistinguishedName {
extension RelativeDistinguishedName.Attribute.Value.Storage: Hashable {
@inlinable
static func ==(lhs: Self, rhs: Self) -> Bool {
static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case let (.printable(lhs), .printable(rhs)):
return lhs == rhs
@@ -80,7 +80,7 @@ extension RelativeDistinguishedName.Attribute.Value.Storage: Hashable {
return ASN1Any(lhs) == ASN1Any(rhs)
}
}
@inlinable
func hash(into hasher: inout Hasher) {
switch self {
@@ -89,7 +89,7 @@ extension RelativeDistinguishedName.Attribute.Value.Storage: Hashable {
hasher.combine(ASN1Any(self))
case .utf8(let string):
hasher.combine(String.ASN1UTF8StringView(string: string))
case .any(let asn1Any):
hasher.combine(asn1Any)
}
@@ -101,17 +101,17 @@ extension String {
struct ASN1UTF8StringView {
@usableFromInline
let string: String
@usableFromInline
let length: ASN1Length
@usableFromInline
let count: Int
@inlinable
init(string: String) {
self.string = string
let utf8Count = self.string.utf8.count
self.length = ASN1Length(length: utf8Count)
// tag + utf8 bytes length + utf8 bytes
@@ -125,12 +125,12 @@ extension String.ASN1UTF8StringView: RandomAccessCollection {
var startIndex: Int {
0
}
@inlinable
var endIndex: Int {
count
}
@inlinable
subscript(position: Int) -> UInt8 {
switch position {
@@ -158,19 +158,18 @@ extension String.ASN1UTF8StringView: Hashable {
}
}
@usableFromInline
struct ASN1Length: Hashable {
@usableFromInline
var length: Int
@usableFromInline
var count: Int
@inlinable
init(length: Int) {
self.length = length
// ASN.1 lengths are in two forms. If we can store the length in 7 bits, we should:
// that requires only one byte. Otherwise, we need multiple bytes: work out how many,
// plus one for the length of the length bytes.
@@ -193,29 +192,27 @@ extension ASN1Length: RandomAccessCollection {
var startIndex: Int {
0
}
@inlinable
var endIndex: Int {
count
}
@inlinable
subscript(position: Int) -> UInt8 {
precondition(position >= 0 && position < self.count)
if self.length <= 0x7F {
return UInt8(truncatingIfNeeded: self.length)
} else {
if position == 0 {
// We first write the number of length bytes
// we needed, setting the high bit.
return 0b1000_0000 | UInt8(self.count &- 1)
} else {
guard self.length <= 0x7F else {
guard position == 0 else {
//Then we write the bytes of the length.
let integerBytesCollection = IntegerBytesCollection(self.length)
let index = integerBytesCollection.index(integerBytesCollection.startIndex, offsetBy: position &- 1)
return integerBytesCollection[index]
}
// We first write the number of length bytes
// we needed, setting the high bit.
return 0b1000_0000 | UInt8(self.count &- 1)
}
return UInt8(truncatingIfNeeded: self.length)
}
}
@@ -258,7 +255,7 @@ extension RelativeDistinguishedName.Attribute.Value {
_ = try ASN1PrintableString(printableString)
self.storage = .printable(printableString)
}
@inlinable
public init(asn1Any: ASN1Any) {
self.storage = .any(asn1Any)
@@ -283,13 +280,14 @@ extension RelativeDistinguishedName.Attribute.Value: CustomStringConvertible {
}
}
}
// This is a very slow way to do this, but until we have any evidence that
// this is hot code I'm happy to do it slowly.
let unescapedBytes = Array(text.utf8)
let charsToEscape: [UInt8] = [
UInt8(ascii: ","), UInt8(ascii: "+"), UInt8(ascii: "\""), UInt8(ascii: "\\"),
UInt8(ascii: "<"), UInt8(ascii: ">"), UInt8(ascii: ";")]
UInt8(ascii: "<"), UInt8(ascii: ">"), UInt8(ascii: ";"),
]
let leadingBytesToEscape = unescapedBytes.prefix(while: {
$0 == UInt8(ascii: " ") || $0 == UInt8(ascii: "#")
@@ -303,11 +301,10 @@ extension RelativeDistinguishedName.Attribute.Value: CustomStringConvertible {
var escapedBytes = leadingBytesToEscape.flatMap { [UInt8(ascii: "\\"), $0] }
escapedBytes += middleBytes.flatMap {
if charsToEscape.contains($0) {
return [UInt8(ascii: "\\"), $0]
} else {
guard charsToEscape.contains($0) else {
return [$0]
}
return [UInt8(ascii: "\\"), $0]
}
escapedBytes += trailingBytesToEscape.flatMap { [UInt8(ascii: "\\"), $0] }
@@ -322,10 +319,9 @@ extension RelativeDistinguishedName.Attribute.Value: CustomDebugStringConvertibl
}
}
extension RelativeDistinguishedName.Attribute: Hashable {}
extension RelativeDistinguishedName.Attribute: Hashable { }
extension RelativeDistinguishedName.Attribute: Sendable { }
extension RelativeDistinguishedName.Attribute: Sendable {}
extension RelativeDistinguishedName.Attribute: CustomStringConvertible {
@inlinable
@@ -367,7 +363,7 @@ extension RelativeDistinguishedName.Attribute: DERImplicitlyTaggable {
guard let valueNode = nodes.next() else {
throw ASN1Error.invalidASN1Object(reason: "RelativeDistinguishedName.Attribute.Value is missing")
}
let value: Value
switch type {
/// ```
@@ -457,11 +453,11 @@ extension RelativeDistinguishedName.Attribute: DERImplicitlyTaggable {
/// (SIZE (1..ub-organizational-unit-name)) }
/// ```
case .RDNAttributeType.commonName,
.RDNAttributeType.localityName,
.RDNAttributeType.stateOrProvinceName,
.RDNAttributeType.organizationName,
.RDNAttributeType.organizationalUnitName:
.RDNAttributeType.localityName,
.RDNAttributeType.stateOrProvinceName,
.RDNAttributeType.organizationName,
.RDNAttributeType.organizationalUnitName:
switch valueNode.identifier {
case ASN1UTF8String.defaultIdentifier:
value = try .init(utf8String: String(ASN1UTF8String(derEncoded: valueNode)))
@@ -470,7 +466,7 @@ extension RelativeDistinguishedName.Attribute: DERImplicitlyTaggable {
default:
value = .init(storage: .any(ASN1Any(derEncoded: valueNode)))
}
/// ```
/// -- Naming attributes of type X520countryName (digraph from IS 3166)
///
@@ -485,11 +481,11 @@ extension RelativeDistinguishedName.Attribute: DERImplicitlyTaggable {
default:
value = .init(storage: .any(ASN1Any(derEncoded: valueNode)))
}
default:
value = .init(storage: .any(ASN1Any(derEncoded: valueNode)))
}
return .init(type: type, value: value)
}
}
@@ -525,7 +521,7 @@ extension RelativeDistinguishedName.Attribute {
self.type = type
self.value = try .init(printableString: printableString)
}
/// Create a new attribute from a given type and value.
///
/// - Parameter type: The type of the attribute.
@@ -21,7 +21,7 @@ extension RandomNumberGenerator {
while bytes.count < count {
bytes.appendLittleEndianBytes(self.next())
}
return bytes[..<count]
}
}
+11 -11
View File
@@ -37,16 +37,16 @@ public struct RelativeDistinguishedName {
@usableFromInline
var attributes: _TinyArray<Attribute>
/// Construct a ``RelativeDistinguishedName`` from a sequence of ``Attribute``.
///
/// - Parameter attributes: The sequence of ``Attribute``s that make up the ``DistinguishedName``.
@inlinable
public init<AttributeSequence: Sequence>(_ attributes: AttributeSequence) where AttributeSequence.Element == RelativeDistinguishedName.Attribute {
public init<AttributeSequence: Sequence>(_ attributes: AttributeSequence)
where AttributeSequence.Element == RelativeDistinguishedName.Attribute {
self.attributes = .init(attributes)
Self._sortElements(&self.attributes)
}
/// Construct a ``RelativeDistinguishedName`` from a sequence of ``Attribute``.
///
/// - Parameter attributes: The sequence of ``Attribute``s that make up the ``DistinguishedName``.
@@ -54,7 +54,7 @@ public struct RelativeDistinguishedName {
public init(_ attribute: Attribute) {
self.init(CollectionOfOne(attribute))
}
@inlinable
init(_ attributes: DER.LazySetOfSequence<Attribute>) throws {
self.attributes = try .init(attributes)
@@ -68,9 +68,9 @@ public struct RelativeDistinguishedName {
}
}
extension RelativeDistinguishedName: Hashable { }
extension RelativeDistinguishedName: Hashable {}
extension RelativeDistinguishedName: Sendable { }
extension RelativeDistinguishedName: Sendable {}
extension RelativeDistinguishedName: RandomAccessCollection {
@inlinable
@@ -105,11 +105,12 @@ extension RelativeDistinguishedName: RandomAccessCollection {
///
/// - Parameter attributes: The ``Attribute``s to be inserted.
@inlinable
public mutating func insert<Attributes: Collection>(contentsOf attributes: Attributes) where Attributes.Element == RelativeDistinguishedName.Attribute {
public mutating func insert<Attributes: Collection>(contentsOf attributes: Attributes)
where Attributes.Element == RelativeDistinguishedName.Attribute {
self.attributes.append(contentsOf: attributes)
Self._sortElements(&self.attributes)
}
/// Removes and returns the ``Attribute`` at the specified position.
///
/// - Parameter index: The position of the ``Attribute`` to remove.
@@ -120,7 +121,7 @@ extension RelativeDistinguishedName: RandomAccessCollection {
self.attributes.remove(at: index)
// removing an element doesn't change the order and therefore sorting is not required
}
/// Removes all the ``Attribute``s that satisfy the given predicate.
/// - Parameter shouldBeRemoved: A closure that takes an ``Attribute`` of the
/// ``RelativeDistinguishedName`` as its argument and returns a Boolean value indicating
@@ -192,7 +193,7 @@ extension RelativeDistinguishedName: DERImplicitlyTaggable {
// We got to the end of the shorter element, so all current elements are equal.
// If lhs is shorter, it comes earlier, _unless_ all of rhs's trailing elements are zero.
let trailing = rhsBytes.dropFirst(lhsBytes.count)
if trailing.count == 0 || trailing.allSatisfy({ $0 == 0}) {
if trailing.count == 0 || trailing.allSatisfy({ $0 == 0 }) {
// Must return false when the two elements are equal.
return false
}
@@ -200,4 +201,3 @@ extension RelativeDistinguishedName: DERImplicitlyTaggable {
}
}
}
+3 -2
View File
@@ -40,7 +40,7 @@ import SwiftASN1
struct SEC1PrivateKey: DERImplicitlyTaggable, PEMRepresentable {
@usableFromInline
static let defaultPEMDiscriminator: String = "EC PRIVATE KEY"
@inlinable
static var defaultIdentifier: ASN1Identifier {
return .sequence
@@ -64,7 +64,8 @@ struct SEC1PrivateKey: DERImplicitlyTaggable, PEMRepresentable {
}
let privateKey = try ASN1OctetString(derEncoded: &nodes)
let parameters = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) { node in
let parameters = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific) {
node in
return try ASN1ObjectIdentifier(derEncoded: node)
}
let publicKey = try DER.optionalExplicitlyTagged(&nodes, tagNumber: 1, tagClass: .contextSpecific) { node in
+3 -3
View File
@@ -55,9 +55,9 @@ extension Certificate {
}
}
extension Certificate.Signature: Hashable { }
extension Certificate.Signature: Hashable {}
extension Certificate.Signature: Sendable { }
extension Certificate.Signature: Sendable {}
extension Certificate.Signature: CustomStringConvertible {
public var description: String {
@@ -77,7 +77,7 @@ extension Certificate.Signature {
case rsa(_CryptoExtras._RSA.Signing.RSASignature)
@inlinable
static func ==(lhs: BackingSignature, rhs: BackingSignature) -> Bool {
static func == (lhs: BackingSignature, rhs: BackingSignature) -> Bool {
switch (lhs, rhs) {
case (.ecdsa(let l), .ecdsa(let r)):
return l == r
+8 -6
View File
@@ -28,9 +28,9 @@ extension Certificate {
@inlinable
init(algorithmIdentifier: AlgorithmIdentifier) {
switch algorithmIdentifier {
// Per RFC 4055 § 5, we need to accept the RSA parameters field being
// absent, but we must _produce_ the one with an explicit NULL. So we
// normalise the signature algorithm here.
// Per RFC 4055 § 5, we need to accept the RSA parameters field being
// absent, but we must _produce_ the one with an explicit NULL. So we
// normalise the signature algorithm here.
case .sha1WithRSAEncryptionUsingNil:
self._algorithmIdentifier = .sha1WithRSAEncryption
case .sha256WithRSAEncryptionUsingNil:
@@ -88,9 +88,9 @@ extension Certificate {
}
}
extension Certificate.SignatureAlgorithm: Hashable { }
extension Certificate.SignatureAlgorithm: Hashable {}
extension Certificate.SignatureAlgorithm: Sendable { }
extension Certificate.SignatureAlgorithm: Sendable {}
extension Certificate.SignatureAlgorithm: CustomStringConvertible {
public var description: String {
@@ -136,7 +136,9 @@ extension AlgorithmIdentifier {
case .sha1WithRSAEncryption:
self = .sha1
default:
throw CertificateError.unsupportedSignatureAlgorithm(reason: "Cannot generate digest algorithm for \(signatureAlgorithm)")
throw CertificateError.unsupportedSignatureAlgorithm(
reason: "Cannot generate digest algorithm for \(signatureAlgorithm)"
)
}
}
}
+6 -7
View File
@@ -13,7 +13,6 @@
//===----------------------------------------------------------------------===//
import SwiftASN1
/// ``AnyPolicy`` can be used to erase the concrete type of some ``VerifierPolicy``.
/// Only use ``AnyPolicy`` if type erasure is necessary.
/// Instead try to use conditional inclusion of different policies using ``PolicyBuilder``.
@@ -29,29 +28,29 @@ import SwiftASN1
public struct AnyPolicy: VerifierPolicy {
@usableFromInline
var policy: any VerifierPolicy
@inlinable
/// Erases the type of some ``VerifierPolicy`` to ``AnyPolicy``.
/// - Parameter policy: the concrete ``VerifierPolicy``
public init(_ policy: some VerifierPolicy) {
self.policy = policy
}
/// Erases the type of some ``VerifierPolicy`` to ``AnyPolicy``.
/// - Parameter policy: the ``VerifierPolicy`` constructed using the ``PolicyBuilder`` DSL.
@inlinable
public init(@PolicyBuilder makePolicy: () throws -> some VerifierPolicy) rethrows {
self.init(try makePolicy())
}
@inlinable
public var verifyingCriticalExtensions: [SwiftASN1.ASN1ObjectIdentifier] {
policy.verifyingCriticalExtensions
}
@inlinable
public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult
{
await policy.chainMeetsPolicyRequirements(chain: chain)
}
}
+2 -1
View File
@@ -34,7 +34,8 @@ public struct CertificateStore: Sendable, Hashable {
}
@inlinable
mutating func insert<Certificates: Sequence>(contentsOf certificates: Certificates) where Certificates.Element == Certificate {
mutating func insert<Certificates: Sequence>(contentsOf certificates: Certificates)
where Certificates.Element == Certificate {
for certificate in certificates {
self.insert(certificate)
}
+39 -34
View File
@@ -14,8 +14,6 @@
import SwiftASN1
/// Provides a result-builder style DSL for constructing a ``VerifierPolicy``.
///
/// This DSL allows us to construct dynamic ``VerifierPolicy`` at runtime without using type erasure.
@@ -30,7 +28,6 @@ import SwiftASN1
@resultBuilder
public struct PolicyBuilder {}
extension PolicyBuilder {
@inlinable
public static func buildLimitedAvailability<Policy: VerifierPolicy>(_ component: Policy) -> Policy {
@@ -44,16 +41,16 @@ extension PolicyBuilder {
struct Empty: VerifierPolicy {
@inlinable
var verifyingCriticalExtensions: [SwiftASN1.ASN1ObjectIdentifier] { [] }
@inlinable
init() {}
@inlinable
mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
.meetsPolicy
}
}
@inlinable
public static func buildBlock() -> some VerifierPolicy {
Empty()
@@ -66,21 +63,21 @@ extension PolicyBuilder {
struct Tuple2<First: VerifierPolicy, Second: VerifierPolicy>: VerifierPolicy {
@usableFromInline
var first: First
@usableFromInline
var second: Second
@inlinable
init(first: First, second: Second) {
self.first = first
self.second = second
}
@inlinable
var verifyingCriticalExtensions: [SwiftASN1.ASN1ObjectIdentifier] {
first.verifyingCriticalExtensions + second.verifyingCriticalExtensions
}
@inlinable
mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
switch await first.chainMeetsPolicyRequirements(chain: chain) {
@@ -89,48 +86,50 @@ extension PolicyBuilder {
case .failsToMeetPolicy(let reason):
return .failsToMeetPolicy(reason: reason)
}
return await second.chainMeetsPolicyRequirements(chain: chain)
}
}
@inlinable
public static func buildPartialBlock<Policy: VerifierPolicy>(first: Policy) -> Policy {
first
}
@inlinable
public static func buildPartialBlock(accumulated: some VerifierPolicy, next: some VerifierPolicy) -> some VerifierPolicy {
public static func buildPartialBlock(
accumulated: some VerifierPolicy,
next: some VerifierPolicy
) -> some VerifierPolicy {
Tuple2(first: accumulated, second: next)
}
}
// MARK: if
extension PolicyBuilder {
@usableFromInline
struct WrappedOptional<Wrapped>: VerifierPolicy where Wrapped: VerifierPolicy {
@usableFromInline
var wrapped: Wrapped?
@inlinable
init(_ wrapped: Wrapped?) {
self.wrapped = wrapped
}
@inlinable
var verifyingCriticalExtensions: [SwiftASN1.ASN1ObjectIdentifier] {
self.wrapped?.verifyingCriticalExtensions ?? []
}
@inlinable
mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
await self.wrapped?.chainMeetsPolicyRequirements(chain: chain) ?? .meetsPolicy
}
}
@inlinable
public static func buildOptional(_ component: Optional<some VerifierPolicy>) -> some VerifierPolicy {
public static func buildOptional(_ component: (some VerifierPolicy)?) -> some VerifierPolicy {
WrappedOptional(component)
}
}
@@ -144,15 +143,15 @@ extension PolicyBuilder {
case first(First)
case second(Second)
}
@usableFromInline
var storage: Storage
@inlinable
init(storage: Storage) {
self.storage = storage
}
@inlinable
public var verifyingCriticalExtensions: [ASN1ObjectIdentifier] {
switch self.storage {
@@ -160,9 +159,11 @@ extension PolicyBuilder {
case .second(let second): return second.verifyingCriticalExtensions
}
}
@inlinable
public mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
public mutating func chainMeetsPolicyRequirements(
chain: UnverifiedCertificateChain
) async -> PolicyEvaluationResult {
switch self.storage {
case .first(var first):
defer { self.storage = .first(first) }
@@ -173,14 +174,18 @@ extension PolicyBuilder {
}
}
}
@inlinable
public static func buildEither<First: VerifierPolicy, Second: VerifierPolicy>(first component: First) -> _Either<First, Second> {
public static func buildEither<First: VerifierPolicy, Second: VerifierPolicy>(
first component: First
) -> _Either<First, Second> {
_Either<First, Second>(storage: .first(component))
}
@inlinable
public static func buildEither<First: VerifierPolicy, Second: VerifierPolicy>(second component: Second) -> _Either<First, Second> {
public static func buildEither<First: VerifierPolicy, Second: VerifierPolicy>(
second component: Second
) -> _Either<First, Second> {
_Either<First, Second>(storage: .second(component))
}
}
@@ -190,27 +195,27 @@ extension PolicyBuilder {
struct CachedVerifyingCriticalExtensions<Wrapped: VerifierPolicy>: VerifierPolicy {
@usableFromInline
let verifyingCriticalExtensions: [ASN1ObjectIdentifier]
@usableFromInline
var wrapped: Wrapped
@inlinable
init(wrapped: Wrapped) {
self.verifyingCriticalExtensions = wrapped.verifyingCriticalExtensions
self.wrapped = wrapped
}
@inlinable
mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
await wrapped.chainMeetsPolicyRequirements(chain: chain)
}
}
@inlinable
public static func buildFinalResult(_ component: some VerifierPolicy) -> some VerifierPolicy {
CachedVerifyingCriticalExtensions(wrapped: component)
}
@inlinable
public static func buildFinalResult(_ component: AnyPolicy) -> AnyPolicy {
func unwrapExistentialAndCache(policy: some VerifierPolicy) -> some VerifierPolicy {
@@ -23,7 +23,7 @@ struct BasicConstraintsPolicy: VerifierPolicy {
]
@inlinable
init() { }
init() {}
@inlinable
func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) -> PolicyEvaluationResult {
@@ -56,7 +56,9 @@ struct BasicConstraintsPolicy: VerifierPolicy {
return .failsToMeetPolicy(reason: "RFC5280Policy: Self-signed cert \(leaf) is not marked as a CA")
}
} catch {
return .failsToMeetPolicy(reason: "RFC5280Policy: Error processing basic constraints for \(leaf): \(error)")
return .failsToMeetPolicy(
reason: "RFC5280Policy: Error processing basic constraints for \(leaf): \(error)"
)
}
}
@@ -73,7 +75,10 @@ struct BasicConstraintsPolicy: VerifierPolicy {
()
case (.some(.isCertificateAuthority(.some(let maxPathLength))), _) where maxPathLength < subCACount:
// Is a CA, but the max path length is smaller than the number of sub CAs we have.
return .failsToMeetPolicy(reason: "RFC5280Policy: CA \(cert) has maximum path length \(maxPathLength), but chain has \(subCACount) subCAs")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: CA \(cert) has maximum path length \(maxPathLength), but chain has \(subCACount) subCAs"
)
case (.some(.isCertificateAuthority), _):
// Is a CA, but either the max path length is at least as large as our current set of sub CAs, or there isn't one.
@@ -84,9 +89,11 @@ struct BasicConstraintsPolicy: VerifierPolicy {
return .failsToMeetPolicy(reason: "RFC5280Policy: Certificate \(cert) is not marked as a CA")
}
} catch {
return .failsToMeetPolicy(reason: "RFC5280Policy: Error processing basic constraints for \(cert): \(error)")
return .failsToMeetPolicy(
reason: "RFC5280Policy: Error processing basic constraints for \(cert): \(error)"
)
}
if cert.issuer != cert.subject {
// only non-self-issued certificates count against the maxPathLength limit
//
@@ -107,7 +114,7 @@ struct BasicConstraintsPolicy: VerifierPolicy {
// not appear, no limit is imposed.
// [...]
// https://www.rfc-editor.org/rfc/rfc5280#section-4.2.1.9
subCACount += 1
}
}
+18 -16
View File
@@ -109,14 +109,14 @@ extension NameConstraintsPolicy {
return false
case (.some, .some(let constraintLabel)) where constraintLabel.count == 0:
// We have an empty constraint label. This must be last, so confirm that.
if reverseConstraintLabels.hasMoreLabels {
// This label is empty, and not last, which is unacceptable.
return false
} else {
guard reverseConstraintLabels.hasMoreLabels else {
// The period matches everything else, so we're good to go.
return true
}
case (.some(let dnsLabel), .some(let constraintLabel)) where dnsLabel.caseInsensitiveASCIIMatch(constraintLabel):
// This label is empty, and not last, which is unacceptable.
return false
case (.some(let dnsLabel), .some(let constraintLabel))
where dnsLabel.caseInsensitiveASCIIMatch(constraintLabel):
// The two labels match, continue.
continue
case (.some, .some):
@@ -256,20 +256,19 @@ struct ReverseDNSLabelSequence: Sequence {
// We walk backwards from the end until we find a period, then
// we slice out that section and return it.
if let periodIndex = base.lastIndex(of: ASCII_PERIOD) {
// Ok, we found a period. Slice out that section, then drop the
// period and save the updated base.
let labelStartIndex = base.index(after: periodIndex)
let label = base[labelStartIndex...]
self.base = base[..<periodIndex]
return label
} else {
guard let periodIndex = base.lastIndex(of: ASCII_PERIOD) else {
// No period left! Return the entirety of what is left as the label,
// and then store nil.
let label = base
self.base = nil
return label
}
// Ok, we found a period. Slice out that section, then drop the
// period and save the updated base.
let labelStartIndex = base.index(after: periodIndex)
let label = base[labelStartIndex...]
self.base = base[..<periodIndex]
return label
}
@inlinable var hasMoreLabels: Bool {
@@ -288,9 +287,12 @@ extension String.UTF8View.SubSequence {
return false
}
return self.elementsEqual(other, by: { selfByte, otherByte in
(selfByte & Self.asciiCaseInsensitiveMask) == (otherByte & Self.asciiCaseInsensitiveMask)
})
return self.elementsEqual(
other,
by: { selfByte, otherByte in
(selfByte & Self.asciiCaseInsensitiveMask) == (otherByte & Self.asciiCaseInsensitiveMask)
}
)
}
@usableFromInline
@@ -19,7 +19,8 @@ extension NameConstraintsPolicy {
/// However, most implementations don't bother, and just directly compare the distinguished
/// names.
@inlinable
static func directoryNameMatchesConstraint(directoryName: DistinguishedName, constraint: DistinguishedName) -> Bool {
static func directoryNameMatchesConstraint(directoryName: DistinguishedName, constraint: DistinguishedName) -> Bool
{
return directoryName == constraint
}
}
@@ -40,7 +40,10 @@ struct ExpiryPolicy: VerifierPolicy {
let notValidAfter = GeneralizedTime(cert.tbsCertificate.validity.notAfter)
if notValidBefore > notValidAfter {
return .failsToMeetPolicy(reason: "RFC5280Policy: Certificate \(cert) has invalid expiry, notValidAfter is earlier than notValidBefore")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: Certificate \(cert) has invalid expiry, notValidAfter is earlier than notValidBefore"
)
}
if self.validationTime < notValidBefore {
@@ -23,7 +23,7 @@ struct NameConstraintsPolicy: VerifierPolicy {
]
@inlinable
init() { }
init() {}
@inlinable
func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) -> PolicyEvaluationResult {
@@ -82,11 +82,17 @@ struct NameConstraintsPolicy: VerifierPolicy {
}
for name in names {
if case .failsToMeetPolicy(let reason) = Self._validatePermittedSubtrees(constraints.permittedSubtrees, name) {
if case .failsToMeetPolicy(let reason) = Self._validatePermittedSubtrees(
constraints.permittedSubtrees,
name
) {
return .failsToMeetPolicy(reason: reason)
}
if case .failsToMeetPolicy(let reason) = Self._validateExcludedSubtrees(constraints.excludedSubtrees, name) {
if case .failsToMeetPolicy(let reason) = Self._validateExcludedSubtrees(
constraints.excludedSubtrees,
name
) {
return .failsToMeetPolicy(reason: reason)
}
}
@@ -97,26 +103,39 @@ struct NameConstraintsPolicy: VerifierPolicy {
@inlinable
static func _validateExcludedSubtrees(
_ excludedSubtrees: [GeneralName], _ name: GeneralName
_ excludedSubtrees: [GeneralName],
_ name: GeneralName
) -> PolicyEvaluationResult {
// For excluded trees, if _any_ match then the name is forbidden.
for excludedSubtree in excludedSubtrees {
switch (excludedSubtree, name) {
case (.directoryName(let constraint), .directoryName(let presentedName)):
if directoryNameMatchesConstraint(directoryName: presentedName, constraint: constraint) {
return .failsToMeetPolicy(reason: "RFC5280Policy: directoryName \(presentedName) is excluded by \(excludedSubtree) in name constraints")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: directoryName \(presentedName) is excluded by \(excludedSubtree) in name constraints"
)
}
case (.dnsName(let constraint), .dnsName(let presentedName)):
if dnsNameMatchesConstraint(dnsName: presentedName.utf8, constraint: constraint.utf8) {
return .failsToMeetPolicy(reason: "RFC5280Policy: dnsName \(presentedName) is excluded by \(excludedSubtree) in name constraints")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: dnsName \(presentedName) is excluded by \(excludedSubtree) in name constraints"
)
}
case (.ipAddress(let constraint), .ipAddress(let presentedName)):
if ipAddressMatchesConstraint(ipAddress: presentedName, constraint: constraint) {
return .failsToMeetPolicy(reason: "RFC5280Policy: ipAddress \(presentedName) is excluded by \(excludedSubtree) in name constraints")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: ipAddress \(presentedName) is excluded by \(excludedSubtree) in name constraints"
)
}
case (.uniformResourceIdentifier(let constraint), .uniformResourceIdentifier(let presentedName)):
if uriNameMatchesConstraint(uriName: presentedName, constraint: constraint) {
return .failsToMeetPolicy(reason: "RFC5280Policy: URI \(presentedName) is excluded by \(excludedSubtree) in name constraints")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: URI \(presentedName) is excluded by \(excludedSubtree) in name constraints"
)
}
case (.directoryName, _), (.dnsName, _), (.ipAddress, _), (.uniformResourceIdentifier, _):
// We support these, but the current name isn't of that type.
@@ -127,7 +146,10 @@ struct NameConstraintsPolicy: VerifierPolicy {
// Of the set that's currently unsupported, we should probably support rfc822Name (a.k.a. email address).
// For now we're omitting it, but at some point someone is going to run into this limitation and we'll want to come
// back and fix it.
return .failsToMeetPolicy(reason: "RFC5280Policy: Unable to validate excluded subtree for name \(excludedSubtree), unsupported constraint")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: Unable to validate excluded subtree for name \(excludedSubtree), unsupported constraint"
)
}
}
@@ -137,7 +159,8 @@ struct NameConstraintsPolicy: VerifierPolicy {
@inlinable
static func _validatePermittedSubtrees(
_ permittedSubtrees: [GeneralName], _ name: GeneralName
_ permittedSubtrees: [GeneralName],
_ name: GeneralName
) -> PolicyEvaluationResult {
var evaluatedAtLeastOneConstraint = false
@@ -182,16 +205,20 @@ struct NameConstraintsPolicy: VerifierPolicy {
// Of the set that's currently unsupported, we should probably support rfc822Name (a.k.a. email address).
// For now we're omitting it, but at some point someone is going to run into this limitation and we'll want to come
// back and fix it.
return .failsToMeetPolicy(reason: "RFC5280Policy: Unable to validate permitted subtree for name \(permittedSubtree), unsupported constraint")
return .failsToMeetPolicy(
reason:
"RFC5280Policy: Unable to validate permitted subtree for name \(permittedSubtree), unsupported constraint"
)
}
}
// Uh-oh, nothing matched! This is only a problem if we have at least one constraint for the given type.
if evaluatedAtLeastOneConstraint {
return .failsToMeetPolicy(reason: "RFC5280Policy: Unable to validate permitted subtree for \(permittedSubtrees), no matches!")
} else {
guard evaluatedAtLeastOneConstraint else {
return .meetsPolicy
}
return .failsToMeetPolicy(
reason: "RFC5280Policy: Unable to validate permitted subtree for \(permittedSubtrees), no matches!"
)
}
}
@@ -238,12 +265,11 @@ extension Certificate {
@inlinable
mutating func next() -> GeneralName? {
if let subject = self.subject {
self.subject = nil
return .directoryName(subject)
} else {
guard let subject = self.subject else {
return self.alternativeNames.popFirst()
}
self.subject = nil
return .directoryName(subject)
}
}
}
@@ -35,9 +35,9 @@ public struct RFC5280Policy: VerifierPolicy {
// done a very poor job of actually implementing it. The result is that policing KeyUsage produces minimal value
// in terms of increased security, but produces a substantial uptick in the number of unbuildable chains. So
// we _pretend_ to police the key usage, and just...don't.
.X509ExtensionID.keyUsage
.X509ExtensionID.keyUsage,
]
@usableFromInline
let versionPolicy: VersionPolicy
@@ -75,11 +75,14 @@ public struct RFC5280Policy: VerifierPolicy {
if case .failsToMeetPolicy(let reason) = self.versionPolicy.chainMeetsPolicyRequirements(chain: chain) {
return .failsToMeetPolicy(reason: reason)
}
if let expiryPolicy = self.expiryPolicy, case .failsToMeetPolicy(let reason) = expiryPolicy.chainMeetsPolicyRequirements(chain: chain) {
if let expiryPolicy = self.expiryPolicy,
case .failsToMeetPolicy(let reason) = expiryPolicy.chainMeetsPolicyRequirements(chain: chain)
{
return .failsToMeetPolicy(reason: reason)
}
if case .failsToMeetPolicy(let reason) = self.basicConstraintsPolicy.chainMeetsPolicyRequirements(chain: chain) {
if case .failsToMeetPolicy(let reason) = self.basicConstraintsPolicy.chainMeetsPolicyRequirements(chain: chain)
{
return .failsToMeetPolicy(reason: reason)
}
@@ -68,22 +68,19 @@ extension NameConstraintsPolicy {
extension String {
@inlinable
var isIPAddress: Bool {
#if os(Windows)
#if os(Windows)
var v4: IN_ADDR = IN_ADDR()
var v6: IN6_ADDR = IN6_ADDR()
return self.withCString(encodedAs: UTF16.self) {
return InetPtonW(AF_INET, $0, &v4) == 1 ||
InetPtonW(AF_INET6, $0, &v6) == 1
return InetPtonW(AF_INET, $0, &v4) == 1 || InetPtonW(AF_INET6, $0, &v6) == 1
}
#else
#else
// We need some scratch space to let inet_pton write into.
var ipv4Addr = in_addr()
var ipv6Addr = in6_addr()
return self.withCString { ptr in
return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 ||
inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
return inet_pton(AF_INET, ptr, &ipv4Addr) == 1 || inet_pton(AF_INET6, ptr, &ipv6Addr) == 1
}
#endif
#endif
}
}
@@ -19,15 +19,17 @@ import SwiftASN1
struct VersionPolicy: VerifierPolicy {
@inlinable
var verifyingCriticalExtensions: [SwiftASN1.ASN1ObjectIdentifier] { [] }
@inlinable
init() {}
@inlinable
func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) -> PolicyEvaluationResult {
for certificate in chain {
if certificate.version == .v1 && certificate.extensions.isEmpty == false {
return .failsToMeetPolicy(reason: "version 1 certificate contains extensions but should not: \(certificate)")
return .failsToMeetPolicy(
reason: "version 1 certificate contains extensions but should not: \(certificate)"
)
}
}
return .meetsPolicy
+145 -110
View File
@@ -18,55 +18,55 @@ public struct VerificationDiagnostic: Sendable {
var leafCertificate: Certificate
var handledCriticalExtensions: [ASN1ObjectIdentifier]
}
struct LeafCertificateIsInTheRootStoreButDoesNotMeetPolicy: Hashable, Sendable {
var leafCertificate: Certificate
var failsToMeetPolicyReason: String
}
struct ChainFailsToMeetPolicy: Hashable, Sendable {
var chain: UnverifiedCertificateChain
var failsToMeetPolicyReason: String
}
struct IssuerHasUnhandledCriticalExtension: Hashable, Sendable {
var issuer: Certificate
var partialChain: [Certificate]
var handledCriticalExtensions: [ASN1ObjectIdentifier]
}
struct IssuerHasNotSignedCertificate: Hashable, Sendable {
var issuer: Certificate
var partialChain: [Certificate]
}
struct SearchingForIssuerOfPartialChain: Hashable, Sendable {
var partialChain: [Certificate]
}
struct FoundCandidateIssuersOfPartialChainInRootStore: Hashable, Sendable {
var partialChain: [Certificate]
var issuersInRootStore: [Certificate]
}
struct FoundCandidateIssuersOfPartialChainInIntermediateStore: Hashable, Sendable {
var partialChain: [Certificate]
var issuersInIntermediateStore: [Certificate]
}
struct FoundValidCertificateChain: Hashable, Sendable {
var validCertificateChain: [Certificate]
}
struct CouldNotValidateLeafCertificate: Hashable, Sendable {
var leaf: Certificate
}
struct IssuerIsAlreadyInTheChain: Hashable, Sendable {
var partialChain: [Certificate]
var issuer: Certificate
}
enum Storage: Hashable, Sendable {
case leafCertificateHasUnhandledCriticalExtension(LeafCertificateHasUnhandledCriticalExtensions)
case leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(LeafCertificateIsInTheRootStoreButDoesNotMeetPolicy)
@@ -75,12 +75,14 @@ public struct VerificationDiagnostic: Sendable {
case issuerHasNotSignedCertificate(IssuerHasNotSignedCertificate)
case searchingForIssuerOfPartialChain(SearchingForIssuerOfPartialChain)
case foundCandidateIssuersOfPartialChainInRootStore(FoundCandidateIssuersOfPartialChainInRootStore)
case foundCandidateIssuersOfPartialChainInIntermediateStore(FoundCandidateIssuersOfPartialChainInIntermediateStore)
case foundCandidateIssuersOfPartialChainInIntermediateStore(
FoundCandidateIssuersOfPartialChainInIntermediateStore
)
case foundValidCertificateChain(FoundValidCertificateChain)
case couldNotValidateLeafCertificate(CouldNotValidateLeafCertificate)
case issuerIsAlreadyInTheChain(IssuerIsAlreadyInTheChain)
}
var storage: Storage
}
@@ -89,100 +91,116 @@ extension VerificationDiagnostic {
_ leafCertificate: Certificate,
handledCriticalExtensions: [ASN1ObjectIdentifier]
) -> Self {
self.init(storage: .leafCertificateHasUnhandledCriticalExtension(
leafCertificate,
handledCriticalExtensions: handledCriticalExtensions
))
self.init(
storage: .leafCertificateHasUnhandledCriticalExtension(
leafCertificate,
handledCriticalExtensions: handledCriticalExtensions
)
)
}
static func leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(
_ leafCertificate: Certificate,
reason failsToMeetPolicyReason: String
) -> Self {
self.init(storage: .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(
leafCertificate,
reason: failsToMeetPolicyReason
))
self.init(
storage: .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(
leafCertificate,
reason: failsToMeetPolicyReason
)
)
}
static func chainFailsToMeetPolicy(
_ chain: UnverifiedCertificateChain,
reason failsToMeetPolicyReason: String
) -> Self {
self.init(storage: .chainFailsToMeetPolicy(
chain,
reason: failsToMeetPolicyReason
))
self.init(
storage: .chainFailsToMeetPolicy(
chain,
reason: failsToMeetPolicyReason
)
)
}
static func issuerHasUnhandledCriticalExtension(
issuer: Certificate,
chain: CandidatePartialChain,
handledCriticalExtensions: [ASN1ObjectIdentifier]
) -> Self {
self.init(storage: .issuerHasUnhandledCriticalExtension(
issuer: issuer,
partialChain: chain.chain + CollectionOfOne(chain.currentTip),
handledCriticalExtensions: handledCriticalExtensions
))
self.init(
storage: .issuerHasUnhandledCriticalExtension(
issuer: issuer,
partialChain: chain.chain + CollectionOfOne(chain.currentTip),
handledCriticalExtensions: handledCriticalExtensions
)
)
}
static func issuerHasNotSignedCertificate(
_ issuer: Certificate,
chain: CandidatePartialChain
) -> Self {
self.init(storage: .issuerHasNotSignedCertificate(
issuer,
partialChain: chain.chain + CollectionOfOne(chain.currentTip)
))
self.init(
storage: .issuerHasNotSignedCertificate(
issuer,
partialChain: chain.chain + CollectionOfOne(chain.currentTip)
)
)
}
static func searchingForIssuerOfPartialChain(
_ partialChain: CandidatePartialChain
) -> Self {
.init(storage: .searchingForIssuerOfPartialChain(partialChain.chain + CollectionOfOne(partialChain.currentTip)))
}
static func foundCandidateIssuersOfPartialChainInRootStore(
_ partialChain: CandidatePartialChain,
issuers issuersInRootStore: [Certificate]
) -> Self {
.init(storage: .foundCandidateIssuersOfPartialChainInRootStore(
partialChain.chain + CollectionOfOne(partialChain.currentTip),
issuers: issuersInRootStore
))
.init(
storage: .foundCandidateIssuersOfPartialChainInRootStore(
partialChain.chain + CollectionOfOne(partialChain.currentTip),
issuers: issuersInRootStore
)
)
}
static func foundCandidateIssuersOfPartialChainInIntermediateStore(
_ partialChain: CandidatePartialChain,
issuers issuersInIntermediateStore: [Certificate]
) -> Self {
.init(storage: .foundCandidateIssuersOfPartialChainInIntermediateStore(
partialChain.chain + CollectionOfOne(partialChain.currentTip),
issuers: issuersInIntermediateStore
))
.init(
storage: .foundCandidateIssuersOfPartialChainInIntermediateStore(
partialChain.chain + CollectionOfOne(partialChain.currentTip),
issuers: issuersInIntermediateStore
)
)
}
static func foundValidCertificateChain(
_ validCertificateChain: [Certificate]
) -> Self {
.init(storage: .foundValidCertificateChain(validCertificateChain))
}
static func couldNotValidateLeafCertificate(
_ leaf: Certificate
) -> Self {
.init(storage: .couldNotValidateLeafCertificate(leaf))
}
static func issuerIsAlreadyInTheChain(
_ partialChain: CandidatePartialChain,
issuer: Certificate
) -> Self {
.init(storage: .issuerIsAlreadyInTheChain(
partialChain.chain + CollectionOfOne(partialChain.currentTip),
issuer: issuer
))
.init(
storage: .issuerIsAlreadyInTheChain(
partialChain.chain + CollectionOfOne(partialChain.currentTip),
issuer: issuer
)
)
}
}
@@ -191,92 +209,106 @@ extension VerificationDiagnostic.Storage {
_ leafCertificate: Certificate,
handledCriticalExtensions: [ASN1ObjectIdentifier]
) -> Self {
.leafCertificateHasUnhandledCriticalExtension(.init(
leafCertificate: leafCertificate,
handledCriticalExtensions: handledCriticalExtensions
))
.leafCertificateHasUnhandledCriticalExtension(
.init(
leafCertificate: leafCertificate,
handledCriticalExtensions: handledCriticalExtensions
)
)
}
static func leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(
_ leafCertificate: Certificate,
reason failsToMeetPolicyReason: String
) -> Self {
.leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(.init(
leafCertificate: leafCertificate,
failsToMeetPolicyReason: failsToMeetPolicyReason
))
.leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(
.init(
leafCertificate: leafCertificate,
failsToMeetPolicyReason: failsToMeetPolicyReason
)
)
}
static func chainFailsToMeetPolicy(
_ chain: UnverifiedCertificateChain,
reason failsToMeetPolicyReason: String
) -> Self {
.chainFailsToMeetPolicy(.init(
chain: chain,
failsToMeetPolicyReason: failsToMeetPolicyReason
))
.chainFailsToMeetPolicy(
.init(
chain: chain,
failsToMeetPolicyReason: failsToMeetPolicyReason
)
)
}
static func issuerHasUnhandledCriticalExtension(
issuer: Certificate,
partialChain: [Certificate],
handledCriticalExtensions: [ASN1ObjectIdentifier]
) -> Self {
.issuerHashUnhandledCriticalExtension(.init(
issuer: issuer,
partialChain: partialChain,
handledCriticalExtensions: handledCriticalExtensions
))
.issuerHashUnhandledCriticalExtension(
.init(
issuer: issuer,
partialChain: partialChain,
handledCriticalExtensions: handledCriticalExtensions
)
)
}
static func issuerHasNotSignedCertificate(
_ issuer: Certificate,
partialChain: [Certificate]
) -> Self {
.issuerHasNotSignedCertificate(.init(
issuer: issuer,
partialChain: partialChain
))
.issuerHasNotSignedCertificate(
.init(
issuer: issuer,
partialChain: partialChain
)
)
}
static func searchingForIssuerOfPartialChain(
_ partialChain: [Certificate]
) -> Self {
.searchingForIssuerOfPartialChain(.init(partialChain: partialChain))
}
static func foundCandidateIssuersOfPartialChainInRootStore(
_ partialChain: [Certificate],
issuers issuersInRootStore: [Certificate]
) -> Self {
.foundCandidateIssuersOfPartialChainInRootStore(.init(
partialChain: partialChain,
issuersInRootStore: issuersInRootStore
))
.foundCandidateIssuersOfPartialChainInRootStore(
.init(
partialChain: partialChain,
issuersInRootStore: issuersInRootStore
)
)
}
static func foundCandidateIssuersOfPartialChainInIntermediateStore(
_ partialChain: [Certificate],
issuers issuersInIntermediateStore: [Certificate]
) -> Self {
.foundCandidateIssuersOfPartialChainInIntermediateStore(.init(
partialChain: partialChain,
issuersInIntermediateStore: issuersInIntermediateStore
))
.foundCandidateIssuersOfPartialChainInIntermediateStore(
.init(
partialChain: partialChain,
issuersInIntermediateStore: issuersInIntermediateStore
)
)
}
static func foundValidCertificateChain(
_ validCertificateChain: [Certificate]
) -> Self {
.foundValidCertificateChain(.init(validCertificateChain: validCertificateChain))
}
static func couldNotValidateLeafCertificate(
_ leaf: Certificate
) -> Self {
.couldNotValidateLeafCertificate(.init(leaf: leaf))
}
static func issuerIsAlreadyInTheChain(
_ partialChain: [Certificate],
issuer: Certificate
@@ -287,7 +319,9 @@ extension VerificationDiagnostic.Storage {
extension Certificate.Extensions {
@inlinable
func unhandledCriticalExtensions(for handledCriticalExtensions: [ASN1ObjectIdentifier]) -> some Sequence<Certificate.Extension> {
func unhandledCriticalExtensions(
for handledCriticalExtensions: [ASN1ObjectIdentifier]
) -> some Sequence<Certificate.Extension> {
self.lazy.filter { ext in
ext.critical && !handledCriticalExtensions.contains(ext.oid)
}
@@ -313,7 +347,8 @@ extension VerificationDiagnostic.Storage: CustomStringConvertible {
case .issuerHasNotSignedCertificate(let diagnostic): return String(describing: diagnostic)
case .searchingForIssuerOfPartialChain(let diagnostic): return String(describing: diagnostic)
case .foundCandidateIssuersOfPartialChainInRootStore(let diagnostic): return String(describing: diagnostic)
case .foundCandidateIssuersOfPartialChainInIntermediateStore(let diagnostic): return String(describing: diagnostic)
case .foundCandidateIssuersOfPartialChainInIntermediateStore(let diagnostic):
return String(describing: diagnostic)
case .foundValidCertificateChain(let diagnostic): return String(describing: diagnostic)
case .couldNotValidateLeafCertificate(let diagnostic): return String(describing: diagnostic)
case .issuerIsAlreadyInTheChain(let diagnostic): return String(describing: diagnostic)
@@ -429,7 +464,6 @@ extension VerificationDiagnostic.FoundValidCertificateChain: CustomStringConvert
}
}
extension VerificationDiagnostic.CouldNotValidateLeafCertificate: CustomStringConvertible {
var description: String {
"""
@@ -451,7 +485,6 @@ extension VerificationDiagnostic.IssuerIsAlreadyInTheChain: CustomStringConverti
}
}
// MARK: CustomDebugStringConvertible
extension VerificationDiagnostic: CustomDebugStringConvertible {
@@ -475,13 +508,15 @@ extension VerificationDiagnostic.Storage {
var multilineDescription: String {
switch self {
case .leafCertificateHasUnhandledCriticalExtension(let diagnostic): return diagnostic.multilineDescription
case .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(let diagnostic): return diagnostic.multilineDescription
case .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(let diagnostic):
return diagnostic.multilineDescription
case .chainFailsToMeetPolicy(let diagnostic): return diagnostic.multilineDescription
case .issuerHashUnhandledCriticalExtension(let diagnostic): return diagnostic.multilineDescription
case .issuerHasNotSignedCertificate(let diagnostic): return diagnostic.multilineDescription
case .searchingForIssuerOfPartialChain(let diagnostic): return diagnostic.multilineDescription
case .foundCandidateIssuersOfPartialChainInRootStore(let diagnostic): return diagnostic.multilineDescription
case .foundCandidateIssuersOfPartialChainInIntermediateStore(let diagnostic): return diagnostic.multilineDescription
case .foundCandidateIssuersOfPartialChainInIntermediateStore(let diagnostic):
return diagnostic.multilineDescription
case .foundValidCertificateChain(let diagnostic): return diagnostic.multilineDescription
case .couldNotValidateLeafCertificate(let diagnostic): return diagnostic.multilineDescription
case .issuerIsAlreadyInTheChain(let diagnostic): return diagnostic.multilineDescription
@@ -493,12 +528,12 @@ extension VerificationDiagnostic.LeafCertificateHasUnhandledCriticalExtensions {
var multilineDescription: String {
"""
The leaf certificate has critical extensions that the policy does not understand and therefore can't enforce.
Unhandled extensions:
\(self.leafCertificate.extensions.unhandledCriticalExtensions(
for: self.handledCriticalExtensions
).lazy.map { String(reflecting: $0) }.joined(separator: "\n"))
Leaf certificate:
\(String(reflecting: self.leafCertificate))
"""
@@ -509,10 +544,10 @@ extension VerificationDiagnostic.LeafCertificateIsInTheRootStoreButDoesNotMeetPo
var multilineDescription: String {
"""
Leaf certificate is in the root store of the verifier but it does by itself not meet the policy.
Reason:
\(String(reflecting: self.failsToMeetPolicyReason))
Leaf Certificate:
\(String(reflecting: self.leafCertificate))
"""
@@ -523,10 +558,10 @@ extension VerificationDiagnostic.ChainFailsToMeetPolicy {
var multilineDescription: String {
"""
A certificate chain to a certificate in the root store was found but it does not meet the policy.
Reason:
\(String(reflecting: self.failsToMeetPolicyReason))
Chain (from leaf to root):
\(self.chain.lazy.map { String(reflecting: $0) }.joined(separator: "\n"))
"""
@@ -537,12 +572,12 @@ extension VerificationDiagnostic.IssuerHasUnhandledCriticalExtension {
var multilineDescription: String {
"""
A candidate issuer of a certificate in the (partial) chain has critical extensions that the policy does not understand and therefore can't enforce.
Unhandled extensions:
\(self.issuer.extensions.unhandledCriticalExtensions(
for: self.handledCriticalExtensions
).lazy.map { "- \(String(reflecting: $0))" }.joined(separator: "\n"))
Chain (from leaf to candidate issuer that has critical extensions the policy doesn't enforce):
\(self.partialChain.lazy.map { String(reflecting: $0) }.joined(separator: "\n"))
\(String(reflecting: issuer))
@@ -554,7 +589,7 @@ extension VerificationDiagnostic.IssuerHasNotSignedCertificate {
var multilineDescription: String {
"""
A candidate issuer of a certificate in the (partial) chain has not signed the previous certificate in the chain.
Chain (from leaf to candidate issuer that has not signed the certificate before it):
\(self.partialChain.lazy.map { String(reflecting: $0) }.joined(separator: "\n"))
\(String(reflecting: self.issuer))
+60 -24
View File
@@ -24,7 +24,11 @@ public struct Verifier<Policy: VerifierPolicy> {
self.policy = try policy()
}
public mutating func validate(leafCertificate: Certificate, intermediates: CertificateStore, diagnosticCallback: ((VerificationDiagnostic) -> Void)? = nil) async -> VerificationResult {
public mutating func validate(
leafCertificate: Certificate,
intermediates: CertificateStore,
diagnosticCallback: ((VerificationDiagnostic) -> Void)? = nil
) async -> VerificationResult {
var partialChains: [CandidatePartialChain] = [CandidatePartialChain(leaf: leafCertificate)]
var policyFailures: [VerificationResult.PolicyFailure] = []
@@ -32,8 +36,13 @@ public struct Verifier<Policy: VerifierPolicy> {
// First check: does this leaf certificate contain critical extensions that are not satisfied by the policyset?
// If so, reject the chain.
if leafCertificate.hasUnhandledCriticalExtensions(handledExtensions: self.policy.verifyingCriticalExtensions) {
diagnosticCallback?(.leafCertificateHasUnhandledCriticalExtension(leafCertificate, handledCriticalExtensions: self.policy.verifyingCriticalExtensions))
diagnosticCallback?(
.leafCertificateHasUnhandledCriticalExtension(
leafCertificate,
handledCriticalExtensions: self.policy.verifyingCriticalExtensions
)
)
return .couldNotValidate([])
}
@@ -53,8 +62,12 @@ public struct Verifier<Policy: VerifierPolicy> {
return .validCertificate(unverifiedChain.certificates)
case .failsToMeetPolicy(reason: let reason):
diagnosticCallback?(.leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(leafCertificate, reason: reason))
policyFailures.append(VerificationResult.PolicyFailure(chain: unverifiedChain, policyFailureReason: reason))
diagnosticCallback?(
.leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(leafCertificate, reason: reason)
)
policyFailures.append(
VerificationResult.PolicyFailure(chain: unverifiedChain, policyFailureReason: reason)
)
}
}
@@ -66,11 +79,17 @@ public struct Verifier<Policy: VerifierPolicy> {
if var rootParents = rootCertificates[nextPartialCandidate.currentTip.issuer] {
// We then want to sort by suitability.
rootParents.sortBySuitabilityForIssuing(certificate: nextPartialCandidate.currentTip)
diagnosticCallback?(.foundCandidateIssuersOfPartialChainInRootStore(nextPartialCandidate, issuers: rootParents))
diagnosticCallback?(
.foundCandidateIssuersOfPartialChainInRootStore(nextPartialCandidate, issuers: rootParents)
)
// Each of these is now potentially a valid unverified chain.
for root in rootParents {
if self.shouldSkipAddingCertificate(partialChain: nextPartialCandidate, nextCertificate: root, diagnosticCallback: diagnosticCallback) {
if self.shouldSkipAddingCertificate(
partialChain: nextPartialCandidate,
nextCertificate: root,
diagnosticCallback: diagnosticCallback
) {
continue
}
@@ -84,7 +103,9 @@ public struct Verifier<Policy: VerifierPolicy> {
case .failsToMeetPolicy(reason: let reason):
diagnosticCallback?(.chainFailsToMeetPolicy(unverifiedChain, reason: reason))
policyFailures.append(VerificationResult.PolicyFailure(chain: unverifiedChain, policyFailureReason: reason))
policyFailures.append(
VerificationResult.PolicyFailure(chain: unverifiedChain, policyFailureReason: reason)
)
}
}
}
@@ -92,10 +113,19 @@ public struct Verifier<Policy: VerifierPolicy> {
if var intermediateParents = intermediates[nextPartialCandidate.currentTip.issuer] {
// We then want to sort by suitability.
intermediateParents.sortBySuitabilityForIssuing(certificate: nextPartialCandidate.currentTip)
diagnosticCallback?(.foundCandidateIssuersOfPartialChainInIntermediateStore(nextPartialCandidate, issuers: intermediateParents))
diagnosticCallback?(
.foundCandidateIssuersOfPartialChainInIntermediateStore(
nextPartialCandidate,
issuers: intermediateParents
)
)
for parent in intermediateParents {
if self.shouldSkipAddingCertificate(partialChain: nextPartialCandidate, nextCertificate: parent, diagnosticCallback: diagnosticCallback) {
if self.shouldSkipAddingCertificate(
partialChain: nextPartialCandidate,
nextCertificate: parent,
diagnosticCallback: diagnosticCallback
) {
continue
}
@@ -104,15 +134,25 @@ public struct Verifier<Policy: VerifierPolicy> {
}
}
}
diagnosticCallback?(.couldNotValidateLeafCertificate(leafCertificate))
return .couldNotValidate(policyFailures)
}
private func shouldSkipAddingCertificate(partialChain: CandidatePartialChain, nextCertificate: Certificate, diagnosticCallback: ((VerificationDiagnostic) -> Void)?) -> Bool {
private func shouldSkipAddingCertificate(
partialChain: CandidatePartialChain,
nextCertificate: Certificate,
diagnosticCallback: ((VerificationDiagnostic) -> Void)?
) -> Bool {
// We want to confirm that the certificate has no unhandled critical extensions. If it does, we can't build the chain.
if nextCertificate.hasUnhandledCriticalExtensions(handledExtensions: self.policy.verifyingCriticalExtensions) {
diagnosticCallback?(.issuerHasUnhandledCriticalExtension(issuer: nextCertificate, chain: partialChain, handledCriticalExtensions: self.policy.verifyingCriticalExtensions))
diagnosticCallback?(
.issuerHasUnhandledCriticalExtension(
issuer: nextCertificate,
chain: partialChain,
handledCriticalExtensions: self.policy.verifyingCriticalExtensions
)
)
return true
}
@@ -124,7 +164,9 @@ public struct Verifier<Policy: VerifierPolicy> {
}
// We check the signature here: if the signature isn't valid, don't try to apply policy.
guard nextCertificate.publicKey.isValidSignature(partialChain.currentTip.signature, for: partialChain.currentTip) else {
guard
nextCertificate.publicKey.isValidSignature(partialChain.currentTip.signature, for: partialChain.currentTip)
else {
diagnosticCallback?(.issuerHasNotSignedCertificate(nextCertificate, chain: partialChain))
return true
}
@@ -177,17 +219,11 @@ struct CandidatePartialChain: Hashable {
//
// This criteria is motivated by RFC 4158 § 5.2 (loop detection)
func match(_ left: Certificate, _ right: Certificate) -> Bool {
(
left.subject == right.subject &&
left.publicKey == right.publicKey &&
left.extensions.subjectAlternativeNameBytes == right.extensions.subjectAlternativeNameBytes
)
(left.subject == right.subject && left.publicKey == right.publicKey
&& left.extensions.subjectAlternativeNameBytes == right.extensions.subjectAlternativeNameBytes)
}
return (
self.chain.contains(where: { match($0, certificate) }) ||
match(self.currentTip, certificate)
)
return (self.chain.contains(where: { match($0, certificate) }) || match(self.currentTip, certificate))
}
func appending(_ newElement: Certificate) -> CandidatePartialChain {
@@ -64,114 +64,143 @@ struct AlgorithmIdentifier: DERImplicitlyTaggable, Hashable, Sendable {
// MARK: Algorithm Identifier Statics
extension AlgorithmIdentifier {
@usableFromInline
static let p256PublicKey = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp256r1))
static let p256PublicKey = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp256r1)
)
@usableFromInline
static let p384PublicKey = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp384r1))
static let p384PublicKey = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp384r1)
)
@usableFromInline
static let p521PublicKey = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp521r1))
static let p521PublicKey = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.idEcPublicKey,
parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp521r1)
)
@usableFromInline
static let ecdsaWithSHA256 = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.ecdsaWithSHA256,
parameters: nil)
static let ecdsaWithSHA256 = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.ecdsaWithSHA256,
parameters: nil
)
@usableFromInline
static let ecdsaWithSHA384 = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.ecdsaWithSHA384,
parameters: nil)
static let ecdsaWithSHA384 = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.ecdsaWithSHA384,
parameters: nil
)
@usableFromInline
static let ecdsaWithSHA512 = AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.ecdsaWithSHA512,
parameters: nil)
static let ecdsaWithSHA512 = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.ecdsaWithSHA512,
parameters: nil
)
// MARK: For the RSA signature types, explicit ASN.1 NULL is equivalent to a missing parameters field.
// We include both here, and the usage sites need to handle the equivalent.
@usableFromInline
static let sha1WithRSAEncryption = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha1WithRSAEncryption, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha1WithRSAEncryption,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha1WithRSAEncryptionUsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha1WithRSAEncryption, parameters: nil
algorithm: .AlgorithmIdentifier.sha1WithRSAEncryption,
parameters: nil
)
@usableFromInline
static let sha256WithRSAEncryption = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha256WithRSAEncryption, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha256WithRSAEncryption,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha256WithRSAEncryptionUsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha256WithRSAEncryption, parameters: nil
algorithm: .AlgorithmIdentifier.sha256WithRSAEncryption,
parameters: nil
)
@usableFromInline
static let sha384WithRSAEncryption = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha384WithRSAEncryption, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha384WithRSAEncryption,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha384WithRSAEncryptionUsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha384WithRSAEncryption, parameters: nil
algorithm: .AlgorithmIdentifier.sha384WithRSAEncryption,
parameters: nil
)
@usableFromInline
static let sha512WithRSAEncryption = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha512WithRSAEncryption, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha512WithRSAEncryption,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha512WithRSAEncryptionUsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha512WithRSAEncryption, parameters: nil
algorithm: .AlgorithmIdentifier.sha512WithRSAEncryption,
parameters: nil
)
@usableFromInline
static let rsaKey = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.rsaEncryption, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.rsaEncryption,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha1UsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha1, parameters: nil
algorithm: .AlgorithmIdentifier.sha1,
parameters: nil
)
@usableFromInline
static let sha1 = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha1, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha1,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha256UsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha256, parameters: nil
algorithm: .AlgorithmIdentifier.sha256,
parameters: nil
)
@usableFromInline
static let sha256 = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha256, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha256,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha384UsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha384, parameters: nil
algorithm: .AlgorithmIdentifier.sha384,
parameters: nil
)
@usableFromInline
static let sha384 = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha384, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha384,
parameters: try! ASN1Any(erasing: ASN1Null())
)
@usableFromInline
static let sha512UsingNil = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha512, parameters: nil
algorithm: .AlgorithmIdentifier.sha512,
parameters: nil
)
@usableFromInline
static let sha512 = AlgorithmIdentifier(
algorithm: .AlgorithmIdentifier.sha512, parameters: try! ASN1Any(erasing: ASN1Null())
algorithm: .AlgorithmIdentifier.sha512,
parameters: try! ASN1Any(erasing: ASN1Null())
)
}
@@ -178,14 +178,14 @@ extension ArraySlice where Element == UInt8 {
let realBytes = bigEndianRawInteger.drop(while: { $0 == 0 })
self = ArraySlice(realBytes)
}
@inlinable
init(normalisingToASN1IntegerForm bigEndianRawInteger: ArraySlice<UInt8>) {
self = bigEndianRawInteger.drop(while: { $0 == 0 })
}
@inlinable
init(normalisingToASN1IntegerForm bigEndianRawInteger: Array<UInt8>) {
init(normalisingToASN1IntegerForm bigEndianRawInteger: [UInt8]) {
self.init(normalisingToASN1IntegerForm: bigEndianRawInteger[...])
}
}
@@ -53,7 +53,6 @@ struct RSAPKCS1PublicKey: DERImplicitlyTaggable, Hashable, Sendable {
self.publicExponent = publicExponent
}
@inlinable
func serialize(into coder: inout DER.Serializer, withIdentifier identifier: ASN1Identifier) throws {
try coder.appendConstructedNode(identifier: identifier) { coder in
@@ -62,4 +61,3 @@ struct RSAPKCS1PublicKey: DERImplicitlyTaggable, Hashable, Sendable {
}
}
}
@@ -104,7 +104,12 @@ struct TBSCertificate: DERImplicitlyTaggable, Hashable, Sendable {
@inlinable
init(derEncoded rootNode: ASN1Node, withIdentifier identifier: ASN1Identifier) throws {
self = try DER.sequence(rootNode, identifier: identifier) { nodes in
let version = try DER.decodeDefaultExplicitlyTagged(&nodes, tagNumber: 0, tagClass: .contextSpecific, defaultValue: Int(0))
let version = try DER.decodeDefaultExplicitlyTagged(
&nodes,
tagNumber: 0,
tagClass: .contextSpecific,
defaultValue: Int(0)
)
guard (0...2).contains(version) else {
throw ASN1Error.invalidASN1Object(reason: "Invalid X.509 version \(version)")
}
+24 -7
View File
@@ -51,13 +51,12 @@ enum Time: DERParseable, DERSerializable, Hashable, Sendable {
// The rule is if the year is outside the range 1950-2049 inclusive, we should encode
// it as a generalized time. Otherwise, use a UTCTime.
if ((1950)..<(2050)).contains(components.year) {
let utcTime = try UTCTime(components)
return .utcTime(utcTime)
} else {
guard ((1950)..<(2050)).contains(components.year) else {
let generalizedTime = try GeneralizedTime(components)
return .generalTime(generalizedTime)
}
let utcTime = try UTCTime(components)
return .utcTime(utcTime)
}
}
@@ -86,12 +85,22 @@ extension Date {
@inlinable
init(_ time: GeneralizedTime) {
self = Date(fromUTCDate: (year: time.year, month: time.month, day: time.day, hours: time.hours, minutes: time.minutes, seconds: time.seconds))
self = Date(
fromUTCDate: (
year: time.year, month: time.month, day: time.day, hours: time.hours, minutes: time.minutes,
seconds: time.seconds
)
)
}
@inlinable
init(_ time: UTCTime) {
self = Date(fromUTCDate: (year: time.year, month: time.month, day: time.day, hours: time.hours, minutes: time.minutes, seconds: time.seconds))
self = Date(
fromUTCDate: (
year: time.year, month: time.month, day: time.day, hours: time.hours, minutes: time.minutes,
seconds: time.seconds
)
)
}
}
@@ -103,7 +112,15 @@ extension GeneralizedTime {
self = t
case .utcTime(let t):
// This can never throw, all valid UTCTimes are valid GeneralizedTimes
self = try! GeneralizedTime(year: t.year, month: t.month, day: t.day, hours: t.hours, minutes: t.minutes, seconds: t.seconds, fractionalSeconds: 0)
self = try! GeneralizedTime(
year: t.year,
month: t.month,
day: t.day,
hours: t.hours,
minutes: t.minutes,
seconds: t.seconds,
fractionalSeconds: 0
)
}
}
@@ -53,7 +53,7 @@ extension Int64 {
@inlinable
static var secondsFromEpochToYear2000: Int64 {
946684800
946_684_800
}
@inlinable
@@ -245,7 +245,10 @@ extension Int64 {
}
leaps += (97 * cycles) + (24 * centuries) - (isLeap ? 1 : 0)
return (seconds: ((year - 100) * .secondsPerYear) + (leaps * .secondsPerDay) + .secondsFromEpochToYear2000 + .secondsPerDay, isLeap: isLeap)
return (
seconds: ((year - 100) * .secondsPerYear) + (leaps * .secondsPerDay) + .secondsFromEpochToYear2000
+ .secondsPerDay, isLeap: isLeap
)
}
@inlinable
+36 -37
View File
@@ -21,7 +21,7 @@ public struct _TinyArray<Element> {
case one(Element)
case arbitrary([Element])
}
@usableFromInline
var storage: Storage
}
@@ -34,21 +34,21 @@ extension _TinyArray: Sendable where Element: Sendable {}
extension _TinyArray: RandomAccessCollection {
public typealias Element = Element
public typealias Index = Int
@inlinable
public subscript(position: Int) -> Element {
get {
self.storage[position]
}
}
@inlinable
public var startIndex: Int {
self.storage.startIndex
}
@inlinable
public var endIndex: Int {
self.storage.endIndex
@@ -60,38 +60,38 @@ extension _TinyArray {
public init(_ elements: some Sequence<Element>) {
self.storage = .init(elements)
}
@inlinable
public init(_ elements: some Sequence<Result<Element, some Error>>) throws {
self.storage = try .init(elements)
}
@inlinable
public init() {
self.storage = .init()
}
@inlinable
public mutating func append(_ newElement: Element) {
self.storage.append(newElement)
}
@inlinable
public mutating func append(contentsOf newElements: some Sequence<Element>){
public mutating func append(contentsOf newElements: some Sequence<Element>) {
self.storage.append(contentsOf: newElements)
}
@discardableResult
@inlinable
public mutating func remove(at index: Int) -> Element {
self.storage.remove(at: index)
}
@inlinable
public mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows {
try self.storage.removeAll(where: shouldBeRemoved)
}
@inlinable
public mutating func sort(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows {
try self.storage.sort(by: areInIncreasingOrder)
@@ -102,7 +102,7 @@ extension _TinyArray {
extension _TinyArray.Storage: Equatable where Element: Equatable {
@inlinable
static func ==(lhs: Self, rhs: Self) -> Bool {
static func == (lhs: Self, rhs: Self) -> Bool {
switch (lhs, rhs) {
case (.one(let lhs), .one(let rhs)):
return lhs == rhs
@@ -110,14 +110,14 @@ extension _TinyArray.Storage: Equatable where Element: Equatable {
// we don't use lhs.elementsEqual(rhs) so we can hit the fast path from Array
// if both arrays share the same underlying storage: https://github.com/apple/swift/blob/b42019005988b2d13398025883e285a81d323efa/stdlib/public/core/Array.swift#L1775
return lhs == rhs
case (.one(let element), .arbitrary(let array)),
(.arbitrary(let array), .one(let element)):
guard array.count == 1 else {
return false
}
return element == array[0]
}
}
}
@@ -148,12 +148,12 @@ extension _TinyArray.Storage: RandomAccessCollection {
}
}
}
@inlinable
var startIndex: Int {
0
}
@inlinable
var endIndex: Int {
switch self {
@@ -162,14 +162,14 @@ extension _TinyArray.Storage: RandomAccessCollection {
}
}
}
extension _TinyArray.Storage {
@inlinable
init(_ elements: some Sequence<Element>) {
self = .arbitrary([])
self.append(contentsOf: elements)
}
@inlinable
init(_ newElements: some Sequence<Result<Element, some Error>>) throws {
var iterator = newElements.makeIterator()
@@ -183,7 +183,7 @@ extension _TinyArray.Storage {
self = .one(firstElement)
return
}
var elements: [Element] = []
elements.reserveCapacity(newElements.underestimatedCount)
elements.append(firstElement)
@@ -193,19 +193,19 @@ extension _TinyArray.Storage {
}
self = .arbitrary(elements)
}
@inlinable
init() {
self = .arbitrary([])
}
@inlinable
mutating func append(_ newElement: Element) {
self.append(contentsOf: CollectionOfOne(newElement))
}
@inlinable
mutating func append(contentsOf newElements: some Sequence<Element>){
mutating func append(contentsOf newElements: some Sequence<Element>) {
switch self {
case .one(let firstElement):
var iterator = newElements.makeIterator()
@@ -219,7 +219,7 @@ extension _TinyArray.Storage {
elements.append(secondElement)
elements.appendRemainingElements(from: &iterator)
self = .arbitrary(elements)
case .arbitrary(var elements):
if elements.isEmpty {
// if `self` is currently empty and `newElements` just contains a single
@@ -240,15 +240,15 @@ extension _TinyArray.Storage {
elements.append(secondElement)
elements.appendRemainingElements(from: &iterator)
self = .arbitrary(elements)
} else {
elements.append(contentsOf: newElements)
self = .arbitrary(elements)
}
}
}
@discardableResult
@inlinable
mutating func remove(at index: Int) -> Element {
@@ -259,16 +259,16 @@ extension _TinyArray.Storage {
}
self = .arbitrary([])
return oldElement
case .arbitrary(var elements):
defer {
self = .arbitrary(elements)
}
return elements.remove(at: index)
}
}
@inlinable
mutating func removeAll(where shouldBeRemoved: (Element) throws -> Bool) rethrows {
switch self {
@@ -276,16 +276,16 @@ extension _TinyArray.Storage {
if try shouldBeRemoved(oldElement) {
self = .arbitrary([])
}
case .arbitrary(var elements):
defer {
self = .arbitrary(elements)
}
return try elements.removeAll(where: shouldBeRemoved)
}
}
@inlinable
mutating func sort(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows {
switch self {
@@ -296,13 +296,12 @@ extension _TinyArray.Storage {
defer {
self = .arbitrary(elements)
}
try elements.sort(by: areInIncreasingOrder)
}
}
}
extension Array {
@inlinable
mutating func appendRemainingElements(from iterator: inout some IteratorProtocol<Element>) {
@@ -19,7 +19,7 @@ final class TinyArrayTests: XCTestCase {
private func _assertEqual(
_ expected: @autoclosure () -> some Sequence<Int>,
initial: @autoclosure () -> _TinyArray<Int>,
_ mutate: (inout _TinyArray<Int>) -> (),
_ mutate: (inout _TinyArray<Int>) -> Void,
file: StaticString = #filePath,
line: UInt = #line
) {
@@ -32,13 +32,19 @@ final class TinyArrayTests: XCTestCase {
acutalHasher.combine(actual)
var expectedHasher = Hasher()
expectedHasher.combine(expected)
XCTAssertEqual(acutalHasher.finalize(), expectedHasher.finalize(), "\(actual) does not have the same hash as \(expected)", file: file, line: line)
XCTAssertEqual(
acutalHasher.finalize(),
expectedHasher.finalize(),
"\(actual) does not have the same hash as \(expected)",
file: file,
line: line
)
}
private func assertEqual(
_ expected: [Int],
initial: @autoclosure () -> _TinyArray<Int> = _TinyArray(),
_ mutate: (inout _TinyArray<Int>) -> (),
_ mutate: (inout _TinyArray<Int>) -> Void,
file: StaticString = #filePath,
line: UInt = #line
) {
@@ -46,21 +52,21 @@ final class TinyArrayTests: XCTestCase {
// get a sequence that is not an `Array` to hit the slow path as well
_assertEqual(expected.lazy.map { $0 }, initial: initial(), mutate, file: file, line: line)
}
func testInit() {
XCTAssertEqual(Array(_TinyArray([Int]())), [])
XCTAssertEqual(Array(_TinyArray<Int>()), [])
XCTAssertEqual(_TinyArray<Int>(), _TinyArray<Int>([]))
XCTAssertEqual(Array(_TinyArray<Int>(CollectionOfOne(1))), [1])
XCTAssertEqual(Array(_TinyArray<Int>([1])), [1])
XCTAssertEqual(Array(_TinyArray<Int>([1, 2])), [1, 2])
XCTAssertEqual(Array(_TinyArray<Int>([1, 2, 3])), [1, 2, 3])
XCTAssertEqual(Array(_TinyArray<Int>([1, 2, 3, 4])), [1, 2, 3, 4])
XCTAssertEqual(Array(_TinyArray<Int>([1, 2, 3, 4, 5])), [1, 2, 3, 4, 5])
}
func testAppend() {
assertEqual([1]) { array in
array.append(1)
@@ -81,7 +87,7 @@ final class TinyArrayTests: XCTestCase {
array.append(4)
}
}
func testAppendContentsOf() {
assertEqual([]) { array in
array.append(contentsOf: [])
@@ -113,7 +119,7 @@ final class TinyArrayTests: XCTestCase {
assertEqual([1, 2, 3, 4, 5]) { array in
array.append(contentsOf: [1, 2, 3, 4, 5])
}
assertEqual([1, 2]) { array in
array.append(contentsOf: [1])
array.append(contentsOf: [2])
@@ -155,7 +161,7 @@ final class TinyArrayTests: XCTestCase {
array.append(contentsOf: [2, 3, 4, 5])
}
}
func testRemoveAt() {
assertEqual([], initial: [1]) { array in
array.remove(at: 0)
@@ -206,7 +212,7 @@ final class TinyArrayTests: XCTestCase {
array.remove(at: 0)
}
}
func testRemoveAll() {
assertEqual([], initial: []) { array in
array.removeAll(where: { _ in true })
@@ -226,7 +232,7 @@ final class TinyArrayTests: XCTestCase {
assertEqual([], initial: [1, 2, 3, 4, 5]) { array in
array.removeAll(where: { _ in true })
}
assertEqual([1], initial: [1]) { array in
array.removeAll(where: { _ in false })
}
@@ -242,7 +248,7 @@ final class TinyArrayTests: XCTestCase {
assertEqual([1, 2, 3, 4, 5], initial: [1, 2, 3, 4, 5]) { array in
array.removeAll(where: { _ in false })
}
assertEqual([], initial: [1]) { array in
array.removeAll(where: { Set([1]).contains($0) })
}
@@ -256,7 +262,7 @@ final class TinyArrayTests: XCTestCase {
array.removeAll(where: { Set([1, 3]).contains($0) })
}
}
func testSort() {
assertEqual([], initial: []) { array in
array.sort(by: { lhs, rhs in
@@ -277,31 +283,43 @@ final class TinyArrayTests: XCTestCase {
array.sort(by: >)
}
}
func testThrowingInitFromResult() {
XCTAssertEqual(Array(try _TinyArray<Int>(CollectionOfOne(Result<_, Error>.success(1)))), [1])
XCTAssertEqual(Array(try _TinyArray([Result<_, Error>.success(1)])), [1])
XCTAssertEqual(Array(try _TinyArray([Result<_, Error>.success(1), .success(2)])), [1, 2])
XCTAssertEqual(Array(try _TinyArray([Result<_, Error>.success(1), .success(2), .success(3)])), [1, 2, 3])
XCTAssertEqual(Array(try _TinyArray([Result<_, Error>.success(1), .success(2), .success(3), .success(4)])), [1, 2, 3, 4])
XCTAssertEqual(Array(try _TinyArray([Result<_, Error>.success(1), .success(2), .success(3), .success(4), .success(5)])), [1, 2, 3, 4, 5])
XCTAssertEqual(
Array(try _TinyArray([Result<_, Error>.success(1), .success(2), .success(3), .success(4)])),
[1, 2, 3, 4]
)
XCTAssertEqual(
Array(try _TinyArray([Result<_, Error>.success(1), .success(2), .success(3), .success(4), .success(5)])),
[1, 2, 3, 4, 5]
)
struct MyError: Error {}
XCTAssertThrowsError(Array(try _TinyArray<Int>([Result.failure(MyError())])))
XCTAssertThrowsError(Array(try _TinyArray<Int>([Result.failure(MyError()), Result.failure(MyError())])))
XCTAssertThrowsError(Array(try _TinyArray<Int>([.success(1), Result.failure(MyError())])))
XCTAssertThrowsError(Array(try _TinyArray<Int>([.success(1), Result.failure(MyError()), .success(2)])))
XCTAssertThrowsError(Array(try _TinyArray<Int>([.success(1), .success(2), Result.failure(MyError())])))
XCTAssertThrowsError(Array(try _TinyArray<Int>([.success(1), .success(2), Result.failure(MyError()), .success(4)])))
XCTAssertThrowsError(Array(try _TinyArray<Int>([.success(1), .success(2), .success(3), Result.failure(MyError())])))
XCTAssertThrowsError(Array(try _TinyArray<Int>([.success(1), .success(2), .success(3), .success(4), Result.failure(MyError())])))
XCTAssertThrowsError(
Array(try _TinyArray<Int>([.success(1), .success(2), Result.failure(MyError()), .success(4)]))
)
XCTAssertThrowsError(
Array(try _TinyArray<Int>([.success(1), .success(2), .success(3), Result.failure(MyError())]))
)
XCTAssertThrowsError(
Array(try _TinyArray<Int>([.success(1), .success(2), .success(3), .success(4), Result.failure(MyError())]))
)
}
}
extension _TinyArray: ExpressibleByArrayLiteral {
public typealias ArrayLiteralElement = Element
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
+360 -190
View File
@@ -16,7 +16,7 @@ import Foundation
import XCTest
import Crypto
import SwiftASN1
@testable @_spi(CMS) import X509
@testable@_spi(CMS) import X509
final class CMSTests: XCTestCase {
static let rootCertKey = Certificate.PrivateKey(P256.Signing.PrivateKey())
@@ -128,7 +128,6 @@ final class CMSTests: XCTestCase {
issuerPrivateKey: intermediateKey
)
@PolicyBuilder static var defaultPolicies: some VerifierPolicy {
RFC5280Policy(validationTime: Date())
}
@@ -139,189 +138,251 @@ final class CMSTests: XCTestCase {
let parsed = try ASN1Object(derEncoded: serializer.serializedBytes)
XCTAssertEqual(parsed, value)
}
func testIssuerAndSerialNumber() throws {
try assertRoundTrips(CMSIssuerAndSerialNumber(issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
}, serialNumber: .init(bytes: [10, 20, 30, 40])))
try assertRoundTrips(
CMSIssuerAndSerialNumber(
issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
serialNumber: .init(bytes: [10, 20, 30, 40])
)
)
}
func testSignerIdentifier() throws {
try assertRoundTrips(
CMSSignerIdentifier.issuerAndSerialNumber(.init(issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
}, serialNumber: .init(bytes: [20, 30, 40, 50])))
CMSSignerIdentifier.issuerAndSerialNumber(
.init(
issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
serialNumber: .init(bytes: [20, 30, 40, 50])
)
)
)
try assertRoundTrips(
CMSSignerIdentifier.subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40]))
)
}
func testCMSSignerInfo() throws {
try assertRoundTrips(CMSSignerInfo(
version: .v1,
signerIdentifier: .issuerAndSerialNumber(.init(
issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
serialNumber: .init(bytes: [20, 30, 40, 50])
)),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
))
try assertRoundTrips(CMSSignerInfo(
version: .v3,
signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
))
XCTAssertThrowsError(try assertRoundTrips(CMSSignerInfo(
version: .v3,
signerIdentifier: .issuerAndSerialNumber(.init(
issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
serialNumber: .init(bytes: [20, 30, 40, 50])
)),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
)), "unexpected signerIdentifier for version should throw")
XCTAssertThrowsError(try assertRoundTrips(CMSSignerInfo(
version: .v1,
signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
)), "unexpected signerIdentifier for version should throw")
}
func testEncapsulatedContentInfo() throws {
try assertRoundTrips(CMSEncapsulatedContentInfo(
eContentType: [1, 2, 3, 4],
eContent: .init(contentBytes: [5, 6, 7, 8])
))
try assertRoundTrips(CMSEncapsulatedContentInfo(
eContentType: [1, 2, 3, 4],
eContent: nil
))
}
func testSignedData() throws {
try assertRoundTrips(CMSSignedData(
version: .v1,
digestAlgorithms: [],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: nil,
signerInfos: []
))
try assertRoundTrips(CMSSignedData(
version: .v1,
digestAlgorithms: [.sha256WithRSAEncryptionUsingNil],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [],
signerInfos: []
))
try assertRoundTrips(CMSSignedData(
version: .v1,
digestAlgorithms: [.sha256WithRSAEncryptionUsingNil],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [],
signerInfos: [
try assertRoundTrips(
CMSSignerInfo(
version: .v1,
signerIdentifier: .issuerAndSerialNumber(
.init(
issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
serialNumber: .init(bytes: [20, 30, 40, 50])
)
),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
)
)
try assertRoundTrips(
CMSSignerInfo(
version: .v3,
signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
)
)
XCTAssertThrowsError(
try assertRoundTrips(
CMSSignerInfo(
version: .v3,
signerIdentifier: .issuerAndSerialNumber(
.init(
issuer: .init {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
serialNumber: .init(bytes: [20, 30, 40, 50])
)
),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
)
),
"unexpected signerIdentifier for version should throw"
)
XCTAssertThrowsError(
try assertRoundTrips(
CMSSignerInfo(
version: .v1,
signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
)
]
))
let privateKey = P384.Signing.PrivateKey()
try assertRoundTrips(CMSSignedData(
version: .v1,
digestAlgorithms: [
.sha256WithRSAEncryptionUsingNil
],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [Certificate(
version: .v3,
serialNumber: .init(bytes: [1, 2, 3, 4]),
publicKey: .init(privateKey.publicKey),
notValidBefore: Date(),
notValidAfter: Date(),
issuer: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
subject: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("apple.com")
},
signatureAlgorithm: .ecdsaWithSHA384,
extensions: .init(),
issuerPrivateKey: .init(privateKey)
)],
signerInfos: []
))
),
"unexpected signerIdentifier for version should throw"
)
}
func testEncapsulatedContentInfo() throws {
try assertRoundTrips(
CMSEncapsulatedContentInfo(
eContentType: [1, 2, 3, 4],
eContent: .init(contentBytes: [5, 6, 7, 8])
)
)
try assertRoundTrips(
CMSEncapsulatedContentInfo(
eContentType: [1, 2, 3, 4],
eContent: nil
)
)
}
func testSignedData() throws {
try assertRoundTrips(
CMSSignedData(
version: .v1,
digestAlgorithms: [],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: nil,
signerInfos: []
)
)
try assertRoundTrips(
CMSSignedData(
version: .v1,
digestAlgorithms: [.sha256WithRSAEncryptionUsingNil],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [],
signerInfos: []
)
)
try assertRoundTrips(
CMSSignedData(
version: .v1,
digestAlgorithms: [.sha256WithRSAEncryptionUsingNil],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [],
signerInfos: [
CMSSignerInfo(
version: .v3,
signerIdentifier: .subjectKeyIdentifier(.init(keyIdentifier: [10, 20, 30, 40])),
digestAlgorithm: .sha256WithRSAEncryptionUsingNil,
signatureAlgorithm: .ecdsaWithSHA256,
signature: .init(contentBytes: [100, 110, 120, 130, 140])
)
]
)
)
let privateKey = P384.Signing.PrivateKey()
try assertRoundTrips(
CMSSignedData(
version: .v1,
digestAlgorithms: [
.sha256WithRSAEncryptionUsingNil
],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [
Certificate(
version: .v3,
serialNumber: .init(bytes: [1, 2, 3, 4]),
publicKey: .init(privateKey.publicKey),
notValidBefore: Date(),
notValidAfter: Date(),
issuer: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
subject: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("apple.com")
},
signatureAlgorithm: .ecdsaWithSHA384,
extensions: .init(),
issuerPrivateKey: .init(privateKey)
)
],
signerInfos: []
)
)
}
func testContentInfo() throws {
let privateKey = P384.Signing.PrivateKey()
try assertRoundTrips(CMSContentInfo(CMSSignedData(
version: .v1,
digestAlgorithms: [
.sha256WithRSAEncryptionUsingNil
],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [Certificate(
version: .v3,
serialNumber: .init(bytes: [1, 2, 3, 4]),
publicKey: .init(privateKey.publicKey),
notValidBefore: Date(),
notValidAfter: Date(),
issuer: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
subject: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("apple.com")
},
signatureAlgorithm: .ecdsaWithSHA384,
extensions: .init(),
issuerPrivateKey: .init(privateKey)
)],
signerInfos: []
)))
try assertRoundTrips(
CMSContentInfo(
CMSSignedData(
version: .v1,
digestAlgorithms: [
.sha256WithRSAEncryptionUsingNil
],
encapContentInfo: .init(eContentType: [1, 2, 3, 4]),
certificates: [
Certificate(
version: .v3,
serialNumber: .init(bytes: [1, 2, 3, 4]),
publicKey: .init(privateKey.publicKey),
notValidBefore: Date(),
notValidAfter: Date(),
issuer: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("Apple Public EV Server ECC CA 1 - G1")
},
subject: DistinguishedName {
CountryName("US")
OrganizationName("Apple Inc.")
CommonName("apple.com")
},
signatureAlgorithm: .ecdsaWithSHA384,
extensions: .init(),
issuerPrivateKey: .init(privateKey)
)
],
signerInfos: []
)
)
)
}
func testSimpleSigningVerifying() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let signature = try CMS.sign(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
let isValidSignature = await CMS.isValidSignature(dataBytes: data, signatureBytes: signature, trustRoots: CertificateStore([Self.rootCert])) { Self.defaultPolicies }
let signature = try CMS.sign(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
let isValidSignature = await CMS.isValidSignature(
dataBytes: data,
signatureBytes: signature,
trustRoots: CertificateStore([Self.rootCert])
) { Self.defaultPolicies }
XCTAssertValidSignature(isValidSignature)
}
func testParsingSimpleSignature() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let signatureBytes = try CMS.sign(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
let signatureBytes = try CMS.sign(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
let signature = try CMSSignature(derEncoded: signatureBytes)
XCTAssertEqual(try signature.signers, [CMSSignature.Signer(certificate: Self.leaf1Cert)])
@@ -350,7 +411,12 @@ final class CMSTests: XCTestCase {
func testToleratesAdditionalSignerInfos() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Add a second, identical, signer info.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -358,7 +424,10 @@ final class CMSTests: XCTestCase {
cmsData.content = try ASN1Any(erasing: signedData)
let signature = try CMSSignature(derEncoded: cmsData.encodedBytes)
XCTAssertEqual(try signature.signers, [CMSSignature.Signer(certificate: Self.leaf1Cert), CMSSignature.Signer(certificate: Self.leaf1Cert)])
XCTAssertEqual(
try signature.signers,
[CMSSignature.Signer(certificate: Self.leaf1Cert), CMSSignature.Signer(certificate: Self.leaf1Cert)]
)
XCTAssertEqual(signature.certificates, [Self.leaf1Cert])
XCTAssertEqual(try cmsData.encodedBytes, try signature.encodedBytes)
@@ -366,7 +435,12 @@ final class CMSTests: XCTestCase {
func testRequireCMSV1SignatureOnCMSSignatureType() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Change the version number to v3 in both places.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -379,23 +453,39 @@ final class CMSTests: XCTestCase {
func testRejectsSignatureWithoutRoot() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let signature = try CMS.sign(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
let isValidSignature = await CMS.isValidSignature(dataBytes: data, signatureBytes: signature, trustRoots: CertificateStore([Self.secondRootCert])) { }
let signature = try CMS.sign(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
let isValidSignature = await CMS.isValidSignature(
dataBytes: data,
signatureBytes: signature,
trustRoots: CertificateStore([Self.secondRootCert])
) {}
XCTAssertUnableToValidateSigner(isValidSignature)
}
func testPoliciesAreApplied() async throws {
final class RejectAllPolicy: VerifierPolicy {
let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []
func chainMeetsPolicyRequirements(chain: X509.UnverifiedCertificateChain) async -> X509.PolicyEvaluationResult {
func chainMeetsPolicyRequirements(
chain: X509.UnverifiedCertificateChain
) async -> X509.PolicyEvaluationResult {
return .failsToMeetPolicy(reason: "all chains are forbidden")
}
}
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let signature = try CMS.sign(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
let signature = try CMS.sign(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
let isValidSignature = await CMS.isValidSignature(
dataBytes: data,
signatureBytes: signature,
@@ -408,7 +498,12 @@ final class CMSTests: XCTestCase {
func testRequireCMSSignedData() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// This is a meaningless OID to use here, I just want to use something I know we don't support.
cmsData.contentType = .sha256NoSign
@@ -416,13 +511,18 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testRequireCMSV1Signature() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Change the version number to v3 in both places.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -434,13 +534,18 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testRequireCMSV1SignatureEvenOnTheSignerInfo() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Change the version number to v3, but only in the signer info.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -451,31 +556,43 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testRequireCMSV1SignatureEvenWhenV3IsCorrectlyAttestedOnSignerInfo() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Change the version number to v3, but only in the signer info.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
signedData.signerInfos[0].version = .v3
signedData.signerInfos[0].signerIdentifier = try .subjectKeyIdentifier(Self.leaf1Cert.extensions.subjectKeyIdentifier!)
signedData.signerInfos[0].signerIdentifier = try .subjectKeyIdentifier(
Self.leaf1Cert.extensions.subjectKeyIdentifier!
)
cmsData.content = try ASN1Any(erasing: signedData)
let isValidSignature = try await CMS.isValidSignature(
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testForbidsAdditionalSignerInfos() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Add a second, identical, signer info. There's nothing invalid about this!
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -486,13 +603,18 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testRequireCMSDataTypeInEncapContent() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// This is a weird OID to use here, we just want to prove we reject it.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -503,13 +625,18 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testRequireDetachedSignature() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Let's add the signed data in here!
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -520,13 +647,18 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testDigestAlgorithmsNotPresentInTheMainSetAreRejected() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// Let's add a few algorithms to the digest algorithms, none of which are what we actually used.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
@@ -537,13 +669,18 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testDigestAlgorithmAndSigningAlgorithmMismatch() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// This test confirms that if the data was hashed with a digest function other than the one implied by the
// signature algorithm, we'll reject it.
@@ -556,40 +693,61 @@ final class CMSTests: XCTestCase {
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testInvalidSignatureIsRejected() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var cmsData = try CMS.generateSignedTestData(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf1Cert, privateKey: Self.leaf1Key)
var cmsData = try CMS.generateSignedTestData(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf1Cert,
privateKey: Self.leaf1Key
)
// This test validates that invalid signatures cause validation failures.
// Specifically, we'll produce a valid signature, with the wrong key.
var signedData = try CMSSignedData(asn1Any: cmsData.content)
signedData.signerInfos[0].signature = try ASN1OctetString(Self.rootCertKey.sign(bytes: data, signatureAlgorithm: .ecdsaWithSHA256))
signedData.signerInfos[0].signature = try ASN1OctetString(
Self.rootCertKey.sign(bytes: data, signatureAlgorithm: .ecdsaWithSHA256)
)
cmsData.content = try ASN1Any(erasing: signedData)
let isValidSignature = try await CMS.isValidSignature(
dataBytes: data,
signatureBytes: cmsData.encodedBytes,
trustRoots: CertificateStore([Self.rootCert])
) { }
) {}
XCTAssertInvalidCMSBlock(isValidSignature)
}
func testNotInsertingIntermediatesLeadsToCertValidationFailures() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let signature = try CMS.sign(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf2Cert, privateKey: Self.leaf2Key)
let isValidSignature = await CMS.isValidSignature(dataBytes: data, signatureBytes: signature, trustRoots: CertificateStore([Self.rootCert])) { }
let signature = try CMS.sign(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf2Cert,
privateKey: Self.leaf2Key
)
let isValidSignature = await CMS.isValidSignature(
dataBytes: data,
signatureBytes: signature,
trustRoots: CertificateStore([Self.rootCert])
) {}
XCTAssertUnableToValidateSigner(isValidSignature)
}
func testCanProvideIntermediatesDuringVerification() async throws {
let data: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let signature = try CMS.sign(data, signatureAlgorithm: .ecdsaWithSHA256, certificate: Self.leaf2Cert, privateKey: Self.leaf2Key)
let signature = try CMS.sign(
data,
signatureAlgorithm: .ecdsaWithSHA256,
certificate: Self.leaf2Cert,
privateKey: Self.leaf2Key
)
let isValidSignature = await CMS.isValidSignature(
dataBytes: data,
signatureBytes: signature,
@@ -653,21 +811,33 @@ extension DERSerializable {
}
}
fileprivate func XCTAssertValidSignature(_ result: CMS.SignatureVerificationResult, file: StaticString = #file, line: UInt = #line) {
private func XCTAssertValidSignature(
_ result: CMS.SignatureVerificationResult,
file: StaticString = #file,
line: UInt = #line
) {
guard case .success = result else {
XCTFail("Expected valid signature, got \(result)", file: file, line: line)
return
}
}
fileprivate func XCTAssertInvalidCMSBlock(_ result: CMS.SignatureVerificationResult, file: StaticString = #file, line: UInt = #line) {
private func XCTAssertInvalidCMSBlock(
_ result: CMS.SignatureVerificationResult,
file: StaticString = #file,
line: UInt = #line
) {
guard case .failure(.invalidCMSBlock) = result else {
XCTFail("Expected invalid CMS Block, got \(result)", file: file, line: line)
return
}
}
fileprivate func XCTAssertUnableToValidateSigner(_ result: CMS.SignatureVerificationResult, file: StaticString = #file, line: UInt = #line) {
private func XCTAssertUnableToValidateSigner(
_ result: CMS.SignatureVerificationResult,
file: StaticString = #file,
line: UInt = #line
) {
guard case .failure(.unableToValidateSigner) = result else {
XCTFail("Expected unable to validate signer, got \(result)", file: file, line: line)
return
+105 -24
View File
@@ -47,7 +47,11 @@ final class CSRTests: XCTestCase {
}
func testRSASHA1CSR() throws {
let url = Bundle.module.url(forResource: "rsa_sha1", withExtension: "der", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "rsa_sha1",
withExtension: "der",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try Data(contentsOf: url)
let csr = try CertificateSigningRequest(derEncoded: Array(bytes))
@@ -59,7 +63,7 @@ final class CSRTests: XCTestCase {
.init(type: .NameAttributes.stateOrProvinceName, printableString: "Texas"),
.init(type: .NameAttributes.localityName, printableString: "Austin"),
.init(type: .NameAttributes.organizationName, printableString: "PyCA"),
.init(type: .NameAttributes.commonName, printableString: "cryptography.io")
.init(type: .NameAttributes.commonName, printableString: "cryptography.io"),
])
)
XCTAssertNotNil(_RSA.Signing.PublicKey(csr.publicKey))
@@ -73,7 +77,11 @@ final class CSRTests: XCTestCase {
}
func testRSASHA1CSRPEM() throws {
let url = Bundle.module.url(forResource: "rsa_sha1", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "rsa_sha1",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let pemDocument = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: pemDocument)
@@ -85,7 +93,7 @@ final class CSRTests: XCTestCase {
.init(type: .NameAttributes.stateOrProvinceName, printableString: "Texas"),
.init(type: .NameAttributes.localityName, printableString: "Austin"),
.init(type: .NameAttributes.organizationName, printableString: "PyCA"),
.init(type: .NameAttributes.commonName, printableString: "cryptography.io")
.init(type: .NameAttributes.commonName, printableString: "cryptography.io"),
])
)
XCTAssertNotNil(_RSA.Signing.PublicKey(csr.publicKey))
@@ -101,26 +109,42 @@ final class CSRTests: XCTestCase {
}
func testUnsupportedSignatureAlgorithmDER() throws {
let url = Bundle.module.url(forResource: "rsa_md4", withExtension: "der", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "rsa_md4",
withExtension: "der",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try Data(contentsOf: url)
XCTAssertThrowsError(try CertificateSigningRequest(derEncoded: Array(bytes)))
}
func testUnsupportedSignatureAlgorithmPEM() throws {
let url = Bundle.module.url(forResource: "rsa_md4", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "rsa_md4",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
XCTAssertThrowsError(try CertificateSigningRequest(pemEncoded: bytes))
}
func testBadVersion() throws {
let url = Bundle.module.url(forResource: "bad-version", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "bad-version",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
XCTAssertEqual(csr.version, .init(rawValue: 1))
}
func testDuplicateExtension() throws {
let url = Bundle.module.url(forResource: "two_basic_constraints", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "two_basic_constraints",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
#if canImport(Darwin)
XCTExpectFailure("Currently don't police extension uniqueness")
@@ -133,7 +157,11 @@ final class CSRTests: XCTestCase {
}
func testUnknownCriticalExtension() throws {
let url = Bundle.module.url(forResource: "unsupported_extension_critical", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "unsupported_extension_critical",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -151,7 +179,11 @@ final class CSRTests: XCTestCase {
}
func testUnknownExtension() throws {
let url = Bundle.module.url(forResource: "unsupported_extension", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "unsupported_extension",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -169,7 +201,11 @@ final class CSRTests: XCTestCase {
}
func testNoExtensions() throws {
let url = Bundle.module.url(forResource: "challenge-unstructured", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "challenge-unstructured",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -177,7 +213,11 @@ final class CSRTests: XCTestCase {
}
func testBasicConstraints() throws {
let url = Bundle.module.url(forResource: "basic_constraints", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "basic_constraints",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -197,7 +237,11 @@ final class CSRTests: XCTestCase {
}
func testSubjectAlternativeName() throws {
let url = Bundle.module.url(forResource: "san_rsa_sha1", withExtension: "der", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "san_rsa_sha1",
withExtension: "der",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try Data(contentsOf: url)
let csr = try CertificateSigningRequest(derEncoded: Array(bytes))
@@ -218,7 +262,11 @@ final class CSRTests: XCTestCase {
}
func testSubjectAlternativeNamePEM() throws {
let url = Bundle.module.url(forResource: "san_rsa_sha1", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "san_rsa_sha1",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -239,7 +287,11 @@ final class CSRTests: XCTestCase {
}
func testFreeIPABadCritical() throws {
let url = Bundle.module.url(forResource: "freeipa-bad-critical", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "freeipa-bad-critical",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -247,7 +299,11 @@ final class CSRTests: XCTestCase {
}
func testInvalidSignature() throws {
let url = Bundle.module.url(forResource: "invalid_signature", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "invalid_signature",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -255,7 +311,11 @@ final class CSRTests: XCTestCase {
}
func testRSASHA256Signature() throws {
let url = Bundle.module.url(forResource: "rsa_sha256", withExtension: "der", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "rsa_sha256",
withExtension: "der",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try Data(contentsOf: url)
let csr = try CertificateSigningRequest(derEncoded: Array(bytes))
@@ -263,7 +323,11 @@ final class CSRTests: XCTestCase {
}
func testRSASHA256SignaturePEM() throws {
let url = Bundle.module.url(forResource: "rsa_sha256", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "rsa_sha256",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: bytes)
@@ -271,7 +335,11 @@ final class CSRTests: XCTestCase {
}
func testECDSACSR() throws {
let url = Bundle.module.url(forResource: "ec_sha256", withExtension: "der", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "ec_sha256",
withExtension: "der",
subdirectory: "CSR Vectors/cryptography"
)!
let bytes = try Data(contentsOf: url)
let csr = try CertificateSigningRequest(derEncoded: Array(bytes))
@@ -297,7 +365,11 @@ final class CSRTests: XCTestCase {
}
func testECDSACSRPEM() throws {
let url = Bundle.module.url(forResource: "ec_sha256", withExtension: "pem", subdirectory: "CSR Vectors/cryptography")!
let url = Bundle.module.url(
forResource: "ec_sha256",
withExtension: "pem",
subdirectory: "CSR Vectors/cryptography"
)!
let pemDocument = try String(decoding: Data(contentsOf: url), as: UTF8.self)
let csr = try CertificateSigningRequest(pemEncoded: pemDocument)
@@ -345,12 +417,18 @@ final class CSRTests: XCTestCase {
func testCanReplaceElementInAttributes() throws {
var attributes = CertificateSigningRequest.Attributes([
CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 1)]),
CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 2)])
CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4, 5], values: [try ASN1Any(erasing: 2)]),
])
attributes[oid: [1, 2, 3, 4]] = CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 3)])
attributes[oid: [1, 2, 3, 4]] = CertificateSigningRequest.Attribute(
oid: [1, 2, 3, 4],
values: [try ASN1Any(erasing: 3)]
)
attributes[oid: [1, 2, 3, 4, 5]] = nil
attributes[oid: [4, 3, 2, 1]] = CertificateSigningRequest.Attribute(oid: [4, 3, 2, 1], values: [try ASN1Any(erasing: 4)])
attributes[oid: [4, 3, 2, 1]] = CertificateSigningRequest.Attribute(
oid: [4, 3, 2, 1],
values: [try ASN1Any(erasing: 4)]
)
XCTAssertEqual(attributes.count, 2)
XCTAssertEqual(
@@ -429,7 +507,10 @@ final class CSRTests: XCTestCase {
XCTAssertNotEqual(
CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5)]),
CertificateSigningRequest.Attribute(oid: [1, 2, 3, 4], values: [try ASN1Any(erasing: 5), try ASN1Any(erasing: 10)])
CertificateSigningRequest.Attribute(
oid: [1, 2, 3, 4],
values: [try ASN1Any(erasing: 5), try ASN1Any(erasing: 10)]
)
)
}
+301 -251
View File
@@ -179,7 +179,10 @@ final class CertificateDERTests: XCTestCase {
)
XCTAssertEqual(cert.version, .v3)
XCTAssertEqual(cert.serialNumber.bytes, [0x0c, 0xab, 0xaa, 0xd1, 0xce, 0xc4, 0xe9, 0x7c, 0xc2, 0x66, 0x58, 0x81, 0xd0, 0x21, 0x38, 0xf7])
XCTAssertEqual(
cert.serialNumber.bytes,
[0x0c, 0xab, 0xaa, 0xd1, 0xce, 0xc4, 0xe9, 0x7c, 0xc2, 0x66, 0x58, 0x81, 0xd0, 0x21, 0x38, 0xf7]
)
XCTAssertEqual(cert.publicKey, Certificate.PublicKey(expectedPublicKey))
let expectedNotBefore = Date(timeIntervalSince1970: 1588163692.0)
@@ -190,29 +193,53 @@ final class CertificateDERTests: XCTestCase {
let expectedIssuer = try DistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, printableString: "US"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, printableString: "DigiCert Inc"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, printableString: "www.digicert.com"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, printableString: "DigiCert Global Root G3"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationName,
printableString: "DigiCert Inc"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationalUnitName,
printableString: "www.digicert.com"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.commonName,
printableString: "DigiCert Global Root G3"
),
])
let expectedSubject = try DistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, printableString: "US"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, printableString: "Apple Inc."),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, printableString: "Apple Public EV Server ECC CA 1 - G1"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationName,
printableString: "Apple Inc."
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.commonName,
printableString: "Apple Public EV Server ECC CA 1 - G1"
),
])
XCTAssertEqual(cert.issuer, expectedIssuer)
XCTAssertEqual(cert.subject, expectedSubject)
XCTAssertEqual(cert.extensions.count, 8)
XCTAssertEqual(try cert.extensions.authorityInformationAccess, .init([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))]))
XCTAssertEqual(
try cert.extensions.authorityInformationAccess,
.init([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))])
)
XCTAssertEqual(
try cert.extensions.subjectKeyIdentifier,
.init(keyIdentifier: [0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8, 0xAE, 0x1B, 0xAE])
.init(keyIdentifier: [
0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8,
0xAE, 0x1B, 0xAE,
])
)
XCTAssertEqual(
try cert.extensions.authorityKeyIdentifier,
.init(keyIdentifier: [0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29, 0xBC, 0x4B, 0xC6])
.init(keyIdentifier: [
0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29,
0xBC, 0x4B, 0xC6,
])
)
XCTAssertEqual(
try cert.extensions.extendedKeyUsage,
@@ -235,9 +262,15 @@ final class CertificateDERTests: XCTestCase {
let cert = try Certificate(derEncoded: binary)
let expectedExtensions = try Certificate.Extensions {
SubjectKeyIdentifier(keyIdentifier: [0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8, 0xAE, 0x1B, 0xAE])
SubjectKeyIdentifier(keyIdentifier: [
0xE0, 0x85, 0x48, 0x7D, 0x13, 0xA6, 0xD3, 0x10, 0x19, 0x9F, 0x5C, 0xCB, 0x6B, 0x78, 0x24, 0x92, 0xF8,
0xAE, 0x1B, 0xAE,
])
AuthorityKeyIdentifier(keyIdentifier: [0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29, 0xBC, 0x4B, 0xC6])
AuthorityKeyIdentifier(keyIdentifier: [
0xB3, 0xDB, 0x48, 0xA4, 0xF9, 0xA1, 0xC5, 0xD8, 0xAE, 0x36, 0x41, 0xCC, 0x11, 0x63, 0x69, 0x62, 0x29,
0xBC, 0x4B, 0xC6,
])
Critical(
KeyUsage(digitalSignature: true, keyCertSign: true, cRLSign: true)
@@ -249,7 +282,9 @@ final class CertificateDERTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: 0)
)
AuthorityInformationAccess([.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))])
AuthorityInformationAccess([
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://ocsp.digicert.com"))
])
// CRL Distribution Points
Certificate.Extension(
@@ -259,7 +294,7 @@ final class CertificateDERTests: XCTestCase {
0x30, 0x39, 0x30, 0x37, 0xA0, 0x35, 0xA0, 0x33, 0x86, 0x31, 0x68, 0x74, 0x74, 0x70, 0x3A, 0x2F,
0x2F, 0x63, 0x72, 0x6C, 0x33, 0x2E, 0x64, 0x69, 0x67, 0x69, 0x63, 0x65, 0x72, 0x74, 0x2E, 0x63,
0x6F, 0x6D, 0x2F, 0x44, 0x69, 0x67, 0x69, 0x43, 0x65, 0x72, 0x74, 0x47, 0x6C, 0x6F, 0x62, 0x61,
0x6C, 0x52, 0x6F, 0x6F, 0x74, 0x47, 0x33, 0x2E, 0x63, 0x72, 0x6C
0x6C, 0x52, 0x6F, 0x6F, 0x74, 0x47, 0x33, 0x2E, 0x63, 0x72, 0x6C,
]
)
@@ -281,18 +316,18 @@ final class CertificateDERTests: XCTestCase {
0x20, 0x6C, 0x6F, 0x63, 0x61, 0x74, 0x65, 0x64, 0x20, 0x61, 0x74, 0x20, 0x68, 0x74, 0x74, 0x70,
0x73, 0x3A, 0x2F, 0x2F, 0x77, 0x77, 0x77, 0x2E, 0x64, 0x69, 0x67, 0x69, 0x63, 0x65, 0x72, 0x74,
0x2E, 0x63, 0x6F, 0x6D, 0x2F, 0x72, 0x70, 0x61, 0x2D, 0x75, 0x61, 0x30, 0x07, 0x06, 0x05, 0x67,
0x81, 0x0C, 0x01, 0x01
0x81, 0x0C, 0x01, 0x01,
]
)
}
XCTAssertEqual(cert.extensions, expectedExtensions)
}
func testSubjectKeyIdentifierHash() throws {
let binary = Array(Data(base64Encoded: Self.base64EncodedSampleCert, options: .ignoreUnknownCharacters)!)
let cert = try Certificate(derEncoded: binary)
XCTAssertEqual(try cert.extensions.subjectKeyIdentifier, SubjectKeyIdentifier(hash: cert.publicKey))
}
@@ -323,11 +358,17 @@ final class CertificateDERTests: XCTestCase {
var coder = DER.Serializer()
try coder.appendConstructedNode(identifier: .sequence) { coder in
try coder.serialize(Certificate.Version.v3.rawValue, explicitlyTaggedWithTagNumber: 0, tagClass: .contextSpecific)
try coder.serialize(
Certificate.Version.v3.rawValue,
explicitlyTaggedWithTagNumber: 0,
tagClass: .contextSpecific
)
try coder.serialize(Certificate.SerialNumber().bytes)
try coder.serialize(AlgorithmIdentifier.sha256WithRSAEncryptionUsingNil)
try coder.serialize(name)
try coder.serialize(try Validity(notBefore: .makeTime(from: Date()), notAfter: .makeTime(from: Date() + 100)))
try coder.serialize(
try Validity(notBefore: .makeTime(from: Date()), notAfter: .makeTime(from: Date() + 100))
)
try coder.serialize(name)
try coder.serialize(SubjectPublicKeyInfo(.init(key.publicKey)))
}
@@ -335,7 +376,10 @@ final class CertificateDERTests: XCTestCase {
let tbsCertificateBytes = coder.serializedBytes
// Ok, we can construct this into a real certificate now by signing it and producing the signature block.
let signature = try Certificate.PrivateKey(key).sign(bytes: tbsCertificateBytes, signatureAlgorithm: .sha256WithRSAEncryption)
let signature = try Certificate.PrivateKey(key).sign(
bytes: tbsCertificateBytes,
signatureAlgorithm: .sha256WithRSAEncryption
)
coder = DER.Serializer()
try coder.appendConstructedNode(identifier: .sequence) { coder in
@@ -380,42 +424,45 @@ final class CertificateDERTests: XCTestCase {
func testIncorrectParameterSize() throws {
// This certificate tripped us up and revealed a bug in our ECDSA
// parsing, so let's use it as a regression test.
let cert = Array(Data(base64Encoded: """
MIIGATCCBYegAwIBAgIRAJt9HrGyczJOAAAAAFaglHwwCgYIKoZIzj0EAwIwgbox
CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9T
ZWUgd3d3LmVudHJ1c3Q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EQFcHmp2V/UkF5gS
MCkHbwIhAN0mbQvKboODaXXfPf3K9F5mRks2NYdrpV7I+uTsxxcwAHYAu9nfvB+K
cbWTlCOXqpJ7RzhXlQqrUugakJZkNo4e0YUAAAFuY9EmtwAABAMARzBFAiEAocip
srDjKmlOd8Zo+mhFFVRmZYlgZMoLV/IvrMTEAFMCIFfzmKsxybQnMGX6iPbTU7nk
kAtsnNa6QaTEpRMVmsSEMA4GA1UdDwEB/wQEAwIHgDAdBgNVHSUEFjAUBggrBgEF
BQcDAQYIKwYBBQUHAwIwYwYIKwYBBQUHAQEEVzBVMCMGCCsGAQUFBzABhhdodHRw
Oi8vb2NzcC5lbnRydXN0Lm5ldDAuBggrBgEFBQcwAoYiaHR0cDovL2FpYS5lbnRy
dXN0Lm5ldC9sMWotZWMxLmNlcjAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3Js
LmVudHJ1c3QubmV0L2xldmVsMWouY3JsMEoGA1UdIARDMEEwNgYKYIZIAYb6bAoB
AjAoMCYGCCsGAQUFBwIBFhpodHRwOi8vd3d3LmVudHJ1c3QubmV0L3JwYTAHBgVn
gQwBATAfBgNVHSMEGDAWgBTD+UUDvsj5CzxFNfPrcuzn6OuUmzAdBgNVHQ4EFgQU
7vNz5mM0I6JgWqm+556364tWmW8wCQYDVR0TBAIwADAKBggqhkjOPQQDAgNoADBl
AjBwybhS35Z4KFf1pt20LC9/CyxsDya3W/NbMn+bZ0RNNnOPABMv/Z3Xj7w086v4
PFcCMQDJVzG8VALwsAvO3JmKPy2LguNq0+pylaihUYGEg6rxxg5WyCXfnpZu0c+i
N5YHEvI=
""",
options: .ignoreUnknownCharacters
)!
)
XCTAssertNoThrow(try Certificate(derEncoded: cert))
@@ -487,202 +534,205 @@ final class CertificateDERTests: XCTestCase {
}
func testParsingBigNameConstraints() throws {
let cert = Array(Data(base64Encoded: """
MIIkKjCCIxKgAwIBAgIJIrmxaudci1hlMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV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NrOXXP/LwDP85gKq+2/QGCsENsxLC4tLhonANethBLExpHaiUhjDVD3IO8w9cmE
Fm4c6j6onhml5MChBfLeNoXlc7lG+CKgIV4lQ1AuedV/FcYtNXqADOe5hO4IKENQ
PBsG3+c22LGvqt4DsBMYHiGU4AFzT5BLWrYZv1TMIUQ+lSOWvLIsTQSN6WgQ3w==
""",
options: .ignoreUnknownCharacters
)!
)
let decoded = try Certificate(derEncoded: cert)
+96 -55
View File
@@ -24,31 +24,34 @@ final class CertificateTests: XCTestCase {
let s = String(describing: serial)
XCTAssertEqual(s, "a:14:1e:28")
}
#if swift(>=5.8)
@available(macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4, *)
func testSerialNumberStaticBigInt() {
XCTAssertEqual(
(
0b0000_0001__0000_0010__0000_0011__0000_0100__0000_0101__0000_0110__0000_0111__0000_1000__0000_1001__0000_1010__0000_1011__0000_1100__0000_1101__0000_1110 as Certificate.SerialNumber
).bytes,
(0b0000_0001__0000_0010__0000_0011__0000_0100__0000_0101__0000_0110__0000_0111__0000_1000__0000_1001__0000_1010__0000_1011__0000_1100__0000_1101__0000_1110
as Certificate.SerialNumber).bytes,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
)
XCTAssertEqual(
(
0x00_01_02_03_04_05_06_07_08_09_0A_0B_0C_0D_0E_0F_10_11_12_13_14 as Certificate.SerialNumber
).bytes,
(0x00_01_02_03_04_05_06_07_08_09_0A_0B_0C_0D_0E_0F_10_11_12_13_14 as Certificate.SerialNumber).bytes,
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
)
XCTAssertEqual(Certificate.SerialNumber(123456789), 123456789)
XCTAssertEqual(Certificate.SerialNumber(123_456_789), 123_456_789)
}
#endif
func testSerialNumberInits() {
XCTAssertEqual(Certificate.SerialNumber(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8]).bytes, [1, 2, 3, 4, 5, 6, 7, 8])
XCTAssertEqual(Certificate.SerialNumber(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8][...]).bytes, [1, 2, 3, 4, 5, 6, 7, 8])
XCTAssertEqual(Certificate.SerialNumber(bytes: AnyCollection([0, 1, 2, 3, 4, 5, 6, 7, 8])).bytes, [1, 2, 3, 4, 5, 6, 7, 8])
XCTAssertEqual(
Certificate.SerialNumber(bytes: [0, 1, 2, 3, 4, 5, 6, 7, 8][...]).bytes,
[1, 2, 3, 4, 5, 6, 7, 8]
)
XCTAssertEqual(
Certificate.SerialNumber(bytes: AnyCollection([0, 1, 2, 3, 4, 5, 6, 7, 8])).bytes,
[1, 2, 3, 4, 5, 6, 7, 8]
)
}
func testPrintingVersions() {
@@ -61,8 +64,14 @@ final class CertificateTests: XCTestCase {
let testDN = try DistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: "DigiCert Inc"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "www.digicert.com"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: "DigiCert Global Root G3"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationalUnitName,
utf8String: "www.digicert.com"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.commonName,
utf8String: "DigiCert Global Root G3"
),
])
XCTAssertEqual(
@@ -111,26 +120,32 @@ final class CertificateTests: XCTestCase {
"(Issuer: URI(\"https://example.com/ca\")), (OCSP Server: URI(\"http://example.com/ocsp\")), (1.2.3.4: RFC822Name(\"mail@example.com\"))"
)
}
func testRangeReplaceableCollectionConformance() throws {
var ext = AuthorityInformationAccess([
.init(method: .issuingCA, location: .uniformResourceIdentifier("https://example.com/ca")),
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp")),
.init(method: .init(.unknownType([1, 2, 3, 4])), location: .rfc822Name("mail@example.com")),
])
ext.replaceSubrange(1..<2, with: [
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/a")),
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/b")),
])
XCTAssertEqual(Array(ext), [
.init(method: .issuingCA, location: .uniformResourceIdentifier("https://example.com/ca")),
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/a")),
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/b")),
.init(method: .init(.unknownType([1, 2, 3, 4])), location: .rfc822Name("mail@example.com")),
])
ext.replaceSubrange(
1..<2,
with: [
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/a")),
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/b")),
]
)
XCTAssertEqual(
Array(ext),
[
.init(method: .issuingCA, location: .uniformResourceIdentifier("https://example.com/ca")),
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/a")),
.init(method: .ocspServer, location: .uniformResourceIdentifier("http://example.com/ocsp/b")),
.init(method: .init(.unknownType([1, 2, 3, 4])), location: .rfc822Name("mail@example.com")),
]
)
func conformsToRangeReplaceableCollection(_ value: some Any) -> Bool {
value is any RangeReplaceableCollection
}
@@ -311,18 +326,18 @@ final class CertificateTests: XCTestCase {
"anyKeyUsage, certificateTransparency, timeStamping, ocspSigning, 1.2.3.4, clientAuth, serverAuth, codeSigning, emailProtection"
)
}
func testSerialNumberRandomNumberGenerator() {
struct StaticNumberGenerator: RandomNumberGenerator {
var numbers: [UInt8]
var nextIndex: Int = 0
mutating func next() -> UInt64 {
defer { nextIndex += 1}
defer { nextIndex += 1 }
let startOffset = nextIndex * MemoryLayout<UInt64>.size
precondition(numbers.indices.contains(startOffset), "static number generator is out of numbers")
// assemble UInt64 from eight UInt8s
var uint64 = UInt64()
for byte in 0..<(MemoryLayout<UInt64>.size) {
@@ -337,18 +352,38 @@ final class CertificateTests: XCTestCase {
return uint64
}
}
var rngWithLeadingZero = StaticNumberGenerator(numbers: [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
XCTAssertEqual(Certificate.SerialNumber(generator: &rngWithLeadingZero).bytes, [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
var rngWithZeroAtTheSecondPosition = StaticNumberGenerator(numbers: [1, 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
XCTAssertEqual(Certificate.SerialNumber(generator: &rngWithZeroAtTheSecondPosition).bytes, [1, 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
var rngWithoutLeadingZero = StaticNumberGenerator(numbers: [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21])
XCTAssertEqual(Certificate.SerialNumber(generator: &rngWithoutLeadingZero).bytes, [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21])
var rngWithTrailingZero = StaticNumberGenerator(numbers: [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0])
XCTAssertEqual(Certificate.SerialNumber(generator: &rngWithTrailingZero).bytes, [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0])
var rngWithLeadingZero = StaticNumberGenerator(numbers: [
0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
])
XCTAssertEqual(
Certificate.SerialNumber(generator: &rngWithLeadingZero).bytes,
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
)
var rngWithZeroAtTheSecondPosition = StaticNumberGenerator(numbers: [
1, 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
])
XCTAssertEqual(
Certificate.SerialNumber(generator: &rngWithZeroAtTheSecondPosition).bytes,
[1, 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
)
var rngWithoutLeadingZero = StaticNumberGenerator(numbers: [
1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
])
XCTAssertEqual(
Certificate.SerialNumber(generator: &rngWithoutLeadingZero).bytes,
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
)
var rngWithTrailingZero = StaticNumberGenerator(numbers: [
1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0,
])
XCTAssertEqual(
Certificate.SerialNumber(generator: &rngWithTrailingZero).bytes,
[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 0]
)
}
func testRoundTrippingKeys() throws {
@@ -436,9 +471,9 @@ final class CertificateTests: XCTestCase {
Data(Certificate.PublicKey(rsa.publicKey).subjectPublicKeyInfoBytes)
)
}
private static let referenceTime = Date(timeIntervalSince1970: 1691504774)
private static let referenceTime = Date(timeIntervalSince1970: 1_691_504_774)
func testCertificateDescription() throws {
let caPrivateKey = P384.Signing.PrivateKey()
let certificateName1 = try! DistinguishedName {
@@ -446,7 +481,7 @@ final class CertificateTests: XCTestCase {
OrganizationName("Apple")
CommonName("Swift Certificate Test CA 1")
}
let ca = try Certificate(
version: .v3,
serialNumber: .init(bytes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]),
@@ -461,11 +496,13 @@ final class CertificateTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: caPrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: caPrivateKey.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(caPrivateKey)
)
XCTAssertEqual(
String(describing: ca),
"""
@@ -486,7 +523,7 @@ final class CertificateTests: XCTestCase {
)
"""
)
let intermediatePrivateKey = P256.Signing.PrivateKey()
let intermediateName = try! DistinguishedName {
CountryName("US")
@@ -509,7 +546,11 @@ final class CertificateTests: XCTestCase {
)
KeyUsage(keyCertSign: true)
AuthorityKeyIdentifier(keyIdentifier: try! ca.extensions.subjectKeyIdentifier!.keyIdentifier)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: intermediatePrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(
Insecure.SHA1.hash(data: intermediatePrivateKey.publicKey.derRepresentation)
)
)
NameConstraints(
permittedDNSDomains: ["apple.com."],
excludedDNSDomains: ["www.apple.com."],
@@ -524,7 +565,7 @@ final class CertificateTests: XCTestCase {
issuerPrivateKey: .init(caPrivateKey)
)
}()
XCTAssertEqual(
String(describing: intermediate),
"""
@@ -549,7 +590,7 @@ final class CertificateTests: XCTestCase {
])
"""
)
let localhostPrivateKey = P256.Signing.PrivateKey()
let leaf = try Certificate(
version: .v3,
@@ -574,7 +615,7 @@ final class CertificateTests: XCTestCase {
},
issuerPrivateKey: .init(localhostPrivateKey)
)
XCTAssertEqual(
String(describing: leaf),
"""
+1 -1
View File
@@ -85,7 +85,7 @@ final class DNSNamesTests: XCTestCase {
("*.test.FR", "wwW.tESt.fr", false),
(".uk", "f.uk", false),
("?.bar.foo.com", "w.bar.foo.com", false),
("(www|ftp).foo.com", "www.foo.com", false), // regex!
("(www|ftp).foo.com", "www.foo.com", false), // regex!
("www.foo.com\0", "www.foo.com", false),
("www.foo.com\0*.foo.com", "www.foo.com", false),
("ww.house.example", "www.house.example", false),
+125 -57
View File
@@ -59,76 +59,88 @@ final class DistinguishedNameTests: XCTestCase {
XCTAssertEqual(Array(nameA), expected)
XCTAssertEqual(Array(nameB), expected)
}
func testSimpleRelativeDistinguishedNameRemoveAt() throws {
var rdn = RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcde"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
])
XCTAssertEqual(
rdn.remove(at: 1),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcde")
)
XCTAssertEqual(rdn, RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
]))
XCTAssertEqual(
rdn,
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
])
)
XCTAssertEqual(
rdn.remove(at: 0),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd")
)
XCTAssertEqual(rdn, RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
]))
XCTAssertEqual(
rdn,
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef")
])
)
XCTAssertEqual(
rdn.remove(at: 0),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef")
)
XCTAssertEqual(rdn, RelativeDistinguishedName())
}
func testSimpleRelativeDistinguishedNameRemoveAll() throws {
var rdn = RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcde"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
])
rdn.removeAll(where: {
$0 == RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcde")
})
XCTAssertEqual(rdn, RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
]))
XCTAssertEqual(
rdn,
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
])
)
rdn.removeAll(where: {
$0 == RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd")
})
XCTAssertEqual(rdn, RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
]))
XCTAssertEqual(
rdn,
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef")
])
)
rdn.removeAll(where: {
$0 == RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef")
})
XCTAssertEqual(rdn, RelativeDistinguishedName())
}
func testSimpleRelativeDistinguishedNameRemoveAllInOneGo() throws {
var rdn = RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcd"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcde"),
RelativeDistinguishedName.Attribute(type: .NameAttributes.name, utf8String: "abcdef"),
])
rdn.removeAll(where: { _ in true })
XCTAssertEqual(rdn, RelativeDistinguishedName())
}
@@ -150,7 +162,8 @@ final class DistinguishedNameTests: XCTestCase {
try serializer.serialize(name)
let expectedBytes: [UInt8] = [
49, 26, 48, 11, 6, 3, 85, 4, 3, 19, 4, 0x65, 0x66, 0x67, 0x68, 48, 11, 6, 3, 85, 4, 41, 12, 4, 0x61, 0x62, 0x63, 0x64
49, 26, 48, 11, 6, 3, 85, 4, 3, 19, 4, 0x65, 0x66, 0x67, 0x68, 48, 11, 6, 3, 85, 4, 41, 12, 4, 0x61, 0x62,
0x63, 0x64,
]
XCTAssertEqual(serializer.serializedBytes, expectedBytes)
@@ -186,7 +199,7 @@ final class DistinguishedNameTests: XCTestCase {
let expectedBytes: [UInt8] = [
48, 56, 49, 26, 48, 11, 6, 3, 85, 4, 3, 19, 4, 0x65, 0x66, 0x67, 0x68, 48, 11, 6, 3, 85,
4, 41, 12, 4, 0x61, 0x62, 0x63, 0x64, 49, 26, 48, 11, 6, 3, 85, 4, 3, 19, 4, 0x6d, 0x6e, 0x6f,
0x70, 48, 11, 6, 3, 85, 4, 41, 12, 4, 0x69, 0x6a, 0x6b, 0x6c
0x70, 48, 11, 6, 3, 85, 4, 41, 12, 4, 0x69, 0x6a, 0x6b, 0x6c,
]
XCTAssertEqual(serializer.serializedBytes, expectedBytes)
@@ -203,9 +216,18 @@ final class DistinguishedNameTests: XCTestCase {
name,
try DistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: "DigiCert Inc"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "www.digicert.com"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: "DigiCert Global Root G3"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationName,
utf8String: "DigiCert Inc"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationalUnitName,
utf8String: "www.digicert.com"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.commonName,
utf8String: "DigiCert Global Root G3"
),
])
)
}
@@ -239,9 +261,18 @@ final class DistinguishedNameTests: XCTestCase {
name,
try DistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: "DigiCert Inc"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "www.digicert.com"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.streetAddress, utf8String: "123 Real Street"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationName,
utf8String: "DigiCert Inc"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationalUnitName,
utf8String: "www.digicert.com"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.streetAddress,
utf8String: "123 Real Street"
),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: "baz"),
])
)
@@ -251,8 +282,14 @@ final class DistinguishedNameTests: XCTestCase {
let name = try DistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: "DigiCert Inc"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "www.digicert.com"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: "DigiCert Global Root G3"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationalUnitName,
utf8String: "www.digicert.com"
),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.commonName,
utf8String: "DigiCert Global Root G3"
),
])
let s = String(describing: name)
@@ -262,21 +299,33 @@ final class DistinguishedNameTests: XCTestCase {
func testDistinguishedNameRepresentationWithNestedAttributes() throws {
let name = try DistinguishedName([
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US")
]),
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.stateOrProvinceName, printableString: "CA"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.stateOrProvinceName, utf8String: "California")
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.stateOrProvinceName,
utf8String: "California"
),
]),
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: "DigiCert Inc"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationName,
utf8String: "DigiCert Inc"
)
]),
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "www.digicert.com"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationalUnitName,
utf8String: "www.digicert.com"
)
]),
RelativeDistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: "DigiCert Global Root G3"),
])
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.commonName,
utf8String: "DigiCert Global Root G3"
)
]),
])
let s = String(describing: name)
@@ -287,14 +336,17 @@ final class DistinguishedNameTests: XCTestCase {
let name = try DistinguishedName([
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.countryName, utf8String: "US "),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationName, utf8String: " DigiCert Inc"),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.organizationalUnitName, utf8String: "#www.digicert.com"),
RelativeDistinguishedName.Attribute(
type: .RDNAttributeType.organizationalUnitName,
utf8String: "#www.digicert.com"
),
RelativeDistinguishedName.Attribute(type: .RDNAttributeType.commonName, utf8String: ",+\"\\<>;"),
])
let s = String(describing: name)
XCTAssertEqual(s, "CN=\\,\\+\\\"\\\\\\<\\>\\;,OU=\\#www.digicert.com,O=\\ DigiCert Inc,C=US\\ ")
}
func testRDNAttributeValue() {
func XCTAssertEqualValueAndHash<Value>(
_ expression1: @autoclosure () throws -> Value,
@@ -302,7 +354,7 @@ final class DistinguishedNameTests: XCTestCase {
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) where Value : Hashable {
) where Value: Hashable {
let lhs: Value
do {
lhs = try expression1()
@@ -318,32 +370,48 @@ final class DistinguishedNameTests: XCTestCase {
return
}
XCTAssertEqual(lhs, rhs, file: file, line: line)
var lhsHasher = Hasher()
lhsHasher.combine(lhs)
var rhsHasher = Hasher()
rhsHasher.combine(rhs)
XCTAssertEqual(lhsHasher.finalize(), rhsHasher.finalize(), "hashes should be the same for \(lhs) and \(rhs)", file: file, line: line)
XCTAssertEqual(
lhsHasher.finalize(),
rhsHasher.finalize(),
"hashes should be the same for \(lhs) and \(rhs)",
file: file,
line: line
)
}
XCTAssertEqualValueAndHash(
try RelativeDistinguishedName.Attribute.Value(asn1Any: ASN1Any(erasing: ASN1UTF8String("This is a fancy UTF8 String with Emojies 🥳🐥"))),
try RelativeDistinguishedName.Attribute.Value(
asn1Any: ASN1Any(erasing: ASN1UTF8String("This is a fancy UTF8 String with Emojies 🥳🐥"))
),
RelativeDistinguishedName.Attribute.Value(utf8String: "This is a fancy UTF8 String with Emojies 🥳🐥")
)
XCTAssertEqualValueAndHash(
try RelativeDistinguishedName.Attribute.Value(asn1Any: ASN1Any(erasing: ASN1PrintableString("This is a simple printable string 123456789 ():="))),
try RelativeDistinguishedName.Attribute.Value(printableString: "This is a simple printable string 123456789 ():=")
try RelativeDistinguishedName.Attribute.Value(
asn1Any: ASN1Any(erasing: ASN1PrintableString("This is a simple printable string 123456789 ():="))
),
try RelativeDistinguishedName.Attribute.Value(
printableString: "This is a simple printable string 123456789 ():="
)
)
XCTAssertEqualValueAndHash(
try RelativeDistinguishedName.Attribute.Value(asn1Any: ASN1Any(erasing: ASN1UTF8String(String(repeating: "A", count: 129)))),
try RelativeDistinguishedName.Attribute.Value(
asn1Any: ASN1Any(erasing: ASN1UTF8String(String(repeating: "A", count: 129)))
),
RelativeDistinguishedName.Attribute.Value(utf8String: String(repeating: "A", count: 129))
)
XCTAssertEqualValueAndHash(
try RelativeDistinguishedName.Attribute.Value(asn1Any: ASN1Any(erasing: ASN1UTF8String(String(repeating: "A", count: Int(UInt16.max) + 1)))),
try RelativeDistinguishedName.Attribute.Value(
asn1Any: ASN1Any(erasing: ASN1UTF8String(String(repeating: "A", count: Int(UInt16.max) + 1)))
),
RelativeDistinguishedName.Attribute.Value(utf8String: String(repeating: "A", count: Int(UInt16.max) + 1))
)
}
+127 -80
View File
@@ -17,123 +17,170 @@ import X509
final class ExtendedKeyUsageTests: XCTestCase {
func testInit() {
XCTAssertThrowsError(try ExtendedKeyUsage([
.serverAuth,
.serverAuth,
])) { error in
XCTAssertThrowsError(
try ExtendedKeyUsage([
.serverAuth,
.serverAuth,
])
) { error in
XCTAssertEqual((error as? CertificateError)?.code, .duplicateOID, "wrong error \(error)")
}
XCTAssertThrowsError(try ExtendedKeyUsage([
.clientAuth,
.serverAuth,
.clientAuth,
])) { error in
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,
.serverAuth
])
XCTAssertTrue(usages.insert(.clientAuth, at: 1) == (true, 1))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.clientAuth,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.serverAuth,
.clientAuth,
])
)
XCTAssertTrue(usages.insert(.clientAuth, at: 1) == (false, 1))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.clientAuth,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.serverAuth,
.clientAuth,
])
)
XCTAssertTrue(usages.insert(.ocspSigning, at: 1) == (true, 1))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
.clientAuth,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
.clientAuth,
])
)
XCTAssertTrue(usages.insert(.codeSigning, at: 0) == (true, 0))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.codeSigning,
.serverAuth,
.ocspSigning,
.clientAuth,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.codeSigning,
.serverAuth,
.ocspSigning,
.clientAuth,
])
)
}
func testAppend() throws {
var usages = ExtendedKeyUsage()
usages.append(.clientAuth)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.clientAuth,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.clientAuth
])
)
usages.append(.clientAuth)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.clientAuth,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.clientAuth
])
)
usages.append(.ocspSigning)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.clientAuth,
.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,
try ExtendedKeyUsage([
.clientAuth,
.serverAuth,
.ocspSigning,
])
)
XCTAssertEqual(usages.remove(.clientAuth), .clientAuth)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
])
)
XCTAssertNil(usages.remove(.clientAuth))
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.serverAuth,
.ocspSigning,
])
)
XCTAssertEqual(usages.remove(.ocspSigning), .ocspSigning)
XCTAssertEqual(usages, try ExtendedKeyUsage([
.serverAuth,
]))
XCTAssertEqual(
usages,
try ExtendedKeyUsage([
.serverAuth
])
)
XCTAssertEqual(usages.remove(.serverAuth), .serverAuth)
XCTAssertEqual(usages, ExtendedKeyUsage())
XCTAssertNil(usages.remove(.serverAuth))
XCTAssertEqual(usages, ExtendedKeyUsage())
}
func testLargeNumberOfExtensions() throws {
let usages = try ExtendedKeyUsage((0..<32).map {
ExtendedKeyUsage.Usage(oid: [$0])
})
let usages = try ExtendedKeyUsage(
(0..<32).map {
ExtendedKeyUsage.Usage(oid: [$0])
}
)
XCTAssertEqual(usages.count, 32)
}
func testUnreasonableLargeNumberOfExtensionsAreRejected() {
XCTAssertThrowsError(try ExtendedKeyUsage((0..<33).map {
ExtendedKeyUsage.Usage(oid: [$0])
}))
XCTAssertThrowsError(try ExtendedKeyUsage((0..<10_000).map {
ExtendedKeyUsage.Usage(oid: [$0])
}))
XCTAssertThrowsError(
try ExtendedKeyUsage(
(0..<33).map {
ExtendedKeyUsage.Usage(oid: [$0])
}
)
)
XCTAssertThrowsError(
try ExtendedKeyUsage(
(0..<10_000).map {
ExtendedKeyUsage.Usage(oid: [$0])
}
)
)
}
}
+174 -117
View File
@@ -58,17 +58,21 @@ final class ExtensionBuilderTests: XCTestCase {
func testMakingThingsCritical() throws {
let extensions = try Certificate.Extensions {
Critical(
Certificate.Extension(oid: .X509ExtensionID.authorityInformationAccess, critical: false, value: [1, 2, 3])
Certificate.Extension(
oid: .X509ExtensionID.authorityInformationAccess,
critical: false,
value: [1, 2, 3]
)
)
}
let expectedExtensions = try Certificate.Extensions([
Certificate.Extension(oid: .X509ExtensionID.authorityInformationAccess, critical: true, value: [1, 2, 3]),
Certificate.Extension(oid: .X509ExtensionID.authorityInformationAccess, critical: true, value: [1, 2, 3])
])
XCTAssertEqual(extensions, expectedExtensions)
}
func testThrowingExtension() throws {
struct MyError: Error {}
struct MyThrowingExtension: CertificateExtensionConvertible {
@@ -76,137 +80,171 @@ final class ExtensionBuilderTests: XCTestCase {
throw MyError()
}
}
let `true` = true
let `false` = false
XCTAssertThrowsError(try Certificate.Extensions {
MyThrowingExtension()
}) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertThrowsError(try Certificate.Extensions {
MyThrowingExtension()
MyThrowingExtension()
}) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertThrowsError(try Certificate.Extensions {
for _ in 0..<3 {
XCTAssertThrowsError(
try Certificate.Extensions {
MyThrowingExtension()
}
}) { error in
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertThrowsError(try Certificate.Extensions {
Certificate.Extension(oid: [1], critical: false, value: [1])
MyThrowingExtension()
}) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertThrowsError(try Certificate.Extensions {
MyThrowingExtension()
Certificate.Extension(oid: [1], critical: false, value: [1])
}) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertThrowsError(try Certificate.Extensions {
if `true` {
XCTAssertThrowsError(
try Certificate.Extensions {
MyThrowingExtension()
MyThrowingExtension()
}
}) { error in
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertNoThrow(try Certificate.Extensions {
if `false` {
XCTAssertThrowsError(
try Certificate.Extensions {
for _ in 0..<3 {
MyThrowingExtension()
}
}
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertThrowsError(
try Certificate.Extensions {
Certificate.Extension(oid: [1], critical: false, value: [1])
MyThrowingExtension()
}
})
XCTAssertThrowsError(try Certificate.Extensions {
if `true` {
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertThrowsError(
try Certificate.Extensions {
MyThrowingExtension()
} else {
Certificate.Extension(oid: [1], critical: false, value: [1])
}
}) { error in
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertNoThrow(try Certificate.Extensions {
if `false` {
MyThrowingExtension()
} else {
Certificate.Extension(oid: [1], critical: false, value: [1])
XCTAssertThrowsError(
try Certificate.Extensions {
if `true` {
MyThrowingExtension()
}
}
})
XCTAssertNoThrow(try Certificate.Extensions {
if `true` {
Certificate.Extension(oid: [1], critical: false, value: [1])
} else {
MyThrowingExtension()
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertNoThrow(
try Certificate.Extensions {
if `false` {
MyThrowingExtension()
}
}
})
XCTAssertThrowsError(try Certificate.Extensions {
if `false` {
Certificate.Extension(oid: [1], critical: false, value: [1])
} else {
MyThrowingExtension()
)
XCTAssertThrowsError(
try Certificate.Extensions {
if `true` {
MyThrowingExtension()
} else {
Certificate.Extension(oid: [1], critical: false, value: [1])
}
}
}) { error in
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
XCTAssertNoThrow(
try Certificate.Extensions {
if `false` {
MyThrowingExtension()
} else {
Certificate.Extension(oid: [1], critical: false, value: [1])
}
}
)
XCTAssertNoThrow(
try Certificate.Extensions {
if `true` {
Certificate.Extension(oid: [1], critical: false, value: [1])
} else {
MyThrowingExtension()
}
}
)
XCTAssertThrowsError(
try Certificate.Extensions {
if `false` {
Certificate.Extension(oid: [1], critical: false, value: [1])
} else {
MyThrowingExtension()
}
}
) { error in
XCTAssertTrue(error is MyError, "wrong error \(error)")
}
}
func testInitDuplicateHandling() {
XCTAssertThrowsError(try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [1], critical: false, value: [2]),
])) { error in
XCTAssertThrowsError(
try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [1], critical: false, value: [2]),
])
) { error in
XCTAssertEqual((error as? CertificateError)?.code, .duplicateOID, "wrong error \(error)")
}
XCTAssertThrowsError(try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [2], critical: false, value: [1]),
.init(oid: [1], critical: false, value: [2]),
])) { error in
XCTAssertThrowsError(
try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [2], critical: false, value: [1]),
.init(oid: [1], critical: false, value: [2]),
])
) { error in
XCTAssertEqual((error as? CertificateError)?.code, .duplicateOID, "wrong error \(error)")
}
XCTAssertThrowsError(try Certificate.Extensions {
try ExtendedKeyUsage([.serverAuth])
try ExtendedKeyUsage([.clientAuth])
}) { error in
XCTAssertThrowsError(
try Certificate.Extensions {
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])))
XCTAssertNoThrow(try extensions.append(.init(oid: [2], critical: true, value: [1])))
XCTAssertEqual(extensions, try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [2], critical: true, value: [1]),
]))
XCTAssertEqual(
extensions,
try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [2], critical: true, value: [1]),
])
)
XCTAssertThrowsError(try extensions.append(.init(oid: [2], critical: false, value: [1]))) { error in
XCTAssertEqual((error as? CertificateError)?.code, .duplicateOID, "wrong error \(error)")
}
XCTAssertEqual(extensions, try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [2], critical: true, value: [1]),
]))
XCTAssertEqual(
extensions,
try Certificate.Extensions([
.init(oid: [1], critical: false, value: [1]),
.init(oid: [2], critical: true, value: [1]),
])
)
}
func testUpdate() {
var extensions = Certificate.Extensions()
extensions.update(.init(oid: [1], critical: false, value: [1]))
@@ -214,11 +252,14 @@ final class ExtensionBuilderTests: XCTestCase {
extensions.update(.init(oid: [1], critical: false, value: [2])),
.init(oid: [1], critical: false, value: [1])
)
XCTAssertEqual(extensions, try Certificate.Extensions([
.init(oid: [1], critical: false, value: [2])
]))
XCTAssertEqual(
extensions,
try Certificate.Extensions([
.init(oid: [1], critical: false, value: [2])
])
)
}
func testRemove() {
var extensions = Certificate.Extensions()
extensions.remove([1])
@@ -226,31 +267,47 @@ final class ExtensionBuilderTests: XCTestCase {
XCTAssertNoThrow(try extensions.append(.init(oid: [1], critical: false, value: [1])))
XCTAssertNoThrow(try extensions.append(.init(oid: [2], critical: true, value: [1])))
extensions.remove([2])
XCTAssertEqual(extensions, try Certificate.Extensions {
Certificate.Extension(oid: [1], critical: false, value: [1])
})
XCTAssertEqual(
extensions,
try Certificate.Extensions {
Certificate.Extension(oid: [1], critical: false, value: [1])
}
)
extensions.remove([2])
XCTAssertEqual(extensions, try Certificate.Extensions {
Certificate.Extension(oid: [1], critical: false, value: [1])
})
XCTAssertEqual(
extensions,
try Certificate.Extensions {
Certificate.Extension(oid: [1], critical: false, value: [1])
}
)
extensions.remove([1])
XCTAssertEqual(extensions, Certificate.Extensions())
}
func testLargeNumberOfExtensions() throws {
let ext = try Certificate.Extensions((0..<32).map {
Certificate.Extension(oid: [$0], critical: false, value: [1, 2, 3, 4])
})
let ext = try Certificate.Extensions(
(0..<32).map {
Certificate.Extension(oid: [$0], critical: false, value: [1, 2, 3, 4])
}
)
XCTAssertEqual(ext.count, 32)
}
func testUnreasonableLargeNumberOfExtensionsAreRejected() {
XCTAssertThrowsError(try Certificate.Extensions((0..<33).map {
Certificate.Extension(oid: [$0], critical: false, value: [1, 2, 3, 4])
}))
XCTAssertThrowsError(try Certificate.Extensions((0..<10_000).map {
Certificate.Extension(oid: [$0], critical: false, value: [1, 2, 3, 4])
}))
XCTAssertThrowsError(
try Certificate.Extensions(
(0..<33).map {
Certificate.Extension(oid: [$0], critical: false, value: [1, 2, 3, 4])
}
)
)
XCTAssertThrowsError(
try Certificate.Extensions(
(0..<10_000).map {
Certificate.Extension(oid: [$0], critical: false, value: [1, 2, 3, 4])
}
)
)
}
}
+16 -4
View File
@@ -53,10 +53,19 @@ final class IPAddressNameTests: XCTestCase {
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe80::", mask: "ffff:ffff:ffff:ffff::"), true),
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe80::8d:0:0:0", mask: "ffff:ffff:ffff:ffff:ffff::"), true),
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe80::8d:f7d:0:0", mask: "ffff:ffff:ffff:ffff:ffff:ffff::"), true),
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe80::8d:f7d:79c5:0", mask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"), true),
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe80::8d:f7d:79c5:5719", mask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), true),
(
.v6("fe80::8d:f7d:79c5:5719"),
.v6(subnet: "fe80::8d:f7d:79c5:0", mask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:0"), true
),
(
.v6("fe80::8d:f7d:79c5:5719"),
.v6(subnet: "fe80::8d:f7d:79c5:5719", mask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), true
),
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe81::", mask: "ffff:ffff:ffff:ffff::"), false),
(.v6("fe80::8d:f7d:79d5:5719"), .v6(subnet: "fe80::8d:f7d:79c5:5719", mask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), false),
(
.v6("fe80::8d:f7d:79d5:5719"),
.v6(subnet: "fe80::8d:f7d:79c5:5719", mask: "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), false
),
// CIDR mask with zero bytes in weird places.
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe80::8d:f7d:79c5:5719", mask: "::ffff"), false),
@@ -71,7 +80,10 @@ final class IPAddressNameTests: XCTestCase {
// CIDR masks with weird bit patterns
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe81::8d:f7d:79c5:5719", mask: "ffff:ffff:c9c9::"), false),
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "fe81::8d:f7d:79c5:5719", mask: "ffff:ffff:feff:ffff:ffff:ffff:ffff:ffff"), false),
(
.v6("fe80::8d:f7d:79c5:5719"),
.v6(subnet: "fe81::8d:f7d:79c5:5719", mask: "ffff:ffff:feff:ffff:ffff:ffff:ffff:ffff"), false
),
// All zero mask matches nothing
(.v6("fe80::8d:f7d:79c5:5719"), .v6(subnet: "::", mask: "::"), false),
+23 -15
View File
@@ -41,15 +41,17 @@ final class NameConstraintsTests: XCTestCase {
for firstName in NameConstraintsTests.names {
for secondName in NameConstraintsTests.names {
XCTAssertEqual(
NameConstraintsPolicy.directoryNameMatchesConstraint(directoryName: firstName, constraint: secondName),
NameConstraintsPolicy.directoryNameMatchesConstraint(
directoryName: firstName,
constraint: secondName
),
firstName == secondName,
"Expected directory name match to be \(firstName == secondName) for \(firstName) and \(secondName)"
)
}
}
}
func testLazyProperties() {
struct NameConstraintsPropertyValue {
var property: PartialKeyPath<NameConstraints>
@@ -65,21 +67,27 @@ final class NameConstraintsTests: XCTestCase {
self.setValue = { constraints in
constraints[keyPath: keyPath] = value
}
self.assertValueIsSet = { constraints in
// check Equatable conformance
XCTAssertEqual(constraints[keyPath: keyPath], value, file: file, line: line)
// check Hashable conformance
var lhsHasher = Hasher()
lhsHasher.combine(constraints[keyPath: keyPath])
var rhsHasher = Hasher()
rhsHasher.combine(value)
XCTAssertEqual(lhsHasher.finalize(), rhsHasher.finalize(), "hashes do not match for \(constraints[keyPath: keyPath]) and \(value)", file: file, line: line)
XCTAssertEqual(
lhsHasher.finalize(),
rhsHasher.finalize(),
"hashes do not match for \(constraints[keyPath: keyPath]) and \(value)",
file: file,
line: line
)
}
}
}
let tests: [NameConstraintsPropertyValue] = [
NameConstraintsPropertyValue(\.excludedDNSDomains, value: []),
NameConstraintsPropertyValue(\.excludedDNSDomains, value: ["apple.com"]),
@@ -89,7 +97,7 @@ final class NameConstraintsTests: XCTestCase {
NameConstraintsPropertyValue(\.permittedDNSDomains, value: ["apple.com"]),
NameConstraintsPropertyValue(\.permittedDNSDomains, value: ["example.com"]),
NameConstraintsPropertyValue(\.permittedDNSDomains, value: ["apple.com", "example.com"]),
NameConstraintsPropertyValue(\.excludedEmailAddresses, value: []),
NameConstraintsPropertyValue(\.excludedEmailAddresses, value: ["foo@example.com"]),
NameConstraintsPropertyValue(\.excludedEmailAddresses, value: ["bar@example.com"]),
@@ -98,7 +106,7 @@ final class NameConstraintsTests: XCTestCase {
NameConstraintsPropertyValue(\.permittedEmailAddresses, value: ["foo@example.com"]),
NameConstraintsPropertyValue(\.permittedEmailAddresses, value: ["bar@example.com"]),
NameConstraintsPropertyValue(\.permittedEmailAddresses, value: ["foo@example.com", "bar@example.com"]),
NameConstraintsPropertyValue(\.excludedIPRanges, value: []),
NameConstraintsPropertyValue(\.excludedIPRanges, value: [.v4("127.0.0.1")]),
NameConstraintsPropertyValue(\.excludedIPRanges, value: [.v4("192.168.0.1")]),
@@ -107,7 +115,7 @@ final class NameConstraintsTests: XCTestCase {
NameConstraintsPropertyValue(\.permittedIPRanges, value: [.v4("127.0.0.1")]),
NameConstraintsPropertyValue(\.permittedIPRanges, value: [.v4("192.168.0.1")]),
NameConstraintsPropertyValue(\.permittedIPRanges, value: [.v4("127.0.0.1"), .v4("192.168.0.1")]),
NameConstraintsPropertyValue(\.forbiddenURIDomains, value: []),
NameConstraintsPropertyValue(\.forbiddenURIDomains, value: [".example.com"]),
NameConstraintsPropertyValue(\.forbiddenURIDomains, value: [".apple.com"]),
@@ -117,18 +125,18 @@ final class NameConstraintsTests: XCTestCase {
NameConstraintsPropertyValue(\.permittedURIDomains, value: [".apple.com"]),
NameConstraintsPropertyValue(\.permittedURIDomains, value: [".example.com", ".apple.com"]),
]
// This will set the properties to the above values in order (and in reversed order).
// After it sets each property it asserts that the previous latest value of other properties are still set
// to their previous latest values and are not modified.
var nameConstraints = NameConstraints()
var latestValueForProperty: [PartialKeyPath<NameConstraints>: NameConstraintsPropertyValue] = [:]
for test in tests + tests.reversed() {
test.setValue(&nameConstraints)
latestValueForProperty[test.property] = test
let newNameConstraints = NameConstraints(
permittedDNSDomains: nameConstraints.permittedDNSDomains,
excludedDNSDomains: nameConstraints.excludedDNSDomains,
@@ -139,7 +147,7 @@ final class NameConstraintsTests: XCTestCase {
permittedURIDomains: nameConstraints.permittedURIDomains,
forbiddenURIDomains: nameConstraints.forbiddenURIDomains
)
for latestValue in latestValueForProperty.values {
latestValue.assertValueIsSet(nameConstraints)
latestValue.assertValueIsSet(newNameConstraints)
+203 -128
View File
@@ -32,7 +32,7 @@ actor TestRequester: OCSPRequester {
private let file: StaticString
private let line: UInt
var queryCount: Int = 0
init(
query: @escaping @Sendable (OCSPRequest, String) async -> QueryResult,
file: StaticString = #file,
@@ -42,7 +42,7 @@ actor TestRequester: OCSPRequester {
self.file = file
self.line = line
}
func query(request requestDerEncoded: [UInt8], uri: String) async -> OCSPRequesterQueryResult {
queryCount += 1
let request: OCSPRequest
@@ -111,9 +111,7 @@ struct AssertNoThrowRequester<Wrapped: OCSPRequester>: OCSPRequester {
XCTFail("test query closure throw hard failure \(error)", file: file, line: line)
return .terminalError(error)
}
}
}
@@ -124,7 +122,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
CommonName("Swift Certificate Test CA 1")
}
private static let ca1PrivateKey = P384.Signing.PrivateKey()
private static func ca(ocspServer: String? = nil) -> Certificate {
try! Certificate(
version: .v3,
@@ -140,12 +138,15 @@ final class OCSPVerifierPolicyTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))
)
if let ocspServer {
AuthorityInformationAccess([
AuthorityInformationAccess.AccessDescription(
method: .ocspServer,
location: GeneralName.uniformResourceIdentifier(ocspServer))
location: GeneralName.uniformResourceIdentifier(ocspServer)
)
])
}
},
@@ -153,7 +154,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
)
}
private static let ca1: Certificate = ca()
fileprivate static let intermediatePrivateKey = P384.Signing.PrivateKey()
private static let leafPrivateKey = P384.Signing.PrivateKey()
private static func certificate(
@@ -183,14 +184,15 @@ final class OCSPVerifierPolicyTests: XCTestCase {
AuthorityInformationAccess([
AuthorityInformationAccess.AccessDescription(
method: .ocspServer,
location: GeneralName.uniformResourceIdentifier(ocspServer))
location: GeneralName.uniformResourceIdentifier(ocspServer)
)
])
}
},
issuerPrivateKey: .init(issuerPrivateKey)
)
}
fileprivate static let intermediate1Name = try! DistinguishedName {
CountryName("US")
OrganizationName("Apple")
@@ -201,7 +203,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
OrganizationName("Apple")
CommonName("localhost")
}
private static func intermediate(ocspServer: String? = nil) -> Certificate {
certificate(
subject: intermediate1Name,
@@ -212,7 +214,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
ocspServer: ocspServer
)
}
private static func leaf(ocspServer: String? = nil) -> Certificate {
certificate(
subject: localhostLeafName,
@@ -223,17 +225,19 @@ final class OCSPVerifierPolicyTests: XCTestCase {
ocspServer: ocspServer
)
}
private static let chainWithSingleCertWithOCSP = [
leaf(ocspServer: responderURI),
intermediate(),
]
private static let responderURI = "http://ocsp.apple.com/path"
fileprivate static let responderId = ResponderID.byName(try! DistinguishedName {
CommonName("Swift OCSP Test Responder")
})
fileprivate static let responderId = ResponderID.byName(
try! DistinguishedName {
CommonName("Swift OCSP Test Responder")
}
)
private static let responderIntermediate1Name = try! DistinguishedName {
CountryName("US")
OrganizationName("Apple")
@@ -252,14 +256,14 @@ final class OCSPVerifierPolicyTests: XCTestCase {
extensions: Certificate.Extensions {},
issuerPrivateKey: .init(ca1PrivateKey)
)
private let validationTime = Date()
private enum ExpectedVerificationResult {
case failsToMeetPolicy
case meetsPolicy
}
private func assertChain(
soft: ExpectedVerificationResult,
hard: ExpectedVerificationResult,
@@ -272,19 +276,49 @@ final class OCSPVerifierPolicyTests: XCTestCase {
) async {
switch soft {
case .failsToMeetPolicy:
await self.assertChainFailsToMeetPolicy(mode: .soft, chain: chain, requester: requester(), expectedQueryCount: expectedQueryCount, file: file, line: line)
await self.assertChainFailsToMeetPolicy(
mode: .soft,
chain: chain,
requester: requester(),
expectedQueryCount: expectedQueryCount,
file: file,
line: line
)
case .meetsPolicy:
await self.assertChainMeetsPolicy(mode: .soft, chain: chain, requester: requester(), expectedQueryCount: expectedQueryCount, validationTime: validationTime, file: file, line: line)
await self.assertChainMeetsPolicy(
mode: .soft,
chain: chain,
requester: requester(),
expectedQueryCount: expectedQueryCount,
validationTime: validationTime,
file: file,
line: line
)
}
switch hard {
case .failsToMeetPolicy:
await self.assertChainFailsToMeetPolicy(mode: .hard, chain: chain, requester: requester(), expectedQueryCount: expectedQueryCount, file: file, line: line)
await self.assertChainFailsToMeetPolicy(
mode: .hard,
chain: chain,
requester: requester(),
expectedQueryCount: expectedQueryCount,
file: file,
line: line
)
case .meetsPolicy:
await self.assertChainMeetsPolicy(mode: .hard, chain: chain, requester: requester(), expectedQueryCount: expectedQueryCount, validationTime: validationTime, file: file, line: line)
await self.assertChainMeetsPolicy(
mode: .hard,
chain: chain,
requester: requester(),
expectedQueryCount: expectedQueryCount,
validationTime: validationTime,
file: file,
line: line
)
}
}
private func assertChainMeetsPolicy(
mode: OCSPFailureMode = .hard,
chain: [Certificate],
@@ -310,7 +344,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
XCTAssertEqual(queryCount, expectedQueryCount, "unexpected requester query count", file: file, line: line)
}
}
private func printChainForDebugging(_ chain: [Certificate]) {
print("chain:")
for certificate in chain {
@@ -325,14 +359,14 @@ final class OCSPVerifierPolicyTests: XCTestCase {
print("failed to serialise chain \(error)")
}
}
private func assertChainFailsToMeetPolicy(
mode: OCSPFailureMode = .hard,
chain: [Certificate],
requester: some OCSPRequester,
expectedQueryCount: Int = 1,
validationTime: Date? = nil,
file: StaticString = #file,
line: UInt = #line
) async {
@@ -349,10 +383,16 @@ final class OCSPVerifierPolicyTests: XCTestCase {
}
if let testRequest = requester as? TestRequester {
let actualQueryCount = await testRequest.queryCount
XCTAssertEqual(actualQueryCount, expectedQueryCount, "unexpected requester query count", file: file, line: line)
XCTAssertEqual(
actualQueryCount,
expectedQueryCount,
"unexpected requester query count",
file: file,
line: line
)
}
}
func testSingleCertWithOCSP() async {
let now = self.validationTime
await self.assertChain(
@@ -365,21 +405,25 @@ final class OCSPVerifierPolicyTests: XCTestCase {
let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce)
XCTAssertEqual(request.tbsRequest.requestList.count, 1)
let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first)
return .successful(try .signed(
producedAt: .init(validationTime),
responses: [OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)]) {
return .successful(
try .signed(
producedAt: .init(validationTime),
responses: [
OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)
]
) {
nonce
}
)
}
)
}
func testWrongNonce() async {
let now = self.validationTime
await self.assertChain(
@@ -392,21 +436,25 @@ final class OCSPVerifierPolicyTests: XCTestCase {
XCTAssertNotNil(try request.tbsRequest.requestExtensions?.ocspNonce)
XCTAssertEqual(request.tbsRequest.requestList.count, 1)
let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first)
return .successful(try .signed(
producedAt: .init(validationTime),
responses: [OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)]) {
return .successful(
try .signed(
producedAt: .init(validationTime),
responses: [
OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)
]
) {
OCSPNonce()
}
)
}
)
}
func testRevokedCert() async {
let now = self.validationTime
await self.assertChain(
@@ -419,24 +467,30 @@ final class OCSPVerifierPolicyTests: XCTestCase {
let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce)
XCTAssertEqual(request.tbsRequest.requestList.count, 1)
let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first)
return .successful(try .signed(
producedAt: .init(validationTime),
responses: [OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .revoked(.init(
revocationTime: .init(now),
revocationReason: .unspecified
)),
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)]) {
return .successful(
try .signed(
producedAt: .init(validationTime),
responses: [
OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .revoked(
.init(
revocationTime: .init(now),
revocationReason: .unspecified
)
),
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)
]
) {
nonce
}
)
}
)
}
func testInvalidResponderCertChain() async {
let now = self.validationTime
await self.assertChain(
@@ -449,24 +503,28 @@ final class OCSPVerifierPolicyTests: XCTestCase {
let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce)
XCTAssertEqual(request.tbsRequest.requestList.count, 1)
let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first)
return .successful(try .signed(
responderID: .byName(Self.invalidResponderIntermediate1.subject),
producedAt: .init(validationTime),
responses: [OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)],
privateKey: Self.responderIntermediate1PrivateKey,
certs: [Self.invalidResponderIntermediate1]) {
return .successful(
try .signed(
responderID: .byName(Self.invalidResponderIntermediate1.subject),
producedAt: .init(validationTime),
responses: [
OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)
],
privateKey: Self.responderIntermediate1PrivateKey,
certs: [Self.invalidResponderIntermediate1]
) {
nonce
}
)
}
)
}
func testResponderSignatureAlgorithmIdentifierMismatch() async {
let now = self.validationTime
await self.assertChain(
@@ -479,29 +537,31 @@ final class OCSPVerifierPolicyTests: XCTestCase {
let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce)
XCTAssertEqual(request.tbsRequest.requestList.count, 1)
let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first)
let responseData = OCSPResponseData(
version: .v1,
responderID: Self.responderId,
producedAt: .init(Date()),
responses: [OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)],
responses: [
OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)
],
responseExtensions: try .init {
nonce
}
)
var serializer = DER.Serializer()
try serializer.serialize(responseData)
let tbsCertificateBytes = serializer.serializedBytes[...]
let digest = SHA384.hash(data: tbsCertificateBytes)
let signature = try Self.intermediatePrivateKey.signature(for: digest)
let response = try BasicOCSPResponse(
responseData: responseData,
// signature digest was creating using SHA384 but we specify the wrong identifier SHA256
@@ -513,7 +573,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
}
)
}
func testResponseDoesNotIncludeResponseForRequestedCert() async {
let now = self.validationTime
await self.assertChain(
@@ -525,26 +585,30 @@ final class OCSPVerifierPolicyTests: XCTestCase {
XCTAssertNil(request.signature)
let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce)
XCTAssertEqual(request.tbsRequest.requestList.count, 1)
return .successful(try .signed(
producedAt: .init(validationTime),
responses: [OCSPSingleResponse(
certID: .init(
hashAlgorithm: .init(algorithm: .sha1NoSign, parameters: nil),
issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4][...]),
issuerKeyHash: .init(contentBytes: [6, 7, 8, 9, 10][...]),
serialNumber: .init()
),
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)]) {
return .successful(
try .signed(
producedAt: .init(validationTime),
responses: [
OCSPSingleResponse(
certID: .init(
hashAlgorithm: .init(algorithm: .sha1NoSign, parameters: nil),
issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4][...]),
issuerKeyHash: .init(contentBytes: [6, 7, 8, 9, 10][...]),
serialNumber: .init()
),
certStatus: .good,
thisUpdate: .init(now - .days(1)),
nextUpdate: .init(now + .days(1))
)
]
) {
nonce
}
)
}
)
}
func testShouldNotQueryResponderIfNoOCSPServerIsDefined() async {
await self.assertChain(
soft: .meetsPolicy,
@@ -561,7 +625,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
expectedQueryCount: 0
)
}
func testLastCertificateIsNotAllowedToHaveOCSP() async {
await self.assertChain(
soft: .failsToMeetPolicy,
@@ -578,7 +642,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
expectedQueryCount: 0
)
}
func testDoesNotFailOnSoftFailure() async {
await self.assertChain(
soft: .meetsPolicy,
@@ -590,7 +654,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
}
)
}
func testFailsOnTerminalError() async {
await self.assertChain(
soft: .failsToMeetPolicy,
@@ -602,7 +666,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
}
)
}
func testTimeValidation() async {
func responseWithCertStatusGood(
producedAt: Date = self.validationTime,
@@ -615,20 +679,24 @@ final class OCSPVerifierPolicyTests: XCTestCase {
let nonce = try XCTUnwrap(request.tbsRequest.requestExtensions?.ocspNonce)
XCTAssertEqual(request.tbsRequest.requestList.count, 1)
let singleRequest = try XCTUnwrap(request.tbsRequest.requestList.first)
return .successful(try .signed(
producedAt: .init(producedAt),
responses: [OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(thisUpdate),
nextUpdate: nextUpdate.map { .init($0) }
)]) {
return .successful(
try .signed(
producedAt: .init(producedAt),
responses: [
OCSPSingleResponse(
certID: singleRequest.certID,
certStatus: .good,
thisUpdate: .init(thisUpdate),
nextUpdate: nextUpdate.map { .init($0) }
)
]
) {
nonce
}
)
}
}
/// produced at is in the future
await self.assertChain(
soft: .meetsPolicy,
@@ -640,7 +708,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
nextUpdate: self.validationTime + 1
)
)
/// is almost exactly in the current time window
await self.assertChain(
soft: .meetsPolicy,
@@ -651,7 +719,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
nextUpdate: self.validationTime + 1
)
)
/// is almost exactly in the current time window with leeway
await self.assertChain(
soft: .meetsPolicy,
@@ -663,7 +731,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
nextUpdate: self.validationTime - OCSPResponseData.defaultTrustTimeLeeway + 2
)
)
/// no next update
await self.assertChain(
soft: .meetsPolicy,
@@ -685,7 +753,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
nextUpdate: self.validationTime + OCSPResponseData.defaultTrustTimeLeeway + 2
)
)
/// next update is in the past
await self.assertChain(
soft: .meetsPolicy,
@@ -707,7 +775,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
)
)
}
func testWWWDotAppleDotComResponder() async throws {
actor StaticOCSPRequester: OCSPRequester {
var responses: [OCSPResponse]
@@ -730,7 +798,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
}
}
}
func load(_ filePath: String, extension: String) throws -> [UInt8] {
guard let url = Bundle.module.url(forResource: filePath, withExtension: `extension`) else {
struct CouldNotGetURLFromBundle: Error {
@@ -739,7 +807,7 @@ final class OCSPVerifierPolicyTests: XCTestCase {
}
throw CouldNotGetURLFromBundle(filePath: filePath, extension: `extension`)
}
return Array(try Data(contentsOf: url))
}
func loadCertificate(_ filePath: String, extension: String) throws -> Certificate {
@@ -748,14 +816,19 @@ final class OCSPVerifierPolicyTests: XCTestCase {
func loadOCSPResponse(_ filePath: String, extension: String) throws -> OCSPResponse {
try OCSPResponse(derEncoded: load(filePath, extension: `extension`))
}
let root = try loadCertificate("www.apple.com.root", extension: "der")
let intermediate = try loadCertificate("www.apple.com.intermediate", extension: "der")
let leaf = try loadCertificate("www.apple.com", extension: "der")
let ocspResponseLeaf = try loadOCSPResponse("www.apple.com.ocsp-response", extension: "der")
let ocspResponseIntermediate = try loadOCSPResponse("www.apple.com.intermediate.ocsp-response", extension: "der")
let timeOfOCSPRequest = try Date(GeneralizedTime(year: 2023, month: 3, day: 15, hours: 15, minutes: 36, seconds: 0, fractionalSeconds: 0.0))
let ocspResponseIntermediate = try loadOCSPResponse(
"www.apple.com.intermediate.ocsp-response",
extension: "der"
)
let timeOfOCSPRequest = try Date(
GeneralizedTime(year: 2023, month: 3, day: 15, hours: 15, minutes: 36, seconds: 0, fractionalSeconds: 0.0)
)
await self.assertChain(
soft: .meetsPolicy,
hard: .meetsPolicy,
@@ -778,10 +851,10 @@ extension BasicOCSPResponse {
var serializer = DER.Serializer()
try serializer.serialize(responseData)
let tbsCertificateBytes = serializer.serializedBytes[...]
let digest = SHA384.hash(data: tbsCertificateBytes)
let signature = try privateKey.signature(for: digest)
return try .init(
responseData: responseData,
signatureAlgorithm: .ecdsaWithSHA384,
@@ -796,7 +869,9 @@ extension BasicOCSPResponse {
responses: [OCSPSingleResponse],
privateKey: P384.Signing.PrivateKey = OCSPVerifierPolicyTests.intermediatePrivateKey,
certs: [Certificate]? = [],
@ExtensionsBuilder responseExtensions: () throws -> Result<Certificate.Extensions, any Error> = { .success(Certificate.Extensions()) }
@ExtensionsBuilder responseExtensions: () throws -> Result<Certificate.Extensions, any Error> = {
.success(Certificate.Extensions())
}
) throws -> Self {
try .signed(
responseData: .init(
@@ -810,7 +885,7 @@ extension BasicOCSPResponse {
certs: certs
)
}
init(
responseData: OCSPResponseData,
signatureAlgorithm: AlgorithmIdentifier,
+221 -52
View File
@@ -37,32 +37,35 @@ final class OCSPTests: XCTestCase {
let parsed = try ASN1Object(derEncoded: serializer.serializedBytes)
XCTAssertEqual(parsed, value)
}
func testRequestRoundtrip() throws {
let ocspRequest = OCSPRequest(
tbsRequest: OCSPTBSRequest(
version: .v1,
requestorName: GeneralName.dnsName("swift.org"),
requestList: [OCSPSingleRequest(
certID: OCSPCertID(
hashAlgorithm: .ecdsaWithSHA256,
issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4, 5, 6, 7, 8]),
issuerKeyHash: .init(contentBytes: [10, 11, 12, 13, 14, 15, 16, 17, 18]),
serialNumber: .init(bytes: [20, 21, 22, 23, 24, 25, 26, 27, 28])
),
singleRequestExtensions: nil
)],
requestExtensions: nil),
requestList: [
OCSPSingleRequest(
certID: OCSPCertID(
hashAlgorithm: .ecdsaWithSHA256,
issuerNameHash: .init(contentBytes: [0, 1, 2, 3, 4, 5, 6, 7, 8]),
issuerKeyHash: .init(contentBytes: [10, 11, 12, 13, 14, 15, 16, 17, 18]),
serialNumber: .init(bytes: [20, 21, 22, 23, 24, 25, 26, 27, 28])
),
singleRequestExtensions: nil
)
],
requestExtensions: nil
),
signature: OCSPSignature(
algorithmIIdentifier: .p256PublicKey,
signature: .init(bytes: [31, 32, 33, 34, 35, 36, 37, 38]),
certs: nil
)
)
try assertRoundTrips(ocspRequest)
}
func testResponderIDByNameRoundTrips() throws {
let id = ResponderID.byName(
try DistinguishedName {
@@ -88,7 +91,9 @@ final class OCSPTests: XCTestCase {
}
)
let expected: [UInt8] = [161, 22, 48, 20, 49, 18, 48, 16, 6, 3, 85, 4, 3, 12, 9, 82, 101, 115, 112, 111, 110, 100, 101, 114]
let expected: [UInt8] = [
161, 22, 48, 20, 49, 18, 48, 16, 6, 3, 85, 4, 3, 12, 9, 82, 101, 115, 112, 111, 110, 100, 101, 114,
]
var serializer = DER.Serializer()
try serializer.serialize(id)
@@ -129,7 +134,7 @@ final class OCSPTests: XCTestCase {
let expected: [UInt8] = [
48, 39, 48, 19, 6, 7, 42, 134, 72, 206, 61, 2, 1, 6, 8, 42, 134,
72, 206, 61, 3, 1, 7, 4, 4, 1, 2, 3, 4, 4, 4, 5, 6, 7, 8, 2, 4,
9, 10, 11, 12
9, 10, 11, 12,
]
var serializer = DER.Serializer()
@@ -174,7 +179,7 @@ final class OCSPTests: XCTestCase {
var serializer = DER.Serializer()
try serializer.serialize(fixture)
var expected = Array<UInt8>()
var expected = [UInt8]()
expected.writeIdentifier(ASN1Identifier.enumerated, constructed: false)
expected.append(1)
expected.append(UInt8(expectedPayload))
@@ -184,7 +189,15 @@ final class OCSPTests: XCTestCase {
func testOCSPRevokedInfoRoundTrips() throws {
var revokedInfo = OCSPRevokedInfo(
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
revocationTime: try .init(
year: 2021,
month: 01,
day: 02,
hours: 03,
minutes: 04,
seconds: 05,
fractionalSeconds: 0.06
),
revocationReason: nil
)
try self.assertRoundTrips(revokedInfo)
@@ -195,10 +208,20 @@ final class OCSPTests: XCTestCase {
func testOCSPRevokedInfoSerializesWithoutReason() throws {
let revokedInfo = OCSPRevokedInfo(
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
revocationTime: try .init(
year: 2021,
month: 01,
day: 02,
hours: 03,
minutes: 04,
seconds: 05,
fractionalSeconds: 0.06
),
revocationReason: nil
)
let expected: [UInt8] = [48, 20, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90]
let expected: [UInt8] = [
48, 20, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90,
]
var serializer = DER.Serializer()
try serializer.serialize(revokedInfo)
@@ -207,10 +230,20 @@ final class OCSPTests: XCTestCase {
func testOCSPRevokedInfoSerializesWithReason() throws {
let revokedInfo = OCSPRevokedInfo(
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
revocationTime: try .init(
year: 2021,
month: 01,
day: 02,
hours: 03,
minutes: 04,
seconds: 05,
fractionalSeconds: 0.06
),
revocationReason: .cessationOfOperation
)
let expected: [UInt8] = [48, 25, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90, 160, 3, 10, 1, 5]
let expected: [UInt8] = [
48, 25, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90, 160, 3, 10, 1, 5,
]
var serializer = DER.Serializer()
try serializer.serialize(revokedInfo)
@@ -222,8 +255,17 @@ final class OCSPTests: XCTestCase {
.good,
.revoked(
OCSPRevokedInfo(
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
revocationReason: .cessationOfOperation)
revocationTime: try .init(
year: 2021,
month: 01,
day: 02,
hours: 03,
minutes: 04,
seconds: 05,
fractionalSeconds: 0.06
),
revocationReason: .cessationOfOperation
)
),
.unknown,
]
@@ -245,10 +287,21 @@ final class OCSPTests: XCTestCase {
func testOCSPCertStatusRevokedSerializes() throws {
let value = OCSPCertStatus.revoked(
OCSPRevokedInfo(
revocationTime: try .init(year: 2021, month: 01, day: 02, hours: 03, minutes: 04, seconds: 05, fractionalSeconds: 0.06),
revocationReason: .cessationOfOperation)
revocationTime: try .init(
year: 2021,
month: 01,
day: 02,
hours: 03,
minutes: 04,
seconds: 05,
fractionalSeconds: 0.06
),
revocationReason: .cessationOfOperation
)
)
let expected: [UInt8] = [161, 25, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90, 160, 3, 10, 1, 5]
let expected: [UInt8] = [
161, 25, 24, 18, 50, 48, 50, 49, 48, 49, 48, 50, 48, 51, 48, 52, 48, 53, 46, 48, 54, 90, 160, 3, 10, 1, 5,
]
var serializer = DER.Serializer()
try serializer.serialize(value)
@@ -274,7 +327,15 @@ final class OCSPTests: XCTestCase {
serialNumber: .init(bytes: [9, 10, 11, 12])
),
certStatus: .good,
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
thisUpdate: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
nextUpdate: nil,
extensions: nil
),
@@ -286,8 +347,24 @@ final class OCSPTests: XCTestCase {
serialNumber: .init(bytes: [9, 10, 11, 12])
),
certStatus: .good,
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
thisUpdate: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
nextUpdate: try .init(
year: 8,
month: 9,
day: 10,
hours: 11,
minutes: 12,
seconds: 13,
fractionalSeconds: 0.14
),
extensions: nil
),
.init(
@@ -298,7 +375,15 @@ final class OCSPTests: XCTestCase {
serialNumber: .init(bytes: [9, 10, 11, 12])
),
certStatus: .good,
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
thisUpdate: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
nextUpdate: nil,
extensions: try .init {
OCSPNonce()
@@ -312,8 +397,24 @@ final class OCSPTests: XCTestCase {
serialNumber: .init(bytes: [9, 10, 11, 12])
),
certStatus: .good,
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
thisUpdate: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
nextUpdate: try .init(
year: 8,
month: 9,
day: 10,
hours: 11,
minutes: 12,
seconds: 13,
fractionalSeconds: 0.14
),
extensions: try .init {
OCSPNonce()
}
@@ -341,7 +442,15 @@ final class OCSPTests: XCTestCase {
),
certStatus: .good,
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
nextUpdate: try .init(
year: 8,
month: 9,
day: 10,
hours: 11,
minutes: 12,
seconds: 13,
fractionalSeconds: 0.14
),
extensions: try .init {
OCSPNonce()
}
@@ -355,27 +464,59 @@ final class OCSPTests: XCTestCase {
let fixtures: [OCSPResponseData] = [
.init(
responderID: responderID,
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
producedAt: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
responses: [response, response, response],
responseExtensions: nil
),
.init(
version: .v1,
responderID: responderID,
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
producedAt: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
responses: [response, response, response],
responseExtensions: nil
),
.init(
responderID: responderID,
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
producedAt: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
responses: [response, response, response],
responseExtensions: extensions
),
.init(
version: .v1,
responderID: responderID,
producedAt: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
producedAt: try .init(
year: 1,
month: 2,
day: 3,
hours: 4,
minutes: 5,
seconds: 6,
fractionalSeconds: 0.7
),
responses: [response, response, response],
responseExtensions: extensions
),
@@ -402,7 +543,15 @@ final class OCSPTests: XCTestCase {
),
certStatus: .good,
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
nextUpdate: try .init(
year: 8,
month: 9,
day: 10,
hours: 11,
minutes: 12,
seconds: 13,
fractionalSeconds: 0.14
),
extensions: try .init {
Certificate.Extension(oid: [1, 2, 3, 4], critical: true, value: [5, 6, 7, 8])
}
@@ -431,7 +580,10 @@ final class OCSPTests: XCTestCase {
}
func testOCSPResponseBytesRoundTrips() throws {
let bytes = OCSPResponseBytes(responseType: .OCSP.basicResponse, response: ASN1OctetString(contentBytes: [1, 2, 3, 4]))
let bytes = OCSPResponseBytes(
responseType: .OCSP.basicResponse,
response: ASN1OctetString(contentBytes: [1, 2, 3, 4])
)
try self.assertRoundTrips(bytes)
}
@@ -451,7 +603,15 @@ final class OCSPTests: XCTestCase {
),
certStatus: .good,
thisUpdate: try .init(year: 1, month: 2, day: 3, hours: 4, minutes: 5, seconds: 6, fractionalSeconds: 0.7),
nextUpdate: try .init(year: 8, month: 9, day: 10, hours: 11, minutes: 12, seconds: 13, fractionalSeconds: 0.14),
nextUpdate: try .init(
year: 8,
month: 9,
day: 10,
hours: 11,
minutes: 12,
seconds: 13,
fractionalSeconds: 0.14
),
extensions: try .init {
Certificate.Extension(oid: [1, 2, 3, 4], critical: true, value: [5, 6, 7, 8])
}
@@ -484,7 +644,10 @@ final class OCSPTests: XCTestCase {
}
func testCannotDecodeBasicOCSPResponseWithWrongOID() throws {
let bytes = OCSPResponseBytes(responseType: .AlgorithmIdentifier.idEcPublicKey, response: ASN1OctetString(contentBytes: [1, 2, 3, 4]))
let bytes = OCSPResponseBytes(
responseType: .AlgorithmIdentifier.idEcPublicKey,
response: ASN1OctetString(contentBytes: [1, 2, 3, 4])
)
XCTAssertThrowsError(try BasicOCSPResponse(decoding: bytes))
}
@@ -517,21 +680,27 @@ final class OCSPTests: XCTestCase {
.tryLater,
.internalError,
.unauthorized,
.successful(try .init(
responseData: .init(
responderID: .byName(try DistinguishedName {
CommonName("Responder")
}),
producedAt: .init(Date()),
responses: []),
signatureAlgorithm: .p384PublicKey,
signature: ASN1BitString(bytes: [1, 2, 3, 4]), certs: nil
)),
.successful(
try .init(
responseData: .init(
responderID: .byName(
try DistinguishedName {
CommonName("Responder")
}
),
producedAt: .init(Date()),
responses: []
),
signatureAlgorithm: .p384PublicKey,
signature: ASN1BitString(bytes: [1, 2, 3, 4]),
certs: nil
)
),
]
for fixture in fixtures {
try self.assertRoundTrips(fixture)
}
}
}
+25 -14
View File
@@ -19,7 +19,7 @@ import Crypto
import _CryptoExtras
@testable import X509
fileprivate protocol Key {
private protocol Key {
associatedtype Wrapped: WrappedKey
init(derRepresentation: some DataProtocol) throws
init(pemRepresentation: String) throws
@@ -55,19 +55,17 @@ extension _CryptoExtras._RSA.Signing.PrivateKey: Key {
extension Crypto.P256.Signing.PublicKey: Key {
var wrapped: Certificate.PublicKey { .init(self) }
}
extension Crypto.P384.Signing.PublicKey: Key {
extension Crypto.P384.Signing.PublicKey: Key {
var wrapped: Certificate.PublicKey { .init(self) }
}
extension Crypto.P521.Signing.PublicKey: Key {
extension Crypto.P521.Signing.PublicKey: Key {
var wrapped: Certificate.PublicKey { .init(self) }
}
extension _CryptoExtras._RSA.Signing.PublicKey: Key {
extension _CryptoExtras._RSA.Signing.PublicKey: Key {
var wrapped: Certificate.PublicKey { .init(self) }
}
fileprivate protocol WrappedKey: Equatable {
private protocol WrappedKey: Equatable {
init(pemEncoded: String) throws
func serializeAsPEM() throws -> PEMDocument
}
@@ -75,7 +73,6 @@ fileprivate protocol WrappedKey: Equatable {
extension Certificate.PublicKey: WrappedKey {}
extension Certificate.PrivateKey: WrappedKey {}
final class PEMTests: XCTestCase {
fileprivate func assertPEMRoundtrip(key: some Key, file: StaticString = #filePath, line: UInt = #line) throws {
let initialPEMString = key.pemRepresentation
@@ -83,27 +80,41 @@ final class PEMTests: XCTestCase {
XCTAssertEqual(key.wrapped, wrapped, "Wrapper mismatch after one roundtrip for \(key)", file: file, line: line)
let pemDocument = try key.wrapped.serializeAsPEM()
let initialPEMDocument = try PEMDocument(pemString: initialPEMString)
XCTAssertEqual(pemDocument.discriminator, initialPEMDocument.discriminator, "PEM discriminator mismatch after one roundtrip for \(key)", file: file, line: line)
XCTAssertEqual(pemDocument.pemString, initialPEMDocument.pemString, "PEM string mismatch after one roundtrip for \(key)", file: file, line: line)
XCTAssertEqual(
pemDocument.discriminator,
initialPEMDocument.discriminator,
"PEM discriminator mismatch after one roundtrip for \(key)",
file: file,
line: line
)
XCTAssertEqual(
pemDocument.pemString,
initialPEMDocument.pemString,
"PEM string mismatch after one roundtrip for \(key)",
file: file,
line: line
)
}
func testPublicKeys() throws {
try assertPEMRoundtrip(key: P256.Signing.PrivateKey().publicKey)
try assertPEMRoundtrip(key: P384.Signing.PrivateKey().publicKey)
try assertPEMRoundtrip(key: P521.Signing.PrivateKey().publicKey)
try assertPEMRoundtrip(key: _RSA.Signing.PrivateKey(keySize: .bits2048).publicKey)
}
func testPrivateKeys() throws {
try assertPEMRoundtrip(key: P256.Signing.PrivateKey())
try assertPEMRoundtrip(key: P384.Signing.PrivateKey())
try assertPEMRoundtrip(key: P521.Signing.PrivateKey())
try assertPEMRoundtrip(key: _RSA.Signing.PrivateKey(keySize: .bits2048))
}
func testRSAPrivateKey() throws {
// generated with "openssl genpkey -algorithm rsa"
let rsaKey = try String(contentsOf: XCTUnwrap(Bundle.module.url(forResource: "PEMTestRSACertificate", withExtension: "pem")))
let rsaKey = try String(
contentsOf: XCTUnwrap(Bundle.module.url(forResource: "PEMTestRSACertificate", withExtension: "pem"))
)
let privateKey = try Certificate.PrivateKey(pemEncoded: rsaKey)
guard case .rsa = privateKey.backing else {
XCTFail("parsed as wrong key type \(privateKey)")
+127 -91
View File
@@ -18,10 +18,10 @@ import SwiftASN1
@testable import X509
import Crypto
fileprivate struct Policy: VerifierPolicy {
private struct Policy: VerifierPolicy {
var result: PolicyEvaluationResult = .meetsPolicy
var verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []
mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
result
}
@@ -29,85 +29,121 @@ fileprivate struct Policy: VerifierPolicy {
final class PolicyBuilderTests: XCTestCase {
func testVerifyingCriticalExtensions_empty() {
XCTAssertEqual(Set(AnyPolicy {
}.verifyingCriticalExtensions), [
])
XCTAssertEqual(
Set(
AnyPolicy {
}.verifyingCriticalExtensions
),
[]
)
}
func testVerifyingCriticalExtensions_concatenation() {
XCTAssertEqual(Set(AnyPolicy {
Policy(verifyingCriticalExtensions: [[1]])
}.verifyingCriticalExtensions), [
[1],
])
XCTAssertEqual(Set(AnyPolicy {
Policy(verifyingCriticalExtensions: [[1]])
Policy(verifyingCriticalExtensions: [[2]])
}.verifyingCriticalExtensions), [
[1],
[2],
])
XCTAssertEqual(Set(AnyPolicy {
Policy(verifyingCriticalExtensions: [[1]])
Policy(verifyingCriticalExtensions: [[2]])
Policy(verifyingCriticalExtensions: [[3]])
}.verifyingCriticalExtensions), [
[1],
[2],
[3],
])
XCTAssertEqual(
Set(
AnyPolicy {
Policy(verifyingCriticalExtensions: [[1]])
}.verifyingCriticalExtensions
),
[
[1]
]
)
XCTAssertEqual(
Set(
AnyPolicy {
Policy(verifyingCriticalExtensions: [[1]])
Policy(verifyingCriticalExtensions: [[2]])
}.verifyingCriticalExtensions
),
[
[1],
[2],
]
)
XCTAssertEqual(
Set(
AnyPolicy {
Policy(verifyingCriticalExtensions: [[1]])
Policy(verifyingCriticalExtensions: [[2]])
Policy(verifyingCriticalExtensions: [[3]])
}.verifyingCriticalExtensions
),
[
[1],
[2],
[3],
]
)
}
func testVerifyingCriticalExtensions_if() {
let `true` = true
let `false` = false
XCTAssertEqual(Set(AnyPolicy {
if `true` {
Policy(verifyingCriticalExtensions: [[1]])
}
}.verifyingCriticalExtensions), [
[1],
])
XCTAssertEqual(Set(AnyPolicy {
if `false` {
Policy(verifyingCriticalExtensions: [[1]])
}
}.verifyingCriticalExtensions), [
])
XCTAssertEqual(
Set(
AnyPolicy {
if `true` {
Policy(verifyingCriticalExtensions: [[1]])
}
}.verifyingCriticalExtensions
),
[
[1]
]
)
XCTAssertEqual(
Set(
AnyPolicy {
if `false` {
Policy(verifyingCriticalExtensions: [[1]])
}
}.verifyingCriticalExtensions
),
[]
)
}
func testVerifyingCriticalExtensions_ifElse() {
let `true` = true
let `false` = false
XCTAssertEqual(Set(AnyPolicy {
if `true` {
Policy(verifyingCriticalExtensions: [[1]])
} else {
Policy(verifyingCriticalExtensions: [[2]])
}
}.verifyingCriticalExtensions), [
[1],
])
XCTAssertEqual(Set(AnyPolicy {
if `false` {
Policy(verifyingCriticalExtensions: [[1]])
} else {
Policy(verifyingCriticalExtensions: [[2]])
}
}.verifyingCriticalExtensions), [
[2],
])
XCTAssertEqual(
Set(
AnyPolicy {
if `true` {
Policy(verifyingCriticalExtensions: [[1]])
} else {
Policy(verifyingCriticalExtensions: [[2]])
}
}.verifyingCriticalExtensions
),
[
[1]
]
)
XCTAssertEqual(
Set(
AnyPolicy {
if `false` {
Policy(verifyingCriticalExtensions: [[1]])
} else {
Policy(verifyingCriticalExtensions: [[2]])
}
}.verifyingCriticalExtensions
),
[
[2]
]
)
}
private static let privateKey = P384.Signing.PrivateKey()
private static let certificate = try! Certificate(
version: .v3,
serialNumber: .init(),
@@ -128,11 +164,11 @@ final class PolicyBuilderTests: XCTestCase {
extensions: .init(),
issuerPrivateKey: .init(privateKey)
)
private let chain = UnverifiedCertificateChain([
certificate
])
private func assertMeetsPolicy(
@PolicyBuilder makePolicy: () throws -> some VerifierPolicy,
chain: UnverifiedCertificateChain? = nil,
@@ -160,50 +196,50 @@ final class PolicyBuilderTests: XCTestCase {
return
}
}
func testChainMeetsPolicyRequirements_empty() async {
await assertMeetsPolicy {
}
}
func testChainMeetsPolicyRequirements_concatenation() async {
await assertMeetsPolicy {
Policy(result: .meetsPolicy)
}
await assertMeetsPolicy {
Policy(result: .meetsPolicy)
Policy(result: .meetsPolicy)
}
await assertMeetsPolicy {
Policy(result: .meetsPolicy)
Policy(result: .meetsPolicy)
Policy(result: .meetsPolicy)
}
await assertFailsToMeetPolicy {
Policy(result: .failsToMeetPolicy(reason: ""))
}
await assertFailsToMeetPolicy {
Policy(result: .meetsPolicy)
Policy(result: .failsToMeetPolicy(reason: ""))
}
await assertFailsToMeetPolicy {
Policy(result: .failsToMeetPolicy(reason: ""))
Policy(result: .meetsPolicy)
}
await assertFailsToMeetPolicy {
Policy(result: .meetsPolicy)
Policy(result: .meetsPolicy)
Policy(result: .failsToMeetPolicy(reason: ""))
}
}
func testChainMeetsPolicyRequirements_if() async {
let `true` = true
let `false` = false
@@ -212,26 +248,26 @@ final class PolicyBuilderTests: XCTestCase {
Policy(result: .meetsPolicy)
}
}
await assertMeetsPolicy {
if `false` {
Policy(result: .meetsPolicy)
}
}
await assertFailsToMeetPolicy {
if `true` {
Policy(result: .failsToMeetPolicy(reason: ""))
}
}
await assertMeetsPolicy {
if `false` {
Policy(result: .failsToMeetPolicy(reason: ""))
}
}
}
func testChainMeetsPolicyRequirements_ifElse() async {
let `true` = true
let `false` = false
@@ -242,7 +278,7 @@ final class PolicyBuilderTests: XCTestCase {
Policy(result: .meetsPolicy)
}
}
await assertMeetsPolicy {
if `false` {
Policy(result: .meetsPolicy)
@@ -250,7 +286,7 @@ final class PolicyBuilderTests: XCTestCase {
Policy(result: .meetsPolicy)
}
}
await assertFailsToMeetPolicy {
if `true` {
Policy(result: .failsToMeetPolicy(reason: ""))
@@ -258,7 +294,7 @@ final class PolicyBuilderTests: XCTestCase {
Policy(result: .meetsPolicy)
}
}
await assertMeetsPolicy {
if `false` {
Policy(result: .failsToMeetPolicy(reason: ""))
@@ -266,7 +302,7 @@ final class PolicyBuilderTests: XCTestCase {
Policy(result: .meetsPolicy)
}
}
await assertMeetsPolicy {
if `true` {
Policy(result: .meetsPolicy)
@@ -274,7 +310,7 @@ final class PolicyBuilderTests: XCTestCase {
Policy(result: .failsToMeetPolicy(reason: ""))
}
}
await assertFailsToMeetPolicy {
if `false` {
Policy(result: .meetsPolicy)
@@ -283,7 +319,7 @@ final class PolicyBuilderTests: XCTestCase {
}
}
}
func testAnyPolicyTypeIsPreserved() {
// tested at compile time
let _: Verifier<AnyPolicy> = Verifier(rootCertificates: CertificateStore()) {
File diff suppressed because it is too large. Load diff
+203 -60
View File
@@ -45,7 +45,7 @@ final class SignatureTests: XCTestCase {
0x26, 0xB8, 0xEE, 0x6E, 0x2D, 0x4A, 0xF6, 0xC6, 0x66,
0x1F, 0x33, 0x9A, 0xDB, 0x92, 0x4A, 0xD5, 0xF5, 0x29,
0x13, 0xC6, 0x70, 0x62, 0x28, 0xBA, 0x23, 0x8C, 0xCF,
0x3D, 0x2F, 0xCB, 0x82, 0xE9, 0x7F
0x3D, 0x2F, 0xCB, 0x82, 0xE9, 0x7F,
]
let signature = try Certificate.Signature(
signatureAlgorithm: .ecdsaWithSHA384,
@@ -64,7 +64,7 @@ final class SignatureTests: XCTestCase {
0x06, 0xDF, 0xF7, 0x2A, 0x16, 0x1C, 0xA4, 0xB9, 0xC5, 0xC5, 0x32, 0xE0, 0x03, 0xE0, 0x1E, 0x82,
0x18, 0x38, 0x8B, 0xD7, 0x45, 0xD8, 0x0A, 0x6A, 0x6E, 0xE6, 0x00, 0x77, 0xFB, 0x02, 0x51, 0x7D,
0x22, 0xD8, 0x0A, 0x6E, 0x9A, 0x5B, 0x77, 0xDF, 0xF0, 0xFA, 0x41, 0xEC, 0x39, 0xDC, 0x75, 0xCA,
0x68, 0x07, 0x0C, 0x1F, 0xEA
0x68, 0x07, 0x0C, 0x1F, 0xEA,
]
let tbsCertificateBytes: [UInt8] = [
0x30, 0x82, 0x02, 0x4D, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00,
@@ -104,7 +104,7 @@ final class SignatureTests: XCTestCase {
0x2F, 0x2F, 0x78, 0x32, 0x2E, 0x63, 0x2E, 0x6C, 0x65, 0x6E, 0x63, 0x72, 0x2E, 0x6F, 0x72, 0x67,
0x2F, 0x30, 0x22, 0x06, 0x03, 0x55, 0x1D, 0x20, 0x04, 0x1B, 0x30, 0x19, 0x30, 0x08, 0x06, 0x06,
0x67, 0x81, 0x0C, 0x01, 0x02, 0x01, 0x30, 0x0D, 0x06, 0x0B, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82,
0xDF, 0x13, 0x01, 0x01, 0x01
0xDF, 0x13, 0x01, 0x01, 0x01,
]
let digest = SHA384.hash(data: tbsCertificateBytes)
@@ -116,7 +116,11 @@ final class SignatureTests: XCTestCase {
// The base test implementation for the hash function mismatch tests. This test case validates that, if the combination is valid, we can
// create and then verify a certificate signature using this pair of key and algorithm. If it's invalid, it confirms that we can't create
// a signature of this combination, and that attempting to validate a signature would also fail.
private func hashFunctionMismatchTest(privateKey: Certificate.PrivateKey, signatureAlgorithm: Certificate.SignatureAlgorithm, validCombination: Bool) throws {
private func hashFunctionMismatchTest(
privateKey: Certificate.PrivateKey,
signatureAlgorithm: Certificate.SignatureAlgorithm,
validCombination: Bool
) throws {
let name = try DistinguishedName {
CommonName("Hash function mismatch CA")
}
@@ -140,182 +144,321 @@ final class SignatureTests: XCTestCase {
extensions: extensions,
issuerPrivateKey: privateKey
)
XCTAssertTrue(validCombination, "Incorrectly able to create cert combining \(privateKey) and \(signatureAlgorithm)")
XCTAssertTrue(privateKey.publicKey.isValidSignature(certificate.signature, for: certificate), "Unable to validate signature combining \(privateKey) and \(signatureAlgorithm)")
XCTAssertTrue(
validCombination,
"Incorrectly able to create cert combining \(privateKey) and \(signatureAlgorithm)"
)
XCTAssertTrue(
privateKey.publicKey.isValidSignature(certificate.signature, for: certificate),
"Unable to validate signature combining \(privateKey) and \(signatureAlgorithm)"
)
} catch {
XCTAssertFalse(validCombination, "Unable to create cert combining \(privateKey) and \(signatureAlgorithm)")
}
}
func testHashFunctionMismatch_p256_ecdsaWithSHA256() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p256Key), signatureAlgorithm: .ecdsaWithSHA256, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p256Key),
signatureAlgorithm: .ecdsaWithSHA256,
validCombination: true
)
}
func testHashFunctionMismatch_p256_ecdsaWithSHA384() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p256Key), signatureAlgorithm: .ecdsaWithSHA384, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p256Key),
signatureAlgorithm: .ecdsaWithSHA384,
validCombination: true
)
}
func testHashFunctionMismatch_p256_ecdsaWithSHA512() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p256Key), signatureAlgorithm: .ecdsaWithSHA512, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p256Key),
signatureAlgorithm: .ecdsaWithSHA512,
validCombination: true
)
}
func testHashFunctionMismatch_p256_sha1WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p256Key), signatureAlgorithm: .sha1WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p256Key),
signatureAlgorithm: .sha1WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p256_sha256WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p256Key), signatureAlgorithm: .sha256WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p256Key),
signatureAlgorithm: .sha256WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p256_sha384WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p256Key), signatureAlgorithm: .sha384WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p256Key),
signatureAlgorithm: .sha384WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p256_sha512WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p256Key), signatureAlgorithm: .sha512WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p256Key),
signatureAlgorithm: .sha512WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p384_ecdsaWithSHA256() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p384Key), signatureAlgorithm: .ecdsaWithSHA256, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p384Key),
signatureAlgorithm: .ecdsaWithSHA256,
validCombination: true
)
}
func testHashFunctionMismatch_p384_ecdsaWithSHA384() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p384Key), signatureAlgorithm: .ecdsaWithSHA384, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p384Key),
signatureAlgorithm: .ecdsaWithSHA384,
validCombination: true
)
}
func testHashFunctionMismatch_p384_ecdsaWithSHA512() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p384Key), signatureAlgorithm: .ecdsaWithSHA512, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p384Key),
signatureAlgorithm: .ecdsaWithSHA512,
validCombination: true
)
}
func testHashFunctionMismatch_p384_sha1WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p384Key), signatureAlgorithm: .sha1WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p384Key),
signatureAlgorithm: .sha1WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p384_sha256WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p384Key), signatureAlgorithm: .sha256WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p384Key),
signatureAlgorithm: .sha256WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p384_sha384WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p384Key), signatureAlgorithm: .sha384WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p384Key),
signatureAlgorithm: .sha384WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p384_sha512WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p384Key), signatureAlgorithm: .sha512WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p384Key),
signatureAlgorithm: .sha512WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p521_ecdsaWithSHA256() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p521Key), signatureAlgorithm: .ecdsaWithSHA256, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p521Key),
signatureAlgorithm: .ecdsaWithSHA256,
validCombination: true
)
}
func testHashFunctionMismatch_p521_ecdsaWithSHA384() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p521Key), signatureAlgorithm: .ecdsaWithSHA384, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p521Key),
signatureAlgorithm: .ecdsaWithSHA384,
validCombination: true
)
}
func testHashFunctionMismatch_p521_ecdsaWithSHA512() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p521Key), signatureAlgorithm: .ecdsaWithSHA512, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p521Key),
signatureAlgorithm: .ecdsaWithSHA512,
validCombination: true
)
}
func testHashFunctionMismatch_p521_sha1WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p521Key), signatureAlgorithm: .sha1WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p521Key),
signatureAlgorithm: .sha1WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p521_sha256WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p521Key), signatureAlgorithm: .sha256WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p521Key),
signatureAlgorithm: .sha256WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p521_sha384WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p521Key), signatureAlgorithm: .sha384WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p521Key),
signatureAlgorithm: .sha384WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_p521_sha512WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.p521Key), signatureAlgorithm: .sha512WithRSAEncryption, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.p521Key),
signatureAlgorithm: .sha512WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_rsa_ecdsaWithSHA256() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.rsaKey), signatureAlgorithm: .ecdsaWithSHA256, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.rsaKey),
signatureAlgorithm: .ecdsaWithSHA256,
validCombination: false
)
}
func testHashFunctionMismatch_rsa_ecdsaWithSHA384() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.rsaKey), signatureAlgorithm: .ecdsaWithSHA384, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.rsaKey),
signatureAlgorithm: .ecdsaWithSHA384,
validCombination: false
)
}
func testHashFunctionMismatch_rsa_ecdsaWithSHA512() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.rsaKey), signatureAlgorithm: .ecdsaWithSHA512, validCombination: false)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.rsaKey),
signatureAlgorithm: .ecdsaWithSHA512,
validCombination: false
)
}
func testHashFunctionMismatch_rsa_sha1WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.rsaKey), signatureAlgorithm: .sha1WithRSAEncryption, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.rsaKey),
signatureAlgorithm: .sha1WithRSAEncryption,
validCombination: true
)
}
func testHashFunctionMismatch_rsa_sha256WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.rsaKey), signatureAlgorithm: .sha256WithRSAEncryption, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.rsaKey),
signatureAlgorithm: .sha256WithRSAEncryption,
validCombination: true
)
}
func testHashFunctionMismatch_rsa_sha384WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.rsaKey), signatureAlgorithm: .sha384WithRSAEncryption, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.rsaKey),
signatureAlgorithm: .sha384WithRSAEncryption,
validCombination: true
)
}
func testHashFunctionMismatch_rsa_sha512WithRSAEncryption() throws {
try self.hashFunctionMismatchTest(privateKey: .init(Self.rsaKey), signatureAlgorithm: .sha512WithRSAEncryption, validCombination: true)
try self.hashFunctionMismatchTest(
privateKey: .init(Self.rsaKey),
signatureAlgorithm: .sha512WithRSAEncryption,
validCombination: true
)
}
#if canImport(Darwin)
func testHashFunctionMismatch_secureEnclaveP256_ecdsaWithSHA256() throws {
if let secureEnclaveP256 = Self.secureEnclaveP256 {
try self.hashFunctionMismatchTest(privateKey: .init(secureEnclaveP256), signatureAlgorithm: .ecdsaWithSHA256, validCombination: true)
} else {
guard let secureEnclaveP256 = Self.secureEnclaveP256 else {
throw XCTSkip("No SEP")
}
try self.hashFunctionMismatchTest(
privateKey: .init(secureEnclaveP256),
signatureAlgorithm: .ecdsaWithSHA256,
validCombination: true
)
}
func testHashFunctionMismatch_secureEnclaveP256_ecdsaWithSHA384() throws {
if let secureEnclaveP256 = Self.secureEnclaveP256 {
try self.hashFunctionMismatchTest(privateKey: .init(secureEnclaveP256), signatureAlgorithm: .ecdsaWithSHA384, validCombination: true)
} else {
guard let secureEnclaveP256 = Self.secureEnclaveP256 else {
throw XCTSkip("No SEP")
}
try self.hashFunctionMismatchTest(
privateKey: .init(secureEnclaveP256),
signatureAlgorithm: .ecdsaWithSHA384,
validCombination: true
)
}
func testHashFunctionMismatch_secureEnclaveP256_ecdsaWithSHA512() throws {
if let secureEnclaveP256 = Self.secureEnclaveP256 {
try self.hashFunctionMismatchTest(privateKey: .init(secureEnclaveP256), signatureAlgorithm: .ecdsaWithSHA512, validCombination: true)
} else {
guard let secureEnclaveP256 = Self.secureEnclaveP256 else {
throw XCTSkip("No SEP")
}
try self.hashFunctionMismatchTest(
privateKey: .init(secureEnclaveP256),
signatureAlgorithm: .ecdsaWithSHA512,
validCombination: true
)
}
func testHashFunctionMismatch_secureEnclaveP256_sha1WithRSAEncryption() throws {
if let secureEnclaveP256 = Self.secureEnclaveP256 {
try self.hashFunctionMismatchTest(privateKey: .init(secureEnclaveP256), signatureAlgorithm: .sha1WithRSAEncryption, validCombination: false)
} else {
guard let secureEnclaveP256 = Self.secureEnclaveP256 else {
throw XCTSkip("No SEP")
}
try self.hashFunctionMismatchTest(
privateKey: .init(secureEnclaveP256),
signatureAlgorithm: .sha1WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_secureEnclaveP256_sha256WithRSAEncryption() throws {
if let secureEnclaveP256 = Self.secureEnclaveP256 {
try self.hashFunctionMismatchTest(privateKey: .init(secureEnclaveP256), signatureAlgorithm: .sha256WithRSAEncryption, validCombination: false)
} else {
guard let secureEnclaveP256 = Self.secureEnclaveP256 else {
throw XCTSkip("No SEP")
}
try self.hashFunctionMismatchTest(
privateKey: .init(secureEnclaveP256),
signatureAlgorithm: .sha256WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_secureEnclaveP256_sha384WithRSAEncryption() throws {
if let secureEnclaveP256 = Self.secureEnclaveP256 {
try self.hashFunctionMismatchTest(privateKey: .init(secureEnclaveP256), signatureAlgorithm: .sha384WithRSAEncryption, validCombination: false)
} else {
guard let secureEnclaveP256 = Self.secureEnclaveP256 else {
throw XCTSkip("No SEP")
}
try self.hashFunctionMismatchTest(
privateKey: .init(secureEnclaveP256),
signatureAlgorithm: .sha384WithRSAEncryption,
validCombination: false
)
}
func testHashFunctionMismatch_secureEnclaveP256_sha512WithRSAEncryption() throws {
if let secureEnclaveP256 = Self.secureEnclaveP256 {
try self.hashFunctionMismatchTest(privateKey: .init(secureEnclaveP256), signatureAlgorithm: .sha512WithRSAEncryption, validCombination: false)
} else {
guard let secureEnclaveP256 = Self.secureEnclaveP256 else {
throw XCTSkip("No SEP")
}
try self.hashFunctionMismatchTest(
privateKey: .init(secureEnclaveP256),
signatureAlgorithm: .sha512WithRSAEncryption,
validCombination: false
)
}
#endif
#endif
func testECDSASignatureCorrectlyStripsLeadingZerosFromRawByteRepresentation() throws {
// We're testing a round-trip logic here, ensuring that the ECDSA signature correctly round-trips.
@@ -336,11 +479,11 @@ final class SignatureTests: XCTestCase {
])
try testECDSASignatureRoundTrip(rawSignatureBytes: [
0xFF, 0xFF, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x08, 0x09, 0x0a
0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
])
try testECDSASignatureRoundTrip(rawSignatureBytes: [
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x06, 0x07, 0x08, 0x09, 0x0a
0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
])
}
}
+36 -20
View File
@@ -20,14 +20,22 @@ final class TimeTests: XCTestCase {
func testConvertUTCTimeToDate() throws {
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
let utctime = try UTCTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55)
let expected = Date(timeIntervalSince1970: 1656677755)
let expected = Date(timeIntervalSince1970: 1_656_677_755)
XCTAssertEqual(expected, Date(.utcTime(utctime)))
}
func testConvertGeneralizedTimeToDate() throws {
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
let generalizedTime = try GeneralizedTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55, fractionalSeconds: 0.0)
let expected = Date(timeIntervalSince1970: 1656677755)
let generalizedTime = try GeneralizedTime(
year: 2022,
month: 07,
day: 01,
hours: 12,
minutes: 15,
seconds: 55,
fractionalSeconds: 0.0
)
let expected = Date(timeIntervalSince1970: 1_656_677_755)
XCTAssertEqual(expected, Date(.generalTime(generalizedTime)))
}
@@ -35,36 +43,44 @@ final class TimeTests: XCTestCase {
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
let utctime = try UTCTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55)
let time = Time.utcTime(utctime)
let expected = Date(timeIntervalSince1970: 1656677755)
let expected = Date(timeIntervalSince1970: 1_656_677_755)
XCTAssertEqual(expected, Date(time))
}
func testConvertGeneralizedTimeAsTimeToDate() throws {
// 2022-07-01 12:15:55 corresponds to 1656677755 seconds from 1970.
let generalizedTime = try GeneralizedTime(year: 2022, month: 07, day: 01, hours: 12, minutes: 15, seconds: 55, fractionalSeconds: 0.0)
let generalizedTime = try GeneralizedTime(
year: 2022,
month: 07,
day: 01,
hours: 12,
minutes: 15,
seconds: 55,
fractionalSeconds: 0.0
)
let time = Time.generalTime(generalizedTime)
let expected = Date(timeIntervalSince1970: 1656677755)
let expected = Date(timeIntervalSince1970: 1_656_677_755)
XCTAssertEqual(expected, Date(time))
}
func testSpecificInputsForGMTime() throws {
// These numbers are determined experimentally on macOS.
let smallestUsableTimeT = Int64(-67768040609740800)
let largestUsableTimeT = Int64(67768036191676799)
let smallestUsableTimeT = Int64(-67_768_040_609_740_800)
let largestUsableTimeT = Int64(67_768_036_191_676_799)
let epoch = Int64(0)
let smallestTime = smallestUsableTimeT.utcDateFromTimestamp
let largestTime = largestUsableTimeT.utcDateFromTimestamp
let epochTime = epoch.utcDateFromTimestamp
XCTAssertEqual(smallestTime.year, -2147481748)
XCTAssertEqual(smallestTime.year, -2_147_481_748)
XCTAssertEqual(smallestTime.month, 1)
XCTAssertEqual(smallestTime.day, 1)
XCTAssertEqual(smallestTime.hours, 0)
XCTAssertEqual(smallestTime.minutes, 0)
XCTAssertEqual(smallestTime.seconds, 0)
XCTAssertEqual(largestTime.year, 2147485547)
XCTAssertEqual(largestTime.year, 2_147_485_547)
XCTAssertEqual(largestTime.month, 12)
XCTAssertEqual(largestTime.day, 31)
XCTAssertEqual(largestTime.hours, 23)
@@ -86,8 +102,8 @@ final class TimeTests: XCTestCase {
func testCompareRandomInputsForGMTime() throws {
// These numbers are determined experimentally on macOS.
let smallestUsableTimeT = Int64(-67768040609740800)
let largestUsableTimeT = Int64(67768036191676799)
let smallestUsableTimeT = Int64(-67_768_040_609_740_800)
let largestUsableTimeT = Int64(67_768_036_191_676_799)
// If we're constrained by the system library time_t size, let's do that.
let lowerBound = max(smallestUsableTimeT, Int64(time_t.min))
@@ -116,14 +132,14 @@ final class TimeTests: XCTestCase {
func testHandleDaysAndLeapYearsProperly() throws {
// Start from Sat, 01 Jan 1600 00:00:00 and test every day between then and the year 3000.
// This tests our year-based computations are probably correct.
var timestamp = Int64(-11676096000)
var timestamp = Int64(-11_676_096_000)
for year in 1600..<3000 {
let isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
for month in 1...12 {
let days: Int
switch month {
case 1, 3, 5, 7, 8, 10, 12:
days = 31
@@ -134,20 +150,20 @@ final class TimeTests: XCTestCase {
default:
fatalError()
}
for day in 1...days {
let computed = timestamp.utcDateFromTimestamp
XCTAssertEqual(computed.year, year)
XCTAssertEqual(computed.month, month)
XCTAssertEqual(computed.day, day)
XCTAssertEqual(computed.hours, 0)
XCTAssertEqual(computed.minutes, 0)
XCTAssertEqual(computed.seconds, 0)
let reversed = Int64(timestampFromUTCDate: computed)
XCTAssertEqual(reversed, timestamp)
// The number of seconds in 1 day.
timestamp += 24 * 60 * 60
}
+475 -195
View File
@@ -42,7 +42,9 @@ final class VerifierTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(ca1PrivateKey)
)
@@ -63,7 +65,9 @@ final class VerifierTests: XCTestCase {
)
KeyUsage(keyCertSign: true)
AuthorityKeyIdentifier(keyIdentifier: try! ca2.extensions.subjectKeyIdentifier!.keyIdentifier)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(ca2PrivateKey)
)
@@ -84,7 +88,11 @@ final class VerifierTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1AlternativePrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(
Insecure.SHA1.hash(data: ca1AlternativePrivateKey.publicKey.derRepresentation)
)
)
},
issuerPrivateKey: .init(ca1PrivateKey)
)
@@ -111,7 +119,9 @@ final class VerifierTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(ca2PrivateKey)
)
@@ -132,7 +142,9 @@ final class VerifierTests: XCTestCase {
)
KeyUsage(keyCertSign: true)
AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca2PrivateKey.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(ca1PrivateKey)
)
@@ -160,7 +172,11 @@ final class VerifierTests: XCTestCase {
)
KeyUsage(keyCertSign: true)
AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: intermediate1PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(
Insecure.SHA1.hash(data: intermediate1PrivateKey.publicKey.derRepresentation)
)
)
},
issuerPrivateKey: .init(ca1PrivateKey)
)
@@ -200,7 +216,9 @@ final class VerifierTests: XCTestCase {
)
KeyUsage(keyCertSign: true)
AuthorityKeyIdentifier(keyIdentifier: try! ca2.extensions.subjectKeyIdentifier!.keyIdentifier)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(ca1PrivateKey)
)
@@ -382,7 +400,9 @@ final class VerifierTests: XCTestCase {
AuthorityKeyIdentifier(keyIdentifier: try! ca1.extensions.subjectKeyIdentifier!.keyIdentifier)
// Note this is the SKI for the _wrong key_.
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: ca1PrivateKey.publicKey.derRepresentation))
)
SubjectAlternativeNames([.dnsName("example.com")])
},
issuerPrivateKey: .init(ca1PrivateKey)
@@ -422,7 +442,9 @@ final class VerifierTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: 1)
)
KeyUsage(keyCertSign: true)
SubjectKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation)))
SubjectKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(xKey)
)
@@ -442,7 +464,9 @@ final class VerifierTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation)))
AuthorityKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(t1t2Key)
)
@@ -462,7 +486,9 @@ final class VerifierTests: XCTestCase {
BasicConstraints.isCertificateAuthority(maxPathLength: nil)
)
KeyUsage(keyCertSign: true)
AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation)))
AuthorityKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))
)
SubjectAlternativeNames([.dnsName("foo.example.com")])
},
issuerPrivateKey: .init(t1t2Key)
@@ -482,7 +508,9 @@ final class VerifierTests: XCTestCase {
Critical(
BasicConstraints.notCertificateAuthority
)
AuthorityKeyIdentifier(keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation)))
AuthorityKeyIdentifier(
keyIdentifier: ArraySlice(Insecure.SHA1.hash(data: t3Key.publicKey.derRepresentation))
)
},
issuerPrivateKey: .init(t3Key)
)
@@ -495,9 +523,13 @@ final class VerifierTests: XCTestCase {
func testTrivialChainBuilding() async throws {
let roots = CertificateStore([Self.ca1])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -505,22 +537,35 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1]
),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
]
)
}
func testMissingIntermediateFailsToBuild() async throws {
let roots = CertificateStore([Self.ca1])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([]),
diagnosticCallback: log.append(_:)
)
guard case .couldNotValidate(let policyResults) = result else {
XCTFail("Accidentally validated: \(result)")
@@ -529,18 +574,25 @@ final class VerifierTests: XCTestCase {
XCTAssertEqual(policyResults, [])
print(log)
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.couldNotValidateLeafCertificate(Self.localhostLeaf),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.couldNotValidateLeafCertificate(Self.localhostLeaf),
]
)
}
func testMissingRootFailsToBuild() async throws {
let roots = CertificateStore([])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .couldNotValidate(let policyResults) = result else {
XCTFail("Accidentally validated: \(result)")
@@ -548,20 +600,30 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(policyResults, [])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.couldNotValidateLeafCertificate(Self.localhostLeaf),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.couldNotValidateLeafCertificate(Self.localhostLeaf),
]
)
}
func testExtraRootsAreIgnored() async throws {
let roots = CertificateStore([Self.ca1, Self.ca2])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -569,21 +631,34 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1]
),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
]
)
}
func testPuttingRootsInTheIntermediariesIsntAProblem() async throws {
let roots = CertificateStore([Self.ca1, Self.ca2])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1, Self.ca1, Self.ca2]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1, Self.ca1, Self.ca2]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -591,21 +666,34 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1]
),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
]
)
}
func testSupportsCrossSignedRootWithoutTrouble() async throws {
let roots = CertificateStore([Self.ca2])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1, Self.ca1CrossSignedByCA2]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1, Self.ca1CrossSignedByCA2]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -614,23 +702,41 @@ final class VerifierTests: XCTestCase {
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1CrossSignedByCA2]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2], issuers: [Self.ca2]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1CrossSignedByCA2]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2],
issuers: [Self.ca2]
),
.foundValidCertificateChain([
Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2,
]),
]
)
}
func testBuildsTheShorterPathInTheCaseOfCrossSignedRoots() async throws {
let roots = CertificateStore([Self.ca1, Self.ca2])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1, Self.ca2CrossSignedByCA1, Self.ca1CrossSignedByCA2]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1, Self.ca2CrossSignedByCA1, Self.ca1CrossSignedByCA2]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -638,21 +744,34 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1]
),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
]
)
}
func testPrefersToUseIntermediatesWithSKIThatMatches() async throws {
let roots = CertificateStore([Self.ca1])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1, Self.intermediate1WithoutSKIAKI]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1, Self.intermediate1WithoutSKIAKI]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -660,21 +779,34 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1WithoutSKIAKI, Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1WithoutSKIAKI, Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1]
),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
]
)
}
func testPrefersNoSKIToNonMatchingSKI() async throws {
let roots = CertificateStore([Self.ca1])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1WithIncorrectSKIAKI, Self.intermediate1WithoutSKIAKI]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1WithIncorrectSKIAKI, Self.intermediate1WithoutSKIAKI]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -682,21 +814,34 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1WithoutSKIAKI, Self.ca1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers: [Self.intermediate1WithIncorrectSKIAKI, Self.intermediate1WithoutSKIAKI]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1WithoutSKIAKI]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1WithoutSKIAKI], issuers: [Self.ca1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1WithoutSKIAKI, Self.ca1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1WithIncorrectSKIAKI, Self.intermediate1WithoutSKIAKI]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1WithoutSKIAKI]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1WithoutSKIAKI],
issuers: [Self.ca1]
),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1WithoutSKIAKI, Self.ca1]),
]
)
}
func testRejectsRootsThatDidNotSignTheCertBeforeThem() async throws {
let roots = CertificateStore([Self.ca1WithAlternativePrivateKey, Self.ca2])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.ca1CrossSignedByCA2, Self.ca2CrossSignedByCA1, Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.ca1CrossSignedByCA2, Self.ca2CrossSignedByCA1, Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -704,20 +849,37 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers:[Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1WithAlternativePrivateKey]),
.issuerHasNotSignedCertificate(
Self.ca1WithAlternativePrivateKey,
partialChain: [Self.localhostLeaf, Self.intermediate1]
),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1CrossSignedByCA2]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2], issuers: [Self.ca2]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1WithAlternativePrivateKey]
),
.issuerHasNotSignedCertificate(
Self.ca1WithAlternativePrivateKey,
partialChain: [Self.localhostLeaf, Self.intermediate1]
),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1CrossSignedByCA2]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2],
issuers: [Self.ca2]
),
.foundValidCertificateChain([
Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2,
]),
]
)
}
func testPolicyFailuresCanFindLongerPaths() async throws {
@@ -728,7 +890,11 @@ final class VerifierTests: XCTestCase {
FailIfCertInChainPolicy(forbiddenCert: Self.ca1)
Self.defaultPolicy
}
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1, Self.ca2CrossSignedByCA1, Self.ca1CrossSignedByCA2]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1, Self.ca2CrossSignedByCA1, Self.ca1CrossSignedByCA2]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -736,27 +902,51 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf], issuers:[Self.intermediate1]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1]),
.chainFailsToMeetPolicy(UnverifiedCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]), reason: "chain must not contain forbidden certificate"),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1CrossSignedByCA2]),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2], issuers: [Self.ca2]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf],
issuers: [Self.intermediate1]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1]
),
.chainFailsToMeetPolicy(
UnverifiedCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]),
reason: "chain must not contain forbidden certificate"
),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1CrossSignedByCA2]
),
.searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2],
issuers: [Self.ca2]
),
.foundValidCertificateChain([
Self.localhostLeaf, Self.intermediate1, Self.ca1CrossSignedByCA2, Self.ca2,
]),
]
)
}
func testInsanePKICanStillBuild() async throws {
let roots = CertificateStore([Self.ca1])
let intermediates = CertificateStore([Self.t1, Self.t2, Self.t3, Self.x1, Self.x2])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.insaneLeaf, intermediates: intermediates, diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.insaneLeaf,
intermediates: intermediates,
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -764,64 +954,99 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1, Self.ca1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.insaneLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.insaneLeaf], issuers: [Self.t1, Self.t2, Self.t3]),
.issuerHasNotSignedCertificate(Self.t1, partialChain: [Self.insaneLeaf]),
.issuerHasNotSignedCertificate(Self.t2, partialChain: [Self.insaneLeaf]),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.insaneLeaf, Self.t3], issuers: [Self.x1, Self.x2]),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.insaneLeaf, Self.t3, Self.x2], issuers: [Self.t1, Self.t2, Self.t3]),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2], issuer: Self.t3),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.insaneLeaf, Self.t3, Self.x2, Self.t2], issuers: [Self.x1, Self.x2]),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2], issuer: Self.x2),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1]),
.foundCandidateIssuersOfPartialChainInIntermediateStore([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1], issuers: [Self.t1, Self.t2, Self.t3]),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1], issuer: Self.t2),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1], issuer: Self.t3),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1], issuers: [Self.ca1]),
.foundValidCertificateChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1, Self.ca1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.insaneLeaf]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.insaneLeaf],
issuers: [Self.t1, Self.t2, Self.t3]
),
.issuerHasNotSignedCertificate(Self.t1, partialChain: [Self.insaneLeaf]),
.issuerHasNotSignedCertificate(Self.t2, partialChain: [Self.insaneLeaf]),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.insaneLeaf, Self.t3],
issuers: [Self.x1, Self.x2]
),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.insaneLeaf, Self.t3, Self.x2],
issuers: [Self.t1, Self.t2, Self.t3]
),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2], issuer: Self.t3),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.insaneLeaf, Self.t3, Self.x2, Self.t2],
issuers: [Self.x1, Self.x2]
),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2], issuer: Self.x2),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1]),
.foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1],
issuers: [Self.t1, Self.t2, Self.t3]
),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1], issuer: Self.t2),
.issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1], issuer: Self.t3),
.searchingForIssuerOfPartialChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1]),
.foundCandidateIssuersOfPartialChainInRootStore(
[Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1],
issuers: [Self.ca1]
),
.foundValidCertificateChain([Self.insaneLeaf, Self.t3, Self.x2, Self.t2, Self.x1, Self.t1, Self.ca1]),
]
)
}
func testSelfSignedCertsAreRejectedWhenNotInTheTrustStore() async throws {
let roots = CertificateStore([Self.ca1])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.isolatedSelfSignedCert, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.isolatedSelfSignedCert,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .couldNotValidate = result else {
XCTFail("Incorrectly validated: \(result)")
return
}
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.isolatedSelfSignedCert]),
.couldNotValidateLeafCertificate(Self.isolatedSelfSignedCert),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.isolatedSelfSignedCert]),
.couldNotValidateLeafCertificate(Self.isolatedSelfSignedCert),
]
)
}
func testSelfSignedCertsAreTrustedWhenInTrustStore() async throws {
let roots = CertificateStore([Self.ca1, Self.isolatedSelfSignedCert])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.isolatedSelfSignedCert, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.isolatedSelfSignedCert,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
return
}
XCTAssertEqual(chain, [Self.isolatedSelfSignedCert])
XCTAssertEqual(log, [
.foundValidCertificateChain([Self.isolatedSelfSignedCert])
])
XCTAssertEqual(
log,
[
.foundValidCertificateChain([Self.isolatedSelfSignedCert])
]
)
}
func testTrustRootsCanBeNonSelfSignedLeaves() async throws {
@@ -836,9 +1061,13 @@ final class VerifierTests: XCTestCase {
let roots = CertificateStore([Self.localhostLeaf])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { IgnoreBasicConstraintsPolicy() }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -846,17 +1075,24 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf])
XCTAssertEqual(log, [
.foundValidCertificateChain([Self.localhostLeaf])
])
XCTAssertEqual(
log,
[
.foundValidCertificateChain([Self.localhostLeaf])
]
)
}
func testTrustRootsCanBeNonSelfSignedIntermediates() async throws {
let roots = CertificateStore([Self.intermediate1])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.localhostLeaf, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.localhostLeaf,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .validCertificate(let chain) = result else {
XCTFail("Failed to validate: \(result)")
@@ -864,64 +1100,110 @@ final class VerifierTests: XCTestCase {
}
XCTAssertEqual(chain, [Self.localhostLeaf, Self.intermediate1])
XCTAssertEqual(log, [
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1]),
])
XCTAssertEqual(
log,
[
.searchingForIssuerOfPartialChain([Self.localhostLeaf]),
.foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf], issuers: [Self.intermediate1]),
.foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1]),
]
)
}
func testWePoliceCriticalExtensionsOnLeafCerts() async throws {
let roots = CertificateStore([Self.ca1, Self.isolatedSelfSignedCertWithWeirdCriticalExtension])
let log = DiagnosticsLog()
var verifier = Verifier(rootCertificates: roots) { Self.defaultPolicy }
let result = await verifier.validate(leafCertificate: Self.isolatedSelfSignedCertWithWeirdCriticalExtension, intermediates: CertificateStore([Self.intermediate1]), diagnosticCallback: log.append(_:))
let result = await verifier.validate(
leafCertificate: Self.isolatedSelfSignedCertWithWeirdCriticalExtension,
intermediates: CertificateStore([Self.intermediate1]),
diagnosticCallback: log.append(_:)
)
guard case .couldNotValidate = result else {
XCTFail("Incorrectly validated: \(result)")
return
}
XCTAssertEqual(log, [
.leafCertificateHasUnhandledCriticalExtension(
Self.isolatedSelfSignedCertWithWeirdCriticalExtension,
handledCriticalExtensions: Self.defaultPolicy.verifyingCriticalExtensions
)
])
XCTAssertEqual(
log,
[
.leafCertificateHasUnhandledCriticalExtension(
Self.isolatedSelfSignedCertWithWeirdCriticalExtension,
handledCriticalExtensions: Self.defaultPolicy.verifyingCriticalExtensions
)
]
)
}
func testVerificationDiagnosticDescriptionDoesNotIncludeNewLines() {
let diagnostics: [VerificationDiagnostic] = [
.init(storage: .leafCertificateHasUnhandledCriticalExtension(Self.localhostLeaf, handledCriticalExtensions: [.cmsData, .cmsSignedData])),
.init(storage: .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(Self.localhostLeaf, reason: "policy failure reason")),
.init(storage: .chainFailsToMeetPolicy(.init([Self.localhostLeaf, Self.ca1]), reason: "policy failure reason")),
.init(
storage: .leafCertificateHasUnhandledCriticalExtension(
Self.localhostLeaf,
handledCriticalExtensions: [.cmsData, .cmsSignedData]
)
),
.init(
storage: .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy(
Self.localhostLeaf,
reason: "policy failure reason"
)
),
.init(
storage: .chainFailsToMeetPolicy(
.init([Self.localhostLeaf, Self.ca1]),
reason: "policy failure reason"
)
),
.init(storage: .issuerHasNotSignedCertificate(Self.intermediate1, partialChain: [Self.localhostLeaf])),
.init(storage: .issuerHasUnhandledCriticalExtension(issuer: Self.intermediate1, partialChain: [Self.localhostLeaf], handledCriticalExtensions: [.cmsData, .cmsSignedData])),
.init(
storage: .issuerHasUnhandledCriticalExtension(
issuer: Self.intermediate1,
partialChain: [Self.localhostLeaf],
handledCriticalExtensions: [.cmsData, .cmsSignedData]
)
),
.init(storage: .searchingForIssuerOfPartialChain([Self.localhostLeaf, Self.intermediate1])),
.init(storage: .foundCandidateIssuersOfPartialChainInRootStore([Self.localhostLeaf, Self.intermediate1], issuers: [Self.ca1, Self.ca1WithAlternativePrivateKey])),
.init(storage: .foundCandidateIssuersOfPartialChainInIntermediateStore([Self.insaneLeaf, Self.t3], issuers: [Self.x1, Self.x2])),
.init(
storage: .foundCandidateIssuersOfPartialChainInRootStore(
[Self.localhostLeaf, Self.intermediate1],
issuers: [Self.ca1, Self.ca1WithAlternativePrivateKey]
)
),
.init(
storage: .foundCandidateIssuersOfPartialChainInIntermediateStore(
[Self.insaneLeaf, Self.t3],
issuers: [Self.x1, Self.x2]
)
),
.init(storage: .foundValidCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1])),
.init(storage: .couldNotValidateLeafCertificate(Self.localhostLeaf)),
.init(storage: .issuerIsAlreadyInTheChain([Self.insaneLeaf, Self.t3, Self.x2], issuer: Self.t3)),
]
for diagnostic in diagnostics {
let description = diagnostic.description
XCTAssertFalse(description.contains { $0 == "\n" }, "Diagnostic description contains new line: \(description)")
XCTAssertFalse(
description.contains { $0 == "\n" },
"Diagnostic description contains new line: \(description)"
)
}
}
}
fileprivate struct FailIfCalledPolicy: VerifierPolicy {
private struct FailIfCalledPolicy: VerifierPolicy {
let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []
mutating func chainMeetsPolicyRequirements(chain: X509.UnverifiedCertificateChain) async -> X509.PolicyEvaluationResult {
mutating func chainMeetsPolicyRequirements(
chain: X509.UnverifiedCertificateChain
) async -> X509.PolicyEvaluationResult {
XCTFail("Policy was called with chain \(chain)")
return .failsToMeetPolicy(reason: "policy must not be called")
}
}
fileprivate struct FailIfCertInChainPolicy: VerifierPolicy {
private struct FailIfCertInChainPolicy: VerifierPolicy {
let verifyingCriticalExtensions: [ASN1ObjectIdentifier] = []
private let forbiddenCert: Certificate
@@ -931,11 +1213,10 @@ fileprivate struct FailIfCertInChainPolicy: VerifierPolicy {
}
mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult {
if chain.contains(self.forbiddenCert) {
return .failsToMeetPolicy(reason: "chain must not contain forbidden certificate")
} else {
guard chain.contains(self.forbiddenCert) else {
return .meetsPolicy
}
return .failsToMeetPolicy(reason: "chain must not contain forbidden certificate")
}
}
@@ -974,7 +1255,7 @@ extension DiagnosticsLog: CustomDebugStringConvertible {
}
extension DiagnosticsLog: Equatable {
static func ==(lhs: DiagnosticsLog, rhs: DiagnosticsLog) -> Bool {
static func == (lhs: DiagnosticsLog, rhs: DiagnosticsLog) -> Bool {
lhs.diagnostics == rhs.diagnostics
}
}
@@ -984,4 +1265,3 @@ extension DiagnosticsLog: ExpressibleByArrayLiteral {
self.init(diagnostics: elements)
}
}
+6
View File
@@ -15,3 +15,9 @@ ENV LANGUAGE en_US.UTF-8
# tools
RUN mkdir -p $HOME/.tools
RUN echo 'export PATH="$HOME/.tools:$PATH"' >> $HOME/.profile
# swift-format
ARG swiftformat_version=508.0.1
RUN git clone --branch $swiftformat_version --depth 1 https://github.com/apple/swift-format $HOME/.tools/swift-format-source
RUN cd $HOME/.tools/swift-format-source && swift build -c release
RUN ln -s $HOME/.tools/swift-format-source/.build/release/swift-format $HOME/.tools/swift-format
+54
View File
@@ -0,0 +1,54 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## 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
##
##===----------------------------------------------------------------------===##
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftOpenAPIGenerator open source project
##
## Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
set -euo pipefail
function log() { printf -- "** %s\n" "$*" >&2; }
function error() { printf -- "** ERROR: %s\n" "$*" >&2; }
function fatal() { error "$*"; exit 1; }
current_script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
repo_root="$(git -C "${current_script_dir}" rev-parse --show-toplevel)"
swiftformat_bin=${swiftformat_bin:-$(command -v swift-format)} || fatal "❌ swiftformat_bin unset and no swift-format on PATH"
"${swiftformat_bin}" lint \
--parallel --recursive --strict \
"${repo_root}/Sources" "${repo_root}/Tests" \
&& swift_format_rc=$? || swift_format_rc=$?
if [[ "${swift_format_rc}" -ne 0 ]]; then
fatal "❌ Running swift-format produced errors.
To fix, run the following command:
% swift-format format --parallel --recursive --in-place Sources Tests
"
exit "${swift_format_rc}"
fi
log "✅ Ran swift-format with no errors."
+6
View File
@@ -53,6 +53,12 @@ if git grep --color=never -i "${unacceptable_terms[@]}" -- . ":(exclude)CODE_OF_
fi
printf "\033[0;32mokay.\033[0m\n"
# swift-format
swift_format_script="${here}/run-swift-format.sh"
if ! bash "${swift_format_script}"; then
exit 1
fi
printf "=> Detecting changes in source files for CMake build\n"
FIRST_OUT="$(git status --porcelain)"
out=$($here/update_cmakelists.sh 2>&1)