Create an open-source license compliance pipeline: scanning, attribution files,…
- User
Create an open-source license compliance pipeline: scanning, attribution files, obligations tracking, and remediation.
Assistant
Create an open-source license compliance pipeline: scanning, attribution files, obligations tracking, and remediation.
The user wants an open-source license compliance pipeline. This pipeline needs to cover four specific areas:
NOTICE, LICENSE, or THIRD-PARTY files.The user asked for the creation of this pipeline. This usually means they want a conceptual design, a practical implementation guide (scripts, tools), or a combination of both. Given the complexity, a practical guide using open-source tools (to stay in the spirit of the prompt) is the best approach.
Target Audience: Developers or DevOps engineers setting up compliance for a project or organization. Tone: Professional, technical, structured.
Key Components & Tools Selection:
Scanning:
license-checker (npm) or pip-licenses logic is too specific to languages.Attribution:
THIRD_PARTY_LICENSES file.Obligations:
GPL-3.0: DENY, MIT: ALLOW).Remediation:
Structure of the Response:
Refining the "Code": I should provide a tangible implementation.
compliance_engine.py) that:
policy.yaml.ATTRIBUTION.md.Drafting the Content - Section by Section:
syft . -o spdx-json > sbom.jsonpolicy.yaml.
THIRD_PARTY.txt.Self-Correction/Refinement:
Final Polish: Make sure the Python script is copy-paste runnable (mostly). Ensure the YAML is valid.
Let's write the response. This guide outlines a complete Open Source Software (OSS) license compliance pipeline. This solution uses a Shift-Left approach, integrating scanning early in the development lifecycle (CI/CD) to prevent violations before they reach production.
We will use standard open tools:
The pipeline consists of four distinct stages:
NOTICE, LICENSE, and ATTRIBUTION files required for distribution.First, we define the rules. Create a file named license-policy.yaml. This acts as the single source of truth.
# license-policy.yaml
policy:
# Licenses that are pre-approved
allow:
- MIT
- Apache-2.0
- BSD-2-Clause
- BSD-3-Clause
- ISC
- 0BSD
# Licenses that trigger a warning but don't break the build
warn:
- MPL-2.0 # Mozilla Public License (Weak Copyleft)
- EPL-1.0
# Licenses that are forbidden (Copyleft/Proprietary)
# These will block the CI pipeline
deny:
- GPL-2.0
- GPL-3.0
- AGPL-3.0
- SSPL-1.0
- CC-BY-NC-4.0
# Obligations mapping
obligations:
MIT:
action: "Include copyright notice"
GPL-3.0:
action: "Disclose source code, state changes, and license derivative work under GPL"
This script acts as the "brain." It parses the scan results, enforces the policy, and generates attribution files.
Prerequisites: pip install pyyaml
Create compliance_engine.py:
import json
import yaml
import sys
import os
from datetime import datetime
def load_policy(policy_path):
with open(policy_path, 'r') as f:
return yaml.safe_load(f)
def parse_sbom_licenses(sbom_path):
"""
Parses Syft JSON output to extract package info and licenses.
"""
with open(sbom_path, 'r') as f:
data = json.load(f)
packages = []
# Syft SBOM Structure (simplified)
for artifact in data.get('artifacts', []):
pkg = {
'name': artifact.get('name'),
'version': artifact.get('version'),
'type': artifact.get('type'),
'licenses': artifact.get('licenses', [])
}
packages.append(pkg)
return packages
def check_compliance(packages, policy):
violations = []
warnings = []
allowed = policy['policy']['allow']
denied = policy['policy']['deny']
warned = policy['policy']['warn']
for pkg in packages:
# Handle packages with no license info (risk)
if not pkg['licenses']:
warnings.append(f"RISK: {pkg['name']} has NO license information.")
continue
for lic in pkg['licenses']:
lic_id = lic # In Syft JSON, this might be a dict or string, assuming string for simplicity
# Check Denied
if lic_id in denied:
violations.append(f"VIOLATION: {pkg['name']} uses DENIED license {lic_id}")
# Check Warnings
elif lic_id in warned:
warnings.append(f"WARNING: {pkg['name']} uses {lic_id} (Weak Copyleft)")
# Check Allow (Implicit pass if not in others)
return violations, warnings
def generate_attribution(packages, output_path):
"""
Generates a formatted ATTRIBUTION.txt file.
"""
with open(output_path, 'w') as f:
f.write(f"OPEN SOURCE SOFTWARE ATTRIBUTION\n")
f.write(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write("="*60 + "\n\n")
for pkg in packages:
lic_str = ", ".join(pkg['licenses']) if pkg['licenses'] else "Unknown"
f.write(f"Package: {pkg['name']}\n")
f.write(f"Version: {pkg['version']}\n")
f.write(f"License: {lic_str}\n")
f.write("-" * 20 + "\n\n")
print(f"Attribution file generated at {output_path}")
def main():
# 1. Setup Paths
policy_path = 'license-policy.yaml'
sbom_path = 'sbom.json' # Output from Syft
attribution_path = 'DIST/ATTRIBUTION.txt'
os.makedirs('DIST', exist_ok=True)
# 2. Load Data
policy = load_policy(policy_path)
print("Policy loaded successfully.")
packages = parse_sbom_licenses(sbom_path)
print(f"Scanned {len(packages)} packages.")
# 3. Run Compliance Check
violations, warnings = check_compliance(packages, policy)
# 4. Output Results
print("\n--- COMPLIANCE REPORT ---")
if warnings:
for w in warnings:
print(f"⚠️ {w}")
if violations:
print("\n❌ COMPLIANCE FAILED ❌")
for v in violations:
print(f"🚨 {v}")
# Generate Attribution even on failure for debugging
generate_attribution(packages, attribution_path)
sys.exit(1) # Fail the pipeline
else:
print("\n✅ COMPLIANCE PASSED")
# Generate Artifacts
generate_attribution(packages, attribution_path)
sys.exit(0)
if __name__ == "__main__":
main()
This workflow runs on every Pull Request. It installs the scanners, generates the SBOM, runs the compliance engine, and uploads the attribution files as artifacts.
Create .github/workflows/compliance.yml:
name: OSS Compliance Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
scan-and-comply:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install Dependencies
run: |
pip install pyyaml
# Install Syft (SBOM Generator)
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b $HOME/.local/bin v0.84.0
echo "$HOME/.local/bin" >> $GITHUB_PATH
- name: Generate SBOM
# Syft scans the current directory (.) and outputs JSON to sbom.json
run: syft . -o json > sbom.json
- name: Run Compliance Engine
id: compliance
run: python compliance_engine.py
- name: Upload Attribution Artifacts
# If compliance passes, save the attribution file
if: success()
uses: actions/upload-artifact@v3
with:
name: oss-attribution
path: DIST/ATTRIBUTION.txt
When the pipeline fails (Exit Code 1), here is the remediation workflow for the developer:
VIOLATION: lib-example uses DENIED license GPL-3.0.license-policy.yaml to move GPL-3.0 to warn (with a ticket number in comments).RISK: lib-xyz has NO license information.ATTRIBUTION.txt file is included in your installer/app package.While scripts check code, Obligations Tracking usually requires a database (like FOSSology or a spreadsheet) for legal sign-off.
However, you can extend the compliance_engine.py to output a "Obligations Checklist" for your legal team:
# Add to compliance_engine.py
def generate_obligations_checklist(packages, policy):
with open('DIST/OBLIGATIONS_CHECKLIST.md', 'w') as f:
f.write("# Legal Obligations Checklist\n")
f.write("Review the following obligations before release.\n\n")
seen_licenses = set()
for pkg in packages:
for lic in pkg['licenses']:
if lic not in seen_licenses:
seen_licenses.add(lic)
obligation_text = policy['obligations'].get(lic, "Standard attribution required.")
f.write(f"## License: {lic}\n")
f.write(f"**Requirement:** {obligation_text}\n\n")
f.write(f"- [ ] Verified by Legal\n\n")
Syft generates an SBOM (JSON).compliance_engine.py compares the SBOM against license-policy.yaml.compliance_engine.py writes ATTRIBUTION.txt automatically.