forked from mike-engel/jwt-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecode.rs
219 lines (199 loc) · 7.61 KB
/
decode.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
use crate::cli_config::{translate_algorithm, DecodeArgs};
use crate::translators::Payload;
use crate::utils::{slurp_file, write_file};
use base64::engine::general_purpose::STANDARD as base64_engine;
use base64::Engine as _;
use jsonwebtoken::errors::{ErrorKind, Result as JWTResult};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Header, TokenData, Validation};
use serde_derive::{Deserialize, Serialize};
use serde_json::to_string_pretty;
use std::collections::HashSet;
use std::io;
use std::path::PathBuf;
#[derive(Debug, PartialEq, Eq)]
pub enum OutputFormat {
Text,
Json,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct TokenOutput {
pub header: Header,
pub payload: Payload,
}
impl TokenOutput {
fn new(data: TokenData<Payload>) -> Self {
TokenOutput {
header: data.header,
payload: data.claims,
}
}
}
pub fn decoding_key_from_secret(alg: &Algorithm, secret_string: &str) -> JWTResult<DecodingKey> {
match alg {
Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
if secret_string.starts_with('@') {
let secret = slurp_file(&secret_string.chars().skip(1).collect::<String>());
Ok(DecodingKey::from_secret(&secret))
} else if secret_string.starts_with("b64:") {
Ok(DecodingKey::from_secret(
&base64_engine
.decode(secret_string.chars().skip(4).collect::<String>())
.unwrap(),
))
} else {
Ok(DecodingKey::from_secret(secret_string.as_bytes()))
}
}
Algorithm::RS256
| Algorithm::RS384
| Algorithm::RS512
| Algorithm::PS256
| Algorithm::PS384
| Algorithm::PS512 => {
let secret = slurp_file(&secret_string.chars().skip(1).collect::<String>());
match secret_string.ends_with(".pem") {
true => DecodingKey::from_rsa_pem(&secret),
false => Ok(DecodingKey::from_rsa_der(&secret)),
}
}
Algorithm::ES256 | Algorithm::ES384 => {
let secret = slurp_file(&secret_string.chars().skip(1).collect::<String>());
match secret_string.ends_with(".pem") {
true => DecodingKey::from_ec_pem(&secret),
false => Ok(DecodingKey::from_ec_der(&secret)),
}
}
Algorithm::EdDSA => {
panic!("EdDSA is not implemented yet!");
}
}
}
pub fn decode_token(
arguments: &DecodeArgs,
) -> (
JWTResult<TokenData<Payload>>,
JWTResult<TokenData<Payload>>,
OutputFormat,
) {
let algorithm = translate_algorithm(&arguments.algorithm);
let secret = match arguments.secret.len() {
0 => None,
_ => Some(decoding_key_from_secret(&algorithm, &arguments.secret)),
};
let jwt = match arguments.jwt.as_str() {
"-" => {
let mut buffer = String::new();
io::stdin()
.read_line(&mut buffer)
.expect("STDIN was not valid UTF-8");
buffer
}
_ => arguments.jwt.clone(),
}
.trim()
.to_owned();
let mut secret_validator = Validation::new(algorithm);
secret_validator.leeway = 1000;
if arguments.ignore_exp {
secret_validator
.required_spec_claims
.retain(|claim| claim != "exp");
secret_validator.validate_exp = false;
}
let mut insecure_validator = secret_validator.clone();
let insecure_decoding_key = DecodingKey::from_secret("".as_ref());
insecure_validator.insecure_disable_signature_validation();
insecure_validator.required_spec_claims = HashSet::new();
insecure_validator.validate_exp = false;
let token_data =
decode::<Payload>(&jwt, &insecure_decoding_key, &insecure_validator).map(|mut token| {
if arguments.iso_dates {
token.claims.convert_timestamps();
}
token
});
(
match secret {
Some(secret_key) => decode::<Payload>(&jwt, &secret_key.unwrap(), &secret_validator),
None => decode::<Payload>(&jwt, &insecure_decoding_key, &insecure_validator),
},
token_data,
if arguments.json {
OutputFormat::Json
} else {
OutputFormat::Text
},
)
}
pub fn print_decoded_token(
validated_token: JWTResult<TokenData<Payload>>,
token_data: JWTResult<TokenData<Payload>>,
format: OutputFormat,
output_path: &Option<PathBuf>,
) -> JWTResult<()> {
if let Err(err) = &validated_token {
match err.kind() {
ErrorKind::InvalidToken => {
bunt::println!("{$red+bold}The JWT provided is invalid{/$}")
}
ErrorKind::InvalidSignature => {
bunt::eprintln!("{$red+bold}The JWT provided has an invalid signature{/$}")
}
ErrorKind::InvalidRsaKey(_) => {
bunt::eprintln!("{$red+bold}The secret provided isn't a valid RSA key{/$}")
}
ErrorKind::InvalidEcdsaKey => {
bunt::eprintln!("{$red+bold}The secret provided isn't a valid ECDSA key{/$}")
}
ErrorKind::MissingRequiredClaim(missing) => {
if missing.as_str() == "exp" {
bunt::eprintln!("{$red+bold}`exp` is missing, but is required. This error can be ignored via the `--ignore-exp` parameter.{/$}")
} else {
bunt::eprintln!("{$red+bold}`{:?}` is missing, but is required{/$}", missing)
}
}
ErrorKind::ExpiredSignature => {
bunt::eprintln!("{$red+bold}The token has expired (or the `exp` claim is not set). This error can be ignored via the `--ignore-exp` parameter.{/$}")
}
ErrorKind::InvalidIssuer => {
bunt::println!("{$red+bold}The token issuer is invalid{/$}")
}
ErrorKind::InvalidAudience => {
bunt::eprintln!("{$red+bold}The token audience doesn't match the subject{/$}")
}
ErrorKind::InvalidSubject => {
bunt::eprintln!("{$red+bold}The token subject doesn't match the audience{/$}")
}
ErrorKind::ImmatureSignature => bunt::eprintln!(
"{$red+bold}The `nbf` claim is in the future which isn't allowed{/$}"
),
ErrorKind::InvalidAlgorithm => bunt::eprintln!(
"{$red+bold}The JWT provided has a different signing algorithm than the one you \
provided{/$}",
),
_ => bunt::eprintln!(
"{$red+bold}The JWT provided is invalid because{/$} {:?}",
err
),
};
return Err(validated_token.err().unwrap());
}
match (output_path.as_ref(), format, token_data) {
(Some(path), _, Ok(token)) => {
let json = to_string_pretty(&TokenOutput::new(token)).unwrap();
write_file(path, json.as_bytes());
println!("Wrote jwt to file {}", path.display());
}
(None, OutputFormat::Json, Ok(token)) => {
println!("{}", to_string_pretty(&TokenOutput::new(token)).unwrap());
}
(None, _, Ok(token)) => {
bunt::println!("\n{$bold}Token header\n------------{/$}");
println!("{}\n", to_string_pretty(&token.header).unwrap());
bunt::println!("{$bold}Token claims\n------------{/$}");
println!("{}", to_string_pretty(&token.claims).unwrap());
}
(_, _, Err(err)) => return Err(err),
}
Ok(())
}