From 64b9d01820c8b4715265bbae06293462c24fdfe7 Mon Sep 17 00:00:00 2001 From: hive-bumblebee <278179999+hive-bumblebee@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:43:14 +0000 Subject: [PATCH 1/2] fix(gmp): compose protected report-result filters (#871) --- .../tests/result_canonical_integration.rs | 62 +++++++++ crates/gvm-gmp/src/filtering.rs | 122 +++++++++++++++++- crates/gvm-gmp/src/lib.rs | 5 +- crates/gvm-gmp/tests/report_results_filter.rs | 122 ++++++++++++++++++ .../gvm-mock-server/src/stateful_results.rs | 74 ++++++++--- .../tests/stateful_result_conformance.rs | 47 +++++++ docs/report-results-filter-gvmd-evidence.md | 18 +++ worklog.md | 12 ++ 8 files changed, 444 insertions(+), 18 deletions(-) create mode 100644 crates/gvm-gmp/tests/report_results_filter.rs create mode 100644 docs/report-results-filter-gvmd-evidence.md diff --git a/crates/gvm-client/tests/result_canonical_integration.rs b/crates/gvm-client/tests/result_canonical_integration.rs index fba2f039..641745cf 100644 --- a/crates/gvm-client/tests/result_canonical_integration.rs +++ b/crates/gvm-client/tests/result_canonical_integration.rs @@ -254,3 +254,65 @@ async fn both_facades_preserve_result_parse_context() { } server.shutdown().await; } + +#[tokio::test] +async fn report_filter_helper_executes_with_protected_scope_and_typed_counts() { + use gvm_gmp::{compose_report_results_filter, Pagination}; + use gvm_mock_server::Resource; + + let report = Resource::new("report", "Selected report"); + let report_id = id(&report.id.to_string()); + let other_report = Resource::new("report", "Other report"); + let server = MockGmpServer::builder() + .mode(ServerMode::Stateful) + .version(MockVersion::V22_8) + .credentials("admin", "admin") + .seed(move |store| { + for (name, severity, selected_report) in [ + ("Selected high", "8.0", report.id), + ("Selected medium", "5.0", report.id), + ("Unrelated high", "9.0", other_report.id), + ] { + let mut result = Resource::new("result", name); + result.set_attr("severity", severity); + result.set_attr("qod", "95"); + result.set_attr("report_id", &selected_report.to_string()); + store.seed(result); + } + store.seed(report.clone()); + store.seed(other_report.clone()); + }) + .unix_socket_auto() + .build() + .await + .expect("server starts"); + let mut client = client(&server).await; + client + .authenticate(gvm_gmp::commands::authentication::AuthenticateRequest::new( + "admin", "admin", + )) + .await + .expect("authenticate"); + for (page, expected_name) in [(1, "Selected high"), (2, "Selected medium")] { + let filter = compose_report_results_filter( + &report_id, + Some("severity>7"), + Some("OR severity<6 sort=name"), + Pagination::new(page, 1), + ) + .expect("strict filter"); + let response = client + .execute(GetResultsRequest { + filter_string: Some(filter), + get_counts: Some(true), + ..GetResultsRequest::default() + }) + .await + .expect("scoped result request"); + assert_eq!(response.items.len(), 1); + assert_eq!(response.items[0].meta.name, expected_name); + assert_eq!(response.counts.filtered, Some(2)); + assert_eq!(response.counts.page, Some(1)); + } + server.shutdown().await; +} diff --git a/crates/gvm-gmp/src/filtering.rs b/crates/gvm-gmp/src/filtering.rs index a807a726..1875b5f0 100644 --- a/crates/gvm-gmp/src/filtering.rs +++ b/crates/gvm-gmp/src/filtering.rs @@ -110,6 +110,126 @@ pub enum FilterFragmentError { }, } +/// Errors from strict report-result filter composition (legacy helpers remain permissive). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ReportResultsFilterError { + /// The report identifier is invalid (including unchecked deserialized values). + #[error("invalid report identifier: {0}")] + InvalidReportId(#[from] crate::types::EntityIdError), + /// A caller attempted to replace endpoint-owned scope or pagination. + #[error(transparent)] + Fragment(#[from] FilterFragmentError), + /// gvmd supports single-character relations, not inclusive or compound comparisons. + #[error("unsupported or malformed filter comparator near byte {offset}; use a single =, >, <, ~ or : relation (>= and <= are not supported by gvmd)")] + Comparator { + /// Byte offset of the invalid comparator. + offset: usize, + }, + /// A quoted literal was not closed. + #[error("unterminated quoted filter literal")] + UnterminatedQuote, +} + +/// Compose a strict, report-isolated result filter with endpoint-owned pagination. +/// +/// `saved_filter` is resolved saved-filter **term text**, not its identifier. Pass +/// the returned text as `GetResultsRequest.filter_string` with `filter_id: None`: +/// gvmd otherwise replaces inline text with the saved filter. Both fragments are +/// validated independently. Boolean predicates retain gvmd's own semantics; +/// report isolation uses its independent report restriction, not a boolean term. +/// This is not a full filter grammar validator: unknown fields remain gvmd-owned. +/// +/// # Errors +/// Rejects caller scope/pagination controls, unsupported compound comparators, +/// and unterminated quoted literals. Existing raw helpers remain unchanged. +pub fn compose_report_results_filter( + report_id: &crate::types::EntityId, + saved_filter: Option<&str>, + inline_filter: Option<&str>, + pagination: Pagination, +) -> Result { + crate::types::EntityId::new(report_id.as_str())?; + let mut clauses = Vec::new(); + for fragment in [saved_filter, inline_filter].into_iter().flatten() { + let fragment = FilterFragment::new( + fragment, + &[ + "report_id", + "_report_id", + "_and_report_id", + "__and_report_id", + "_first", + "_rows", + "max", + "offset", + "limit", + "page", + "per_page", + "ignore_pagination", + "_ignore_pagination", + ], + )?; + validate_strict_comparators(fragment.as_str())?; + if !fragment.as_str().is_empty() { + clauses.push(fragment.into_inner()); + } + } + let (first, rows) = pagination.gvmd_window(); + clauses.push(format!( + "_and_report_id={report_id} first={first} rows={rows}" + )); + Ok(clauses.join(" ")) +} + +fn validate_strict_comparators(fragment: &str) -> Result<(), ReportResultsFilterError> { + let mut quote = None; + let mut escaped = false; + let mut previous_nonspace = None; + let mut token_operator = false; + for (offset, byte) in fragment.bytes().enumerate() { + if let Some(active) = quote { + if escaped { + escaped = false; + } else if byte == b'\\' { + escaped = true; + } else if byte == active { + quote = None; + } + continue; + } + if matches!(byte, b'"' | b'\'') { + quote = Some(byte); + previous_nonspace = Some(byte); + continue; + } + if byte.is_ascii_whitespace() { + token_operator = false; + continue; + } + if matches!(byte, b'=' | b'>' | b'<' | b'~' | b':' | b'!') { + if byte == b'!' + || token_operator + || previous_nonspace.is_some_and(|previous| { + matches!(previous, b'=' | b'>' | b'<' | b'~' | b':' | b'!') + }) + { + return Err(ReportResultsFilterError::Comparator { offset }); + } + token_operator = true; + } + previous_nonspace = Some(byte); + } + if quote.is_some() { + return Err(ReportResultsFilterError::UnterminatedQuote); + } + if previous_nonspace.is_some_and(|byte| matches!(byte, b'=' | b'>' | b'<' | b'~' | b':')) { + return Err(ReportResultsFilterError::Comparator { + offset: fragment.len().saturating_sub(1), + }); + } + Ok(()) +} + /// Builder for gvmd filter strings that append pagination terms centrally. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct PaginatedFilter { @@ -291,7 +411,7 @@ fn skip_grouping_and_whitespace(bytes: &[u8], mut index: usize) -> usize { } fn is_operator_byte(byte: u8) -> bool { - matches!(byte, b'=' | b'<' | b'>' | b'~') + matches!(byte, b'=' | b'<' | b'>' | b'~' | b':') } #[cfg(test)] diff --git a/crates/gvm-gmp/src/lib.rs b/crates/gvm-gmp/src/lib.rs index a7a0fdc5..92f7d7b8 100644 --- a/crates/gvm-gmp/src/lib.rs +++ b/crates/gvm-gmp/src/lib.rs @@ -33,7 +33,10 @@ pub use execution::{ GmpStreamingResponse, }; /// Re-exported gvmd filter helpers. -pub use filtering::{FilterFragment, FilterFragmentError, PaginatedFilter, Pagination}; +pub use filtering::{ + compose_report_results_filter, FilterFragment, FilterFragmentError, PaginatedFilter, + Pagination, ReportResultsFilterError, +}; /// Re-exported semantic GMP server-error classification. pub use responses::GmpServerErrorKind; /// Re-exported typed schedule values. diff --git a/crates/gvm-gmp/tests/report_results_filter.rs b/crates/gvm-gmp/tests/report_results_filter.rs new file mode 100644 index 00000000..b285e4dd --- /dev/null +++ b/crates/gvm-gmp/tests/report_results_filter.rs @@ -0,0 +1,122 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later +// SPDX-FileCopyrightText: 2026 Greenbone AG + +#![allow(missing_docs)] +use gvm_gmp::commands::results::GetResultsRequest; +use gvm_gmp::{ + compose_report_results_filter, EntityId, GmpRequestCodec, GmpVersion, PaginatedFilter, + Pagination, ReportResultsFilterError, +}; + +fn compose(saved: Option<&str>, inline: Option<&str>) -> Result { + compose_report_results_filter( + &EntityId::new("report-1").expect("id"), + saved, + inline, + Pagination::new(2, 3), + ) +} + +#[test] +fn protected_scope_composes_saved_inline_and_window() { + assert_eq!( + compose(Some(" severity>5 "), Some("severity<9 OR severity=10")).expect("filter"), + "severity>5 severity<9 OR severity=10 _and_report_id=report-1 first=4 rows=3" + ); + assert_eq!( + compose(None, Some(" ")).expect("filter"), + "_and_report_id=report-1 first=4 rows=3" + ); +} + +#[test] +fn both_inputs_reject_scope_and_pagination_overrides_quote_aware() { + for key in [ + "report_id", + "_report_id", + "_and_report_id", + "__and_report_id", + "first", + "rows", + "_first", + "_rows", + "max", + "offset", + "limit", + "page", + "per_page", + "ignore_pagination", + "_ignore_pagination", + ] { + for operator in ["=", ">", "<", "~", ":"] { + let fragment = format!("OR ({key} {operator} other)"); + for (saved, inline) in [ + (Some(fragment.as_str()), None), + (None, Some(fragment.as_str())), + ] { + assert!(compose(saved, inline).is_err(), "{fragment}"); + } + } + } + let literal = r#"name="a\" first=1 severity>=5" comment='rows=10 _and_report_id=x <=5'"#; + assert!(compose(None, Some(literal)).is_ok()); + assert!(compose(None, Some(r#"name="literal" ROWS=2"#)).is_err()); +} + +#[test] +fn strict_comparators_do_not_change_legacy_escape_hatch() { + for fragment in [ + "severity>=5", + "severity<=5", + "severity==5", + "severity=>5", + "severity!=5", + "severity><5", + "severity> =5", + "severity>5<9", + "severity>", + "severity=", + ] { + assert!( + matches!( + compose(None, Some(fragment)), + Err(ReportResultsFilterError::Comparator { .. }) + ), + "{fragment}" + ); + assert!(PaginatedFilter::new() + .with_filter_string(Some(fragment)) + .build() + .is_some()); + } + for fragment in [ + "severity>5", + "severity<9", + "name~foo", + "name:foo", + r#"name="severity>=5""#, + r#"comment='x <= 5'"#, + ] { + assert!(compose(None, Some(fragment)).is_ok(), "{fragment}"); + } + assert_eq!( + compose(Some(r#"name="oops"#), None), + Err(ReportResultsFilterError::UnterminatedQuote) + ); +} + +#[test] +fn composed_text_uses_existing_request_xml_escaping() { + let request = GetResultsRequest { + filter_string: Some( + compose(Some("severity>5"), Some(r#"name="a&b" severity<9"#)).expect("filter"), + ), + ..GetResultsRequest::default() + }; + let xml = String::from_utf8(request.encode(GmpVersion(22, 8)).expect("encode")).expect("utf8"); + assert!(xml.contains("severity>5")); + assert!(xml.contains("severity<9")); + assert!(xml.contains("a&b")); + assert!(xml.contains("_and_report_id=report-1")); + assert!(!xml.contains("filt_id=")); +} diff --git a/crates/gvm-mock-server/src/stateful_results.rs b/crates/gvm-mock-server/src/stateful_results.rs index 9ea83f15..fa0433c5 100644 --- a/crates/gvm-mock-server/src/stateful_results.rs +++ b/crates/gvm-mock-server/src/stateful_results.rs @@ -30,7 +30,8 @@ struct Predicate { #[derive(Debug)] struct ResultQuery { - predicates: Vec, + predicates: Vec>, + report_restriction: Option, first: usize, max: usize, sort: String, @@ -44,7 +45,8 @@ struct ResultQuery { impl Default for ResultQuery { fn default() -> Self { Self { - predicates: Vec::new(), + predicates: vec![Vec::new()], + report_restriction: None, first: 1, max: DEFAULT_MAX_ROWS, sort: "id".to_string(), @@ -142,9 +144,22 @@ fn effective_filter(cmd: &ParsedCommand, store: &ResourceStore) -> Result Result { let mut query = ResultQuery::default(); + let mut conjunction = false; for token in filter.split_whitespace() { + if token.eq_ignore_ascii_case("or") { + conjunction = false; + continue; + } + if token.eq_ignore_ascii_case("and") { + conjunction = true; + continue; + } let (field, relation, value) = split_predicate(token)?; match field { + "_and_report_id" => { + require_equal(relation, field)?; + query.report_restriction = Some(value.to_string()); + } "first" => { require_equal(relation, field)?; query.first = value @@ -191,19 +206,29 @@ fn parse_result_filter(filter: &str) -> Result { } "severity" | "qod" => { validate_finite_number(value, field)?; - query.predicates.push(Predicate { - field: field.to_string(), - relation, - value: value.to_string(), - }); + append_predicate( + &mut query.predicates, + conjunction, + Predicate { + field: field.to_string(), + relation, + value: value.to_string(), + }, + ); + conjunction = false; } "id" | "uuid" | "name" | "host" | "port" | "threat" | "task_id" | "report_id" => { require_equal(relation, field)?; - query.predicates.push(Predicate { - field: field.to_string(), - relation, - value: value.to_string(), - }); + append_predicate( + &mut query.predicates, + conjunction, + Predicate { + field: field.to_string(), + relation, + value: value.to_string(), + }, + ); + conjunction = false; } _ => return Err(format!("Unsupported result filter field '{field}'")), } @@ -211,6 +236,16 @@ fn parse_result_filter(filter: &str) -> Result { Ok(query) } +// Ordinary predicates default to OR in gvmd; explicit AND binds within a group. +fn append_predicate(groups: &mut Vec>, conjunction: bool, predicate: Predicate) { + if !conjunction && groups.last().is_some_and(|group| !group.is_empty()) { + groups.push(Vec::new()); + } + if let Some(group) = groups.last_mut() { + group.push(predicate); + } +} + fn split_predicate(token: &str) -> Result<(&str, Relation, &str), String> { let Some((index, operator)) = token .char_indices() @@ -295,11 +330,18 @@ fn select_results( .into_iter() .map(|result| evaluate_result(result, store, query.apply_overrides)) .filter(|result| result_qod(&result.resource) >= query.min_qod) + // gvmd passes this restriction independently of the boolean expression. + .filter(|result| { + query.report_restriction.as_ref().is_none_or(|report_id| { + result.resource.attr("report_id") == Some(report_id.as_str()) + }) + }) .filter(|result| { - query - .predicates - .iter() - .all(|predicate| result_matches(result, predicate, store)) + query.predicates.iter().any(|group| { + group + .iter() + .all(|predicate| result_matches(result, predicate, store)) + }) }) .collect::>(); sort_results(&mut resources, query); diff --git a/crates/gvm-mock-server/tests/stateful_result_conformance.rs b/crates/gvm-mock-server/tests/stateful_result_conformance.rs index 9c15a09c..d54b30e5 100644 --- a/crates/gvm-mock-server/tests/stateful_result_conformance.rs +++ b/crates/gvm-mock-server/tests/stateful_result_conformance.rs @@ -619,3 +619,50 @@ async fn equal_sort_keys_use_id_ties_across_insertion_orders_and_pages() { server.shutdown().await; } } + +#[tokio::test] +async fn protected_report_scope_is_independent_of_boolean_filters_and_pagination() { + let (server, _) = seeded_server().await; + let mut stream = connect_and_auth(&server).await; + // Ordinary report_id is a boolean predicate: the second OR arm escapes it. + let ordinary = send_recv(&mut stream, format!( + "" + )).await; + assert!(text(&ordinary).contains(&RESULT_1.to_string())); + assert!(text(&ordinary).contains(&RESULT_2.to_string())); + assert!(text(&ordinary).contains("2")); + + for predicates in [ + "severity>7 OR severity<6", + "severity>7 severity<6", + "severity>7 AND severity<9", + "severity>99 OR severity<6", + ] { + let response = send_recv(&mut stream, format!( + "" + )).await; + let response = text(&response); + assert!(!response.contains(&RESULT_2.to_string()), "{response}"); + assert!( + !response.contains(&RESULT_LOW_QOD.to_string()), + "{response}" + ); + if predicates.starts_with("severity>99") { + assert!(!response.contains(&RESULT_1.to_string())); + assert!(response.contains("0")); + } else { + assert!(response.contains(&RESULT_1.to_string())); + assert!(response.contains("1")); + assert!(response.contains("1")); + } + } + let second_page = send_recv(&mut stream, format!( + "" + )).await; + let second_page = text(&second_page); + assert!(!second_page.contains(&RESULT_1.to_string())); + assert!(!second_page.contains(&RESULT_2.to_string())); + assert!(second_page.contains("1")); + assert!(second_page.contains("0")); + server.shutdown().await; +} diff --git a/docs/report-results-filter-gvmd-evidence.md b/docs/report-results-filter-gvmd-evidence.md new file mode 100644 index 00000000..255e0c7b --- /dev/null +++ b/docs/report-results-filter-gvmd-evidence.md @@ -0,0 +1,18 @@ +# Protected report-result filtering (#871, API #741) + +Public source pin: gvmd `f2d5c97bcb2d3bdeac879c865ebe9cf9c998f766`. + +- `src/gmp.c:17453–17479` extracts `_and_report_id` and passes the resolved report as an independent `init_result_get_iterator` restriction. A normal `report_id` predicate does not provide this guarantee. +- `src/manage_sql_filters.c:get_join` and `filter_term_sql` use OR between ordinary predicates unless explicitly preceded by AND. The scope restriction must not be part of that expression. +- `src/manage_filter_utils.c:parse_column_relation` models single-character `=`, `>`, `<`, `~`, `:` relations. Inclusive/compound syntax is not a reliable numeric comparison. +- `filter_term_value` also recognizes an underscore-prefixed keyword alias; the strict composer reserves `_report_id`, `_first`, `_rows`, and `__and_report_id` as well as canonical controls. + +## Additive typed API + +`gvm_gmp::compose_report_results_filter(&EntityId, Option<&str>, Option<&str>, Pagination) -> Result` takes a report identity, resolved saved-filter term text, inline term text, and page/per-page window. It always returns nonempty scope/window text. Pass it as `GetResultsRequest.filter_string`, leaving `filter_id` unset: gvmd saved-filter selection replaces rather than augments inline terms. Both fragments are independently validated before appending protected scope and pagination. Boolean expression semantics are retained (including default OR); saved and inline text are not parenthesized or rewritten into a different grammar. + +The new error type leaves exhaustive matches on existing `FilterFragmentError` source-compatible. Existing raw `PaginatedFilter` and request escape hatches remain permissive. The strict helper rejects compound or malformed comparisons outside quoted literals and unclosed quotes; it is not a complete gvmd grammar/field validator. Scope and pagination keys are rejected quote-aware, including conservative pagination aliases. + +## Bounded verification + +The stateful result mock models numeric severity/QoD predicates, equality fields, default/explicit OR, explicit AND groups, independent protected report restriction, counts and pagination. It deliberately does not implement the full gvmd filter engine (parentheses, NOT, regexp/approximate matching, arbitrary fields, user ACLs, or database behavior). Typed composition/encoding tests cover quoted literals and wire escaping separately. This is pinned-source-shaped deterministic qualification, not live gvmd validation. diff --git a/worklog.md b/worklog.md index 04716b4a..d01802a6 100644 --- a/worklog.md +++ b/worklog.md @@ -64,3 +64,15 @@ - Integrated both #861/#866 review corrections through all six upper branches without rewriting published history; exact branch heads saved in review-restack.json. - Full combined workspace verification with serde and socket tests: 1,634 passed across 128 targets, zero failures, one pre-existing ignored doctest. Strict socket-enabled workspace/all-target Clippy, formatting and diff checks passed. - Documentation matrix links APIs, feature evidence and mock limits; downstream REST contract supplement remains explicitly planned, not an implemented OpenAPI claim. +# Protected report-result filtering (#871 / API #741) + +- Created isolated worktree at b6f33da (PR #868 stack), branch b02/protected-report-filter. +- Read repository guidance and pinned gvmd gmp.c independent `_and_report_id` restriction and manage_filter_utils single-character relations. +- New additive helper interface written early to /workspace/reviews/api-727-742/upstream-filter-interface.md; returns Result (always nonempty scope+window), no existing error/request/facade shape changes. +- Implementing strict fragment boundary and bounded mock OR/report restriction tests. No live gvmd qualification claimed. + +- Implemented `compose_report_results_filter(&EntityId, Option<&str>, Option<&str>, Pagination) -> Result` plus pinned source/bounded-model documentation. +- Revalidates EntityId; quote-aware strict boundary rejects scope and pagination overrides including gvmd underscore aliases, unsupported compound/inclusive operators and unclosed literals. No request/facade changes. +- Corrected bounded result mock to source-supported default OR / explicit AND groups, with protected report restriction evaluated independently before counts/paging. +- Verification: GMP filtering unit tests (23), result request tests (7), new strict composition tests (4), stateful result conformance (6), typed client result integration (6); fmt check and strict focused Clippy on all touched libraries/test targets passed. Broad all-target Clippy additionally attempted and blocked by pre-existing missing crate docs in agent_schedule_serde_test.rs; no unrelated file modified. Existing manifest unused-workspace-dependency warnings remain. +- Tests use /workspace/866-test-env with CARGO_TARGET_DIR=/workspace/.cache/upstream-filter-target. No live gvmd qualification. From fa990ad0c8aab4609dec7999f01e9922713fe71b Mon Sep 17 00:00:00 2001 From: hive-bumblebee <278179999+hive-bumblebee@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:48:22 +0000 Subject: [PATCH 2/2] fix(gmp): align protected filter quotes with gvmd parser --- crates/gvm-gmp/src/filtering.rs | 100 +++++++++++++----- crates/gvm-gmp/tests/report_results_filter.rs | 35 +++++- docs/report-results-filter-gvmd-evidence.md | 2 +- worklog.md | 5 + 4 files changed, 115 insertions(+), 27 deletions(-) diff --git a/crates/gvm-gmp/src/filtering.rs b/crates/gvm-gmp/src/filtering.rs index 1875b5f0..f5a32291 100644 --- a/crates/gvm-gmp/src/filtering.rs +++ b/crates/gvm-gmp/src/filtering.rs @@ -151,8 +151,9 @@ pub fn compose_report_results_filter( crate::types::EntityId::new(report_id.as_str())?; let mut clauses = Vec::new(); for fragment in [saved_filter, inline_filter].into_iter().flatten() { - let fragment = FilterFragment::new( - fragment, + let visible = strict_visible_filter(fragment)?; + FilterFragment::new( + visible.as_str(), &[ "report_id", "_report_id", @@ -169,9 +170,9 @@ pub fn compose_report_results_filter( "_ignore_pagination", ], )?; - validate_strict_comparators(fragment.as_str())?; - if !fragment.as_str().is_empty() { - clauses.push(fragment.into_inner()); + validate_strict_comparators(&visible)?; + if !fragment.trim().is_empty() { + clauses.push(fragment.trim().to_string()); } } let (first, rows) = pagination.gvmd_window(); @@ -181,27 +182,81 @@ pub fn compose_report_results_filter( Ok(clauses.join(" ")) } -fn validate_strict_comparators(fragment: &str) -> Result<(), ReportResultsFilterError> { - let mut quote = None; - let mut escaped = false; - let mut previous_nonspace = None; - let mut token_operator = false; +// Mask only literals recognized by pinned gvmd split_filter. In particular, +// apostrophes and backslashes are ordinary bytes, and embedded double quotes +// are not openers. Keep byte offsets stable for comparator diagnostics. Do not +// change legacy FilterFragment's historical quoting/escaping contract. +fn strict_visible_filter(fragment: &str) -> Result { + let mut visible = fragment.as_bytes().to_vec(); + let mut quoted = false; + let mut between = true; + let mut column = false; + let mut prefix = false; + let mut value_start = 0; for (offset, byte) in fragment.bytes().enumerate() { - if let Some(active) = quote { - if escaped { - escaped = false; - } else if byte == b'\\' { - escaped = true; - } else if byte == active { - quote = None; + if quoted { + visible[offset] = b'x'; + if byte == b'"' { + quoted = false; + between = true; + visible[offset] = b' '; } continue; } - if matches!(byte, b'"' | b'\'') { - quote = Some(byte); - previous_nonspace = Some(byte); - continue; + match byte { + b'"' => { + if between || ((column || prefix) && offset == value_start) { + quoted = true; + between = false; + column = false; + prefix = false; + } + visible[offset] = b'x'; + } + b'\'' => { + visible[offset] = b'x'; + if between { + between = false; + column = false; + prefix = false; + } + } + b' ' | b'\t' | b'\n' | b'\r' => between = true, + b'=' | b'~' if between => { + between = false; + column = false; + prefix = true; + value_start = offset + 1; + } + b'=' | b'~' | b':' | b'>' | b'<' => { + if between { + between = false; + column = false; + prefix = false; + } else if !column { + column = true; + value_start = offset + 1; + } + } + _ if between => { + between = false; + column = false; + prefix = false; + } + _ => {} } + } + if quoted { + return Err(ReportResultsFilterError::UnterminatedQuote); + } + // Replacing entire quoted UTF-8 spans with ASCII preserves valid UTF-8. + Ok(String::from_utf8(visible).expect("masked UTF-8 filter")) +} + +fn validate_strict_comparators(fragment: &str) -> Result<(), ReportResultsFilterError> { + let mut previous_nonspace = None; + let mut token_operator = false; + for (offset, byte) in fragment.bytes().enumerate() { if byte.is_ascii_whitespace() { token_operator = false; continue; @@ -219,9 +274,6 @@ fn validate_strict_comparators(fragment: &str) -> Result<(), ReportResultsFilter } previous_nonspace = Some(byte); } - if quote.is_some() { - return Err(ReportResultsFilterError::UnterminatedQuote); - } if previous_nonspace.is_some_and(|byte| matches!(byte, b'=' | b'>' | b'<' | b'~' | b':')) { return Err(ReportResultsFilterError::Comparator { offset: fragment.len().saturating_sub(1), diff --git a/crates/gvm-gmp/tests/report_results_filter.rs b/crates/gvm-gmp/tests/report_results_filter.rs index b285e4dd..1d169b96 100644 --- a/crates/gvm-gmp/tests/report_results_filter.rs +++ b/crates/gvm-gmp/tests/report_results_filter.rs @@ -58,7 +58,7 @@ fn both_inputs_reject_scope_and_pagination_overrides_quote_aware() { } } } - let literal = r#"name="a\" first=1 severity>=5" comment='rows=10 _and_report_id=x <=5'"#; + let literal = r#"name="first=1 severity>=5" comment="rows=10 _and_report_id=x <=5""#; assert!(compose(None, Some(literal)).is_ok()); assert!(compose(None, Some(r#"name="literal" ROWS=2"#)).is_err()); } @@ -95,7 +95,7 @@ fn strict_comparators_do_not_change_legacy_escape_hatch() { "name~foo", "name:foo", r#"name="severity>=5""#, - r#"comment='x <= 5'"#, + r#"comment="x <= 5""#, ] { assert!(compose(None, Some(fragment)).is_ok(), "{fragment}"); } @@ -120,3 +120,34 @@ fn composed_text_uses_existing_request_xml_escaping() { assert!(xml.contains("_and_report_id=report-1")); assert!(!xml.contains("filt_id=")); } + +#[test] +fn strict_quotes_follow_gvmd_not_shell_escaping() { + // gvmd treats apostrophes and backslashes as ordinary bytes. An embedded + // double quote starts a literal only at a token/value boundary. + for fragment 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""#, + ] { + for (saved, inline) in [(Some(fragment), None), (None, Some(fragment))] { + assert!(compose(saved, inline).is_err(), "{fragment}"); + } + } + for fragment in [ + r#"name="_and_report_id=other >=5""#, + r#"name="ends in backslash\""#, + r#"name=abc"def"#, + "name=O'Brien", + ] { + assert!(compose(None, Some(fragment)).is_ok(), "{fragment}"); + } + assert_eq!( + compose(None, Some(r#"name='a" b'"#)), + Ok("name='a\" b' _and_report_id=report-1 first=4 rows=3".to_string()) + ); +} diff --git a/docs/report-results-filter-gvmd-evidence.md b/docs/report-results-filter-gvmd-evidence.md index 255e0c7b..77621409 100644 --- a/docs/report-results-filter-gvmd-evidence.md +++ b/docs/report-results-filter-gvmd-evidence.md @@ -11,7 +11,7 @@ Public source pin: gvmd `f2d5c97bcb2d3bdeac879c865ebe9cf9c998f766`. `gvm_gmp::compose_report_results_filter(&EntityId, Option<&str>, Option<&str>, Pagination) -> Result` takes a report identity, resolved saved-filter term text, inline term text, and page/per-page window. It always returns nonempty scope/window text. Pass it as `GetResultsRequest.filter_string`, leaving `filter_id` unset: gvmd saved-filter selection replaces rather than augments inline terms. Both fragments are independently validated before appending protected scope and pagination. Boolean expression semantics are retained (including default OR); saved and inline text are not parenthesized or rewritten into a different grammar. -The new error type leaves exhaustive matches on existing `FilterFragmentError` source-compatible. Existing raw `PaginatedFilter` and request escape hatches remain permissive. The strict helper rejects compound or malformed comparisons outside quoted literals and unclosed quotes; it is not a complete gvmd grammar/field validator. Scope and pagination keys are rejected quote-aware, including conservative pagination aliases. +The new error type leaves exhaustive matches on existing `FilterFragmentError` source-compatible. Existing raw `PaginatedFilter` and request escape hatches remain permissive. The strict helper rejects compound or malformed comparisons outside quoted literals and unclosed quotes; it is not a complete gvmd grammar/field validator. Scope and pagination keys are rejected quote-aware, including conservative pagination aliases. Strict literal handling follows `split_filter`: only double quotes at token/value boundaries open a literal; backslashes do not escape quotes, apostrophes are ordinary bytes, and embedded double quotes do not open literals. The historical legacy fragment parser remains unchanged. ## Bounded verification diff --git a/worklog.md b/worklog.md index d01802a6..2558708a 100644 --- a/worklog.md +++ b/worklog.md @@ -76,3 +76,8 @@ - Corrected bounded result mock to source-supported default OR / explicit AND groups, with protected report restriction evaluated independently before counts/paging. - Verification: GMP filtering unit tests (23), result request tests (7), new strict composition tests (4), stateful result conformance (6), typed client result integration (6); fmt check and strict focused Clippy on all touched libraries/test targets passed. Broad all-target Clippy additionally attempted and blocked by pre-existing missing crate docs in agent_schedule_serde_test.rs; no unrelated file modified. Existing manifest unused-workspace-dependency warnings remain. - Tests use /workspace/866-test-env with CARGO_TARGET_DIR=/workspace/.cache/upstream-filter-target. No live gvmd qualification. + +## PR #872 exact-head security review +- Head 64b9d018 completed checks green so far; all-features, coverage and Geiger pending. No failed checks observed. +- Independent source review found strict/legacy quote mismatch: gvmd recognizes only boundary double quotes and no backslash escapes. Added regression demonstrating old helper accepted hidden `_and_report_id`; strict-only mask now follows pinned split_filter states, preserving legacy API behavior. New regressions cover both inputs, pagination, inclusive operators, embedded quotes, apostrophes and trailing backslashes. +- Verification: 40 focused tests passed (23 legacy filtering, 5 strict helper, 6 enabled mock, 6 typed client); fmt/diff checks and strict GMP library/helper-target Clippy passed. Original head CI and Security workflows both completed SUCCESS. No merge requested/performed.