Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
A signature that can fail, a registry we chose, and an image that cannot change (#734)
Beenu Arora1ba0c70a5772
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 69b7b785a..3ef7c3d06 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -4734,6 +4734,89 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/community/publishers/keys:+ get:+ tags:+ - community+ summary: List Publisher Keys+ operationId: list_publisher_keys_api_v1_community_publishers_keys_get+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ items:+ $ref: '#/components/schemas/PublisherKeyOut'+ type: array+ title: Response List Publisher Keys Api V1 Community Publishers Keys+ Get+ security:+ - HTTPBearer: []+ post:+ tags:+ - community+ summary: Add Publisher Key+ description: 'Register a public key you will sign submissions with.+++ Until a key is registered, submissions are accepted and marked++ unverified. Once one is, a submission that does not match it is rejected++ — which is the difference between a signature and a decoration.'+ operationId: add_publisher_key_api_v1_community_publishers_keys_post+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PublisherKeyIn'+ required: true+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/PublisherKeyOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ security:+ - HTTPBearer: []+ /api/v1/community/publishers/keys/{fingerprint}:+ delete:+ tags:+ - community+ summary: Revoke Publisher Key+ description: 'Revoke a key.+++ Recorded as a timestamp, not a delete: "signed by a key we have since++ revoked" is a more useful statement after the fact than "unknown key".'+ operationId: revoke_publisher_key_api_v1_community_publishers_keys__fingerprint__delete+ security:+ - HTTPBearer: []+ parameters:+ - name: fingerprint+ in: path+ required: true+ schema:+ type: string+ title: Fingerprint+ responses:+ '204':+ description: Successful Response+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/community/plugins/publish:post:tags:@@ -23496,6 +23579,50 @@ components:- view_count- created_attitle: PublishedSummary+ PublisherKeyIn:+ properties:+ public_key_pem:+ type: string+ title: Public Key Pem+ description: PEM-encoded Ed25519 public key.+ label:+ type: string+ maxLength: 120+ title: Label+ description: Which machine or CI job holds the private half.+ default: ''+ display_name:+ type: string+ maxLength: 200+ title: Display Name+ default: ''+ contact_email:+ type: string+ maxLength: 320+ title: Contact Email+ default: ''+ type: object+ required:+ - public_key_pem+ title: PublisherKeyIn+ PublisherKeyOut:+ properties:+ fingerprint:+ type: string+ title: Fingerprint+ label:+ type: string+ title: Label+ publisher_id:+ type: string+ format: uuid+ title: Publisher Id+ type: object+ required:+ - fingerprint+ - label+ - publisher_id+ title: PublisherKeyOutQueryRequest:properties:question:diff --git a/packages/aisoc-cli/src/aisoc_cli/main.py b/packages/aisoc-cli/src/aisoc_cli/main.pyindex 3b66e9fc7..eaa5eb408 100644--- a/packages/aisoc-cli/src/aisoc_cli/main.py+++ b/packages/aisoc-cli/src/aisoc_cli/main.py@@ -301,7 +301,11 @@ def plugin_publish(path: str, api_url: str, api_key: str, private_key: str) -> Nconsole.print(f"Publishing to [bold]{api_url}[/bold]...")with httpx.Client(base_url=api_url, headers={"Authorization": f"Bearer {api_key}"}) as client:resp = client.post(- "/api/v1/plugins/publish",+ # `/api/v1/plugins/publish` for as long as this command has+ # existed. No router ever served that path — the real one is+ # under the community prefix — so `aisoc plugin publish` was+ # broken as shipped and failed with a 404 nobody could act on.+ "/api/v1/community/plugins/publish",content=tarball,headers={"Content-Type": "application/octet-stream",diff --git a/services/api/app/api/v1/endpoints/community.py b/services/api/app/api/v1/endpoints/community.pyindex 4138565ee..509307911 100644--- a/services/api/app/api/v1/endpoints/community.py+++ b/services/api/app/api/v1/endpoints/community.py@@ -41,7 +41,17 @@ from fastapi import (from pydantic import BaseModel, Fieldfrom app.api.v1.deps import AuthUser, CurrentUser, require_permission-from app.core.security import verify_ed25519_signature+from app.db.rls import TenantDBSession+from app.services.marketplace_publishers import (+ PublisherKeyError,+ active_keys,+ ensure_publisher,+ keys_for_user,+ parse_public_key,+ register_key,+ revoke_key,+ verify_against,+)router = APIRouter(prefix="/community", tags=["community"])@@ -117,6 +127,83 @@ class CommunityPlaybookOut(BaseModel):definition: dict[str, Any] | None = None+# ── Publisher identity ────────────────────────────────────────────────────────+++class PublisherKeyIn(BaseModel):+ public_key_pem: str = Field(..., description="PEM-encoded Ed25519 public key.")+ label: str = Field(default="", max_length=120, description="Which machine or CI job holds the private half.")+ display_name: str = Field(default="", max_length=200)+ contact_email: str = Field(default="", max_length=320)+++class PublisherKeyOut(BaseModel):+ fingerprint: str+ label: str+ publisher_id: uuid.UUID++[email protected]("/publishers/keys", response_model=PublisherKeyOut, status_code=201)+async def add_publisher_key(+ body: PublisherKeyIn,+ current_user: AuthUser,+ db: TenantDBSession,+) -> PublisherKeyOut:+ """Register a public key you will sign submissions with.++ Until a key is registered, submissions are accepted and marked+ unverified. Once one is, a submission that does not match it is rejected+ — which is the difference between a signature and a decoration.+ """+ try:+ parse_public_key(body.public_key_pem)+ except PublisherKeyError as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc++ publisher_id = await ensure_publisher(+ db,+ tenant_id=current_user.tenant_id,+ user_id=current_user.user_id,+ display_name=body.display_name or (current_user.email or "Publisher"),+ contact_email=body.contact_email or (current_user.email or ""),+ )+ key = await register_key(db, publisher_id=publisher_id, public_key_pem=body.public_key_pem, label=body.label)+ return PublisherKeyOut(fingerprint=key.fingerprint, label=key.label, publisher_id=key.publisher_id)++[email protected]("/publishers/keys", response_model=list[PublisherKeyOut])+async def list_publisher_keys(+ current_user: AuthUser,+ db: TenantDBSession,+) -> list[PublisherKeyOut]:+ keys = await keys_for_user(db, tenant_id=current_user.tenant_id, user_id=current_user.user_id)+ return [PublisherKeyOut(fingerprint=k.fingerprint, label=k.label, publisher_id=k.publisher_id) for k in keys]++[email protected]("/publishers/keys/{fingerprint}", status_code=204)+async def revoke_publisher_key(+ fingerprint: str,+ current_user: AuthUser,+ db: TenantDBSession,+) -> None:+ """Revoke a key.++ Recorded as a timestamp, not a delete: "signed by a key we have since+ revoked" is a more useful statement after the fact than "unknown key".+ """+ publisher_id = await ensure_publisher(+ db,+ tenant_id=current_user.tenant_id,+ user_id=current_user.user_id,+ display_name=current_user.email or "Publisher",+ contact_email=current_user.email or "",+ )+ keys = await active_keys(db, publisher_id=publisher_id)+ if not any(k.fingerprint == fingerprint for k in keys):+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such active key for this publisher")+ await revoke_key(db, publisher_id=publisher_id, fingerprint=fingerprint)++# ── Plugin endpoints ──────────────────────────────────────────────────────────@@ -124,6 +211,7 @@ class CommunityPlaybookOut(BaseModel):async def publish_plugin(request: Request,current_user: AuthUser,+ db: TenantDBSession,) -> dict[str, Any]:"""Submit a signed plugin tarball for community review."""sig_b64 = request.headers.get("X-Plugin-Signature")@@ -145,18 +233,28 @@ async def publish_plugin(except Exception as exc:raise HTTPException(status_code=400, detail=f"Invalid signature or manifest: {exc}") from exc- # Signature verification — allow submission without registered key (marks as unverified)+ # Signature verification against this publisher's registered keys.+ #+ # Two outcomes that used to be one. A submission from somebody with no+ # registered key is *unverified* and accepted as such; a submission whose+ # signature does not match a key they do have is *rejected*. Before the+ # publisher tables existed, `_get_registered_pub_key` returned None+ # unconditionally, so the second branch was unreachable and no plugin+ # could ever be rejected for a bad signature.verified = False- registered_pub_key = _get_registered_pub_key(str(current_user.user_id))- if registered_pub_key:- try:- verify_ed25519_signature(registered_pub_key, tarball, signature)- verified = True- except Exception as exc:+ signing_fingerprint: str | None = None+ keys = await keys_for_user(db, tenant_id=current_user.tenant_id, user_id=current_user.user_id)+ if keys:+ signing_fingerprint = verify_against(keys, tarball, signature)+ if signing_fingerprint is None:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,- detail="Invalid Ed25519 signature",- ) from exc+ detail=(+ "Signature does not match any key registered to this publisher. "+ "Register the key you signed with, or revoke the stale one."+ ),+ )+ verified = Trueplugin_id = manifest.get("id", str(uuid.uuid4()))entry = {@@ -172,6 +270,7 @@ async def publish_plugin("rating": 0.0,"rating_count": 0,"verified": verified,+ "signing_fingerprint": signing_fingerprint,"submitted_by": current_user.user_id,"submitted_at": datetime.now(UTC).isoformat(),"approved_at": None,@@ -500,6 +599,8 @@ async def curate_community_playbook(# ── Helpers ───────────────────────────────────────────────────────────────────-def _get_registered_pub_key(user_id: str) -> bytes | None:- """Retrieve user's registered Ed25519 public key (stub — wire to DB)."""- return None+# `_get_registered_pub_key` used to live here, returning None unconditionally+# with the comment "(stub — wire to DB)". It is gone rather than fixed in+# place, because the shape was wrong as well as the body: one key per user+# cannot express a rotation, and a publisher who cannot rotate will not.+# `app.services.marketplace_publishers` owns this now.diff --git a/services/api/app/api/v1/endpoints/plugins.py b/services/api/app/api/v1/endpoints/plugins.pyindex af8f5090c..e27ffc2c3 100644--- a/services/api/app/api/v1/endpoints/plugins.py+++ b/services/api/app/api/v1/endpoints/plugins.py@@ -163,6 +163,26 @@ async def reload_plugin(return _to_plugin_out(_mgr().get_plugin(plugin_id)) # type: ignore[arg-type]+# The OCI install route is NOT exposed here, and the reason is worth keeping.+#+# `PluginManager.install_from_oci` is 220 lines of hardened ingest with no+# HTTP caller, so all of that hardening protects a path nobody can take. That+# is a real gap and v9.0 tried to close it.+#+# Adding the route made CodeQL flag eight `py/path-injection` sites across the+# plugin-ingest graph, all high severity. The validation those paths rely on+# is real and runs — `_validate_plugin_id`, `_validate_oci_ref`,+# `_assert_no_symlinks` — but taint analysis does not follow a value across a+# function boundary, and neither does a reader. Exposing the entry point+# turned an invisible property into eight visible findings.+#+# Trading "a hardened path with no caller" for "a reachable path with eight+# unresolved high findings" is a worse position, so the route is held back+# until each site sanitises at its point of use. Everything else in the+# marketplace wave — publisher identity, the registry allow-list, digest+# pinning — landed, and those are what make the route safe to add.++@router.delete("/{plugin_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)async def unload_plugin(plugin_id: str,diff --git a/services/api/app/services/marketplace_publishers.py b/services/api/app/services/marketplace_publishers.pynew file mode 100644index 000000000..33600a633--- /dev/null+++ b/services/api/app/services/marketplace_publishers.py@@ -0,0 +1,236 @@+"""Publisher identity: who signed this, and may we say so.++``_get_registered_pub_key`` returned ``None`` unconditionally, with the+comment ``(stub — wire to DB)``. The consequence is worth stating exactly,+because it is not "signatures were weak": ``publish_plugin`` reads that+function, finds no key, and **skips verification entirely**, storing+``verified: False``. A submitted plugin could not be rejected for a bad+signature. The signing path existed end to end, was documented, had a CLI+command, and could never fail.++That matters most for what comes next. A marketplace that takes payment has+to be able to say which publisher a listing belongs to; paying people we+cannot identify for code we cannot attribute is not a feature gap, it is a+different product.++Three properties this module holds:++**A key is registered against a person, not a tenant.** Publishing is an+individual act and revocation has to be able to name one.++**Revocation is a timestamp, not a delete.** A signature made before+revocation stays explicable afterwards — "this was signed by a key we have+since revoked" is a different and more useful statement than "unknown key".++**Verification failing is different from no key being registered.** The first+is a rejection; the second is an unverified submission. Collapsing them is+how the stub above looked like a working control.+"""++from __future__ import annotations++import hashlib+import uuid+from dataclasses import dataclass++import structlog+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey+from sqlalchemy import text+from sqlalchemy.ext.asyncio import AsyncSession++logger = structlog.get_logger(__name__)+++class PublisherKeyError(ValueError):+ """The supplied key is not a usable Ed25519 public key."""+++@dataclass(frozen=True)+class RegisteredKey:+ id: uuid.UUID+ publisher_id: uuid.UUID+ public_key_pem: str+ fingerprint: str+ label: str+++def parse_public_key(pem: str) -> tuple[Ed25519PublicKey, str]:+ """Validate a PEM Ed25519 public key and return it with its fingerprint.++ Rejecting a non-Ed25519 key here rather than at verification time means a+ publisher finds out while registering, not when their first release is+ silently unverifiable.+ """+ try:+ loaded = serialization.load_pem_public_key(pem.encode("utf-8"))+ except Exception as exc: # noqa: BLE001 — any parse failure is the same answer+ raise PublisherKeyError("not a valid PEM public key") from exc++ if not isinstance(loaded, Ed25519PublicKey):+ raise PublisherKeyError("only Ed25519 public keys are accepted")++ der = loaded.public_bytes(+ encoding=serialization.Encoding.DER,+ format=serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ return loaded, hashlib.sha256(der).hexdigest()+++async def ensure_publisher(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ user_id: uuid.UUID,+ display_name: str,+ contact_email: str,+) -> uuid.UUID:+ """Return this user's publisher id, creating an unverified one if needed."""+ row = (+ await db.execute(+ text("SELECT id FROM marketplace_publishers " "WHERE tenant_id = :tenant_id AND user_id = :user_id"),+ {"tenant_id": str(tenant_id), "user_id": str(user_id)},+ )+ ).first()+ if row is not None:+ return uuid.UUID(str(row[0]))++ created = (+ await db.execute(+ text(+ "INSERT INTO marketplace_publishers "+ "(tenant_id, user_id, display_name, contact_email) "+ "VALUES (:tenant_id, :user_id, :display_name, :contact_email) "+ "RETURNING id"+ ),+ {+ "tenant_id": str(tenant_id),+ "user_id": str(user_id),+ "display_name": display_name[:200],+ "contact_email": contact_email[:320],+ },+ )+ ).first()+ await db.commit()+ return uuid.UUID(str(created[0]))+++async def register_key(+ db: AsyncSession,+ *,+ publisher_id: uuid.UUID,+ public_key_pem: str,+ label: str = "",+) -> RegisteredKey:+ _, fingerprint = parse_public_key(public_key_pem)++ row = (+ await db.execute(+ text(+ "INSERT INTO marketplace_publisher_keys "+ "(publisher_id, public_key_pem, fingerprint, label) "+ "VALUES (:publisher_id, :pem, :fingerprint, :label) "+ "ON CONFLICT (fingerprint) DO UPDATE SET label = EXCLUDED.label "+ "RETURNING id, publisher_id, public_key_pem, fingerprint, label"+ ),+ {+ "publisher_id": str(publisher_id),+ "pem": public_key_pem,+ "fingerprint": fingerprint,+ "label": label[:120],+ },+ )+ ).first()+ await db.commit()+ return RegisteredKey(+ id=uuid.UUID(str(row[0])),+ publisher_id=uuid.UUID(str(row[1])),+ public_key_pem=str(row[2]),+ fingerprint=str(row[3]),+ label=str(row[4]),+ )+++async def revoke_key(db: AsyncSession, *, publisher_id: uuid.UUID, fingerprint: str) -> bool:+ result = await db.execute(+ text(+ "UPDATE marketplace_publisher_keys SET revoked_at = now() "+ "WHERE publisher_id = :publisher_id AND fingerprint = :fingerprint "+ "AND revoked_at IS NULL"+ ),+ {"publisher_id": str(publisher_id), "fingerprint": fingerprint},+ )+ await db.commit()+ return bool(result.rowcount)+++async def active_keys(db: AsyncSession, *, publisher_id: uuid.UUID) -> list[RegisteredKey]:+ rows = (+ await db.execute(+ text(+ "SELECT id, publisher_id, public_key_pem, fingerprint, label "+ "FROM marketplace_publisher_keys "+ "WHERE publisher_id = :publisher_id AND revoked_at IS NULL "+ "ORDER BY created_at"+ ),+ {"publisher_id": str(publisher_id)},+ )+ ).fetchall()+ return [+ RegisteredKey(+ id=uuid.UUID(str(r[0])),+ publisher_id=uuid.UUID(str(r[1])),+ public_key_pem=str(r[2]),+ fingerprint=str(r[3]),+ label=str(r[4]),+ )+ for r in rows+ ]+++async def keys_for_user(+ db: AsyncSession,+ *,+ tenant_id: uuid.UUID,+ user_id: uuid.UUID,+) -> list[RegisteredKey]:+ """Every active key this user can sign with. Empty is a normal state."""+ rows = (+ await db.execute(+ text(+ "SELECT k.id, k.publisher_id, k.public_key_pem, k.fingerprint, k.label "+ "FROM marketplace_publisher_keys k "+ "JOIN marketplace_publishers p ON p.id = k.publisher_id "+ "WHERE p.tenant_id = :tenant_id AND p.user_id = :user_id "+ "AND k.revoked_at IS NULL ORDER BY k.created_at"+ ),+ {"tenant_id": str(tenant_id), "user_id": str(user_id)},+ )+ ).fetchall()+ return [+ RegisteredKey(+ id=uuid.UUID(str(r[0])),+ publisher_id=uuid.UUID(str(r[1])),+ public_key_pem=str(r[2]),+ fingerprint=str(r[3]),+ label=str(r[4]),+ )+ for r in rows+ ]+++def verify_against(keys: list[RegisteredKey], payload: bytes, signature: bytes) -> str | None:+ """Return the fingerprint of the key that verified, or None.++ Tries every active key because a publisher rotating keys will have two+ valid ones for a while, and forcing them to re-sign everything during a+ rotation is how rotations get skipped.+ """+ for key in keys:+ try:+ public_key, _ = parse_public_key(key.public_key_pem)+ public_key.verify(signature, payload)+ return key.fingerprint+ except Exception: # noqa: BLE001, S112 — a key that does not verify is the normal case here+ continue+ return Nonediff --git a/services/api/app/services/plugin_manager.py b/services/api/app/services/plugin_manager.pyindex cbdd9721a..f7c6dcac6 100644--- a/services/api/app/services/plugin_manager.py+++ b/services/api/app/services/plugin_manager.py@@ -117,6 +117,35 @@ _OCI_FORBIDDEN_HOST_SUBSTRINGS = ("metadata.azure.com",)+#: Registries an operator permits plugins to be installed from.+#:+#: Empty means "any registry", which is the historical behaviour and stays+#: the default so this does not break an existing deployment on upgrade. The+#: documentation had claimed an allow-list existed; it did not, and only a+#: metadata-host *deny* list was present. A deny list answers "is this one of+#: three known-bad hosts" — an allow-list answers "is this a registry we+#: chose", which is the question worth asking about code that runs in-process.+_OCI_REGISTRY_ALLOWLIST_ENV = "AISOC_PLUGIN_REGISTRY_ALLOWLIST"++#: A pinned reference names an immutable digest.+_OCI_DIGEST_RE = re.compile(r"@sha256:[a-f0-9]{64}$")+++def _registry_allowlist() -> tuple[str, ...]:+ raw = os.environ.get(_OCI_REGISTRY_ALLOWLIST_ENV, "")+ return tuple(entry.strip().lower() for entry in raw.split(",") if entry.strip())+++def _registry_of(oci_ref: str) -> str:+ """The host portion of a reference, lower-cased.++ A reference with no host — ``library/thing:1.0`` — resolves to Docker Hub+ implicitly. Returning an empty string for that case means it fails an+ allow-list rather than passing one by accident.+ """+ head = oci_ref.split("/", 1)[0]+ return head.lower() if ("." in head or ":" in head or head == "localhost") else ""+def _validate_plugin_id(plugin_id: str) -> str:"""Return ``plugin_id`` if it is a safe path/module component.@@ -156,9 +185,49 @@ def _validate_oci_ref(oci_ref: str) -> str:lowered = oci_ref.lower()if any(bad in lowered for bad in _OCI_FORBIDDEN_HOST_SUBSTRINGS):raise PluginError(oci_ref, "oci_ref host is on the forbidden metadata-service deny list")++ allowlist = _registry_allowlist()+ if allowlist:+ registry = _registry_of(oci_ref)+ if registry not in allowlist:+ raise PluginError(+ oci_ref,+ f"registry {registry or '(implicit docker hub)'} is not in {_OCI_REGISTRY_ALLOWLIST_ENV}",+ )return oci_ref+def _require_pinned(oci_ref: str) -> str:+ """Reject a reference that does not name an immutable digest.++ A tag is mutable: ``:latest`` resolves to one image at install time and a+ different one tomorrow, so "what plugin is this deployment running" has+ no answer after the fact, and a publisher — or anyone who takes their+ account — can change in-process code without touching this system.++ The signature gate does not close this. It verifies whatever arrived; it+ cannot tell you that what arrived is what was reviewed.++ Opt-out exists (``AISOC_PLUGIN_ALLOW_UNPINNED=1``) because requiring+ digests unconditionally would break every existing tag-based install on+ upgrade, and a control that forces an operator to disable it wholesale is+ worse than one they can adopt.+ """+ if _OCI_DIGEST_RE.search(oci_ref):+ return oci_ref+ if os.environ.get("AISOC_PLUGIN_ALLOW_UNPINNED", "").strip().lower() in {"1", "true", "yes", "on"}:+ logger.warning(+ "plugin.oci_unpinned",+ oci_ref=oci_ref,+ note="installed from a mutable tag; the running code can change without this system being told",+ )+ return oci_ref+ raise PluginError(+ oci_ref,+ "oci_ref must be pinned to a digest (repo@sha256:...); " "set AISOC_PLUGIN_ALLOW_UNPINNED=1 to accept a mutable tag",+ )++def _assert_no_symlinks(root: Path) -> None:"""Raise ``PluginError`` if ``root`` contains *any* symbolic link.@@ -647,8 +716,10 @@ class PluginManager:Returns the plugin_id after successful installation."""- # 1) Input validation — argv hygiene before any subprocess work.+ # 1) Input validation — argv hygiene, an operator-chosen registry, and+ # an immutable reference, all before any subprocess work._validate_oci_ref(oci_ref)+ _require_pinned(oci_ref)if plugin_id_hint is not None:_validate_plugin_id(plugin_id_hint)@@ -721,7 +792,19 @@ class PluginManager:# so links would be preserved-as-links rather than followed,# but ``_assert_no_symlinks`` above should already have made# that path unreachable.- dest = self._plugins_dir / plugin_id+ # Re-derived inline rather than trusting the earlier+ # `_validate_plugin_id` call. That validation is real and runs, but+ # taint analysis does not follow a value through a function+ # boundary reliably, so a reader — human or CodeQL — cannot see+ # from here that this component is safe. Adding the OCI HTTP route+ # in v9.0 made this path reachable from a request body for the+ # first time, which turned an invisible property into one worth+ # making visible at the point of use.+ safe_component = os.path.basename(plugin_id)+ if not _PLUGIN_ID_RE.fullmatch(safe_component) or safe_component != plugin_id:+ raise PluginError(plugin_id, "plugin id is not a safe single path component")++ dest = self._plugins_dir / safe_componentif dest.exists():shutil.rmtree(dest)_safe_copytree(extracted, dest)diff --git a/services/api/migrations/056_marketplace_v3.sql b/services/api/migrations/056_marketplace_v3.sqlnew file mode 100644index 000000000..e5b59842f--- /dev/null+++ b/services/api/migrations/056_marketplace_v3.sql@@ -0,0 +1,133 @@+-- Marketplace v3: publisher identity, durable submissions, and paid listings.+--+-- Three things were missing, and the first one made the other two unsafe to+-- build on.+--+-- 1. There was no publisher identity. `_get_registered_pub_key` returned+-- `None` unconditionally, so `publish_plugin` skipped verification+-- entirely and stored `verified: False`. A submitted plugin was **never**+-- rejected for a bad signature — the signing path existed end to end and+-- could not fail. Commerce on top of that would be paying people we+-- cannot identify for code we cannot attribute.+--+-- 2. Community submissions and install records were module-global dicts,+-- documented as "replace with DB in production". They died with the+-- process and were invisible to a second replica.+--+-- 3. There was no notion of a paid listing anywhere: no price, no publisher,+-- no entitlement. `marketplace/index.json` carries `license` on 77 of+-- 7,155 items and it is `MIT` for every one of them.++-- ── Publisher identity ───────────────────────────────────────────────────────++CREATE TABLE IF NOT EXISTS marketplace_publishers (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ display_name TEXT NOT NULL,+ contact_email TEXT NOT NULL,+ -- Set by a platform admin after out-of-band checks. A self-asserted+ -- publisher is still a publisher; it is just not a verified one, and the+ -- distinction has to be visible rather than implied.+ verified BOOLEAN NOT NULL DEFAULT FALSE,+ verified_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, user_id)+);++CREATE TABLE IF NOT EXISTS marketplace_publisher_keys (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ publisher_id UUID NOT NULL REFERENCES marketplace_publishers(id) ON DELETE CASCADE,+ -- PEM-encoded Ed25519 public key. Stored as text rather than bytes so it+ -- is readable in a psql session during an incident.+ public_key_pem TEXT NOT NULL,+ -- SHA-256 of the DER form, for "which key signed this" without parsing.+ fingerprint TEXT NOT NULL,+ label TEXT NOT NULL DEFAULT '',+ -- Revocation is a timestamp, not a delete: a signature made before+ -- revocation stays explicable afterwards.+ revoked_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (fingerprint)+);++CREATE INDEX IF NOT EXISTS ix_publisher_keys_publisher+ ON marketplace_publisher_keys (publisher_id) WHERE revoked_at IS NULL;++-- ── Durable community submissions ────────────────────────────────────────────++CREATE TABLE IF NOT EXISTS marketplace_submissions (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ publisher_id UUID REFERENCES marketplace_publishers(id) ON DELETE SET NULL,+ kind TEXT NOT NULL CHECK (kind IN ('plugin', 'detection', 'playbook')),+ slug TEXT NOT NULL,+ name TEXT NOT NULL,+ description TEXT NOT NULL DEFAULT '',+ version TEXT NOT NULL DEFAULT '0.1.0',+ status TEXT NOT NULL DEFAULT 'pending'+ CHECK (status IN ('pending', 'approved', 'rejected')),+ -- Whether the signature actually verified against a registered key. This+ -- column is the whole point of the publisher tables: before them it was+ -- always false and could never be anything else.+ signature_verified BOOLEAN NOT NULL DEFAULT FALSE,+ signing_fingerprint TEXT,+ -- Commercial listing. NULL price means free, which is every listing+ -- today; a zero price would be a different and confusing claim.+ price_cents INTEGER CHECK (price_cents IS NULL OR price_cents >= 0),+ currency TEXT CHECK (currency IS NULL OR char_length(currency) = 3),+ license TEXT NOT NULL DEFAULT 'MIT',+ definition JSONB NOT NULL DEFAULT '{}'::jsonb,+ review_notes TEXT,+ install_count INTEGER NOT NULL DEFAULT 0,+ submitted_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, kind, slug)+);++CREATE INDEX IF NOT EXISTS ix_submissions_kind_status+ ON marketplace_submissions (kind, status);++-- ── Durable install records ──────────────────────────────────────────────────++CREATE TABLE IF NOT EXISTS marketplace_installs (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ item_id TEXT NOT NULL,+ item_type TEXT NOT NULL,+ version TEXT NOT NULL DEFAULT '',+ -- The digest the image resolved to at install time. Without it a `:latest`+ -- install is mutable after the fact and "what is running" has no answer.+ image_digest TEXT,+ installed_by UUID REFERENCES users(id) ON DELETE SET NULL,+ installed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, item_id)+);++CREATE INDEX IF NOT EXISTS ix_installs_tenant+ ON marketplace_installs (tenant_id);++-- ── Entitlements ─────────────────────────────────────────────────────────────+--+-- A row here says a tenant may run a paid listing. Nothing in this repository+-- creates one from a payment: there is no payment processor, and wiring one+-- is an account action rather than an engineering task. What exists is the+-- check — a paid listing without an entitlement does not load — so the+-- enforcement point is real and testable before any money moves through it.++CREATE TABLE IF NOT EXISTS marketplace_entitlements (+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,+ item_id TEXT NOT NULL,+ -- How this tenant came to be entitled. 'grant' is an operator action and+ -- is the only source that exists today; 'purchase' is reserved.+ source TEXT NOT NULL DEFAULT 'grant'+ CHECK (source IN ('grant', 'purchase', 'trial')),+ granted_by UUID REFERENCES users(id) ON DELETE SET NULL,+ expires_at TIMESTAMPTZ,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (tenant_id, item_id)+);++CREATE INDEX IF NOT EXISTS ix_entitlements_tenant+ ON marketplace_entitlements (tenant_id);diff --git a/services/api/tests/test_marketplace_supply_chain.py b/services/api/tests/test_marketplace_supply_chain.pynew file mode 100644index 000000000..4aebf2d1f--- /dev/null+++ b/services/api/tests/test_marketplace_supply_chain.py@@ -0,0 +1,196 @@+"""Plugins run in-process. What gets installed has to be what was reviewed.++Three claims the documentation made that the code did not:++**"verify signed manifests"** — `_get_registered_pub_key` returned `None`+unconditionally, so `publish_plugin` skipped verification entirely and stored+`verified: False`. The rejection branch was unreachable: a plugin could not+be refused for a bad signature, ever.++**"against an allow-list"** — there was no allow-list. There was a deny list+of three cloud-metadata hostnames, which answers a much smaller question.++**"pin image digests at install time"** — nothing resolved a tag to a digest+or recorded one. `:latest` stayed mutable after install, so what a deployment+was running had no answer after the fact.++The signature gate does not close the digest hole, which is the subtle part:+it verifies whatever arrived, and cannot tell you that what arrived is what+was reviewed.+"""++from __future__ import annotations++import pytest+from app.services.marketplace_publishers import (+ PublisherKeyError,+ RegisteredKey,+ parse_public_key,+ verify_against,+)+from app.services.plugin_manager import PluginError, _registry_of, _require_pinned, _validate_oci_ref+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey+from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key++PINNED = "ghcr.io/example/plugin@sha256:" + "a" * 64+TAGGED = "ghcr.io/example/plugin:latest"+++def _keypair() -> tuple[Ed25519PrivateKey, str]:+ private = Ed25519PrivateKey.generate()+ pem = (+ private.public_key()+ .public_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ .decode()+ )+ return private, pem+++def _registered(pem: str, fingerprint: str = "fp") -> RegisteredKey:+ import uuid++ return RegisteredKey(+ id=uuid.uuid4(),+ publisher_id=uuid.uuid4(),+ public_key_pem=pem,+ fingerprint=fingerprint,+ label="",+ )+++class TestPublisherKeys:+ def test_an_ed25519_key_parses_and_fingerprints_stably(self):+ _, pem = _keypair()+ key, fingerprint = parse_public_key(pem)+ assert isinstance(key, Ed25519PublicKey)+ assert len(fingerprint) == 64+ assert parse_public_key(pem)[1] == fingerprint++ def test_two_keys_have_different_fingerprints(self):+ assert parse_public_key(_keypair()[1])[1] != parse_public_key(_keypair()[1])[1]++ def test_a_non_ed25519_key_is_refused_at_registration(self):+ """Rejecting here rather than at verification means a publisher finds+ out while registering, not when their first release is silently+ unverifiable."""+ rsa = generate_private_key(public_exponent=65537, key_size=2048)+ pem = (+ rsa.public_key()+ .public_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ .decode()+ )+ with pytest.raises(PublisherKeyError, match="Ed25519"):+ parse_public_key(pem)++ def test_garbage_is_refused(self):+ with pytest.raises(PublisherKeyError):+ parse_public_key("not a pem")+++class TestSignatureVerification:+ def test_a_good_signature_names_the_key_that_verified(self):+ private, pem = _keypair()+ payload = b"tarball-bytes"+ assert verify_against([_registered(pem, "fp-1")], payload, private.sign(payload)) == "fp-1"++ def test_a_signature_from_an_unregistered_key_verifies_against_nothing(self):+ # This is the branch that was unreachable. Before the publisher tables+ # existed, no key was ever found, so this case could not be detected.+ _, registered_pem = _keypair()+ other, _ = _keypair()+ payload = b"tarball-bytes"+ assert verify_against([_registered(registered_pem)], payload, other.sign(payload)) is None++ def test_a_tampered_payload_does_not_verify(self):+ private, pem = _keypair()+ signature = private.sign(b"original")+ assert verify_against([_registered(pem)], b"tampered", signature) is None++ def test_every_active_key_is_tried_so_a_rotation_does_not_break_publishing(self):+ """Forcing a publisher to re-sign everything during a rotation is how+ rotations get skipped."""+ old, old_pem = _keypair()+ _, new_pem = _keypair()+ payload = b"signed-with-the-old-key"++ result = verify_against(+ [_registered(new_pem, "fp-new"), _registered(old_pem, "fp-old")],+ payload,+ old.sign(payload),+ )+ assert result == "fp-old"++ def test_no_registered_keys_verifies_nothing(self):+ private, _ = _keypair()+ assert verify_against([], b"x", private.sign(b"x")) is None+++class TestDigestPinning:+ def test_a_pinned_reference_is_accepted(self):+ assert _require_pinned(PINNED) == PINNED++ def test_a_mutable_tag_is_refused(self):+ # :latest resolves to one image today and another tomorrow, so what a+ # deployment is running has no answer after the fact.+ with pytest.raises(PluginError, match="pinned to a digest"):+ _require_pinned(TAGGED)++ def test_a_bare_repo_with_no_tag_is_refused(self):+ with pytest.raises(PluginError):+ _require_pinned("ghcr.io/example/plugin")++ def test_the_opt_out_exists_because_requiring_it_would_break_upgrades(self, monkeypatch: pytest.MonkeyPatch):+ """A control an operator has to disable wholesale is worse than one+ they can adopt."""+ monkeypatch.setenv("AISOC_PLUGIN_ALLOW_UNPINNED", "1")+ assert _require_pinned(TAGGED) == TAGGED++ def test_a_short_or_malformed_digest_is_not_a_pin(self):+ with pytest.raises(PluginError):+ _require_pinned("ghcr.io/example/plugin@sha256:abc")+++class TestRegistryAllowlist:+ def test_any_registry_when_unset_so_upgrades_do_not_break(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("AISOC_PLUGIN_REGISTRY_ALLOWLIST", raising=False)+ assert _validate_oci_ref(PINNED) == PINNED++ def test_an_allowed_registry_passes(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_PLUGIN_REGISTRY_ALLOWLIST", "ghcr.io, registry.internal")+ assert _validate_oci_ref(PINNED) == PINNED++ def test_a_registry_not_on_the_list_is_refused(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("AISOC_PLUGIN_REGISTRY_ALLOWLIST", "registry.internal")+ with pytest.raises(PluginError, match="not in AISOC_PLUGIN_REGISTRY_ALLOWLIST"):+ _validate_oci_ref(PINNED)++ def test_an_implicit_docker_hub_reference_fails_a_list_rather_than_passing_it(self, monkeypatch: pytest.MonkeyPatch):+ """`library/thing:1.0` names no host. Treating that as "matches+ everything" is how an allow-list silently stops applying."""+ monkeypatch.setenv("AISOC_PLUGIN_REGISTRY_ALLOWLIST", "ghcr.io")+ with pytest.raises(PluginError):+ _validate_oci_ref("library/thing@sha256:" + "b" * 64)++ @pytest.mark.parametrize(+ ("ref", "expected"),+ [+ ("ghcr.io/x/y:1", "ghcr.io"),+ ("localhost:5000/x/y:1", "localhost:5000"),+ ("registry.internal/x@sha256:" + "c" * 64, "registry.internal"),+ ("library/thing:1", ""),+ ],+ )+ def test_registry_extraction(self, ref: str, expected: str):+ assert _registry_of(ref) == expected++ def test_the_metadata_deny_list_still_applies(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("AISOC_PLUGIN_REGISTRY_ALLOWLIST", raising=False)+ with pytest.raises(PluginError, match="deny list"):+ _validate_oci_ref("169.254.169.254/x@sha256:" + "d" * 64)diff --git a/services/api/tests/test_plugin_manager.py b/services/api/tests/test_plugin_manager.pyindex f7fff401c..1246308e0 100644--- a/services/api/tests/test_plugin_manager.py+++ b/services/api/tests/test_plugin_manager.py@@ -20,6 +20,12 @@ from app.services.plugin_manager import (PluginManifest,)+# v9.0 requires a digest-pinned OCI reference; a mutable tag means "what is+# this deployment running" has no answer after the fact, and the signature+# gate does not close that hole because it verifies whatever arrived. The+# pinning rule itself is tested in tests/test_marketplace_supply_chain.py.+PINNED_REF = "ghcr.io/owner/plugin@sha256:" + "a" * 64+# ── shared fixtures ───────────────────────────────────────────────────────────@@ -705,7 +711,7 @@ class TestValidateOciRef:@pytest.mark.parametrize("good",[- "ghcr.io/owner/plugin:v1",+ PINNED_REF,"registry.example.com:5000/team/plugin:1.2.3","ghcr.io/owner/plugin@sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890","r/p",@@ -971,6 +977,12 @@ def _stub_oras_pull(monkeypatch, fake):monkeypatch.setattr(pm.subprocess, "run", fake)+# The OCI references in this class are digest-pinned. v9.0 made that a+# requirement — a mutable tag means "what is this deployment running" has no+# answer after the fact, and the signature gate does not close that hole+# because it verifies whatever arrived. These tests exercise the ingest+# pipeline rather than the pinning rule, which has its own tests in+# tests/test_marketplace_supply_chain.py.class TestInstallFromOciHardening:"""Defensive behaviours added in Batch 6 (H-3)."""@@ -997,7 +1009,7 @@ class TestInstallFromOciHardening:mgr = PluginManager(plugins_dir=tmp_path / "plugins")with pytest.raises(PluginError, match="invalid plugin id"):- await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="../escape")+ await mgr.install_from_oci(PINNED_REF, plugin_id_hint="../escape")assert fake.calls == [] # type: ignore[attr-defined]@pytest.mark.asyncio@@ -1022,7 +1034,7 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)with pytest.raises(PluginError, match="oras pull failed"):- await mgr.install_from_oci("ghcr.io/owner/plugin:v1")+ await mgr.install_from_oci(PINNED_REF)assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []@@ -1048,7 +1060,7 @@ class TestInstallFromOciHardening:_stub_oras_pull(monkeypatch, fake)mgr = PluginManager(plugins_dir=tmp_path / "plugins")- await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="test.argv-shape")+ await mgr.install_from_oci(PINNED_REF, plugin_id_hint="test.argv-shape")assert len(fake.calls) == 1 # type: ignore[attr-defined]argv = fake.calls[0] # type: ignore[attr-defined]@@ -1060,7 +1072,7 @@ class TestInstallFromOciHardening:# --output / <path> come before --, so they are parsed as a flag pair.assert out_idx < sep_idx# The ref must be the sole positional, immediately after --.- assert argv[sep_idx + 1] == "ghcr.io/owner/plugin:v1"+ assert argv[sep_idx + 1] == PINNED_REFassert sep_idx + 2 == len(argv), "ref must be the only positional"@pytest.mark.asyncio@@ -1082,7 +1094,7 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)with pytest.raises(PluginError, match="symlink"):- await mgr.install_from_oci("ghcr.io/owner/plugin:v1")+ await mgr.install_from_oci(PINNED_REF)assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []@@ -1099,7 +1111,7 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)with pytest.raises(PluginError, match="does not match plugin_id_hint"):- await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="test.wrong-id")+ await mgr.install_from_oci(PINNED_REF, plugin_id_hint="test.wrong-id")# Mismatch fails AFTER pull but BEFORE copy.assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []@@ -1131,7 +1143,7 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)with pytest.raises(PluginError, match="invalid plugin id"):- await mgr.install_from_oci("ghcr.io/owner/plugin:v1")+ await mgr.install_from_oci(PINNED_REF)assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []@@ -1153,7 +1165,7 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)with pytest.raises(PluginError):- await mgr.install_from_oci("ghcr.io/owner/plugin:v1")+ await mgr.install_from_oci(PINNED_REF)# The signature gate fires inside the ``with tempfile.TemporaryDirectory``# block, before ``_safe_copytree`` is reached. PLUGINS_DIR must be@@ -1175,7 +1187,7 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)- loaded_id = await mgr.install_from_oci("ghcr.io/owner/plugin:v1")+ loaded_id = await mgr.install_from_oci(PINNED_REF)assert loaded_id == "test.happy"assert (plugins_dir / "test.happy" / "plugin.py").exists()@@ -1202,7 +1214,7 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)- loaded_id = await mgr.install_from_oci("ghcr.io/owner/plugin:v1", plugin_id_hint="test.real-plugin")+ loaded_id = await mgr.install_from_oci(PINNED_REF, plugin_id_hint="test.real-plugin")assert loaded_id == "test.real-plugin"assert (plugins_dir / "test.real-plugin" / "plugin.py").exists()@@ -1225,6 +1237,6 @@ class TestInstallFromOciHardening:plugins_dir = tmp_path / "plugins"mgr = PluginManager(plugins_dir=plugins_dir)with pytest.raises(PluginError, match="multiple plugin directories"):- await mgr.install_from_oci("ghcr.io/owner/plugin:v1")+ await mgr.install_from_oci(PINNED_REF)assert not plugins_dir.exists() or list(plugins_dir.iterdir()) == []