Skip to content
Open
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
57 changes: 56 additions & 1 deletion Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ members = [
"common/auth",
"common/db",
"common/infrastructure",
"cli",
"cvss",
"entity",
"migration",
Expand Down Expand Up @@ -172,6 +173,7 @@ trustify-query-derive = {path = "query/query-derive" }
trustify-server = { path = "server", default-features = false }
trustify-test-context = { path = "test-context" }
trustify-ui = { git = "https://github.com/trustification/trustify-ui.git", branch = "publish/main" }
trustify-cli = { path = "cli" }

# These dependencies are active during both the build time and the run time. So they are normal dependencies
# as well as build-dependencies. However, we can't control feature flags for build dependencies the way we do
Expand Down
19 changes: 19 additions & 0 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "trustify-cli"
version.workspace = true
edition.workspace = true
publish.workspace = true
license.workspace = true

[dependencies]
anyhow = { workspace = true }
clap = { workspace = true, features = ["derive"] }
log = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
reqwest = { workspace = true, features = ["native-tls"] }
tokio = { workspace = true, features = ["full"] }
regex = { workspace = true }
base64 = { workspace = true }

directories = "6.0.0"
178 changes: 178 additions & 0 deletions cli/src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
use anyhow::{Result, anyhow};
use base64::{Engine, engine::general_purpose};
use directories::ProjectDirs;
use regex::Regex;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::{fs, io::Write, path::PathBuf, process::ExitCode};
use tokio::time::{Duration, sleep};

#[derive(clap::Parser, Debug, Clone, Eq, PartialEq)]
#[command()]
#[group(id = "login")]
pub struct Login {
#[arg(id = "oidc_client_id", long = "oidc-client-id", default_value = "cli")]
pub oidc_client_id: String,

// If not set, we will try to discover it from trustify_server_url
#[arg(id = "oidc_server_url", long = "oidc-server-url")]
pub oidc_server_url: Option<String>,

// The Trustify root URL
#[arg(
id = "trustify_server_url",
long = "trustify-server-url",
default_value = "http://localhost:8080"
)]
pub trustify_server_url: String,
}

#[derive(clap::Parser, Debug, Clone, Eq, PartialEq)]
#[command()]
#[group(id = "logout")]
pub struct Logout;

#[derive(Debug, Clone, Eq, PartialEq)]
struct Auth {
config_dir: PathBuf,
config_file: PathBuf,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "UPPERCASE")]
struct TrustifyConfig {
oidc_server_url: String,
}

#[derive(Deserialize, Debug)]
struct DeviceCodeResponse {
device_code: String,
user_code: String,
verification_uri: String,
expires_in: u64,
interval: u64,
}

#[derive(Serialize, Deserialize, Debug)]
struct TokenResponse {
access_token: String,
refresh_token: Option<String>,
expires_in: u64,
}

impl Auth {
fn init_default() -> Result<Self> {
let proj_dirs = ProjectDirs::from("org", "guac", "trustify")
.ok_or(anyhow!("Could not determine config directory for this OS"))?;
let config_dir: PathBuf = proj_dirs.config_dir().to_path_buf();

// Ensure directory exists
fs::create_dir_all(&config_dir)?;

// Define JSON file path
let config_file = config_dir.join("config.json");

Ok(Self {
config_dir,
config_file,
})
}

fn save_token_response(self, token_response: &TokenResponse) -> Result<()> {
// Serialize to JSON string
let json = serde_json::to_string_pretty(token_response)?;

// Write JSON to fileProjectDirs
let mut file = fs::File::create(&self.config_file)?;
file.write_all(json.as_bytes())?;

println!("Credentials saved to {:?}", &self.config_file);
Ok(())
}
}

impl Login {
pub async fn run(self) -> Result<ExitCode> {
let client = Client::new();

// Prepare OIDC URLs
let oidc_server_url = if let Some(oidc_server_url) = self.oidc_server_url {
oidc_server_url
} else {
let index_page = client
.get(self.trustify_server_url)
.send()
.await?
.text()
.await?;

let regex = Regex::new(r#"window\._env\s*=\s*"([^"]+)""#)
.map_err(|error| anyhow!(error.to_string()))?;
let env_base64 = regex
.captures(&index_page)
.ok_or(anyhow!("Could not match regex in index.html"))?
.get(1)
.ok_or(anyhow!("Could not extract _env value"))?;

let decoded_bytes = general_purpose::STANDARD.decode(env_base64.as_str())?;
let decoded_str = String::from_utf8(decoded_bytes)?;
let trustify_config: TrustifyConfig = serde_json::from_str(&decoded_str)?;
trustify_config.oidc_server_url
};
println!("oidc_server_url={oidc_server_url}");

// Get device code
let resp = client
.post(format!(
"{}/protocol/openid-connect/auth/device",
oidc_server_url
))
.form(&[
("client_id", self.oidc_client_id.as_str()),
("scope", "openid"),
])
.send()
.await?
.json::<DeviceCodeResponse>()
.await?;

println!(
"Please visit {} and enter code: {}",
resp.verification_uri, resp.user_code
);
println!("Code expires in {} seconds", resp.expires_in);

// Poll token endpoint
loop {
sleep(Duration::from_secs(resp.interval)).await;

let token_resp = client
.post(format!("{}/protocol/openid-connect/token", oidc_server_url))
.form(&[
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
("device_code", resp.device_code.as_str()),
("client_id", self.oidc_client_id.as_str()),
])
.send()
.await?;

if token_resp.status().is_success() {
let token_response = token_resp.json::<TokenResponse>().await?;

match Auth::init_default() {
Ok(auth) => {
auth.save_token_response(&token_response)?;
break Ok(ExitCode::SUCCESS);
}
Err(_) => break Ok(ExitCode::FAILURE),
}
}
}
}
}

impl Logout {
pub async fn run(self) -> Result<ExitCode> {
Ok(ExitCode::SUCCESS)
}
}
33 changes: 33 additions & 0 deletions cli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use anyhow::Result;
use std::process::ExitCode;

use crate::{
auth::{Login, Logout},
scan::Scan,
};

mod auth;
mod scan;

#[derive(clap::Args, Debug)]
pub struct Run {
#[command(subcommand)]
pub(crate) command: Command,
}

#[derive(clap::Subcommand, Debug)]
pub enum Command {
Login(Login),
Logout(Logout),
Scan(Scan),
}

impl Run {
pub async fn run(self) -> Result<ExitCode> {
match self.command {
Command::Login(login) => login.run().await,
Command::Logout(logout) => logout.run().await,
Command::Scan(scan) => scan.run().await,
}
}
}
19 changes: 19 additions & 0 deletions cli/src/scan.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use std::{path::PathBuf, process::ExitCode};

use anyhow::Result;

#[derive(clap::Parser, Debug, Clone, Eq, PartialEq)]
#[command()]
#[group(id = "scan")]
pub struct Scan {
#[arg(id = "input", long = "input")]
pub input: PathBuf,
#[arg(id = "output", long = "output")]
pub output: Option<PathBuf>,
}

impl Scan {
pub async fn run(self) -> Result<ExitCode> {
Ok(ExitCode::SUCCESS)
}
}
1 change: 1 addition & 0 deletions trustd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ trustify-common = { workspace = true }
trustify-db = { workspace = true }
trustify-infrastructure = { workspace = true }
trustify-server = { workspace = true }
trustify-cli = { workspace = true }

anyhow = { workspace = true }
clap = { workspace = true, features = ["derive", "env"] }
Expand Down
3 changes: 3 additions & 0 deletions trustd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub enum Command {
Db(db::Run),
/// Access OpenAPI related information of the API server
Openapi(openapi::Run),
/// CLI terminal tool
Cli(trustify_cli::Run),
}

#[derive(clap::Parser, Debug)]
Expand All @@ -45,6 +47,7 @@ impl Trustd {
Some(Command::Importer(run)) => run.run().await,
Some(Command::Db(run)) => run.run().await,
Some(Command::Openapi(run)) => run.run().await,
Some(Command::Cli(run)) => run.run().await,
None => pm_mode().await,
}
}
Expand Down
Loading