From 92ffb4827bd216e487e95d7605cbe3ec5fe16045 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Mon, 21 Aug 2023 20:01:19 +0100 Subject: [PATCH] Add `PolicyFailureReason` to support lazy failure reason string interpolation (#126) * Add `PolicyFailureReason` to support lazy failure reason string interpolation * fix allocation test compilation * update allocation counters --- .../test_01_resources/test_validation.swift | 2 +- Sources/X509/OCSP/OCSPPolicy.swift | 29 ++++++++------ .../RFC5280/BasicConstraintsPolicy.swift | 1 + .../Verifier/VerificationDiagnostic.swift | 12 +++--- Sources/X509/Verifier/Verifier.swift | 4 +- Sources/X509/Verifier/VerifierPolicy.swift | 40 ++++++++++++++++++- Tests/X509Tests/VerifierTests.swift | 6 +-- docker/docker-compose.2204.57.yaml | 2 +- docker/docker-compose.2204.58.yaml | 2 +- docker/docker-compose.2204.59.yaml | 2 +- docker/docker-compose.2204.main.yaml | 2 +- 11 files changed, 73 insertions(+), 29 deletions(-) diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_validation.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_validation.swift index 838ab57..ca9f0d0 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_validation.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_validation.swift @@ -311,7 +311,7 @@ fileprivate struct FailIfCertInChainPolicy: VerifierPolicy { self.forbiddenCert = forbiddenCert } - mutating func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { + func chainMeetsPolicyRequirements(chain: UnverifiedCertificateChain) async -> PolicyEvaluationResult { if chain.contains(self.forbiddenCert) { return .failsToMeetPolicy(reason: "chain must not contain \(self.forbiddenCert)") } else { diff --git a/Sources/X509/OCSP/OCSPPolicy.swift b/Sources/X509/OCSP/OCSPPolicy.swift index 7f1ee4e..52e3cfd 100644 --- a/Sources/X509/OCSP/OCSPPolicy.swift +++ b/Sources/X509/OCSP/OCSPPolicy.swift @@ -249,7 +249,7 @@ 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 { + private func softFailure(reason: PolicyFailureReason) -> PolicyEvaluationResult { switch self.failureMode.storage { case .soft: return .meetsPolicy @@ -299,7 +299,7 @@ extension OCSPVerifierPolicy.Storage { do { authorityInformationAccess = try certificate.extensions.authorityInformationAccess } catch { - return self.softFailure(reason: "failed to decode AuthorityInformationAccess \(error)") + return self.softFailure(reason: .init("failed to decode AuthorityInformationAccess \(error)")) } guard let authorityInformationAccess else { // OCSP not necessary for certificate @@ -320,14 +320,16 @@ extension OCSPVerifierPolicy.Storage { return responderURI }.first guard let responderURI else { - return self.softFailure(reason: "expected OCSP location to be a URI but got \(ocspAccessDescriptions)") + return self.softFailure( + reason: .init("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 self.softFailure(reason: .init("failed to create OCSPCertID \(error)")) } return await self.queryAndVerifyCertificateStatus(for: certID, responderURI: responderURI, issuer: issuer) @@ -346,7 +348,7 @@ extension OCSPVerifierPolicy.Storage { try serializer.serialize(request) requestBytes = serializer.serializedBytes } catch { - return self.softFailure(reason: "failed to create OCSPRequest \(error)") + return self.softFailure(reason: .init("failed to create OCSPRequest \(error)")) } let responseDerEncoded: [UInt8] @@ -364,7 +366,7 @@ extension OCSPVerifierPolicy.Storage { do { response = try OCSPResponse(derEncoded: responseDerEncoded[...]) } catch { - return self.softFailure(reason: "OCSP deserialisation failed \(error)") + return self.softFailure(reason: .init("OCSP deserialisation failed \(error)")) } return await self.verifyResponse(response, requestedCertID: certID, requestNonce: requestNonce, issuer: issuer) @@ -378,7 +380,7 @@ extension OCSPVerifierPolicy.Storage { ) async -> PolicyEvaluationResult { switch response { case .unauthorized, .tryLater, .sigRequired, .malformedRequest, .internalError: - return self.softFailure(reason: "OCSP request failed \(OCSPResponseStatus(response))") + return self.softFailure(reason: .init("OCSP request failed \(OCSPResponseStatus(response))")) case .successful(let basicResponse): return await self.verifySuccessfulResponse( basicResponse, @@ -397,8 +399,9 @@ extension OCSPVerifierPolicy.Storage { ) async -> PolicyEvaluationResult { guard let response = basicResponse.responseData.responses.first(where: { $0.certID == requestedCertID }) else { return self.softFailure( - reason: + reason: .init( "OCSP response does not include a response for the queried certificate \(requestedCertID) - responses: \(basicResponse.responseData.responses)" + ) ) } @@ -410,7 +413,9 @@ extension OCSPVerifierPolicy.Storage { } guard basicResponse.responseData.version == .v1 else { - return self.softFailure(reason: "OCSP response version unsupported \(basicResponse.responseData.version)") + return self.softFailure( + reason: .init("OCSP response version unsupported \(basicResponse.responseData.version)") + ) } switch basicResponse.responseData.verifyTime(validationTime: self.validationTime) { @@ -427,13 +432,13 @@ extension OCSPVerifierPolicy.Storage { if let responseNonce = try basicResponse.responseData.responseExtensions?.ocspNonce, requestNonce != responseNonce { - return self.softFailure(reason: "OCSP response nonce does not match request nonce") + return self.softFailure(reason: .init("OCSP response nonce does not match request nonce")) } } else { precondition(nonceExtensionEnabled == false) } } catch { - return self.softFailure(reason: "failed to decode nonce response \(error)") + return self.softFailure(reason: .init("failed to decode nonce response \(error)")) } switch response.verifyTime(validationTime: self.validationTime) { @@ -449,7 +454,7 @@ extension OCSPVerifierPolicy.Storage { reason: "revoked through OCSP, reason: \(info.revocationReason?.description ?? "nil")" ) case .unknown: - return self.softFailure(reason: "OCSP response returned as status unknown") + return self.softFailure(reason: .init("OCSP response returned as status unknown")) case .good: return .meetsPolicy } diff --git a/Sources/X509/Verifier/RFC5280/BasicConstraintsPolicy.swift b/Sources/X509/Verifier/RFC5280/BasicConstraintsPolicy.swift index 8e6d5dd..0bd74d2 100644 --- a/Sources/X509/Verifier/RFC5280/BasicConstraintsPolicy.swift +++ b/Sources/X509/Verifier/RFC5280/BasicConstraintsPolicy.swift @@ -75,6 +75,7 @@ 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. + let subCACount = subCACount return .failsToMeetPolicy( reason: "RFC5280Policy: CA \(cert) has maximum path length \(maxPathLength), but chain has \(subCACount) subCAs" diff --git a/Sources/X509/Verifier/VerificationDiagnostic.swift b/Sources/X509/Verifier/VerificationDiagnostic.swift index 2385f2e..8a758fc 100644 --- a/Sources/X509/Verifier/VerificationDiagnostic.swift +++ b/Sources/X509/Verifier/VerificationDiagnostic.swift @@ -21,12 +21,12 @@ public struct VerificationDiagnostic: Sendable { struct LeafCertificateIsInTheRootStoreButDoesNotMeetPolicy: Hashable, Sendable { var leafCertificate: Certificate - var failsToMeetPolicyReason: String + var failsToMeetPolicyReason: PolicyFailureReason } struct ChainFailsToMeetPolicy: Hashable, Sendable { var chain: UnverifiedCertificateChain - var failsToMeetPolicyReason: String + var failsToMeetPolicyReason: PolicyFailureReason } struct IssuerHasUnhandledCriticalExtension: Hashable, Sendable { @@ -101,7 +101,7 @@ extension VerificationDiagnostic { static func leafCertificateIsInTheRootStoreButDoesNotMeetPolicy( _ leafCertificate: Certificate, - reason failsToMeetPolicyReason: String + reason failsToMeetPolicyReason: PolicyFailureReason ) -> Self { self.init( storage: .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy( @@ -113,7 +113,7 @@ extension VerificationDiagnostic { static func chainFailsToMeetPolicy( _ chain: UnverifiedCertificateChain, - reason failsToMeetPolicyReason: String + reason failsToMeetPolicyReason: PolicyFailureReason ) -> Self { self.init( storage: .chainFailsToMeetPolicy( @@ -219,7 +219,7 @@ extension VerificationDiagnostic.Storage { static func leafCertificateIsInTheRootStoreButDoesNotMeetPolicy( _ leafCertificate: Certificate, - reason failsToMeetPolicyReason: String + reason failsToMeetPolicyReason: PolicyFailureReason ) -> Self { .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy( .init( @@ -231,7 +231,7 @@ extension VerificationDiagnostic.Storage { static func chainFailsToMeetPolicy( _ chain: UnverifiedCertificateChain, - reason failsToMeetPolicyReason: String + reason failsToMeetPolicyReason: PolicyFailureReason ) -> Self { .chainFailsToMeetPolicy( .init( diff --git a/Sources/X509/Verifier/Verifier.swift b/Sources/X509/Verifier/Verifier.swift index 4543dc3..27c93c5 100644 --- a/Sources/X509/Verifier/Verifier.swift +++ b/Sources/X509/Verifier/Verifier.swift @@ -183,10 +183,10 @@ public enum VerificationResult: Hashable, Sendable { extension VerificationResult { public struct PolicyFailure: Hashable, Sendable { public var chain: UnverifiedCertificateChain - public var policyFailureReason: String + public var policyFailureReason: PolicyFailureReason @inlinable - public init(chain: UnverifiedCertificateChain, policyFailureReason: String) { + public init(chain: UnverifiedCertificateChain, policyFailureReason: PolicyFailureReason) { self.chain = chain self.policyFailureReason = policyFailureReason } diff --git a/Sources/X509/Verifier/VerifierPolicy.swift b/Sources/X509/Verifier/VerifierPolicy.swift index d9fde35..216b002 100644 --- a/Sources/X509/Verifier/VerifierPolicy.swift +++ b/Sources/X509/Verifier/VerifierPolicy.swift @@ -55,5 +55,43 @@ public protocol VerifierPolicy { public enum PolicyEvaluationResult: Sendable { case meetsPolicy - case failsToMeetPolicy(reason: String) + case failsToMeetPolicy(PolicyFailureReason) + + public static func failsToMeetPolicy(reason makeReason: @autoclosure @Sendable @escaping () -> String) -> Self { + return .failsToMeetPolicy(.init(makeReason())) + } + + public static func failsToMeetPolicy(reason: PolicyFailureReason) -> Self { + return .failsToMeetPolicy(reason) + } +} + +public struct PolicyFailureReason: Sendable { + var storage: @Sendable () -> String + + public init(_ makeString: @autoclosure @Sendable @escaping () -> String) { + self.storage = makeString + } +} + +extension PolicyFailureReason: Equatable { + public static func == (lhs: PolicyFailureReason, rhs: PolicyFailureReason) -> Bool { + lhs.description == rhs.description + } +} + +extension PolicyFailureReason: Hashable { + public func hash(into hasher: inout Hasher) { + description.hash(into: &hasher) + } +} + +extension PolicyFailureReason: CustomStringConvertible, CustomDebugStringConvertible { + public var description: String { + storage() + } + + public var debugDescription: String { + description.debugDescription + } } diff --git a/Tests/X509Tests/VerifierTests.swift b/Tests/X509Tests/VerifierTests.swift index 2389d2d..819646b 100644 --- a/Tests/X509Tests/VerifierTests.swift +++ b/Tests/X509Tests/VerifierTests.swift @@ -918,7 +918,7 @@ final class VerifierTests: XCTestCase { ), .chainFailsToMeetPolicy( UnverifiedCertificateChain([Self.localhostLeaf, Self.intermediate1, Self.ca1]), - reason: "chain must not contain forbidden certificate" + reason: .init("chain must not contain forbidden certificate") ), .foundCandidateIssuersOfPartialChainInIntermediateStore( [Self.localhostLeaf, Self.intermediate1], @@ -1148,13 +1148,13 @@ final class VerifierTests: XCTestCase { .init( storage: .leafCertificateIsInTheRootStoreButDoesNotMeetPolicy( Self.localhostLeaf, - reason: "policy failure reason" + reason: .init("policy failure reason") ) ), .init( storage: .chainFailsToMeetPolicy( .init([Self.localhostLeaf, Self.ca1]), - reason: "policy failure reason" + reason: .init("policy failure reason") ) ), .init(storage: .issuerHasNotSignedCertificate(Self.intermediate1, partialChain: [Self.localhostLeaf])), diff --git a/docker/docker-compose.2204.57.yaml b/docker/docker-compose.2204.57.yaml index 3795af7..470ab90 100644 --- a/docker/docker-compose.2204.57.yaml +++ b/docker/docker-compose.2204.57.yaml @@ -15,7 +15,7 @@ services: - MAX_ALLOCS_ALLOWED_parse_webpki_roots=422050 - MAX_ALLOCS_ALLOWED_tiny_array_cow_append_contents_of=9050 - MAX_ALLOCS_ALLOWED_tiny_array_non_allocating_operations=0 - - MAX_ALLOCS_ALLOWED_validation=206050 + - MAX_ALLOCS_ALLOWED_validation=120050 - WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors # - SANITIZER_ARG=--sanitize=thread # TSan broken still diff --git a/docker/docker-compose.2204.58.yaml b/docker/docker-compose.2204.58.yaml index 1296de1..d81654b 100644 --- a/docker/docker-compose.2204.58.yaml +++ b/docker/docker-compose.2204.58.yaml @@ -15,7 +15,7 @@ services: - MAX_ALLOCS_ALLOWED_parse_webpki_roots=422050 - MAX_ALLOCS_ALLOWED_tiny_array_cow_append_contents_of=9050 - MAX_ALLOCS_ALLOWED_tiny_array_non_allocating_operations=0 - - MAX_ALLOCS_ALLOWED_validation=205750 + - MAX_ALLOCS_ALLOWED_validation=120050 - WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error # - SANITIZER_ARG=--sanitize=thread # TSan broken still diff --git a/docker/docker-compose.2204.59.yaml b/docker/docker-compose.2204.59.yaml index 6443eed..4e685af 100644 --- a/docker/docker-compose.2204.59.yaml +++ b/docker/docker-compose.2204.59.yaml @@ -14,7 +14,7 @@ services: - MAX_ALLOCS_ALLOWED_parse_webpki_roots=422050 - MAX_ALLOCS_ALLOWED_tiny_array_cow_append_contents_of=9050 - MAX_ALLOCS_ALLOWED_tiny_array_non_allocating_operations=0 - - MAX_ALLOCS_ALLOWED_validation=205950 + - MAX_ALLOCS_ALLOWED_validation=120050 - WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error # - SANITIZER_ARG=--sanitize=thread # TSan broken still diff --git a/docker/docker-compose.2204.main.yaml b/docker/docker-compose.2204.main.yaml index 2691d74..70d52d7 100644 --- a/docker/docker-compose.2204.main.yaml +++ b/docker/docker-compose.2204.main.yaml @@ -14,7 +14,7 @@ services: - MAX_ALLOCS_ALLOWED_parse_webpki_roots=422050 - MAX_ALLOCS_ALLOWED_tiny_array_cow_append_contents_of=9050 - MAX_ALLOCS_ALLOWED_tiny_array_non_allocating_operations=0 - - MAX_ALLOCS_ALLOWED_validation=205950 + - MAX_ALLOCS_ALLOWED_validation=120050 - WARN_AS_ERROR_ARG=-Xswiftc -warnings-as-errors - IMPORT_CHECK_ARG=--explicit-target-dependency-import-check error # - SANITIZER_ARG=--sanitize=thread # TSan broken still