From 6752699c9902a7dbac85d84502de3432f5011fa9 Mon Sep 17 00:00:00 2001 From: tomer doron Date: Thu, 19 Dec 2019 12:53:36 -0800 Subject: [PATCH] prepare project for public CI (#2) * prepare project for public CI motivation: get ready to open source project changes: * add sanity script * add doc generation script * add docker and docker-compose setup * run swiftformat * remove generate_linux_tests.rb * add template for github PRs * add tempalte for git commit message * add api-breakage detection scipt * fixup * format * fixup --- .github/ISSUE_TEMPLATE.md | 20 ++ .github/PULL_REQUEST_TEMPLATE.md | 13 + .swiftformat | 13 + NOTICE.txt | 9 + Package.swift | 7 +- .../AES/GCM/BoringSSL/AES-GCM_boring.swift | 6 +- .../BoringSSL/ChaChaPoly_boring.swift | 27 +- .../Digests/BoringSSL/Digest_boring.swift | 14 +- .../Key Agreement/BoringSSL/ECDH_boring.swift | 2 +- .../Keys/EC/BoringSSL/Ed25519_boring.swift | 6 +- .../BoringSSL/EllipticCurvePoint_boring.swift | 9 +- .../EC/BoringSSL/EllipticCurve_boring.swift | 11 +- .../EC/BoringSSL/NISTCurvesKeys_boring.swift | 48 ++-- .../Keys/EC/BoringSSL/X25519Keys_boring.swift | 14 +- .../BoringSSL/ECDSASignature_boring.swift | 11 +- .../Signatures/BoringSSL/ECDSA_boring.swift | 3 +- .../Signatures/BoringSSL/EdDSA_boring.swift | 18 +- .../ArbitraryPrecisionInteger_boring.swift | 44 ++-- .../FiniteFieldArithmeticContext_boring.swift | 5 +- .../Util/BoringSSL/SafeCompare_boring.swift | 3 +- .../ArbitraryPrecisionIntegerTests.swift | 2 +- Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift | 24 +- .../BoringSSL/secpECDH_Runner_boring.swift | 10 +- .../Encodings/BoringSSL/DERTests_boring.swift | 2 +- dev/git.commit.template | 14 ++ docker/Dockerfile | 35 +++ docker/docker-compose.1804.51.yaml | 18 ++ docker/docker-compose.yaml | 36 +++ scripts/check_no_api_breakages.sh | 122 +++++++++ scripts/generate_contributors_list.sh | 2 +- scripts/generate_docs.sh | 103 ++++++++ scripts/generate_linux_tests.rb | 231 ------------------ scripts/sanity.sh | 36 ++- 33 files changed, 530 insertions(+), 388 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .swiftformat create mode 100644 dev/git.commit.template create mode 100644 docker/Dockerfile create mode 100644 docker/docker-compose.1804.51.yaml create mode 100644 docker/docker-compose.yaml create mode 100755 scripts/check_no_api_breakages.sh create mode 100755 scripts/generate_docs.sh delete mode 100755 scripts/generate_linux_tests.rb diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..af70e8d5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,20 @@ +### Expected behavior +_[what you expected to happen]_ + +### Actual behavior +_[what actually happened]_ + +### Steps to reproduce + +1. ... +2. ... + +### If possible, minimal yet complete reproducer code (or URL to code) + +_[anything to help us reproducing the issue]_ + +### SwiftLog version/commit hash + +_[the SwiftLog tag/commit hash]_ + +### Swift & OS version (output of `swift --version && uname -a`) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..ab90c7b9 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,13 @@ +_[One line description of your change]_ + +### Motivation: + +_[Explain here the context, and why you're making that change. What is the problem you're trying to solve.]_ + +### Modifications: + +_[Describe the modifications you've done.]_ + +### Result: + +_[After your change, what will change.]_ diff --git a/.swiftformat b/.swiftformat new file mode 100644 index 00000000..4212a065 --- /dev/null +++ b/.swiftformat @@ -0,0 +1,13 @@ +# file options + +--exclude .build + +# format options + +--self insert +--patternlet inline +--stripunusedargs unnamed-only +--comments ignore +--ifdef no-indent + +# rules diff --git a/NOTICE.txt b/NOTICE.txt index f622b4e1..9d59cd38 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -31,3 +31,12 @@ This product contains test vectors from Google's wycheproof project. * https://github.com/google/wycheproof/blob/master/LICENSE * HOMEPAGE: * https://github.com/google/wycheproof + +--- + +This product contains a derivation of various scripts from SwiftNIO. + + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/apple/swift-nio diff --git a/Package.swift b/Package.swift index 0ad1d4bc..f470fb3d 100644 --- a/Package.swift +++ b/Package.swift @@ -27,7 +27,7 @@ import PackageDescription let swiftSettings: [SwiftSetting] = [ .define("CRYPTO_IN_SWIFTPM"), // To develop this on Apple platforms, uncomment this define. - //.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"), + // .define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API"), ] let package = Package( @@ -41,8 +41,8 @@ let package = Package( products: [ .library(name: "Crypto", targets: ["Crypto"]), /* This target is used only for symbol mangling. It's added and removed automatically because it emits build warnings. MANGLE_START - .library(name: "CCryptoBoringSSL", type: .static, targets: ["CCryptoBoringSSL"]), - MANGLE_END */ + .library(name: "CCryptoBoringSSL", type: .static, targets: ["CCryptoBoringSSL"]), + MANGLE_END */ ], dependencies: [], targets: [ @@ -54,4 +54,3 @@ let package = Package( ], cxxLanguageStandard: .cxx11 ) - diff --git a/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift b/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift index ff4bd112..ad2c2ca8 100644 --- a/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift +++ b/Sources/Crypto/AEADs/AES/GCM/BoringSSL/AES-GCM_boring.swift @@ -14,13 +14,13 @@ #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else -import Foundation @_implementationOnly import CCryptoBoringSSL +import Foundation enum OpenSSLAESGCMImpl { @inlinable static func seal - (key: SymmetricKey, message: Plaintext, nonce: AES.GCM.Nonce?, authenticatedData: AuthenticatedData? = nil) throws -> AES.GCM.SealedBox { + (key: SymmetricKey, message: Plaintext, nonce: AES.GCM.Nonce?, authenticatedData: AuthenticatedData? = nil) throws -> AES.GCM.SealedBox { let nonce = nonce ?? AES.GCM.Nonce() let aead = try Self._backingAEAD(key: key) @@ -38,7 +38,7 @@ enum OpenSSLAESGCMImpl { @inlinable static func open - (key: SymmetricKey, sealedBox: AES.GCM.SealedBox, authenticatedData: AuthenticatedData? = nil) throws -> Data { + (key: SymmetricKey, sealedBox: AES.GCM.SealedBox, authenticatedData: AuthenticatedData? = nil) throws -> Data { let aead = try Self._backingAEAD(key: key) if let ad = authenticatedData { diff --git a/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift b/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift index 79d05692..4996a36a 100644 --- a/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift +++ b/Sources/Crypto/AEADs/ChachaPoly/BoringSSL/ChaChaPoly_boring.swift @@ -14,10 +14,9 @@ #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else -import Foundation @_implementationOnly import CCryptoBoringSSL @_implementationOnly import CCryptoBoringSSLShims - +import Foundation enum OpenSSLChaChaPolyImpl { static func encrypt(key: SymmetricKey, message: M, nonce: ChaChaPoly.Nonce?, authenticatedData: AD?) throws -> ChaChaPoly.SealedBox { @@ -50,7 +49,6 @@ enum OpenSSLChaChaPolyImpl { } } - /// An abstraction over a BoringSSL AEAD @usableFromInline enum BoringSSLAEAD { @@ -73,7 +71,6 @@ enum BoringSSLAEAD { } } - extension BoringSSLAEAD { // Arguably this class is excessive, but it's probably better for this API to be as safe as possible // rather than rely on defer statements for our cleanup. @@ -86,7 +83,7 @@ extension BoringSSLAEAD { let rc: CInt = key.withUnsafeBytes { keyPointer in withUnsafeMutablePointer(to: &self.context) { contextPointer in // Create the AEAD context with a default tag length using the given key. - return CCryptoBoringSSLShims_EVP_AEAD_CTX_init(contextPointer, cipher.boringSSLCipher, keyPointer.baseAddress, keyPointer.count, 0, nil) + CCryptoBoringSSLShims_EVP_AEAD_CTX_init(contextPointer, cipher.boringSSLCipher, keyPointer.baseAddress, keyPointer.count, 0, nil) } } guard rc == 1 else { @@ -102,7 +99,8 @@ extension BoringSSLAEAD { } } -// MARK:- Sealing +// MARK: - Sealing + extension BoringSSLAEAD.AEADContext { /// The main entry point for sealing data. Covers the full gamut of types, including discontiguous data types. This must be inlinable. @inlinable @@ -128,7 +126,6 @@ extension BoringSSLAEAD.AEADContext { let contiguousAD = Array(authenticatedData) return try self._sealContiguous(message: contiguousMessage, nonce: nonce, authenticatedData: contiguousAD) } - } /// A fast-path for sealing contiguous data. Also inlinable to gain specialization information. @@ -177,8 +174,8 @@ extension BoringSSLAEAD.AEADContext { } } +// MARK: - Opening -// MARK:- Opening extension BoringSSLAEAD.AEADContext { /// The main entry point for opening data. Covers the full gamut of types, including discontiguous data types. This must be inlinable. @inlinable @@ -220,12 +217,12 @@ extension BoringSSLAEAD.AEADContext { let outputBuffer = UnsafeMutableRawBufferPointer(start: malloc(ciphertext.count)!, count: ciphertext.count) let rc = withUnsafePointer(to: &self.context) { contextPointer in - return CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(contextPointer, - outputBuffer.baseAddress, - nonceBytes.baseAddress, nonceBytes.count, - ciphertext.baseAddress, ciphertext.count, - tagBytes.baseAddress, tagBytes.count, - authenticatedData.baseAddress, authenticatedData.count) + CCryptoBoringSSLShims_EVP_AEAD_CTX_open_gather(contextPointer, + outputBuffer.baseAddress, + nonceBytes.baseAddress, nonceBytes.count, + ciphertext.baseAddress, ciphertext.count, + tagBytes.baseAddress, tagBytes.count, + authenticatedData.baseAddress, authenticatedData.count) } guard rc == 1 else { @@ -239,8 +236,8 @@ extension BoringSSLAEAD.AEADContext { } } +// MARK: - Supported ciphers -// MARK:- Supported ciphers extension BoringSSLAEAD { var boringSSLCipher: OpaquePointer { switch self { diff --git a/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift b/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift index 8dc96a2f..40edc8ae 100644 --- a/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift +++ b/Sources/Crypto/Digests/BoringSSL/Digest_boring.swift @@ -16,15 +16,12 @@ #else @_implementationOnly import CCryptoBoringSSL - -protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate { } - +protocol HashFunctionImplementationDetails: HashFunction where Digest: DigestPrivate {} protocol BoringSSLBackedHashFunction: HashFunctionImplementationDetails { static var digestType: DigestContext.DigestType { get } } - extension Insecure.MD5: BoringSSLBackedHashFunction { static var digestType: DigestContext.DigestType { return .md5 @@ -55,7 +52,6 @@ extension SHA512: BoringSSLBackedHashFunction { } } - struct OpenSSLDigestImpl { private var context: DigestContext @@ -76,19 +72,18 @@ struct OpenSSLDigestImpl { let digestBytes = copyContext.finalize() return digestBytes.withUnsafeBytes { // We force unwrap here because if the digest size is wrong it's an internal error. - return H.Digest(bufferPointer: $0)! + H.Digest(bufferPointer: $0)! } } } - class DigestContext { private var contextPointer: UnsafeMutablePointer init(digest: DigestType) { // We force unwrap because we cannot recover from allocation failure. self.contextPointer = CCryptoBoringSSL_EVP_MD_CTX_new()! - guard 0 != CCryptoBoringSSL_EVP_DigestInit(self.contextPointer, digest.dispatchTable) else { + guard CCryptoBoringSSL_EVP_DigestInit(self.contextPointer, digest.dispatchTable) != 0 else { // We can't do much but crash here. fatalError("Unable to initialize digest state: \(CCryptoBoringSSL_ERR_get_error())") } @@ -97,7 +92,7 @@ class DigestContext { init(copying original: DigestContext) { // We force unwrap because we cannot recover from allocation failure. self.contextPointer = CCryptoBoringSSL_EVP_MD_CTX_new()! - guard 0 != CCryptoBoringSSL_EVP_MD_CTX_copy(self.contextPointer, original.contextPointer) else { + guard CCryptoBoringSSL_EVP_MD_CTX_copy(self.contextPointer, original.contextPointer) != 0 else { // We can't do much but crash here. fatalError("Unable to copy digest state: \(CCryptoBoringSSL_ERR_get_error())") } @@ -130,7 +125,6 @@ class DigestContext { } } - extension DigestContext { struct DigestType { var dispatchTable: OpaquePointer diff --git a/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift b/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift index f294a6e4..2548bd4c 100644 --- a/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift +++ b/Sources/Crypto/Key Agreement/BoringSSL/ECDH_boring.swift @@ -29,6 +29,7 @@ extension P384.KeyAgreement.PrivateKey { return SharedSecret(ss: key) } } + extension P521.KeyAgreement.PrivateKey { internal func openSSLSharedSecretFromKeyAgreement(with publicKeyShare: P521.KeyAgreement.PublicKey) throws -> SharedSecret { let key = try self.impl.key.keyExchange(publicKey: publicKeyShare.impl.key) @@ -36,4 +37,3 @@ extension P521.KeyAgreement.PrivateKey { } } #endif // (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API - diff --git a/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift index 14aac446..5305c4ad 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/Ed25519_boring.swift @@ -14,9 +14,9 @@ #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else -import Foundation @_implementationOnly import CCryptoBoringSSL @_implementationOnly import CCryptoBoringSSLShims +import Foundation // For signing and verifying, we use BoringSSL's Ed25519, not the X25519 stuff. extension Curve25519.Signing { @@ -30,7 +30,7 @@ extension Curve25519.Signing { // BoringSSL's Ed25519 implementation stores the private key concatenated with the public key, so we do // as well. We also store the public key because it makes our lives easier. var publicKey = Array(repeating: UInt8(0), count: 32) - let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) { (privateKeyPtr, privateKeyBytes) in + let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) { privateKeyPtr, privateKeyBytes in privateKeyBytes = 64 publicKey.withUnsafeMutableBytes { publicKeyPtr in CCryptoBoringSSLShims_ED25519_keypair(publicKeyPtr.baseAddress, privateKeyPtr.baseAddress) @@ -60,7 +60,7 @@ extension Curve25519.Signing { throw CryptoKitError.incorrectKeySize } - let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) { (privateKeyPtr, privateKeyBytes) in + let privateKey = SecureBytes(unsafeUninitializedCapacity: 64) { privateKeyPtr, privateKeyBytes in privateKeyBytes = 64 publicKey.withUnsafeMutableBytes { publicKeyPtr in CCryptoBoringSSLShims_ED25519_keypair_from_seed(publicKeyPtr.baseAddress, privateKeyPtr.baseAddress, seedPtr.baseAddress) diff --git a/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurvePoint_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurvePoint_boring.swift index da22d419..8e90b56c 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurvePoint_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurvePoint_boring.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// @_implementationOnly import CCryptoBoringSSL - /// A wrapper around BoringSSL's EC_POINT with some lifetime management. @usableFromInline class EllipticCurvePoint { @@ -30,7 +29,7 @@ class EllipticCurvePoint { try group.withUnsafeGroupPointer { groupPtr in try scalar.withUnsafeBignumPointer { bigNumPtr in - guard 0 != CCryptoBoringSSL_EC_POINT_mul(groupPtr, self._basePoint, bigNumPtr, nil, nil, nil) else { + guard CCryptoBoringSSL_EC_POINT_mul(groupPtr, self._basePoint, bigNumPtr, nil, nil, nil) != 0 else { throw CryptoKitError.internalBoringSSLError() } } @@ -51,8 +50,8 @@ class EllipticCurvePoint { } } +// MARK: - Helpers -// MARK:- Helpers extension EllipticCurvePoint { @inlinable func withPointPointer(_ body: (OpaquePointer) throws -> T) rethrows -> T { @@ -60,14 +59,14 @@ extension EllipticCurvePoint { } @usableFromInline - func affineCoordinates(group: BoringSSLEllipticCurveGroup) throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger) { + func affineCoordinates(group: BoringSSLEllipticCurveGroup) throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger) { var x = ArbitraryPrecisionInteger() var y = ArbitraryPrecisionInteger() try x.withUnsafeMutableBignumPointer { xPtr in try y.withUnsafeMutableBignumPointer { yPtr in try group.withUnsafeGroupPointer { groupPtr in - guard 0 != CCryptoBoringSSL_EC_POINT_get_affine_coordinates_GFp(groupPtr, self._basePoint, xPtr, yPtr, nil) else { + guard CCryptoBoringSSL_EC_POINT_get_affine_coordinates_GFp(groupPtr, self._basePoint, xPtr, yPtr, nil) != 0 else { throw CryptoKitError.internalBoringSSLError() } } diff --git a/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurve_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurve_boring.swift index 9dfba93e..edc40c18 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurve_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/EllipticCurve_boring.swift @@ -13,8 +13,6 @@ //===----------------------------------------------------------------------===// @_implementationOnly import CCryptoBoringSSL - - /// A wrapper around BoringSSL's EC_GROUP object that handles reference counting and /// liveness. @usableFromInline @@ -35,7 +33,8 @@ class BoringSSLEllipticCurveGroup { } } -// MARK:- Helpers +// MARK: - Helpers + extension BoringSSLEllipticCurveGroup { @usableFromInline var coordinateByteCount: Int { @@ -45,7 +44,7 @@ extension BoringSSLEllipticCurveGroup { @usableFromInline func makeUnsafeOwnedECKey() throws -> OpaquePointer { guard let key = CCryptoBoringSSL_EC_KEY_new(), - 1 == CCryptoBoringSSL_EC_KEY_set_group(key, self._group) else { + CCryptoBoringSSL_EC_KEY_set_group(key, self._group) == 1 else { throw CryptoKitError.internalBoringSSLError() } @@ -85,7 +84,8 @@ extension BoringSSLEllipticCurveGroup { } } -// MARK:- CurveName +// MARK: - CurveName + extension BoringSSLEllipticCurveGroup { @usableFromInline enum CurveName { @@ -95,7 +95,6 @@ extension BoringSSLEllipticCurveGroup { } } - extension BoringSSLEllipticCurveGroup.CurveName { @usableFromInline var baseNID: CInt { diff --git a/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift index f1b86bf0..93484649 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/NISTCurvesKeys_boring.swift @@ -14,9 +14,9 @@ #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else -import Foundation @_implementationOnly import CCryptoBoringSSL @_implementationOnly import CCryptoBoringSSLShims +import Foundation @usableFromInline protocol OpenSSLSupportedNISTCurve { @@ -24,7 +24,6 @@ protocol OpenSSLSupportedNISTCurve { static var group: BoringSSLEllipticCurveGroup { get } } - extension OpenSSLSupportedNISTCurve { @inlinable static var coordinateByteCount: Int { @@ -32,7 +31,6 @@ extension OpenSSLSupportedNISTCurve { } } - extension P256 { @usableFromInline struct CurveDetails: OpenSSLSupportedNISTCurve { @@ -43,7 +41,6 @@ extension P256 { } } - extension P384 { @usableFromInline struct CurveDetails: OpenSSLSupportedNISTCurve { @@ -54,7 +51,6 @@ extension P384 { } } - extension P521 { @usableFromInline struct CurveDetails: OpenSSLSupportedNISTCurve { @@ -65,7 +61,6 @@ extension P521 { } } - @usableFromInline struct OpenSSLNISTCurvePrivateKeyImpl { @usableFromInline @@ -96,7 +91,6 @@ struct OpenSSLNISTCurvePrivateKeyImpl { } } - @usableFromInline struct OpenSSLNISTCurvePublicKeyImpl { @usableFromInline @@ -135,7 +129,6 @@ struct OpenSSLNISTCurvePublicKeyImpl { } } - /// A simple wrapper for an EC_KEY pointer for a private key. This manages the lifetime of that pointer and /// allows some helper operations. @usableFromInline @@ -150,14 +143,14 @@ class BoringSSLECPrivateKeyWrapper { // If we've been asked to generate a compact representable key, we need to try a few times. This loop shouldn't // execute more than 100 times: if it does, we'll crash because something bad is happening. - for _ in 0..<100 { + for _ in 0 ..< 100 { // We generate FIPS compliant keys to match the behaviour of CryptoKit on Apple platforms. - guard 0 != CCryptoBoringSSL_EC_KEY_generate_key(self.key) else { + guard CCryptoBoringSSL_EC_KEY_generate_key(self.key) != 0 else { throw CryptoKitError.internalBoringSSLError() } // We want to generate FIPS compliant keys. If this isn't, loop around again. - if 0 == CCryptoBoringSSL_EC_KEY_check_fips(self.key) { + if CCryptoBoringSSL_EC_KEY_check_fips(self.key) == 0 { continue } @@ -198,7 +191,7 @@ class BoringSSLECPrivateKeyWrapper { func setPrivateKey(_ keyScalar: ArbitraryPrecisionInteger) throws { try keyScalar.withUnsafeBignumPointer { bigNum in - guard 0 != CCryptoBoringSSL_EC_KEY_set_private_key(self.key, bigNum) else { + guard CCryptoBoringSSL_EC_KEY_set_private_key(self.key, bigNum) != 0 else { throw CryptoKitError.internalBoringSSLError() } } @@ -209,7 +202,7 @@ class BoringSSLECPrivateKeyWrapper { try y.withUnsafeMutableBignumPointer { yPointer in // This function is missing some const declarations here, which is why we need the bignums inout. // If that gets fixed, we can clean this function up. - guard 0 != CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer) else { + guard CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer) != 0 else { throw CryptoKitError.internalBoringSSLError() } } @@ -218,7 +211,7 @@ class BoringSSLECPrivateKeyWrapper { func setPublicKey(point: EllipticCurvePoint) throws { try point.withPointPointer { ecPointer in - guard 0 != CCryptoBoringSSL_EC_KEY_set_public_key(self.key, ecPointer) else { + guard CCryptoBoringSSL_EC_KEY_set_public_key(self.key, ecPointer) != 0 else { throw CryptoKitError.internalBoringSSLError() } } @@ -275,7 +268,7 @@ class BoringSSLECPrivateKeyWrapper { let pubKeyPoint = publicKey.publicKeyPoint let outputSize = Curve.group.coordinateByteCount - return try SecureBytes(unsafeUninitializedCapacity: outputSize) { (secretPtr, secretSize) in + return try SecureBytes(unsafeUninitializedCapacity: outputSize) { secretPtr, secretSize in let rc = pubKeyPoint.withPointPointer { pointPtr in CCryptoBoringSSL_ECDH_compute_key(secretPtr.baseAddress, secretPtr.count, pointPtr, self.key, nil) } @@ -290,7 +283,7 @@ class BoringSSLECPrivateKeyWrapper { func sign(digest: D) throws -> ECDSASignature { let optionalRawSignature: UnsafeMutablePointer? = digest.withUnsafeBytes { digestPtr in - return CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key) + CCryptoBoringSSLShims_ECDSA_do_sign(digestPtr.baseAddress, digestPtr.count, self.key) } guard let rawSignature = optionalRawSignature else { throw CryptoKitError.internalBoringSSLError() @@ -304,7 +297,6 @@ class BoringSSLECPrivateKeyWrapper { } } - /// A simple wrapper for an EC_KEY pointer for a public key. This manages the lifetime of that pointer and /// allows some helper operations. @usableFromInline @@ -428,7 +420,7 @@ class BoringSSLECPublicKeyWrapper { try y.withUnsafeMutableBignumPointer { yPointer in // This function is missing some const declarations here, which is why we need the bignums inout. // If that gets fixed, we can clean this function up. - guard 0 != CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer) else { + guard CCryptoBoringSSL_EC_KEY_set_public_key_affine_coordinates(self.key, xPointer, yPointer) != 0 else { throw CryptoKitError.internalBoringSSLError() } } @@ -438,7 +430,7 @@ class BoringSSLECPublicKeyWrapper { func isValidSignature(_ signature: ECDSASignature, for digest: D) -> Bool { let rc: CInt = signature.withUnsafeSignaturePointer { signaturePointer in digest.withUnsafeBytes { digestPointer in - return CCryptoBoringSSLShims_ECDSA_do_verify(digestPointer.baseAddress, digestPointer.count, signaturePointer, self.key) + CCryptoBoringSSLShims_ECDSA_do_verify(digestPointer.baseAddress, digestPointer.count, signaturePointer, self.key) } } @@ -446,23 +438,22 @@ class BoringSSLECPublicKeyWrapper { } } - extension ContiguousBytes { func readx963PrivateNumbers() throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger, k: ArbitraryPrecisionInteger) { // The x9.63 private key format is a discriminator byte (0x4) concatenated with the X and Y points // of the public key, and the K value of the secret scalar. Let's load that in. return try self.withUnsafeBytes { bytesPtr in guard bytesPtr.first == 0x04 else { - throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms. + throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms. } let stride = (bytesPtr.count - 1) / 3 var offset = 1 - let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)]) + let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)]) offset += stride - let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)]) + let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)]) offset += stride - let kPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)]) + let kPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)]) let x = try ArbitraryPrecisionInteger(bytes: xPointer) let y = try ArbitraryPrecisionInteger(bytes: yPointer) @@ -478,7 +469,7 @@ extension ContiguousBytes { // of the public key. Let's load that in. return try self.withUnsafeBytes { bytesPtr in guard bytesPtr.first == 0x04 else { - throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms. + throw CryptoKitError.incorrectKeySize // This is the same error CryptoKit throws on Apple platforms. } return try readRawPublicNumbers(copyingBytes: UnsafeRawBufferPointer(rebasing: bytesPtr[1...])) @@ -488,11 +479,11 @@ extension ContiguousBytes { @usableFromInline func readRawPublicNumbers(copyingBytes bytesPtr: UnsafeRawBufferPointer) throws -> (x: ArbitraryPrecisionInteger, y: ArbitraryPrecisionInteger) { - let stride = (bytesPtr.count) / 2 + let stride = bytesPtr.count / 2 var offset = 0 - let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)]) + let xPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)]) offset += stride - let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset..<(offset + stride)]) + let yPointer = UnsafeRawBufferPointer(rebasing: bytesPtr[offset ..< (offset + stride)]) // We cannot handle allocation errors, so we check for fatal error. let x = try ArbitraryPrecisionInteger(bytes: xPointer) @@ -501,7 +492,6 @@ func readRawPublicNumbers(copyingBytes bytesPtr: UnsafeRawBufferPointer) throws return (x: x, y: y) } - /// In a number of places we need to know if an EC key is compact representable. This function implements that check. /// /// The check is defined in https://tools.ietf.org/id/draft-jivsov-ecc-compact-05.html#rfc.section.4.2.1. Specifically, a diff --git a/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift b/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift index 716b6bd9..4050641e 100644 --- a/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift +++ b/Sources/Crypto/Keys/EC/BoringSSL/X25519Keys_boring.swift @@ -14,9 +14,9 @@ #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else -import Foundation @_implementationOnly import CCryptoBoringSSL @_implementationOnly import CCryptoBoringSSLShims +import Foundation extension Curve25519.KeyAgreement { @usableFromInline @@ -60,13 +60,13 @@ extension Curve25519.KeyAgreement { init() { var publicKey = Array(repeating: UInt8(0), count: Curve25519.KeyAgreement.keySizeBytes) - self.key = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { (privateKeyBytes, privateKeySize) in + self.key = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { privateKeyBytes, privateKeySize in publicKey.withUnsafeMutableBytes { publicKeyBytes in precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes) precondition(privateKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes) CCryptoBoringSSLShims_X25519_keypair(publicKeyBytes.baseAddress, privateKeyBytes.baseAddress) } - privateKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing. + privateKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing. } self.publicKey = .init(publicKey) } @@ -77,10 +77,10 @@ extension Curve25519.KeyAgreement { throw CryptoKitError.incorrectKeySize } - return Array(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { (publicKeyBytes, publicKeySize) in + return Array(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { publicKeyBytes, publicKeySize in precondition(publicKeyBytes.count >= Curve25519.KeyAgreement.keySizeBytes) CCryptoBoringSSLShims_X25519_public_from_private(publicKeyBytes.baseAddress, privatePointer.baseAddress) - publicKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing. + publicKeySize = Curve25519.KeyAgreement.keySizeBytes // We always use the whole thing. } } @@ -90,7 +90,7 @@ extension Curve25519.KeyAgreement { @usableFromInline func sharedSecretFromKeyAgreement(with publicKeyShare: OpenSSLCurve25519PublicKeyImpl) throws -> SharedSecret { - let sharedSecret = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { (secretPointer, secretSize) in + let sharedSecret = SecureBytes(unsafeUninitializedCapacity: Curve25519.KeyAgreement.keySizeBytes) { secretPointer, secretSize in self.key.withUnsafeBytes { privateKeyPointer in // We precondition on all of these sizes because bounds checking is cool. // These are fatal instead of guards because we allocated the secret (so it must be right), @@ -108,7 +108,7 @@ extension Curve25519.KeyAgreement { CCryptoBoringSSLShims_X25519(secretPointer.baseAddress, privateKeyPointer.baseAddress, publicKeyShare.keyBytes) } - secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it. + secretSize = Curve25519.KeyAgreement.keySizeBytes // We always use all of it. } return SharedSecret(ss: sharedSecret) diff --git a/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift b/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift index 6ec8b53b..fc1fbf24 100644 --- a/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift +++ b/Sources/Crypto/Signatures/BoringSSL/ECDSASignature_boring.swift @@ -11,10 +11,9 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import Foundation @_implementationOnly import CCryptoBoringSSL @_implementationOnly import CCryptoBoringSSLShims - +import Foundation /// A wrapper around BoringSSL's ECDSA_SIG with some lifetime management. class ECDSASignature { @@ -75,8 +74,8 @@ class ECDSASignature { @usableFromInline var components: (r: ArbitraryPrecisionInteger, s: ArbitraryPrecisionInteger) { - var rPtr: UnsafePointer? = nil - var sPtr: UnsafePointer? = nil + var rPtr: UnsafePointer? + var sPtr: UnsafePointer? // We force-unwrap here because a valid ECDSA_SIG cannot fail to have both R and S components. CCryptoBoringSSL_ECDSA_SIG_get0(self._baseSig, &rPtr, &sPtr) @@ -85,9 +84,9 @@ class ECDSASignature { @usableFromInline var derBytes: Data { - var dataPtr: UnsafeMutablePointer? = nil + var dataPtr: UnsafeMutablePointer? var length = 0 - guard 1 == CCryptoBoringSSL_ECDSA_SIG_to_bytes(&dataPtr, &length, self._baseSig) else { + guard CCryptoBoringSSL_ECDSA_SIG_to_bytes(&dataPtr, &length, self._baseSig) == 1 else { fatalError("Unable to marshal signature to DER") } defer { diff --git a/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift b/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift index bd0b5c53..8625ad6c 100644 --- a/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift +++ b/Sources/Crypto/Signatures/BoringSSL/ECDSA_boring.swift @@ -14,9 +14,8 @@ #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else -import Foundation @_implementationOnly import CCryptoBoringSSL - +import Foundation extension Data { init(derSignature derBytes: D, over: Curve.Type = Curve.self) throws { diff --git a/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift b/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift index a548a2d2..fba0e14d 100644 --- a/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift +++ b/Sources/Crypto/Signatures/BoringSSL/EdDSA_boring.swift @@ -14,9 +14,9 @@ #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && CRYPTO_IN_SWIFTPM && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @_exported import CryptoKit #else -import Foundation @_implementationOnly import CCryptoBoringSSL @_implementationOnly import CCryptoBoringSSLShims +import Foundation extension Curve25519.Signing.PublicKey { // We do this to enable inlinability on these methods. @@ -49,8 +49,8 @@ extension Curve25519.Signing.PublicKey { @inlinable func openSSLIsValidSignature(contiguousSignature signature: S, contiguousData data: D) -> Bool { return signature.withUnsafeBytes { signaturePointer in - return data.withUnsafeBytes { dataPointer in - return self.openSSLIsValidSignature(signaturePointer: signaturePointer, dataPointer: dataPointer) + data.withUnsafeBytes { dataPointer in + self.openSSLIsValidSignature(signaturePointer: signaturePointer, dataPointer: dataPointer) } } } @@ -61,10 +61,10 @@ extension Curve25519.Signing.PublicKey { precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureLength) precondition(self.keyBytes.count == 32) let rc: CInt = self.keyBytes.withUnsafeBytes { keyBytesPtr in - return CCryptoBoringSSLShims_ED25519_verify(dataPointer.baseAddress, - dataPointer.count, - signaturePointer.baseAddress, - keyBytesPtr.baseAddress) + CCryptoBoringSSLShims_ED25519_verify(dataPointer.baseAddress, + dataPointer.count, + signaturePointer.baseAddress, + keyBytesPtr.baseAddress) } return rc == 1 @@ -80,7 +80,7 @@ extension Curve25519.Signing.PrivateKey { return try self.openSSLSignature(forContiguousData: Array(data)) } } - + @inlinable func openSSLSignature(forContiguousData data: C) throws -> Data { return try data.withUnsafeBytes { @@ -93,7 +93,7 @@ extension Curve25519.Signing.PrivateKey { var signature = Data(repeating: 0, count: Curve25519.Signing.PublicKey.signatureLength) let rc: CInt = signature.withUnsafeMutableBytes { signaturePointer in - return self.key.withUnsafeBytes { keyPointer in + self.key.withUnsafeBytes { keyPointer in precondition(signaturePointer.count == Curve25519.Signing.PublicKey.signatureLength) precondition(keyPointer.count == ED25519_PRIVATE_KEY_LEN) diff --git a/Sources/Crypto/Util/BoringSSL/ArbitraryPrecisionInteger_boring.swift b/Sources/Crypto/Util/BoringSSL/ArbitraryPrecisionInteger_boring.swift index 7cefdaa5..f0c7aa71 100644 --- a/Sources/Crypto/Util/BoringSSL/ArbitraryPrecisionInteger_boring.swift +++ b/Sources/Crypto/Util/BoringSSL/ArbitraryPrecisionInteger_boring.swift @@ -11,9 +11,9 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import Foundation @_implementationOnly import CCryptoBoringSSL @_implementationOnly import CCryptoBoringSSLShims +import Foundation /// A wrapper around the OpenSSL BIGNUM object that is appropriately lifetime managed, /// and that provides better Swift types for this object. @@ -41,7 +41,8 @@ struct ArbitraryPrecisionInteger { } } -// MARK:- BackingStorage +// MARK: - BackingStorage + extension ArbitraryPrecisionInteger { final class BackingStorage { private var _backing: BIGNUM @@ -53,7 +54,7 @@ extension ArbitraryPrecisionInteger { init(copying original: UnsafePointer) throws { self._backing = BIGNUM() - guard nil != CCryptoBoringSSL_BN_copy(&self._backing, original) else { + guard CCryptoBoringSSL_BN_copy(&self._backing, original) != nil else { throw CryptoKitError.internalBoringSSLError() } } @@ -62,7 +63,7 @@ extension ArbitraryPrecisionInteger { self._backing = BIGNUM() try original.withUnsafeMutableBignumPointer { bnPtr in - guard nil != CCryptoBoringSSL_BN_copy(&self._backing, bnPtr) else { + guard CCryptoBoringSSL_BN_copy(&self._backing, bnPtr) != nil else { throw CryptoKitError.internalBoringSSLError() } } @@ -84,14 +85,14 @@ extension ArbitraryPrecisionInteger { } } -// MARK:- Extra initializers +// MARK: - Extra initializers + extension ArbitraryPrecisionInteger { init(bytes: Bytes) throws { self._backing = try BackingStorage(bytes: bytes) } } - extension ArbitraryPrecisionInteger.BackingStorage { convenience init(bytes: Bytes) throws { self.init() @@ -105,8 +106,8 @@ extension ArbitraryPrecisionInteger.BackingStorage { } } +// MARK: - Pointer helpers -// MARK:- Pointer helpers extension ArbitraryPrecisionInteger { func withUnsafeBignumPointer(_ body: (UnsafePointer) throws -> T) rethrows -> T { return try self._backing.withUnsafeBignumPointer(body) @@ -122,7 +123,6 @@ extension ArbitraryPrecisionInteger { } } - extension ArbitraryPrecisionInteger.BackingStorage { func withUnsafeBignumPointer(_ body: (UnsafePointer) throws -> T) rethrows -> T { return try body(&self._backing) @@ -133,13 +133,13 @@ extension ArbitraryPrecisionInteger.BackingStorage { } } +// MARK: - Other helpers -// MARK:- Other helpers extension ArbitraryPrecisionInteger { /* private but @usableFromInline */ @usableFromInline static func _compare(lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> CInt { return lhs.withUnsafeBignumPointer { lhsPtr in rhs.withUnsafeBignumPointer { rhsPtr in - return CCryptoBoringSSL_BN_cmp(lhsPtr, rhsPtr) + CCryptoBoringSSL_BN_cmp(lhsPtr, rhsPtr) } } } @@ -147,7 +147,7 @@ extension ArbitraryPrecisionInteger { // This lets us check the sign of an ArbitraryPrecisionInteger. /* private but @usableFromInline */ @usableFromInline var _positive: Bool { return self.withUnsafeBignumPointer { - return CCryptoBoringSSL_BN_is_negative($0) == 0 + CCryptoBoringSSL_BN_is_negative($0) == 0 } } @@ -202,8 +202,8 @@ extension ArbitraryPrecisionInteger { } } +// MARK: - Equatable -// MARK:- Equatable extension ArbitraryPrecisionInteger: Equatable { @inlinable static func == (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> Bool { @@ -211,8 +211,8 @@ extension ArbitraryPrecisionInteger: Equatable { } } +// MARK: - Comparable -// MARK:- Comparable extension ArbitraryPrecisionInteger: Comparable { @inlinable static func < (lhs: ArbitraryPrecisionInteger, rhs: ArbitraryPrecisionInteger) -> Bool { @@ -235,12 +235,12 @@ extension ArbitraryPrecisionInteger: Comparable { } } +// MARK: - ExpressibleByIntegerLiteral -// MARK:- ExpressibleByIntegerLiteral -extension ArbitraryPrecisionInteger: ExpressibleByIntegerLiteral { } +extension ArbitraryPrecisionInteger: ExpressibleByIntegerLiteral {} +// MARK: - AdditiveArithmetic -// MARK:- AdditiveArithmetic extension ArbitraryPrecisionInteger: AdditiveArithmetic { @inlinable static var zero: ArbitraryPrecisionInteger { @@ -300,8 +300,8 @@ extension ArbitraryPrecisionInteger: AdditiveArithmetic { } } +// MARK: - Numeric -// MARK:- Numeric extension ArbitraryPrecisionInteger: Numeric { @usableFromInline typealias Magnitude = Self @@ -357,8 +357,8 @@ extension ArbitraryPrecisionInteger: Numeric { } } +// MARK: - SignedNumeric -// MARK:- SignedNumeric extension ArbitraryPrecisionInteger: SignedNumeric { @usableFromInline mutating func negate() { @@ -370,8 +370,8 @@ extension ArbitraryPrecisionInteger: SignedNumeric { } } +// MARK: - Serializing -// MARK:- Serializing extension Data { /// Serializes an ArbitraryPrecisionInteger padded out to a certain minimum size. @usableFromInline @@ -399,8 +399,8 @@ extension Data { } } +// MARK: - Printing -// MARK:- Printing extension ArbitraryPrecisionInteger: CustomDebugStringConvertible { @usableFromInline var debugDescription: String { @@ -418,10 +418,10 @@ extension ArbitraryPrecisionInteger: CustomDebugStringConvertible { return "ArbitraryPrecisionInteger: (error generating representation)" } - var stringPointer: UnsafePointer? = nil + var stringPointer: UnsafePointer? var length: Int = 0 - guard 1 == CCryptoBoringSSL_BIO_mem_contents(bio, &stringPointer, &length) else { + guard CCryptoBoringSSL_BIO_mem_contents(bio, &stringPointer, &length) == 1 else { return "ArbitraryPrecisionInteger: (error generating representation)" } diff --git a/Sources/Crypto/Util/BoringSSL/FiniteFieldArithmeticContext_boring.swift b/Sources/Crypto/Util/BoringSSL/FiniteFieldArithmeticContext_boring.swift index ada01159..8cec7528 100644 --- a/Sources/Crypto/Util/BoringSSL/FiniteFieldArithmeticContext_boring.swift +++ b/Sources/Crypto/Util/BoringSSL/FiniteFieldArithmeticContext_boring.swift @@ -11,9 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import Foundation @_implementationOnly import CCryptoBoringSSL - +import Foundation /// A context for performing mathematical operations on ArbitraryPrecisionIntegers over a finite field. /// @@ -47,8 +46,8 @@ class FiniteFieldArithmeticContext { } } +// MARK: - Arithmetic operations -// MARK:- Arithmetic operations extension FiniteFieldArithmeticContext { @usableFromInline func square(_ input: ArbitraryPrecisionInteger) throws -> ArbitraryPrecisionInteger { diff --git a/Sources/Crypto/Util/BoringSSL/SafeCompare_boring.swift b/Sources/Crypto/Util/BoringSSL/SafeCompare_boring.swift index 4105b018..76ea6da5 100644 --- a/Sources/Crypto/Util/BoringSSL/SafeCompare_boring.swift +++ b/Sources/Crypto/Util/BoringSSL/SafeCompare_boring.swift @@ -24,7 +24,6 @@ internal func openSSLSafeCompare(_ l } } - /// A straightforward constant-time comparison function for any two collections of bytes. @inlinable internal func constantTimeCompare(_ lhs: LHS, _ rhs: RHS) -> Bool where LHS.Element == UInt8, RHS.Element == UInt8 { @@ -32,5 +31,5 @@ internal func constantTimeCompare(_ lhs: LHS, return false } - return 0 == zip(lhs, rhs).reduce(into: 0) { $0 |= $1.0 ^ $1.1 } + return zip(lhs, rhs).reduce(into: 0) { $0 |= $1.0 ^ $1.1 } == 0 } diff --git a/Tests/CryptoTests/BoringSSL/ArbitraryPrecisionIntegerTests.swift b/Tests/CryptoTests/BoringSSL/ArbitraryPrecisionIntegerTests.swift index f5392232..f151402a 100644 --- a/Tests/CryptoTests/BoringSSL/ArbitraryPrecisionIntegerTests.swift +++ b/Tests/CryptoTests/BoringSSL/ArbitraryPrecisionIntegerTests.swift @@ -11,8 +11,8 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import XCTest @testable import Crypto +import XCTest final class ArbitraryPrecisionIntegerTests: XCTestCase { func testSimpleArithmetic() { diff --git a/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift b/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift index ab15d8de..44a26f8f 100644 --- a/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift +++ b/Tests/CryptoTests/ECDH/BoringSSL/ASN1.swift @@ -20,8 +20,8 @@ import XCTest #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @testable import CryptoKit #else -@testable import Crypto @_implementationOnly import CCryptoBoringSSL +@testable import Crypto #endif // This module implements "just enough" ASN.1. Specifically, we implement exactly enough ASN.1 DER parsing to handle @@ -68,8 +68,8 @@ import XCTest // // This is the complete set of things we need to be able to parse. It's not that big. Let's see how the code looks. +// MARK: - SPKI -// MARK:- SPKI struct ASN1SubjectPublicKeyInfo { var algorithm: ASN1AlgorithmIdentifier @@ -88,8 +88,8 @@ struct ASN1SubjectPublicKeyInfo { } } +// MARK: - AlgorithmIdentifier -// MARK:- AlgorithmIdentifier struct ASN1AlgorithmIdentifier { var algorithm: ASN1ObjectIdentifier @@ -108,8 +108,8 @@ struct ASN1AlgorithmIdentifier { } } +// MARK: - Bitstring -// MARK:- Bitstring // A bitstring is a representation of...well...some bits. struct ASN1BitString { private var bytes: [UInt8] @@ -135,14 +135,14 @@ struct ASN1BitString { } } - extension ASN1BitString: ContiguousBytes { func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R { return try self.bytes.withUnsafeBytes(body) } } -// MARK:- ObjectIdentifier +// MARK: - ObjectIdentifier + // An Object Identifier is a representation of some kind of object: really any kind of object. // // It represents a node in an OID hierarchy, and is usually represented as an ordered sequence of numbers. @@ -200,7 +200,7 @@ struct ASN1ObjectIdentifier { case ..<40: oidComponents.append(0) oidComponents.append(subcomponents.first!) - case 40..<80: + case 40 ..< 80: oidComponents.append(1) oidComponents.append(subcomponents.first! - 40) default: @@ -214,9 +214,7 @@ struct ASN1ObjectIdentifier { } } - -extension ASN1ObjectIdentifier: Hashable { } - +extension ASN1ObjectIdentifier: Hashable {} extension ASN1ObjectIdentifier: ExpressibleByArrayLiteral { init(arrayLiteral elements: UInt...) { @@ -224,7 +222,6 @@ extension ASN1ObjectIdentifier: ExpressibleByArrayLiteral { } } - extension ASN1ObjectIdentifier { enum NamedCurves { static let secp256r1: ASN1ObjectIdentifier = [1, 2, 840, 10045, 3, 1, 7] @@ -239,8 +236,8 @@ extension ASN1ObjectIdentifier { } } +// MARK: - Helpers -// MARK:- Helpers extension ArraySlice where Element == UInt8 { /// Returns an ArraySlice with the length of the ASN.1 section, and slices this slice to cover the remaining bytes. /// Requires the length to be at `startIndex`. @@ -292,7 +289,7 @@ extension ArraySlice where Element == UInt8 { throw ECDHTestErrors.ParseSPKIFailure } - let oidSlice = self[self.startIndex...subidentifierEndIndex] + let oidSlice = self[self.startIndex ... subidentifierEndIndex] self = self[self.index(after: subidentifierEndIndex)...] // We need to compact the bits. These are 7-bit integers, which is really awkward. @@ -300,7 +297,6 @@ extension ArraySlice where Element == UInt8 { } } - extension UInt { init(bigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 { guard bytes.count <= MemoryLayout.size else { diff --git a/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift b/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift index 627b5815..7dcbaec7 100644 --- a/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift +++ b/Tests/CryptoTests/ECDH/BoringSSL/secpECDH_Runner_boring.swift @@ -20,14 +20,13 @@ import XCTest #if (os(macOS) || os(iOS) || os(watchOS) || os(tvOS)) && !CRYPTO_IN_SWIFTPM_FORCE_BUILD_API @testable import CryptoKit #else -@testable import Crypto @_implementationOnly import CCryptoBoringSSL +@testable import Crypto #endif - extension NISTECDHTests { func testGroupOpenSSL(group: ECDHTestGroup, privateKeys: PrivKey.Type, onCurve curve: Curve.Type) { - func padKeyIfNecessary(vector: String, curveDetails: OpenSSLSupportedNISTCurve.Type) -> Array { + func padKeyIfNecessary(vector: String, curveDetails: OpenSSLSupportedNISTCurve.Type) -> [UInt8] { let hexStringFromVector = (vector.count % 2 == 0) ? vector : "0\(vector)" return try! Array(hexString: hexStringFromVector) } @@ -37,12 +36,12 @@ extension NISTECDHTests { let pkBytes = try Array(hexString: testVector.publicKey) let publicKey = try PrivKey.PublicKey(derBytes: pkBytes, curve: Curve.self) - var privateBytes = Array() + var privateBytes = [UInt8]() privateBytes = padKeyIfNecessary(vector: testVector.privateKey, curveDetails: curve) let privateKey = try PrivKey(rawRepresentation: privateBytes) - let result = try privateKey.sharedSecretFromKeyAgreement(with: (publicKey as! PrivKey.P)) + let result = try privateKey.sharedSecretFromKeyAgreement(with: publicKey as! PrivKey.P) let expectedResult = try Array(hexString: testVector.shared) @@ -60,7 +59,6 @@ extension NISTECDHTests { } } - extension NISTECPublicKey { /// Creates the given EC public key using the DER encoding of the key. init(derBytes: [UInt8], curve: Curve.Type = Curve.self) throws { diff --git a/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift b/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift index 938dc1fc..837a0d1f 100644 --- a/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift +++ b/Tests/CryptoTests/Encodings/BoringSSL/DERTests_boring.swift @@ -23,7 +23,7 @@ import XCTest #endif extension DERTests { - func openSSLCoordinateSizeForCurve(_ curve: Curve.Type) -> Int { + func openSSLCoordinateSizeForCurve(_: Curve.Type) -> Int { return Curve.coordinateByteCount } } diff --git a/dev/git.commit.template b/dev/git.commit.template new file mode 100644 index 00000000..c52bfa1a --- /dev/null +++ b/dev/git.commit.template @@ -0,0 +1,14 @@ +One line description of your change + +Motivation: + +Explain here the context, and why you're making that change. +What is the problem you're trying to solve. + +Modifications: + +Describe the modifications you've done. + +Result: + +After your change, what will change. diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 00000000..c769b77e --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,35 @@ +ARG swift_version=5.0 +ARG ubuntu_version=bionic +FROM swift:$swift_version-$ubuntu_version +# needed to do again after FROM due to docker limitation +ARG swift_version +ARG ubuntu_version + +# set as UTF-8 +RUN apt-get update && apt-get install -y locales locales-all +ENV LC_ALL en_US.UTF-8 +ENV LANG en_US.UTF-8 +ENV LANGUAGE en_US.UTF-8 + +# dependencies +RUN apt-get update && apt-get install -y wget +RUN apt-get update && apt-get install -y lsof dnsutils netcat-openbsd net-tools curl jq # used by integration tests + +# ruby and jazzy for docs generation +RUN apt-get update && apt-get install -y ruby ruby-dev libsqlite3-dev +RUN gem install jazzy --no-ri --no-rdoc + +# tools +RUN mkdir -p $HOME/.tools +RUN echo 'export PATH="$HOME/.tools:$PATH"' >> $HOME/.profile + +# script to allow mapping framepointers on linux (until part of the toolchain) +RUN wget -q https://raw.githubusercontent.com/apple/swift/master/utils/symbolicate-linux-fatal -O $HOME/.tools/symbolicate-linux-fatal +RUN chmod 755 $HOME/.tools/symbolicate-linux-fatal + +# swiftformat (until part of the toolchain) + +ARG swiftformat_version=0.40.12 +RUN git clone --branch $swiftformat_version --depth 1 https://github.com/nicklockwood/SwiftFormat $HOME/.tools/swift-format +RUN cd $HOME/.tools/swift-format && swift build -c release +RUN ln -s $HOME/.tools/swift-format/.build/release/swiftformat $HOME/.tools/swiftformat diff --git a/docker/docker-compose.1804.51.yaml b/docker/docker-compose.1804.51.yaml new file mode 100644 index 00000000..a286bc6f --- /dev/null +++ b/docker/docker-compose.1804.51.yaml @@ -0,0 +1,18 @@ +version: "3" + +services: + + runtime-setup: + image: swift-crypto:18.04-5.1 + build: + args: + ubuntu_version: "bionic" + swift_version: "5.1" + + test: + image: swift-crypto:18.04-5.1 + environment: [] + #- SANITIZER_ARG=--sanitize=thread + + shell: + image: swift-crypto:18.04-5.1 diff --git a/docker/docker-compose.yaml b/docker/docker-compose.yaml new file mode 100644 index 00000000..cfd45497 --- /dev/null +++ b/docker/docker-compose.yaml @@ -0,0 +1,36 @@ +# this file is not designed to be run directly +# instead, use the docker-compose.. files +# eg docker-compose -f docker/docker-compose.yaml -f docker/docker-compose.1804.51.yaml run test +version: "3" + +services: + + runtime-setup: + image: swift-crypto:default + build: + context: . + dockerfile: Dockerfile + + common: &common + image: swift-crypto:default + depends_on: [runtime-setup] + volumes: + - ~/.ssh:/root/.ssh + - ..:/code + working_dir: /code + + sanity: + <<: *common + command: /bin/bash -xcl "./scripts/sanity.sh" + + test: + <<: *common + # FIXME: get rid of existing warnings + #command: /bin/bash -xcl "swift test --enable-test-discovery -Xswiftc -warnings-as-errors $${SANITIZER_ARG-}" + command: /bin/bash -xcl "swift test --enable-test-discovery" + + # util + + shell: + <<: *common + entrypoint: /bin/bash diff --git a/scripts/check_no_api_breakages.sh b/scripts/check_no_api_breakages.sh new file mode 100755 index 00000000..cf03fa79 --- /dev/null +++ b/scripts/check_no_api_breakages.sh @@ -0,0 +1,122 @@ +#!/bin/bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftCrypto open source project +## +## Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors +## Licensed under Apache License v2.0 +## +## See LICENSE.txt for license information +## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +set -eu + +# repodir +function all_modules() { + local repodir="$1" + ( + set -eu + cd "$repodir" + swift package dump-package | jq '.products | + map(select(.type | has("library") )) | + map(.name) | .[]' | tr -d '"' + ) +} + +# repodir tag output +function build_and_do() { + local repodir=$1 + local tag=$2 + local output=$3 + + ( + cd "$repodir" + git checkout -q "$tag" + swift build + while read -r module; do + swift api-digester -sdk "$sdk" -dump-sdk -module "$module" \ + -o "$output/$module.json" -I "$repodir/.build/debug" + done < <(all_modules "$repodir") + ) +} + +function usage() { + echo >&2 "Usage: $0 REPO-GITHUB-URL NEW-VERSION OLD-VERSIONS..." + echo >&2 + echo >&2 "This script requires a Swift 5.1+ toolchain." + echo >&2 + echo >&2 "Examples:" + echo >&2 + echo >&2 "Check between master and tag 2.1.1 of swift-nio:" + echo >&2 " $0 https://github.com/apple/swift-nio master 2.1.1" + echo >&2 + echo >&2 "Check between HEAD and commit 64cf63d7 using the provided toolchain:" + echo >&2 " xcrun --toolchain org.swift.5120190702a $0 ../some-local-repo HEAD 64cf63d7" +} + +if [[ $# -lt 3 ]]; then + usage + exit 1 +fi + +sdk=/ +if [[ "$(uname -s)" == Darwin ]]; then + sdk=$(xcrun --show-sdk-path) +fi + +hash jq 2> /dev/null || { echo >&2 "ERROR: jq must be installed"; exit 1; } +tmpdir=$(mktemp -d /tmp/.check-api_XXXXXX) +repo_url=$1 +new_tag=$2 +shift 2 + +repodir="$tmpdir/repo" +git clone "$repo_url" "$repodir" +git -C "$repodir" fetch -q origin '+refs/pull/*:refs/remotes/origin/pr/*' +errors=0 + +for old_tag in "$@"; do + mkdir "$tmpdir/api-old" + mkdir "$tmpdir/api-new" + + echo "Checking public API breakages from $old_tag to $new_tag" + + build_and_do "$repodir" "$new_tag" "$tmpdir/api-new/" + build_and_do "$repodir" "$old_tag" "$tmpdir/api-old/" + + for f in "$tmpdir/api-new"/*; do + f=$(basename "$f") + report="$tmpdir/$f.report" + if [[ ! -f "$tmpdir/api-old/$f" ]]; then + echo "NOTICE: NEW MODULE $f" + continue + fi + + echo -n "Checking $f... " + swift api-digester -sdk "$sdk" -diagnose-sdk \ + --input-paths "$tmpdir/api-old/$f" -input-paths "$tmpdir/api-new/$f" 2>&1 \ + > "$report" 2>&1 + + if ! shasum "$report" | grep -q cefc4ee5bb7bcdb7cb5a7747efa178dab3c794d5; then + echo ERROR + echo >&2 "==============================" + echo >&2 "ERROR: public API change in $f" + echo >&2 "==============================" + cat >&2 "$report" + errors=$(( errors + 1 )) + else + echo OK + fi + done + rm -rf "$tmpdir/api-new" "$tmpdir/api-old" +done + +if [[ "$errors" == 0 ]]; then + echo "OK, all seems good" +fi +echo done +exit "$errors" diff --git a/scripts/generate_contributors_list.sh b/scripts/generate_contributors_list.sh index d74bd588..0cb1d72f 100755 --- a/scripts/generate_contributors_list.sh +++ b/scripts/generate_contributors_list.sh @@ -3,7 +3,7 @@ ## ## This source file is part of the SwiftCrypto open source project ## -## Copyright (c) 2017-2019 Apple Inc. and the SwiftCrypto project authors +## Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information diff --git a/scripts/generate_docs.sh b/scripts/generate_docs.sh new file mode 100755 index 00000000..15d98fbd --- /dev/null +++ b/scripts/generate_docs.sh @@ -0,0 +1,103 @@ +#!/bin/bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftCrypto open source project +## +## Copyright (c) 2018-2019 Apple Inc. and the SwiftCrypto project authors +## Licensed under Apache License v2.0 +## +## See LICENSE.txt for license information +## See CONTRIBUTORS.txt for the list of SwiftCrypto project authors +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +set -e + +my_path="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +root_path="$my_path/.." +version=$(git describe --abbrev=0 --tags || echo "0.0.0") +modules=(Crypto) + +if [[ "$(uname -s)" == "Linux" ]]; then + # build code if required + if [[ ! -d "$root_path/.build/x86_64-unknown-linux" ]]; then + swift build + fi + # setup source-kitten if required + mkdir -p "$root_path/.build/sourcekitten" + source_kitten_source_path="$root_path/.build/sourcekitten/source" + if [[ ! -d "$source_kitten_source_path" ]]; then + git clone https://github.com/jpsim/SourceKitten.git "$source_kitten_source_path" + fi + source_kitten_path="$source_kitten_source_path/.build/x86_64-unknown-linux/debug" + if [[ ! -d "$source_kitten_path" ]]; then + rm -rf "$source_kitten_source_path/.swift-version" + cd "$source_kitten_source_path" && swift build && cd "$root_path" + fi + # generate + for module in "${modules[@]}"; do + if [[ ! -f "$root_path/.build/sourcekitten/$module.json" ]]; then + "$source_kitten_path/sourcekitten" doc --spm-module $module > "$root_path/.build/sourcekitten/$module.json" + fi + done +fi + +# prep index +tmp=`mktemp -d` +module_switcher="$tmp/README.md" +cat > "$module_switcher" <<"EOF" +# SwiftCrypto Docs + +SwiftCrypto is a SwiftCrypto package. + +To get started with SwiftCrypto, [`import Crypto`](../Crypto/index.html). +EOF + +# run jazzy +if ! command -v jazzy > /dev/null; then + gem install jazzy --no-ri --no-rdoc +fi + +jazzy_args=(--clean + --author 'SwiftCrypto team' + --readme "$module_switcher" + --author_url https://github.com/apple/swift-crypto + --github_url https://github.com/apple/swift-crypto + --github-file-prefix https://github.com/apple/swift-crypto/tree/$version + --theme fullwidth + --swift-build-tool spm) + +for module in "${modules[@]}"; do + args=("${jazzy_args[@]}" --output "$tmp/docs/$version/$module" --docset-path "$tmp/docset/$version/$module" --module "$module") + if [[ "$(uname -s)" == "Linux" ]]; then + args+=(--sourcekitten-sourcefile "$root_path/.build/sourcekitten/$module.json") + fi + jazzy "${args[@]}" +done + +# push to github pages +if [[ $CI == true ]]; then + BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD) + GIT_AUTHOR=$(git --no-pager show -s --format='%an <%ae>' HEAD) + git fetch origin +gh-pages:gh-pages + git checkout gh-pages + rm -rf "docs" + cp -r "$tmp/docs" . + cp -r "docs/$version" docs/current + git add --all docs + echo '' > index.html + git add index.html + touch .nojekyll + git add .nojekyll + changes=$(git diff-index --name-only HEAD) + if [[ -n "$changes" ]]; then + echo -e "changes detected\n$changes" + git commit --author="$GIT_AUTHOR" -m "publish $version docs" + git push origin gh-pages + else + echo "no changes detected" + fi + git checkout -f $BRANCH_NAME +fi diff --git a/scripts/generate_linux_tests.rb b/scripts/generate_linux_tests.rb deleted file mode 100755 index fbf450a8..00000000 --- a/scripts/generate_linux_tests.rb +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/env ruby - -# -# process_test_files.rb -# -# Copyright 2016 Tony Stone -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Created by Tony Stone on 5/4/16. -# -require 'getoptlong' -require 'fileutils' -require 'pathname' - -include FileUtils - -# -# This ruby script will auto generate LinuxMain.swift and the +XCTest.swift extension files for Swift Package Manager on Linux platforms. -# -# See https://github.com/apple/swift-corelibs-xctest/blob/master/Documentation/Linux.md -# -def header(fileName) - string = <<-eos -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftCrypto open source project -// -// Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of SwiftCrypto project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// -// -// -// -import XCTest - -/// -/// NOTE: This file was generated by generate_linux_tests.rb -/// -/// Do NOT edit this file directly as it will be regenerated automatically when needed. -/// - eos - - string - .sub('', File.basename(fileName)) - .sub('', Time.now.to_s) -end - -def createExtensionFile(fileName, classes) - extensionFile = fileName.sub! '.swift', '+XCTest.swift' - print 'Creating file: ' + extensionFile + "\n" - - File.open(extensionFile, 'w') do |file| - file.write header(extensionFile) - file.write "\n" - - for classArray in classes - file.write 'extension ' + classArray[0] + " {\n\n" - file.write ' static var allTests : [(String, (' + classArray[0] + ") -> () throws -> Void)] {\n" - file.write " return [\n" - - for funcName in classArray[1] - file.write ' ("' + funcName + '", ' + funcName + "),\n" - end - - file.write " ]\n" - file.write " }\n" - file.write "}\n\n" - end - end -end - -def createLinuxMain(testsDirectory, allTestSubDirectories, files) - fileName = testsDirectory + '/LinuxMain.swift' - print 'Creating file: ' + fileName + "\n" - - File.open(fileName, 'w') do |file| - file.write header(fileName) - file.write "\n" - - file.write "#if os(Linux) || os(FreeBSD)\n" - for testSubDirectory in allTestSubDirectories.sort { |x, y| x <=> y } - file.write ' @testable import ' + testSubDirectory + "\n" - end - file.write "\n" - file.write " XCTMain([\n" - - testCases = [] - for classes in files - for classArray in classes - testCases << classArray[0] - end - end - - for testCase in testCases.sort { |x, y| x <=> y } - file.write ' testCase(' + testCase + ".allTests),\n" - end - file.write " ])\n" - file.write "#endif\n" - end -end - -def parseSourceFile(fileName) - puts 'Parsing file: ' + fileName + "\n" - - classes = [] - currentClass = nil - inIfLinux = false - inElse = false - ignore = false - - # - # Read the file line by line - # and parse to find the class - # names and func names - # - File.readlines(fileName).each do |line| - if inIfLinux - if /\#else/.match(line) - inElse = true - ignore = true - else - if /\#end/.match(line) - inElse = false - inIfLinux = false - ignore = false - end - end - else - if /\#if[ \t]+os\(Linux\)/.match(line) - inIfLinux = true - ignore = false - end - end - - next if ignore - # Match class or func - match = line[/class[ \t]+[a-zA-Z0-9_]*(?=[ \t]*:[ \t]*XCTestCase)|func[ \t]+test[a-zA-Z0-9_]*(?=[ \t]*\(\))/, 0] - if match - - if match[/class/, 0] == 'class' - className = match.sub(/^class[ \t]+/, '') - # - # Create a new class / func structure - # and add it to the classes array. - # - currentClass = [className, []] - classes << currentClass - else # Must be a func - funcName = match.sub(/^func[ \t]+/, '') - # - # Add each func name the the class / func - # structure created above. - # - currentClass[1] << funcName - end - end - end - classes -end - -# -# Main routine -# -# - -testsDirectory = 'Tests' - -options = GetoptLong.new(['--tests-dir', GetoptLong::OPTIONAL_ARGUMENT]) -options.quiet = true - -begin - options.each do |option, value| - case option - when '--tests-dir' - testsDirectory = value - end - end -rescue GetoptLong::InvalidOption -end - -allTestSubDirectories = [] -allFiles = [] - -Dir[testsDirectory + '/**/*'].each do |subDirectory| - next unless File.directory?(subDirectory) - directoryHasClasses = false - Dir[subDirectory + '/*Test{s,}.swift'].each do |fileName| - next unless File.file? fileName - fileClasses = parseSourceFile(fileName) - - # - # If there are classes in the - # test source file, create an extension - # file for it. - # - next unless fileClasses.count > 0 - createExtensionFile(fileName, fileClasses) - directoryHasClasses = true - allFiles << fileClasses - end - - if directoryHasClasses - allTestSubDirectories << Pathname.new(subDirectory).split.last.to_s - end -end - -# -# Last step is the create a LinuxMain.swift file that -# references all the classes and funcs in the source files. -# -if allFiles.count > 0 - createLinuxMain(testsDirectory, allTestSubDirectories, allFiles) -end -# eof diff --git a/scripts/sanity.sh b/scripts/sanity.sh index 35c4a0db..6610aa24 100755 --- a/scripts/sanity.sh +++ b/scripts/sanity.sh @@ -3,7 +3,7 @@ ## ## This source file is part of the SwiftCrypto open source project ## -## Copyright (c) 2017-2019 Apple Inc. and the SwiftCrypto project authors +## Copyright (c) 2019 Apple Inc. and the SwiftCrypto project authors ## Licensed under Apache License v2.0 ## ## See LICENSE.txt for license information @@ -18,21 +18,43 @@ here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" function replace_acceptable_years() { # this needs to replace all acceptable forms with 'YEARS' - sed -e 's/2017-201[89]/YEARS/' -e 's/2019/YEARS/' + sed -e 's/2018-2019/YEARS/' -e 's/2019/YEARS/' } +printf "=> Checking format\n" +FIRST_OUT="$(git status --porcelain)" +# only checking direcotry named BoringSSL, rest is shared code and we need to preserve original format +shopt -u dotglob +find Sources/* Tests/* -name BoringSSL -type d | while IFS= read -r d; do + printf " * checking $d... " + out=$(swiftformat "$d" 2>&1) + SECOND_OUT="$(git status --porcelain)" + if [[ "$out" == *"error"*] && ["$out" != "*No eligible files" ]]; then + printf "\033[0;31merror!\033[0m\n" + echo $out + exit 1 + fi + if [[ "$FIRST_OUT" != "$SECOND_OUT" ]]; then + printf "\033[0;31mformatting issues!\033[0m\n" + git --no-pager diff + exit 1 + fi + printf "\033[0;32mokay.\033[0m\n" +done + printf "=> Checking #defines..." if grep '\.define("CRYPTO_IN_SWIFTPM_FORCE_BUILD_API")' Package.swift | grep -v "//" > /dev/null; then - printf "\033[0;31mstill in development mode!\033[0m Comment out CRYPTO_IN_SWIFTPM_FORCE_BUILD_API.\n" - exit 1 + printf "\033[0;31mstill in development mode!\033[0m Comment out CRYPTO_IN_SWIFTPM_FORCE_BUILD_API.\n" + exit 1 else - printf "\033[0;32mokay.\033[0m\n" + printf "\033[0;32mokay.\033[0m\n" fi -printf "=> Checking license headers... " -tmp=$(mktemp /tmp/.swift-nio-sanity_XXXXXX) +printf "=> Checking license headers\n" +tmp=$(mktemp /tmp/.swift-crypto-sanity_XXXXXX) for language in swift-or-c bash dtrace; do + printf " * $language... " declare -a matching_files declare -a exceptions expections=( )