Skip to content

[Backend] Recommendation report endpoint (POST /v3/recommend/report) - #2656

Open
ruromero wants to merge 6 commits into
guacsec:mainfrom
ruromero:TC-5999
Open

ruromero wants to merge 6 commits into
guacsec:mainfrom
ruromero:TC-5999

Conversation

@ruromero

@ruromero ruromero commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Adds POST /v3/recommend/report endpoint that accepts a list of SBOM IDs and returns an aggregated vendor recommendation report
  • Uses query-time pattern matching via recommend_patterns (same approach as the updated /purl/recommend endpoint — no recommendation DB table required)
  • Enforces a configurable total package count limit (TRUSTD_RECOMMEND_REPORT_PACKAGE_LIMIT env var, default 10 000) returning 413 package_limit_exceeded when exceeded
  • Packages appearing in multiple SBOMs are deduplicated: a single entry with all SBOM IDs in found_in
  • Fix (TC-6217): report_for_sboms now returns per-SBOM zero-count entries when recommend_patterns is not configured; previously returned an empty sboms list
  • Fix: openapi.yaml regenerated to correctly show 413 (not 400) for package_limit_exceeded

Response shape

{
  "impact_summary": { "sboms_with_recommendations": N, "addressable_packages": N },
  "sboms": [{ "id": UUID, "name": String, "addressable_packages": N, "vulnerability_count": N }],
  "packages": [{ "purl": String, "recommended_purl": String, "advisory_id": String, "vulnerabilities": [CVE], "found_in": [UUID] }]
}

Out-of-scope file changes

Two files outside the task's "Files to Modify" list were updated minimally to wire the feature end-to-end:

  • modules/fundamental/src/endpoints.rs — added recommend_report_package_limit: u64 to Config with Default impl that reads TRUSTD_RECOMMEND_REPORT_PACKAGE_LIMIT env var (enables per-test configuration)
  • server/src/profile/api.rs — added ..Default::default() to the Config initializer (one line, supplies the new field's default)

Test plan

  • cargo xtask precommit — passes
  • Integration test: report for 2 SBOMs with recommendations → correct impact_summary, sboms, packages
  • Integration test: same package in both SBOMs → deduplicated entry with both SBOM IDs in found_in
  • Integration test: total packages exceed limit → 413 package_limit_exceeded
  • Integration test: SBOMs with no recommendations → empty packages, zero counts
  • Integration test: no recommendation patterns configured → sboms list has one entry with zero counts (not empty)

Implements TC-5999

🤖 Generated with Claude Code

Summary by Sourcery

Add an aggregated SBOM vendor recommendation report endpoint with configurable request limits and complete per-package and per-SBOM impact reporting.

New Features:

  • Add a POST /v3/recommend/report endpoint that aggregates vendor recommendations across requested SBOMs with per-SBOM and package-level impact data.
  • Support configurable package-count limits for recommendation reports and return 413 when requests exceed the limit.

Bug Fixes:

  • Return zero-count entries for requested SBOMs when recommendation patterns or matching recommendations are unavailable.
  • Exclude inactive vulnerability statuses from report vulnerability results.

Enhancements:

  • Deduplicate recommended packages across SBOMs and report all containing SBOM IDs.
  • Generate OpenAPI definitions for the recommendation report endpoint and response models.

Tests:

  • Add integration coverage for aggregated reports, package deduplication, package limits, empty results, missing patterns, and vulnerability filtering.

@sourcery-ai

sourcery-ai Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Introduces an authenticated POST /v3/recommend/report API that scans requested SBOM package associations at query time, selects vendor rebuild recommendations using configured patterns, aggregates vulnerability and advisory data, deduplicates packages across SBOMs, and enforces a configurable total-package limit. The PR also adds API schemas, configuration plumbing, OpenAPI documentation, and integration tests for the primary report behaviors.

Sequence diagram for the SBOM recommendation report request

sequenceDiagram
    participant Client
    participant API as RecommendReportEndpoint
    participant Service as PurlService
    participant DB as ReadOnlyDatabase

    Client->>API: POST /v3/recommend/report
    API->>DB: begin()
    API->>Service: count_sbom_packages(sbom_ids, tx)
    alt package limit exceeded
        Service-->>API: total package count
        API-->>Client: 400 package_limit_exceeded
    else within limit
        API->>Service: report_for_sboms(sbom_ids, tx)
        Service->>DB: fetch_sbom_names(sbom_ids)
        Service->>DB: fetch_sbom_purl_rows(sbom_ids)
        Service->>Service: find_highest_vendor_patch(pattern, version, candidates)
        Service->>DB: fetch vulnerability statuses
        Service-->>API: RecommendReportResponse
        API-->>Client: 200 aggregated report
    end
Loading

Flow diagram for recommendation report aggregation

flowchart TD
    A["SBOM IDs"] --> B[count_sbom_packages]
    B --> C{"Total exceeds report_package_limit?"}
    C -->|Yes| D["400 package_limit_exceeded"]
    C -->|No| E[fetch_sbom_purl_rows]
    E --> F[Group by base PURL and version]
    F --> G[Pattern-match vendor rebuilds]
    G --> H[Select highest vendor patch]
    H --> I[Fetch vulnerability and advisory status]
    I --> J[Deduplicate package entries and collect found_in]
    J --> K[Build impact_summary, sboms, and packages]
    K --> L["200 RecommendReportResponse"]
Loading

File-Level Changes

Change Details Files
Adds the authenticated recommendation report endpoint and wires it into the PURL service with configurable package-count protection.
  • Registers POST /v3/recommend/report and documents success and limit-exceeded responses.
  • Counts all SBOM package associations before generating the report and returns a structured 400 error when the configured limit is exceeded.
  • Adds a configurable limit sourced from TRUSTD_RECOMMEND_REPORT_PACKAGE_LIMIT, with a default of 10,000, and propagates it through endpoint configuration.
modules/fundamental/src/endpoints.rs
modules/fundamental/src/purl/endpoints/mod.rs
server/src/profile/api.rs
Implements query-time aggregation of vendor recommendations across multiple SBOMs without a recommendation database table.
  • Loads SBOM names and package associations, groups packages by base PURL and version, and applies configured vendor-version patterns to select the highest matching patch.
  • Fetches vulnerability status and advisory provenance for winning recommendations, selecting the latest status per vulnerability.
  • Builds impact totals, per-SBOM addressable-package and vulnerability counts, and deduplicated package entries with found_in SBOM IDs.
  • Handles empty requests, empty SBOMs, and cases with no matching recommendations.
modules/fundamental/src/purl/service/mod.rs
Defines the request and response model for the aggregated recommendation report.
  • Adds schemas for request SBOM IDs, impact summary, per-SBOM details, and deduplicated package recommendations.
  • Includes optional advisory provenance, vulnerability identifiers, recommended PURLs, and SBOM membership in the response.
modules/fundamental/src/purl/model/mod.rs
openapi.yaml
Adds integration coverage for the report’s aggregation, deduplication, limit enforcement, and empty-result behavior.
  • Tests aggregated results across two SBOMs and vendor patch selection.
  • Verifies a shared package appears once with both SBOM IDs in found_in.
  • Verifies the configured zero limit produces 400 package_limit_exceeded.
  • Verifies SBOMs without recommendations return zero counts and no packages.
modules/fundamental/src/purl/endpoints/test.rs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="modules/fundamental/src/purl/service/mod.rs" line_range="913" />
<code_context>
+        sbom_ids: &[Uuid],
+        connection: &C,
+    ) -> Result<RecommendReportResponse, Error> {
+        if sbom_ids.is_empty() || self.recommend_patterns.is_empty() {
+            return Ok(RecommendReportResponse::default());
+        }
+
</code_context>
<issue_to_address>
**issue (bug_risk):** When `recommend_patterns` is empty, `report_for_sboms` returns `RecommendReportResponse::default()` before fetching or populating the requested SBOMs, so the response contains an empty `sboms` list instead of one per requested SBOM.

**Triggers:** When the endpoint is configured without recommendation patterns, such as a caller using the default `Config`.

**Suggested fix:** Populate the per-SBOM zero-count entries before returning, or remove this early return and let the normal empty-result path build the response.

```suggestion
        if sbom_ids.is_empty() {
```
</issue_to_address>

### Comment 2
<location path="modules/fundamental/src/purl/service/mod.rs" line_range="1071-1070" />
<code_context>
     weakness,
 };

-#[derive(Clone, Debug, Default)]
+#[derive(Clone, Debug)]
</code_context>
<issue_to_address>
**issue (broader_impact):** The report emits every vulnerability status returned for the winning vendor PURL, without filtering by `status_slug` or applying the status/remediation rules used by `assemble_recommend_entry`; therefore vulnerabilities with non-impactful statuses such as fixed or not-affected are reported as vulnerabilities for the package.

**Triggers:** When a winning vendor PURL has multiple VEX statuses, including statuses that should not count as applicable vulnerabilities.

**Suggested fix:** Reuse the status filtering logic from `assemble_recommend_entry` when constructing the report's vulnerability list and per-SBOM vulnerability counts.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: modules/fundamental/src/purl/service/mod.rs:913, modules/fundamental/src/purl/service/mod.rs:1070


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread modules/fundamental/src/purl/service/mod.rs Outdated
Comment thread modules/fundamental/src/purl/service/mod.rs Outdated
@ruromero

ruromero commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

[sdlc-workflow/verify-pr] Re: @sourcery-ai review — Classified as code change request — 2 issues identified; sub-tasks TC-6217 (empty sboms on no patterns) and TC-6218 (vulnerability status filtering) created to address this feedback.

@ruromero

ruromero commented Sep 14, 2026

Copy link
Copy Markdown
Contributor Author

Verification Report for TC-5999 (commit b99b098)

Check Result Details
Review Feedback WARN 2 code change requests from sourcery-ai[bot]; sub-tasks TC-6217 (empty sboms on no patterns) and TC-6218 (vuln status filtering) created
Root-Cause Investigation DONE Bug 1: implement-task gap (exit-path × AC cross-walk missing) → TC-6219; Bug 2: plan-feature gap (behavioral contract not extracted from reference) → TC-6220
Scope Containment PASS Core files match spec; 3 peripheral files (endpoints.rs, test.rs, server/api.rs) are justified incidental changes
Diff Size PASS ~790 additions proportionate to new endpoint + service logic + 4 integration tests
Commit Traceability PASS Both commits reference TC-5999 in body
Sensitive Patterns PASS No secrets, credentials, or tokens in any added line
CI Status WARN Latest test run: flaky embedded-DB timeout in trustify_module_analysis (unrelated to this PR); prior run passed
Acceptance Criteria FAIL 4/6 met — AC1/AC5 broken by empty-patterns early-return bug (TC-6217); AC4 partially met (advisory_id is optional/may be absent)
Test Quality WARN Test doc comment on recommend_report_package_limit_exceeded said "400" but test asserts PAYLOAD_TOO_LARGE (413); Eval Quality: N/A
Test Change Classification ADDITIVE +246 lines of new tests, no existing tests removed or weakened
Verification Commands PASS cargo xtask precommit exits 0; note: regenerated openapi.yaml (400→413) is an uncommitted local change and must be committed before merge

Overall: FAIL

Blockers before merge:

  1. TC-6217 — Fix report_for_sboms empty-patterns early-return: when recommend_patterns is empty, sboms list is empty instead of per-SBOM zero-count entries. Fix: remove || self.recommend_patterns.is_empty() from line 913; run cargo xtask precommit and commit the regenerated openapi.yaml (corrects 400→413 in spec).
  2. TC-6218 — Fix vulnerability status filtering: best_by_vuln.keys() emits all vulnerability IDs including fixed/not_affected. Fix: filter by status_slug ∈ {"affected", "under_investigation"} before collecting.
  3. openapi.yamlcargo xtask precommit regenerates the spec to show 413 but that change is uncommitted. Commit it (can be done as part of TC-6217 fix).

This comment was AI-generated by sdlc-workflow/verify-pr v0.13.9.

sourcery-ai[bot]
sourcery-ai Bot previously approved these changes Sep 14, 2026

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sourcery assessment

Approved.

@ruromero
ruromero requested review from a team and rh-jfuller and removed request for rh-jfuller September 14, 2026 15:44
}

// Fetch vulnerability statuses for all winning versioned PURLs.
let statuses_by_base = Self::fetch_vulnerability_statuses(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

something not quite right here (but I am not very familiar with expected output) - if this returns statuses keyed only by base_purl_id even though report contains multiple 'winning' versioned PURLs for that base ? Each package sees a 'union of statuses' from every version and best_by_vuln selects by advisory date rather than the applicable package version. Key statuses by the winning versioned PURL ID as well. Is this what you want ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the catch, you're right. When two winning PURLs share the same base_purl_id (different upstream versions across the requested SBOMs), statuses_by_base merges their status rows, so best_by_vuln can pick a status entry from the wrong winner if advisory dates differ between them. Fix: key the result by winner_vp_id instead of base_purl_id, select versioned_purl.id in fetch_vulnerability_statuses, and update the lookup to statuses_by_vp.get(&winner.winner_vp_id). Will fix.

)]
#[post("/v3/recommend/report")]
/// Generate an aggregated vendor recommendation report for a set of SBOMs.
pub async fn recommend_report(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this new endpoint returns SBOM names, package PURLs, and SBOM membership but requires only ReadAdvisory perm. Existing PURL/SBOM reads require ReadSbom which is prob needed here as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the endpoint returns SBOM names and membership data so ReadSbom should also be required alongside ReadAdvisory. Will add.

@sourcery-ai
sourcery-ai Bot dismissed their stale review September 15, 2026 14:00

Sourcery withdrew this approval because the latest commits introduced blocking findings.

ruromero and others added 5 commits September 15, 2026 18:33
Implements on-demand vendor recommendation report for a list of SBOM IDs.
Uses query-time pattern matching (same as /purl/recommend) rather than
a dedicated recommendation DB table.

Key behaviour:
- Counts total packages across all requested SBOMs and returns 400
  package_limit_exceeded when the total exceeds TRUSTD_RECOMMEND_REPORT_PACKAGE_LIMIT
  (default 10 000, configurable via Config.recommend_report_package_limit).
- Joins sbom_node_purl_ref → versioned_purl → base_purl to collect upstream
  PURLs, then runs recommend_patterns regex matching to find the highest vendor
  patch version for each unique (base, version) pair.
- Deduplicates packages that appear in multiple SBOMs; all SBOM IDs appear in
  found_in on the single package entry.
- Fetches VEX statuses for winning vendor PURLs and reports vulnerability IDs
  and advisory provenance.
- Returns RecommendReportResponse with impact_summary, per-sbom breakdown,
  and deduplicated packages list.

Also threads recommend_report_package_limit through Config and the purl
endpoint configure function so tests can set an explicit limit without
relying on environment variables.

Integration tests cover: aggregated data for 2 SBOMs, deduplication with
found_in, package limit exceeded → 400, and empty result for unknown packages.

Implements TC-5999

Assisted-by: Claude Code
Implements TC-5999

Assisted-by: Claude Code
Previously report_for_sboms returned RecommendReportResponse::default()
(empty sboms list) when recommend_patterns was not configured. The correct
behaviour is one zero-count RecommendReportSbom entry per requested SBOM,
matching the existing winners.is_empty() path.

Also regenerates openapi.yaml via cargo xtask precommit — corrects the
stale 400 → 413 status code for the package_limit_exceeded response.

Adds integration test: POST /v3/recommend/report with empty patterns
returns sboms list with one entry at zero counts.

Implements TC-6217

Assisted-by: Claude Code
Report's vulnerabilities list previously emitted all VEX status entries
regardless of status_slug. Fixed and not_affected statuses are now excluded
server-side, since the report returns raw CVE IDs with no status context
and callers cannot filter downstream.

Only "affected" and "under_investigation" status slugs contribute to the
vulnerabilities list and per-SBOM vulnerability_count.

Adds integration test verifying that a not_affected CVE is absent from
the report's vulnerabilities list even when a vendor patch is found.

Implements TC-6218

Assisted-by: Claude Code
Fix 1 (status cross-version contamination): when the same base PURL
appears with two different upstream versions (two winner_vp_ids),
the batch fetch_vulnerability_statuses call grouped both versions'
statuses under the same base_purl_id bucket. best_by_vuln then
selected by advisory date across both versions, which could assign
a status from the wrong version to a winner. Fix: call
fetch_vulnerability_statuses once per winner (keyed by winner_vp_id)
to scope version-range matching to each winner's specific versioned PURL.

Fix 2 (missing permission): the endpoint returns SBOM names and
membership data (found_in SBOM IDs) so ReadSbom must be required
alongside ReadAdvisory.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Assisted-by: Claude Code
@ruromero
ruromero force-pushed the TC-5999 branch 2 times, most recently from 88b5580 to fdf880d Compare September 15, 2026 16:59
Signed-off-by: Ruben Romero Montes <rromerom@redhat.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

2 participants