diff --git a/src/sharplsp/src/nuget/vulnerability/settings.rs b/src/sharplsp/src/nuget/vulnerability/settings.rs index a1265636..e7a7e71c 100644 --- a/src/sharplsp/src/nuget/vulnerability/settings.rs +++ b/src/sharplsp/src/nuget/vulnerability/settings.rs @@ -20,32 +20,31 @@ pub(crate) struct AuditSettings { pub(super) suppressed: Vec, } -/// Read the audit settings from the project and its imported props. +/// Read the audit settings from the project and its imported props, the way +/// `MSBuild` evaluates them: the props first, then the project body, the last +/// unconditional assignment winning. Suppressions accumulate from every file. pub(super) fn audit_settings(project: &str) -> AuditSettings { - let files = policy_files(project); - let mut settings = AuditSettings { - enabled: true, - level: None, - suppressed: Vec::new(), - }; - for file in files { - let Ok(text) = std::fs::read_to_string(&file) else { - continue; - }; - if property(&text, "NuGetAudit").as_deref() == Some("false") { - settings.enabled = false; - } - if let Some(level) = property(&text, "NuGetAuditLevel") - .as_deref() - .and_then(audit_level) - { - settings.level = Some(level); - } - settings - .suppressed - .extend(items_with_include(&text, "NuGetAuditSuppress")); + let texts: Vec = evaluation_order(project) + .filter_map(|file| std::fs::read_to_string(file).ok()) + .collect(); + let last = |name: &str| texts.iter().rev().find_map(|text| property(text, name)); + AuditSettings { + enabled: last("NuGetAudit").is_none_or(|value| !value.eq_ignore_ascii_case("false")), + level: last("NuGetAuditLevel").as_deref().and_then(audit_level), + suppressed: texts + .iter() + .flat_map(|text| items_with_include(text, "NuGetAuditSuppress")) + .collect(), } - settings +} + +/// [`policy_files`] in `MSBuild`'s import order: `Directory.Build.props` and +/// `Directory.Packages.props` are imported before the project body, so a value +/// the project sets overrides theirs. +fn evaluation_order(project: &str) -> impl Iterator { + let mut files: Vec<_> = policy_files(project).collect(); + files.rotate_left(1); + files.into_iter() } /// The files a project's package policy is read from: the project, then the @@ -67,9 +66,10 @@ pub(super) fn policy_files(project: &str) -> impl Iterator bool { targets::find_packages_props(Path::new(project)).is_some() - && policy_files(project) + && evaluation_order(project) .filter_map(|file| std::fs::read_to_string(file).ok()) - .find_map(|text| property(&text, "CentralPackageTransitivePinningEnabled")) + .filter_map(|text| property(&text, "CentralPackageTransitivePinningEnabled")) + .last() .is_some_and(|value| value.eq_ignore_ascii_case("true")) } @@ -84,22 +84,43 @@ fn audit_level(text: &str) -> Option { } } -/// A `` property's text, read through the XML parser. +/// A property's LAST unconditional assignment in one file, read through the +/// XML parser. An element carrying a `Condition` — a `PropertyGroup`, a `When` +/// or the property itself — is skipped whole: the host cannot evaluate it, and +/// guessing it true would let one CI-only value override the real one. fn property(text: &str, name: &str) -> Option { let mut reader = quick_xml::Reader::from_str(text); + let mut last = None; loop { - match reader.read_event().ok()? { - quick_xml::events::Event::Start(element) + match reader.read_event() { + Ok(quick_xml::events::Event::Start(element)) if conditioned(&element, &reader) => { + let end = element.to_end().into_owned(); + if reader.read_to_end(end.name()).is_err() { + return last; + } + } + Ok(quick_xml::events::Event::Start(element)) if element.name().as_ref() == name.as_bytes() => { - return element_text(&mut reader); + last = element_text(&mut reader).or(last); } - quick_xml::events::Event::Eof => return None, - _ => {} + Ok(quick_xml::events::Event::Eof) | Err(_) => return last, + Ok(_) => {} } } } +/// True when `element` carries a `Condition` attribute. +fn conditioned( + element: &quick_xml::events::BytesStart<'_>, + reader: &quick_xml::Reader<&[u8]>, +) -> bool { + matches!( + parse::attribute_value(element, "Condition", reader.decoder()), + Ok(Some(_)) + ) +} + /// One element's direct text content, stopping at its end tag. fn element_text(reader: &mut quick_xml::Reader<&[u8]>) -> Option { let mut text = String::new(); diff --git a/src/sharplsp/src/nuget/vulnerability_tests.rs b/src/sharplsp/src/nuget/vulnerability_tests.rs index 39affdad..a79020c2 100644 --- a/src/sharplsp/src/nuget/vulnerability_tests.rs +++ b/src/sharplsp/src/nuget/vulnerability_tests.rs @@ -142,6 +142,60 @@ fn audit_settings_are_read_from_the_props_chain() { assert!(!disabled.enabled, "NuGetAudit=false disables reporting"); } +/// The policy evaluates the way `MSBuild` does: the props files are imported +/// BEFORE the project body, so the project's own value wins; within a file the +/// LAST assignment wins; and a conditioned value — which the host cannot +/// evaluate — never overrides the unconditional one. [PKG-VULN-DIAG] +#[test] +fn audit_settings_follow_msbuild_last_assignment_and_project_precedence() { + let dir = tempfile::tempdir().unwrap(); + let project = dir.path().join("App.csproj"); + let props = dir.path().join("Directory.Build.props"); + let write = |path: &std::path::Path, groups: &str| { + std::fs::write(path, format!("{groups}")).unwrap(); + }; + + // Interaction 1 — within one file, the later assignment wins. + write(&props, "lowhigh"); + write(&project, ""); + let settings = audit_settings(project.to_str().unwrap()); + assert_eq!( + settings.level, + Some(AdvisorySeverity::High), + "the last assignment wins" + ); + + // Interaction 2 — a conditioned group never overrides the unconditional value. + write(&props, "lowcritical"); + let settings = audit_settings(project.to_str().unwrap()); + assert_eq!( + settings.level, + Some(AdvisorySeverity::Low), + "a conditioned group is not applied" + ); + write(&props, "lowcritical"); + let settings = audit_settings(project.to_str().unwrap()); + assert_eq!( + settings.level, + Some(AdvisorySeverity::Low), + "a conditioned property is not applied" + ); + + // Interaction 3 — the project body overrides the props it imports. + write(&props, "falsecritical"); + write(&project, "truemoderate"); + let settings = audit_settings(project.to_str().unwrap()); + assert!( + settings.enabled, + "the project re-enables what its props disabled" + ); + assert_eq!( + settings.level, + Some(AdvisorySeverity::Moderate), + "the project's level wins" + ); +} + /// The wire shape of .NET 10's listing parses: severity words, the lowercase /// `advisoryurl` alias, and transitive packages without requested versions. #[test]