CVE-2023-40030: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: Cargo downloads a Rust project’s dependencies and compiles the project. Starting in Rust 1.60.0 and prior to 1.72, Cargo did not escape Cargo feature names when including them in the report generated by `cargo build --timings`. A malicious package included as a dependency may inject nearly arbitrary HTML here, potentially leading to cross-site scripting if the report is subsequently uploaded somewhere. The vulnerability affects users relying on dependencies from git, local paths, or alternative registries. Users who solely depend on crates.io are unaffected.

Rust 1.60.0 introduced `cargo build --timings`, which produces a report of how long the different steps of the build process took. It includes lists of Cargo features for each crate. Prior to Rust 1.72, Cargo feature names were allowed to contain almost any characters (with some exceptions as used by the feature syntax), but it would produce a future incompatibility warning about them since Rust 1.49. crates.io is far more stringent about what it considers a valid feature name and has not allowed such feature names. As the feature names were included unescaped in the timings report, they could be used to inject Javascript into the page, for example with a feature name like `features = ["<img src='' onerror=alert(0)"]`. If this report were subsequently uploaded to a domain that uses credentials, the injected Javascript could access resources from the website visitor.

This issue was fixed in Rust 1.72 by turning the future incompatibility warning into an error. Users should still exercise care in which package they download, by only including trusted dependencies in their projects. Please note that even with these vulnerabilities fixed, by design Cargo allows arbitrary code execution at build time thanks to build scripts and procedural macros: a malicious dependency will be able to cause damage regardless of these vulnerabilities. crates.io has server-side checks preventing this attack, and there are no packages on crates.io exploiting these vulnerabilities. crates.io users still need to excercise care in choosing their dependencies though, as remote code execution is allowed by design there as well.
CWE description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
CVSS v3 base score: 6.1
Published: 2023-08-24T23:15Z
Repository: https://github.com/rust-lang/cargo
Language: Rust
Files changed: crates/resolver-tests/src/lib.rs, src/cargo/core/resolver/version_prefs.rs, src/cargo/core/summary.rs, src/cargo/sources/registry/index.rs, src/cargo/util/toml/mod.rs, tests/testsuite/features.rs
Commit date: 2023-06-20 12:39:27 -0700
Commit message: Convert valid feature name warning to an error.

Diff: diff --git a/crates/resolver-tests/src/lib.rs b/crates/resolver-tests/src/lib.rs
index 01d9b5e6d6..ab34e86631 100644
--- a/crates/resolver-tests/src/lib.rs
+++ b/crates/resolver-tests/src/lib.rs
@@ -177,11 +177,10 @@ pub fn resolve_with_config_raw(
     let mut registry = MyRegistry {
         list: registry,
         used: HashSet::new(),
     };
     let summary = Summary::new(
-        config,
         pkg_id("root"),
         deps,
         &BTreeMap::new(),
         None::<&String>,
         None::<&String>,
@@ -579,11 +578,10 @@ pub fn pkg_dep<T: ToPkgId>(name: T, dep: Vec<Dependency>) -> Summary {
         Some(pkgid.name().as_str())
     } else {
         None
     };
     Summary::new(
-        &Config::default().unwrap(),
         name.to_pkgid(),
         dep,
         &BTreeMap::new(),
         link,
         None::<&String>,
@@ -608,11 +606,10 @@ pub fn pkg_loc(name: &str, loc: &str) -> Summary {
         Some(name)
     } else {
         None
     };
     Summary::new(
-        &Config::default().unwrap(),
         pkg_id_loc(name, loc),
         Vec::new(),
         &BTreeMap::new(),
         link,
         None::<&String>,
@@ -623,11 +620,10 @@ pub fn pkg_loc(name: &str, loc: &str) -> Summary {
 pub fn remove_dep(sum: &Summary, ind: usize) -> Summary {
     let mut deps = sum.dependencies().to_vec();
     deps.remove(ind);
     // note: more things will need to be copied over in the future, but it works for now.
     Summary::new(
-        &Config::default().unwrap(),
         sum.package_id(),
         deps,
         &BTreeMap::new(),
         sum.links().map(|a| a.as_str()),
         None::<&String>,
diff --git a/src/cargo/core/resolver/version_prefs.rs b/src/cargo/core/resolver/version_prefs.rs
index 002f11ff80..bf26d0498f 100644
--- a/src/cargo/core/resolver/version_prefs.rs
+++ b/src/cargo/core/resolver/version_prefs.rs
@@ -79,11 +79,10 @@ impl VersionPreferences {
 
 #[cfg(test)]
 mod test {
     use super::*;
     use crate::core::SourceId;
-    use crate::util::Config;
     use std::collections::BTreeMap;
 
     fn pkgid(name: &str, version: &str) -> PackageId {
         let src_id =
             SourceId::from_url("registry+https://github.com/rust-lang/crates.io-index").unwrap();
@@ -96,14 +95,12 @@ mod test {
         Dependency::parse(name, Some(version), src_id).unwrap()
     }
 
     fn summ(name: &str, version: &str) -> Summary {
         let pkg_id = pkgid(name, version);
-        let config = Config::default().unwrap();
         let features = BTreeMap::new();
         Summary::new(
-            &config,
             pkg_id,
             Vec::new(),
             &features,
             None::<&String>,
             None::<&String>,
diff --git a/src/cargo/core/summary.rs b/src/cargo/core/summary.rs
index 2535c44829..1883df33b8 100644
--- a/src/cargo/core/summary.rs
+++ b/src/cargo/core/summary.rs
@@ -1,8 +1,8 @@
 use crate::core::{Dependency, PackageId, SourceId};
 use crate::util::interning::InternedString;
-use crate::util::{CargoResult, Config};
+use crate::util::CargoResult;
 use anyhow::bail;
 use semver::Version;
 use std::collections::{BTreeMap, HashMap, HashSet};
 use std::fmt;
 use std::hash::{Hash, Hasher};
@@ -28,11 +28,10 @@ struct Inner {
     rust_version: Option<InternedString>,
 }
 
 impl Summary {
     pub fn new(
-        config: &Config,
         pkg_id: PackageId,
         dependencies: Vec<Dependency>,
         features: &BTreeMap<InternedString, Vec<InternedString>>,
         links: Option<impl Into<InternedString>>,
         rust_version: Option<impl Into<InternedString>>,
@@ -47,11 +46,11 @@ impl Summary {
                     "dev-dependencies are not allowed to be optional: `{}`",
                     dep_name
                 )
             }
         }
-        let feature_map = build_feature_map(config, pkg_id, features, &dependencies)?;
+        let feature_map = build_feature_map(pkg_id, features, &dependencies)?;
         Ok(Summary {
             inner: Rc::new(Inner {
                 package_id: pkg_id,
                 dependencies,
                 features: Rc::new(feature_map),
@@ -138,11 +137,10 @@ impl Hash for Summary {
 }
 
 /// Checks features for errors, bailing out a CargoResult:Err if invalid,
 /// and creates FeatureValues for each feature.
 fn build_feature_map(
-    config: &Config,
     pkg_id: PackageId,
     features: &BTreeMap<InternedString, Vec<InternedString>>,
     dependencies: &[Dependency],
 ) -> CargoResult<FeatureMap> {
     use self::FeatureValue::*;
@@ -202,11 +200,11 @@ fn build_feature_map(
             bail!(
                 "feature named `{}` is not allowed to contain slashes",
                 feature
             );
         }
-        validate_feature_name(config, pkg_id, feature)?;
+        validate_feature_name(pkg_id, feature)?;
         for fv in fvs {
             // Find data for the referenced dependency...
             let dep_data = {
                 match fv {
                     Feature(dep_name) | Dep { dep_name, .. } | DepFeature { dep_name, .. } => {
@@ -429,35 +427,65 @@ impl fmt::Display for FeatureValue {
     }
 }
 
 pub type FeatureMap = BTreeMap<InternedString, Vec<FeatureValue>>;
 
-fn validate_feature_name(config: &Config, pkg_id: PackageId, name: &str) -> CargoResult<()> {
+fn validate_feature_name(pkg_id: PackageId, name: &str) -> CargoResult<()> {
     let mut chars = name.chars();
-    const FUTURE: &str = "This was previously accepted but is being phased out; \
-        it will become a hard error in a future release.\n\
-        For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, \
-        and please leave a comment if this will be a problem for your project.";
     if let Some(ch) = chars.next() {
         if !(unicode_xid::UnicodeXID::is_xid_start(ch) || ch == '_' || ch.is_digit(10)) {
-            config.shell().warn(&format!(
+            bail!(
                 "invalid character `{}` in feature `{}` in package {}, \
                 the first character must be a Unicode XID start character or digit \
-                (most letters or `_` or `0` to `9`)\n\
-                {}",
-                ch, name, pkg_id, FUTURE
-            ))?;
+                (most letters or `_` or `0` to `9`)",
+                ch,
+                name,
+                pkg_id
+            );
         }
     }
     for ch in chars {
         if !(unicode_xid::UnicodeXID::is_xid_continue(ch) || ch == '-' || ch == '+' || ch == '.') {
-            config.shell().warn(&format!(
+            bail!(
                 "invalid character `{}` in feature `{}` in package {}, \
                 characters must be Unicode XID characters, `+`, or `.` \
-                (numbers, `+`, `-`, `_`, `.`, or most letters)\n\
-                {}",
-                ch, name, pkg_id, FUTURE
-            ))?;
+                (numbers, `+`, `-`, `_`, `.`, or most letters)",
+                ch,
+                name,
+                pkg_id
+            );
         }
     }
     Ok(())
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use crate::sources::CRATES_IO_INDEX;
+    use crate::util::into_url::IntoUrl;
+
+    use crate::core::SourceId;
+
+    #[test]
+    fn valid_feature_names() {
+        let loc = CRATES_IO_INDEX.into_url().unwrap();
+        let source_id = SourceId::for_registry(&loc).unwrap();
+        let pkg_id = PackageId::new("foo", "1.0.0", source_id).unwrap();
+
+        assert!(validate_feature_name(pkg_id, "c++17").is_ok());
+        assert!(validate_feature_name(pkg_id, "128bit").is_ok());
+        assert!(validate_feature_name(pkg_id, "_foo").is_ok());
+        assert!(validate_feature_name(pkg_id, "feat-name").is_ok());
+        assert!(validate_feature_name(pkg_id, "feat_name").is_ok());
+        assert!(validate_feature_name(pkg_id, "foo.bar").is_ok());
+
+        assert!(validate_feature_name(pkg_id, "+foo").is_err());
+        assert!(validate_feature_name(pkg_id, "-foo").is_err());
+        assert!(validate_feature_name(pkg_id, ".foo").is_err());
+        assert!(validate_feature_name(pkg_id, "foo:bar").is_err());
+        assert!(validate_feature_name(pkg_id, "foo?").is_err());
+        assert!(validate_feature_name(pkg_id, "?foo").is_err());
+        assert!(validate_feature_name(pkg_id, "ⒶⒷⒸ").is_err());
+        assert!(validate_feature_name(pkg_id, "a¼").is_err());
+    }
+}
diff --git a/src/cargo/sources/registry/index.rs b/src/cargo/sources/registry/index.rs
index aa5c2a78c3..6d565da8f5 100644
--- a/src/cargo/sources/registry/index.rs
+++ b/src/cargo/sources/registry/index.rs
@@ -406,11 +406,10 @@ impl<'cfg> RegistryIndex<'cfg> {
     ) -> Poll<CargoResult<impl Iterator<Item = &'a IndexSummary> + 'b>>
     where
         'a: 'b,
     {
         let source_id = self.source_id;
-        let config = self.config;
 
         // First up parse what summaries we have available.
         let name = InternedString::new(name);
         let summaries = ready!(self.load_summaries(name, load)?);
 
@@ -423,19 +422,17 @@ impl<'cfg> RegistryIndex<'cfg> {
         let raw_data = &summaries.raw_data;
         Poll::Ready(Ok(summaries
             .versions
             .iter_mut()
             .filter_map(move |(k, v)| if req.matches(k) { Some(v) } else { None })
-            .filter_map(
-                move |maybe| match maybe.parse(config, raw_data, source_id) {
-                    Ok(summary) => Some(summary),
-                    Err(e) => {
-                        info!("failed to parse `{}` registry package: {}", name, e);
-                        None
-                    }
-                },
-            )
+            .filter_map(move |maybe| match maybe.parse(raw_data, source_id) {
+                Ok(summary) => Some(summary),
+                Err(e) => {
+                    info!("failed to parse `{}` registry package: {}", name, e);
+                    None
+                }
+            })
             .filter(move |is| {
                 if is.v > INDEX_V_MAX {
                     debug!(
                         "unsupported schema version {} ({} {})",
                         is.v,
@@ -712,11 +709,11 @@ impl Summaries {
                     // Attempt forwards-compatibility on the index by ignoring
                     // everything that we ourselves don't understand, that should
                     // allow future cargo implementations to break the
                     // interpretation of each line here and older cargo will simply
                     // ignore the new lines.
-                    let summary = match IndexSummary::parse(config, line, source_id) {
+                    let summary = match IndexSummary::parse(line, source_id) {
                         Ok(summary) => summary,
                         Err(e) => {
                             // This should only happen when there is an index
                             // entry from a future version of cargo that this
                             // version doesn't understand. Hopefully, those future
@@ -861,21 +858,16 @@ impl MaybeIndexSummary {
     /// Parses this "maybe a summary" into a `Parsed` for sure variant.
     ///
     /// Does nothing if this is already `Parsed`, and otherwise the `raw_data`
     /// passed in is sliced with the bounds in `Unparsed` and then actually
     /// parsed.
-    fn parse(
-        &mut self,
-        config: &Config,
-        raw_data: &[u8],
-        source_id: SourceId,
-    ) -> CargoResult<&IndexSummary> {
+    fn parse(&mut self, raw_data: &[u8], source_id: SourceId) -> CargoResult<&IndexSummary> {
         let (start, end) = match self {
             MaybeIndexSummary::Unparsed { start, end } => (*start, *end),
             MaybeIndexSummary::Parsed(summary) => return Ok(summary),
         };
-        let summary = IndexSummary::parse(config, &raw_data[start..end], source_id)?;
+        let summary = IndexSummary::parse(&raw_data[start..end], source_id)?;
         *self = MaybeIndexSummary::Parsed(summary);
         match self {
             MaybeIndexSummary::Unparsed { .. } => unreachable!(),
             MaybeIndexSummary::Parsed(summary) => Ok(summary),
         }
@@ -892,11 +884,11 @@ impl IndexSummary {
     /// Parses a line from the registry's index file into an [`IndexSummary`]
     /// for a package.
     ///
     /// The `line` provided is expected to be valid JSON. It is supposed to be
     /// a [`IndexPackage`].
-    fn parse(config: &Config, line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary> {
+    fn parse(line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary> {
         // ****CAUTION**** Please be extremely careful with returning errors
         // from this function. Entries that error are not included in the
         // index cache, and can cause cargo to get confused when switching
         // between different versions that understand the index differently.
         // Make sure to consider the INDEX_V_MAX and CURRENT_CACHE_VERSION
@@ -923,11 +915,11 @@ impl IndexSummary {
         if let Some(features2) = features2 {
             for (name, values) in features2 {
                 features.entry(name).or_default().extend(values);
             }
         }
-        let mut summary = Summary::new(config, pkgid, deps, &features, links, rust_version)?;
+        let mut summary = Summary::new(pkgid, deps, &features, links, rust_version)?;
         summary.set_checksum(cksum);
         Ok(IndexSummary {
             summary,
             yanked: yanked.unwrap_or(false),
             v,
diff --git a/src/cargo/util/toml/mod.rs b/src/cargo/util/toml/mod.rs
index 1cc32dee8f..a32f0384b6 100644
--- a/src/cargo/util/toml/mod.rs
+++ b/src/cargo/util/toml/mod.rs
@@ -2430,11 +2430,10 @@ impl TomlManifest {
             .transpose()?
             .unwrap_or_default();
         let empty_features = BTreeMap::new();
 
         let summary = Summary::new(
-            config,
             pkgid,
             deps,
             me.features.as_ref().unwrap_or(&empty_features),
             package.links.as_deref(),
             rust_version.as_deref().map(InternedString::new),
diff --git a/tests/testsuite/features.rs b/tests/testsuite/features.rs
index 848e056774..557fab14ab 100644
--- a/tests/testsuite/features.rs
+++ b/tests/testsuite/features.rs
@@ -1935,87 +1935,72 @@ fn nonexistent_required_features() {
         )
         .run();
 }
 
 #[cargo_test]
-fn invalid_feature_names_warning() {
-    // Warnings for more restricted feature syntax.
+fn invalid_feature_names_error() {
+    // Errors for more restricted feature syntax.
     let p = project()
         .file(
             "Cargo.toml",
             r#"
                 [package]
                 name = "foo"
                 version = "0.1.0"
 
                 [features]
-                # Some valid, but unusual names, shouldn't warn.
-                "c++17" = []
-                "128bit" = []
-                "_foo" = []
-                "feat-name" = []
-                "feat_name" = []
-                "foo.bar" = []
-
-                # Invalid names.
+                # Invalid start character.
                 "+foo" = []
-                "-foo" = []
-                ".foo" = []
-                "foo:bar" = []
-                "foo?" = []
-                "?foo" = []
-                "ⒶⒷⒸ" = []
-                "a¼" = []
             "#,
         )
         .file("src/lib.rs", "")
         .build();
 
-    // Unfortunately the warnings are duplicated due to the Summary being
-    // loaded twice (once in the Workspace, and once in PackageRegistry) and
-    // Cargo does not have a de-duplication system. This should probably be
-    // OK, since I'm not expecting this to affect anyone.
     p.cargo("check")
-        .with_stderr("\
-[WARNING] invalid character `+` in feature `+foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `-` in feature `-foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `.` in feature `.foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `?` in feature `?foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `¼` in feature `a¼` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `:` in feature `foo:bar` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `?` in feature `foo?` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `Ⓐ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `Ⓑ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[WARNING] invalid character `Ⓒ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
-This was previously accepted but is being phased out; it will become a hard error in a future release.
-For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
-[CHECKING] foo v0.1.0 [..]
-[FINISHED] [..]
-")
+        .with_status(101)
+        .with_stderr(
+            "\
+error: failed to parse manifest at `[ROOT]/foo/Cargo.toml`
+
+Caused by:
+  invalid character `+` in feature `+foo` in package foo v0.1.0 ([ROOT]/foo), \
+  the first character must be a Unicode XID start character or digit \
+  (most letters or `_` or `0` to `9`)
+",
+        )
+        .run();
+
+    p.change_file(
+        "Cargo.toml",
+        r#"
+            [package]
+            name = "foo"
+            version = "0.1.0"
+
+            [features]
+            # Invalid continue character.
+            "a&b" = []
+        "#,
+    );
+
+    p.cargo("check")
+        .with_status(101)
+        .with_stderr(
+            "\
+error: failed to parse manifest at `[ROOT]/foo/Cargo.toml`
+
+Caused by:
+  invalid character `&` in feature `a&b` in package foo v0.1.0 ([ROOT]/foo), \
+  characters must be Unicode XID characters, `+`, or `.` \
+  (numbers, `+`, `-`, `_`, `.`, or most letters)
+",
+        )
         .run();
 }
 
 #[cargo_test]
-fn invalid_feature_names_error() {
+fn invalid_feature_name_slash_error() {
     // Errors for more restricted feature syntax.
     let p = project()
         .file(
             "Cargo.toml",
             r#"

Vulnerable code:         config,
        &Config::default().unwrap(),
        &Config::default().unwrap(),
        &Config::default().unwrap(),
    use crate::util::Config;
        let config = Config::default().unwrap();
            &config,
use crate::util::{CargoResult, Config};
        config: &Config,
        let feature_map = build_feature_map(config, pkg_id, features, &dependencies)?;
    config: &Config,
        validate_feature_name(config, pkg_id, feature)?;
fn validate_feature_name(config: &Config, pkg_id: PackageId, name: &str) -> CargoResult<()> {
    const FUTURE: &str = "This was previously accepted but is being phased out; \
        it will become a hard error in a future release.\n\
        For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, \
        and please leave a comment if this will be a problem for your project.";
            config.shell().warn(&format!(
                (most letters or `_` or `0` to `9`)\n\
                {}",
                ch, name, pkg_id, FUTURE
            ))?;
            config.shell().warn(&format!(
                (numbers, `+`, `-`, `_`, `.`, or most letters)\n\
                {}",
                ch, name, pkg_id, FUTURE
            ))?;
        let config = self.config;
            .filter_map(
                move |maybe| match maybe.parse(config, raw_data, source_id) {
                    Ok(summary) => Some(summary),
                    Err(e) => {
                        info!("failed to parse `{}` registry package: {}", name, e);
                        None
                    }
                },
            )
                    let summary = match IndexSummary::parse(config, line, source_id) {
    fn parse(
        &mut self,
        config: &Config,
        raw_data: &[u8],
        source_id: SourceId,
    ) -> CargoResult<&IndexSummary> {
        let summary = IndexSummary::parse(config, &raw_data[start..end], source_id)?;
    fn parse(config: &Config, line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary> {
        let mut summary = Summary::new(config, pkgid, deps, &features, links, rust_version)?;
            config,
fn invalid_feature_names_warning() {
    // Warnings for more restricted feature syntax.
                # Some valid, but unusual names, shouldn't warn.
                "c++17" = []
                "128bit" = []
                "_foo" = []
                "feat-name" = []
                "feat_name" = []
                "foo.bar" = []

                # Invalid names.
                "-foo" = []
                ".foo" = []
                "foo:bar" = []
                "foo?" = []
                "?foo" = []
                "ⒶⒷⒸ" = []
                "a¼" = []
    // Unfortunately the warnings are duplicated due to the Summary being
    // loaded twice (once in the Workspace, and once in PackageRegistry) and
    // Cargo does not have a de-duplication system. This should probably be
    // OK, since I'm not expecting this to affect anyone.
        .with_stderr("\
[WARNING] invalid character `+` in feature `+foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `-` in feature `-foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `.` in feature `.foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `?` in feature `?foo` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `¼` in feature `a¼` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `:` in feature `foo:bar` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `?` in feature `foo?` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `Ⓐ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), the first character must be a Unicode XID start character or digit (most letters or `_` or `0` to `9`)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `Ⓑ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[WARNING] invalid character `Ⓒ` in feature `ⒶⒷⒸ` in package foo v0.1.0 ([ROOT]/foo), characters must be Unicode XID characters, `+`, or `.` (numbers, `+`, `-`, `_`, `.`, or most letters)
This was previously accepted but is being phased out; it will become a hard error in a future release.
For more information, see issue #8813 <https://github.com/rust-lang/cargo/issues/8813>, and please leave a comment if this will be a problem for your project.
[CHECKING] foo v0.1.0 [..]
[FINISHED] [..]
")
fn invalid_feature_names_error() {
Fixed code: use crate::util::CargoResult;
        let feature_map = build_feature_map(pkg_id, features, &dependencies)?;
        validate_feature_name(pkg_id, feature)?;
fn validate_feature_name(pkg_id: PackageId, name: &str) -> CargoResult<()> {
            bail!(
                (most letters or `_` or `0` to `9`)",
                ch,
                name,
                pkg_id
            );
            bail!(
                (numbers, `+`, `-`, `_`, `.`, or most letters)",
                ch,
                name,
                pkg_id
            );

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sources::CRATES_IO_INDEX;
    use crate::util::into_url::IntoUrl;

    use crate::core::SourceId;

    #[test]
    fn valid_feature_names() {
        let loc = CRATES_IO_INDEX.into_url().unwrap();
        let source_id = SourceId::for_registry(&loc).unwrap();
        let pkg_id = PackageId::new("foo", "1.0.0", source_id).unwrap();

        assert!(validate_feature_name(pkg_id, "c++17").is_ok());
        assert!(validate_feature_name(pkg_id, "128bit").is_ok());
        assert!(validate_feature_name(pkg_id, "_foo").is_ok());
        assert!(validate_feature_name(pkg_id, "feat-name").is_ok());
        assert!(validate_feature_name(pkg_id, "feat_name").is_ok());
        assert!(validate_feature_name(pkg_id, "foo.bar").is_ok());

        assert!(validate_feature_name(pkg_id, "+foo").is_err());
        assert!(validate_feature_name(pkg_id, "-foo").is_err());
        assert!(validate_feature_name(pkg_id, ".foo").is_err());
        assert!(validate_feature_name(pkg_id, "foo:bar").is_err());
        assert!(validate_feature_name(pkg_id, "foo?").is_err());
        assert!(validate_feature_name(pkg_id, "?foo").is_err());
        assert!(validate_feature_name(pkg_id, "ⒶⒷⒸ").is_err());
        assert!(validate_feature_name(pkg_id, "a¼").is_err());
    }
}
            .filter_map(move |maybe| match maybe.parse(raw_data, source_id) {
                Ok(summary) => Some(summary),
                Err(e) => {
                    info!("failed to parse `{}` registry package: {}", name, e);
                    None
                }
            })
                    let summary = match IndexSummary::parse(line, source_id) {
    fn parse(&mut self, raw_data: &[u8], source_id: SourceId) -> CargoResult<&IndexSummary> {
        let summary = IndexSummary::parse(&raw_data[start..end], source_id)?;
    fn parse(line: &[u8], source_id: SourceId) -> CargoResult<IndexSummary> {
        let mut summary = Summary::new(pkgid, deps, &features, links, rust_version)?;
fn invalid_feature_names_error() {
    // Errors for more restricted feature syntax.
                # Invalid start character.
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[ROOT]/foo/Cargo.toml`

Caused by:
  invalid character `+` in feature `+foo` in package foo v0.1.0 ([ROOT]/foo), \
  the first character must be a Unicode XID start character or digit \
  (most letters or `_` or `0` to `9`)
",
        )
        .run();

    p.change_file(
        "Cargo.toml",
        r#"
            [package]
            name = "foo"
            version = "0.1.0"

            [features]
            # Invalid continue character.
            "a&b" = []
        "#,
    );

    p.cargo("check")
        .with_status(101)
        .with_stderr(
            "\
error: failed to parse manifest at `[ROOT]/foo/Cargo.toml`

Caused by:
  invalid character `&` in feature `a&b` in package foo v0.1.0 ([ROOT]/foo), \
  characters must be Unicode XID characters, `+`, or `.` \
  (numbers, `+`, `-`, `_`, `.`, or most letters)
",
        )
fn invalid_feature_name_slash_error() {