1use crate::error::ExtensionError;
17
18pub use super::spdx_exceptions::SPDX_LICENSE_EXCEPTIONS;
19
20const MAX_NESTING: usize = 64;
22
23pub const COMMON_SPDX_LICENSES: &[&str] = &[
43 "0BSD",
44 "AAL",
45 "AFL-3.0",
46 "AGPL-3.0-only",
47 "AGPL-3.0-or-later",
48 "Apache-2.0",
49 "Artistic-2.0",
50 "BSD-2-Clause",
51 "BSD-3-Clause",
52 "BSL-1.0",
53 "BlueOak-1.0.0",
54 "CAL-1.0",
55 "CAL-1.0-Combined-Work-Exception",
56 "CECILL-2.1",
57 "CERN-OHL-P-2.0",
58 "CERN-OHL-S-2.0",
59 "CERN-OHL-W-2.0",
60 "ECL-2.0",
61 "EFL-2.0",
62 "EPL-2.0",
63 "EUPL-1.2",
64 "GPL-2.0-only",
65 "GPL-2.0-or-later",
66 "GPL-3.0-only",
67 "GPL-3.0-or-later",
68 "ISC",
69 "LGPL-2.1-only",
70 "LGPL-2.1-or-later",
71 "LGPL-3.0-only",
72 "LGPL-3.0-or-later",
73 "MIT",
74 "MIT-0",
75 "MPL-2.0",
76 "MulanPSL-2.0",
77 "NCSA",
78 "OSL-3.0",
79 "PostgreSQL",
80 "RPL-1.5",
81 "SSPL-1.0",
82 "UPL-1.0",
83 "Unlicense",
84 "Zlib",
85];
86
87pub fn validate_spdx_license(license: &str) -> Result<(), ExtensionError> {
135 check_spdx_expression(license)?.map_or(Ok(()), |unlisted| Err(ExtensionError::new(unlisted)))
136}
137
138pub(crate) fn check_spdx_expression(license: &str) -> Result<Option<String>, ExtensionError> {
150 if license.trim().is_empty() {
151 return Err(ExtensionError::new("license identifier must not be empty"));
152 }
153
154 let tokens = tokenize(license);
155 let mut parser = ExprParser {
156 rest: &tokens,
157 depth: 0,
158 };
159 let unlisted = parser.expression().and_then(|unlisted| {
160 parser.rest.first().map_or(Ok(unlisted), |extra| {
161 Err(format!(
162 "unexpected '{extra}' in license expression '{license}'"
163 ))
164 })
165 });
166 let unlisted = unlisted.map_err(|msg| {
167 ExtensionError::new(format!(
168 "{msg}; expected an SPDX identifier such as 'MIT' or an expression such as \
169 'MIT OR Apache-2.0' — see https://spdx.org/licenses/"
170 ))
171 })?;
172 let Some(unlisted) = unlisted else {
173 return Ok(None);
174 };
175 for token in &tokens {
176 let id = token.strip_suffix('+').unwrap_or(token);
177 let spdx_chars = id
178 .bytes()
179 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-'));
180 if !matches!(*token, "(" | ")") && (id.is_empty() || !spdx_chars) {
181 return Err(ExtensionError::new(format!(
182 "license expression '{license}' contains '{token}', which is not an SPDX \
183 identifier: identifiers are letters, digits, '.' and '-' (see \
184 https://spdx.org/licenses/)"
185 )));
186 }
187 }
188 match unlisted {
189 Unlisted::License(id) => COMMON_SPDX_LICENSES
193 .iter()
194 .find(|known| known.eq_ignore_ascii_case(id))
195 .map_or_else(
196 || {
197 Ok(Some(format!(
198 "license '{id}' is not in quack-rs's list of common SPDX identifiers. \
199 It may still be valid — check https://spdx.org/licenses/. Common \
200 choices: MIT, Apache-2.0, BSD-3-Clause, GPL-3.0-or-later, MPL-2.0"
201 )))
202 },
203 |canonical| {
206 Err(ExtensionError::new(format!(
207 "license '{id}' should be spelled '{canonical}': SPDX identifiers match \
208 case-insensitively, but the canonical case is the one the SPDX list \
209 and its URLs use"
210 )))
211 },
212 ),
213 Unlisted::Exception(id) => Ok(Some(format!(
216 "license exception '{id}' is not in the SPDX license-exception list quack-rs \
217 carries (SPDX license list 3.29.0). Check the spelling and case at \
218 https://spdx.org/licenses/exceptions-index.html; an exception added to SPDX \
219 since then may still be valid"
220 ))),
221 }
222}
223
224fn tokenize(expr: &str) -> Vec<&str> {
226 let mut tokens = Vec::new();
227 let mut start: Option<usize> = None;
228 for (i, ch) in expr.char_indices() {
229 if ch.is_whitespace() || ch == '(' || ch == ')' {
230 if let Some(s) = start.take() {
231 tokens.push(&expr[s..i]);
232 }
233 if !ch.is_whitespace() {
234 tokens.push(&expr[i..=i]);
235 }
236 } else if start.is_none() {
237 start = Some(i);
238 }
239 }
240 if let Some(s) = start {
241 tokens.push(&expr[s..]);
242 }
243 tokens
244}
245
246#[derive(Clone, Copy)]
248enum Unlisted<'a> {
249 License(&'a str),
251 Exception(&'a str),
253}
254
255struct ExprParser<'a> {
269 rest: &'a [&'a str],
270 depth: usize,
271}
272
273impl<'a> ExprParser<'a> {
274 fn eat(&mut self, expected: &str) -> bool {
276 match self.rest.split_first() {
277 Some((&token, tail)) if token == expected => {
278 self.rest = tail;
279 true
280 }
281 _ => false,
282 }
283 }
284
285 fn expression(&mut self) -> Result<Option<Unlisted<'a>>, String> {
286 let mut unlisted = self.term()?;
287 while self.eat("OR") {
288 let next = self.term()?;
289 unlisted = unlisted.or(next);
290 }
291 Ok(unlisted)
292 }
293
294 fn term(&mut self) -> Result<Option<Unlisted<'a>>, String> {
295 let mut unlisted = self.atom()?;
296 while self.eat("AND") {
297 let next = self.atom()?;
298 unlisted = unlisted.or(next);
299 }
300 Ok(unlisted)
301 }
302
303 fn atom(&mut self) -> Result<Option<Unlisted<'a>>, String> {
304 let Some((&token, tail)) = self.rest.split_first() else {
305 return Err("license expression ends where an identifier was expected".into());
306 };
307 self.rest = tail;
308 match token {
309 "(" => {
310 if self.depth >= MAX_NESTING {
311 return Err(format!(
312 "license expression nests parentheses more than {MAX_NESTING} deep"
313 ));
314 }
315 self.depth += 1;
316 let unlisted = self.expression()?;
317 self.depth -= 1;
318 if self.eat(")") {
319 Ok(unlisted)
320 } else {
321 Err("unbalanced '(' in license expression".into())
322 }
323 }
324 ")" | "AND" | "OR" | "WITH" => {
325 Err(format!("'{token}' where a license identifier was expected"))
326 }
327 id => {
328 let license = (!COMMON_SPDX_LICENSES.contains(&id) && !is_license_ref(id))
329 .then_some(Unlisted::License(id));
330 let exception = if self.eat("WITH") {
331 self.exception()?
332 } else {
333 None
334 };
335 Ok(license.or(exception))
336 }
337 }
338 }
339
340 fn exception(&mut self) -> Result<Option<Unlisted<'a>>, String> {
342 let Some((&token, tail)) = self.rest.split_first() else {
343 return Err("license expression ends where a license exception was expected".into());
344 };
345 self.rest = tail;
346 match token {
347 "(" | ")" | "AND" | "OR" | "WITH" => Err(format!(
348 "'{token}' where a license exception identifier was expected after 'WITH'"
349 )),
350 id if SPDX_LICENSE_EXCEPTIONS.contains(&id) || is_addition_ref(id) => Ok(None),
351 id => Ok(Some(Unlisted::Exception(id))),
352 }
353 }
354}
355
356fn is_license_ref(id: &str) -> bool {
358 is_user_ref(id, "LicenseRef-")
359}
360
361fn is_addition_ref(id: &str) -> bool {
363 is_user_ref(id, "AdditionRef-")
364}
365
366fn is_user_ref(id: &str, prefix: &str) -> bool {
367 id.strip_prefix(prefix).is_some_and(|rest| {
368 !rest.is_empty()
369 && rest
370 .bytes()
371 .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
372 })
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn mit_accepted() {
381 assert!(validate_spdx_license("MIT").is_ok());
382 }
383
384 #[test]
385 fn apache_accepted() {
386 assert!(validate_spdx_license("Apache-2.0").is_ok());
387 }
388
389 #[test]
390 fn bsd_3_clause_accepted() {
391 assert!(validate_spdx_license("BSD-3-Clause").is_ok());
392 }
393
394 #[test]
395 fn gpl_accepted() {
396 assert!(validate_spdx_license("GPL-3.0-only").is_ok());
397 assert!(validate_spdx_license("GPL-2.0-or-later").is_ok());
398 }
399
400 #[test]
401 fn unlicense_accepted() {
402 assert!(validate_spdx_license("Unlicense").is_ok());
403 }
404
405 #[test]
409 fn expressions_of_listed_identifiers_are_accepted() {
410 for expr in [
411 "MIT OR Apache-2.0",
412 "(MIT OR Apache-2.0)",
413 "Apache-2.0 AND MIT",
414 "MIT OR (Apache-2.0 AND BSD-3-Clause)",
415 "LicenseRef-Proprietary",
416 "MIT OR LicenseRef-My.Terms-2",
417 ] {
418 assert!(validate_spdx_license(expr).is_ok(), "{expr}");
419 }
420 }
421
422 #[test]
423 fn malformed_or_unlisted_expressions_are_rejected() {
424 for expr in [
425 "MIT OR",
426 "OR MIT",
427 "MIT Apache-2.0",
428 "(MIT OR Apache-2.0",
429 "MIT OR Apache-2.0)",
430 "MIT or Apache-2.0",
431 "MIT OR CC0-1.0",
432 "()",
433 "LicenseRef-",
434 "BSL 1.1",
435 ] {
436 assert!(validate_spdx_license(expr).is_err(), "{expr}");
437 }
438 }
439
440 #[test]
444 fn deeply_nested_parentheses_are_an_error_not_a_stack_overflow() {
445 let depth = if cfg!(miri) { 1_000 } else { 1_000_000 };
449 let started = std::time::Instant::now();
450 let err = validate_spdx_license(&"(".repeat(depth)).unwrap_err();
451 assert!(err.as_str().contains("nests parentheses"), "{err}");
452 if !cfg!(miri) {
453 assert!(started.elapsed() < std::time::Duration::from_secs(5));
454 }
455
456 let yml = format!(
457 "extension:\n name: my_ext\n description: d\n language: Rust\n build: cargo\n \
458 license: \"{}\"\n maintainers:\n - a\nrepo:\n github: a/b\n ref: main\n",
459 "(".repeat(depth)
460 );
461 let parsed = crate::validate::description_yml::parse_description_yml(&yml)
462 .expect("an unusable license is a warning, not a parse failure");
463 assert!(
464 parsed
465 .warnings
466 .iter()
467 .any(|w| w.contains("nests parentheses")),
468 "{:?}",
469 parsed.warnings
470 );
471 }
472
473 #[test]
474 fn nesting_is_accepted_up_to_the_limit() {
475 let nested = |depth: usize| format!("{}MIT{}", "(".repeat(depth), ")".repeat(depth));
476 assert!(validate_spdx_license(&nested(MAX_NESTING)).is_ok());
477 assert!(validate_spdx_license(&nested(MAX_NESTING + 1)).is_err());
478 }
479
480 #[test]
484 fn sibling_groups_do_not_count_towards_the_nesting_limit() {
485 let group = format!("{}MIT{}", "(".repeat(MAX_NESTING), ")".repeat(MAX_NESTING));
486 let groups = if cfg!(miri) { 3 } else { MAX_NESTING + 2 };
489 let many = vec![group.as_str(); groups].join(" AND ");
490 assert!(validate_spdx_license(&many).is_ok(), "{many}");
491 let flat = vec!["(MIT)"; 2 * MAX_NESTING].join(" OR ");
492 assert!(validate_spdx_license(&flat).is_ok(), "{flat}");
493 }
494
495 #[test]
498 fn with_exception_is_accepted() {
499 for expr in [
500 "Apache-2.0 WITH LLVM-exception",
501 "GPL-2.0-or-later WITH Classpath-exception-2.0",
502 "(MIT OR Apache-2.0 WITH LLVM-exception)",
503 "MIT OR Apache-2.0 WITH LLVM-exception AND ISC",
504 "LicenseRef-Mine WITH GCC-exception-3.1",
505 "GPL-3.0-or-later WITH AdditionRef-My.Exception-1",
506 ] {
507 assert!(validate_spdx_license(expr).is_ok(), "{expr}");
508 }
509 }
510
511 #[test]
512 fn malformed_with_is_rejected() {
513 for expr in [
514 "MIT WITH",
515 "WITH LLVM-exception",
516 "MIT WITH LLVM-exception WITH LLVM-exception",
517 "MIT WITH (LLVM-exception)",
518 "(MIT OR ISC) WITH LLVM-exception",
519 "MIT WITH MIT",
520 "MIT with LLVM-exception",
521 "MIT WITH AdditionRef-",
522 ] {
523 assert!(validate_spdx_license(expr).is_err(), "{expr}");
524 }
525 }
526
527 #[test]
528 fn unknown_exception_is_named_and_not_called_invalid() {
529 let err = validate_spdx_license("MIT WITH Made-Up-exception").unwrap_err();
530 assert!(err.as_str().contains("Made-Up-exception"), "{err}");
531 assert!(err.as_str().contains("exceptions-index"), "{err}");
532 }
533
534 #[test]
535 fn unlisted_license_with_a_real_exception_reports_the_license() {
536 let err = validate_spdx_license("CC0-1.0 WITH LLVM-exception").unwrap_err();
537 assert!(err.as_str().contains("'CC0-1.0'"), "{err}");
538 assert!(err.as_str().contains("may still be valid"), "{err}");
539 }
540
541 #[test]
542 fn exception_list_is_sorted_and_unique() {
543 let mut sorted = SPDX_LICENSE_EXCEPTIONS.to_vec();
544 sorted.sort_unstable();
545 assert_eq!(sorted.as_slice(), SPDX_LICENSE_EXCEPTIONS);
546 sorted.dedup();
547 assert_eq!(sorted.len(), SPDX_LICENSE_EXCEPTIONS.len());
548 }
549
550 #[test]
551 fn empty_rejected() {
552 let err = validate_spdx_license("").unwrap_err();
553 assert!(err.as_str().contains("empty"));
554 }
555
556 #[test]
557 fn unknown_license_rejected() {
558 let err = validate_spdx_license("FAKE-LICENSE").unwrap_err();
559 assert!(err.as_str().contains("not in quack-rs's list"));
560 }
561
562 #[test]
563 fn rejection_does_not_claim_the_identifier_is_invalid() {
564 let err = validate_spdx_license("CC0-1.0").unwrap_err();
568 assert!(
569 err.as_str().contains("may still be valid"),
570 "misleading message: {err}"
571 );
572 assert!(err.as_str().contains("spdx.org/licenses"));
573 }
574
575 #[test]
576 fn list_is_sorted_and_unique() {
577 let mut sorted = COMMON_SPDX_LICENSES.to_vec();
578 sorted.sort_unstable();
579 assert_eq!(
580 sorted.as_slice(),
581 COMMON_SPDX_LICENSES,
582 "keep the list sorted so additions are reviewable"
583 );
584 sorted.dedup();
585 assert_eq!(sorted.len(), COMMON_SPDX_LICENSES.len());
586 }
587
588 #[test]
592 fn a_case_only_difference_names_the_canonical_spelling() {
593 for (given, canonical) in [("mit", "MIT"), ("apache-2.0", "Apache-2.0")] {
594 let err = validate_spdx_license(given).expect_err(given);
595 assert!(
596 err.as_str()
597 .contains(&format!("should be spelled '{canonical}'")),
598 "{err}"
599 );
600 }
601 let err = validate_spdx_license("NotALicense").expect_err("unlisted");
602 assert!(err.as_str().contains("not in quack-rs's list"), "{err}");
603 }
604
605 #[test]
606 fn all_listed_licenses_validate() {
607 for &license in COMMON_SPDX_LICENSES {
608 assert!(
609 validate_spdx_license(license).is_ok(),
610 "expected '{license}' to be accepted"
611 );
612 }
613 }
614}