The user wants a tool or system for open-source license compliance.
The key requirements are:
- Scanning: Identifying dependencies and their licenses.
- Attribution Files: Generating documents (like
NOTICE, LICENSE, or HTML reports) that credit the authors.
- Copyleft Triggers: Analyzing the dependency tree to identify if using a copyleft license (GPL, LGPL, etc.) might force the user's proprietary code to be open-sourced.
I need to design a solution. Since this is a coding-oriented request, I should probably provide a Python-based tool or a structured guide on how to build one. Writing a full-blown enterprise scanner from scratch is complex, but building a functional MVP (Minimum Viable Product) that demonstrates these three pillars is feasible and instructive.
Approach:
I will create a Python script called license_compliance_tool.py.
Component 1: Scanning
- How do we scan? Most modern projects use package managers (npm, pip, maven, cargo).
- To keep it language-agnostic or simple, I'll focus on Python (pip) as the primary example because it's easy to demonstrate, but I'll mention how to extend it.
- Implementation details: I can use the
pip-licenses library (standard and easy) or scan requirements.txt and look up PyPI API. Using pip-licenses is robust.
- Alternative: Manual file system scanning (looking for LICENSE files) is hard to do generically in a snippet. I will rely on
pip metadata for the demo.
Component 2: Attribution Files
- Input: List of libraries with license text.
- Output: A Markdown or Text file listing the library name, version, license type, and full license text.
- Implementation: Gather data from Component 1, format it into a string, write to
ATTRIBUTIONS.md.
Component 3: Copyleft Triggers
- Logic: We need a list of "risky" licenses (GPL-2.0, GPL-3.0, AGPL, SSPL, etc.).
- Check: Compare scanned licenses against the risky list.
- Output: A warning report.
Refining the Solution:
Instead of just writing a script that relies on external binaries like pip-licenses, I can write a Python script that parses the installed packages in the current environment. This makes it self-contained (assuming the user runs it inside their venv).
Architecture of the proposed tool:
Scanner class: Uses importlib.metadata (standard lib) to find installed packages and their metadata (License, Author, etc.).
Analyzer class: Defines rules for copyleft.
Reporter class: Generates the attribution file.
Code Structure:
- Imports:
importlib.metadata, argparse, sys, re.
- Constants: Define lists of Copyleft licenses (GPL, AGPL, etc.) and Permissive licenses (MIT, Apache, BSD).
- Functions:
scan_dependencies(): Get all packages.
check_copyleft(): Filter for dangerous licenses.
generate_attribution(): Create the file.
Adding a "Real-world" Context:
While I build this MVP, I must emphasize that for production, existing tools like FOSSA, Snyk, or Black Duck are better. However, for a "Build an open-source license compliance" prompt, the user usually wants the code or the logic.
Let's stick to building a custom Python tool. It demonstrates the logic perfectly.
Drafting the Code (Mental or Scratchpad):
import importlib.metadata
- Loop through
distributions().
- Get
metadata.get('Name'), metadata.get('License').
- Problem: The
License field in package metadata is often just "MIT" or "Apache 2.0", but sometimes it's "UNKNOWN".
- Text extraction: Getting the full text of the license usually requires looking for
LICENSE or COPYING files within the package installation directory. This is slightly more complex but doable.
- Strategy: I'll implement a function to attempt to find the license file path.
The Copyleft Logic:
- Strict Copyleft: GPL, AGPL.
- Weak Copyleft: LGPL, MPL.
- The user asked for "triggers," which implies checking if the license requires source distribution.
The Output:
I will provide:
- The Architecture: High-level explanation.
- The Code: A complete Python script (
compliance_scanner.py).
- How to use it: Instructions.
- Explanation of Copyleft Triggers: Educational context.
Let's refine the code to be robust.
- Use
stdlib as much as possible.
- Use
argparse for CLI interaction.
- Output a JSON report + Markdown Attribution file.
Step-by-step Implementation Plan:
- Detect Packages: Use
importlib.metadata.
- Classify License: Use a simple lookup dictionary or list for "Red" (Copyleft) vs "Green" (Permissive).
- Generate Output:
- Console output: Warnings for GPL.
- File output:
THIRD_PARTY_NOTICES.
Self-Correction during drafting:
Simply checking metadata.get('License') is often unreliable because some packages use "License :: OSI Approved :: MIT License" classifiers instead of the License field. I need to parse classifiers too.
Code Logic:
metadata = dist.metadata
license_name = metadata.get("License")
classifiers = metadata.get_all("Classifier")
# Parse classifiers for "License :: ..."
Let's build the solution.
Feature List for the MVP:
- Scanner: Scans current Python environment.
- Risk Engine: Identifies Copyleft/Proprietary.
- Attribution Generator: Writes a Markdown file.
- Dependency Tree (Bonus): Printing the tree helps understand where a GPL lib came from.
pipdeptree does this, but implementing it from scratch might be too much code. I'll stick to flat dependencies for simplicity but mention tree analysis.
Final Plan:
Write a comprehensive Python CLI tool.
Name it os_license_scanner.py.
It will produce a report and an attribution file.
Detailed Code Structure:
LicenseScanner class.
- Methods:
scan, analyze_copyleft, generate_attribution.
main: CLI interface.
I will also include a section on "How to integrate this into CI/CD" to make it practical.
Copyleft Trigger Logic:
I need to explicitly define what triggers what.
- GPL/AGPL: Triggers whole program source release (viral).
- LGPL: Triggers source release only if you modify the library statically linked; dynamic linking is usually okay.
- Permissive (MIT/Apache): Only triggers attribution requirement.
I will structure the response to be educational and functional.
This is a comprehensive guide to building an internal Open Source Program Office (OSPO) style tool. We will build a Python-based utility called license-sheriff.
This tool will perform three main tasks:
- Scanning: Identify dependencies and their licenses.
- Attribution: Generate a
NOTICE or ATTRIBUTION file automatically.
- Compliance (Copyleft Triggers): Analyze the dependency tree to see if "viral" licenses (like GPL) are infecting your proprietary code.
Prerequisites
You will need Python 3 installed. We will use the standard importlib.metadata (available in Python 3.8+) to inspect installed packages without needing external heavy scanners.
Part 1: The Architecture
Create a file named license_sheriff.py. We will break this down into classes:
Dependency: A data structure to hold info about a package.
Scanner: Gathers license info from the environment.
ComplianceEngine: Checks for copyleft conflicts.
AttributionGenerator: Writes the output files.
Part 2: The Implementation
Here is the complete source code for the tool.
import importlib.metadata
import argparse
import sys
import os
from dataclasses import dataclass
from typing import List, Dict
# --- Configuration ---
# Define license categories
PERMISSIVE_LICENSES = {
"MIT", "Apache-2.0", "Apache Software License", "BSD-3-Clause",
"BSD-2-Clause", "ISC", "Python-2.0", "PostgreSQL", "Zlib"
}
COPYLEFT_LICENSES = {
"GPL-2.0", "GPL-3.0", "LGPL-2.1", "LGPL-3.0",
"AGPL-3.0", "MPL-2.0", "CDDL-1.0", "EPL-1.0"
}
# --- Data Models ---
@dataclass
class Dependency:
name: str
version: str
license_name: str
is_copyleft: bool = False
# --- Core Logic ---
class LicenseScanner:
def __init__(self):
self.deps: List[Dependency] = []
def scan_environment(self):
"""Scans installed python packages via metadata."""
print("🔍 Scanning installed packages...")
# Get all distributions
distributions = importlib.metadata.distributions()
for dist in distributions:
try:
name = dist.metadata['Name']
version = dist.version
# License metadata can be messy; try to find it
license_name = dist.metadata.get('License', 'UNKNOWN')
# Sometimes licenses are buried in classifiers
if license_name == 'UNKNOWN' or 'License' not in dist.metadata:
for classifier in dist.metadata.get_all("Classifier"):
if classifier.startswith("License ::"):
license_name = classifier.split("::")[-1].strip()
break
is_copyleft = self._check_copyleft(license_name)
dep = Dependency(name, version, license_name, is_copyleft)
self.deps.append(dep)
except Exception as e:
# Skip packages with broken metadata
continue
def _check_copyleft(self, license_str: str) -> bool:
"""Simple heuristic to check if a license string is copyleft."""
license_str = license_str.upper()
for trigger in COPYLEFT_LICENSES:
# Check if the license ID or name contains the trigger
if trigger.upper() in license_str:
return True
return False
class ComplianceEngine:
def __init__(self, deps: List[Dependency]):
self.deps = deps
def analyze(self) -> Dict[str, List[Dependency]]:
"""Categorizes dependencies and flags risks."""
report = {
"permissive": [],
"copyleft": [],
"unknown": []
}
for dep in self.deps:
if dep.is_copyleft:
report["copyleft"].append(dep)
elif dep.license_name == "UNKNOWN":
report["unknown"].append(dep)
else:
report["permissive"].append(dep)
return report
class AttributionGenerator:
def __init__(self, deps: List[Dependency], output_file="ATTRIBUTIONS.md"):
self.deps = deps
self.output_file = output_file
def generate(self):
"""Generates a markdown file with license text."""
print(f"📝 Generating {self.output_file}...")
with open(self.output_file, "w") as f:
f.write("# Third-Party Open Source Attributions\n\n")
f.write("This application uses the following open source packages:\n\n")
for dep in sorted(self.deps, key=lambda x: x.name):
f.write(f"## {dep.name} (v{dep.version})\n")
f.write(f"**License**: {dep.license_name}\n\n")
f.write("---\n\n")
print(f"✅ Attribution file created.")
# --- CLI Interface ---
def main():
parser = argparse.ArgumentParser(description="OSPO License Compliance Tool")
parser.add_argument("--check-copyleft", action="store_true", help="Fail if Copyleft licenses are found (for CI/CD)")
parser.add_argument("--output", type=str, default="ATTRIBUTIONS.md", help="Output file for attributions")
args = parser.parse_args()
# 1. Scan
scanner = LicenseScanner()
scanner.scan_environment()
# 2. Analyze
engine = ComplianceEngine(scanner.deps)
report = engine.analyze()
# 3. Report
print("\n--- COMPLIANCE REPORT ---")
print(f"Total Dependencies: {len(scanner.deps)}")
print(f"Permissive: {len(report['permissive'])}")
print(f"Copyleft (Flags): {len(report['copyleft'])}")
print(f"Unknown Licenses: {len(report['unknown'])}")
# 4. Handle Copyleft Triggers
if report['copyleft']:
print("\n⚠️ WARNING: COPILEFT LICENSES DETECTED ⚠️")
print("The following packages may trigger source code disclosure requirements:")
for dep in report['copyleft']:
print(f" - {dep.name}: {dep.license_name}")
if args.check_copyleft:
print("\n❌ CI Check Failed due to Copyleft violation policy.")
sys.exit(1)
# 5. Generate Attributions
generator = AttributionGenerator(scanner.deps, args.output)
generator.generate()
if __name__ == "__main__":
main()
Part 3: How to Use This Tool
Save the code above as license_sheriff.py.
1. Basic Scanning
To simply scan your current Python virtual environment and generate an attribution file:
pip install pandas numpy requests # Install some dummy packages
python license_sheriff.py
Output:
It will print a report in the terminal and create an ATTRIBUTIONS.md file containing the license info for pandas, numpy, etc.
2. Copyleft Trigger Blocking (CI/CD Mode)
If you want your build pipeline to fail if a developer accidentally adds a GPL library to your proprietary project, use the --check-copyleft flag.
First, install a GPL package to test:
pip install gitpython # GitPython is BSD, let's pretend or find a GPL one like 'mysql-connector-python' (GPLv2)
Run the tool:
python license_sheriff.py --check-copyleft
If a copyleft license is found, the script will exit with status code 1, causing your CI pipeline to fail.
Part 4: Deep Dive into the Logic
Here is an explanation of the three pillars implemented in the code:
1. Scanning (The LicenseScanner Class)
We use importlib.metadata. This is the modern standard for Python.
- The Problem: Python packages don't always list their license in a machine-readable way. Some put it in the
License field; others only put it in the Classifier field (e.g., License :: OSI Approved :: MIT License).
- The Solution: The script checks the
License field first. If that is "UNKNOWN", it falls back to parsing the Classifier list.
2. Attribution (The AttributionGenerator Class)
This satisfies the legal requirement of Permissive licenses (MIT, Apache 2.0, BSD).
- The Logic: It iterates through every dependency and writes a Markdown section.
- Production Upgrade: In a real-world scenario, you would also want to copy the
LICENSE file text itself. You can find the path to the license file using dist.files (locating files named LICENSE or COPYING within the package installation folder) and appending that text to the output file.
3. Copyleft Triggers (The ComplianceEngine Class)
This is the "Compliance" part.
- Viral Licenses: GPL and AGPL are "Strong Copyleft." If you link your code to them, your code arguably becomes Open Source too.
- Weak Copyleft: LGPL and MPL are "Weak." They usually only require you to open-source changes to the library itself, not your whole app.
- The Trigger: The script maintains a
COPYLEFT_LICENSES set. If a dependency matches this set, it flags a risk.
Part 5: Extending for Production
For a production environment, you should enhance this tool with:
- SPDX Compliance: Use the
license-expression library to normalize license strings (e.g., turning "MIT License" and "MIT" into the standardized ID "MIT").
- Dependency Tree: Use
pipdeptree logic. If a library you use depends on a GPL library (transitive dependency), your code is also triggered. The current script scans flat dependencies.
- External Scanners: For non-Python code (JavaScript, Docker images), integrate Trivy or Syft. They output JSON, which you can feed into the
ComplianceEngine class built above.