Build an open‑source license compliance office: inventory/BOM, policy exceptions, dual…
- User
Build an open‑source license compliance office: inventory/BOM, policy exceptions, dual licensing, and contribution governance.
Assistant
Build an open‑source license compliance office: inventory/BOM, policy exceptions, dual licensing, and contribution governance.
The user wants a "License Compliance Office" system. The key features requested are:
Target Audience/Format: The prompt is asking to "Build" this. Since I am an AI text model, I cannot generate a hosted, running executable. I must provide the architecture, database schema, API design, and a code skeleton (likely in Python or Node.js) that constitutes the MVP (Minimum Viable Product) of such a system.
Language Choice: Python (FastAPI) + SQLite/PostgreSQL + SQLAlchemy is a standard, robust choice for enterprise backend tools. It allows for clear schema definition and easy API generation.
Core Entities:
Key Workflows to Model:
Structure of the Response:
Drafting the Content - Section by Section:
components, projects, dependencies, policy_rules, exception_requests, contribution_requests.POST /bom (upload), GET /compliance/report, POST /exceptions, POST /contributions.Refining the Code:
I'll use Python with FastAPI because it's concise and self-documenting.
I'll mock the database with SQLAlchemy models.
I'll implement a ComplianceChecker class to handle the logic of "Is this allowed?".
Self-Correction during thought process: Initial thought: Should I write a full frontend in React? Correction: No, that takes too much space and distracts from the logic. Focus on the backend API and data model, which is the core of a compliance office. I will provide a textual description of the UI.
Specific focus on "Dual Licensing":
How do we model this? A component shouldn't just have one license string. It should have available_licenses (e.g., "MIT", "Commercial"). When added to a project, the engineer must select the selected_license. If "Commercial" is selected, the policy might allow it (but requires a purchase record). If "GPL" is selected, it might trigger a policy violation for proprietary software.
Final Plan:
Let's write the code. I will define a main.py that contains the models and the API logic.
Schema Details:
Component: purl, name, version, declared_license (spdx id).Project: name, version.ProjectDependency: link Project to Component + license_context (for dual licensing).ExceptionRequest: project_id, component_id, reason, status.OutboundContribution: repo_url, user, description, status.Policy Engine Logic:
Let's assemble this into a cohesive response. This is a blueprint and implementation skeleton for an Open Source Program Office (OSPO) compliance system. This solution handles the lifecycle of open-source consumption (inventory), policy enforcement (exceptions), legal management (dual licensing), and outbound contributions.
We will use Python (FastAPI) for the backend due to its robustness in data processing, and SQLAlchemy for the database ORM to manage relationships between components, licenses, and projects.
The system is divided into four core domains:
We need a flexible schema to handle the complexity of dual licensing (where one library has multiple license options).
pip install fastapi uvicorn sqlalchemy pydantic
main.py)from typing import List, Optional, Enum
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, DateTime, Boolean, Text
from sqlalchemy.orm import declarative_base, relationship, Session
from pydantic import BaseModel
from fastapi import FastAPI, HTTPException, Depends
# --- DATABASE SETUP ---
Base = declarative_base()
engine = create_engine('sqlite:///./ospo_compliance.db')
# --- ENUMS ---
class LicenseType(str, Enum):
PERMISSIVE = "Permissive" # MIT, Apache
WEAK_COPYLEFT = "Weak Copyleft" # LGPL, MPL
STRONG_COPYLEFT = "Strong Copyleft" # GPL
PROPRIETARY = "Proprietary"
class ApprovalStatus(str, Enum):
PENDING = "Pending"
APPROVED = "Approved"
REJECTED = "Rejected"
class UsageType(str, Enum):
DYNAMIC_LINK = "Dynamic Link"
STATIC_LINK = "Static Link"
MODIFIED = "Modified Code"
UNMODIFIED = "Unmodified"
# --- ORM MODELS ---
class License(Base):
__tablename__ = 'licenses'
id = Column(Integer, primary_key=True)
spdx_id = Column(String) # e.g., "Apache-2.0"
full_name = Column(String)
category = Column(String) # Permissive, Copyleft, etc.
# Relationships
components = relationship("ComponentLicense", back_populates="license")
class Component(Base):
__tablename__ = 'components'
id = Column(Integer, primary_key=True)
name = Column(String)
version = Column(String)
purl = Column(String) # Package URL (standard identifier)
# A component can have multiple license options (Dual Licensing)
license_options = relationship("ComponentLicense", back_populates="component")
class ComponentLicense(Base):
"""Associates a component with a license (handles dual licensing)."""
__tablename__ = 'component_licenses'
id = Column(Integer, primary_key=True)
component_id = Column(Integer, ForeignKey('components.id'))
license_id = Column(Integer, ForeignKey('licenses.id'))
# If this license requires a purchase (e.g., Commercial variant of dual license)
requires_purchase = Column(Boolean, default=False)
component = relationship("Component", back_populates="license_options")
license = relationship("License", back_populates="components")
class Project(Base):
__tablename__ = 'projects'
id = Column(Integer, primary_key=True)
name = Column(String)
version = Column(String)
is_proprietary = Column(Boolean, default=True)
dependencies = relationship("ProjectDependency", back_populates="project")
class ProjectDependency(Base):
"""The Inventory / BOM entry."""
__tablename__ = 'project_dependencies'
id = Column(Integer, primary_key=True)
project_id = Column(Integer, ForeignKey('projects.id'))
component_id = Column(Integer, ForeignKey('components.id'))
# Store the specific license chosen in case of dual licensing
chosen_license_id = Column(Integer, ForeignKey('licenses.id'))
usage_type = Column(String) # Static, Dynamic, etc.
project = relationship("Project", back_populates="dependencies")
component = relationship("Component")
chosen_license = relationship("License")
class PolicyException(Base):
__tablename__ = 'policy_exceptions'
id = Column(Integer, primary_key=True)
project_dependency_id = Column(Integer, ForeignKey('project_dependencies.id'))
justification = Column(Text)
status = Column(String, default=ApprovalStatus.PENDING)
approved_by = Column(String, nullable=True)
expiry_date = Column(DateTime, nullable=True)
class OutboundContribution(Base):
__tablename__ = 'outbound_contributions'
id = Column(Integer, primary_key=True)
upstream_project = Column(String)
contributor_email = Column(String)
description = Column(Text)
cla_signed = Column(Boolean, default=False)
status = Column(String, default="Pending Review")
# --- PYDANTIC SCHEMAS ---
class DependencyIn(BaseModel):
project_name: str
component_purl: str
component_name: str
usage: UsageType
class ExceptionRequest(BaseModel):
dependency_id: int
justification: str
class ContributionIn(BaseModel):
upstream_project: str
contributor_email: str
description: str
# --- APP INITIALIZATION ---
app = FastAPI(title="OSPO Compliance Office")
def get_db():
db = Session(engine)
try:
yield db
finally:
db.close()
# Initialize DB with some defaults
@app.on_event("startup")
def startup():
Base.metadata.create_all(bind=engine)
db = Session(engine)
if not db.query(License).first():
db.add(License(spdx_id="MIT", category=LicenseType.PERMISSIVE))
db.add(License(spdx_id="Apache-2.0", category=LicenseType.PERMISSIVE))
db.add(License(spdx_id="GPL-3.0", category=LicenseType.STRONG_COPYLEFT))
db.add(License(spdx_id="LGPL-3.0", category=LicenseType.WEAK_COPYLEFT))
db.add(License(spdx_id="Commercial", category=LicenseType.PROPRIETARY))
db.commit()
# --- API ROUTINES ---
@app.post("/inventory/add-dependency")
def add_dependency(data: DependencyIn, db: Session = Depends(get_db)):
"""
Add a component to a project's BOM.
In a real system, this would ingest a CycloneDX JSON automatically.
"""
# 1. Find or Create Project
project = db.query(Project).filter(Project.name == data.project_name).first()
if not project:
project = Project(name=data.project_name, is_proprietary=True)
db.add(project)
db.commit()
# 2. Find Component (Mocking a lookup)
comp = db.query(Component).filter(Component.purl == data.component_purl).first()
if not comp:
# Mock creation for demo
comp = Component(name=data.component_name, purl=data.component_purl, version="1.0.0")
# Assume GPL for demo if new
gpl = db.query(License).filter(License.spdx_id == "GPL-3.0").first()
comp.license_options.append(ComponentLicense(license=gpl))
db.add(comp)
db.commit()
# 3. Create Dependency Link
dep = ProjectDependency(
project=project,
component=comp,
usage_type=data.usage.value,
chosen_license=comp.license_options[0].license # Default choice
)
db.add(dep)
db.commit()
return {"status": "added", "dependency_id": dep.id}
@app.get("/compliance/check/{project_id}")
def check_compliance(project_id: int, db: Session = Depends(get_db)):
"""
The Policy Engine: Scans BOM for violations based on usage and license type.
"""
project = db.query(Project).get(project_id)
violations = []
for dep in project.dependencies:
license = dep.chosen_license
is_violation = False
reason = ""
# RULE 1: No Strong Copyleft in Proprietary Software (unless dynamic link allowed by policy)
if project.is_proprietary and license.category == LicenseType.STRONG_COPYLEFT:
if dep.usage_type != UsageType.DYNAMIC_LINK.value: # Example policy nuance
is_violation = True
reason = f"Strong Copyleft ({license.spdx_id}) used in Proprietary code via {dep.usage_type}"
# RULE 2: Check for existing exceptions
exception = db.query(PolicyException).filter(
PolicyException.project_dependency_id == dep.id,
PolicyException.status == ApprovalStatus.APPROVED
).first()
if is_violation:
violations.append({
"component": dep.component.name,
"license": license.spdx_id,
"reason": reason,
"exception_status": "APPROVED" if exception else "NONE"
})
return {"project": project.name, "compliance_status": "FAIL" if violations else "PASS", "violations": violations}
@app.post("/exceptions/request")
def request_exception(req: ExceptionRequest, db: Session = Depends(get_db)):
"""Request a policy exception."""
existing = db.query(PolicyException).filter(PolicyException.project_dependency_id == req.dependency_id).first()
if existing:
raise HTTPException(status_code=400, detail="Exception already exists")
exc = PolicyException(
project_dependency_id=req.dependency_id,
justification=req.justification,
status=ApprovalStatus.PENDING
)
db.add(exc)
db.commit()
return {"status": "Exception Requested"}
@app.post("/dual-license/select")
def select_dual_license(dep_id: int, license_spdx: str, db: Session = Depends(get_db)):
"""
Manages Dual Licensing.
E.g., Switching a library from GPL (Open Source) to Commercial (Paid).
"""
dep = db.query(ProjectDependency).get(dep_id)
target_license = db.query(License).filter(License.spdx_id == license_spdx).first()
if not dep or not target_license:
raise HTTPException(status_code=404, detail="Not found")
# Logic: Verify the component actually offers this license
available = False
for opt in dep.component.license_options:
if opt.license.spdx_id == license_spdx:
available = True
break
if not available:
raise HTTPException(status_code=400, detail="This license is not available for this component")
dep.chosen_license = target_license
db.commit()
return {"status": "updated", "new_license": target_license.spdx_id}
@app.post("/contributions/submit")
def submit_contribution(data: ContributionIn, db: Session = Depends(get_db)):
"""Governance for contributing code back to open source."""
contrib = OutboundContribution(**data.dict())
db.add(contrib)
db.commit()
return {"id": contrib.id, "message": "Contribution logged for review"}
@app.post("/contributions/{contrib_id}/approve")
def approve_contribution(contrib_id: int, db: Session = Depends(get_db)):
contrib = db.query(OutboundContribution).get(contrib_id)
if not contrib.cla_signed:
# In a real app, integrate with CLA assistant / DocuSign API
raise HTTPException(status_code=403, detail="CLA must be signed before approval")
contrib.status = "Approved"
db.commit()
return {"status": "Approved"}
In the code above, the ProjectDependency table forms the BOM.
add_dependency endpoint with a parser that accepts CycloneDX (JSON) or SPDX files. You would iterate through the components array in the SBOM and populate the database automatically.The /compliance/check/ endpoint implements the logic.
library-x which is GPL, in your proprietary app./exceptions/request.PolicyException record status changes to APPROVED.This is handled by the chosen_license_id in the ProjectDependency table.
Component (Qt) has two entries in ComponentLicense.The OutboundContribution model tracks employees pushing code to GitHub.
To turn this skeleton into a full enterprise product, add the following:
GET /project/{id}/sbom that generates a valid CycloneDX JSON file for your customers (required for enterprise sales contracts now).cla_signed automatically before approving contributions.