Skip to content

Commit

Permalink
make HMAC jwt signer thread safe (#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanner0101 committed Mar 12, 2020
1 parent d83df63 commit 03c8c11
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Sources/JWT/JWTSigner.swift
Expand Up @@ -80,11 +80,11 @@ extension JWTSigner {
}

/// Creates an HMAC-based `CustomJWTAlgorithm` and `JWTSigner`.
private static func hmac(_ hmac: HMAC, name: String, key: LosslessDataConvertible) -> JWTSigner {
private static func hmac(_ hmac: @autoclosure @escaping () -> HMAC, name: String, key: LosslessDataConvertible) -> JWTSigner {
let alg = CustomJWTAlgorithm(name: name, sign: { plaintext in
return try hmac.authenticate(plaintext, key: key)
return try hmac().authenticate(plaintext, key: key)
}, verify: { signature, plaintext in
return try hmac.authenticate(plaintext, key: key) == signature.convertToData()
return try hmac().authenticate(plaintext, key: key) == signature.convertToData()
})
return .init(algorithm: alg)
}
Expand Down
31 changes: 31 additions & 0 deletions Tests/JWTTests/JWTTests.swift
Expand Up @@ -79,6 +79,36 @@ class JWTTests: XCTestCase {
XCTAssertEqual(publicVerified.payload.name, "Foo")
XCTAssertEqual(privateVerified.payload.name, "Foo")
}

func testThreadSafety() throws {
let signer = JWTSigner.hs256(key: "test")

let start = DispatchGroup()
start.enter()
start.enter()

let done = DispatchGroup()
done.enter()
done.enter()

Thread.async {
start.leave()
start.wait()
for _ in 0..<100 {
_ = try? signer.verify("foo", header: "bar", payload: "baz")
}
done.leave()
}
Thread.async {
start.leave()
start.wait()
for _ in 0..<100 {
_ = try? signer.verify("foo", header: "bar", payload: "baz")
}
done.leave()
}
done.wait()
}

static var allTests = [
("testParse", testParse),
Expand All @@ -87,6 +117,7 @@ class JWTTests: XCTestCase {
("testExpirationEncoding", testExpirationEncoding),
("testSigners", testSigners),
("testRSA", testRSA),
("testThreadSafety", testThreadSafety),
]
}

Expand Down

0 comments on commit 03c8c11

Please sign in to comment.