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: Add output to file option #221

Merged
merged 8 commits into from
Jan 19, 2023
Merged
Show file tree
Hide file tree
Changes from 6 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
63 changes: 63 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ chrono = "0.4"
parse_duration = "2.1.1"
atty = "0.2"
base64 = "0.21.0"
tempdir = "0.3.7"
11 changes: 11 additions & 0 deletions src/cli_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::translators::{PayloadItem, SupportedTypes};
use crate::utils::parse_duration_string;
use clap::{Parser, Subcommand, ValueEnum};
use jsonwebtoken::Algorithm;
use std::path::PathBuf;

#[derive(Parser, Debug)]
#[clap(name = "jwt")]
Expand Down Expand Up @@ -94,6 +95,11 @@ pub struct EncodeArgs {
#[clap(long, short = 'S')]
#[clap(value_parser)]
pub secret: String,

/// The path of the file to write the result to (suppresses default standard output)
#[clap(long = "out", short = 'o')]
#[clap(value_parser)]
pub output_path: Option<PathBuf>,
}

#[derive(Debug, Clone, Parser)]
Expand Down Expand Up @@ -130,6 +136,11 @@ pub struct DecodeArgs {
#[clap(long = "ignore-exp")]
#[clap(value_parser)]
pub ignore_exp: bool,

/// The path of the file to write the result to (suppresses default standard output, implies JSON format)
#[clap(long = "out", short = 'o')]
#[clap(value_parser)]
pub output_path: Option<PathBuf>,
}

#[allow(clippy::upper_case_acronyms)]
Expand Down
6 changes: 4 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ fn main() {
warn_unsupported(arguments);

let token = encode_token(arguments);
let output_path = &arguments.output_path;

print_encoded_token(token);
print_encoded_token(token, output_path);
}
Commands::Decode(arguments) => {
let (validated_token, token_data, format) = decode_token(arguments);
let output_path = &arguments.output_path;

print_decoded_token(validated_token, token_data, format);
print_decoded_token(validated_token, token_data, format, output_path);
}
}
}
19 changes: 13 additions & 6 deletions src/translators/decode.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::cli_config::{translate_algorithm, DecodeArgs};
use crate::translators::Payload;
use crate::utils::slurp_file;
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};
Expand All @@ -9,6 +9,7 @@ use serde_derive::{Deserialize, Serialize};
use serde_json::to_string_pretty;
use std::collections::HashSet;
use std::io;
use std::path::PathBuf;
use std::process::exit;

#[derive(Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -147,6 +148,7 @@ pub fn print_decoded_token(
validated_token: JWTResult<TokenData<Payload>>,
token_data: JWTResult<TokenData<Payload>>,
format: OutputFormat,
output_path: &Option<PathBuf>,
) {
if let Err(err) = &validated_token {
match err.kind() {
Expand Down Expand Up @@ -195,17 +197,22 @@ pub fn print_decoded_token(
};
}

match (format, token_data) {
(OutputFormat::Json, Ok(token)) => {
println!("{}", to_string_pretty(&TokenOutput::new(token)).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());
}
(_, Ok(token)) => {
(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(_)) => exit(1),
(_, _, Err(_)) => exit(1),
}

exit(match validated_token {
Expand Down
17 changes: 11 additions & 6 deletions src/translators/encode.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::cli_config::{translate_algorithm, EncodeArgs};
use crate::translators::{Payload, PayloadItem};
use crate::utils::slurp_file;
use crate::utils::{slurp_file, write_file};
use atty::Stream;
use base64::engine::general_purpose::STANDARD as base64_engine;
use base64::Engine as _;
Expand All @@ -9,6 +9,7 @@ use jsonwebtoken::errors::Result as JWTResult;
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
use serde_json::{from_str, Value};
use std::io;
use std::path::PathBuf;
use std::process::exit;

fn create_header(alg: Algorithm, kid: Option<&String>) -> Header {
Expand Down Expand Up @@ -113,17 +114,21 @@ pub fn encode_token(arguments: &EncodeArgs) -> JWTResult<String> {
.and_then(|secret| encode(&header, &claims, &secret))
}

pub fn print_encoded_token(token: JWTResult<String>) {
match token {
Ok(jwt) => {
pub fn print_encoded_token(token: JWTResult<String>, output_path: &Option<PathBuf>) {
match (output_path.as_ref(), token) {
(Some(path), Ok(jwt)) => {
write_file(path, jwt.as_bytes());
println!("Wrote jwt to file {}", path.display());
}
(None, Ok(jwt)) => {
if atty::is(Stream::Stdout) {
println!("{}", jwt);
} else {
print!("{}", jwt);
}
};
exit(0);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this exit be removed now as well?

}
Err(err) => {
(_, Err(err)) => {
bunt::eprintln!("{$red+bold}Something went awry creating the jwt{/$}\n");
eprintln!("{}", err);
exit(1);
Expand Down
5 changes: 5 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
use std::fs;
use std::path::Path;

pub fn slurp_file(file_name: &str) -> Vec<u8> {
fs::read(file_name).unwrap_or_else(|_| panic!("Unable to read file {}", file_name))
}

pub fn write_file(path: &Path, content: &[u8]) {
fs::write(path, content).unwrap_or_else(|_| panic!("Unable to write file {}", path.display()))
}

pub fn parse_duration_string(val: &str) -> Result<i64, String> {
let mut base_val = val.replace(" ago", "");

Expand Down
73 changes: 72 additions & 1 deletion tests/main_test.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
extern crate tempdir;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason this is still using the old edition imports?

Suggested change
extern crate tempdir;
use tempdir;


include!("../src/main.rs");

#[cfg(test)]
mod tests {
use super::cli_config::{App, DecodeArgs, EncodeArgs};
use super::translators::decode::{decode_token, OutputFormat};
use super::translators::encode::encode_token;
use super::translators::encode::{encode_token, print_encoded_token};
use super::utils::slurp_file;
use chrono::{Duration, TimeZone, Utc};
use clap::{CommandFactory, FromArgMatches};
use jsonwebtoken::{Algorithm, TokenData};
use serde_json::from_value;
use tempdir::TempDir;

#[test]
fn encodes_a_token() {
Expand Down Expand Up @@ -665,4 +669,71 @@ mod tests {
Some(&Utc.timestamp_opt(exp, 0).unwrap().to_rfc3339().into())
);
}

#[test]
fn writes_jwt_to_file() {
let tmp_dir_result = TempDir::new("jwtclitest");
assert!(tmp_dir_result.is_ok());

let tmp_dir = tmp_dir_result.unwrap();
let out_path = tmp_dir.path().join("jwt.out");
println!("Output path: {}", out_path.to_str().unwrap());

let secret = "1234567890";
let kid = "1234";
let exp = (Utc::now() + Duration::minutes(60)).timestamp();
let nbf = Utc::now().timestamp();
let encode_matcher = App::command()
.try_get_matches_from(vec![
"jwt",
"encode",
"-S",
secret,
"-A",
"HS256",
&format!("-e={}", &exp.to_string()),
"-k",
kid,
"-n",
&nbf.to_string(),
"-o",
out_path.to_str().unwrap(),
])
.unwrap();
let encode_matches = encode_matcher.subcommand_matches("encode").unwrap();
let encode_arguments = EncodeArgs::from_arg_matches(encode_matches).unwrap();

let out_path_from_args = &encode_arguments.output_path;
assert!(out_path_from_args.is_some());
assert_eq!(out_path, *out_path_from_args.as_ref().unwrap());

let encoded_token = encode_token(&encode_arguments);
print_encoded_token(encoded_token, out_path_from_args);

let out_content_buf = slurp_file(out_path.to_str().unwrap());
let out_content_str = std::str::from_utf8(&out_content_buf);
assert!(out_content_str.is_ok());
println!("jwt: {}", out_content_str.unwrap());

let decode_matcher = App::command()
.try_get_matches_from(vec![
"jwt",
"decode",
"-S",
secret,
&out_content_str.unwrap(),
])
.unwrap();
let decode_matches = decode_matcher.subcommand_matches("decode").unwrap();
let decode_arguments = DecodeArgs::from_arg_matches(decode_matches).unwrap();
let (decoded_token, _, _) = decode_token(&decode_arguments);

assert!(decoded_token.is_ok());
let TokenData { claims, header } = decoded_token.unwrap();

assert_eq!(header.alg, Algorithm::HS256);
assert_eq!(header.kid, Some(kid.to_string()));
assert_eq!(claims.0["nbf"], nbf);
assert_eq!(claims.0["exp"], exp);
}
}