Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make HMAC signer thread safe #117

Merged
merged 1 commit into from Mar 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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