Skip to content

Commit 0341dd8

Browse files
authored
Add phylum firewall log subcommand (#1551)
This patch adds the new `phylum firewall log` to allow checking the Aviary log from the CLI. While the UI gives a more user-friendly overview, this should be complementary by giving access to the data in a structure closer to the original layout. The CLI arguments allow applying most filters exposed by the API, but combine the individual package components into a PURL to avoid an excessive number of arguments. Currently neither the `--json` output nor the pretty-printer have a way to paginate through the logs. While this could be done either automatically or by manually specifying the pagination offset, it seems to me like the limit of 10_000 entries per page should be sufficient for all current usecases. Contrary to our existing timestamp columns, the timestamp in the output table uses nanosecond precision. The additional precision seems worthwhile in this case since this automatically groups versions together if they were submitted for analysis as a batch.
1 parent 715f00b commit 0341dd8

File tree

15 files changed

+427
-15
lines changed

15 files changed

+427
-15
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
1111
### Added
1212

1313
- Support for C#'s `packages.*.config` lockfile type
14+
- `phylum firewall log` command to browse firewall activity log
1415

1516
## 7.1.5 - 2024-11-26
1617

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

cli/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ phylum_lockfile = { path = "../lockfile", features = ["generator"] }
4848
phylum_project = { path = "../phylum_project" }
4949
phylum_types = { git = "https://github.com/phylum-dev/phylum-types", branch = "development" }
5050
prettytable-rs = "0.10.0"
51+
purl = "0.1.1"
5152
rand = "0.8.4"
5253
regex = "1.5.5"
5354
reqwest = { version = "0.12.7", features = ["blocking", "json", "rustls-tls", "rustls-tls-native-roots", "rustls-tls-webpki-roots"], default-features = false }

cli/src/api/endpoints.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,11 @@ pub fn org_groups_delete(
192192
Ok(url)
193193
}
194194

195+
/// Aviary activity endpoint.
196+
pub fn firewall_log(api_uri: &str) -> Result<Url, BaseUriError> {
197+
Ok(get_firewall_path(api_uri)?.join("activity")?)
198+
}
199+
195200
/// GET /.well-known/openid-configuration
196201
pub fn oidc_discovery(api_uri: &str) -> Result<Url, BaseUriError> {
197202
Ok(get_api_path(api_uri)?.join(".well-known/openid-configuration")?)
@@ -242,6 +247,14 @@ fn get_locksmith_path(api_uri: &str) -> Result<Url, BaseUriError> {
242247
Ok(parse_base_url(api_uri)?.join(LOCKSMITH_PATH)?)
243248
}
244249

250+
fn get_firewall_path(api_uri: &str) -> Result<Url, BaseUriError> {
251+
let mut api_path = parse_base_url(api_uri)?;
252+
let host = api_path.host_str().ok_or(ParseError::EmptyHost)?;
253+
let host = host.replacen("api.", "aviary.", 1);
254+
api_path.set_host(Some(&host))?;
255+
Ok(api_path)
256+
}
257+
245258
#[cfg(test)]
246259
mod test {
247260
use super::*;

cli/src/api/mod.rs

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
use std::borrow::Cow;
12
use std::collections::HashSet;
23
use std::time::Duration;
34

45
use anyhow::{anyhow, Context};
6+
use phylum_types::types::auth::AccessToken;
57
use phylum_types::types::common::{JobId, ProjectId};
68
use phylum_types::types::group::{
79
CreateGroupRequest, CreateGroupResponse, ListGroupMembersResponse,
@@ -27,10 +29,11 @@ use crate::auth::{
2729
use crate::config::{AuthInfo, Config};
2830
use crate::types::{
2931
AddOrgUserRequest, AnalysisPackageDescriptor, ApiOrgGroup, CreateProjectRequest,
30-
GetProjectResponse, HistoryJob, ListUserGroupsResponse, OrgGroupsResponse, OrgMembersResponse,
31-
OrgsResponse, PackageSpecifier, PackageSubmitResponse, Paginated, PingResponse,
32-
PolicyEvaluationRequest, PolicyEvaluationResponse, PolicyEvaluationResponseRaw,
33-
ProjectListEntry, RevokeTokenRequest, SubmitPackageRequest, UpdateProjectRequest, UserToken,
32+
FirewallLogFilter, FirewallLogResponse, FirewallPaginated, GetProjectResponse, HistoryJob,
33+
ListUserGroupsResponse, OrgGroupsResponse, OrgMembersResponse, OrgsResponse, PackageSpecifier,
34+
PackageSubmitResponse, Paginated, PingResponse, PolicyEvaluationRequest,
35+
PolicyEvaluationResponse, PolicyEvaluationResponseRaw, ProjectListEntry, RevokeTokenRequest,
36+
SubmitPackageRequest, UpdateProjectRequest, UserToken,
3437
};
3538

3639
pub mod endpoints;
@@ -41,6 +44,7 @@ pub struct PhylumApi {
4144
roles: HashSet<RealmRole>,
4245
config: Config,
4346
client: Client,
47+
access_token: AccessToken,
4448
}
4549

4650
/// Phylum Api Error type
@@ -140,7 +144,7 @@ impl PhylumApi {
140144
// Try to parse token's roles.
141145
let roles = jwt::user_roles(access_token.as_str()).unwrap_or_default();
142146

143-
Ok(Self { config, client, roles })
147+
Ok(Self { config, client, roles, access_token })
144148
}
145149

146150
async fn get<T: DeserializeOwned, U: IntoUrl>(&self, path: U) -> Result<T> {
@@ -562,6 +566,36 @@ impl PhylumApi {
562566
Ok(())
563567
}
564568

569+
/// Get Aviary activity log.
570+
pub async fn firewall_log(
571+
&self,
572+
org: Option<&str>,
573+
group: &str,
574+
filter: FirewallLogFilter<'_>,
575+
) -> Result<FirewallPaginated<FirewallLogResponse>> {
576+
let user = match org {
577+
Some(org) => Cow::Owned(format!("{org}/{group}")),
578+
None => Cow::Borrowed(group),
579+
};
580+
let url = endpoints::firewall_log(&self.config.connection.uri)?;
581+
582+
let request =
583+
self.client.get(url).basic_auth(user, Some(&self.access_token)).query(&filter);
584+
585+
let response = request.send().await?;
586+
let status_code = response.status();
587+
let body = response.text().await?;
588+
589+
if !status_code.is_success() {
590+
let err = ResponseError { details: body, code: status_code };
591+
return Err(err.into());
592+
}
593+
594+
let log = serde_json::from_str(&body).map_err(|e| PhylumApiError::Other(e.into()))?;
595+
596+
Ok(log)
597+
}
598+
565599
/// Get reachable vulnerabilities.
566600
#[cfg(feature = "vulnreach")]
567601
pub async fn vulnerabilities(&self, job: Job) -> Result<Vec<Vulnerability>> {

cli/src/app.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -603,6 +603,61 @@ pub fn add_subcommands(command: Command) -> Command {
603603
.subcommand(
604604
Command::new("unlink").about("Clear the configured default organization"),
605605
),
606+
)
607+
.subcommand(
608+
Command::new("firewall")
609+
.about("Manage the package firewall")
610+
.arg_required_else_help(true)
611+
.subcommand_required(true)
612+
.subcommand(
613+
Command::new("log")
614+
.about("Show firewall activity log")
615+
.args(&[Arg::new("json")
616+
.action(ArgAction::SetTrue)
617+
.short('j')
618+
.long("json")
619+
.help("Produce output in json format (default: false)")])
620+
.args(&[
621+
Arg::new("group")
622+
.value_name("GROUP_NAME")
623+
.help("Specify a group to use for analysis")
624+
.required(true),
625+
Arg::new("ecosystem")
626+
.long("ecosystem")
627+
.value_name("ECOSYSTEM")
628+
.help("Only show logs matching this ecosystem")
629+
.value_parser([
630+
"npm", "rubygems", "pypi", "maven", "nuget", "cargo",
631+
]),
632+
Arg::new("package")
633+
.long("package")
634+
.value_name("PURL")
635+
.help("Only show logs matching this PURL")
636+
.conflicts_with("ecosystem"),
637+
Arg::new("action")
638+
.long("action")
639+
.value_name("ACTION")
640+
.help("Only show logs matching this log action")
641+
.value_parser([
642+
"Download",
643+
"AnalysisSuccess",
644+
"AnalysisFailure",
645+
"AnalysisWarning",
646+
]),
647+
Arg::new("before").long("before").value_name("TIMESTAMP").help(
648+
"Only show logs created before this timestamp (RFC3339 format)",
649+
),
650+
Arg::new("after").long("after").value_name("TIMESTAMP").help(
651+
"Only show logs created after this timestamp (RFC3339 format)",
652+
),
653+
Arg::new("limit")
654+
.long("limit")
655+
.value_name("COUNT")
656+
.help("Maximum number of log entries to show")
657+
.default_value("10")
658+
.value_parser(1..=10_000),
659+
]),
660+
),
606661
);
607662

608663
#[cfg(feature = "extensions")]

cli/src/bin/phylum.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ use phylum_cli::commands::sandbox;
1414
#[cfg(feature = "selfmanage")]
1515
use phylum_cli::commands::uninstall;
1616
use phylum_cli::commands::{
17-
auth, find_dependency_files, group, init, jobs, org, packages, parse, project, status,
18-
CommandResult, ExitCode,
17+
auth, find_dependency_files, firewall, group, init, jobs, org, packages, parse, project,
18+
status, CommandResult, ExitCode,
1919
};
2020
use phylum_cli::config::{self, Config};
2121
use phylum_cli::spinner::Spinner;
@@ -145,6 +145,9 @@ async fn handle_commands() -> CommandResult {
145145
"init" => init::handle_init(&Spinner::wrap(api).await?, sub_matches, config).await,
146146
"status" => status::handle_status(sub_matches).await,
147147
"org" => org::handle_org(&Spinner::wrap(api).await?, sub_matches, config).await,
148+
"firewall" => {
149+
firewall::handle_firewall(&Spinner::wrap(api).await?, sub_matches, config).await
150+
},
148151

149152
#[cfg(feature = "selfmanage")]
150153
"uninstall" => uninstall::handle_uninstall(sub_matches),

cli/src/commands/firewall.rs

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
//! Subcommand `phylum firewall`.
2+
3+
use std::borrow::Cow;
4+
use std::str::FromStr;
5+
6+
use clap::ArgMatches;
7+
use purl::Purl;
8+
9+
use crate::api::PhylumApi;
10+
use crate::commands::{CommandResult, ExitCode};
11+
use crate::config::Config;
12+
use crate::format::Format;
13+
use crate::print_user_failure;
14+
use crate::types::FirewallLogFilter;
15+
16+
/// Handle `phylum firewall` subcommand.
17+
pub async fn handle_firewall(
18+
api: &PhylumApi,
19+
matches: &ArgMatches,
20+
config: Config,
21+
) -> CommandResult {
22+
match matches.subcommand() {
23+
Some(("log", matches)) => handle_log(api, matches, config).await,
24+
_ => unreachable!("invalid clap configuration"),
25+
}
26+
}
27+
28+
/// Handle `phylum firewall log` subcommand.
29+
pub async fn handle_log(api: &PhylumApi, matches: &ArgMatches, config: Config) -> CommandResult {
30+
let org = config.org();
31+
let group = matches.get_one::<String>("group").unwrap();
32+
33+
// Get log filter args.
34+
let ecosystem = matches.get_one::<String>("ecosystem");
35+
let purl = matches.get_one::<String>("package");
36+
let action = matches.get_one::<String>("action");
37+
let before = matches.get_one::<String>("before");
38+
let after = matches.get_one::<String>("after");
39+
let limit = matches.get_one::<i64>("limit").unwrap();
40+
41+
// Parse PURL filter.
42+
let parsed_purl = purl.map(|purl| Purl::from_str(purl));
43+
let (ecosystem, namespace, name, version) = match &parsed_purl {
44+
Some(Ok(purl)) => {
45+
let ecosystem = Cow::Owned(purl.package_type().to_string());
46+
(Some(ecosystem), purl.namespace(), Some(purl.name()), purl.version())
47+
},
48+
Some(Err(err)) => {
49+
print_user_failure!("Could not parse purl {purl:?}: {err}");
50+
return Ok(ExitCode::Generic);
51+
},
52+
None => (ecosystem.map(Cow::Borrowed), None, None, None),
53+
};
54+
55+
// Construct the filter.
56+
let filter = FirewallLogFilter {
57+
ecosystem: ecosystem.as_ref().map(|e| e.as_str()),
58+
namespace,
59+
name,
60+
version,
61+
action: action.map(String::as_str),
62+
before: before.map(String::as_str),
63+
after: after.map(String::as_str),
64+
limit: Some(*limit as i32),
65+
};
66+
67+
let response = api.firewall_log(org, group, filter).await?;
68+
69+
let pretty = !matches.get_flag("json");
70+
response.data.write_stdout(pretty);
71+
72+
Ok(ExitCode::Ok)
73+
}

cli/src/commands/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ pub mod auth;
44
#[cfg(feature = "extensions")]
55
pub mod extensions;
66
pub mod find_dependency_files;
7+
pub mod firewall;
78
pub mod group;
89
pub mod init;
910
pub mod jobs;

0 commit comments

Comments
 (0)