From 43e0170e65d148bf7a822c74bc82facff2598b68 Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Fri, 11 Aug 2023 09:42:48 +0100 Subject: [PATCH] Adopt `apple/swift-format` (#35) * default swift-format configuration * Adopt `apple/swift-format` * Fix soundness.sh * Fix linting warnings * update license header * Apply review comments --- .swift-format | 58 ++++ NOTICE.txt | 8 + Sources/SwiftASN1/ASN1.swift | 326 ++++++++++++------ .../Basic ASN1 Types/ASN1BitString.swift | 16 +- .../Basic ASN1 Types/ASN1Identifier.swift | 4 +- .../Basic ASN1 Types/ASN1Integer.swift | 41 +-- .../SwiftASN1/Basic ASN1 Types/ASN1Null.swift | 2 +- .../Basic ASN1 Types/ASN1OctetString.swift | 4 +- .../Basic ASN1 Types/ArraySliceBigint.swift | 10 +- .../Basic ASN1 Types/GeneralizedTime.swift | 24 +- .../Basic ASN1 Types/ObjectIdentifier.swift | 6 +- .../Basic ASN1 Types/PEMDocument.swift | 33 +- .../Basic ASN1 Types/TimeUtilities.swift | 61 ++-- .../SwiftASN1/Basic ASN1 Types/UTCTime.swift | 2 +- Sources/SwiftASN1/Errors.swift | 65 +++- Tests/SwiftASN1Tests/ASN1Tests.swift | 300 +++++++++------- .../SwiftASN1Tests/GeneralizedTimeTests.swift | 233 +++++++++---- .../Test Helper Types/SEC1PrivateKey.swift | 5 +- .../SubjectPublicKeyInfo.swift | 19 +- Tests/SwiftASN1Tests/UTCTimeTests.swift | 12 +- docker/Dockerfile | 6 + scripts/run-swift-format.sh | 54 +++ scripts/soundness.sh | 6 + 23 files changed, 907 insertions(+), 388 deletions(-) create mode 100644 .swift-format create mode 100644 scripts/run-swift-format.sh diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..0b2b0a8 --- /dev/null +++ b/.swift-format @@ -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" : true, + "UseTripleSlashForDocumentationComments" : true, + "UseWhereClausesInForLoops" : false, + "ValidateDocumentationComments" : false + }, + "spacesAroundRangeFormationOperators" : false, + "tabWidth" : 8, + "version" : 1 +} \ No newline at end of file diff --git a/NOTICE.txt b/NOTICE.txt index 2b2e5c1..eb8fa8e 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -33,3 +33,11 @@ This product contains derivations of various scripts from SwiftNIO. * HOMEPAGE: * https://github.com/apple/swift-nio +--- + +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 diff --git a/Sources/SwiftASN1/ASN1.swift b/Sources/SwiftASN1/ASN1.swift index 31722c1..bfdad72 100644 --- a/Sources/SwiftASN1/ASN1.swift +++ b/Sources/SwiftASN1/ASN1.swift @@ -14,7 +14,7 @@ /// ``DER`` defines a namespace that is used to store a number of helper methods and types /// for DER encoding and decoding. -public enum DER { } +public enum DER {} // MARK: - Parser Node extension DER { @@ -64,14 +64,15 @@ extension DER { } } -extension DER.ParserNode: Hashable { } +extension DER.ParserNode: Hashable {} -extension DER.ParserNode: Sendable { } +extension DER.ParserNode: Sendable {} extension DER.ParserNode: CustomStringConvertible { @inlinable var description: String { - return "DER.ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))" + return + "DER.ParserNode(identifier: \(self.identifier), depth: \(self.depth), dataBytes: \(self.dataBytes?.count ?? 0))" } } @@ -86,7 +87,11 @@ extension DER { /// - identifier: The ``ASN1Identifier`` that the SEQUENCE is expected to have. /// - builder: A closure that will be called with the collection of nodes within the sequence. @inlinable - public static func sequence(_ node: ASN1Node, identifier: ASN1Identifier, _ builder: (inout ASN1NodeCollection.Iterator) throws -> T) throws -> T { + public static func sequence( + _ node: ASN1Node, + identifier: ASN1Identifier, + _ builder: (inout ASN1NodeCollection.Iterator) throws -> T + ) throws -> T { guard node.identifier == identifier, case .constructed(let nodes) = node.content else { throw ASN1Error.unexpectedFieldType(node.identifier) } @@ -112,7 +117,11 @@ extension DER { /// - rootNode: The ``ASN1Node`` to parse /// - returns: An array of elements representing the elements in the sequence. @inlinable - public static func sequence(of: T.Type = T.self, identifier: ASN1Identifier, rootNode: ASN1Node) throws -> [T] { + public static func sequence( + of: T.Type = T.self, + identifier: ASN1Identifier, + rootNode: ASN1Node + ) throws -> [T] { guard rootNode.identifier == identifier, case .constructed(let nodes) = rootNode.content else { throw ASN1Error.unexpectedFieldType(rootNode.identifier) } @@ -130,10 +139,16 @@ extension DER { /// - nodes: An ``ASN1NodeCollection/Iterator`` of nodes to parse. /// - returns: An array of elements representing the elements in the sequence. @inlinable - public static func sequence(of: T.Type = T.self, identifier: ASN1Identifier, nodes: inout ASN1NodeCollection.Iterator) throws -> [T] { + public static func sequence( + of: T.Type = T.self, + identifier: ASN1Identifier, + nodes: inout ASN1NodeCollection.Iterator + ) throws -> [T] { guard let node = nodes.next() else { // Not present, throw. - throw ASN1Error.invalidASN1Object(reason: "No sequence node available for \(T.self) and identifier \(identifier)") + throw ASN1Error.invalidASN1Object( + reason: "No sequence node available for \(T.self) and identifier \(identifier)" + ) } return try sequence(of: T.self, identifier: identifier, rootNode: node) @@ -148,11 +163,15 @@ extension DER { /// - identifier: The ``ASN1Identifier`` that the SET is expected to have. /// - builder: A closure that will be called with the collection of nodes within the set. @inlinable - public static func set(_ node: ASN1Node, identifier: ASN1Identifier, _ builder: (inout ASN1NodeCollection.Iterator) throws -> T) throws -> T { + public static func set( + _ node: ASN1Node, + identifier: ASN1Identifier, + _ builder: (inout ASN1NodeCollection.Iterator) throws -> T + ) throws -> T { // Shhhh these two are secretly the same with identifier. return try sequence(node, identifier: identifier, builder) } - + /// Parse the node as an ASN.1 SET OF. /// /// Constructs an array of `T` elements parsed from the set. @@ -163,15 +182,21 @@ extension DER { /// - nodes: An ``ASN1NodeCollection/Iterator`` of nodes to parse. /// - returns: An array of elements representing the elements in the set. @inlinable - public static func set(of: T.Type = T.self, identifier: ASN1Identifier, nodes: inout ASN1NodeCollection.Iterator) throws -> [T] { + public static func set( + of: T.Type = T.self, + identifier: ASN1Identifier, + nodes: inout ASN1NodeCollection.Iterator + ) throws -> [T] { guard let node = nodes.next() else { // Not present, throw. - throw ASN1Error.invalidASN1Object(reason: "No set node available for \(T.self) and identifier \(identifier)") + throw ASN1Error.invalidASN1Object( + reason: "No set node available for \(T.self) and identifier \(identifier)" + ) } return try Self.set(of: T.self, identifier: identifier, rootNode: node) } - + /// Parse the node as an ASN.1 SET OF. /// /// Constructs an array of `T` elements parsed from the set. @@ -182,10 +207,14 @@ extension DER { /// - rootNode: The ``ASN1Node`` to parse /// - returns: An array of elements representing the elements in the sequence. @inlinable - public static func set(of type: T.Type = T.self, identifier: ASN1Identifier, rootNode: ASN1Node) throws -> [T] { + public static func set( + of type: T.Type = T.self, + identifier: ASN1Identifier, + rootNode: ASN1Node + ) throws -> [T] { try self.lazySet(of: type, identifier: identifier, rootNode: rootNode).map { try $0.get() } } - + /// Parse the node as an ASN.1 SET OF lazily. /// /// Constructs a Sequence of `T` elements that will be lazily parsed from the set. @@ -196,47 +225,51 @@ extension DER { /// - rootNode: The ``ASN1Node`` to parse /// - returns: A `Sequence` of elements representing the `Result` of parsing the elements in the sequence. @inlinable - public static func lazySet(of: T.Type = T.self, identifier: ASN1Identifier, rootNode: ASN1Node) throws -> LazySetOfSequence { + public static func lazySet( + of: T.Type = T.self, + identifier: ASN1Identifier, + rootNode: ASN1Node + ) throws -> LazySetOfSequence { guard rootNode.identifier == identifier, case .constructed(let nodes) = rootNode.content else { throw ASN1Error.unexpectedFieldType(rootNode.identifier) } - + guard nodes.isOrderedAccordingToSetOfSemantics() else { throw ASN1Error.invalidASN1Object(reason: "SET OF fields are not lexicographically ordered") } - + return .init(nodes.lazy.map { node in Result { try T(derEncoded: node) } }) } - + public struct LazySetOfSequence: Sequence { public typealias Element = Result - + @usableFromInline typealias WrappedSequence = LazyMapSequence.Elements, Result> - + public struct Iterator: IteratorProtocol { @usableFromInline var wrapped: WrappedSequence.Iterator - + @inlinable mutating public func next() -> Element? { wrapped.next() } - + @inlinable init(_ wrapped: WrappedSequence.Iterator) { self.wrapped = wrapped } } - + @usableFromInline var wrapped: WrappedSequence - + @inlinable init(_ wrapped: WrappedSequence) { self.wrapped = wrapped } - + @inlinable public func makeIterator() -> Iterator { .init(wrapped.makeIterator()) @@ -256,7 +289,12 @@ extension DER { /// /// - returns: The result of `builder` if the element was present, or `nil` if it was not. @inlinable - public static func optionalExplicitlyTagged(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T? { + public static func optionalExplicitlyTagged( + _ nodes: inout ASN1NodeCollection.Iterator, + tagNumber: UInt, + tagClass: ASN1Identifier.TagClass, + _ builder: (ASN1Node) throws -> T + ) throws -> T? { var localNodesCopy = nodes guard let node = localNodesCopy.next() else { // Node not present, return nil. @@ -264,7 +302,7 @@ extension DER { } let expectedNodeID = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass) -// assert(expectedNodeID.constructed) + // assert(expectedNodeID.constructed) guard node.identifier == expectedNodeID else { // Node is a mismatch, with the wrong tag. Our optional isn't present. return nil @@ -281,7 +319,9 @@ extension DER { var nodeIterator = nodes.makeIterator() guard let child = nodeIterator.next(), nodeIterator.next() == nil else { - throw ASN1Error.invalidASN1Object(reason: "Too many child nodes in optionally tagged node of \(T.self) with identifier \(expectedNodeID)") + throw ASN1Error.invalidASN1Object( + reason: "Too many child nodes in optionally tagged node of \(T.self) with identifier \(expectedNodeID)" + ) } return try builder(child) @@ -298,7 +338,10 @@ extension DER { /// /// - returns: The parsed element, if it was present, or `nil` if it was not. @inlinable - public static func optionalImplicitlyTagged(_ nodes: inout ASN1NodeCollection.Iterator, tag: ASN1Identifier = T.defaultIdentifier) throws -> T? { + public static func optionalImplicitlyTagged( + _ nodes: inout ASN1NodeCollection.Iterator, + tag: ASN1Identifier = T.defaultIdentifier + ) throws -> T? { var localNodesCopy = nodes guard let node = localNodesCopy.next() else { // Node not present, return nil. @@ -313,7 +356,7 @@ extension DER { // We're good: pass the node on. return try T(derEncoded: &nodes, withIdentifier: tag) } - + /// Parses an optional implicitly tagged element. /// /// - parameters: @@ -335,16 +378,16 @@ extension DER { // Node not present, return nil. return nil } - + let expectedNodeID = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass) guard node.identifier == expectedNodeID else { // Node is a mismatch, with the wrong tag. Our optional isn't present. return nil } - + // We have the right optional, so let's consume it. nodes = localNodesCopy - + // We're good: pass the node on. return try builder(node) } @@ -364,7 +407,12 @@ extension DER { /// /// - returns: The parsed element, if it was present, or the default if it was not. @inlinable - public static func decodeDefault(_ nodes: inout ASN1NodeCollection.Iterator, identifier: ASN1Identifier, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T { + public static func decodeDefault( + _ nodes: inout ASN1NodeCollection.Iterator, + identifier: ASN1Identifier, + defaultValue: T, + _ builder: (ASN1Node) throws -> T + ) throws -> T { // A weird trick here: we only want to consume the next node _if_ it has the right tag. To achieve that, // we work on a copy. var localNodesCopy = nodes @@ -385,7 +433,10 @@ extension DER { // DER forbids encoding DEFAULT values at their default state. // We can lift this in BER. guard parsed != defaultValue else { - throw ASN1Error.invalidASN1Object(reason: "DEFAULT for \(T.self) with identifier \(identifier) present in DER but encoded at default value \(defaultValue)") + throw ASN1Error.invalidASN1Object( + reason: + "DEFAULT for \(T.self) with identifier \(identifier) present in DER but encoded at default value \(defaultValue)" + ) } return parsed @@ -404,8 +455,14 @@ extension DER { /// /// - returns: The parsed element, if it was present, or the default if it was not. @inlinable - public static func decodeDefault(_ nodes: inout ASN1NodeCollection.Iterator, identifier: ASN1Identifier, defaultValue: T) throws -> T { - return try Self.decodeDefault(&nodes, identifier: identifier, defaultValue: defaultValue) { try T(derEncoded: $0) } + public static func decodeDefault( + _ nodes: inout ASN1NodeCollection.Iterator, + identifier: ASN1Identifier, + defaultValue: T + ) throws -> T { + return try Self.decodeDefault(&nodes, identifier: identifier, defaultValue: defaultValue) { + try T(derEncoded: $0) + } } /// Parses a value that is encoded with a DEFAULT. @@ -420,7 +477,10 @@ extension DER { /// /// - returns: The parsed element, if it was present, or the default if it was not. @inlinable - public static func decodeDefault(_ nodes: inout ASN1NodeCollection.Iterator, defaultValue: T) throws -> T { + public static func decodeDefault( + _ nodes: inout ASN1NodeCollection.Iterator, + defaultValue: T + ) throws -> T { return try Self.decodeDefault(&nodes, identifier: T.defaultIdentifier, defaultValue: defaultValue) } @@ -437,18 +497,27 @@ extension DER { /// /// - returns: The parsed element, if it was present, or the default if it was not. @inlinable - public static func decodeDefaultExplicitlyTagged(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, defaultValue: T, _ builder: (ASN1Node) throws -> T) throws -> T { - if let result = try optionalExplicitlyTagged(&nodes, tagNumber: tagNumber, tagClass: tagClass, builder) { - guard result != defaultValue else { - // DER forbids encoding DEFAULT values at their default state. - // We can lift this in BER. - throw ASN1Error.invalidASN1Object(reason: "DEFAULT for \(T.self) with tag number \(tagNumber) and class \(tagClass) present in DER but encoded at default value \(defaultValue)") - } - - return result - } else { + public static func decodeDefaultExplicitlyTagged( + _ nodes: inout ASN1NodeCollection.Iterator, + tagNumber: UInt, + tagClass: ASN1Identifier.TagClass, + defaultValue: T, + _ builder: (ASN1Node) throws -> T + ) throws -> T { + guard let result = try optionalExplicitlyTagged(&nodes, tagNumber: tagNumber, tagClass: tagClass, builder) + else { return defaultValue } + guard result != defaultValue else { + // DER forbids encoding DEFAULT values at their default state. + // We can lift this in BER. + throw ASN1Error.invalidASN1Object( + reason: + "DEFAULT for \(T.self) with tag number \(tagNumber) and class \(tagClass) present in DER but encoded at default value \(defaultValue)" + ) + } + + return result } /// Parses a value that is encoded with a DEFAULT and an explicit tag. @@ -465,9 +534,17 @@ extension DER { /// /// - returns: The parsed element, if it was present, or the default if it was not. @inlinable - public static func decodeDefaultExplicitlyTagged(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, defaultValue: T) throws -> T { + public static func decodeDefaultExplicitlyTagged( + _ nodes: inout ASN1NodeCollection.Iterator, + tagNumber: UInt, + tagClass: ASN1Identifier.TagClass, + defaultValue: T + ) throws -> T { return try Self.decodeDefaultExplicitlyTagged( - &nodes, tagNumber: tagNumber, tagClass: tagClass, defaultValue: defaultValue + &nodes, + tagNumber: tagNumber, + tagClass: tagClass, + defaultValue: defaultValue ) { try T(derEncoded: $0) } @@ -486,10 +563,18 @@ extension DER { /// /// - returns: The result of `builder`. @inlinable - public static func explicitlyTagged(_ nodes: inout ASN1NodeCollection.Iterator, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T { + public static func explicitlyTagged( + _ nodes: inout ASN1NodeCollection.Iterator, + tagNumber: UInt, + tagClass: ASN1Identifier.TagClass, + _ builder: (ASN1Node) throws -> T + ) throws -> T { guard let node = nodes.next() else { // Node not present, throw. - throw ASN1Error.invalidASN1Object(reason: "Explicitly tagged node for \(T.self) with tag number \(tagNumber) and class \(tagClass) not present") + throw ASN1Error.invalidASN1Object( + reason: + "Explicitly tagged node for \(T.self) with tag number \(tagNumber) and class \(tagClass) not present" + ) } return try self.explicitlyTagged(node, tagNumber: tagNumber, tagClass: tagClass, builder) @@ -505,7 +590,12 @@ extension DER { /// /// - returns: The result of `builder`. @inlinable - public static func explicitlyTagged(_ node: ASN1Node, tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T { + public static func explicitlyTagged( + _ node: ASN1Node, + tagNumber: UInt, + tagClass: ASN1Identifier.TagClass, + _ builder: (ASN1Node) throws -> T + ) throws -> T { let expectedNodeID = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass) guard node.identifier == expectedNodeID else { // Node is a mismatch, with the wrong tag. @@ -519,14 +609,15 @@ extension DER { var nodeIterator = nodes.makeIterator() guard let child = nodeIterator.next(), nodeIterator.next() == nil else { - throw ASN1Error.invalidASN1Object(reason: "Invalid number of child nodes for explicit tag \(expectedNodeID) for \(T.self)") + throw ASN1Error.invalidASN1Object( + reason: "Invalid number of child nodes for explicit tag \(expectedNodeID) for \(T.self)" + ) } return try builder(child) } } - // MARK: - Parsing extension DER { /// A parsed representation of ASN.1. @@ -583,7 +674,9 @@ extension DER { // We need a check here: this number needs to be greater than or equal to 0x1f, or it should have been encoded as short form. guard tagNumber >= 0x1f else { - throw ASN1Error.invalidASN1Object(reason: "ASN.1 tag incorrectly encoded in long form: \(tagNumber)") + throw ASN1Error.invalidASN1Object( + reason: "ASN.1 tag incorrectly encoded in long form: \(tagNumber)" + ) } identifier = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass) } else { @@ -636,7 +729,7 @@ extension DER { } } -extension DER.ParseResult: Hashable { } +extension DER.ParseResult: Hashable {} extension DER { /// Parses an array of bytes as DER-encoded ASN.1 bytes. @@ -723,9 +816,9 @@ public struct ASN1NodeCollection { } } -extension ASN1NodeCollection: Hashable { } +extension ASN1NodeCollection: Hashable {} -extension ASN1NodeCollection: Sendable { } +extension ASN1NodeCollection: Sendable {} extension ASN1NodeCollection: Sequence { /// An iterator of ASN.1 nodes that are children of a specific constructed node. @@ -751,16 +844,7 @@ extension ASN1NodeCollection: Sequence { } assert(nextNode.depth == self._depth + 1) - if nextNode.isConstructed { - // We need to feed it the next set of nodes. - let nodeCollection = self._nodes.prefix { $0.depth > nextNode.depth } - self._nodes = self._nodes.dropFirst(nodeCollection.count) - return ASN1Node( - identifier: nextNode.identifier, - content: .constructed(.init(nodes: nodeCollection, depth: nextNode.depth)), - encodedBytes: nextNode.encodedBytes - ) - } else { + guard nextNode.isConstructed else { // There must be data bytes here, even if they're empty. return ASN1Node( identifier: nextNode.identifier, @@ -768,6 +852,14 @@ extension ASN1NodeCollection: Sequence { encodedBytes: nextNode.encodedBytes ) } + // We need to feed it the next set of nodes. + let nodeCollection = self._nodes.prefix { $0.depth > nextNode.depth } + self._nodes = self._nodes.dropFirst(nodeCollection.count) + return ASN1Node( + identifier: nextNode.identifier, + content: .constructed(.init(nodes: nodeCollection, depth: nextNode.depth)), + encodedBytes: nextNode.encodedBytes + ) } } @@ -853,7 +945,10 @@ extension DER { /// - identifier: The tag for this ASN.1 node /// - contentWriter: A callback that will be invoked that allows users to write their bytes into the output stream. @inlinable - public mutating func appendPrimitiveNode(identifier: ASN1Identifier, _ contentWriter: (inout [UInt8]) throws -> Void) rethrows { + public mutating func appendPrimitiveNode( + identifier: ASN1Identifier, + _ contentWriter: (inout [UInt8]) throws -> Void + ) rethrows { try self._appendNode(identifier: identifier, constructed: false) { try contentWriter(&$0._serializedBytes) } } @@ -866,7 +961,10 @@ extension DER { /// - identifier: The tag for this ASN.1 node /// - contentWriter: A callback that will be invoked that allows users to write the objects contained within this constructed node. @inlinable - public mutating func appendConstructedNode(identifier: ASN1Identifier, _ contentWriter: (inout Serializer) throws -> Void) rethrows { + public mutating func appendConstructedNode( + identifier: ASN1Identifier, + _ contentWriter: (inout Serializer) throws -> Void + ) rethrows { try self._appendNode(identifier: identifier, constructed: true, contentWriter) } @@ -889,7 +987,11 @@ extension DER { /// tagNumber: The number of the explicit tag. /// tagClass: The number of the explicit tag. @inlinable - public mutating func serialize(_ node: T, explicitlyTaggedWithTagNumber tagNumber: UInt, tagClass: ASN1Identifier.TagClass) throws { + public mutating func serialize( + _ node: T, + explicitlyTaggedWithTagNumber tagNumber: UInt, + tagClass: ASN1Identifier.TagClass + ) throws { let identifier = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass) return try self.serialize(node, explicitlyTaggedWithIdentifier: identifier) } @@ -900,7 +1002,10 @@ extension DER { /// node: The node to be serialized. /// identifier: The explicit ASN.1 tag to apply. @inlinable - public mutating func serialize(_ node: T, explicitlyTaggedWithIdentifier identifier: ASN1Identifier) throws { + public mutating func serialize( + _ node: T, + explicitlyTaggedWithIdentifier identifier: ASN1Identifier + ) throws { try self.appendConstructedNode(identifier: identifier) { coder in try coder.serialize(node) } @@ -929,7 +1034,10 @@ extension DER { /// node: The node to be serialized. /// identifier: The implicit ASN.1 tag to apply. @inlinable - public mutating func serializeOptionalImplicitlyTagged(_ node: T?, withIdentifier identifier: ASN1Identifier) throws { + public mutating func serializeOptionalImplicitlyTagged( + _ node: T?, + withIdentifier identifier: ASN1Identifier + ) throws { if let node = node { try node.serialize(into: &self, withIdentifier: identifier) } @@ -945,7 +1053,11 @@ extension DER { /// tagClass: The number of the explicit tag. /// block: The block that will be invoked to encode the contents of the explicit tag. @inlinable - public mutating func serialize(explicitlyTaggedWithTagNumber tagNumber: UInt, tagClass: ASN1Identifier.TagClass, _ block: (inout Serializer) throws -> Void) rethrows { + public mutating func serialize( + explicitlyTaggedWithTagNumber tagNumber: UInt, + tagClass: ASN1Identifier.TagClass, + _ block: (inout Serializer) throws -> Void + ) rethrows { let identifier = ASN1Identifier(tagWithNumber: tagNumber, tagClass: tagClass) try self.appendConstructedNode(identifier: identifier) { coder in try block(&coder) @@ -958,21 +1070,27 @@ extension DER { /// - elements: The members of the ASN.1 SEQUENCE OF. /// - identifier: The identifier to use for the SEQUENCE OF node. Defaults to ``ASN1Identifier/sequence``. @inlinable - public mutating func serializeSequenceOf(_ elements: Elements, identifier: ASN1Identifier = .sequence) throws where Elements.Element: DERSerializable { + public mutating func serializeSequenceOf( + _ elements: Elements, + identifier: ASN1Identifier = .sequence + ) throws where Elements.Element: DERSerializable { try self.appendConstructedNode(identifier: identifier) { coder in for element in elements { try coder.serialize(element) } } } - + /// Serializes a SET OF ASN.1 nodes. /// /// - parameters: /// - elements: The members of the ASN.1 SET OF. /// - identifier: The identifier to use for the SET OF node. Defaults to ``ASN1Identifier/set``. @inlinable - public mutating func serializeSetOf(_ elements: Elements, identifier: ASN1Identifier = .set) throws where Elements.Element: DERSerializable { + public mutating func serializeSetOf( + _ elements: Elements, + identifier: ASN1Identifier = .set + ) throws where Elements.Element: DERSerializable { // We first serialize all elements into one intermediate Serializer and // create ArraySlices of their binary DER representation. var intermediateSerializer = DER.Serializer() @@ -986,7 +1104,7 @@ extension DER { // get `ArraySlice`s during the sort and write operations on demand. return startIndex.. Void) rethrows { + mutating func _appendNode( + identifier: ASN1Identifier, + constructed: Bool, + _ contentWriter: (inout Serializer) throws -> Void + ) rethrows { // This is a tricky game to play. We want to write the identifier and the length, but we don't know what the // length is here. To get around that, we _assume_ the length will be one byte, and let the writer write their content. // If it turns out to have been longer, we recalculate how many bytes we need and shuffle them in the buffer, @@ -1066,7 +1188,10 @@ extension DER { try contentWriter(&self) - let contentLength = self._serializedBytes.distance(from: originalEndIndex, to: self._serializedBytes.endIndex) + let contentLength = self._serializedBytes.distance( + from: originalEndIndex, + to: self._serializedBytes.endIndex + ) let lengthBytesNeeded = contentLength._bytesNeededToEncode if lengthBytesNeeded == 1 { // We can just set this at the top, and we're done! @@ -1077,7 +1202,10 @@ extension DER { // Whoops, we need more than one byte to represent the length. That's annoying! // To sort this out we want to "move" the memory to the right. - self._serializedBytes._moveRange(offset: lengthBytesNeeded - 1, range: originalEndIndex.., withIdentifier identifier: ASN1Identifier = Self.defaultIdentifier) throws { + public init( + derEncoded: ArraySlice, + withIdentifier identifier: ASN1Identifier = Self.defaultIdentifier + ) throws { self = try .init(derEncoded: DER.parse(derEncoded), withIdentifier: identifier) } @@ -1275,7 +1408,9 @@ extension ArraySlice where Element == UInt8 { switch requiredBits { case 0...7: // For 0 to 7 bits, the long form is unacceptable and we require the short. - throw ASN1Error.unsupportedFieldLength(reason: "Field length encoded in long form, but DER requires \(length) to be encoded in short form") + throw ASN1Error.unsupportedFieldLength( + reason: "Field length encoded in long form, but DER requires \(length) to be encoded in short form" + ) case 8...: // For 8 or more bits, fieldLength should be the minimum required. let requiredBytes = (requiredBits + 7) / 8 @@ -1284,7 +1419,9 @@ extension ArraySlice where Element == UInt8 { } default: // This is not reachable, but we'll error anyway. - throw ASN1Error.unsupportedFieldLength(reason: "Correctness error: computed required bits as \(requiredBits)") + throw ASN1Error.unsupportedFieldLength( + reason: "Correctness error: computed required bits as \(requiredBits)" + ) } return length @@ -1346,15 +1483,14 @@ extension Int { // 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. - if self <= 0x7F { - return 1 - } else { + guard self <= 0x7F else { // We need to work out how many bytes we need. There are many fancy bit-twiddling // ways of doing this, but honestly we don't do this enough to need them, so we'll // do it the easy way. This math is done on UInt because it makes the shift semantics clean. // We save a branch here because we can never overflow this addition. return UInt(self).neededBytes &+ 1 } + return 1 } } @@ -1374,7 +1510,7 @@ extension ASN1NodeCollection { guard let first = iterator.next() else { return true } - + var previousElement = first while let nextElement = iterator.next() { guard asn1SetElementLessThanOrEqual(previousElement.encodedBytes, nextElement.encodedBytes) else { @@ -1382,7 +1518,7 @@ extension ASN1NodeCollection { } previousElement = nextElement } - + return true } } @@ -1398,7 +1534,7 @@ func asn1SetElementLessThan(_ lhs: ArraySlice, _ rhs: ArraySlice) return false } } - + // 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 = rhs.dropFirst(lhs.count) @@ -1414,5 +1550,3 @@ func asn1SetElementLessThanOrEqual(_ lhs: ArraySlice, _ rhs: ArraySlice(_ body: (IntegerBytesCollection) throws -> ReturnType) rethrows -> ReturnType { + public func withBigEndianIntegerBytes( + _ body: (IntegerBytesCollection) throws -> ReturnType + ) rethrows -> ReturnType { return try body(IntegerBytesCollection(self)) } } @@ -140,7 +141,7 @@ public struct IntegerBytesCollection { } } -extension IntegerBytesCollection: Hashable { } +extension IntegerBytesCollection: Hashable {} extension IntegerBytesCollection: Sendable where Integer: Sendable {} @@ -185,29 +186,29 @@ extension IntegerBytesCollection: RandomAccessCollection { } } -extension IntegerBytesCollection.Index: Hashable { } +extension IntegerBytesCollection.Index: Hashable {} -extension IntegerBytesCollection.Index: Sendable { } +extension IntegerBytesCollection.Index: Sendable {} extension IntegerBytesCollection.Index: Comparable { // Comparable here is backwards to the original ordering. @inlinable - public static func <(lhs: Self, rhs: Self) -> Bool { + public static func < (lhs: Self, rhs: Self) -> Bool { return lhs._byteNumber > rhs._byteNumber } @inlinable - public static func >(lhs: Self, rhs: Self) -> Bool { + public static func > (lhs: Self, rhs: Self) -> Bool { return lhs._byteNumber < rhs._byteNumber } @inlinable - public static func <=(lhs: Self, rhs: Self) -> Bool { + public static func <= (lhs: Self, rhs: Self) -> Bool { return lhs._byteNumber >= rhs._byteNumber } @inlinable - public static func >=(lhs: Self, rhs: Self) -> Bool { + public static func >= (lhs: Self, rhs: Self) -> Bool { return lhs._byteNumber <= rhs._byteNumber } } @@ -225,25 +226,25 @@ extension IntegerBytesCollection.Index: Strideable { } } -extension Int8: ASN1IntegerRepresentable { } +extension Int8: ASN1IntegerRepresentable {} -extension UInt8: ASN1IntegerRepresentable { } +extension UInt8: ASN1IntegerRepresentable {} -extension Int16: ASN1IntegerRepresentable { } +extension Int16: ASN1IntegerRepresentable {} -extension UInt16: ASN1IntegerRepresentable { } +extension UInt16: ASN1IntegerRepresentable {} -extension Int32: ASN1IntegerRepresentable { } +extension Int32: ASN1IntegerRepresentable {} -extension UInt32: ASN1IntegerRepresentable { } +extension UInt32: ASN1IntegerRepresentable {} -extension Int64: ASN1IntegerRepresentable { } +extension Int64: ASN1IntegerRepresentable {} -extension UInt64: ASN1IntegerRepresentable { } +extension UInt64: ASN1IntegerRepresentable {} -extension Int: ASN1IntegerRepresentable { } +extension Int: ASN1IntegerRepresentable {} -extension UInt: ASN1IntegerRepresentable { } +extension UInt: ASN1IntegerRepresentable {} extension RandomAccessCollection where Element == UInt8 { @inlinable diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift index aa73647..39b19c8 100644 --- a/Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1Null.swift @@ -21,7 +21,7 @@ public struct ASN1Null: DERImplicitlyTaggable, Hashable, Sendable { /// Construct a new ASN.1 null. @inlinable - public init() { } + public init() {} @inlinable public init(derEncoded node: ASN1Node, withIdentifier identifier: ASN1Identifier) throws { diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift b/Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift index 90364f7..bab6bb6 100644 --- a/Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift +++ b/Sources/SwiftASN1/Basic ASN1 Types/ASN1OctetString.swift @@ -52,9 +52,9 @@ public struct ASN1OctetString: DERImplicitlyTaggable { } } -extension ASN1OctetString: Hashable { } +extension ASN1OctetString: Hashable {} -extension ASN1OctetString: Sendable { } +extension ASN1OctetString: Sendable {} extension ASN1OctetString { @inlinable diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift b/Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift index 533edc5..606caac 100644 --- a/Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift +++ b/Sources/SwiftASN1/Basic ASN1 Types/ArraySliceBigint.swift @@ -13,11 +13,11 @@ //===----------------------------------------------------------------------===// // For temporary purposes we pretend that ArraySlice is our "bigint" type. We don't really need anything else. -extension ArraySlice: DERSerializable where Element == UInt8 { } +extension ArraySlice: DERSerializable where Element == UInt8 {} -extension ArraySlice: DERParseable where Element == UInt8 { } +extension ArraySlice: DERParseable where Element == UInt8 {} -extension ArraySlice: DERImplicitlyTaggable where Element == UInt8 { } +extension ArraySlice: DERImplicitlyTaggable where Element == UInt8 {} extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 { // We only use unsigned "bigint"s @@ -32,7 +32,9 @@ extension ArraySlice: ASN1IntegerRepresentable where Element == UInt8 { } @inlinable - public func withBigEndianIntegerBytes(_ body: (ArraySlice) throws -> ReturnType) rethrows -> ReturnType { + public func withBigEndianIntegerBytes( + _ body: (ArraySlice) throws -> ReturnType + ) rethrows -> ReturnType { return try body(self) } } diff --git a/Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift b/Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift index 18025f6..f265a2d 100644 --- a/Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift +++ b/Sources/SwiftASN1/Basic ASN1 Types/GeneralizedTime.swift @@ -126,7 +126,15 @@ public struct GeneralizedTime: DERImplicitlyTaggable, Hashable, Sendable { /// - seconds: The numerical seconds /// - fractionalSeconds: The numerical fractional seconds. @inlinable - public init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Int, fractionalSeconds: Double) throws { + public init( + year: Int, + month: Int, + day: Int, + hours: Int, + minutes: Int, + seconds: Int, + fractionalSeconds: Double + ) throws { self._year = year self._month = month self._day = day @@ -167,11 +175,15 @@ public struct GeneralizedTime: DERImplicitlyTaggable, Hashable, Sendable { // This also validates the month. guard let daysInMonth = TimeUtilities.daysInMonth(self._month, ofYear: self._year) else { - throw ASN1Error.invalidASN1Object(reason: "Invalid month \(self._month) of year \(self.year) for GeneralizedTime") + throw ASN1Error.invalidASN1Object( + reason: "Invalid month \(self._month) of year \(self.year) for GeneralizedTime" + ) } guard self._day >= 1 && self._day <= daysInMonth else { - throw ASN1Error.invalidASN1Object(reason: "Invalid day \(self._day) of month \(self._month) for GeneralizedTime") + throw ASN1Error.invalidASN1Object( + reason: "Invalid day \(self._day) of month \(self._month) for GeneralizedTime" + ) } guard self._hours >= 0 && self._hours < 24 else { @@ -192,14 +204,16 @@ public struct GeneralizedTime: DERImplicitlyTaggable, Hashable, Sendable { // Fractional seconds may not be negative and may not be 1 or more. guard self._fractionalSeconds >= 0 && self._fractionalSeconds < 1 else { - throw ASN1Error.invalidASN1Object(reason: "Invalid fractional seconds for GeneralizedTime \(self._fractionalSeconds)") + throw ASN1Error.invalidASN1Object( + reason: "Invalid fractional seconds for GeneralizedTime \(self._fractionalSeconds)" + ) } } } extension GeneralizedTime: Comparable { @inlinable - public static func <(lhs: GeneralizedTime, rhs: GeneralizedTime) -> Bool { + public static func < (lhs: GeneralizedTime, rhs: GeneralizedTime) -> Bool { if lhs.year < rhs.year { return true } else if lhs.year > rhs.year { return false } if lhs.month < rhs.month { return true } else if lhs.month > rhs.month { return false } if lhs.day < rhs.day { return true } else if lhs.day > rhs.day { return false } diff --git a/Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift b/Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift index ac8d3f8..6ad4563 100644 --- a/Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift +++ b/Sources/SwiftASN1/Basic ASN1 Types/ObjectIdentifier.swift @@ -115,7 +115,7 @@ public struct ASN1ObjectIdentifier: DERImplicitlyTaggable { extension ASN1ObjectIdentifier: Hashable {} -extension ASN1ObjectIdentifier: Sendable { } +extension ASN1ObjectIdentifier: Sendable {} extension ASN1ObjectIdentifier: ExpressibleByArrayLiteral { @inlinable @@ -256,7 +256,7 @@ extension ASN1ObjectIdentifier { /// The 'dc' ('domainComponent' in RFC 1274) attribute type is a string /// holding one component, a label, of a DNS domain name naming a host. - public static let domainComponent: ASN1ObjectIdentifier = [0, 9, 2342, 19200300, 100, 1, 25] + public static let domainComponent: ASN1ObjectIdentifier = [0, 9, 2342, 19_200_300, 100, 1, 25] /// The emailAddress attribute type specifies the electronic-mail address /// or addresses of a subject as an unstructured ASCII string. @@ -281,7 +281,7 @@ extension ArraySlice where Element == UInt8 { throw ASN1Error.invalidASN1Object(reason: "Invalid encoding for OID subidentifier") } - let oidSlice = self[self.startIndex ... subidentifierEndIndex] + let oidSlice = self[self.startIndex...subidentifierEndIndex] guard let firstByte = oidSlice.first, firstByte != 0x80 else { // If the first byte is 0x80 then we have a leading 0 byte. All numbers encoded this way diff --git a/Sources/SwiftASN1/Basic ASN1 Types/PEMDocument.swift b/Sources/SwiftASN1/Basic ASN1 Types/PEMDocument.swift index 15c0259..c7a3635 100644 --- a/Sources/SwiftASN1/Basic ASN1 Types/PEMDocument.swift +++ b/Sources/SwiftASN1/Basic ASN1 Types/PEMDocument.swift @@ -30,7 +30,7 @@ public protocol PEMSerializable: DERSerializable { /// -----END defaultPEMDiscriminator----- /// ``` static var defaultPEMDiscriminator: String { get } - + func serializeAsPEM(discriminator: String) throws -> PEMDocument } @@ -49,7 +49,7 @@ public protocol PEMParseable: DERParseable { /// -----END defaultPEMDiscriminator----- /// ``` static var defaultPEMDiscriminator: String { get } - + init(pemDocument: PEMDocument) throws } @@ -63,9 +63,9 @@ public protocol PEMParseable: DERParseable { public typealias PEMRepresentable = PEMSerializable & PEMParseable extension PEMParseable { - + /// Initialize this object from a serialized PEM representation. - /// + /// /// This will check that the discriminator matches ``PEMParseable/defaultPEMDiscriminator``, decode the base64 encoded string and /// then decode the DER encoded bytes using ``DERParseable/init(derEncoded:)-i2rf``. /// @@ -75,7 +75,7 @@ extension PEMParseable { public init(pemEncoded pemString: String) throws { try self.init(pemDocument: try PEMDocument(pemString: pemString)) } - + /// Initialize this object from a serialized PEM representation. /// This will check that the ``PEMParseable/pemDiscriminator`` matches and /// forward the DER encoded bytes to ``DERParseable/init(derEncoded:)-i2rf``. @@ -85,9 +85,12 @@ extension PEMParseable { @inlinable public init(pemDocument: PEMDocument) throws { guard pemDocument.discriminator == Self.defaultPEMDiscriminator else { - throw ASN1Error.invalidPEMDocument(reason: "PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.defaultPEMDiscriminator) instead") + throw ASN1Error.invalidPEMDocument( + reason: + "PEMDocument has incorrect discriminator \(pemDocument.discriminator). Expected \(Self.defaultPEMDiscriminator) instead" + ) } - + try self.init(derEncoded: pemDocument.derBytes) } } @@ -100,10 +103,10 @@ extension PEMSerializable { public func serializeAsPEM(discriminator: String) throws -> PEMDocument { var serializer = DER.Serializer() try serializer.serialize(self) - + return PEMDocument(type: discriminator, derBytes: serializer.serializedBytes) } - + /// Serializes `self` as a PEM document with the ``defaultPEMDiscriminator``. @inlinable public func serializeAsPEM() throws -> PEMDocument { @@ -115,13 +118,12 @@ extension PEMSerializable { public struct PEMDocument: Hashable, Sendable { fileprivate static let lineLength = 64 - @available(*, deprecated, renamed: "discriminator") public var type: String { get { discriminator } set { discriminator = newValue } } - + /// The PEM discriminator is in the first line of a PEM string after `BEGIN` and at the end of the string after `END` e.g. /// ``` /// -----BEGIN discriminator----- @@ -129,7 +131,7 @@ public struct PEMDocument: Hashable, Sendable { /// -----END discriminator----- /// ``` public var discriminator: String - + public var derBytes: [UInt8] public init(pemString: String) throws { @@ -155,7 +157,8 @@ public struct PEMDocument: Hashable, Sendable { lines = lines.dropFirst().dropLast() guard lines.count > 0, lines.dropLast().allSatisfy({ $0.utf8.count == PEMDocument.lineLength }), - lines.last!.utf8.count <= PEMDocument.lineLength else { + lines.last!.utf8.count <= PEMDocument.lineLength + else { throw ASN1Error.invalidPEMDocument(reason: "PEMDocument has incorrect line lengths") } @@ -189,7 +192,9 @@ public struct PEMDocument: Hashable, Sendable { pemLines.append("-----BEGIN \(self.discriminator)-----") while encoded.count > 0 { - let prefixIndex = encoded.index(encoded.startIndex, offsetBy: Self.lineLength, limitedBy: encoded.endIndex) ?? encoded.endIndex + let prefixIndex = + encoded.index(encoded.startIndex, offsetBy: Self.lineLength, limitedBy: encoded.endIndex) + ?? encoded.endIndex pemLines.append(encoded[.. Int? { guard let first = self._readTwoDigitDecimalInteger(), - let second = self._readTwoDigitDecimalInteger() else { + let second = self._readTwoDigitDecimalInteger() + else { return nil } @@ -153,12 +162,14 @@ extension ArraySlice where Element == UInt8 { @inlinable mutating func _readTwoDigitDecimalInteger() -> Int? { guard let firstASCII = self.popFirst(), - let secondASCII = self.popFirst() else { + let secondASCII = self.popFirst() + else { return nil } guard let first = Int(fromDecimalASCII: firstASCII), - let second = Int(fromDecimalASCII: secondASCII) else { + let second = Int(fromDecimalASCII: secondASCII) + else { return nil } @@ -175,7 +186,7 @@ extension ArraySlice where Element == UInt8 { var numerator = 0 var denominator = 1 - while let nextASCII = self.first, let next = Int(fromDecimalASCII: nextASCII) { + while let nextASCII = self.first, let next = Int(fromDecimalASCII: nextASCII) { self = self.dropFirst() let (newNumerator, multiplyOverflow) = numerator.multipliedReportingOverflow(by: 10) diff --git a/Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift b/Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift index 63daf22..939b2f0 100644 --- a/Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift +++ b/Sources/SwiftASN1/Basic ASN1 Types/UTCTime.swift @@ -183,7 +183,7 @@ public struct UTCTime: DERImplicitlyTaggable, Hashable, Sendable { extension UTCTime: Comparable { @inlinable - public static func <(lhs: UTCTime, rhs: UTCTime) -> Bool { + public static func < (lhs: UTCTime, rhs: UTCTime) -> Bool { if lhs.year < rhs.year { return true } else if lhs.year > rhs.year { return false } if lhs.month < rhs.month { return true } else if lhs.month > rhs.month { return false } if lhs.day < rhs.day { return true } else if lhs.day > rhs.day { return false } diff --git a/Sources/SwiftASN1/Errors.swift b/Sources/SwiftASN1/Errors.swift index bb8a368..4d5b759 100644 --- a/Sources/SwiftASN1/Errors.swift +++ b/Sources/SwiftASN1/Errors.swift @@ -49,11 +49,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible { /// The ASN.1 tag for the parsed field does not match the tag expected for the field. @inline(never) public static func unexpectedFieldType( - _ identifier: ASN1Identifier, file: String = #fileID, line: UInt = #line + _ identifier: ASN1Identifier, + file: String = #fileID, + line: UInt = #line ) -> ASN1Error { return ASN1Error( backing: .init( - code: .unexpectedFieldType, reason: "\(identifier)", file: file, line: line + code: .unexpectedFieldType, + reason: "\(identifier)", + file: file, + line: line ) ) } @@ -62,11 +67,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible { /// being decoded. @inline(never) public static func invalidASN1Object( - reason: String, file: String = #fileID, line: UInt = #line + reason: String, + file: String = #fileID, + line: UInt = #line ) -> ASN1Error { return ASN1Error( backing: .init( - code: .invalidASN1Object, reason: reason, file: file, line: line + code: .invalidASN1Object, + reason: reason, + file: file, + line: line ) ) } @@ -74,11 +84,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible { /// An ASN.1 integer was decoded that does not use the minimum number of bytes for its encoding. @inline(never) public static func invalidASN1IntegerEncoding( - reason: String, file: String = #fileID, line: UInt = #line + reason: String, + file: String = #fileID, + line: UInt = #line ) -> ASN1Error { return ASN1Error( backing: .init( - code: .invalidASN1IntegerEncoding, reason: reason, file: file, line: line + code: .invalidASN1IntegerEncoding, + reason: reason, + file: file, + line: line ) ) } @@ -86,11 +101,15 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible { /// An ASN.1 field was truncated and could not be decoded. @inline(never) public static func truncatedASN1Field( - file: String = #fileID, line: UInt = #line + file: String = #fileID, + line: UInt = #line ) -> ASN1Error { return ASN1Error( backing: .init( - code: .truncatedASN1Field, reason: "", file: file, line: line + code: .truncatedASN1Field, + reason: "", + file: file, + line: line ) ) } @@ -98,11 +117,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible { /// The encoding used for the field length is not supported. @inline(never) public static func unsupportedFieldLength( - reason: String, file: String = #fileID, line: UInt = #line + reason: String, + file: String = #fileID, + line: UInt = #line ) -> ASN1Error { return ASN1Error( backing: .init( - code: .unsupportedFieldLength, reason: reason, file: file, line: line + code: .unsupportedFieldLength, + reason: reason, + file: file, + line: line ) ) } @@ -110,11 +134,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible { /// It was not possible to parse a string as a PEM document. @inline(never) public static func invalidPEMDocument( - reason: String, file: String = #fileID, line: UInt = #line + reason: String, + file: String = #fileID, + line: UInt = #line ) -> ASN1Error { return ASN1Error( backing: .init( - code: .invalidPEMDocument, reason: reason, file: file, line: line + code: .invalidPEMDocument, + reason: reason, + file: file, + line: line ) ) } @@ -122,11 +151,16 @@ public struct ASN1Error: Error, Hashable, CustomStringConvertible { /// A string was invalid. @inline(never) public static func invalidStringRepresentation( - reason: String, file: String = #fileID, line: UInt = #line + reason: String, + file: String = #fileID, + line: UInt = #line ) -> ASN1Error { return ASN1Error( backing: .init( - code: .invalidStringRepresentation, reason: reason, file: file, line: line + code: .invalidStringRepresentation, + reason: reason, + file: file, + line: line ) ) } @@ -206,7 +240,7 @@ extension ASN1Error { } // 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 } @@ -215,4 +249,3 @@ extension ASN1Error { } } } - diff --git a/Tests/SwiftASN1Tests/ASN1Tests.swift b/Tests/SwiftASN1Tests/ASN1Tests.swift index 376857b..f7a9583 100644 --- a/Tests/SwiftASN1Tests/ASN1Tests.swift +++ b/Tests/SwiftASN1Tests/ASN1Tests.swift @@ -18,10 +18,12 @@ import XCTest class ASN1Tests: XCTestCase { func testSimpleASN1P256SPKI() throws { // Given a static SPKI structure, verifies the parse. - let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ==" + let encodedSPKI = + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ==" let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!) - let encodedExpectedKeyBytes = "BNmnTK3Ru2lH2R+e2nihRTNNXT55MQtfEnEW+GeqaDAYCbWJVbXfZcut1Eb+e2VtDXLNS4mQe1gE297L7vtXOx0=" + let encodedExpectedKeyBytes = + "BNmnTK3Ru2lH2R+e2nihRTNNXT55MQtfEnEW+GeqaDAYCbWJVbXfZcut1Eb+e2VtDXLNS4mQe1gE297L7vtXOx0=" let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!) let result = try DER.parse(decodedSPKI) @@ -40,10 +42,12 @@ class ASN1Tests: XCTestCase { } func testSimpleASN1P384SPKI() throws { - let encodedSPKI = "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEcBr0TNmgagf1ysckEA/3XLGx2amgzeHjDBZREqhCIVBrLhIiIR4zrJ8dqad/Y+zI2Hu8TIUbrzS/diFpFoE0YYKBTfYMCAUtaWuMb1oaBdFzWsLfYSSzF+ON1yeJCtro" + let encodedSPKI = + "MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEcBr0TNmgagf1ysckEA/3XLGx2amgzeHjDBZREqhCIVBrLhIiIR4zrJ8dqad/Y+zI2Hu8TIUbrzS/diFpFoE0YYKBTfYMCAUtaWuMb1oaBdFzWsLfYSSzF+ON1yeJCtro" let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!) - let encodedExpectedKeyBytes = "BHAa9EzZoGoH9crHJBAP91yxsdmpoM3h4wwWURKoQiFQay4SIiEeM6yfHamnf2PsyNh7vEyFG680v3YhaRaBNGGCgU32DAgFLWlrjG9aGgXRc1rC32EksxfjjdcniQra6A==" + let encodedExpectedKeyBytes = + "BHAa9EzZoGoH9crHJBAP91yxsdmpoM3h4wwWURKoQiFQay4SIiEeM6yfHamnf2PsyNh7vEyFG680v3YhaRaBNGGCgU32DAgFLWlrjG9aGgXRc1rC32EksxfjjdcniQra6A==" let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!) let result = try DER.parse(decodedSPKI) @@ -59,10 +63,12 @@ class ASN1Tests: XCTestCase { } func testSimpleASN1P521SPKI() throws { - let encodedSPKI = "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBTxMJZTRr9NcKmD7iTeX7ofcgz77JPTIDXOHFfS1tZHd9P0uAeK/ARwwDdsQpIKCvmtaO4O52oHqmczdrRwGtrHIBUTqaOw2Fqdiqt0fRQju9wH1Xi4h8u0h80MymUM0sbAQ70jHCeV0S0mGcJS8t3nfP+qLes30h297dPfV3SLsLg8M=" + let encodedSPKI = + "MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBTxMJZTRr9NcKmD7iTeX7ofcgz77JPTIDXOHFfS1tZHd9P0uAeK/ARwwDdsQpIKCvmtaO4O52oHqmczdrRwGtrHIBUTqaOw2Fqdiqt0fRQju9wH1Xi4h8u0h80MymUM0sbAQ70jHCeV0S0mGcJS8t3nfP+qLes30h297dPfV3SLsLg8M=" let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!) - let encodedExpectedKeyBytes = "BAFPEwllNGv01wqYPuJN5fuh9yDPvsk9MgNc4cV9LW1kd30/S4B4r8BHDAN2xCkgoK+a1o7g7nageqZzN2tHAa2scgFROpo7DYWp2Kq3R9FCO73AfVeLiHy7SHzQzKZQzSxsBDvSMcJ5XRLSYZwlLy3ed8/6ot6zfSHb3t099XdIuwuDww==" + let encodedExpectedKeyBytes = + "BAFPEwllNGv01wqYPuJN5fuh9yDPvsk9MgNc4cV9LW1kd30/S4B4r8BHDAN2xCkgoK+a1o7g7nageqZzN2tHAa2scgFROpo7DYWp2Kq3R9FCO73AfVeLiHy7SHzQzKZQzSxsBDvSMcJ5XRLSYZwlLy3ed8/6ot6zfSHb3t099XdIuwuDww==" let expectedKeyBytes = Array(Data(base64Encoded: encodedExpectedKeyBytes)!) let result = try DER.parse(decodedSPKI) @@ -78,13 +84,15 @@ class ASN1Tests: XCTestCase { } func testASN1SEC1PrivateKeyP256() throws { - let encodedPrivateKey = "MHcCAQEEIFAV2+taX2/ht9HEcLQPtfyuRktTkn4S3RaCQwDmDnrloAoGCCqGSM49AwEHoUQDQgAE3Oed98X0hHmzHmmmgtf5rAVEv0jIeH61K61P5UyiCozn+fz+mlmBywvluiVvERiT9WZCd3tkPPWwbIr+a0dnwA==" + let encodedPrivateKey = + "MHcCAQEEIFAV2+taX2/ht9HEcLQPtfyuRktTkn4S3RaCQwDmDnrloAoGCCqGSM49AwEHoUQDQgAE3Oed98X0hHmzHmmmgtf5rAVEv0jIeH61K61P5UyiCozn+fz+mlmBywvluiVvERiT9WZCd3tkPPWwbIr+a0dnwA==" let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!) let encodedPrivateKeyBytes = "UBXb61pfb+G30cRwtA+1/K5GS1OSfhLdFoJDAOYOeuU=" let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!) - let encodedPublicKeyBytes = "BNznnffF9IR5sx5ppoLX+awFRL9IyHh+tSutT+VMogqM5/n8/ppZgcsL5bolbxEYk/VmQnd7ZDz1sGyK/mtHZ8A=" + let encodedPublicKeyBytes = + "BNznnffF9IR5sx5ppoLX+awFRL9IyHh+tSutT+VMogqM5/n8/ppZgcsL5bolbxEYk/VmQnd7ZDz1sGyK/mtHZ8A=" let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!) let result = try DER.parse(decodedPrivateKey) @@ -101,13 +109,15 @@ class ASN1Tests: XCTestCase { } func testASN1SEC1PrivateKeyP384() throws { - let encodedPrivateKey = "MIGkAgEBBDAWv9iH6ZivZKtk5ihjvjlZCYc9JHyykqvmJ7JVQ50ZZWTkCPtIe7RSKzm+l7NJltqgBwYFK4EEACKhZANiAAQz0BBmMxeOj5XwTL1G4fqTYO2UAiYrUMixiRFlFKVY5I6jAgiEWdNbmte8o6dByo0No5YoyDHdG637xvuzGaWd+IT5LoBAVVv3AgL3ao3dA4aVhm6Yz6G6/2o3X7AH99c=" + let encodedPrivateKey = + "MIGkAgEBBDAWv9iH6ZivZKtk5ihjvjlZCYc9JHyykqvmJ7JVQ50ZZWTkCPtIe7RSKzm+l7NJltqgBwYFK4EEACKhZANiAAQz0BBmMxeOj5XwTL1G4fqTYO2UAiYrUMixiRFlFKVY5I6jAgiEWdNbmte8o6dByo0No5YoyDHdG637xvuzGaWd+IT5LoBAVVv3AgL3ao3dA4aVhm6Yz6G6/2o3X7AH99c=" let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!) let encodedPrivateKeyBytes = "Fr/Yh+mYr2SrZOYoY745WQmHPSR8spKr5ieyVUOdGWVk5Aj7SHu0Uis5vpezSZba" let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!) - let encodedPublicKeyBytes = "BDPQEGYzF46PlfBMvUbh+pNg7ZQCJitQyLGJEWUUpVjkjqMCCIRZ01ua17yjp0HKjQ2jlijIMd0brfvG+7MZpZ34hPkugEBVW/cCAvdqjd0DhpWGbpjPobr/ajdfsAf31w==" + let encodedPublicKeyBytes = + "BDPQEGYzF46PlfBMvUbh+pNg7ZQCJitQyLGJEWUUpVjkjqMCCIRZ01ua17yjp0HKjQ2jlijIMd0brfvG+7MZpZ34hPkugEBVW/cCAvdqjd0DhpWGbpjPobr/ajdfsAf31w==" let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!) let result = try DER.parse(decodedPrivateKey) @@ -124,13 +134,16 @@ class ASN1Tests: XCTestCase { } func testASN1SEC1PrivateKeyP521() throws { - let encodedPrivateKey = "MIHcAgEBBEIBONszidL11f7D8LEbVGKG4A7768X16w35/m6OSPO7MGQcYhWHpgSV4NZ6AFKcksavZSCa59lYdAN+MA3sUjO7R/mgBwYFK4EEACOhgYkDgYYABAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ==" + let encodedPrivateKey = + "MIHcAgEBBEIBONszidL11f7D8LEbVGKG4A7768X16w35/m6OSPO7MGQcYhWHpgSV4NZ6AFKcksavZSCa59lYdAN+MA3sUjO7R/mgBwYFK4EEACOhgYkDgYYABAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ==" let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!) - let encodedPrivateKeyBytes = "ATjbM4nS9dX+w/CxG1RihuAO++vF9esN+f5ujkjzuzBkHGIVh6YEleDWegBSnJLGr2UgmufZWHQDfjAN7FIzu0f5" + let encodedPrivateKeyBytes = + "ATjbM4nS9dX+w/CxG1RihuAO++vF9esN+f5ujkjzuzBkHGIVh6YEleDWegBSnJLGr2UgmufZWHQDfjAN7FIzu0f5" let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!) - let encodedPublicKeyBytes = "BAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ==" + let encodedPublicKeyBytes = + "BAAzsbWlHXjMkaSQTBnBKcyPDy/x0nk+VlkYQJXkh+lPJSVEYLbrUZ1LdbfM9mGE7HpgyyELNRHy/BD1JdNnAVPemAC5VQjeGKbezrxz7D5iZNiZiQFVYtMBU3XSsuJrPWVSjBF7xIkOr06k2xg1qlOoXQ66EPHQlwEYJ3xATNKk8K2jlQ==" let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!) let result = try DER.parse(decodedPrivateKey) @@ -147,13 +160,15 @@ class ASN1Tests: XCTestCase { } func testASN1PKCS8PrivateKeyP256() throws { - let encodedPrivateKey = "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgCRQo0CoBKfTOhdgQHcQIVv21vIUsxmE3t9L1LqV00bahRANCAATDXEj3jviAtzgx4bnMa/081v+FXbp7O5D1KtKVdje+ckejGVLYuYKE4Lpf5jonefi6wtoCc/sWHlbLiNV5PEB9" + let encodedPrivateKey = + "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgCRQo0CoBKfTOhdgQHcQIVv21vIUsxmE3t9L1LqV00bahRANCAATDXEj3jviAtzgx4bnMa/081v+FXbp7O5D1KtKVdje+ckejGVLYuYKE4Lpf5jonefi6wtoCc/sWHlbLiNV5PEB9" let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!) let encodedPrivateKeyBytes = "CRQo0CoBKfTOhdgQHcQIVv21vIUsxmE3t9L1LqV00bY=" let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!) - let encodedPublicKeyBytes = "BMNcSPeO+IC3ODHhucxr/TzW/4Vduns7kPUq0pV2N75yR6MZUti5goTgul/mOid5+LrC2gJz+xYeVsuI1Xk8QH0=" + let encodedPublicKeyBytes = + "BMNcSPeO+IC3ODHhucxr/TzW/4Vduns7kPUq0pV2N75yR6MZUti5goTgul/mOid5+LrC2gJz+xYeVsuI1Xk8QH0=" let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!) let result = try DER.parse(decodedPrivateKey) @@ -171,13 +186,15 @@ class ASN1Tests: XCTestCase { } func testASN1PKCS8PrivateKeyP384() throws { - let encodedPrivateKey = "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDCKfeRAkTtGQG7bGao6Ca5MDDcmxttyr6HNmNoaSkmuYvBtLGLLBWm1+VHT602xOIihZANiAAS56RzXiLO5YvFI0qh/+T9DhOXfkm3K/jJSUAqV/hP0FUlIUR824cFVdMMQA1S100mETsxdT0QDqUGAinMTUBSyk9y+jR33Fw/A068ZQRlqTCa0ThS0vwxKhM/M4vhYeDE=" + let encodedPrivateKey = + "MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDCKfeRAkTtGQG7bGao6Ca5MDDcmxttyr6HNmNoaSkmuYvBtLGLLBWm1+VHT602xOIihZANiAAS56RzXiLO5YvFI0qh/+T9DhOXfkm3K/jJSUAqV/hP0FUlIUR824cFVdMMQA1S100mETsxdT0QDqUGAinMTUBSyk9y+jR33Fw/A068ZQRlqTCa0ThS0vwxKhM/M4vhYeDE=" let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!) let encodedPrivateKeyBytes = "in3kQJE7RkBu2xmqOgmuTAw3Jsbbcq+hzZjaGkpJrmLwbSxiywVptflR0+tNsTiI" let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!) - let encodedPublicKeyBytes = "BLnpHNeIs7li8UjSqH/5P0OE5d+Sbcr+MlJQCpX+E/QVSUhRHzbhwVV0wxADVLXTSYROzF1PRAOpQYCKcxNQFLKT3L6NHfcXD8DTrxlBGWpMJrROFLS/DEqEz8zi+Fh4MQ==" + let encodedPublicKeyBytes = + "BLnpHNeIs7li8UjSqH/5P0OE5d+Sbcr+MlJQCpX+E/QVSUhRHzbhwVV0wxADVLXTSYROzF1PRAOpQYCKcxNQFLKT3L6NHfcXD8DTrxlBGWpMJrROFLS/DEqEz8zi+Fh4MQ==" let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!) let result = try DER.parse(decodedPrivateKey) @@ -195,13 +212,16 @@ class ASN1Tests: XCTestCase { } func testASN1PKCS8PrivateKeyP521() throws { - let encodedPrivateKey = "MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIB/rwbfr3a+rdHQvKToS6Fw1WxsVFy3Wq2ylWC+EyQv//nGiT5TQYIAV2WDmmud3WnczITapXAAe6eS66jHa+OxyGhgYkDgYYABADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ==" + let encodedPrivateKey = + "MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIB/rwbfr3a+rdHQvKToS6Fw1WxsVFy3Wq2ylWC+EyQv//nGiT5TQYIAV2WDmmud3WnczITapXAAe6eS66jHa+OxyGhgYkDgYYABADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ==" let decodedPrivateKey = Array(Data(base64Encoded: encodedPrivateKey)!) - let encodedPrivateKeyBytes = "Af68G3692vq3R0Lyk6EuhcNVsbFRct1qtspVgvhMkL//5xok+U0GCAFdlg5prnd1p3MyE2qVwAHunkuuox2vjsch" + let encodedPrivateKeyBytes = + "Af68G3692vq3R0Lyk6EuhcNVsbFRct1qtspVgvhMkL//5xok+U0GCAFdlg5prnd1p3MyE2qVwAHunkuuox2vjsch" let privateKeyBytes = Array(Data(base64Encoded: encodedPrivateKeyBytes)!) - let encodedPublicKeyBytes = "BADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ==" + let encodedPublicKeyBytes = + "BADrY6IBU4t8BjSIvDWA4VrLILdUOFemM2G8phpJWlGpEO8Qmk28w5pdLD2j3chBvg0xBBi2k9Ked9L43R4E3+gPCAA3CY8v01xlA6npJvdAK0/Md4mY+p65Ehua95jXnSwrpF66+Q/se2ODvZPhXGKBvttxrKyBr9htmkAUv9Sdah+dWQ==" let publicKeyBytes = Array(Data(base64Encoded: encodedPublicKeyBytes)!) let result = try DER.parse(decodedPrivateKey) @@ -220,7 +240,8 @@ class ASN1Tests: XCTestCase { func testRejectDripFedASN1SPKIP256() throws { // This test drip-feeds an ASN.1 P256 SPKI block. It should never parse correctly until we feed the entire block. - let encodedSPKI = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ==" + let encodedSPKI = + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE2adMrdG7aUfZH57aeKFFM01dPnkxC18ScRb4Z6poMBgJtYlVtd9ly63URv57ZW0Ncs1LiZB7WATb3svu+1c7HQ==" let decodedSPKI = Array(Data(base64Encoded: encodedSPKI)!) for index in decodedSPKI.indices { @@ -416,12 +437,12 @@ class ASN1Tests: XCTestCase { func testStraightforwardPEMDocumentParsing() throws { let simplePEM = """ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49 -AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG -O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== ------END EC PRIVATE KEY----- -""" + -----BEGIN EC PRIVATE KEY----- + MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49 + AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG + O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== + -----END EC PRIVATE KEY----- + """ let document = try PEMDocument(pemString: simplePEM) XCTAssertEqual(document.discriminator, "EC PRIVATE KEY") XCTAssertEqual(document.derBytes.count, 121) @@ -437,15 +458,15 @@ O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== let reserialized2 = PEMDocument(type: "EC PRIVATE KEY", derBytes: serializer.serializedBytes) XCTAssertEqual(reserialized2.pemString, simplePEM) } - + func testStraightforwardPEMParsing() throws { let simplePEM = """ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49 -AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG -O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== ------END EC PRIVATE KEY----- -""" + -----BEGIN EC PRIVATE KEY----- + MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49 + AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG + O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== + -----END EC PRIVATE KEY----- + """ let pkey = try SEC1PrivateKey(pemEncoded: simplePEM) let reserialized = try pkey.serializeAsPEM().pemString @@ -460,12 +481,12 @@ O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== func testTruncatedPEMDocumentsAreRejected() throws { // We drip feed the PEM one extra character at a time. It never parses successfully. let simplePEM = """ ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49 -AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG -O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== ------END EC PRIVATE KEY----- -""" + -----BEGIN EC PRIVATE KEY----- + MHcCAQEEIBHli4jaj+JwWQlU0yhZUu+TdMPVhZ3wR2PS416Sz/K/oAoGCCqGSM49 + AwEHoUQDQgAEOhvJhbc3zM4SJooCaWdyheY2E6wWkISg7TtxJYgb/S0Zz7WruJzG + O9zxi7HTvuXyQr7QKSBtdCGmHym+WoPsbA== + -----END EC PRIVATE KEY----- + """ for index in simplePEM.indices.dropLast() { XCTAssertThrowsError(try PEMDocument(pemString: String(simplePEM[.., @@ -929,7 +990,8 @@ O9zxi7HTvuXyQr7QKSBtdC%mHym+WoPsbA== XCTAssert( asn1SetElementLessThanOrEqual(lhs, rhs), "\(lhs) is not less than or equal to \(rhs)", - file: file, line: line + file: file, + line: line ) } assertSetOfLessThanOrEqual([1], [1]) diff --git a/Tests/SwiftASN1Tests/GeneralizedTimeTests.swift b/Tests/SwiftASN1Tests/GeneralizedTimeTests.swift index de0a6ac..816f368 100644 --- a/Tests/SwiftASN1Tests/GeneralizedTimeTests.swift +++ b/Tests/SwiftASN1Tests/GeneralizedTimeTests.swift @@ -28,26 +28,86 @@ final class GeneralizedTimeTests: XCTestCase { // We store the byte payload here as a string. let vectors: [(String, GeneralizedTime?)] = [ // Valid representations - ("19920521000000Z", try .init(year: 1992, month: 5, day: 21, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), - ("19920622123421Z", try .init(year: 1992, month: 6, day: 22, hours: 12, minutes: 34, seconds: 21, fractionalSeconds: 0)), - ("19920722132100.3Z", try .init(year: 1992, month: 7, day: 22, hours: 13, minutes: 21, seconds: 0, fractionalSeconds: 0.3)), - ("19851106210627.3Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.3)), - ("19851106210627.14159Z", try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.14159)), - ("20210131000000Z", try .init(year: 2021, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in January - ("20210228000000Z", try .init(year: 2021, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 28 days in February 2021 - ("20200229000000Z", try .init(year: 2020, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 29 days in February 2020 - ("21000228000000Z", try .init(year: 2100, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 28 days in February 2100 - ("20000229000000Z", try .init(year: 2000, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 29 days in February 2000 - ("20210331000000Z", try .init(year: 2021, month: 3, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in March - ("20210430000000Z", try .init(year: 2021, month: 4, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in April - ("20210531000000Z", try .init(year: 2021, month: 5, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in May - ("20210630000000Z", try .init(year: 2021, month: 6, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in June - ("20210731000000Z", try .init(year: 2021, month: 7, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in July - ("20210831000000Z", try .init(year: 2021, month: 8, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in August - ("20210930000000Z", try .init(year: 2021, month: 9, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in September - ("20211031000000Z", try .init(year: 2021, month: 10, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in October - ("20211130000000Z", try .init(year: 2021, month: 11, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 30 days in November - ("20211231000000Z", try .init(year: 2021, month: 12, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0)), // only 31 days in December + ( + "19920521000000Z", + try .init(year: 1992, month: 5, day: 21, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), + ( + "19920622123421Z", + try .init(year: 1992, month: 6, day: 22, hours: 12, minutes: 34, seconds: 21, fractionalSeconds: 0) + ), + ( + "19920722132100.3Z", + try .init(year: 1992, month: 7, day: 22, hours: 13, minutes: 21, seconds: 0, fractionalSeconds: 0.3) + ), + ( + "19851106210627.3Z", + try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.3) + ), + ( + "19851106210627.14159Z", + try .init(year: 1985, month: 11, day: 6, hours: 21, minutes: 6, seconds: 27, fractionalSeconds: 0.14159) + ), + ( + "20210131000000Z", + try .init(year: 2021, month: 1, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 31 days in January + ( + "20210228000000Z", + try .init(year: 2021, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 28 days in February 2021 + ( + "20200229000000Z", + try .init(year: 2020, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 29 days in February 2020 + ( + "21000228000000Z", + try .init(year: 2100, month: 2, day: 28, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 28 days in February 2100 + ( + "20000229000000Z", + try .init(year: 2000, month: 2, day: 29, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 29 days in February 2000 + ( + "20210331000000Z", + try .init(year: 2021, month: 3, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 31 days in March + ( + "20210430000000Z", + try .init(year: 2021, month: 4, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 30 days in April + ( + "20210531000000Z", + try .init(year: 2021, month: 5, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 31 days in May + ( + "20210630000000Z", + try .init(year: 2021, month: 6, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 30 days in June + ( + "20210731000000Z", + try .init(year: 2021, month: 7, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 31 days in July + ( + "20210831000000Z", + try .init(year: 2021, month: 8, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 31 days in August + ( + "20210930000000Z", + try .init(year: 2021, month: 9, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 30 days in September + ( + "20211031000000Z", + try .init(year: 2021, month: 10, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 31 days in October + ( + "20211130000000Z", + try .init(year: 2021, month: 11, day: 30, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 30 days in November + ( + "20211231000000Z", + try .init(year: 2021, month: 12, day: 31, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 0) + ), // only 31 days in December // Invalid representations ("19920520240000Z", nil), // midnight may not be 2400000 @@ -79,11 +139,11 @@ final class GeneralizedTimeTests: XCTestCase { ("20211131000000Z", nil), // only 30 days in November ("20211232000000Z", nil), // only 31 days in December ("20200101000000.9223372036854775808Z", nil), // Fractional part will overflow a 64-bit integer by adding - ("20200101000000.92233720368547758071Z", nil), // Fractional part will overflow a 64-bit integer by multiplication + ] for (stringRepresentation, expectedResult) in vectors { - var serialized = Array() + var serialized = [UInt8]() serialized.writeIdentifier(ASN1Identifier.generalizedTime, constructed: false) serialized.append(UInt8(stringRepresentation.utf8.count)) serialized.append(contentsOf: stringRepresentation.utf8) @@ -102,40 +162,69 @@ final class GeneralizedTimeTests: XCTestCase { XCTAssertThrowsError(try code()) } - mustFail(try .init(year: -1, month: 1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid year, negative - mustFail(try .init(year: 2000, month: 0, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, zero. - mustFail(try .init(year: 2000, month: -1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, negative. - mustFail(try .init(year: 2000, month: 13, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid month, too large. - mustFail(try .init(year: 2000, month: 1, day: 0, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid day, zero. - mustFail(try .init(year: 2000, month: 1, day: -1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid day, negative. - mustFail(try .init(year: 2000, month: 1, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in January - mustFail(try .init(year: 2021, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 28 days in February 2021 - mustFail(try .init(year: 2020, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 29 days in February 2020 - mustFail(try .init(year: 2100, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 28 days in February 2100 - mustFail(try .init(year: 2000, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 29 days in February 2000 - mustFail(try .init(year: 2000, month: 3, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in March - mustFail(try .init(year: 2000, month: 4, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in April - mustFail(try .init(year: 2000, month: 5, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in May - mustFail(try .init(year: 2000, month: 6, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in June - mustFail(try .init(year: 2000, month: 7, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in July - mustFail(try .init(year: 2000, month: 8, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in August - mustFail(try .init(year: 2000, month: 9, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in September - mustFail(try .init(year: 2000, month: 10, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in October - mustFail(try .init(year: 2000, month: 11, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 30 days in November - mustFail(try .init(year: 2000, month: 11, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // only 31 days in December - mustFail(try .init(year: 2000, month: 1, day: 1, hours: -1, minutes: 1, seconds: 1, fractionalSeconds: 0)) // Invalid hour, negative - mustFail(try .init(year: 2000, month: 1, day: 1, hours: 24, minutes: 0, seconds: 0, fractionalSeconds: 0)) // Invalid hour, 24 - mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: -1, seconds: 1, fractionalSeconds: 0)) // Invalid minute, negative - mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 60, seconds: 0, fractionalSeconds: 0)) // Invalid minute, 60 - mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: -1, fractionalSeconds: 0)) // Invalid second, negative - mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 62, fractionalSeconds: 0)) // Invalid second, 62 (we allow some leap seconds) - mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: -0.5)) // Invalid fractional seconds, negative - mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 1.1)) // Invalid fractional seconds, greater than one + // Invalid year, negative + mustFail(try .init(year: -1, month: 1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // Invalid month, zero. + mustFail(try .init(year: 2000, month: 0, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // Invalid month, negative. + mustFail(try .init(year: 2000, month: -1, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // Invalid month, too large. + mustFail(try .init(year: 2000, month: 13, day: 1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // Invalid day, zero. + mustFail(try .init(year: 2000, month: 1, day: 0, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // Invalid day, negative. + mustFail(try .init(year: 2000, month: 1, day: -1, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 31 days in January + mustFail(try .init(year: 2000, month: 1, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 28 days in February 2021 + mustFail(try .init(year: 2021, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 29 days in February 2020 + mustFail(try .init(year: 2020, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 28 days in February 2100 + mustFail(try .init(year: 2100, month: 2, day: 29, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 29 days in February 2000 + mustFail(try .init(year: 2000, month: 2, day: 30, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 31 days in March + mustFail(try .init(year: 2000, month: 3, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 30 days in April + mustFail(try .init(year: 2000, month: 4, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 31 days in May + mustFail(try .init(year: 2000, month: 5, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 30 days in June + mustFail(try .init(year: 2000, month: 6, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 31 days in July + mustFail(try .init(year: 2000, month: 7, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 31 days in August + mustFail(try .init(year: 2000, month: 8, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 30 days in September + mustFail(try .init(year: 2000, month: 9, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 31 days in October + mustFail(try .init(year: 2000, month: 10, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 30 days in November + mustFail(try .init(year: 2000, month: 11, day: 31, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // only 31 days in December + mustFail(try .init(year: 2000, month: 11, day: 32, hours: 1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // Invalid hour, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: -1, minutes: 1, seconds: 1, fractionalSeconds: 0)) + // Invalid hour, 24 + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 24, minutes: 0, seconds: 0, fractionalSeconds: 0)) + // Invalid minute, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: -1, seconds: 1, fractionalSeconds: 0)) + // Invalid minute, 60 + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 60, seconds: 0, fractionalSeconds: 0)) + // Invalid second, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: -1, fractionalSeconds: 0)) + // Invalid second, 62 (we allow some leap seconds) + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 62, fractionalSeconds: 0)) + // Invalid fractional seconds, negative + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: -0.5)) + // Invalid fractional seconds, greater than one + mustFail(try .init(year: 2000, month: 1, day: 1, hours: 0, minutes: 0, seconds: 0, fractionalSeconds: 1.1)) } func testTruncatedRepresentationsRejected() throws { func mustNotDeserialize(_ stringRepresentation: Substring) { - var serialized = Array() + var serialized = [UInt8]() serialized.writeIdentifier(ASN1Identifier.generalizedTime, constructed: false) serialized.append(UInt8(stringRepresentation.utf8.count)) serialized.append(contentsOf: stringRepresentation.utf8) @@ -144,7 +233,7 @@ final class GeneralizedTimeTests: XCTestCase { } func deserializes(_ stringRepresentation: Substring) { - var serialized = Array() + var serialized = [UInt8]() serialized.writeIdentifier(ASN1Identifier.generalizedTime, constructed: false) serialized.append(UInt8(stringRepresentation.utf8.count)) serialized.append(contentsOf: stringRepresentation.utf8) @@ -170,7 +259,7 @@ final class GeneralizedTimeTests: XCTestCase { func testRequiresAppropriateTag() throws { let rawValue = "19920521000000Z".utf8 - var invalidBytes = Array() + var invalidBytes = [UInt8]() invalidBytes.writeIdentifier(ASN1Identifier.integer, constructed: false) // generalizedTime isn't an integer invalidBytes.append(UInt8(rawValue.count)) invalidBytes.append(contentsOf: rawValue) @@ -185,16 +274,28 @@ final class GeneralizedTimeTests: XCTestCase { case greaterThan } - let original = try GeneralizedTime(year: 2020, month: 03, day: 03, hours: 03, minutes: 03, seconds: 03, fractionalSeconds: 0.105) + let original = try GeneralizedTime( + year: 2020, + month: 03, + day: 03, + hours: 03, + minutes: 03, + seconds: 03, + fractionalSeconds: 0.105 + ) - func modify(_ field: WritableKeyPath, of time: GeneralizedTime, by modifier: Modifiable) -> GeneralizedTime { + func modify( + _ field: WritableKeyPath, + of time: GeneralizedTime, + by modifier: Modifiable + ) -> GeneralizedTime { var copy = time copy[keyPath: field] += modifier return copy } let integerTransformable: [WritableKeyPath] = [ - \.year, \.month, \.day, \.hours, \.minutes, \.seconds + \.year, \.month, \.day, \.hours, \.minutes, \.seconds, ] var transformationsAndResults: [(GeneralizedTime, ExpectedComparisonResult)] = [] @@ -208,10 +309,20 @@ final class GeneralizedTimeTests: XCTestCase { transformationsAndResults.append((modify(\.fractionalSeconds, of: original, by: 0.1), .greaterThan)) transformationsAndResults.append((modify(\.fractionalSeconds, of: original, by: -0.1), .lessThan)) - transformationsAndResults.append(( - try GeneralizedTime(year: 2019, month: 08, day: 08, hours: 08, minutes: 08, seconds: 08, fractionalSeconds: 0.205), - .lessThan - )) + transformationsAndResults.append( + ( + try GeneralizedTime( + year: 2019, + month: 08, + day: 08, + hours: 08, + minutes: 08, + seconds: 08, + fractionalSeconds: 0.205 + ), + .lessThan + ) + ) for (newValue, expectedResult) in transformationsAndResults { switch expectedResult { diff --git a/Tests/SwiftASN1Tests/Test Helper Types/SEC1PrivateKey.swift b/Tests/SwiftASN1Tests/Test Helper Types/SEC1PrivateKey.swift index 5d9400b..66519b7 100644 --- a/Tests/SwiftASN1Tests/Test Helper Types/SEC1PrivateKey.swift +++ b/Tests/SwiftASN1Tests/Test Helper Types/SEC1PrivateKey.swift @@ -23,7 +23,7 @@ import SwiftASN1 // } struct SEC1PrivateKey: DERImplicitlyTaggable, PEMRepresentable { static let defaultPEMDiscriminator: String = "EC PRIVATE KEY" - + static var defaultIdentifier: ASN1Identifier { return .sequence } @@ -42,7 +42,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 diff --git a/Tests/SwiftASN1Tests/Test Helper Types/SubjectPublicKeyInfo.swift b/Tests/SwiftASN1Tests/Test Helper Types/SubjectPublicKeyInfo.swift index 47de6b0..1ea7fd4 100644 --- a/Tests/SwiftASN1Tests/Test Helper Types/SubjectPublicKeyInfo.swift +++ b/Tests/SwiftASN1Tests/Test Helper Types/SubjectPublicKeyInfo.swift @@ -103,15 +103,20 @@ struct RFC5480AlgorithmIdentifier: DERImplicitlyTaggable, Hashable { } } - // MARK: Algorithm Identifier Statics extension RFC5480AlgorithmIdentifier { - static let ecdsaP256 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey, - parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp256r1)) + static let ecdsaP256 = RFC5480AlgorithmIdentifier( + algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp256r1) + ) - static let ecdsaP384 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey, - parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp384r1)) + static let ecdsaP384 = RFC5480AlgorithmIdentifier( + algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp384r1) + ) - static let ecdsaP521 = RFC5480AlgorithmIdentifier(algorithm: .AlgorithmIdentifier.idEcPublicKey, - parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp521r1)) + static let ecdsaP521 = RFC5480AlgorithmIdentifier( + algorithm: .AlgorithmIdentifier.idEcPublicKey, + parameters: try! .init(erasing: ASN1ObjectIdentifier.NamedCurves.secp521r1) + ) } diff --git a/Tests/SwiftASN1Tests/UTCTimeTests.swift b/Tests/SwiftASN1Tests/UTCTimeTests.swift index 0def334..c6fbfda 100644 --- a/Tests/SwiftASN1Tests/UTCTimeTests.swift +++ b/Tests/SwiftASN1Tests/UTCTimeTests.swift @@ -32,7 +32,7 @@ final class UTCTimeTests: XCTestCase { } let integerTransformable: [WritableKeyPath] = [ - \.year, \.month, \.day, \.hours, \.minutes, \.seconds + \.year, \.month, \.day, \.hours, \.minutes, \.seconds, ] var transformationsAndResults: [(UTCTime, ExpectedComparisonResult)] = [] @@ -43,10 +43,12 @@ final class UTCTimeTests: XCTestCase { transformationsAndResults.append((modify(transform, of: original, by: -1), .lessThan)) } - transformationsAndResults.append(( - try UTCTime(year: 2019, month: 08, day: 08, hours: 08, minutes: 08, seconds: 08), - .lessThan - )) + transformationsAndResults.append( + ( + try UTCTime(year: 2019, month: 08, day: 08, hours: 08, minutes: 08, seconds: 08), + .lessThan + ) + ) for (newValue, expectedResult) in transformationsAndResults { switch expectedResult { diff --git a/docker/Dockerfile b/docker/Dockerfile index daba577..e4828b4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -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 diff --git a/scripts/run-swift-format.sh b/scripts/run-swift-format.sh new file mode 100644 index 0000000..35aec4b --- /dev/null +++ b/scripts/run-swift-format.sh @@ -0,0 +1,54 @@ +#!/bin/bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftASN1 open source project +## +## Copyright (c) 2022-2023 Apple Inc. and the SwiftASN1 project authors +## Licensed under Apache License v2.0 +## +## See LICENSE.txt for license information +## See CONTRIBUTORS.txt for the list of SwiftASN1 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." diff --git a/scripts/soundness.sh b/scripts/soundness.sh index c84d99f..81fe1a2 100755 --- a/scripts/soundness.sh +++ b/scripts/soundness.sh @@ -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)