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

fix: urlencode purl qualifier values in the db #1116

Merged
merged 3 commits into from
Dec 20, 2024
Merged
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
2 changes: 2 additions & 0 deletions migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ mod m0000760_product_status_index;
mod m0000780_alter_source_document_time;
mod m0000790_alter_sbom_alter_document_id;
mod m0000800_alter_product_version_range_scheme;
mod m0000810_fix_get_purl;

pub struct Migrator;

Expand Down Expand Up @@ -201,6 +202,7 @@ impl MigratorTrait for Migrator {
Box::new(m0000780_alter_source_document_time::Migration),
Box::new(m0000790_alter_sbom_alter_document_id::Migration),
Box::new(m0000800_alter_product_version_range_scheme::Migration),
Box::new(m0000810_fix_get_purl::Migration),
]
}
}
Expand Down
35 changes: 35 additions & 0 deletions migration/src/m0000810_fix_get_purl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.get_connection()
.execute_unprepared(include_str!("m0000810_fix_get_purl/get_purl.sql"))
.await
.map(|_| ())?;

Ok(())
}

async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
manager
.get_connection()
.execute_unprepared(include_str!("m0000740_ensure_get_purl_fns/get_purl.sql"))
.await?;

manager
.get_connection()
.execute_unprepared(
r#"
DROP FUNCTION IF EXISTS encode_uri_component;
"#,
)
.await?;

Ok(())
}
}
49 changes: 49 additions & 0 deletions migration/src/m0000810_fix_get_purl/get_purl.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
CREATE OR REPLACE FUNCTION encode_uri_component(text) RETURNS text AS $$
SELECT string_agg(
CASE
WHEN bytes > 1 or c !~ '[0-9a-zA-Z_.!~*''()-]+' THEN
regexp_replace(encode(convert_to(c, 'utf-8')::bytea, 'hex'), '(..)', E'%\\1', 'g')
ELSE
c
END,
''
)
FROM (
SELECT c, octet_length(c) bytes
FROM regexp_split_to_table($1, '') c
) q;
$$ LANGUAGE sql IMMUTABLE STRICT ;

CREATE OR REPLACE FUNCTION get_purl(qualified_purl_id UUID)
RETURNS TEXT AS $$
DECLARE
result TEXT;
BEGIN
SELECT
COALESCE(
'pkg:' || bp.type ||
'/' || COALESCE(bp.namespace, '') || '/' ||
bp.name ||
'@' || vp.version ||
CASE
WHEN qp.qualifiers IS NOT NULL AND qp.qualifiers <> '{}'::jsonb THEN
'?' || (
SELECT string_agg(key || '=' || encode_uri_component(value), '&')
FROM jsonb_each_text(qp.qualifiers)
)
ELSE
''
END,
qualified_purl_id::text
)
INTO result
FROM
qualified_purl qp
LEFT JOIN versioned_purl vp ON vp.id = qp.versioned_purl_id
LEFT JOIN base_purl bp ON bp.id = vp.base_purl_id
WHERE
qp.id = qualified_purl_id;

RETURN result;
END;
$$ LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;
25 changes: 24 additions & 1 deletion migration/tests/getpurl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async fn test_getpurl(ctx: &TrustifyContext) -> Result<(), anyhow::Error> {
match get_purl(&ctx.db, sbom_package_purl_ref.qualified_purl_id.to_string()).await {
Ok(Some(purl)) => {
let parse_purl: Purl = Purl::from_str(purl.as_str())?;
assert!(parse_purl.name == sbom_node_name);
assert_eq!(parse_purl.name, sbom_node_name);
}
Ok(None) => panic!("getpurl() test should match"),
Err(e) => panic!("error testing getpurl() pg function. {}", e),
Expand All @@ -63,3 +63,26 @@ async fn test_getpurl(ctx: &TrustifyContext) -> Result<(), anyhow::Error> {

Ok(())
}

#[test_context(TrustifyContext)]
#[test(tokio::test)]
async fn getpurl_urls(ctx: &TrustifyContext) -> Result<(), anyhow::Error> {
let qualified = ctx
.graph
.ingest_qualified_package(
&Purl::from_str("pkg:maven/org.foo.bar/[email protected]?key=value%3dvalue")?,
&ctx.db,
)
.await?;

let id = qualified.qualified_package.id;

let result = get_purl(&ctx.db, id.to_string()).await?;

assert_eq!(
result.as_deref(),
Some("pkg:maven/org.foo.bar/[email protected]?key=value%3dvalue")
);

Ok(())
}
2 changes: 2 additions & 0 deletions migration/tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ async fn test_migrations(ctx: TrustifyContext) -> Result<(), anyhow::Error> {
#[test_context(TrustifyContext, skip_teardown)]
#[test(tokio::test)]
async fn only_up_migration(_ctx: TrustifyContext) -> Result<(), anyhow::Error> {
// The initialization of the database will already call the `up` function. So we
// don't need any extra code here
Ok(())
}
2 changes: 1 addition & 1 deletion modules/analysis/src/endpoints.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ mod test {
);
assert_eq!(
response["items"][0]["ancestors"][0]["purl"],
"pkg:maven/com.redhat.quarkus.platform/[email protected]?type=pom&repository_url=https://maven.repository.redhat.com/ga/"
"pkg:maven/com.redhat.quarkus.platform/[email protected]?type=pom&repository_url=https%3a%2f%2fmaven.repository.redhat.com%2fga%2f"
);

assert_eq!(&response["total"], 2);
Expand Down
2 changes: 1 addition & 1 deletion modules/analysis/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1109,7 +1109,7 @@ mod test {
.unwrap();

assert_eq!(analysis_graph.items.last().unwrap().ancestors.last().unwrap().purl,
"pkg:maven/com.redhat.quarkus.platform/[email protected]?type=pom&repository_url=https://maven.repository.redhat.com/ga/".to_string()
"pkg:maven/com.redhat.quarkus.platform/[email protected]?type=pom&repository_url=https%3a%2f%2fmaven.repository.redhat.com%2fga%2f".to_string()
);
assert_eq!(
analysis_graph
Expand Down
Loading