1 //! Checks the licenses of third-party dependencies by inspecting vendors.
3 use std::collections::{BTreeSet, HashSet, HashMap};
6 use std::process::Command;
8 use serde::Deserialize;
11 const LICENSES: &[&str] = &[
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] = &[
27 "mdbook", // MPL2, mdbook
28 "openssl", // BSD+advertising clause, cargo, mdbook
29 "pest", // MPL2, mdbook via handlebars
30 "arrayref", // BSD-2-Clause, mdbook via handlebars via pest
31 "thread-id", // Apache-2.0, mdbook
32 "toml-query", // MPL-2.0, mdbook
33 "is-match", // MPL-2.0, mdbook
34 "cssparser", // MPL-2.0, rustdoc
35 "smallvec", // MPL-2.0, rustdoc
36 "fuchsia-zircon-sys", // BSD-3-Clause, rustdoc, rustc, cargo
37 "fuchsia-zircon", // BSD-3-Clause, rustdoc, rustc, cargo (jobserver & tempdir)
38 "cssparser-macros", // MPL-2.0, rustdoc
39 "selectors", // MPL-2.0, rustdoc
40 "clippy_lints", // MPL-2.0, rls
41 "colored", // MPL-2.0, rustfmt
42 "ordslice", // Apache-2.0, rls
43 "cloudabi", // BSD-2-Clause, (rls -> crossbeam-channel 0.2 -> rand 0.5)
44 "ryu", // Apache-2.0, rls/cargo/... (because of serde)
45 "bytesize", // Apache-2.0, cargo
46 "im-rc", // MPL-2.0+, cargo
47 "adler32", // BSD-3-Clause AND Zlib, cargo dep that isn't used
48 "fortanix-sgx-abi", // MPL-2.0+, libstd but only for `sgx` target
49 "constant_time_eq", // CC0-1.0, rustfmt
52 /// Which crates to check against the whitelist?
53 const WHITELIST_CRATES: &[CrateVersion<'_>] = &[
54 CrateVersion("rustc", "0.0.0"),
55 CrateVersion("rustc_codegen_llvm", "0.0.0"),
58 /// Whitelist of crates rustc is allowed to depend on. Avoid adding to the list if possible.
59 const WHITELIST: &[Crate<'_>] = &[
61 Crate("aho-corasick"),
65 Crate("backtrace-sys"),
71 Crate("chalk-engine"),
72 Crate("chalk-macros"),
75 Crate("compiler_builtins"),
78 Crate("crossbeam-deque"),
79 Crate("crossbeam-epoch"),
80 Crate("crossbeam-utils"),
87 Crate("fuchsia-zircon"),
88 Crate("fuchsia-zircon-sys"),
93 Crate("kernel32-sys"),
99 Crate("log_settings"),
105 Crate("miniz_oxide"),
106 Crate("miniz_oxide_c_api"),
110 Crate("parking_lot"),
111 Crate("parking_lot_core"),
113 Crate("polonius-engine"),
114 Crate("proc-macro2"),
115 Crate("quick-error"),
118 Crate("rand_chacha"),
123 Crate("rand_xorshift"),
124 Crate("redox_syscall"),
125 Crate("redox_termios"),
127 Crate("regex-syntax"),
128 Crate("remove_dir_all"),
129 Crate("rustc-demangle"),
131 Crate("rustc-rayon"),
132 Crate("rustc-rayon-core"),
133 Crate("rustc_version"),
137 Crate("semver-parser"),
139 Crate("serde_derive"),
141 Crate("stable_deref_trait"),
143 Crate("synstructure"),
148 Crate("thread_local"),
150 Crate("unicode-width"),
151 Crate("unicode-xid"),
152 Crate("unreachable"),
153 Crate("utf8-ranges"),
155 Crate("version_check"),
158 Crate("winapi-build"),
159 Crate("winapi-i686-pc-windows-gnu"),
160 Crate("winapi-util"),
161 Crate("winapi-x86_64-pc-windows-gnu"),
165 // Some types for Serde to deserialize the output of `cargo metadata` to.
167 #[derive(Deserialize)]
172 #[derive(Deserialize)]
174 nodes: Vec<ResolveNode>,
177 #[derive(Deserialize)]
180 dependencies: Vec<String>,
183 /// A unique identifier for a crate.
184 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
185 struct Crate<'a>(&'a str); // (name)
187 #[derive(Copy, Clone, PartialOrd, Ord, PartialEq, Eq, Debug, Hash)]
188 struct CrateVersion<'a>(&'a str, &'a str); // (name, version)
191 pub fn id_str(&self) -> String {
192 format!("{} ", self.0)
196 impl<'a> CrateVersion<'a> {
197 /// Returns the struct and whether or not the dependency is in-tree.
198 pub fn from_str(s: &'a str) -> (Self, bool) {
199 let mut parts = s.split(' ');
200 let name = parts.next().unwrap();
201 let version = parts.next().unwrap();
202 let path = parts.next().unwrap();
204 let is_path_dep = path.starts_with("(path+");
206 (CrateVersion(name, version), is_path_dep)
209 pub fn id_str(&self) -> String {
210 format!("{} {}", self.0, self.1)
214 impl<'a> From<CrateVersion<'a>> for Crate<'a> {
215 fn from(cv: CrateVersion<'a>) -> Crate<'a> {
220 /// Checks the dependency at the given path. Changes `bad` to `true` if a check failed.
222 /// Specifically, this checks that the license is correct.
223 pub fn check(path: &Path, bad: &mut bool) {
225 let path = path.join("../vendor");
226 assert!(path.exists(), "vendor directory missing");
227 let mut saw_dir = false;
228 for dir in t!(path.read_dir()) {
232 // Skip our exceptions.
233 let is_exception = EXCEPTIONS.iter().any(|exception| {
237 .contains(&format!("vendor/{}", exception))
243 let toml = dir.path().join("Cargo.toml");
244 *bad = *bad || !check_license(&toml);
246 assert!(saw_dir, "no vendored source");
249 /// Checks the dependency of `WHITELIST_CRATES` at the given path. Changes `bad` to `true` if a
252 /// Specifically, this checks that the dependencies are on the `WHITELIST`.
253 pub fn check_whitelist(path: &Path, cargo: &Path, bad: &mut bool) {
254 // Get dependencies from Cargo metadata.
255 let resolve = get_deps(path, cargo);
257 // Get the whitelist in a convenient form.
258 let whitelist: HashSet<_> = WHITELIST.iter().cloned().collect();
260 // Check dependencies.
261 let mut visited = BTreeSet::new();
262 let mut unapproved = BTreeSet::new();
263 for &krate in WHITELIST_CRATES.iter() {
264 let mut bad = check_crate_whitelist(&whitelist, &resolve, &mut visited, krate, false);
265 unapproved.append(&mut bad);
268 if !unapproved.is_empty() {
269 println!("Dependencies not on the whitelist:");
270 for dep in unapproved {
271 println!("* {}", dep.id_str());
276 check_crate_duplicate(&resolve, bad);
279 fn check_license(path: &Path) -> bool {
281 panic!("{} does not exist", path.display());
283 let contents = t!(fs::read_to_string(&path));
285 let mut found_license = false;
286 for line in contents.lines() {
287 if !line.starts_with("license") {
290 let license = extract_license(line);
291 if !LICENSES.contains(&&*license) {
292 println!("invalid license {} in {}", license, path.display());
295 found_license = true;
299 println!("no license in {}", path.display());
306 fn extract_license(line: &str) -> String {
307 let first_quote = line.find('"');
308 let last_quote = line.rfind('"');
309 if let (Some(f), Some(l)) = (first_quote, last_quote) {
310 let license = &line[f + 1..l];
313 "bad-license-parse".into()
317 /// Gets the dependencies of the crate at the given path using `cargo metadata`.
318 fn get_deps(path: &Path, cargo: &Path) -> Resolve {
319 // Run `cargo metadata` to get the set of dependencies.
320 let output = Command::new(cargo)
322 .arg("--format-version")
324 .arg("--manifest-path")
325 .arg(path.join("../Cargo.toml"))
327 .expect("Unable to run `cargo metadata`")
329 let output = String::from_utf8_lossy(&output);
330 let output: Output = serde_json::from_str(&output).unwrap();
335 /// Checks the dependencies of the given crate from the given cargo metadata to see if they are on
336 /// the whitelist. Returns a list of illegal dependencies.
337 fn check_crate_whitelist<'a>(
338 whitelist: &'a HashSet<Crate<'_>>,
339 resolve: &'a Resolve,
340 visited: &mut BTreeSet<CrateVersion<'a>>,
341 krate: CrateVersion<'a>,
342 must_be_on_whitelist: bool,
343 ) -> BTreeSet<Crate<'a>> {
344 // This will contain bad deps.
345 let mut unapproved = BTreeSet::new();
347 // Check if we have already visited this crate.
348 if visited.contains(&krate) {
352 visited.insert(krate);
354 // If this path is in-tree, we don't require it to be on the whitelist.
355 if must_be_on_whitelist {
356 // If this dependency is not on `WHITELIST`, add to bad set.
357 if !whitelist.contains(&krate.into()) {
358 unapproved.insert(krate.into());
362 // Do a DFS in the crate graph (it's a DAG, so we know we have no cycles!).
363 let to_check = resolve
366 .find(|n| n.id.starts_with(&krate.id_str()))
367 .expect("crate does not exist");
369 for dep in to_check.dependencies.iter() {
370 let (krate, is_path_dep) = CrateVersion::from_str(dep);
372 let mut bad = check_crate_whitelist(whitelist, resolve, visited, krate, !is_path_dep);
373 unapproved.append(&mut bad);
379 fn check_crate_duplicate(resolve: &Resolve, bad: &mut bool) {
380 const FORBIDDEN_TO_HAVE_DUPLICATES: &[&str] = &[
381 // These two crates take quite a long time to build, so don't allow two versions of them
382 // to accidentally sneak into our dependency graph, in order to ensure we keep our CI times
388 let mut name_to_id: HashMap<_, Vec<_>> = HashMap::new();
389 for node in resolve.nodes.iter() {
390 name_to_id.entry(node.id.split_whitespace().next().unwrap())
395 for name in FORBIDDEN_TO_HAVE_DUPLICATES {
396 if name_to_id[name].len() <= 1 {
399 println!("crate `{}` is duplicated in `Cargo.lock`", name);
400 for id in name_to_id[name].iter() {
401 println!(" * {}", id);