From 3b19b7bd1e221bb98352534042728fff35cd5d19 Mon Sep 17 00:00:00 2001 From: augustuswm Date: Thu, 5 Oct 2023 19:06:45 -0500 Subject: [PATCH] Fmt --- .../src/endpoints/login/oauth/device_token.rs | 56 +++++++++++-------- rfd-api/src/endpoints/login/oauth/github.rs | 14 ++--- rfd-api/src/endpoints/login/oauth/mod.rs | 11 ++-- rfd-api/src/mapper/github_username.rs | 13 ++++- rfd-api/src/mapper/mod.rs | 5 +- rfd-cli/src/main.rs | 9 +-- rfd-cli/src/printer/json.rs | 7 ++- rfd-cli/src/printer/mod.rs | 2 +- rfd-cli/src/printer/tab.rs | 52 ++++++++++------- rfd-sdk/src/lib.rs | 51 ++++++++++++++--- 10 files changed, 146 insertions(+), 74 deletions(-) diff --git a/rfd-api/src/endpoints/login/oauth/device_token.rs b/rfd-api/src/endpoints/login/oauth/device_token.rs index 78a3787..d6c43b5 100644 --- a/rfd-api/src/endpoints/login/oauth/device_token.rs +++ b/rfd-api/src/endpoints/login/oauth/device_token.rs @@ -1,6 +1,6 @@ use chrono::{DateTime, Utc}; use dropshot::{endpoint, HttpError, HttpResponseOk, Method, Path, RequestContext, TypedBody}; -use http::{header, Request, Response, StatusCode, HeaderValue}; +use http::{header, HeaderValue, Request, Response, StatusCode}; use hyper::{body::to_bytes, Body}; use oauth2::{basic::BasicTokenType, EmptyExtraTokenFields, StandardTokenResponse, TokenResponse}; use schemars::JsonSchema; @@ -155,14 +155,12 @@ pub async fn exchange_device_token( // We unfortunately can not trust our providers to follow specs and therefore need to do // our own inspection of the response to determine what to do if !parts.status.is_success() { - // If the server returned a non-success status then we are going to trust the server and // report their error back to the client tracing::debug!(provider = ?path.provider, "Received error response from OAuth provider"); Ok(Response::from_parts(parts, body)) } else { - // The server gave us back a non-error response but it still may not be a success. // GitHub for instance does not use a status code for indicating the success or failure // of a call. So instead we try to deserialize the body into an access token, with the @@ -170,15 +168,20 @@ pub async fn exchange_device_token( // an error instead. let bytes = to_bytes(body).await?; - let parsed: Result, serde_json::Error> = serde_json::from_slice(&bytes); + let parsed: Result< + StandardTokenResponse, + serde_json::Error, + > = serde_json::from_slice(&bytes); match parsed { Ok(parsed) => { let info = provider - .get_user_info(provider.client(), parsed.access_token().secret()) - .await - .map_err(LoginError::UserInfo) - .tap_err(|err| tracing::error!(?err, "Failed to look up user information"))?; + .get_user_info(provider.client(), parsed.access_token().secret()) + .await + .map_err(LoginError::UserInfo) + .tap_err(|err| { + tracing::error!(?err, "Failed to look up user information") + })?; tracing::debug!("Verified and validated OAuth user"); @@ -223,45 +226,52 @@ pub async fn exchange_device_token( .unwrap() .into(), )?) - }, + } Err(_) => { - // Do not log the error here as we want to ensure we do not leak token information - tracing::debug!("Failed to parse a success response from the remote token endpoint"); + tracing::debug!( + "Failed to parse a success response from the remote token endpoint" + ); // Try to deserialize the body again, but this time as an error - let mut error_response = match serde_json::from_slice::(&bytes) { + let mut error_response = match serde_json::from_slice::(&bytes) + { Ok(error) => { - // We found an error in the message body. This is not ideal, but we at // least can understand what the server was trying to tell us tracing::debug!(?error, provider = ?path.provider, "Parsed error response from OAuth provider"); Response::from_parts(parts, Body::from(bytes)) } Err(_) => { - // We still do not know what the remote server is doing... and need to // cancel the request ourselves - tracing::warn!("Remote OAuth provide returned a response that we do not undestand"); - - Response::new(Body::from(serde_json::to_string(&ProxyTokenError { - error: "access_denied".to_string(), - error_description: Some(format!("{} returned a malformed response", path.provider)), - error_uri: None, - }).unwrap())) + tracing::warn!( + "Remote OAuth provide returned a response that we do not undestand" + ); + + Response::new(Body::from( + serde_json::to_string(&ProxyTokenError { + error: "access_denied".to_string(), + error_description: Some(format!( + "{} returned a malformed response", + path.provider + )), + error_uri: None, + }) + .unwrap(), + )) } }; *error_response.status_mut() = StatusCode::BAD_REQUEST; error_response.headers_mut().insert( header::CONTENT_TYPE, - HeaderValue::from_static("application/json") + HeaderValue::from_static("application/json"), ); Ok(error_response) } } - } } else { tracing::info!(provider = ?path.provider, "Found an OAuth provider, but it is not configured properly"); diff --git a/rfd-api/src/endpoints/login/oauth/github.rs b/rfd-api/src/endpoints/login/oauth/github.rs index 5924260..e441de4 100644 --- a/rfd-api/src/endpoints/login/oauth/github.rs +++ b/rfd-api/src/endpoints/login/oauth/github.rs @@ -1,13 +1,16 @@ use std::fmt; -use http::{HeaderMap, header::USER_AGENT, HeaderValue}; +use http::{header::USER_AGENT, HeaderMap, HeaderValue}; use hyper::body::Bytes; use reqwest::Client; use serde::Deserialize; use crate::endpoints::login::{ExternalUserId, UserInfo, UserInfoError}; -use super::{ClientType, ExtractUserInfo, OAuthProvider, OAuthProviderName, OAuthPublicCredentials, OAuthPrivateCredentials}; +use super::{ + ClientType, ExtractUserInfo, OAuthPrivateCredentials, OAuthProvider, OAuthProviderName, + OAuthPublicCredentials, +}; pub struct GitHubOAuthProvider { // public: GitHubPublicProvider, @@ -34,10 +37,7 @@ impl GitHubOAuthProvider { ) -> Self { let mut headers = HeaderMap::new(); headers.insert(USER_AGENT, HeaderValue::from_static("rfd-api")); - let client = Client::builder() - .default_headers(headers) - .build() - .unwrap(); + let client = Client::builder().default_headers(headers).build().unwrap(); Self { device_public: OAuthPublicCredentials { @@ -87,7 +87,7 @@ impl ExtractUserInfo for GitHubOAuthProvider { Ok(UserInfo { external_id: ExternalUserId::GitHub(user.id.to_string()), verified_emails, - github_username: Some(user.login) + github_username: Some(user.login), }) } } diff --git a/rfd-api/src/endpoints/login/oauth/mod.rs b/rfd-api/src/endpoints/login/oauth/mod.rs index 245f3c2..017adb2 100644 --- a/rfd-api/src/endpoints/login/oauth/mod.rs +++ b/rfd-api/src/endpoints/login/oauth/mod.rs @@ -1,10 +1,7 @@ use async_trait::async_trait; use dropshot::Method; use http::header; -use hyper::{ - body::Bytes, - Body -}; +use hyper::{body::Bytes, Body}; use oauth2::{basic::BasicClient, url::ParseError, AuthUrl, ClientId, ClientSecret, TokenUrl}; use rfd_model::OAuthClient; use schemars::JsonSchema; @@ -104,14 +101,14 @@ where &self, client: &reqwest::Client, token: &str, - ) -> Result - { + ) -> Result { tracing::trace!("Requesting user information from OAuth provider"); let mut responses = vec![]; for endpoint in self.user_info_endpoints() { - let request = client.request(Method::GET, endpoint) + let request = client + .request(Method::GET, endpoint) .header(header::AUTHORIZATION, format!("Bearer {}", token)) .body(Body::empty()) .build()?; diff --git a/rfd-api/src/mapper/github_username.rs b/rfd-api/src/mapper/github_username.rs index 6371428..1a1682b 100644 --- a/rfd-api/src/mapper/github_username.rs +++ b/rfd-api/src/mapper/github_username.rs @@ -25,7 +25,11 @@ impl MapperRule for GitHubUsernameMapper { _ctx: &ApiContext, user: &UserInfo, ) -> Result { - if user.github_username.as_ref().map(|u| u == &self.github_username).unwrap_or(false) + if user + .github_username + .as_ref() + .map(|u| u == &self.github_username) + .unwrap_or(false) { Ok(self.permissions.clone()) } else { @@ -38,7 +42,12 @@ impl MapperRule for GitHubUsernameMapper { ctx: &ApiContext, user: &UserInfo, ) -> Result, StoreError> { - if user.github_username.as_ref().map(|u| u == &self.github_username).unwrap_or(false) { + if user + .github_username + .as_ref() + .map(|u| u == &self.github_username) + .unwrap_or(false) + { let groups = ctx .get_groups() .await? diff --git a/rfd-api/src/mapper/mod.rs b/rfd-api/src/mapper/mod.rs index 7700253..657feda 100644 --- a/rfd-api/src/mapper/mod.rs +++ b/rfd-api/src/mapper/mod.rs @@ -8,7 +8,10 @@ use uuid::Uuid; use crate::{context::ApiContext, endpoints::login::UserInfo, ApiPermissions}; -use self::{email_address::EmailAddressMapper, email_domain::EmailDomainMapper, github_username::GitHubUsernameMapper}; +use self::{ + email_address::EmailAddressMapper, email_domain::EmailDomainMapper, + github_username::GitHubUsernameMapper, +}; pub mod email_address; pub mod email_domain; diff --git a/rfd-cli/src/main.rs b/rfd-cli/src/main.rs index 642fca7..f97231d 100644 --- a/rfd-cli/src/main.rs +++ b/rfd-cli/src/main.rs @@ -3,7 +3,7 @@ use anyhow::{anyhow, Result}; use clap::{Arg, ArgAction, Command, CommandFactory, FromArgMatches}; use generated::cli::*; -use printer::{RfdTabPrinter, Printer, RfdJsonPrinter}; +use printer::{Printer, RfdJsonPrinter, RfdTabPrinter}; use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION}; use rfd_sdk::Client; use std::time::Duration; @@ -168,7 +168,8 @@ async fn main() -> Result<(), Box> { } let mut cmd = root.cmd("rfd"); - cmd = cmd.bin_name("rfd") + cmd = cmd + .bin_name("rfd") .arg( Arg::new("debug") .long("debug") @@ -185,7 +186,7 @@ async fn main() -> Result<(), Box> { .global(true) .value_parser(["json", "tab"]) .default_value("json") - .action(ArgAction::Set) + .action(ArgAction::Set), ); cmd = cmd.subcommand(cmd::config::ConfigCmd::command()); @@ -203,7 +204,7 @@ async fn main() -> Result<(), Box> { let printer = match format.as_str() { "json" => Printer::Json(RfdJsonPrinter), "tab" => Printer::Tab(RfdTabPrinter), - other => panic!("Unknown format {}", other) + other => panic!("Unknown format {}", other), }; let mut node = &root; diff --git a/rfd-cli/src/printer/json.rs b/rfd-cli/src/printer/json.rs index 962208e..b9f5f2a 100644 --- a/rfd-cli/src/printer/json.rs +++ b/rfd-cli/src/printer/json.rs @@ -5,7 +5,10 @@ use crate::generated::cli::CliOutput; pub struct RfdJsonPrinter; -fn print_cli_output(response: &Result>) where T: Serialize { +fn print_cli_output(response: &Result>) +where + T: Serialize, +{ match response { Ok(res) => println!("{}", serde_json::to_string(&res).unwrap()), Err(err) => eprintln!("{}", err), @@ -225,4 +228,4 @@ impl CliOutput for RfdJsonPrinter { ) { print_cli_output(&response) } -} \ No newline at end of file +} diff --git a/rfd-cli/src/printer/mod.rs b/rfd-cli/src/printer/mod.rs index bfc7d41..01f40cf 100644 --- a/rfd-cli/src/printer/mod.rs +++ b/rfd-cli/src/printer/mod.rs @@ -321,4 +321,4 @@ impl CliOutput for Printer { Printer::Tab(printer) => printer.output_get_self(response), } } -} \ No newline at end of file +} diff --git a/rfd-cli/src/printer/tab.rs b/rfd-cli/src/printer/tab.rs index 8b41b3a..43dc013 100644 --- a/rfd-cli/src/printer/tab.rs +++ b/rfd-cli/src/printer/tab.rs @@ -1,5 +1,5 @@ -use itertools::{Itertools, EitherOrBoth}; -use rfd_sdk::types::{Error, ListRfd, ApiUserForApiPermission, AccessGroupForApiPermission}; +use itertools::{EitherOrBoth, Itertools}; +use rfd_sdk::types::{AccessGroupForApiPermission, ApiUserForApiPermission, Error, ListRfd}; use std::{fs::File, io::Write, process::Command}; use tabwriter::TabWriter; @@ -118,7 +118,7 @@ impl CliOutput for RfdTabPrinter { ) { match response { Ok(user) => print_user(&user), - Err(err) => print_error(err) + Err(err) => print_error(err), } } @@ -128,7 +128,7 @@ impl CliOutput for RfdTabPrinter { ) { match response { Ok(user) => print_user(&user), - Err(err) => print_error(err) + Err(err) => print_error(err), } } @@ -141,7 +141,7 @@ impl CliOutput for RfdTabPrinter { ) { match response { Ok(groups) => print_groups(&groups), - Err(err) => print_error(err) + Err(err) => print_error(err), } } } @@ -239,9 +239,17 @@ fn print_user(user: &ApiUserForApiPermission) { &mut tw, "{}{}\t{}\t{}", TEXT_COLOR, - if i == 0 { user.id.to_string() } else { String::new() }, + if i == 0 { + user.id.to_string() + } else { + String::new() + }, inner, - if i == 0 { user.created_at.to_string() } else { String::new() }, + if i == 0 { + user.created_at.to_string() + } else { + String::new() + }, ); } @@ -254,16 +262,8 @@ fn print_user(user: &ApiUserForApiPermission) { fn print_groups(groups: &Vec) { let mut tw = TabWriter::new(vec![]).ansi(true); - writeln!( - &mut tw, - "{}Id\tName\tPermissions\tCreated At", - HEADER_COLOR - ); - writeln!( - &mut tw, - "{}--\t----\t-----------\t----------", - HEADER_COLOR - ); + writeln!(&mut tw, "{}Id\tName\tPermissions\tCreated At", HEADER_COLOR); + writeln!(&mut tw, "{}--\t----\t-----------\t----------", HEADER_COLOR); for group in groups { for (i, permission) in group.permissions.iter().enumerate() { @@ -271,10 +271,22 @@ fn print_groups(groups: &Vec) { &mut tw, "{}{}\t{}\t{}\t{}", TEXT_COLOR, - if i == 0 { group.id.to_string() } else { String::new() }, - if i == 0 { group.name.to_string() } else { String::new() }, + if i == 0 { + group.id.to_string() + } else { + String::new() + }, + if i == 0 { + group.name.to_string() + } else { + String::new() + }, permission, - if i == 0 { group.created_at.to_string() } else { String::new() }, + if i == 0 { + group.created_at.to_string() + } else { + String::new() + }, ); } } diff --git a/rfd-sdk/src/lib.rs b/rfd-sdk/src/lib.rs index e336754..cb6f0fd 100644 --- a/rfd-sdk/src/lib.rs +++ b/rfd-sdk/src/lib.rs @@ -2,8 +2,8 @@ mod generated; use std::fmt::Display; -pub use generated::sdk::*; use generated::sdk::types::ApiPermission; +pub use generated::sdk::*; pub use progenitor_client::Error as ProgenitorClientError; impl Display for ApiPermission { @@ -37,27 +37,64 @@ impl Display for ApiPermission { Self::RemoveFromGroup(id) => write!(f, "remove-group-membership:{}", id), Self::DeleteGroup(id) => write!(f, "delete-group:{}", id), Self::GetRfd(number) => write!(f, "get-rfd:{}", number), - Self::GetRfds(numbers) => write!(f, "get-rfds:{}", numbers.iter().map(|i| i.to_string()).collect::>().join(",")), + Self::GetRfds(numbers) => write!( + f, + "get-rfds:{}", + numbers + .iter() + .map(|i| i.to_string()) + .collect::>() + .join(",") + ), Self::GetRfdsAssigned => write!(f, "get-rfds-assigned"), Self::GetRfdsAll => write!(f, "get-rfds-all"), Self::GetDiscussion(number) => write!(f, "get-discussion:{}", number), - Self::GetDiscussions(numbers) => write!(f, "get-discussions:{}", numbers.iter().map(|i| i.to_string()).collect::>().join(",")), + Self::GetDiscussions(numbers) => write!( + f, + "get-discussions:{}", + numbers + .iter() + .map(|i| i.to_string()) + .collect::>() + .join(",") + ), Self::GetDiscussionsAssigned => write!(f, "get-discussions-assigned"), Self::GetDiscussionsAll => write!(f, "get-discussions-all"), Self::SearchRfds => write!(f, "search-rfds"), Self::CreateOAuthClient => write!(f, "create-oauth-client"), Self::GetOAuthClient(id) => write!(f, "get-oauth-client:{}", id), - Self::GetOAuthClients(ids) => write!(f, "get-oauth-clients:{}", ids.iter().map(|i| i.to_string()).collect::>().join(",")), + Self::GetOAuthClients(ids) => write!( + f, + "get-oauth-clients:{}", + ids.iter() + .map(|i| i.to_string()) + .collect::>() + .join(",") + ), Self::GetOAuthClientsAssigned => write!(f, "get-oauth-clients-assigned"), Self::GetOAuthClientsAll => write!(f, "get-oauth-clients-all"), Self::UpdateOAuthClient(id) => write!(f, "update-oauth-client:{}", id), - Self::UpdateOAuthClients(ids) => write!(f, "update-oauth-clients:{}", ids.iter().map(|i| i.to_string()).collect::>().join(",")), + Self::UpdateOAuthClients(ids) => write!( + f, + "update-oauth-clients:{}", + ids.iter() + .map(|i| i.to_string()) + .collect::>() + .join(",") + ), Self::UpdateOAuthClientsAssigned => write!(f, "update-oauth-clients-assigned"), Self::UpdateOAuthClientsAll => write!(f, "update-oauth-clients-all"), Self::DeleteOAuthClient(id) => write!(f, "delete-oauth-client:{}", id), - Self::DeleteOAuthClients(ids) => write!(f, "delete-oauth-clients:{}", ids.iter().map(|i| i.to_string()).collect::>().join(",")), + Self::DeleteOAuthClients(ids) => write!( + f, + "delete-oauth-clients:{}", + ids.iter() + .map(|i| i.to_string()) + .collect::>() + .join(",") + ), Self::DeleteOAuthClientsAssigned => write!(f, "delete-oauth-clients-assigned"), Self::DeleteOAuthClientsAll => write!(f, "delete-oauth-clients-self"), } } -} \ No newline at end of file +}