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 the encoding API more type-safe #403

Open
GBathie opened this issue Aug 28, 2024 · 0 comments
Open

Make the encoding API more type-safe #403

GBathie opened this issue Aug 28, 2024 · 0 comments

Comments

@GBathie
Copy link

GBathie commented Aug 28, 2024

Hi!

The current API allows writing encoding code with a key that does not match the algorithm used, e.g.

let header = Header { alg: Algorithm::RS256, ..Default::default() };
let encoding_key = EncodingKey::from_secret("shared_secret".as_bytes());
let token = encode(&header, &claims, &encoding_key);

This results in an error because the key type does not match the algorithm family.
This kind of error could be caught at compile time.

My proposal is to change the crate's API to catch this kind of error at compile-time instead of runtime, by moving from an enum-based checking to a type-based system.
Here is an overview of the proposed changes:

  • Each algorithm family becomes a separated enum.
  • the Header struct is changed to Header<AF>, taking its algorithm family enum as type parameter, with an algorithm: AF data member.
  • similarly, the EncodingKey struct is changed to EncodingKey<AF>, with AF recorded in a PhantomData member.
  • the encode function's signature is changed to something like
pub fn encode<T: Serialize, AF>(header: &Header<AF>, claims: &T, key: &EncodingKey<AF>) -> Result<String>

With this approach, code using a key for the wrong algorithm family will no longer compile, and we can get rid of some runtime checks.
On the other hand, you can no longer implement FromStr for all algorithms families at once. But since one needs to call a different function to generate the key depending on the algorithm family, I don't think this is a huge problem.

Would you be interested in a PR implementing this proposal?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant