Skip to content
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
85 changes: 53 additions & 32 deletions src/sharplsp/src/nuget/vulnerability/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,32 +20,31 @@ pub(crate) struct AuditSettings {
pub(super) suppressed: Vec<String>,
}

/// 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<String> = 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<Item = std::path::PathBuf> {
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
Expand All @@ -67,9 +66,10 @@ pub(super) fn policy_files(project: &str) -> impl Iterator<Item = std::path::Pat
/// over the props files'. [PKG-VULN-FIX]
pub(super) fn pins_transitives_centrally(project: &str) -> 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"))
}

Expand All @@ -84,22 +84,43 @@ fn audit_level(text: &str) -> Option<AdvisorySeverity> {
}
}

/// A `<PropertyGroup>` 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<String> {
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<String> {
let mut text = String::new();
Expand Down
54 changes: 54 additions & 0 deletions src/sharplsp/src/nuget/vulnerability_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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!("<Project>{groups}</Project>")).unwrap();
};

// Interaction 1 — within one file, the later assignment wins.
write(&props, "<PropertyGroup><NuGetAuditLevel>low</NuGetAuditLevel></PropertyGroup><PropertyGroup><NuGetAuditLevel>high</NuGetAuditLevel></PropertyGroup>");
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, "<PropertyGroup><NuGetAuditLevel>low</NuGetAuditLevel></PropertyGroup><PropertyGroup Condition=\"'$(CI)'=='true'\"><NuGetAuditLevel>critical</NuGetAuditLevel></PropertyGroup>");
let settings = audit_settings(project.to_str().unwrap());
assert_eq!(
settings.level,
Some(AdvisorySeverity::Low),
"a conditioned group is not applied"
);
write(&props, "<PropertyGroup><NuGetAuditLevel>low</NuGetAuditLevel><NuGetAuditLevel Condition=\"'$(CI)'=='true'\">critical</NuGetAuditLevel></PropertyGroup>");
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, "<PropertyGroup><NuGetAudit>false</NuGetAudit><NuGetAuditLevel>critical</NuGetAuditLevel></PropertyGroup>");
write(&project, "<PropertyGroup><NuGetAudit>true</NuGetAudit><NuGetAuditLevel>moderate</NuGetAuditLevel></PropertyGroup>");
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]
Expand Down