Skip to content

Commit

Permalink
chore: Align code style
Browse files Browse the repository at this point in the history
  • Loading branch information
kylef committed Dec 2, 2016
1 parent e36d4f0 commit 8e72a33
Show file tree
Hide file tree
Showing 8 changed files with 32 additions and 39 deletions.
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import PackageDescription
let package = Package(
name: "JWT",
dependencies: [
.Package(url: "https://github.com/krzyzanowskim/CryptoSwift", versions: Version(0, 6, 1) ..< Version(0, 7, 0))
.Package(url: "https://github.com/krzyzanowskim/CryptoSwift", versions: Version(0, 6, 1) ..< Version(0, 7, 0)),
]
)
5 changes: 2 additions & 3 deletions Sources/Base64.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import Foundation


/// URI Safe base64 encode
func base64encode(_ input:Data) -> String {
func base64encode(_ input: Data) -> String {
let data = input.base64EncodedData(options: NSData.Base64EncodingOptions(rawValue: 0))
let string = String(data: data, encoding: .utf8)!
return string
Expand All @@ -12,7 +11,7 @@ func base64encode(_ input:Data) -> String {
}

/// URI Safe base64 decode
func base64decode(_ input:String) -> Data? {
func base64decode(_ input: String) -> Data? {
let rem = input.characters.count % 4

var ending = ""
Expand Down
2 changes: 1 addition & 1 deletion Sources/Claims.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

func validateDate(_ payload:Payload, key:String, comparison:ComparisonResult, failure:InvalidToken, decodeError:String) throws {
func validateDate(_ payload: Payload, key: String, comparison: ComparisonResult, failure: InvalidToken, decodeError: String) throws {
if payload[key] == nil {
return
}
Expand Down
10 changes: 3 additions & 7 deletions Sources/Decode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation


/// Failure reasons from decoding a JWT
public enum InvalidToken : CustomStringConvertible, Error {
public enum InvalidToken: CustomStringConvertible, Error {
/// Decoding the JWT itself failed
case decodeError(String)

Expand All @@ -25,7 +25,7 @@ public enum InvalidToken : CustomStringConvertible, Error {
case invalidIssuer

/// Returns a readable description of the error
public var description:String {
public var description: String {
switch self {
case .decodeError(let error):
return "Decode Error: \(error)"
Expand Down Expand Up @@ -58,30 +58,26 @@ public func decode(_ jwt: String, algorithms: [Algorithm], verify: Bool = true,
return claims
}


/// Decode a JWT
public func decode(_ jwt: String, algorithm: Algorithm, verify: Bool = true, audience: String? = nil, issuer: String? = nil) throws -> ClaimSet {
return try decode(jwt, algorithms: [algorithm], verify: verify, audience: audience, issuer: issuer)
}


/// Decode a JWT
@available(*, deprecated, message: "use decode that returns a ClaimSet instead")
public func decode(_ jwt: String, algorithms: [Algorithm], verify: Bool = true, audience: String? = nil, issuer: String? = nil) throws -> Payload {
return try decode(jwt, algorithms: algorithms, verify: verify, audience: audience, issuer: issuer).claims
}


/// Decode a JWT
@available(*, deprecated, message: "use decode that returns a ClaimSet instead")
public func decode(_ jwt: String, algorithm: Algorithm, verify: Bool = true, audience: String? = nil, issuer: String? = nil) throws -> Payload {
return try decode(jwt, algorithms: [algorithm], verify: verify, audience: audience, issuer: issuer).claims
}


// MARK: Parsing a JWT

func load(_ jwt:String) throws -> (header: JOSEHeader, payload: ClaimSet, signature: Data, signatureInput: String) {
func load(_ jwt: String) throws -> (header: JOSEHeader, payload: ClaimSet, signature: Data, signatureInput: String) {
let segments = jwt.components(separatedBy: ".")
if segments.count != 3 {
throw InvalidToken.decodeError("Not enough segments")
Expand Down
2 changes: 1 addition & 1 deletion Sources/Encode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public func encode(claims: [String: Any], algorithm: Algorithm) -> String {


/// Encode a set of claims using the builder pattern
public func encode(_ algorithm: Algorithm, closure: ((ClaimSetBuilder) -> ())) -> String {
public func encode(_ algorithm: Algorithm, closure: ((ClaimSetBuilder) -> Void)) -> String {
let builder = ClaimSetBuilder()
closure(builder)
return encode(claims: builder.claims, algorithm: algorithm)
Expand Down
12 changes: 6 additions & 6 deletions Sources/JWT.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import CryptoSwift
public typealias Payload = [String: Any]

/// The supported Algorithms
public enum Algorithm : CustomStringConvertible {
public enum Algorithm: CustomStringConvertible {
/// No Algorithm, i-e, insecure
case none

Expand All @@ -17,7 +17,7 @@ public enum Algorithm : CustomStringConvertible {
/// HMAC using SHA-512 hash algorithm
case hs512(Data)

public var description:String {
public var description: String {
switch self {
case .none:
return "none"
Expand All @@ -31,10 +31,10 @@ public enum Algorithm : CustomStringConvertible {
}

/// Sign a message using the algorithm
func sign(_ message:String) -> String {
func signHS(_ key: Data, variant:CryptoSwift.HMAC.Variant) -> String {
func sign(_ message: String) -> String {
func signHS(_ key: Data, variant: CryptoSwift.HMAC.Variant) -> String {
let messageData = message.data(using: String.Encoding.utf8, allowLossyConversion: false)!
let mac = HMAC(key: key.bytes, variant:variant)
let mac = HMAC(key: key.bytes, variant: variant)
let result: [UInt8]
do {
result = try mac.authenticate(messageData.bytes)
Expand All @@ -60,7 +60,7 @@ public enum Algorithm : CustomStringConvertible {
}

/// Verify a signature for a message using the algorithm
func verify(_ message:String, signature:Data) -> Bool {
func verify(_ message: String, signature: Data) -> Bool {
return sign(message) == base64encode(signature)
}
}
30 changes: 15 additions & 15 deletions Tests/JWTTests/JWTTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ class EncodeTests: XCTestCase {
class PayloadTests: XCTestCase {
func testIssuer() {
_ = JWT.encode(.none) { builder in
builder.issuer = "fuller.li"
builder.issuer = "fuller.li"
XCTAssertEqual(builder.issuer, "fuller.li")
XCTAssertEqual(builder["iss"] as? String, "fuller.li")
}
Expand Down Expand Up @@ -106,26 +106,26 @@ class DecodeTests: XCTestCase {

func testDisablingVerify() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.2_8pWJfyPup0YwOXK7g9Dn0cF1E3pdn299t4hSeJy5w"
assertSuccess(try decode(jwt, algorithm: .none, verify:false, issuer:"fuller.li"))
assertSuccess(try decode(jwt, algorithm: .none, verify: false, issuer: "fuller.li"))
}

// MARK: Issuer claim

func testSuccessfulIssuerValidation() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmdWxsZXIubGkifQ.d7B7PAQcz1E6oNhrlxmHxHXHgg39_k7X7wWeahl8kSQ"
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), issuer:"fuller.li")) { payload in
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), issuer: "fuller.li")) { payload in
XCTAssertEqual(payload as! [String: String], ["iss": "fuller.li"])
}
}

func testIncorrectIssuerValidation() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmdWxsZXIubGkifQ.wOhJ9_6lx-3JGJPmJmtFCDI3kt7uMAMmhHIslti7ryI"
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), issuer:"querykit.org"))
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), issuer: "querykit.org"))
}

func testMissingIssuerValidation() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.2_8pWJfyPup0YwOXK7g9Dn0cF1E3pdn299t4hSeJy5w"
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), issuer:"fuller.li"))
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), issuer: "fuller.li"))
}

// MARK: Expiration claim
Expand All @@ -147,7 +147,7 @@ class DecodeTests: XCTestCase {
XCTAssertEqual(payload as! [String: Int], ["exp": 1728188491])
}
}

func testUnexpiredClaimString() {
// If this just started failing, hello 2024!
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIxNzI4MTg4NDkxIn0.y4w7lNLrfRRPzuNUfM-ZvPkoOtrTU_d8ZVYasLdZGpk"
Expand All @@ -164,7 +164,7 @@ class DecodeTests: XCTestCase {
XCTAssertEqual(payload as! [String: Int], ["nbf": 1428189720])
}
}

func testNotBeforeClaimString() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOiIxNDI4MTg5NzIwIn0.qZsj36irdmIAeXv6YazWDSFbpuxHtEh4Deof5YTpnVI"
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!))) { payload in
Expand Down Expand Up @@ -215,34 +215,34 @@ class DecodeTests: XCTestCase {

func testAudiencesClaim() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsibWF4aW5lIiwia2F0aWUiXX0.-PKvdNLCClrWG7CvesHP6PB0-vxu-_IZcsYhJxBy5JM"
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience:"maxine")) { payload in
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience: "maxine")) { payload in
XCTAssertEqual(payload.count, 1)
XCTAssertEqual(payload["aud"] as! [String], ["maxine", "katie"])
}
}

func testAudienceClaim() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJreWxlIn0.dpgH4JOwueReaBoanLSxsGTc7AjKUvo7_M1sAfy_xVE"
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience:"kyle")) { payload in
assertSuccess(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience: "kyle")) { payload in
XCTAssertEqual(payload as! [String: String], ["aud": "kyle"])
}
}

func testMismatchAudienceClaim() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJreWxlIn0.VEB_n06pTSLlTXPFkc46ARADJ9HXNUBUPo3VhL9RDe4" // kyle
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience:"maxine"))
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience: "maxine"))
}

func testMissingAudienceClaim() {
let jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.2_8pWJfyPup0YwOXK7g9Dn0cF1E3pdn299t4hSeJy5w"
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience:"kyle"))
assertFailure(try decode(jwt, algorithm: .hs256("secret".data(using: .utf8)!), audience: "kyle"))
}

// MARK: Signature verification

func testNoneAlgorithm() {
let jwt = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJ0ZXN0IjoiaW5nIn0."
assertSuccess(try decode(jwt, algorithm:.none)) { payload in
assertSuccess(try decode(jwt, algorithm: .none)) { payload in
XCTAssertEqual(payload as! [String: String], ["test": "ing"])
}
}
Expand Down Expand Up @@ -274,7 +274,7 @@ class DecodeTests: XCTestCase {

// MARK: Helpers

func assertSuccess(_ decoder: @autoclosure () throws -> Payload, closure:((Payload) -> ())? = nil) {
func assertSuccess(_ decoder: @autoclosure () throws -> Payload, closure: ((Payload) -> Void)? = nil) {
do {
let payload = try decoder()
closure?(payload)
Expand All @@ -283,7 +283,7 @@ func assertSuccess(_ decoder: @autoclosure () throws -> Payload, closure:((Paylo
}
}

func assertFailure(_ decoder: @autoclosure () throws -> Payload, closure:((InvalidToken) -> ())? = nil) {
func assertFailure(_ decoder: @autoclosure () throws -> Payload, closure: ((InvalidToken) -> Void)? = nil) {
do {
_ = try decoder()
XCTFail("Decoding succeeded, expected a failure.")
Expand All @@ -294,7 +294,7 @@ func assertFailure(_ decoder: @autoclosure () throws -> Payload, closure:((Inval
}
}

func assertDecodeError(_ decoder:@autoclosure () throws -> Payload, error:String) {
func assertDecodeError(_ decoder: @autoclosure () throws -> Payload, error: String) {
assertFailure(try decoder()) { failure in
switch failure {
case .decodeError(let decodeError):
Expand Down
8 changes: 3 additions & 5 deletions Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@ import XCTest


extension EncodeTests {
static var allTests : [(String, (EncodeTests) -> () throws -> Void)] {
static var allTests: [(String, (EncodeTests) -> Void throws -> Void)] {
return [
("testEncodingJWT", testEncodingJWT),
("testEncodingWithBuilder", testEncodingWithBuilder),
]
}
}


extension DecodeTests {
static var allTests : [(String, (DecodeTests) -> () throws -> Void)] {
static var allTests: [(String, (DecodeTests) -> Void throws -> Void)] {
return [
("testDecodingValidJWT", testDecodingValidJWT),
("testFailsToDecodeInvalidStringWithoutThreeSegments", testFailsToDecodeInvalidStringWithoutThreeSegments),
Expand Down Expand Up @@ -46,9 +45,8 @@ extension DecodeTests {
}
}


extension PayloadTests {
static var allTests : [(String, (PayloadTests) -> () throws -> Void)] {
static var allTests: [(String, (PayloadTests) -> Void throws -> Void)] {
return [
("testIssuer", testIssuer),
("testAudience", testAudience),
Expand Down

0 comments on commit 8e72a33

Please sign in to comment.