From 4e96a2f77d3824339fcca43e697f6ca30790866f Mon Sep 17 00:00:00 2001 From: Lucas Jenss Date: Sat, 6 Feb 2021 15:38:48 +0100 Subject: [PATCH] Trim potential whitespace around jwt before decoding Given that JWTs are base64 encoded and can thus not have leading or trailing whitespace, it is safe to trim the string before decoding (e.g. the decoder on jwt.io appears to do the same). This is mostly a convenience feature for people using jwt-cli like this: # pbpaste prints the text from the clipboard on macOS pbpaste | jwt decode - When copying from UIs such the Fx developer tools it's not always trivial to copy the value without any whitespace, and this change avoids the extra step of having to remove that whitespace manually. Of course e.g. piping through `xargs` would also be an option, but is, in my opinion, very obscure especially when used in scripts. --- src/main.rs | 5 ++++- tests/jwt-cli.rs | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 85d299b..6d41021 100644 --- a/src/main.rs +++ b/src/main.rs @@ -464,7 +464,10 @@ fn decode_token( buffer }) - .unwrap(); + .unwrap() + .trim() + .to_owned(); + let secret_validator = create_validations(algorithm); ( diff --git a/tests/jwt-cli.rs b/tests/jwt-cli.rs index 2aa3535..3a2f451 100644 --- a/tests/jwt-cli.rs +++ b/tests/jwt-cli.rs @@ -469,6 +469,21 @@ mod tests { assert!(result.is_ok()); } + #[test] + fn decodes_a_token_with_leading_and_trailing_whitespace() { + let matches = config_options() + .get_matches_from_safe(vec![ + "jwt", + "decode", + " eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.SEQijh6tEuOOAAKpHPuKxgFqEvlTNP1jj4FUNoBwXaM ", + ]) + .unwrap(); + let decode_matches = matches.subcommand_matches("decode").unwrap(); + let (result, _, _) = decode_token(&decode_matches); + + assert!(result.is_ok()); + } + #[test] fn encodes_and_decodes_an_rsa_token_using_key_from_file() { let body: String = "{\"field\":\"value\"}".to_string();