1 //! Checks the licenses of third-party dependencies.
3 use cargo_metadata::{Metadata, Package, PackageId, Resolve};
4 use std::collections::{BTreeSet, HashSet};
7 /// These are licenses that are allowed for all crates, including the runtime,
9 const LICENSES: &[&str] = &[
16 "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT", // wasi license
20 "0BSD OR MIT OR Apache-2.0", // adler license
23 /// These are exceptions to Rust's permissive licensing policy, and
24 /// should be considered bugs. Exceptions are only allowed in Rust
25 /// tooling. It is _crucial_ that no exception crates be dependencies
26 /// of the Rust runtime (std/test).
27 const EXCEPTIONS: &[(&str, &str)] = &[
28 ("mdbook", "MPL-2.0"), // mdbook
29 ("openssl", "Apache-2.0"), // cargo, mdbook
30 ("rdrand", "ISC"), // mdbook, rustfmt
31 ("fuchsia-cprng", "BSD-3-Clause"), // mdbook, rustfmt
32 ("fuchsia-zircon-sys", "BSD-3-Clause"), // rustdoc, rustc, cargo
33 ("fuchsia-zircon", "BSD-3-Clause"), // rustdoc, rustc, cargo (jobserver & tempdir)
34 ("colored", "MPL-2.0"), // rustfmt
35 ("ordslice", "Apache-2.0"), // rls
36 ("cloudabi", "BSD-2-Clause"), // (rls -> crossbeam-channel 0.2 -> rand 0.5)
37 ("ryu", "Apache-2.0 OR BSL-1.0"), // rls/cargo/... (because of serde)
38 ("bytesize", "Apache-2.0"), // cargo
39 ("im-rc", "MPL-2.0+"), // cargo
40 ("constant_time_eq", "CC0-1.0"), // rustfmt
41 ("sized-chunks", "MPL-2.0+"), // cargo via im-rc
42 ("bitmaps", "MPL-2.0+"), // cargo via im-rc
43 // FIXME: this dependency violates the documentation comment above:
44 ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
45 ("crossbeam-channel", "MIT/Apache-2.0 AND BSD-2-Clause"), // cargo
48 /// These are the root crates that are part of the runtime. The licenses for
49 /// these and all their dependencies *must not* be in the exception list.
50 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
52 /// Crates whose dependencies must be explicitly permitted.
53 const RESTRICTED_DEPENDENCY_CRATES: &[&str] = &["rustc_middle", "rustc_codegen_llvm"];
55 /// Crates rustc is allowed to depend on. Avoid adding to the list if possible.
57 /// This list is here to provide a speed-bump to adding a new dependency to
58 /// rustc. Please check with the compiler team before adding an entry.
59 const PERMITTED_DEPENDENCIES: &[&str] = &[
160 "stable_deref_trait",
169 "tracing-attributes",
172 "unicode-normalization",
182 "winapi-i686-pc-windows-gnu",
184 "winapi-x86_64-pc-windows-gnu",
187 /// Dependency checks.
189 /// `root` is path to the directory with the root `Cargo.toml` (for the workspace). `cargo` is path
190 /// to the cargo executable.
191 pub fn check(root: &Path, cargo: &Path, bad: &mut bool) {
192 let mut cmd = cargo_metadata::MetadataCommand::new();
193 cmd.cargo_path(cargo)
194 .manifest_path(root.join("Cargo.toml"))
195 .features(cargo_metadata::CargoOpt::AllFeatures);
196 let metadata = t!(cmd.exec());
197 check_exceptions(&metadata, bad);
198 check_dependencies(&metadata, bad);
199 check_crate_duplicate(&metadata, bad);
202 /// Check that all licenses are in the valid list in `LICENSES`.
204 /// Packages listed in `EXCEPTIONS` are allowed for tools.
205 fn check_exceptions(metadata: &Metadata, bad: &mut bool) {
206 // Validate the EXCEPTIONS list hasn't changed.
207 for (name, license) in EXCEPTIONS {
208 // Check that the package actually exists.
209 if !metadata.packages.iter().any(|p| p.name == *name) {
211 "could not find exception package `{}`\n\
212 Remove from EXCEPTIONS list if it is no longer used.",
217 // Check that the license hasn't changed.
218 for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
219 if pkg.name == "fuchsia-cprng" {
220 // This package doesn't declare a license expression. Manual
221 // inspection of the license file is necessary, which appears
222 // to be BSD-3-Clause.
223 assert!(pkg.license.is_none());
229 "dependency exception `{}` does not declare a license expression",
234 Some(pkg_license) => {
235 if pkg_license.as_str() != *license {
236 println!("dependency exception `{}` license has changed", name);
237 println!(" previously `{}` now `{}`", license, pkg_license);
238 println!(" update EXCEPTIONS for the new license");
246 let exception_names: Vec<_> = EXCEPTIONS.iter().map(|(name, _license)| *name).collect();
247 let runtime_ids = compute_runtime_crates(metadata);
249 // Check if any package does not have a valid license.
250 for pkg in &metadata.packages {
251 if pkg.source.is_none() {
252 // No need to check local packages.
255 if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
258 let license = match &pkg.license {
259 Some(license) => license,
261 println!("dependency `{}` does not define a license expression", pkg.id,);
266 if !LICENSES.contains(&license.as_str()) {
267 if pkg.name == "fortanix-sgx-abi" {
268 // This is a specific exception because SGX is considered
269 // "third party". See
270 // https://github.com/rust-lang/rust/issues/62620 for more. In
271 // general, these should never be added.
274 println!("invalid license `{}` in `{}`", license, pkg.id);
280 /// Checks the dependency of `RESTRICTED_DEPENDENCY_CRATES` at the given path. Changes `bad` to
281 /// `true` if a check failed.
283 /// Specifically, this checks that the dependencies are on the `PERMITTED_DEPENDENCIES`.
284 fn check_dependencies(metadata: &Metadata, bad: &mut bool) {
285 // Check that the PERMITTED_DEPENDENCIES does not have unused entries.
286 for name in PERMITTED_DEPENDENCIES {
287 if !metadata.packages.iter().any(|p| p.name == *name) {
289 "could not find allowed package `{}`\n\
290 Remove from PERMITTED_DEPENDENCIES list if it is no longer used.",
296 // Get the list in a convenient form.
297 let permitted_dependencies: HashSet<_> = PERMITTED_DEPENDENCIES.iter().cloned().collect();
299 // Check dependencies.
300 let mut visited = BTreeSet::new();
301 let mut unapproved = BTreeSet::new();
302 for &krate in RESTRICTED_DEPENDENCY_CRATES.iter() {
303 let pkg = pkg_from_name(metadata, krate);
305 check_crate_dependencies(&permitted_dependencies, metadata, &mut visited, pkg);
306 unapproved.append(&mut bad);
309 if !unapproved.is_empty() {
310 println!("Dependencies not explicitly permitted:");
311 for dep in unapproved {
312 println!("* {}", dep);
318 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
319 /// the list of permitted dependencies. Returns a list of disallowed dependencies.
320 fn check_crate_dependencies<'a>(
321 permitted_dependencies: &'a HashSet<&'static str>,
322 metadata: &'a Metadata,
323 visited: &mut BTreeSet<&'a PackageId>,
325 ) -> BTreeSet<&'a PackageId> {
326 // This will contain bad deps.
327 let mut unapproved = BTreeSet::new();
329 // Check if we have already visited this crate.
330 if visited.contains(&krate.id) {
334 visited.insert(&krate.id);
336 // If this path is in-tree, we don't require it to be explicitly permitted.
337 if krate.source.is_some() {
338 // If this dependency is not on `PERMITTED_DEPENDENCIES`, add to bad set.
339 if !permitted_dependencies.contains(krate.name.as_str()) {
340 unapproved.insert(&krate.id);
344 // Do a DFS in the crate graph.
345 let to_check = deps_of(metadata, &krate.id);
347 for dep in to_check {
348 let mut bad = check_crate_dependencies(permitted_dependencies, metadata, visited, dep);
349 unapproved.append(&mut bad);
355 /// Prevents multiple versions of some expensive crates.
356 fn check_crate_duplicate(metadata: &Metadata, bad: &mut bool) {
357 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
358 // These two crates take quite a long time to build, so don't allow two versions of them
359 // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
362 "rustc-ap-rustc_ast",
365 for &name in FORBIDDEN_TO_HAVE_DUPLICATES {
366 let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
367 match matches.len() {
370 "crate `{}` is missing, update `check_crate_duplicate` \
371 if it is no longer used",
379 "crate `{}` is duplicated in `Cargo.lock`, \
380 it is too expensive to build multiple times, \
381 so make sure only one version appears across all dependencies",
385 println!(" * {}", pkg.id);
393 /// Returns a list of dependencies for the given package.
394 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
395 let resolve = metadata.resolve.as_ref().unwrap();
399 .find(|n| &n.id == pkg_id)
400 .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
404 metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
405 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
411 /// Finds a package with the given name.
412 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
413 let mut i = metadata.packages.iter().filter(|p| p.name == name);
415 i.next().unwrap_or_else(|| panic!("could not find package `{}` in package list", name));
416 assert!(i.next().is_none(), "more than one package found for `{}`", name);
420 /// Finds all the packages that are in the rust runtime.
421 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
422 let resolve = metadata.resolve.as_ref().unwrap();
423 let mut result = HashSet::new();
424 for name in RUNTIME_CRATES {
425 let id = &pkg_from_name(metadata, name).id;
426 normal_deps_of_r(resolve, id, &mut result);
431 /// Recursively find all normal dependencies.
432 fn normal_deps_of_r<'a>(
433 resolve: &'a Resolve,
434 pkg_id: &'a PackageId,
435 result: &mut HashSet<&'a PackageId>,
437 if !result.insert(pkg_id) {
443 .find(|n| &n.id == pkg_id)
444 .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
445 // Don't care about dev-dependencies.
446 // Build dependencies *shouldn't* matter unless they do some kind of
447 // codegen. For now we'll assume they don't.
448 let deps = node.deps.iter().filter(|node_dep| {
452 .any(|kind_info| kind_info.kind == cargo_metadata::DependencyKind::Normal)
455 normal_deps_of_r(resolve, &dep.pkg, result);