diff --git a/crates/gvm-gateway-gvmd/src/gvmd_adapter/ports/reports.rs b/crates/gvm-gateway-gvmd/src/gvmd_adapter/ports/reports.rs index 96676b78..b0989cda 100644 --- a/crates/gvm-gateway-gvmd/src/gvmd_adapter/ports/reports.rs +++ b/crates/gvm-gateway-gvmd/src/gvmd_adapter/ports/reports.rs @@ -82,7 +82,7 @@ impl ReportPort for GvmdAdapter { // Fetch only report metadata; embedded results are loaded below through // the explicit result-window request. - let mut request = GetReportRequest::new(report_id); + let mut request = GetReportRequest::new(report_id.clone()); request.details = Some(false); let parsed = self .execute_with_session(session_token, "reports.get", request) @@ -119,12 +119,15 @@ impl ReportPort for GvmdAdapter { } // Fetch the explicitly requested embedded-result window for this report. - let filter = paginated_filter( - Some(&format!("report_id={id}")), - None, - opts.page, - opts.per_page, - )?; + let filter = Some( + gvm_gmp::compose_report_results_filter( + &report_id, + None, + None, + GmpPagination::new(opts.page as usize, opts.per_page as usize), + ) + .map_err(|error| GatewayError::InvalidInput(error.to_string()))?, + ); let results_parsed = self .execute_with_session( @@ -142,6 +145,7 @@ impl ReportPort for GvmdAdapter { }, ) .await?; + ensure_report_result_scope(&results_parsed.items, id)?; report.results = results_parsed .items .into_iter() @@ -285,25 +289,27 @@ impl ReportPort for GvmdAdapter { report_id: &str, query: &ResultQuery, ) -> Result { - // Validate that the report_id is a valid UUID - let _ = parse_entity_id(report_id)?; + let scope_id = parse_entity_id(report_id)?; let filter_id = query .filter_id .as_deref() .map(parse_entity_id) .transpose()?; - let filter = self - .paginated_filter_resolving_filter_id( - session_token, - Some(&format!("report_id={report_id}")), + let saved_filter = self + .saved_filter_term(session_token, filter_id.as_ref()) + .await?; + // Keep wire semantics in rust-gvm: its protected scope control is + // independent of the caller's boolean expression and applies to counts. + let filter = Some( + gvm_gmp::compose_report_results_filter( + &scope_id, + saved_filter.as_deref(), query.filter_string.as_deref(), - filter_id.as_ref(), - query.page, - query.per_page, - &["report_id"], + GmpPagination::new(query.page as usize, query.per_page as usize), ) - .await?; + .map_err(|error| GatewayError::InvalidInput(error.to_string()))?, + ); let parsed = self .execute_with_session( @@ -321,6 +327,7 @@ impl ReportPort for GvmdAdapter { }, ) .await?; + ensure_report_result_scope(&parsed.items, report_id)?; let items = parsed .items .into_iter() @@ -709,3 +716,23 @@ fn unsupported_typed_report_detail_error(command: &str, resource: &str) -> Gatew "{resource} are not available because gvmd does not implement `{command}` on this backend version; the proxy does not emulate unsupported GMP commands" )) } + +// An endpoint-owned report identity must never be weakened by backend filtering. +// Fail the entire response rather than returning a cross-report page or quietly +// dropping rows and making pagination counts untrustworthy. +fn ensure_report_result_scope( + results: &[gvm_gmp::responses::ScanResult], + report_id: &str, +) -> Result<(), GatewayError> { + if results.iter().any(|result| { + result + .report + .as_ref() + .is_none_or(|report| !report.id.as_str().eq_ignore_ascii_case(report_id)) + }) { + return Err(GatewayError::BackendUnavailable( + "backend returned results outside the requested report".into(), + )); + } + Ok(()) +} diff --git a/crates/gvm-gateway-gvmd/tests/gvmd_adapter_test.rs b/crates/gvm-gateway-gvmd/tests/gvmd_adapter_test.rs index 65bfc099..ba5630ca 100644 --- a/crates/gvm-gateway-gvmd/tests/gvmd_adapter_test.rs +++ b/crates/gvm-gateway-gvmd/tests/gvmd_adapter_test.rs @@ -1855,7 +1855,7 @@ async fn gvmd_adapter_direct_lists_emit_backend_pagination_filter() { } ), "get_results", - "filter=\"report_id=550e8400-e29b-41d4-a716-446655440000 name=Target first=11 rows=10\"" + "filter=\"name=Target _and_report_id=550e8400-e29b-41d4-a716-446655440000 first=11 rows=10\"" ); assert_backend_pagination!( adapter, @@ -3966,7 +3966,7 @@ async fn gvmd_adapter_get_report_results_resolves_filter_id_into_inline_filter() .expect("get_results command should be recorded"); let xml = String::from_utf8(command.raw_xml().to_vec()).expect("xml command"); assert!(xml.contains( - "filter=\"threat=Alarm report_id=550e8400-e29b-41d4-a716-446655440000 severity>5 first=1 rows=25\"" + "filter=\"threat=Alarm severity>5 _and_report_id=550e8400-e29b-41d4-a716-446655440000 first=1 rows=25\"" )); assert!(!xml.contains("filter_id")); diff --git a/crates/gvm-gateway-gvmd/tests/report_scope.rs b/crates/gvm-gateway-gvmd/tests/report_scope.rs new file mode 100644 index 00000000..26e21481 --- /dev/null +++ b/crates/gvm-gateway-gvmd/tests/report_scope.rs @@ -0,0 +1,343 @@ +//! Regression coverage for endpoint-owned report isolation (issue #741). +use gvm_gateway_domain::{GatewayError, GetReportOpts, ReportPort, ResultQuery}; +use gvm_gateway_gvmd::GvmdAdapter; +use gvm_mock_server::{GmpVersion, MockGmpServer, ServerMode}; + +const PATH_REPORT: &str = "aabbccdd-0000-4000-8000-000000000001"; +const OTHER_REPORT: &str = "aabbccdd-0000-4000-8000-000000000002"; + +async fn adapter_with_result(report_id: &str) -> (GvmdAdapter, MockGmpServer) { + let response = format!( + r#"Scoped result8.0Report11"# + ); + adapter_with_results_xml(&response, GmpVersion::V22_8).await +} + +async fn adapter_with_results_xml( + response: &str, + version: GmpVersion, +) -> (GvmdAdapter, MockGmpServer) { + let report_response = format!( + r#"Path report"# + ); + let server = MockGmpServer::builder() + .mode(ServerMode::Fixture) + .version(version) + .override_response("get_reports", &report_response) + .override_response("get_results", response) + .unix_socket_auto() + .build() + .await + .expect("start fixture server"); + let adapter = GvmdAdapter::unix_socket(server.socket_path().expect("socket")); + adapter + .connect_session("scope-session", "admin", "admin") + .await + .expect("authenticate"); + (adapter, server) +} + +#[tokio::test] +async fn report_results_fail_closed_when_backend_returns_a_different_report() { + // A misbehaving backend must not leak rows or return misleading filtered + // counts, even when it responds with a syntactically successful payload. + let (adapter, server) = adapter_with_result(OTHER_REPORT).await; + let result = adapter + .get_report_results( + "scope-session", + PATH_REPORT, + &ResultQuery { + page: 1, + per_page: 25, + ..Default::default() + }, + ) + .await; + assert!( + matches!(result, Err(GatewayError::BackendUnavailable(detail)) + if detail == "backend returned results outside the requested report") + ); + server.shutdown().await; +} + +#[tokio::test] +async fn report_scope_accepts_equivalent_uuid_case_without_rewriting_payload() { + // UUID spelling is not identity: an uppercase requested path remains the + // same report while the server's original lowercase spelling is retained. + let (adapter, server) = adapter_with_result(PATH_REPORT).await; + let result = adapter + .get_report_results( + "scope-session", + &PATH_REPORT.to_uppercase(), + &ResultQuery { + page: 1, + per_page: 25, + ..Default::default() + }, + ) + .await + .expect("same report"); + assert_eq!(result.data.len(), 1); + assert_eq!( + result.data[0].report.as_ref().expect("report").id, + PATH_REPORT + ); + server.shutdown().await; +} + +#[tokio::test] +async fn protected_scope_applies_to_boolean_results_counts_and_saved_filters() { + // Each report has high and low findings. The low OR arm must not escape + // the path report, and pagination counts must be scoped before slicing. + let server = MockGmpServer::builder() + .mode(ServerMode::Stateful) + .version(GmpVersion::V22_8) + .seed(|store| { + for report in [PATH_REPORT, OTHER_REPORT] { + let report_id = uuid::Uuid::parse_str(report).unwrap(); + store.create(gvm_mock_server::Resource::with_id( + "report", "Report", report_id, + )); + for (index, severity) in [(0, "8.0"), (1, "5.0")] { + let mut result = gvm_mock_server::Resource::with_id( + "result", + "Finding", + uuid::Uuid::new_v5(&report_id, &[index]), + ); + result.set_attr("report_id", report); + result.set_attr("severity", severity); + store.create(result); + } + } + let mut filter = gvm_mock_server::Resource::with_id( + "filter", + "Saved alternative", + uuid::Uuid::parse_str("123e4567-e89b-12d3-a456-426614174000").unwrap(), + ); + filter.set_attr("term", "severity>7 OR severity<6"); + filter.set_attr("type", "result"); + store.create(filter); + }) + .unix_socket_auto() + .build() + .await + .unwrap(); + let adapter = GvmdAdapter::unix_socket(server.socket_path().unwrap()); + adapter + .connect_session("scope-session", "admin", "admin") + .await + .unwrap(); + for saved in [false, true] { + for page in [1, 2] { + let query = ResultQuery { + filter_string: (!saved).then(|| "severity>7 OR severity<6".to_string()), + filter_id: saved.then(|| "123e4567-e89b-12d3-a456-426614174000".to_string()), + page, + per_page: 1, + }; + let results = adapter + .get_report_results("scope-session", PATH_REPORT, &query) + .await + .unwrap(); + assert_eq!(results.pagination.total, 2, "saved={saved}, page={page}"); + assert_eq!(results.data.len(), 1); + assert_eq!(results.data[0].report.as_ref().unwrap().id, PATH_REPORT); + } + } + server.shutdown().await; +} + +#[tokio::test] +async fn invalid_report_filter_controls_fail_before_result_execution() { + // Unsupported comparators and endpoint-owned controls are client errors, + // not silently ignored predicates or backend result requests. + let (adapter, server) = adapter_with_result(PATH_REPORT).await; + for filter in [ + "severity>=7", + "severity<=7", + "severity==7", + "report_id=x", + "_and_report_id=x", + "first=9", + "rows=100", + ] { + server.clear_history(); + let result = adapter + .get_report_results( + "scope-session", + PATH_REPORT, + &ResultQuery { + filter_string: Some(filter.to_string()), + page: 1, + per_page: 25, + ..Default::default() + }, + ) + .await; + assert!( + matches!(result, Err(GatewayError::InvalidInput(_))), + "{filter}: {result:?}" + ); + assert!(!server + .command_history() + .iter() + .any(|record| record.command_name() == "get_results")); + } + server.shutdown().await; +} + +#[tokio::test] +async fn quote_disguised_scope_and_window_overrides_never_reach_result_transport() { + // These are not literals in gvmd: apostrophes/backslashes do not quote or + // escape, and an embedded double quote does not open a literal. Validate + // both resolved saved terms and inline terms before any result request. + for term in [ + "name='benign _and_report_id=other'", + r#"name="benign\" _and_report_id=other x="end""#, + r#"name=ab"cd _and_report_id=other x="end""#, + "name='benign rows=99'", + r#"name="benign\" first=99 x="end""#, + "name='severity>=5'", + r#"name="benign\" severity<=5 x="end""#, + ] { + let filter_id = "123e4567-e89b-12d3-a456-426614174000"; + let server = MockGmpServer::builder() + .mode(ServerMode::Stateful) + .version(GmpVersion::V22_8) + .seed(|store| { + let mut filter = gvm_mock_server::Resource::with_id( + "filter", + "Untrusted saved filter", + uuid::Uuid::parse_str(filter_id).unwrap(), + ); + filter.set_attr("term", term); + filter.set_attr("type", "result"); + store.create(filter); + }) + .unix_socket_auto() + .build() + .await + .unwrap(); + let adapter = GvmdAdapter::unix_socket(server.socket_path().unwrap()); + adapter + .connect_session("scope-session", "admin", "admin") + .await + .unwrap(); + for saved in [false, true] { + server.clear_history(); + let result = adapter + .get_report_results( + "scope-session", + PATH_REPORT, + &ResultQuery { + filter_string: (!saved).then(|| term.to_string()), + filter_id: saved.then(|| filter_id.to_string()), + page: 1, + per_page: 25, + }, + ) + .await; + assert!( + matches!(result, Err(GatewayError::InvalidInput(_))), + "saved={saved}, term={term}: {result:?}" + ); + let history = server.command_history(); + assert_eq!( + history + .iter() + .any(|record| record.command_name() == "get_filters"), + saved, + "saved terms must be resolved before validation" + ); + assert!( + !history + .iter() + .any(|record| record.command_name() == "get_results"), + "saved={saved}, term={term}: unsafe text reached result transport" + ); + } + server.shutdown().await; + } +} + +#[tokio::test] +async fn real_quoted_filter_literals_still_reach_result_transport() { + // The strict upstream boundary must not reject reserved/operator spellings + // inside genuine double-quoted literals. Fixture playback isolates gateway + // dispatch from the deliberately bounded stateful mock predicate parser. + let (adapter, server) = adapter_with_result(PATH_REPORT).await; + for term in [ + r#"name="_and_report_id=other rows=99 severity>=5""#, + r#"name="ends in backslash\""#, + "name=O'Brien", + ] { + server.clear_history(); + let result = adapter + .get_report_results( + "scope-session", + PATH_REPORT, + &ResultQuery { + filter_string: Some(term.to_string()), + page: 1, + per_page: 25, + ..Default::default() + }, + ) + .await + .expect("supported literal is dispatched"); + assert_eq!(result.data.len(), 1); + assert!(server + .command_history() + .iter() + .any(|record| record.command_name() == "get_results")); + } + server.shutdown().await; +} + +#[tokio::test] +async fn missing_report_reference_is_rejected_for_scoped_and_embedded_results() { + // A successful payload is not proof of isolation. Without a report ID, no + // row can be verified against either endpoint's path-owned identity. + let response = r#"Unverifiable finding8.011"#; + for embedded in [false, true] { + // 22.7 exercises the supported older-backend read path: structured + // snapshot enrichment is unavailable, but result isolation still applies. + let (adapter, server) = adapter_with_results_xml(response, GmpVersion::V22_7).await; + let result = if embedded { + adapter + .get_report( + "scope-session", + PATH_REPORT, + &GetReportOpts { + page: 1, + per_page: 25, + }, + ) + .await + .map(|_| ()) + } else { + adapter + .get_report_results( + "scope-session", + PATH_REPORT, + &ResultQuery { + page: 1, + per_page: 25, + ..Default::default() + }, + ) + .await + .map(|_| ()) + }; + assert!( + matches!(result, Err(GatewayError::BackendUnavailable(ref detail)) + if detail == "backend returned results outside the requested report"), + "embedded={embedded}: {result:?}" + ); + assert!(server + .command_history() + .iter() + .any(|entry| entry.command_name() == "get_results")); + server.shutdown().await; + } +} diff --git a/crates/gvm-gateway-rest/src/reports.rs b/crates/gvm-gateway-rest/src/reports.rs index e67daf65..5a040712 100644 --- a/crates/gvm-gateway-rest/src/reports.rs +++ b/crates/gvm-gateway-rest/src/reports.rs @@ -1338,13 +1338,18 @@ pub(crate) fn get_report_results_docs(op: TransformOperation<'_>) -> TransformOp .id("getReportResults") .tag("Reports") .summary("Get paginated results for a report") - .description("Returns a paginated list of results for a specific report.") + .description("Returns results and counts scoped to the report in the path, including boolean filters. Reserved report/pagination controls and unsupported inclusive comparisons such as severity>=7 return 400. Backend rows with missing or mismatched report references fail as 502 rather than being returned or silently discarded.") .security_requirement("bearerAuth") .input::<(Path, Query)>() .response_with::<200, Json, _>(ok_json("Paginated list of results")); + let op = problem_response::<400>(op, "Invalid filter or request"); let op = problem_response::<401>(op, "Authentication required or session expired"); - problem_response::<404>(op, "Resource not found") + let op = problem_response::<404>(op, "Resource not found"); + problem_response::<502>( + op, + "Backend response violates report scope or is unavailable", + ) } /// OpenAPI transform for `GET /api/v1/reports/{id}/vulnerabilities`. diff --git a/spec/rest-api/reports.yaml b/spec/rest-api/reports.yaml index 23adfc69..3ced772e 100644 --- a/spec/rest-api/reports.yaml +++ b/spec/rest-api/reports.yaml @@ -141,6 +141,15 @@ paths: operationId: getReportResults tags: [Reports] summary: Get paginated results for a report + description: | + Results and counts remain restricted to the report in the path, including + when caller or saved filters contain boolean alternatives. Endpoint-owned + report scope and pagination controls cannot be overridden. Supported + comparison operators retain GMP semantics; unsupported inclusive operators + such as `severity>=7` or `severity<=7` return 400 rather than being silently + ignored. Use supported strict or equality comparisons explicitly. + A backend response with missing or mismatched row report references fails as 502; + the gateway never drops those rows while retaining misleading counts. parameters: - $ref: "./common.yaml#/components/parameters/FilterString" - $ref: "./common.yaml#/components/parameters/FilterId" @@ -153,6 +162,8 @@ paths: application/json: schema: $ref: "./results.yaml#/components/schemas/ResultList" + "400": + $ref: "./common.yaml#/components/responses/BadRequest" "401": $ref: "./common.yaml#/components/responses/Unauthorized" "502": diff --git a/spec/rest-api/test-spec.md b/spec/rest-api/test-spec.md index 97e72ead..9e70af4a 100644 --- a/spec/rest-api/test-spec.md +++ b/spec/rest-api/test-spec.md @@ -370,3 +370,19 @@ raw result/catalog refs with unknown types and escaped opaque identifiers. Generated/curated OpenAPI parity remains required. These fixtures are not live Agent/gvmd or KEV-feed qualification. KEV-specific tests await actual producer and typed library contracts; absence is never a synthetic negative observation. + + +## Report-result scope and comparison contract (#741) + +- Seed two reports with overlapping high/low severities. Both strict severity + predicates and explicit boolean alternatives must return only path-report rows, + with counts and pagination computed in that scope. +- Compose saved and inline filters through the typed upstream scope helper; + reject attempts to replace report identity or endpoint-owned pagination. +- Unsupported inclusive `>=`/`<=` comparators outside quoted literal values + return 400 before the results operation, never silently ignored success. +- A successful backend response with a missing report association or another + report ID returns a sanitized 502 for both scoped-result and embedded-report + loading, not partial data with unadjusted counts. +- Upper/lowercase UUID spellings identify the same report. Keep returned payload + spelling and optional source metadata unchanged. diff --git a/worklog.md b/worklog.md index a2e8f93c..b5c2249e 100644 --- a/worklog.md +++ b/worklog.md @@ -87,6 +87,26 @@ - #742 independent review repeated immutable gvmd source/schema and typed-model search: refs/EPSS producers present, no KEV contract found. Corrected producer source anchors. Following explicit parent authorization and fresh authenticated all-state duplicate searches (KEV and “known exploited”), filed gvmd #3254 and rust-gvm #873, and cross-linked API #742 comment 7018718816. No runtime branch publication. Expanded raw refs regression to diverse feed types, escaped URL, CVE compatibility and duplicate/order retention. - #742 focused typed/REST collection regressions pass; required full-workspace Clippy, formatting and docs validation pass. Full workspace rerun pending final result. - Independent read-only review of parent b02/732-agent-os-metadata (dcd4706; #730–732) against issue acceptance and specs found no concrete blocker in scheduler compatibility/range mapping, inventory-token authentication/capabilities/status/confidentiality/cache, or OS omission/open-string mapping. Parent worktree and branches were not changed. + +# API #741 report result isolation + +- 2026-11-19: Rooted at PR740 head9a5664f. Read contract/code and pinned local gvmd producer. +- Identified protected `_and_report_id` control in gvmd source; filed rust-gvm#871 for typed composition and strict comparator validation, rather than parsing GMP in gateway. +- Adding defense-in-depth response scope invariant: backend cross-report rows fail the whole page with sanitized502; UUID case-equivalent identities remain accepted. +- Waiting on upstream helper plus shared immutable dependency adoption before final adapter integration/testing/publication. + +- Adopted upstream immutable feature stack b6f33da; reviewed 270-method typed facade (three newly blocked REST adopters). Building isolated target; native compiler provisioned inside workspace only. +- Integrated typed compose_report_results_filter at both report result read paths; saved terms resolve first and no filter_id is forwarded. Added transport regressions for caller/saved boolean alternatives, report-scoped counts across pages, and rejection before result execution for unsupported or endpoint-owned predicates. +- Focused testing initially used CLI path patches; final manifest and regenerated lockfile now pin all five upstream crates to published immutable 64b9d01820c8b4715265bbae06293462c24fdfe7 (rust-gvm#872), without local patches. All 120 focused adapter/scope tests and strict workspace Clippy passed; full workspace tests running. + +- Parent full-suite retries exposed two stale dependency-adoption expectations: application fixture intentionally lacks severity (kept absent), and the exact dependency invariant now pins64b9d018. Both corrected without weakening production contracts. The fixture correction is already present in stack730 and need not be cherry-picked into final741. Full-suite retry in progress. +- Full workspace `cargo test --workspace --locked` completed successfully, including OpenAPI parity and doctests; zero failures. Strict workspace Clippy was already successful at this code state. Integration into issue-specific final stack pending sibling slice completion. + +## API #741 quote-override transport follow-up +- Independent upstream parser review corrected quote semantics in rust-gvm #872 at fa990ad0c8aab4609dec7999f01e9922713fe71b. Updated all five manifest/lock pins and exact architecture invariant; no local protocol parsing or parent edits. +- Added transport regressions for disguised scope/window controls and inclusive operators in both inline and resolved saved terms; assert InvalidInput and absence of get_results. Real double-quoted literals, terminal backslashes and ordinary apostrophes remain dispatchable using fixture playback. +- Confirmed negative regression fails against 64b9d018 (old helper dispatches and returns an empty successful page). At fa990ad all six report-scope transport tests pass (including OR, counts/paging, saved and inline reserved/quote cases), as do all 22 architecture tests. Exact manifest/lock coherence and fmt/diff checks pass. +- Required `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings` passed (only pre-existing Cargo manifest unused-dependency warnings). Tooling sourced /workspace/api-agent-env, isolated CARGO_TARGET_DIR=/workspace/.cache/api-filter-target. No parent checkout or specifications modified; no push/PR requested. ## Review correction #730 (2026-11-20) Reject explicit null maxDelaySeconds on all agent schedule and group inputs; preserve omission, zero and GMP bounds. Add HTTP 400/no-backend-dispatch regressions and REST boundary coverage. @@ -115,6 +135,11 @@ Validation (source /workspace/api-agent-env; CARGO_TARGET_DIR=/workspace/.cache/ - Final verification: full REST suite 214 passed (including generated no-store schema), gateway contract 30 passed (including served-generated/curated header-schema parity); fmt check and required strict workspace/all-target/all-feature Clippy passed. Used an isolated copy of the existing report cache to avoid other worktree artifacts; no dependency changes. +## 2026-11-20 — issue #741 review +- Review correctly identified that successful rows missing their report association bypassed the response-side scope check. +- Reject absent and mismatched report identities before conversion for both report-results and embedded-report paths; preserve case-equivalent UUID acceptance. +- Added successful-response fixture coverage without a report association through both typed adapter paths. Updated the published report error contract to describe unverifiable rows. + ## PR #743 response delay review (2026-11-20) - Isolated worktree based on exact a1c3f29611a2e37611e64fba38c4887a5ed95625; no shared stack edits.