Skip to content

Commit

Permalink
Locksmith token CHANGELOG entry and cleanup (#1175)
Browse files Browse the repository at this point in the history
  • Loading branch information
kylewillmon authored Aug 8, 2023
1 parent 63141f6 commit 040778f
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 28 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).

### Changed
- Include lockfile paths when analyzing projects
- Generate and use API Keys instead of OpenID Connect tokens

### Fixed
- Search for manifests' lockfiles in parent, rather than child directories
Expand Down
9 changes: 4 additions & 5 deletions cli/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::api::endpoints::BaseUriError;
use crate::app::USER_AGENT;
use crate::auth::jwt::RealmRole;
use crate::auth::{
fetch_locksmith_server_settings, handle_auth_flow, handle_refresh_tokens, jwt, AuthAction,
fetch_locksmith_server_settings, handle_auth_flow, jwt, renew_access_token, AuthAction,
UserInfo,
};
use crate::config::{AuthInfo, Config};
Expand Down Expand Up @@ -176,10 +176,9 @@ impl PhylumApi {
},
};

let access_token =
handle_refresh_tokens(&refresh_token, ignore_certs, &config.connection.uri)
.await
.context("Token refresh failed")?;
let access_token = renew_access_token(&refresh_token, ignore_certs, &config.connection.uri)
.await
.context("Token refresh failed")?;

let mut headers = HeaderMap::new();
// the cli runs a command or a few short commands then exits, so we do
Expand Down
4 changes: 2 additions & 2 deletions cli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ pub fn add_subcommands(command: Command) -> Command {
.action(ArgAction::Set)
.short('n')
.long("token-name")
.help("API token name"),
.help("Unique name for the new token that will be created"),
),
)
.subcommand(
Expand All @@ -212,7 +212,7 @@ pub fn add_subcommands(command: Command) -> Command {
.action(ArgAction::Set)
.short('n')
.long("token-name")
.help("API token name"),
.help("Unique name for the new token that will be created"),
),
)
.subcommand(
Expand Down
33 changes: 26 additions & 7 deletions cli/src/auth/oidc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ fn build_grant_type_auth_code_post_body(
token_name: Option<String>,
) -> Result<HashMap<String, String>> {
let body = hashmap! {
"client_id".to_owned() => LOCKSMITH_CLIENT_ID.to_owned(),
"client_id".to_owned() => Default::default(),
"code".to_owned() => authorization_code.into(),
"code_verifier".to_owned() => code_verfier.into(),
"grant_type".to_owned() => "authorization_code".to_owned(),
Expand Down Expand Up @@ -317,7 +317,8 @@ pub async fn refresh_tokens(
}
}

pub async fn handle_refresh_tokens(
/// Get a new access token using the refresh token.
pub async fn renew_access_token(
refresh_token: &RefreshToken,
ignore_certs: bool,
api_uri: &str,
Expand All @@ -342,16 +343,34 @@ pub struct LocksmithTokenResponse {
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct UserInfo {
pub email: String,
pub sub: Option<String>,
pub name: Option<String>,
pub given_name: Option<String>,
pub family_name: Option<String>,
pub preferred_username: Option<String>,
pub email_verified: Option<bool>,
}

impl UserInfo {
pub fn identity(&self) -> String {
match &self.name {
Some(name) => format!("{} <{}>", name, self.email),
None => format!("<{}>", self.email),
}
}
}

/// Keycloak error response.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ResponseError {
error: String,
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn user_info_identity() {
let named = UserInfo { email: "[email protected]".into(), name: Some("John Doe".into()) };
assert_eq!(named.identity(), "John Doe <[email protected]>");

let nameless = UserInfo { email: "[email protected]".into(), name: None };
assert_eq!(nameless.identity(), "<[email protected]>");
}
}
15 changes: 4 additions & 11 deletions cli/src/commands/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::path::Path;

use anyhow::{anyhow, Context, Result};
use clap::ArgMatches;
use log::debug;
use phylum_types::types::auth::RefreshToken;
use tokio::io::{self, AsyncBufReadExt, BufReader};

Expand Down Expand Up @@ -69,18 +68,12 @@ pub async fn handle_auth_status(config: Config, timeout: Option<u64>) -> Command

let user_info = api.user_info().await;

debug!("User info reponse: {:?}", user_info);

match user_info {
Ok(user) => {
print_user_success!(
"Currently authenticated as '{}<{}>' via {}",
user.name.map_or_else(Default::default, |mut n| {
n.push(' ');
n
}),
user.email,
auth_type,
"Currently authenticated as '{}' via {}",
user.identity(),
auth_type
);
Ok(ExitCode::Ok)
},
Expand All @@ -106,7 +99,7 @@ pub async fn handle_auth_token(config: &Config, matches: &clap::ArgMatches) -> C
if matches.get_flag("bearer") {
let api_uri = &config.connection.uri;
let access_token =
auth::handle_refresh_tokens(refresh_token, config.ignore_certs(), api_uri).await?;
auth::renew_access_token(refresh_token, config.ignore_certs(), api_uri).await?;
println!("{}", access_token);
Ok(ExitCode::Ok)
} else {
Expand Down
2 changes: 1 addition & 1 deletion cli/src/commands/extensions/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ async fn get_access_token(
let config = api.config();

let access_token =
crate::auth::handle_refresh_tokens(&refresh_token, ignore_certs, &config.connection.uri)
crate::auth::renew_access_token(&refresh_token, ignore_certs, &config.connection.uri)
.await?;
Ok(access_token)
}
Expand Down
2 changes: 1 addition & 1 deletion docs/command_line_tool/phylum_auth_login.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Usage: phylum auth login [OPTIONS]
&emsp; Force a login prompt

-n, --token-name
&emsp; API token name
&emsp; Unique name for the new token that will be created

-v, --verbose...
&emsp; Increase the level of verbosity (the maximum is -vvv)
Expand Down
2 changes: 1 addition & 1 deletion docs/command_line_tool/phylum_auth_register.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Usage: phylum auth register [OPTIONS]
### Options

-n, --token-name
&emsp; API token name
&emsp; Unique name for the new token that will be created

-v, --verbose...
&emsp; Increase the level of verbosity (the maximum is -vvv)
Expand Down

0 comments on commit 040778f

Please sign in to comment.