hummingbird-project / hummingbird-examples

Examples demonstrating various aspects of the Hummingbird swift server framework
Apache License 2.0
90 stars 19 forks source link

Question about Bcrypt hash and verify caller thread #77

Closed ladiesman218 closed 7 months ago

ladiesman218 commented 7 months ago

I see BCrypt.hash() and BCrypt.verify() used in multiple examples, however some of them are called on NIO's thread pool, like:

https://github.com/hummingbird-project/hummingbird-examples/blob/da34b0829b93fcac4c4231fcc18ff6d3eaadb8c3/sessions/Sources/App/Models/User.swift#L47

https://github.com/hummingbird-project/hummingbird-examples/blob/da34b0829b93fcac4c4231fcc18ff6d3eaadb8c3/auth-jwt/Sources/App/Middleware/BasicAuthenticator.swift#L35

https://github.com/hummingbird-project/hummingbird-examples/blob/da34b0829b93fcac4c4231fcc18ff6d3eaadb8c3/todos-auth-fluent/Sources/App/Models/User.swift#L68

And some of them are not, like: https://github.com/hummingbird-project/hummingbird-examples/blob/da34b0829b93fcac4c4231fcc18ff6d3eaadb8c3/auth-jwt/Sources/App/Models/User.swift#L44

https://github.com/hummingbird-project/hummingbird-examples/blob/da34b0829b93fcac4c4231fcc18ff6d3eaadb8c3/todos-auth-fluent/Sources/App/Middleware/BasicAuthenticator.swift#L33

So, what gives?

adam-fowler commented 7 months ago

Ah they should all be called inside NIOThreadPool.singleton.runIfActive. Bcrypt is a long process and you don't want it blocking one of your threads on the main task pool.

ladiesman218 commented 7 months ago

@adam-fowler thanks, good to know.

So is there any way to modify the hash() and verify function themselves, other than relying on users to avoid making the mistake?

adam-fowler commented 7 months ago

I cannot assume that the user wants to use NIOThreadPool.singleton to run their hashing, verifying code.

ladiesman218 commented 7 months ago

I mean the framework user😂 If NIOThreadPool.singleton is not the proper way to call hashing and verifying method, then what is? Sorry but my understand of SwiftNIO is quite shallow atm.

adam-fowler commented 7 months ago

NIOThreadPool.singleton is the most likely way people will run long running code off the main task threads. A user might have their own NIOThreadPool which they've fine tuned for their setup though. And I wouldn't want to initialise a whole series of extra threads by instantiating NIOThreadPool.singleton in that case.