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
22 /// These are exceptions to Rust's permissive licensing policy, and
23 /// should be considered bugs. Exceptions are only allowed in Rust
24 /// tooling. It is _crucial_ that no exception crates be dependencies
25 /// of the Rust runtime (std/test).
26 const EXCEPTIONS: &[(&str, &str)] = &[
27 ("mdbook", "MPL-2.0"), // mdbook
28 ("openssl", "Apache-2.0"), // cargo, mdbook
29 ("toml-query", "MPL-2.0"), // mdbook
30 ("toml-query_derive", "MPL-2.0"), // mdbook
31 ("is-match", "MPL-2.0"), // mdbook
32 ("rdrand", "ISC"), // mdbook, rustfmt
33 ("fuchsia-cprng", "BSD-3-Clause"), // mdbook, rustfmt
34 ("fuchsia-zircon-sys", "BSD-3-Clause"), // rustdoc, rustc, cargo
35 ("fuchsia-zircon", "BSD-3-Clause"), // rustdoc, rustc, cargo (jobserver & tempdir)
36 ("colored", "MPL-2.0"), // rustfmt
37 ("ordslice", "Apache-2.0"), // rls
38 ("cloudabi", "BSD-2-Clause"), // (rls -> crossbeam-channel 0.2 -> rand 0.5)
39 ("ryu", "Apache-2.0 OR BSL-1.0"), // rls/cargo/... (because of serde)
40 ("bytesize", "Apache-2.0"), // cargo
41 ("im-rc", "MPL-2.0+"), // cargo
42 ("adler32", "BSD-3-Clause AND Zlib"), // cargo dep that isn't used
43 ("constant_time_eq", "CC0-1.0"), // rustfmt
44 ("sized-chunks", "MPL-2.0+"), // cargo via im-rc
45 ("bitmaps", "MPL-2.0+"), // cargo via im-rc
46 // FIXME: this dependency violates the documentation comment above:
47 ("fortanix-sgx-abi", "MPL-2.0"), // libstd but only for `sgx` target
48 ("crossbeam-channel", "MIT/Apache-2.0 AND BSD-2-Clause"), // cargo
51 /// These are the root crates that are part of the runtime. The licenses for
52 /// these and all their dependencies *must not* be in the exception list.
53 const RUNTIME_CRATES: &[&str] = &["std", "core", "alloc", "test", "panic_abort", "panic_unwind"];
55 /// Which crates to check against the whitelist?
56 const WHITELIST_CRATES: &[&str] = &["rustc_middle", "rustc_codegen_llvm"];
58 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
60 /// This list is here to provide a speed-bump to adding a new dependency to
61 /// rustc. Please check with the compiler team before adding an entry.
62 const WHITELIST: &[&str] = &[
100 "fuchsia-zircon-sys",
161 "stable_deref_trait",
170 "unicode-normalization",
180 "winapi-i686-pc-windows-gnu",
182 "winapi-x86_64-pc-windows-gnu",
186 /// Dependency checks.
188 /// `path` is path to the `src` directory, `cargo` is path to the cargo executable.
189 pub fn check(path: &Path, cargo: &Path, bad: &mut bool) {
190 let mut cmd = cargo_metadata::MetadataCommand::new();
191 cmd.cargo_path(cargo)
192 .manifest_path(path.parent().unwrap().join("Cargo.toml"))
193 .features(cargo_metadata::CargoOpt::AllFeatures);
194 let metadata = t!(cmd.exec());
195 check_exceptions(&metadata, bad);
196 check_whitelist(&metadata, bad);
197 check_crate_duplicate(&metadata, bad);
200 /// Check that all licenses are in the valid list in `LICENSES`.
202 /// Packages listed in `EXCEPTIONS` are allowed for tools.
203 fn check_exceptions(metadata: &Metadata, bad: &mut bool) {
204 // Validate the EXCEPTIONS list hasn't changed.
205 for (name, license) in EXCEPTIONS {
206 // Check that the package actually exists.
207 if !metadata.packages.iter().any(|p| p.name == *name) {
209 "could not find exception package `{}`\n\
210 Remove from EXCEPTIONS list if it is no longer used.",
215 // Check that the license hasn't changed.
216 for pkg in metadata.packages.iter().filter(|p| p.name == *name) {
217 if pkg.name == "fuchsia-cprng" {
218 // This package doesn't declare a license expression. Manual
219 // inspection of the license file is necessary, which appears
220 // to be BSD-3-Clause.
221 assert!(pkg.license.is_none());
227 "dependency exception `{}` does not declare a license expression",
232 Some(pkg_license) => {
233 if pkg_license.as_str() != *license {
234 println!("dependency exception `{}` license has changed", name);
235 println!(" previously `{}` now `{}`", license, pkg_license);
236 println!(" update EXCEPTIONS for the new license");
244 let exception_names: Vec<_> = EXCEPTIONS.iter().map(|(name, _license)| *name).collect();
245 let runtime_ids = compute_runtime_crates(metadata);
247 // Check if any package does not have a valid license.
248 for pkg in &metadata.packages {
249 if pkg.source.is_none() {
250 // No need to check local packages.
253 if !runtime_ids.contains(&pkg.id) && exception_names.contains(&pkg.name.as_str()) {
256 let license = match &pkg.license {
257 Some(license) => license,
259 println!("dependency `{}` does not define a license expression", pkg.id,);
264 if !LICENSES.contains(&license.as_str()) {
265 if pkg.name == "fortanix-sgx-abi" {
266 // This is a specific exception because SGX is considered
267 // "third party". See
268 // https://github.com/rust-lang/rust/issues/62620 for more. In
269 // general, these should never be added.
272 println!("invalid license `{}` in `{}`", license, pkg.id);
278 /// Checks the dependency of `WHITELIST_CRATES` at the given path. Changes `bad` to `true` if a
281 /// Specifically, this checks that the dependencies are on the `WHITELIST`.
282 fn check_whitelist(metadata: &Metadata, bad: &mut bool) {
283 // Check that the WHITELIST does not have unused entries.
284 for name in WHITELIST {
285 if !metadata.packages.iter().any(|p| p.name == *name) {
287 "could not find whitelisted package `{}`\n\
288 Remove from WHITELIST list if it is no longer used.",
294 // Get the whitelist in a convenient form.
295 let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
297 // Check dependencies.
298 let mut visited = BTreeSet::new();
299 let mut unapproved = BTreeSet::new();
300 for &krate in WHITELIST_CRATES.iter() {
301 let pkg = pkg_from_name(metadata, krate);
302 let mut bad = check_crate_whitelist(&whitelist, metadata, &mut visited, pkg);
303 unapproved.append(&mut bad);
306 if !unapproved.is_empty() {
307 println!("Dependencies not on the whitelist:");
308 for dep in unapproved {
309 println!("* {}", dep);
315 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
316 /// the whitelist. Returns a list of illegal dependencies.
317 fn check_crate_whitelist<'a>(
318 whitelist: &'a HashSet<&'static str>,
319 metadata: &'a Metadata,
320 visited: &mut BTreeSet<&'a PackageId>,
322 ) -> BTreeSet<&'a PackageId> {
323 // This will contain bad deps.
324 let mut unapproved = BTreeSet::new();
326 // Check if we have already visited this crate.
327 if visited.contains(&krate.id) {
331 visited.insert(&krate.id);
333 // If this path is in-tree, we don't require it to be on the whitelist.
334 if krate.source.is_some() {
335 // If this dependency is not on `WHITELIST`, add to bad set.
336 if !whitelist.contains(krate.name.as_str()) {
337 unapproved.insert(&krate.id);
341 // Do a DFS in the crate graph.
342 let to_check = deps_of(metadata, &krate.id);
344 for dep in to_check {
345 let mut bad = check_crate_whitelist(whitelist, metadata, visited, dep);
346 unapproved.append(&mut bad);
352 /// Prevents multiple versions of some expensive crates.
353 fn check_crate_duplicate(metadata: &Metadata, bad: &mut bool) {
354 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
355 // These two crates take quite a long time to build, so don't allow two versions of them
356 // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
359 "rustc-ap-rustc_ast",
362 for &name in FORBIDDEN_TO_HAVE_DUPLICATES {
363 let matches: Vec<_> = metadata.packages.iter().filter(|pkg| pkg.name == name).collect();
364 match matches.len() {
367 "crate `{}` is missing, update `check_crate_duplicate` \
368 if it is no longer used",
376 "crate `{}` is duplicated in `Cargo.lock`, \
377 it is too expensive to build multiple times, \
378 so make sure only one version appears across all dependencies",
382 println!(" * {}", pkg.id);
390 /// Returns a list of dependencies for the given package.
391 fn deps_of<'a>(metadata: &'a Metadata, pkg_id: &'a PackageId) -> Vec<&'a Package> {
392 let resolve = metadata.resolve.as_ref().unwrap();
396 .find(|n| &n.id == pkg_id)
397 .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
401 metadata.packages.iter().find(|pkg| pkg.id == dep.pkg).unwrap_or_else(|| {
402 panic!("could not find dep `{}` for pkg `{}` in resolve", dep.pkg, pkg_id)
408 /// Finds a package with the given name.
409 fn pkg_from_name<'a>(metadata: &'a Metadata, name: &'static str) -> &'a Package {
410 let mut i = metadata.packages.iter().filter(|p| p.name == name);
412 i.next().unwrap_or_else(|| panic!("could not find package `{}` in package list", name));
413 assert!(i.next().is_none(), "more than one package found for `{}`", name);
417 /// Finds all the packages that are in the rust runtime.
418 fn compute_runtime_crates<'a>(metadata: &'a Metadata) -> HashSet<&'a PackageId> {
419 let resolve = metadata.resolve.as_ref().unwrap();
420 let mut result = HashSet::new();
421 for name in RUNTIME_CRATES {
422 let id = &pkg_from_name(metadata, name).id;
423 normal_deps_of_r(resolve, id, &mut result);
428 /// Recursively find all normal dependencies.
429 fn normal_deps_of_r<'a>(
430 resolve: &'a Resolve,
431 pkg_id: &'a PackageId,
432 result: &mut HashSet<&'a PackageId>,
434 if !result.insert(pkg_id) {
440 .find(|n| &n.id == pkg_id)
441 .unwrap_or_else(|| panic!("could not find `{}` in resolve", pkg_id));
442 // Don't care about dev-dependencies.
443 // Build dependencies *shouldn't* matter unless they do some kind of
444 // codegen. For now we'll assume they don't.
445 let deps = node.deps.iter().filter(|node_dep| {
449 .any(|kind_info| kind_info.kind == cargo_metadata::DependencyKind::Normal)
452 normal_deps_of_r(resolve, &dep.pkg, result);