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

Work towards new API from ADR #1213

Closed
wants to merge 6 commits into from
Closed
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
1 change: 1 addition & 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 @@ -61,6 +61,7 @@ csaf = { version = "0.5.0", default-features = false }
csaf-walker = { version = "0.10.0", default-features = false }
cve = "0.3.1"
env_logger = "0.11.0"
fixedbitset = "0.5.7"
futures = "0.3.30"
futures-util = "0.3"
garage-door = "0.1.1"
Expand Down
4 changes: 2 additions & 2 deletions common/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ impl<R> PaginatedResults<R> {
})
}

pub fn map<O, F: Fn(R) -> O>(mut self, f: F) -> PaginatedResults<O> {
pub fn map<O, F: Fn(R) -> O>(self, f: F) -> PaginatedResults<O> {
PaginatedResults {
items: self.items.drain(..).map(f).collect(),
items: self.items.into_iter().map(f).collect(),
total: self.total,
}
}
Expand Down
28 changes: 28 additions & 0 deletions entity/src/relationship.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,34 @@ pub enum Relationship {
#[sea_orm(num_value = 14)]
PackageOf,
#[sea_orm(num_value = 15)]
Contains,
#[sea_orm(num_value = 16)]
Dependency,
#[sea_orm(num_value = 17)]
DevDependency,
#[sea_orm(num_value = 18)]
OptionalDependency,
#[sea_orm(num_value = 19)]
ProvidedDependency,
#[sea_orm(num_value = 20)]
TestDependency,
#[sea_orm(num_value = 21)]
RuntimeDependency,
#[sea_orm(num_value = 22)]
Example,
#[sea_orm(num_value = 23)]
Generates,
#[sea_orm(num_value = 24)]
Variant,
#[sea_orm(num_value = 25)]
BuildTool,
#[sea_orm(num_value = 26)]
DevTool,
#[sea_orm(num_value = 27)]
Describes,
#[sea_orm(num_value = 28)]
Packages,
#[sea_orm(num_value = 29)]
Undefined,
}

Expand Down
2 changes: 2 additions & 0 deletions migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ mod m0000810_fix_get_purl;
mod m0000820_create_conversation;
mod m0000830_perf_indexes;
mod m0000840_add_relationship_14_15;
mod m0000850_normalise_relationships;

pub struct Migrator;

Expand Down Expand Up @@ -209,6 +210,7 @@ impl MigratorTrait for Migrator {
Box::new(m0000820_create_conversation::Migration),
Box::new(m0000830_perf_indexes::Migration),
Box::new(m0000840_add_relationship_14_15::Migration),
Box::new(m0000850_normalise_relationships::Migration),
]
}
}
Expand Down
57 changes: 57 additions & 0 deletions migration/src/m0000850_normalise_relationships.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;
const DATA: [(i32, &str); 14] = [
(16, "Contains"),
(17, "Dependency"),
(18, "DevDependency"),
(19, "OptionalDependency"),
(20, "ProvidedDependency"),
(21, "TestDependency"),
(22, "RuntimeDependency"),
(23, "Example"),
(24, "Generates"),
(25, "Variant"),
(26, "BuildTool"),
(27, "DevTool"),
(28, "Describes"),
(29, "Packages"),
];

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
for (id, description) in DATA {
let insert = Query::insert()
.into_table(Relationship::Table)
.columns([Relationship::Id, Relationship::Description])
.values_panic([id.into(), description.into()])
.to_owned();

manager.exec_stmt(insert).await?;
}

Ok(())
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
for (id, _) in DATA {
let insert = Query::delete()
.from_table(Relationship::Table)
.and_where(Expr::col(Relationship::Id).lt(id))
.to_owned();

manager.exec_stmt(insert).await?;
}

Ok(())
}
}

#[derive(DeriveIden)]
pub enum Relationship {
Table,
Id,
Description,
}
1 change: 1 addition & 0 deletions modules/analysis/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ actix-http = { workspace = true }
actix-web = { workspace = true }
anyhow = { workspace = true }
cpe = { workspace = true }
fixedbitset = { workspace = true }
log = { workspace = true }
parking_lot = { workspace = true }
petgraph = { workspace = true }
Expand Down
69 changes: 52 additions & 17 deletions modules/analysis/src/endpoints/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ mod query;
#[cfg(test)]
mod test;

use super::service::AnalysisService;
use super::service::{AnalysisService, QueryOptions};
use crate::{
endpoints::query::OwnedComponentReference,
model::{AnalysisStatus, AncestorSummary, BaseSummary, DepSummary},
model::{AnalysisStatus, BaseSummary, Node, RootTraces},
};
use actix_web::{get, web, HttpResponse, Responder};
use trustify_auth::{
Expand All @@ -20,9 +20,7 @@ use trustify_common::{
};
use utoipa_actix_web::service_config::ServiceConfig;

pub fn configure(config: &mut ServiceConfig, db: Database) {
let analysis = AnalysisService::new();

pub fn configure(config: &mut ServiceConfig, db: Database, analysis: AnalysisService) {
config
.app_data(web::Data::new(analysis))
.app_data(web::Data::new(db))
Expand All @@ -31,7 +29,8 @@ pub fn configure(config: &mut ServiceConfig, db: Database) {
.service(get_component)
.service(analysis_status)
.service(search_component_deps)
.service(get_component_deps);
.service(get_component_deps)
.service(render_sbom_graph);
}

#[utoipa::path(
Expand Down Expand Up @@ -61,7 +60,7 @@ pub async fn analysis_status(
Paginated,
),
responses(
(status = 200, description = "Search component(s) and return their root components.", body = PaginatedResults<AncestorSummary>),
(status = 200, description = "Search component(s) and return their root components.", body = PaginatedResults<Node>),
),
)]
#[get("/v2/analysis/root-component")]
Expand All @@ -74,8 +73,9 @@ pub async fn search_component_root_components(
) -> actix_web::Result<impl Responder> {
Ok(HttpResponse::Ok().json(
service
.retrieve_root_components(&search, paginated, db.as_ref())
.await?,
.retrieve(&search, QueryOptions::ancestors(), paginated, db.as_ref())
.await?
.root_traces(),
))
}

Expand All @@ -86,7 +86,7 @@ pub async fn search_component_root_components(
("key" = String, Path, description = "provide component name, URL-encoded pURL, or CPE itself")
),
responses(
(status = 200, description = "Retrieve component(s) root components by name, pURL, or CPE.", body = PaginatedResults<AncestorSummary>),
(status = 200, description = "Retrieve component(s) root components by name, pURL, or CPE.", body = PaginatedResults<Node>),
),
)]
#[get("/v2/analysis/root-component/{key}")]
Expand All @@ -101,8 +101,9 @@ pub async fn get_component_root_components(

Ok(HttpResponse::Ok().json(
service
.retrieve_root_components(&query, paginated, db.as_ref())
.await?,
.retrieve(&query, QueryOptions::ancestors(), paginated, db.as_ref())
.await?
.root_traces(),
))
}

Expand All @@ -128,7 +129,14 @@ pub async fn get_component(

Ok(HttpResponse::Ok().json(
service
.retrieve_components(&query, paginated, db.as_ref())
.retrieve(
&query,
QueryOptions {
..Default::default()
},
paginated,
db.as_ref(),
)
.await?,
))
}
Expand All @@ -141,7 +149,7 @@ pub async fn get_component(
Paginated,
),
responses(
(status = 200, description = "Search component(s) and return their deps.", body = PaginatedResults<DepSummary>),
(status = 200, description = "Search component(s) and return their deps.", body = PaginatedResults<Node>),
),
)]
#[get("/v2/analysis/dep")]
Expand All @@ -154,7 +162,7 @@ pub async fn search_component_deps(
) -> actix_web::Result<impl Responder> {
Ok(HttpResponse::Ok().json(
service
.retrieve_deps(&search, paginated, db.as_ref())
.retrieve(&search, QueryOptions::descendants(), paginated, db.as_ref())
.await?,
))
}
Expand All @@ -166,7 +174,7 @@ pub async fn search_component_deps(
("key" = String, Path, description = "provide component name or URL-encoded pURL itself")
),
responses(
(status = 200, description = "Retrieve component(s) dep components by name or pURL.", body = PaginatedResults<DepSummary>),
(status = 200, description = "Retrieve component(s) dep components by name or pURL.", body = PaginatedResults<Node>),
),
)]
#[get("/v2/analysis/dep/{key}")]
Expand All @@ -180,7 +188,34 @@ pub async fn get_component_deps(
let query = OwnedComponentReference::try_from(key.as_str())?;
Ok(HttpResponse::Ok().json(
service
.retrieve_deps(&query, paginated, db.as_ref())
.retrieve(&query, QueryOptions::descendants(), paginated, db.as_ref())
.await?,
))
}

#[utoipa::path(
tag = "analysis",
operation_id = "renderSbomGraph",
params(
("sbom" = String, Path, description = "ID of the SBOM")
),
responses(
(status = 200, description = "A graphwiz dot file of the SBOM graph", body = String),
(status = 404, description = "The SBOM was not found"),
),
)]
#[get("/v2/analysis/sbom/{sbom}/render")]
pub async fn render_sbom_graph(
service: web::Data<AnalysisService>,
db: web::Data<Database>,
sbom: web::Path<String>,
_: Require<ReadSbom>,
) -> actix_web::Result<impl Responder> {
service.load_graph(db.as_ref(), &sbom).await;

if let Some(data) = service.render_dot(&sbom) {
Ok(HttpResponse::Ok().body(data))
} else {
Ok(HttpResponse::NotFound().finish())
}
}
6 changes: 4 additions & 2 deletions modules/analysis/src/endpoints/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,12 +181,14 @@ async fn test_simple_dep_endpoint(ctx: &TrustifyContext) -> Result<(), anyhow::E
let request: Request = TestRequest::get().uri(uri).to_request();
let response: Value = app.call_and_read_body_json(request).await;

log::debug!("Response: {:#?}", response);

assert_eq!(
response["items"][0]["purl"],
Value::from(["pkg:rpm/redhat/[email protected]?arch=src"]),
);

let purls = response["items"][0]["deps"]
let purls = response["items"][0]["descendent"]
.as_array()
.iter()
.flat_map(|deps| *deps)
Expand Down Expand Up @@ -606,7 +608,7 @@ async fn cdx_ancestor_of(ctx: &TrustifyContext) -> Result<(), anyhow::Error> {
// we're only looking for the parent node
.filter(|m| m["node_id"] == parent)
// flatten all dependencies of that parent node
.flat_map(|m| m["deps"].as_array().into_iter().flatten())
.flat_map(|m| m["descendent"].as_array().into_iter().flatten())
// filter out all non-AncestorOf dependencies
.filter(|m| m["relationship"] == "AncestorOf")
.collect();
Expand Down
Loading