#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Set reported license and source link for backend dependencies (#8765)
EthanHealy01b78729215bf3
diff --git a/.github/config/.files.yaml b/.github/config/.files.yamlindex c09cda6ae5..648ca08e01 100644--- a/.github/config/.files.yaml+++ b/.github/config/.files.yaml@@ -13,6 +13,8 @@ build: &build- build.gradle- gradle/spotless.gradle- app/(common|core|proprietary|saas)/build.gradle+ - app/allowed-licenses.json+ - app/license-overrides.json- Taskfile.yml- .taskfiles/backend.yml- .github/workflows/check-licence.ymldiff --git a/app/allowed-licenses.json b/app/allowed-licenses.jsonindex 033661629f..c035fbf9a6 100644--- a/app/allowed-licenses.json+++ b/app/allowed-licenses.json@@ -2,239 +2,255 @@"allowedLicenses": [{"moduleName": ".*",- "moduleLicense": "BSD License"+ "moduleLicense": "BSD License",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "The BSD License"+ "moduleLicense": "The BSD License",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "BSD-2-Clause"+ "moduleLicense": "BSD-2-Clause",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "BSD 2-Clause License"+ "moduleLicense": "BSD 2-Clause License",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "The 2-Clause BSD License"+ "moduleLicense": "BSD-3-Clause",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "BSD-3-Clause"+ "moduleLicense": "The BSD 3-Clause License (BSD3)",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "The BSD 3-Clause License (BSD3)"+ "moduleLicense": "BSD 3-Clause License",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "BSD-4 License"+ "moduleLicense": "EDL 1.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "Revised BSD"+ "moduleLicense": "Eclipse Distribution License - v 1.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "ISC"+ "moduleLicense": "Eclipse Distribution License v. 1.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "MIT"+ "moduleLicense": "Revised BSD",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "MIT License"+ "moduleLicense": "ISC",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "The MIT License"+ "moduleLicense": "MIT",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "MIT-0"+ "moduleLicense": "MIT License",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "MIT license"- },- {- "moduleName": "com.github.jai-imageio:jai-imageio-core",- "moduleLicense": "LICENSE.txt"- },- {- "moduleName": "com.github.jai-imageio:jai-imageio-jpeg2000",- "moduleLicense": "LICENSE-JJ2000.txt, LICENSE-Sun.txt"- },- {- "moduleName": ".*",- "moduleLicense": "Apache 2"- },- {- "moduleName": ".*",- "moduleLicense": "Apache 2.0"- },- {- "moduleName": ".*",- "moduleLicense": "Apache-2.0"- },- {- "moduleName": ".*",- "moduleLicense": "Apache-2.0 License"- },- {- "moduleName": ".*",- "moduleLicense": "Apache License 2.0"- },- {- "moduleName": ".*",- "moduleLicense": "Apache License Version 2.0"- },- {- "moduleName": ".*",- "moduleLicense": "Apache License version 2.0"- },- {- "moduleName": ".*",- "moduleLicense": "Apache License, Version 2.0"+ "moduleLicense": "The MIT License",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "Apache License, version 2.0"+ "moduleLicense": "MIT-0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "The Apache License, Version 2.0"+ "moduleLicense": "MIT license",+ "category": "permissive"},{- "moduleName": ".*",- "moduleLicense": "The Apache Software License, Version 2.0"+ "moduleName": "com.github.jai-imageio:jai-imageio-core",+ "moduleLicense": "BSD 3-clause License w/nuclear disclaimer",+ "category": "permissive"},{- "moduleName": "com.nimbusds:oauth2-oidc-sdk",- "moduleLicense": "\"Apache License, version 2.0\";link=\"https://www.apache.org/licenses/LICENSE-2.0.html\""+ "moduleName": "com.github.jai-imageio:jai-imageio-jpeg2000",+ "moduleLicense": "BSD 3-clause License w/nuclear disclaimer AND JJ2000",+ "allOf": [+ "BSD 3-clause License w/nuclear disclaimer",+ "JJ2000"+ ],+ "category": "restricted"},{- "moduleName": ".*",- "moduleLicense": "MPL 2.0"+ "moduleName": "org.verapdf:verapdf-xmp-core",+ "moduleLicense": "BSD 3-Clause License AND Mozilla Public License 2.0 (MPL-2.0)",+ "allOf": [+ "BSD 3-Clause License",+ "Mozilla Public License 2.0 (MPL-2.0)"+ ],+ "category": "weak-copyleft"},{- "moduleName": ".*",- "moduleLicense": "Mozilla Public License, Version 2.0"+ "moduleName": "com.github.mwiede:jsch",+ "moduleLicense": "Revised BSD AND ISC",+ "allOf": [+ "Revised BSD",+ "ISC"+ ],+ "category": "permissive"},{- "moduleName": ".*",- "moduleLicense": "Mozilla Public License 2.0 (MPL-2.0)"+ "moduleName": "xml-apis:xml-apis",+ "moduleLicense": "The Apache Software License, Version 2.0 AND The SAX License AND The W3C License",+ "allOf": [+ "The Apache Software License, Version 2.0",+ "The SAX License",+ "The W3C License"+ ],+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "Mozilla Public License Version 2.0"+ "moduleLicense": "Apache 2",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "CDDL+GPL License"+ "moduleLicense": "Apache 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "BSD"+ "moduleLicense": "Apache-2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "UnboundID SCIM2 SDK Free Use License"+ "moduleLicense": "Apache License 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "GPL2 w/ CPE"+ "moduleLicense": "Apache License Version 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "GPLv2+CE"+ "moduleLicense": "Apache License version 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "GNU GENERAL PUBLIC LICENSE, Version 2 + Classpath Exception"+ "moduleLicense": "Apache License, Version 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "GNU Lesser Public License"+ "moduleLicense": "Apache License, version 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "The GNU Lesser General Public License"- },- {- "moduleName": "com.martiansoftware:jsap",- "moduleLicense": "LGPL"- },- {- "moduleName": "org.hibernate.orm:hibernate-core",- "moduleLicense": "GNU Library General Public License v2.1 or later"+ "moduleLicense": "The Apache License, Version 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0"+ "moduleLicense": "The Apache Software License, Version 2.0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "Eclipse Public License 1.0"+ "moduleLicense": "MPL 2.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "Eclipse Public License - v 1.0"+ "moduleLicense": "Mozilla Public License, Version 2.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "Eclipse Public License v2.0"+ "moduleLicense": "Mozilla Public License 2.0 (MPL-2.0)",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "Eclipse Public License v. 2.0"+ "moduleLicense": "Mozilla Public License Version 2.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "Eclipse Public License - v 2.0"+ "moduleLicense": "BSD",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "Eclipse Public License - Version 2.0"+ "moduleLicense": "COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "Eclipse Public License, Version 2.0"+ "moduleLicense": "Eclipse Public License v. 2.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "EPL-2.0"+ "moduleLicense": "Eclipse Public License - v 2.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "LGPL-2.1-only"+ "moduleLicense": "Eclipse Public License, Version 2.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "Ubuntu Font Licence 1.0"+ "moduleLicense": "EPL-2.0",+ "category": "weak-copyleft"},{"moduleName": ".*",- "moduleLicense": "Bouncy Castle Licence"+ "moduleLicense": "Bouncy Castle Licence",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "Public Domain, per Creative Commons CC0"+ "moduleLicense": "Public Domain, per Creative Commons CC0",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "The W3C License"+ "moduleLicense": "The W3C License",+ "category": "permissive"},{"moduleName": "com.google.re2j:re2j",- "moduleLicense": "Go License"+ "moduleLicense": "Go License",+ "category": "permissive"},{"moduleName": ".*",- "moduleLicense": "UnRar License"+ "moduleLicense": "UnRar License",+ "category": "restricted"}]}diff --git a/build.gradle b/build.gradleindex d6667a3bb6..ec2f78705b 100644--- a/build.gradle+++ b/build.gradle@@ -19,6 +19,7 @@ import org.gradle.api.JavaVersionimport org.gradle.api.tasks.testing.Testimport org.gradle.jvm.toolchain.JavaLanguageVersionimport stirling.software.gradle.ModuleLicenseOverrideFilter+import stirling.software.gradle.PreferredLicenseFilterext {springBootVersion = "4.1.2"@@ -596,18 +597,23 @@ gradle.taskGraph.whenReady { graph ->def allProjects = ((subprojects as Set<Project>) + project) as Set<Project>def moduleLicenseOverridesFile = project.layout.projectDirectory.file("app/license-overrides.json").asFile+def allowedLicensesJsonFile = project.layout.projectDirectory.file("app/allowed-licenses.json").asFilelicenseReport {projects = allProjectsrenderers = [new JsonReportRenderer()]- allowedLicensesFile = project.layout.projectDirectory.file("app/allowed-licenses.json").asFile+ allowedLicensesFile = allowedLicensesJsonFileoutputDir = project.layout.buildDirectory.dir("reports/dependency-license").get().asFile.pathconfigurations = [ "productionRuntimeClasspath", "runtimeClasspath" ]- filters = [new ModuleLicenseOverrideFilter(moduleLicenseOverridesFile)]+ filters = [+ new ModuleLicenseOverrideFilter(moduleLicenseOverridesFile),+ new PreferredLicenseFilter(allowedLicensesJsonFile)+ ]}tasks.named('generateLicenseReport') {inputs.file(moduleLicenseOverridesFile)+ inputs.file(allowedLicensesJsonFile)}tasks.named('checkLicensePreparation') {diff --git a/buildSrc/README.md b/buildSrc/README.mdindex bbcfb0de6c..f3ee62c006 100644--- a/buildSrc/README.md+++ b/buildSrc/README.md@@ -7,7 +7,8 @@ license files. Some artifacts do not publish license metadata in a form the plugthough the artifact has a known license.This directory contains the build logic used to provide narrowly scoped fallback license metadata-for those artifacts.+for those artifacts, and to choose which license and URL the report shows for a dependency that+declares several (see [Preferred license](#preferred-license)).## Files@@ -17,8 +18,10 @@ for those artifacts.- `src/main/groovy/stirling/software/gradle/ModuleLicenseOverrideFilter.groovy` implements theplugin's `DependencyFilter` interface.- `../app/license-overrides.json` contains the actual module-specific fallback values.+- `src/main/groovy/stirling/software/gradle/PreferredLicenseFilter.groovy` chooses the reported+ license and, for copyleft dependencies, the source link.- `../app/allowed-licenses.json` defines which detected or supplied licenses are accepted by- `checkLicense`.+ `checkLicense`, and the category each one is reported under.## How it works@@ -97,7 +100,7 @@ https://github.com/<owner>/<repository>/tree/<full-commit-hash>Do not use the repository's default branch or another moving URL. See the existing entries in`app/license-overrides.json` for concrete examples.-If the license name is not already accepted, add a suitably narrow rule to+If the license name is not already accepted, add a suitably narrow rule with a `category` to`app/allowed-licenses.json`. Adding an override and allowing a license are separate operations:- `license-overrides.json` supplies missing metadata for a specific artifact version.@@ -119,6 +122,50 @@ If the new artifact publishes usable license metadata, no override is necessary.report or license check removes the old entry from `app/license-overrides.json` automatically. Thefile must contain only overrides that are still needed.+## Preferred license++Without this filter, the plugin reports the alphabetically last license a dependency declares, so a+dependency offered under Apache-2.0 or LGPL is reported as LGPL. `PreferredLicenseFilter` runs after+the override filter and reports the declared license whose `category` in+`app/allowed-licenses.json` comes first in this order instead:++```json+{ "moduleName": ".*", "moduleLicense": "Apache-2.0", "category": "permissive" }+```++1. `permissive`: open source, no source obligation (Apache, MIT, BSD, EDL and similar).+2. `weak-copyleft`: open source, file-level copyleft (MPL, EPL, CDDL).+3. `restricted`: not open source; free to use but with conditions on how (UnRar, JJ2000).++LGPL and GPL licenses are not allowed, so a dependency available only under them fails+`checkLicense`.++Every entry must set a category, otherwise the license report fails. Entries are matched the same way+`checkLicense` matches them. A declared license with no entry is never reported, and a dependency+with no allowed license still fails `checkLicense`. Ties keep the plugin's alphabetical choice.++A POM cannot say whether its licenses are alternatives or all apply, so the filter treats them as+alternatives. When all of them apply, add one entry for the module that lists them in `allOf`:++```json+{+ "moduleName": "com.github.jai-imageio:jai-imageio-jpeg2000",+ "moduleLicense": "BSD 3-clause License w/nuclear disclaimer AND JJ2000",+ "allOf": ["BSD 3-clause License w/nuclear disclaimer", "JJ2000"],+ "category": "restricted"+}+```++The dependency is then reported under the entry's `moduleLicense`, and the build fails if a later+version stops declaring one of the listed licenses.++When the reported license is `weak-copyleft`, the dependency's URL becomes its `-sources.jar` on+Maven Central for the resolved version. Maven Central requires a sources jar for every published jar+and never changes a published file, so the link does not go stale.++A dependency the filter changes reports only the chosen license, in the report and in+`checkLicense`. Other dependencies are left as the plugin reads them.+## VerificationRun the filter unit tests:@@ -131,7 +178,10 @@ The tests use `com.example:example-library` versions 1.4 and 1.7 to cover the mimetadata fallback, placeholder creation, version migration, preservation of a populated neweroverride, automatic cleanup after license metadata appears, exact-version matching, and concurrentresolved versions. They also verify removal when a dependency version disappears. A separate `1.9`-to `1.11.0` case verifies numeric Gradle version ordering.+to `1.11.0` case verifies numeric Gradle version ordering. `PreferredLicenseFilterTest` covers+choosing by category, the sources jar link, ignoring licenses with no entry, module-scoped entries,+failure on a missing category, combined `AND` licenses, and that it matches entries the same way+`checkLicense` does.Run the normal backend license workflow from the repository root:@@ -159,7 +209,8 @@ The override JSON is registered as an input of `generateLicenseReport` and- Do not use an unversioned key. It cannot match the filter and would make the intended scopeambiguous.-- Do not use an override to replace valid license metadata published by a dependency.+- Do not use an override to replace valid license metadata published by a dependency. Choosing+ between declared licenses is handled by `PreferredLicenseFilter`.- Do not add an empty license to `allowed-licenses.json` merely to silence `checkLicense`; thatwould still leave the generated report without useful license information.- Do not exclude a dependency from the report solely because it is transitive. Runtime transitivediff --git a/buildSrc/src/main/groovy/stirling/software/gradle/PreferredLicenseFilter.groovy b/buildSrc/src/main/groovy/stirling/software/gradle/PreferredLicenseFilter.groovynew file mode 100644index 0000000000..116ea30cf9--- /dev/null+++ b/buildSrc/src/main/groovy/stirling/software/gradle/PreferredLicenseFilter.groovy@@ -0,0 +1,157 @@+package stirling.software.gradle++import com.github.jk1.license.License+import com.github.jk1.license.ManifestData+import com.github.jk1.license.ModuleData+import com.github.jk1.license.ProjectData+import com.github.jk1.license.filter.DependencyFilter+import com.github.jk1.license.render.LicenseDataCollector+import groovy.json.JsonSlurper+import groovy.transform.PackageScope+import org.gradle.api.GradleException++/**+ * Chooses the license each dependency is reported under, from the {@code category} of its entries in+ * {@code app/allowed-licenses.json}. The rules are under "Preferred license" in+ * {@code buildSrc/README.md}.+ *+ * <p>Fails the build when an entry has no valid category, or when a dependency declares only some of+ * an {@code allOf} entry's licenses. Entries are matched the way {@code checkLicense} matches them.+ */+class PreferredLicenseFilter implements DependencyFilter {+ private static final String MAVEN_CENTRAL = 'https://repo1.maven.org/maven2'+ private static final List<String> CATEGORIES = ['permissive', 'weak-copyleft', 'restricted']+ private static final Set<String> SOURCE_LINK_CATEGORIES = ['weak-copyleft'] as Set<String>++ private final File allowedLicensesFile++ PreferredLicenseFilter(File allowedLicensesFile) {+ this.allowedLicensesFile = allowedLicensesFile+ }++ @Override+ ProjectData filter(ProjectData projectData) {+ List<Map<String, Object>> entries = loadEntries(allowedLicensesFile)+ projectData.configurations+ .collectMany { configuration -> configuration.dependencies }+ .each { module -> applyPreferredLicense(module, entries) }+ return projectData+ }++ @PackageScope+ static List<Map<String, Object>> loadEntries(File allowedLicensesFile) {+ List<Map<String, Object>> entries =+ new JsonSlurper().parse(allowedLicensesFile).allowedLicenses as List<Map<String, Object>>+ entries.each { entry ->+ if (!CATEGORIES.contains(entry.category)) {+ throw new GradleException(+ "Allowed license ${entry.moduleLicense} for ${entry.moduleName} must set " ++ "'category' to one of ${CATEGORIES} in ${allowedLicensesFile}")+ }+ if (entry.containsKey('allOf')+ && !(entry.allOf instanceof List && entry.allOf.size() > 1+ && entry.allOf.every { part -> part instanceof String && !part.isBlank() })) {+ throw new GradleException(+ "Allowed license ${entry.moduleLicense} for ${entry.moduleName} must list at least " ++ "two license names in 'allOf' in ${allowedLicensesFile}")+ }+ }+ return entries+ }++ /**+ * Category of a license for a module, or {@code null} when no entry allows it. When several+ * entries match, the least permissive category wins.+ */+ @PackageScope+ static String categoryOf(+ String moduleName, String moduleVersion, String licenseName, List<Map<String, Object>> entries) {+ List<Map<String, Object>> matching = entries.findAll { entry ->+ matches(moduleName, entry.moduleName)+ && matches(moduleVersion, entry.moduleVersion)+ && matches(licenseName, entry.moduleLicense)+ }+ return matching.collect { entry -> entry.category }.max { category -> CATEGORIES.indexOf(category) }+ }++ private static void applyPreferredLicense(ModuleData module, List<Map<String, Object>> entries) {+ String moduleName = "${module.group}:${module.name}"+ Map<String, License> declared = LicenseDataCollector.multiModuleLicenseInfo(module).licenses+ .findAll { license -> license.name }+ .collectEntries { license -> [(license.name): license] }+ Map<License, Integer> rankByLicense = combinedLicense(moduleName, module.version, declared, entries)+ if (rankByLicense.isEmpty()) {+ declared.values().each { license ->+ String category = categoryOf(moduleName, module.version, license.name, entries)+ if (category != null) {+ rankByLicense[license] = CATEGORIES.indexOf(category)+ }+ }+ }+ if (rankByLicense.isEmpty()) {+ return+ }++ int bestRank = rankByLicense.values().min()+ License chosen = rankByLicense+ .findAll { license, rank -> rank == bestRank }+ .keySet()+ .max { license -> license.name }+ boolean needsSource = SOURCE_LINK_CATEGORIES.contains(CATEGORIES[bestRank])+ List<String> defaultInfo = LicenseDataCollector.singleModuleLicenseInfo(module)+ if (!needsSource && defaultInfo[1] == chosen.name) {+ return+ }++ String moduleUrl = needsSource ? sourcesJarUrl(module) : defaultInfo[0]+ module.poms = new TreeSet<>()+ module.licenseFiles = new TreeSet<>()+ module.manifests = [+ new ManifestData(+ module.name,+ module.version,+ null,+ null,+ moduleUrl,+ [chosen] as LinkedHashSet<License>,+ false)+ ] as LinkedHashSet<ManifestData>+ }++ private static Map<License, Integer> combinedLicense(+ String moduleName,+ String moduleVersion,+ Map<String, License> declared,+ List<Map<String, Object>> entries) {+ Map<String, Object> entry = entries.find { candidate ->+ candidate.allOf+ && matches(moduleName, candidate.moduleName)+ && matches(moduleVersion, candidate.moduleVersion)+ && candidate.allOf.any { part -> declared.containsKey(part) }+ }+ if (entry == null) {+ return [:]+ }++ List<String> parts = entry.allOf as List<String>+ List<String> missing = parts.findAll { part -> !declared.containsKey(part) }+ if (!missing.isEmpty()) {+ throw new GradleException(+ "${moduleName}:${moduleVersion} no longer declares ${missing}, which allowed license " ++ "'${entry.moduleLicense}' requires. Re-verify its licenses in allowed-licenses.json.")+ }+ License combined = new License(entry.moduleLicense, declared[parts[0]].url)+ return [(combined): CATEGORIES.indexOf(entry.category)]+ }++ // Mirrors checkLicense: a missing pattern matches anything, otherwise regex or exact match.+ // PreferredLicenseFilterTest compares the two, so a plugin upgrade that changes it fails there.+ private static boolean matches(String value, String pattern) {+ return pattern == null || value ==~ pattern || value == pattern+ }++ private static String sourcesJarUrl(ModuleData module) {+ String directory = "${MAVEN_CENTRAL}/${module.group.replace('.', '/')}/${module.name}/${module.version}"+ return "${directory}/${module.name}-${module.version}-sources.jar"+ }+}diff --git a/buildSrc/src/test/groovy/stirling/software/gradle/PreferredLicenseFilterTest.groovy b/buildSrc/src/test/groovy/stirling/software/gradle/PreferredLicenseFilterTest.groovynew file mode 100644index 0000000000..819d384b2f--- /dev/null+++ b/buildSrc/src/test/groovy/stirling/software/gradle/PreferredLicenseFilterTest.groovy@@ -0,0 +1,333 @@+package stirling.software.gradle++import com.github.jk1.license.ConfigurationData+import com.github.jk1.license.License+import com.github.jk1.license.ManifestData+import com.github.jk1.license.ModuleData+import com.github.jk1.license.ProjectData+import com.github.jk1.license.check.LicenseChecker+import com.github.jk1.license.render.LicenseDataCollector+import groovy.json.JsonOutput+import groovy.json.JsonSlurper+import java.nio.file.Path+import org.gradle.api.GradleException+import org.gradle.testfixtures.ProjectBuilder+import org.junit.jupiter.api.Test+import org.junit.jupiter.api.io.TempDir++import static org.junit.jupiter.api.Assertions.assertEquals+import static org.junit.jupiter.api.Assertions.assertThrows+import static org.junit.jupiter.api.Assertions.assertTrue++class PreferredLicenseFilterTest {+ private static final String GROUP = 'com.example.libs'+ private static final String MODULE = 'example-library'+ private static final String VERSION = '1.4.2'+ private static final String HOMEPAGE = 'https://www.example.com'+ private static final String SOURCES_JAR =+ 'https://repo1.maven.org/maven2/com/example/libs/example-library/1.4.2/example-library-1.4.2-sources.jar'+ private static final License APACHE =+ new License('Apache License, Version 2.0', 'https://www.apache.org/licenses/LICENSE-2.0')+ private static final License APACHE_ALIAS =+ new License('The Apache Software License, Version 2.0', 'https://www.apache.org/licenses/LICENSE-2.0.txt')+ private static final License EPL = new License('EPL 2.0', 'https://www.eclipse.org/legal/epl-2.0')+ private static final License MPL = new License('MPL 2.0', 'https://www.mozilla.org/MPL/2.0/')+ private static final License LGPL = new License('LGPL-2.1-only', 'https://spdx.org/licenses/LGPL-2.1-only.html')+ private static final License GPL_CPE = new License('GPL2 w/ CPE', 'https://openjdk.org/legal/gplv2+ce.html')+ private static final License UNRAR = new License('UnRar License', 'https://www.rarlab.com/license.htm')+ private static final License UNLISTED = new License('Unlisted License', 'https://www.example.com/license')++ private static final List<Map<String, String>> ALLOWED = [+ allowed(APACHE, 'permissive'),+ allowed(APACHE_ALIAS, 'permissive'),+ allowed(EPL, 'weak-copyleft'),+ allowed(MPL, 'weak-copyleft')+ ]++ @TempDir+ Path temporaryDirectory++ @Test+ void reportsPermissiveLicenseInsteadOfAlphabeticallyLastOne() {+ ModuleData module = createModule(APACHE, GPL_CPE)+ assertEquals(GPL_CPE.name, singleLicenseInfo(module)[1])++ filter(module, ALLOWED)++ assertEquals([HOMEPAGE, APACHE.name, APACHE.url], singleLicenseInfo(module))+ assertEquals([APACHE.name], licenseNames(module))+ }++ @Test+ void linksSourcesJarForWeakCopyleftLicense() {+ ModuleData module = createModule(MPL)++ filter(module, ALLOWED)++ assertEquals([SOURCES_JAR, MPL.name, MPL.url], singleLicenseInfo(module))+ }++ @Test+ void prefersWeakCopyleftOverRestricted() {+ ModuleData module = createModule(MPL, UNRAR)++ filter(module, ALLOWED + [allowed(UNRAR, 'restricted')])++ assertEquals([SOURCES_JAR, MPL.name, MPL.url], singleLicenseInfo(module))+ }++ @Test+ void doesNotLinkSourcesJarForRestrictedLicense() {+ ModuleData module = createModule(UNRAR)++ filter(module, [allowed(UNRAR, 'restricted')])++ assertEquals([HOMEPAGE, UNRAR.name, UNRAR.url], singleLicenseInfo(module))+ }++ @Test+ void reportsWeakCopyleftWhenOtherOptionIsNotAllowed() {+ ModuleData module = createModule(EPL, LGPL)++ filter(module, ALLOWED)++ assertEquals([SOURCES_JAR, EPL.name, EPL.url], singleLicenseInfo(module))+ assertEquals([EPL.name], licenseNames(module))+ }++ @Test+ void neverReportsLicenseMissingFromAllowedLicenses() {+ ModuleData module = createModule(MPL, UNLISTED)++ filter(module, ALLOWED)++ assertEquals([SOURCES_JAR, MPL.name, MPL.url], singleLicenseInfo(module))+ }++ @Test+ void leavesModuleWithoutAllowedLicenseUnchanged() {+ ModuleData module = createModule(UNLISTED)++ filter(module, ALLOWED)++ assertEquals([HOMEPAGE, UNLISTED.name, UNLISTED.url], singleLicenseInfo(module))+ }++ @Test+ void leavesModuleUnchangedWhenDefaultLicenseIsAlreadyPermissive() {+ ModuleData module = createModule(APACHE, APACHE_ALIAS)++ filter(module, ALLOWED)++ assertEquals([HOMEPAGE, APACHE_ALIAS.name, APACHE_ALIAS.url], singleLicenseInfo(module))+ assertEquals([APACHE.name, APACHE_ALIAS.name], licenseNames(module))+ }++ @Test+ void appliesModuleScopedEntryOnlyToThatModule() {+ List<Map<String, String>> allowed = [+ [moduleName: 'com.other:library', moduleLicense: UNLISTED.name, category: 'permissive'],+ allowed(MPL, 'weak-copyleft')+ ]+ ModuleData module = createModule(UNLISTED, MPL)++ filter(module, allowed)++ assertEquals([SOURCES_JAR, MPL.name, MPL.url], singleLicenseInfo(module))+ }++ @Test+ void usesLeastPermissiveCategoryWhenEntriesConflict() {+ List<Map<String, String>> allowed = [allowed(MPL, 'permissive'), allowed(MPL, 'weak-copyleft')]+ ModuleData module = createModule(MPL)++ filter(module, allowed)++ assertEquals(SOURCES_JAR, singleLicenseInfo(module)[0])+ }++ @Test+ void reportsEveryPartOfCombinedLicense() {+ License bsd = new License('BSD 3-clause License w/nuclear disclaimer', 'LICENSE-Sun.txt')+ License jj2000 = new License('JJ2000', 'LICENSE-JJ2000.txt')+ String combined = "${bsd.name} AND ${jj2000.name}"+ List<Map<String, Object>> allowed = [+ [moduleName: "${GROUP}:${MODULE}".toString(), moduleLicense: combined,+ allOf: [bsd.name, jj2000.name], category: 'restricted'],+ [moduleName: '.*', moduleLicense: bsd.name, category: 'permissive']+ ]+ ModuleData module = createModule(bsd, jj2000, new License('LICENSE-JJ2000.txt, LICENSE-Sun.txt', null))++ filter(module, allowed)++ assertEquals([HOMEPAGE, combined, bsd.url], singleLicenseInfo(module))+ assertEquals([combined], licenseNames(module))+ }++ @Test+ void linksSourcesJarForCombinedCopyleftLicense() {+ String combined = "${APACHE.name} AND ${MPL.name}"+ ModuleData module = createModule(APACHE, MPL)++ filter(module, [[moduleName: "${GROUP}:${MODULE}".toString(), moduleLicense: combined,+ allOf: [APACHE.name, MPL.name], category: 'weak-copyleft']])++ assertEquals([SOURCES_JAR, combined, APACHE.url], singleLicenseInfo(module))+ }++ @Test+ void failsWhenModuleNoLongerDeclaresEveryPartOfCombinedLicense() {+ String combined = "${APACHE.name} AND JJ2000"+ ModuleData module = createModule(APACHE)++ GradleException failure = assertThrows(GradleException) {+ filter(module, [[moduleName: "${GROUP}:${MODULE}".toString(), moduleLicense: combined,+ allOf: [APACHE.name, 'JJ2000'], category: 'permissive']])+ }++ assertTrue(failure.message.contains('JJ2000'))+ }++ @Test+ void treatsAndInsideLicenseNameAsPartOfTheName() {+ License cddl = new License('COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0', null)+ ModuleData module = createModule(cddl)++ filter(module, [[moduleName: '.*', moduleLicense: cddl.name, category: 'weak-copyleft']])++ assertEquals([SOURCES_JAR, cddl.name, null], singleLicenseInfo(module))+ }++ @Test+ void failsWhenAllOfListsFewerThanTwoLicenses() {+ List<Map<String, Object>> allowed = [[moduleName: '.*', moduleLicense: MPL.name, allOf: [MPL.name],+ category: 'weak-copyleft']]++ assertThrows(GradleException) { filter(createModule(MPL), allowed) }+ }++ @Test+ void failsWhenAllowedLicenseHasNoValidCategory() {+ List<Map<String, String>> allowed = [[moduleName: '.*', moduleLicense: MPL.name], allowed(APACHE, 'copyleft')]++ GradleException failure = assertThrows(GradleException) { filter(createModule(MPL), allowed) }++ assertTrue(failure.message.contains(MPL.name))+ }++ @Test+ void agreesWithCheckLicenseOnTrickyEntries() {+ String quoted = '"Quoted, version 2.0";link="https://www.example.com/LICENSE-2.0.html"'+ List<Map<String, String>> allowed = [+ [moduleName: '.*', moduleLicense: 'Apache.*', category: 'permissive'],+ [moduleName: 'com.example:scoped', moduleLicense: 'Scoped License', category: 'permissive'],+ [moduleName: 'com.example:versioned', moduleVersion: '1\\..*', moduleLicense: 'Versioned License',+ category: 'weak-copyleft'],+ [moduleName: '.*', moduleLicense: quoted, category: 'permissive'],+ [moduleLicense: 'No Module Name', category: 'weak-copyleft'],+ [moduleName: 'com.example:any-license', moduleLicense: '.*', category: 'weak-copyleft']+ ]+ List<List<String>> cases = [+ ['com.example:lib', '1.0', 'Apache License 2.0'],+ ['com.example:lib', '1.0', 'apache license 2.0'],+ ['com.example:scoped', '1.0', 'Scoped License'],+ ['com.example:other', '1.0', 'Scoped License'],+ ['com.example:versioned', '1.2', 'Versioned License'],+ ['com.example:versioned', '2.0', 'Versioned License'],+ ['com.example:lib', '1.0', quoted],+ ['com.example:lib', '1.0', 'No Module Name'],+ ['com.example:any-license', '1.0', 'Anything'],+ ['com.example:lib', '1.0', 'Unlisted License']+ ]++ assertAgreesWithCheckLicense(writeAllowedLicenses(allowed), cases)+ }++ @Test+ void agreesWithCheckLicenseOnRepositoryAllowedLicenses() {+ File allowedLicensesFile = new File('../app/allowed-licenses.json')+ List<List<String>> cases = PreferredLicenseFilter.loadEntries(allowedLicensesFile).collectMany { entry ->+ String moduleName = entry.moduleName == '.*' ? 'com.example:lib' : entry.moduleName+ String license = entry.moduleLicense+ [[moduleName, '1.0', license], [moduleName, '1.0', license.toLowerCase()], [moduleName, '1.0', "${license} ".toString()]]+ }++ assertAgreesWithCheckLicense(allowedLicensesFile, cases)+ }++ private void assertAgreesWithCheckLicense(File allowedLicensesFile, List<List<String>> cases) {+ File dependenciesFile = temporaryDirectory.resolve('dependencies.json').toFile()+ dependenciesFile.text = JsonOutput.toJson([dependencies: cases.collect { moduleName, version, license ->+ [moduleName: moduleName, moduleVersion: version, moduleLicenses: [[moduleLicense: license]]]+ }])+ File rejectedFile = temporaryDirectory.resolve('rejected.json').toFile()+ try {+ new LicenseChecker().checkAllDependencyLicensesAreAllowed(+ allowedLicensesFile, dependenciesFile, rejectedFile)+ } catch (GradleException ignored) {+ // checkLicense throws when anything is rejected; the rejected file is what is compared.+ }+ Set<List<String>> rejected = (new JsonSlurper().parse(rejectedFile).dependenciesWithoutAllowedLicenses+ as List<Map<String, String>>)+ .collect { dependency -> [dependency.moduleName, dependency.moduleVersion, dependency.moduleLicense] }+ as Set<List<String>>+ assertTrue(!rejected.isEmpty() && rejected.size() < cases.size(), 'cases must include allowed and rejected')++ List<Map<String, Object>> entries = PreferredLicenseFilter.loadEntries(allowedLicensesFile)+ cases.each { testCase ->+ boolean allowedByFilter = PreferredLicenseFilter.categoryOf(+ testCase[0], testCase[1], testCase[2], entries) != null+ assertEquals(!rejected.contains(testCase), allowedByFilter, testCase.toString())+ }+ }++ private File writeAllowedLicenses(List<Map<String, Object>> allowed) {+ File allowedLicensesFile = temporaryDirectory.resolve('allowed-licenses.json').toFile()+ allowedLicensesFile.text = JsonOutput.toJson([allowedLicenses: allowed])+ return allowedLicensesFile+ }++ private void filter(ModuleData module, List<Map<String, Object>> allowed) {+ File allowedLicensesFile = writeAllowedLicenses(allowed)+ ConfigurationData configuration =+ new ConfigurationData('runtimeClasspath', [module] as LinkedHashSet<ModuleData>)+ new PreferredLicenseFilter(allowedLicensesFile).filter(+ new ProjectData(+ ProjectBuilder.builder().build(),+ [configuration] as LinkedHashSet<ConfigurationData>))+ }++ private static Map<String, String> allowed(License license, String category) {+ return [moduleName: '.*', moduleLicense: license.name, category: category]+ }++ private static ModuleData createModule(License... licenses) {+ Set<ManifestData> manifests = [+ new ManifestData(+ MODULE,+ VERSION,+ null,+ null,+ HOMEPAGE,+ licenses as LinkedHashSet<License>,+ false)+ ] as LinkedHashSet<ManifestData>+ return new ModuleData(+ GROUP,+ MODULE,+ VERSION,+ true,+ manifests,+ new LinkedHashSet<>(),+ new LinkedHashSet<>())+ }++ private static List<String> singleLicenseInfo(ModuleData module) {+ return LicenseDataCollector.singleModuleLicenseInfo(module)+ }++ private static List<String> licenseNames(ModuleData module) {+ Set<License> licenses = LicenseDataCollector.multiModuleLicenseInfo(module).licenses+ return licenses.collect { license -> license.name }.sort()+ }+}