Spaces:
Paused

yaz / src /core /licensing /models.py
anaselamr's picture
[PLATFORM] feat(sprint53-76): Sprint 53→76 — EDUCA cards, SURGIO daily-briefing, traceability core, security hardening, VPS deploy runbook, tiered backup retention, visitor login fix (black+isort+ruff applied)
8f21a0d
Raw History Blame Contribute Delete
11.2 kB
# SPDX-License-Identifier: LicenseRef-YAZ-Dual
# Copyright (c) 2024–2026 Dr. Anass Elamrani. See LICENSE for details.
"""
YAZ Platform — License Domain Models
======================================
Defines license types, tiers, features, and key validation structures.
License Architecture
--------------------
AYUJI → Charitable / Research (free, unlimited, AGPL + AYUJI-Charitable-1.0)
For: NGOs, humanitarian missions, LMICs, academic researchers
Governed by: AYUJI Holding Evidence
Community → AGPL-3.0, single-tenant, 3 users, 2 modules, no SLA
YEMA Starter → Commercial under YEMA Holding Ops, 10 users, 1 org
YEMA Professional→ Commercial under YEMA Holding Ops, 50 users, all engines
YEMA Enterprise → Commercial under YEMA Holding Ops, unlimited, multi-tenant
Creator → Add-on for Intelligence Module publishing (70/30 revenue split)
Internal → Author / internal YAZ use (unlimited)
Dual-Licence Model
------------------
AYUJI track: Free ∀ verified NGOs/researchers. Obligation: anonymised case
contributions flow to AYUJI evidence base for scientific publication.
YEMA track: Revenue model. Surgery centers, private hospitals, enterprises.
YEMA Holding claims 30% platform fee; 70% to intelligence creators.
Security: License keys are HMAC-signed; validated locally without network call.
Performance: Key validation <5ms (cached per process lifetime)
"""
from __future__ import annotations
from datetime import UTC, date, datetime, timezone
from enum import Enum
from typing import Dict, List, Optional
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, field_validator
from sqlmodel import JSON, Column, SQLModel
from sqlmodel import Field as SQLField
# ============================================================================
# ENUMS
# ============================================================================
class LicenseTier(str, Enum):
"""Ordered license tiers — higher ordinal = more capabilities."""
# ── AYUJI track (Charitable / Research — governed by AYUJI Holding Evidence)
AYUJI = "ayuji" # Free for verified NGOs/researchers, AGPL + AYUJI-Charitable-1.0
# ── Open source baseline
COMMUNITY = "community" # AGPL-3.0, free, 3 users
# ── YEMA track (Commercial — governed by YEMA Holding Ops)
STARTER = "starter" # $59/mo
PROFESSIONAL = "professional" # $249/mo
ENTERPRISE = "enterprise" # Custom
INTERNAL = "internal" # Author / internal YAZ use (unlimited)
# Holding attribution per tier (display / legal)
TIER_HOLDING: dict[LicenseTier, str] = {}
_HOLDING_MAP = {
"ayuji": "AYUJI Holding Evidence",
"community": "AYRAD Cloud SARL (AGPL-3.0)",
"starter": "YEMA Holding Ops",
"professional": "YEMA Holding Ops",
"enterprise": "YEMA Holding Ops",
"internal": "AYRAD Group SAS",
}
class LicenseType(str, Enum):
"""Binding legal license type."""
AGPL3 = "agpl-3.0"
COMMERCIAL = "commercial"
class LicenseStatus(str, Enum):
ACTIVE = "active"
EXPIRED = "expired"
SUSPENDED = "suspended"
TRIAL = "trial"
CANCELLED = "cancelled"
class FeatureFlag(str, Enum):
"""Features gated by license tier."""
# Infrastructure
MULTI_TENANT = "multi_tenant"
WHITE_LABEL = "white_label"
CUSTOM_DOMAIN = "custom_domain"
API_ACCESS = "api_access"
# Auth
SSO_OAUTH = "sso_oauth"
SSO_SAML = "sso_saml"
LDAP = "ldap"
# Platform
ALL_ENGINES = "all_engines"
CREATOR_PUBLISH = "creator_publish"
MARKETPLACE_BUY = "marketplace_buy"
ADVANCED_ANALYTICS = "advanced_analytics"
AUDIT_EXPORT = "audit_export"
# Support
SLA_SUPPORT = "sla_support"
DEDICATED_CSM = "dedicated_csm"
SOURCE_ACCESS = "source_access"
# Compliance
BAA_AGREEMENT = "baa_agreement"
DPA_AGREEMENT = "dpa_agreement"
PENTEST_REPORTS = "pentest_reports"
# ============================================================================
# FEATURE MATRIX — per tier
# ============================================================================
TIER_FEATURES: dict[LicenseTier, list[FeatureFlag]] = {
# ── AYUJI: all features for verified charitable/research orgs
LicenseTier.AYUJI: list(FeatureFlag), # Full access — evidence contribution is the return
LicenseTier.COMMUNITY: [
FeatureFlag.API_ACCESS,
FeatureFlag.MARKETPLACE_BUY,
],
LicenseTier.STARTER: [
FeatureFlag.API_ACCESS,
FeatureFlag.MARKETPLACE_BUY,
FeatureFlag.AUDIT_EXPORT,
],
LicenseTier.PROFESSIONAL: [
FeatureFlag.API_ACCESS,
FeatureFlag.MARKETPLACE_BUY,
FeatureFlag.CREATOR_PUBLISH,
FeatureFlag.AUDIT_EXPORT,
FeatureFlag.ADVANCED_ANALYTICS,
FeatureFlag.SSO_OAUTH,
FeatureFlag.BAA_AGREEMENT,
FeatureFlag.DPA_AGREEMENT,
],
LicenseTier.ENTERPRISE: [
FeatureFlag.MULTI_TENANT,
FeatureFlag.WHITE_LABEL,
FeatureFlag.CUSTOM_DOMAIN,
FeatureFlag.API_ACCESS,
FeatureFlag.SSO_OAUTH,
FeatureFlag.SSO_SAML,
FeatureFlag.LDAP,
FeatureFlag.ALL_ENGINES,
FeatureFlag.CREATOR_PUBLISH,
FeatureFlag.MARKETPLACE_BUY,
FeatureFlag.ADVANCED_ANALYTICS,
FeatureFlag.AUDIT_EXPORT,
FeatureFlag.SLA_SUPPORT,
FeatureFlag.DEDICATED_CSM,
FeatureFlag.SOURCE_ACCESS,
FeatureFlag.BAA_AGREEMENT,
FeatureFlag.DPA_AGREEMENT,
FeatureFlag.PENTEST_REPORTS,
],
LicenseTier.INTERNAL: list(FeatureFlag), # All features
}
# Tier limits
TIER_LIMITS: dict[LicenseTier, dict] = {
# AYUJI: unlimited for all dimensions — obligation is evidence contribution
LicenseTier.AYUJI: {
"max_users": -1,
"max_tenants": 1,
"max_engines": -1,
"max_intelligence_modules": -1,
},
LicenseTier.COMMUNITY: {
"max_users": 3,
"max_tenants": 1,
"max_engines": 2,
"max_intelligence_modules": 2,
},
LicenseTier.STARTER: {
"max_users": 10,
"max_tenants": 1,
"max_engines": 2,
"max_intelligence_modules": 5,
},
LicenseTier.PROFESSIONAL: {
"max_users": 50,
"max_tenants": 3,
"max_engines": -1, # -1 = unlimited
"max_intelligence_modules": -1,
},
LicenseTier.ENTERPRISE: {
"max_users": -1,
"max_tenants": -1,
"max_engines": -1,
"max_intelligence_modules": -1,
},
LicenseTier.INTERNAL: {
"max_users": -1,
"max_tenants": -1,
"max_engines": -1,
"max_intelligence_modules": -1,
},
}
# Annual pricing (USD)
TIER_PRICING: dict[LicenseTier, dict] = {
LicenseTier.AYUJI: {
"monthly": 0,
"annual": 0,
"currency": "USD",
"note": "Free for verified NGOs, humanitarian orgs, academic researchers. Evidence contribution required.",
},
LicenseTier.COMMUNITY: {"monthly": 0, "annual": 0, "currency": "USD"},
LicenseTier.STARTER: {"monthly": 59, "annual": 49 * 12, "currency": "USD"},
LicenseTier.PROFESSIONAL: {"monthly": 249, "annual": 199 * 12, "currency": "USD"},
LicenseTier.ENTERPRISE: {"monthly": None, "annual": None, "currency": "USD"},
LicenseTier.INTERNAL: {"monthly": 0, "annual": 0, "currency": "USD"},
}
# ============================================================================
# DATABASE MODEL
# ============================================================================
class LicenseRecord(SQLModel, table=True):
"""
Persisted license record per tenant.
Security: tenant_id on every query. License keys are stored as
opaque identifiers — the actual validation uses HMAC signatures.
Performance: <5ms via lru_cache on the service layer.
"""
__tablename__ = "license_records"
id: UUID = SQLField(default_factory=uuid4, primary_key=True)
tenant_id: UUID = SQLField(index=True)
# License identity
license_key: str = SQLField(index=True, unique=True, max_length=200)
tier: LicenseTier = SQLField(default=LicenseTier.COMMUNITY)
license_type: LicenseType = SQLField(default=LicenseType.AGPL3)
status: LicenseStatus = SQLField(default=LicenseStatus.ACTIVE)
# Temporal
issued_at: datetime = SQLField(default_factory=lambda: datetime.now(UTC))
valid_from: date = SQLField()
valid_until: date | None = SQLField(default=None) # None = perpetual
trial_ends_at: datetime | None = SQLField(default=None)
# Limits (override tier defaults if set)
max_users: int | None = SQLField(default=None)
max_tenants: int | None = SQLField(default=None)
max_engines: int | None = SQLField(default=None)
# Metadata
licensee_name: str = SQLField(default="", max_length=200)
licensee_email: str = SQLField(default="", max_length=200)
licensee_org: str = SQLField(default="", max_length=200)
licensee_country: str = SQLField(default="", max_length=2) # ISO 3166-1 alpha-2
features_override: list[str] | None = SQLField(default=None, sa_column=Column(JSON))
extra_data: dict | None = SQLField(default=None, sa_column=Column(JSON))
# Compliance
baa_signed: bool = SQLField(default=False)
dpa_signed: bool = SQLField(default=False)
baa_signed_at: datetime | None = SQLField(default=None)
dpa_signed_at: datetime | None = SQLField(default=None)
# Billing
stripe_subscription_id: str | None = SQLField(default=None, max_length=100)
stripe_customer_id: str | None = SQLField(default=None, max_length=100)
created_at: datetime = SQLField(default_factory=lambda: datetime.now(UTC))
updated_at: datetime = SQLField(default_factory=lambda: datetime.now(UTC))
# ============================================================================
# PYDANTIC SCHEMAS
# ============================================================================
class LicenseSummary(BaseModel):
"""Read-only license view returned to API clients."""
tier: LicenseTier
license_type: LicenseType
status: LicenseStatus
valid_until: date | None
features: list[FeatureFlag]
limits: dict
licensee_org: str
licensee_country: str
baa_signed: bool
dpa_signed: bool
model_config = {"from_attributes": True}
class LicenseCheckResult(BaseModel):
"""Result of a feature/limit gate check."""
allowed: bool
tier: LicenseTier
feature: FeatureFlag | None = None
reason: str | None = None
class LicenseActivationRequest(BaseModel):
"""Payload sent to activate a new license key."""
license_key: str = Field(..., min_length=20, max_length=200)
licensee_name: str = Field(..., min_length=1, max_length=200)
licensee_email: str = Field(..., min_length=5, max_length=200)
licensee_org: str = Field(..., min_length=1, max_length=200)
licensee_country: str = Field(..., min_length=2, max_length=2)
@field_validator("licensee_country")
@classmethod
def upper_country(cls, v: str) -> str:
return v.upper()