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

feat(output): Output as JSON for consumption with jq #6

Merged
merged 1 commit into from
Sep 25, 2018
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 58 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,27 @@ extern crate term_painter;

use chrono::{Duration, Utc};
use clap::{App, Arg, ArgMatches, SubCommand};
use jwt::{dangerous_unsafe_decode, decode, encode, Algorithm, Header, TokenData, Validation};
use jwt::errors::{Error, ErrorKind, Result as JWTResult};
use jwt::{dangerous_unsafe_decode, decode, encode, Algorithm, Header, TokenData, Validation};
use serde_json::{from_str, to_string_pretty, Value};
use std::collections::BTreeMap;
use std::process::exit;
use term_painter::ToStyle;
use term_painter::Color::*;
use term_painter::Attr::*;
use term_painter::Color::*;
use term_painter::ToStyle;

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct PayloadItem(String, Value);

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Payload(BTreeMap<String, Value>);

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct TokenOutput {
header: Header,
payload: Payload,
}

arg_enum!{
#[derive(Debug, PartialEq)]
enum SupportedAlgorithms {
Expand All @@ -44,6 +50,12 @@ arg_enum!{
}
}

#[derive(Debug, PartialEq)]
enum OutputFormat {
Text,
JSON,
}

impl PayloadItem {
fn from_string(val: Option<&str>) -> Option<PayloadItem> {
if val.is_some() {
Expand Down Expand Up @@ -109,6 +121,15 @@ impl SupportedAlgorithms {
}
}

impl TokenOutput {
fn new(data: TokenData<Payload>) -> Self {
TokenOutput {
header: data.header,
payload: data.claims,
}
}
}

fn config_options<'a, 'b>() -> App<'a, 'b> {
App::new("jwt")
.about("Encode and decode JWTs from the command line")
Expand Down Expand Up @@ -230,6 +251,12 @@ fn config_options<'a, 'b>() -> App<'a, 'b> {
.long("secret")
.short("S")
.default_value(""),
)
.arg(
Arg::with_name("json")
.help("render decoded JWT as JSON")
.long("json")
.short("j"),
),
)
}
Expand Down Expand Up @@ -321,7 +348,13 @@ fn encode_token(matches: &ArgMatches) -> JWTResult<String> {
encode(&header, &claims, secret.as_ref())
}

fn decode_token(matches: &ArgMatches) -> (JWTResult<TokenData<Payload>>, TokenData<Payload>) {
fn decode_token(
matches: &ArgMatches,
) -> (
JWTResult<TokenData<Payload>>,
TokenData<Payload>,
OutputFormat,
) {
let algorithm = translate_algorithm(SupportedAlgorithms::from_string(
matches.value_of("algorithm").unwrap(),
));
Expand All @@ -336,6 +369,11 @@ fn decode_token(matches: &ArgMatches) -> (JWTResult<TokenData<Payload>>, TokenDa
dangerous_unsafe_decode::<Payload>(&jwt)
},
dangerous_unsafe_decode::<Payload>(&jwt).unwrap(),
if matches.is_present("json") {
OutputFormat::JSON
} else {
OutputFormat::Text
},
)
}

Expand All @@ -359,9 +397,8 @@ fn print_encoded_token(token: JWTResult<String>) {
fn print_decoded_token(
validated_token: JWTResult<TokenData<Payload>>,
token_data: TokenData<Payload>,
format: OutputFormat,
) {
println!("\n");

match &validated_token {
&Err(Error(ref err, _)) => {
match err {
Expand Down Expand Up @@ -418,13 +455,21 @@ fn print_decoded_token(
),
};
}
_ => println!("{}", Cyan.bold().paint("Looks like a valid JWT!")),
_ => {}
}

println!("\n{}", Plain.bold().paint("Token header\n------------"));
println!("{}\n", to_string_pretty(&token_data.header).unwrap());
println!("{}", Plain.bold().paint("Token claims\n------------"));
println!("{}", to_string_pretty(&token_data.claims).unwrap());
match format {
OutputFormat::JSON => println!(
"{}",
to_string_pretty(&TokenOutput::new(token_data)).unwrap()
),
_ => {
println!("\n{}", Plain.bold().paint("Token header\n------------"));
println!("{}\n", to_string_pretty(&token_data.header).unwrap());
println!("{}", Plain.bold().paint("Token claims\n------------"));
println!("{}", to_string_pretty(&token_data.claims).unwrap());
}
}

exit(match validated_token {
Err(_) => 1,
Expand All @@ -444,9 +489,9 @@ fn main() {
print_encoded_token(token);
}
("decode", Some(decode_matches)) => {
let (validated_token, token_data) = decode_token(&decode_matches);
let (validated_token, token_data, format) = decode_token(&decode_matches);

print_decoded_token(validated_token, token_data);
print_decoded_token(validated_token, token_data, format);
}
_ => (),
}
Expand Down
39 changes: 29 additions & 10 deletions tests/jwt-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ include!("../src/main.rs");

#[cfg(test)]
mod tests {
use super::{config_options, create_header, decode_token, encode_token, is_num,
is_payload_item, translate_algorithm, Payload, PayloadItem, SupportedAlgorithms};
use super::{
config_options, create_header, decode_token, encode_token, is_num, is_payload_item,
translate_algorithm, OutputFormat, Payload, PayloadItem, SupportedAlgorithms,
};
use chrono::{Duration, Utc};
use jwt::{Algorithm, Header, TokenData};
use serde_json::from_value;
Expand Down Expand Up @@ -213,7 +215,7 @@ mod tests {
.get_matches_from_safe(vec!["jwt", "decode", "-S", "1234567890", &encoded_token])
.unwrap();
let decode_matches = decode_matcher.subcommand_matches("decode").unwrap();
let (decoded_token, _) = decode_token(&decode_matches);
let (decoded_token, _, _) = decode_token(&decode_matches);

assert!(decoded_token.is_ok());

Expand Down Expand Up @@ -244,7 +246,7 @@ mod tests {
.get_matches_from_safe(vec!["jwt", "decode", "-S", "1234567890", &encoded_token])
.unwrap();
let decode_matches = decode_matcher.subcommand_matches("decode").unwrap();
let (decoded_token, _) = decode_token(&decode_matches);
let (decoded_token, _, _) = decode_token(&decode_matches);

assert!(decoded_token.is_ok());

Expand Down Expand Up @@ -277,7 +279,7 @@ mod tests {
.get_matches_from_safe(vec!["jwt", "decode", "-S", "1234567890", &encoded_token])
.unwrap();
let decode_matches = decode_matcher.subcommand_matches("decode").unwrap();
let (decoded_token, _) = decode_token(&decode_matches);
let (decoded_token, _, _) = decode_token(&decode_matches);

assert!(decoded_token.is_ok());

Expand All @@ -302,11 +304,28 @@ mod tests {
])
.unwrap();
let decode_matches = matches.subcommand_matches("decode").unwrap();
let (result, _) = decode_token(&decode_matches);
let (result, _, _) = decode_token(&decode_matches);

assert!(result.is_ok());
}

#[test]
fn decodes_a_token_as_json() {
let matches = config_options()
.get_matches_from_safe(vec![
"jwt",
"decode",
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0aGlzIjoidGhhdCJ9.AdAECLE_4iRa0uomMEdsMV2hDXv1vhLpym567-AzhrM",
"-j",
])
.unwrap();
let decode_matches = matches.subcommand_matches("decode").unwrap();
let (result, _, format) = decode_token(&decode_matches);

assert!(result.is_ok());
assert!(format == OutputFormat::JSON);
}

#[test]
fn decodes_a_token_with_invalid_secret() {
let matches = config_options()
Expand All @@ -321,7 +340,7 @@ mod tests {
])
.unwrap();
let decode_matches = matches.subcommand_matches("decode").unwrap();
let (result, _) = decode_token(&decode_matches);
let (result, _, _) = decode_token(&decode_matches);

assert!(result.is_err());
}
Expand All @@ -338,7 +357,7 @@ mod tests {
])
.unwrap();
let decode_matches = matches.subcommand_matches("decode").unwrap();
let (result, _) = decode_token(&decode_matches);
let (result, _, _) = decode_token(&decode_matches);

assert!(result.is_ok());
}
Expand All @@ -353,7 +372,7 @@ mod tests {
])
.unwrap();
let decode_matches = matches.subcommand_matches("decode").unwrap();
let (result, _) = decode_token(&decode_matches);
let (result, _, _) = decode_token(&decode_matches);

assert!(result.is_ok());
}
Expand All @@ -368,7 +387,7 @@ mod tests {
])
.unwrap();
let decode_matches = matches.subcommand_matches("decode").unwrap();
let (result, _) = decode_token(&decode_matches);
let (result, _, _) = decode_token(&decode_matches);

assert!(result.is_ok());
}
Expand Down