1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! License data structures and SPDX expression handling.
//!
//! Uses the `spdx` crate for proper SPDX expression parsing and license
//! classification, with substring-based fallback for non-standard expressions.
use serde::{Deserialize, Serialize};
use std::fmt;
/// License expression following SPDX license expression syntax
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseExpression {
/// The raw license expression string
pub expression: String,
/// Whether this is a valid SPDX expression
pub is_valid_spdx: bool,
/// Human-readable name resolved from the document's license
/// definitions (e.g. SPDX hasExtractedLicensingInfos for a bare
/// `LicenseRef-*` expression). Display metadata only: excluded from
/// equality/hashing below so identical expressions stay equal (and
/// pre-existing serialized SBOMs stay diff-identical) whether or not
/// resolution ran.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolved_name: Option<String>,
}
/// Equality/hashing deliberately ignore `resolved_name`: the raw
/// expression is the license identity.
impl PartialEq for LicenseExpression {
fn eq(&self, other: &Self) -> bool {
self.expression == other.expression && self.is_valid_spdx == other.is_valid_spdx
}
}
impl Eq for LicenseExpression {}
impl std::hash::Hash for LicenseExpression {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.expression.hash(state);
self.is_valid_spdx.hash(state);
}
}
impl LicenseExpression {
/// Create a new license expression
#[must_use]
pub fn new(expression: String) -> Self {
let is_valid_spdx = Self::validate_spdx(&expression);
Self {
expression,
is_valid_spdx,
resolved_name: None,
}
}
/// Human-readable display form: the name resolved from the document's
/// license definitions (e.g. SPDX `hasExtractedLicensingInfos` for a bare
/// `LicenseRef-*`) when present, otherwise the raw expression. For
/// rendering/emit only — equality and identity stay on `expression`.
#[must_use]
pub fn display_name(&self) -> &str {
self.resolved_name.as_deref().unwrap_or(&self.expression)
}
/// Create from an SPDX license ID
#[must_use]
pub fn from_spdx_id(id: &str) -> Self {
// Validate rather than trusting the caller: scoring now relies on
// `is_valid_spdx`, so a hardcoded `true` would be a footgun.
Self::new(id.to_string())
}
/// Validate an SPDX expression using the spdx crate.
///
/// Uses lax parsing mode to accept common non-standard expressions
/// (e.g., "Apache2" instead of "Apache-2.0", "/" instead of "OR").
fn validate_spdx(expr: &str) -> bool {
// Reject expressions with a NOASSERTION/NONE clause (no license
// information), matching whole tokens so that legitimate ids like
// `LicenseRef-NONEXCLUSIVE` are not caught by a substring test.
let has_no_info_token = expr
.split(|c: char| c.is_whitespace() || c == '(' || c == ')')
.any(|tok| tok == "NOASSERTION" || tok == "NONE");
if expr.is_empty() || has_no_info_token {
return false;
}
spdx::Expression::parse_mode(expr, spdx::ParseMode::LAX).is_ok()
}
/// Check if this expression includes a permissive license option.
///
/// For OR expressions (e.g., "MIT OR GPL-2.0"), returns true if at least
/// one branch is permissive (the licensee can choose the permissive option).
/// Falls back to substring matching for non-parseable expressions.
#[must_use]
pub fn is_permissive(&self) -> bool {
spdx::Expression::parse_mode(&self.expression, spdx::ParseMode::LAX).map_or_else(
|_| {
// Fallback for non-standard expressions
let expr_lower = self.expression.to_lowercase();
expr_lower.contains("mit")
|| expr_lower.contains("apache")
|| expr_lower.contains("bsd")
|| expr_lower.contains("isc")
|| expr_lower.contains("unlicense")
},
|expr| {
expr.requirements().any(|req| {
if let spdx::LicenseItem::Spdx { id, .. } = req.req.license {
!id.is_copyleft() && (id.is_osi_approved() || id.is_fsf_free_libre())
} else {
false
}
})
},
)
}
/// Check if this expression requires copyleft compliance.
///
/// Returns true if any license term in the expression is copyleft.
/// Falls back to substring matching for non-parseable expressions.
#[must_use]
pub fn is_copyleft(&self) -> bool {
spdx::Expression::parse_mode(&self.expression, spdx::ParseMode::LAX).map_or_else(
|_| {
let expr_lower = self.expression.to_lowercase();
expr_lower.contains("gpl")
|| expr_lower.contains("agpl")
|| expr_lower.contains("lgpl")
|| expr_lower.contains("mpl")
},
|expr| {
expr.requirements().any(|req| {
if let spdx::LicenseItem::Spdx { id, .. } = req.req.license {
id.is_copyleft()
} else {
false
}
})
},
)
}
/// Get the license family classification.
///
/// For compound expressions:
/// - OR: returns the most permissive option (licensee can choose)
/// - AND: returns the most restrictive requirement
/// Falls back to substring matching for non-parseable expressions.
#[must_use]
pub fn family(&self) -> LicenseFamily {
if let Ok(expr) = spdx::Expression::parse_mode(&self.expression, spdx::ParseMode::LAX) {
let mut has_copyleft = false;
let mut has_weak_copyleft = false;
let mut has_permissive = false;
let mut has_or = false;
for node in expr.iter() {
match node {
spdx::expression::ExprNode::Op(spdx::expression::Operator::Or) => {
has_or = true;
}
spdx::expression::ExprNode::Req(req) => {
if let spdx::LicenseItem::Spdx { id, .. } = req.req.license {
match classify_spdx_license(id) {
LicenseFamily::Copyleft => has_copyleft = true,
LicenseFamily::WeakCopyleft => has_weak_copyleft = true,
LicenseFamily::Permissive | LicenseFamily::PublicDomain => {
has_permissive = true;
}
_ => {}
}
}
}
spdx::expression::ExprNode::Op(_) => {}
}
}
// OR: licensee can choose the most permissive option
if has_or && has_permissive {
return LicenseFamily::Permissive;
}
// AND or single license: return the most restrictive
if has_copyleft {
LicenseFamily::Copyleft
} else if has_weak_copyleft {
LicenseFamily::WeakCopyleft
} else if has_permissive {
LicenseFamily::Permissive
} else {
LicenseFamily::Other
}
} else {
// Fallback for non-parseable expressions
self.family_from_substring()
}
}
/// Substring-based fallback for license family classification.
fn family_from_substring(&self) -> LicenseFamily {
let expr_lower = self.expression.to_lowercase();
if expr_lower.contains("mit")
|| expr_lower.contains("apache")
|| expr_lower.contains("bsd")
|| expr_lower.contains("isc")
|| expr_lower.contains("unlicense")
{
LicenseFamily::Permissive
} else if expr_lower.contains("gpl")
|| expr_lower.contains("agpl")
|| expr_lower.contains("lgpl")
|| expr_lower.contains("mpl")
{
LicenseFamily::Copyleft
} else if expr_lower.contains("proprietary") {
LicenseFamily::Proprietary
} else {
LicenseFamily::Other
}
}
}
/// Rank a license family by restrictiveness (higher is more restrictive).
fn family_restrictiveness(family: &LicenseFamily) -> u8 {
match family {
LicenseFamily::Proprietary => 5,
LicenseFamily::Copyleft => 4,
LicenseFamily::WeakCopyleft => 3,
LicenseFamily::Permissive => 2,
LicenseFamily::PublicDomain => 1,
LicenseFamily::Other => 0,
}
}
/// Classify an SPDX license ID into a license family.
fn classify_spdx_license(id: spdx::LicenseId) -> LicenseFamily {
let name = id.name;
// Check for public domain dedications
if name == "CC0-1.0" || name == "Unlicense" || name == "0BSD" {
return LicenseFamily::PublicDomain;
}
if id.is_copyleft() {
// Distinguish weak copyleft (LGPL, MPL, EPL, CDDL) from strong copyleft (GPL, AGPL)
let name_upper = name.to_uppercase();
if name_upper.contains("LGPL")
|| name_upper.starts_with("MPL")
|| name_upper.starts_with("EPL")
|| name_upper.starts_with("CDDL")
|| name_upper.starts_with("EUPL")
|| name_upper.starts_with("OSL")
{
LicenseFamily::WeakCopyleft
} else {
LicenseFamily::Copyleft
}
} else if id.is_osi_approved() || id.is_fsf_free_libre() {
LicenseFamily::Permissive
} else {
LicenseFamily::Other
}
}
impl fmt::Display for LicenseExpression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.expression)
}
}
impl Default for LicenseExpression {
fn default() -> Self {
Self {
expression: "NOASSERTION".to_string(),
is_valid_spdx: false,
resolved_name: None,
}
}
}
/// License family classification
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum LicenseFamily {
Permissive,
Copyleft,
WeakCopyleft,
Proprietary,
PublicDomain,
Other,
}
impl fmt::Display for LicenseFamily {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Permissive => write!(f, "Permissive"),
Self::Copyleft => write!(f, "Copyleft"),
Self::WeakCopyleft => write!(f, "Weak Copyleft"),
Self::Proprietary => write!(f, "Proprietary"),
Self::PublicDomain => write!(f, "Public Domain"),
Self::Other => write!(f, "Other"),
}
}
}
/// License information for a component
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LicenseInfo {
/// Declared licenses from the component metadata
pub declared: Vec<LicenseExpression>,
/// Concluded license after analysis
pub concluded: Option<LicenseExpression>,
/// License evidence from scanning
pub evidence: Vec<LicenseEvidence>,
}
impl LicenseInfo {
/// Create new empty license info
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Add a declared license
pub fn add_declared(&mut self, license: LicenseExpression) {
self.declared.push(license);
}
/// Get all unique license expressions
#[must_use]
pub fn all_licenses(&self) -> Vec<&LicenseExpression> {
let mut licenses: Vec<&LicenseExpression> = self.declared.iter().collect();
if let Some(concluded) = &self.concluded {
licenses.push(concluded);
}
licenses
}
/// Get the effective license family across all expressions.
///
/// Per-expression OR-choice is already resolved inside
/// [`LicenseExpression::family`]; multiple expressions (declared and
/// concluded) are treated conjunctively (conservative), so the most
/// restrictive family wins:
/// Proprietary > Copyleft > `WeakCopyleft` > Permissive > `PublicDomain` > Other.
/// Returns [`LicenseFamily::Other`] when no licenses are present.
#[must_use]
pub fn effective_family(&self) -> LicenseFamily {
self.all_licenses()
.into_iter()
.map(LicenseExpression::family)
.max_by_key(family_restrictiveness)
.unwrap_or(LicenseFamily::Other)
}
/// Check if there are potential license conflicts across license expressions
/// (declared and concluded).
///
/// A conflict exists when one expression requires copyleft compliance
/// and another declares proprietary terms. Note that a single expression like
/// "MIT OR GPL-2.0" is NOT a conflict — it offers a choice.
pub fn has_conflicts(&self) -> bool {
let families: Vec<LicenseFamily> = self
.all_licenses()
.into_iter()
.map(LicenseExpression::family)
.collect();
let has_copyleft = families.contains(&LicenseFamily::Copyleft);
let has_proprietary = families.contains(&LicenseFamily::Proprietary);
has_copyleft && has_proprietary
}
}
/// License evidence from source scanning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LicenseEvidence {
/// The detected license
pub license: LicenseExpression,
/// Confidence score (0.0 - 1.0)
pub confidence: f64,
/// File path where detected
pub file_path: Option<String>,
/// Line number in the file
pub line_number: Option<u32>,
}
impl LicenseEvidence {
/// Create new license evidence
#[must_use]
pub const fn new(license: LicenseExpression, confidence: f64) -> Self {
Self {
license,
confidence,
file_path: None,
line_number: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn info(declared: &[&str], concluded: Option<&str>) -> LicenseInfo {
let mut info = LicenseInfo::new();
for lic in declared {
info.add_declared(LicenseExpression::new((*lic).to_string()));
}
info.concluded = concluded.map(|c| LicenseExpression::new(c.to_string()));
info
}
#[test]
fn effective_family_precedence() {
assert_eq!(info(&[], None).effective_family(), LicenseFamily::Other);
assert_eq!(
info(&["MIT"], None).effective_family(),
LicenseFamily::Permissive
);
assert_eq!(
info(&["MIT", "GPL-3.0-only"], None).effective_family(),
LicenseFamily::Copyleft
);
assert_eq!(
info(&["MIT", "LGPL-3.0-only"], None).effective_family(),
LicenseFamily::WeakCopyleft
);
assert_eq!(
info(&["GPL-3.0-only", "Proprietary"], None).effective_family(),
LicenseFamily::Proprietary
);
assert_eq!(
info(&["MIT"], Some("GPL-3.0-only")).effective_family(),
LicenseFamily::Copyleft
);
}
#[test]
fn display_name_prefers_resolved_name() {
let mut lic = LicenseExpression::new("LicenseRef-foo".to_string());
assert_eq!(lic.display_name(), "LicenseRef-foo");
lic.resolved_name = Some("Foo Proprietary License".to_string());
assert_eq!(lic.display_name(), "Foo Proprietary License");
// Identity (equality) still ignores the resolved display name.
assert_eq!(lic, LicenseExpression::new("LicenseRef-foo".to_string()));
}
#[test]
fn has_conflicts_includes_concluded() {
let conflicted = info(&["Proprietary"], Some("GPL-3.0-only"));
assert!(conflicted.has_conflicts());
let declared_only = info(&["GPL-3.0-only", "Proprietary"], None);
assert!(declared_only.has_conflicts());
let no_conflict = info(&["MIT"], Some("GPL-3.0-only"));
assert!(!no_conflict.has_conflicts());
}
}