Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

feat(api): a real TAXII 2.1 server over the tenant IOC store (depth 4.2)

Beenu Arora873f82afd297
diff --git a/services/api/app/api/v1/endpoints/stix_taxii.py b/services/api/app/api/v1/endpoints/stix_taxii.py
index cc1ba5c41..8587d5ae0 100644
--- a/services/api/app/api/v1/endpoints/stix_taxii.py
+++ b/services/api/app/api/v1/endpoints/stix_taxii.py
@@ -477,7 +477,19 @@ async def create_bundle(
@router.get("/taxii/collections", response_model=TAXIICollectionListResponse)
async def list_taxii_collections(user: AuthUser) -> TAXIICollectionListResponse:
- """List TAXII 2.1 collections for server compatibility."""
+ """Demo-only sample of TAXII collection metadata.
+
+ This is **not** the TAXII server. It returns a fixed sample list and is
+ gated behind demo mode, and it predates the real implementation added
+ for depth item 4.2, which lives at ``/api/v1/taxii2/`` and serves
+ discovery, API root, collections, objects, manifest and ``added_after``
+ pagination over this tenant's own indicator store.
+
+ Kept rather than deleted because removing a published operation is a
+ breaking change to the committed OpenAPI document; said plainly here
+ because two surfaces both called "TAXII collections" is how a reader
+ concludes the product has two TAXII implementations.
+ """
_demo_only()
return TAXIICollectionListResponse(
items=DEMO_TAXII_COLLECTIONS,
diff --git a/services/api/app/api/v1/endpoints/taxii.py b/services/api/app/api/v1/endpoints/taxii.py
new file mode 100644
index 000000000..13494529a
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/taxii.py
@@ -0,0 +1,595 @@
+"""A TAXII 2.1 server over the tenant IOC store.
+
+Depth plan 4.2 / parity 6.10.
+
+Two surfaces live here:
+
+* ``/taxii2/...`` — the shape the specification fixes, which is what a
+ stock TAXII client walks: discovery, API root, collections, objects and
+ manifest. Paths, media type and query parameters are not ours to choose.
+* ``/taxii/collections`` — management, so a tenant can publish a subset
+ without an operator editing a table.
+
+Where the tenant comes from
+---------------------------
+From the authenticated principal, never from the URL. The API root is a
+fixed string for exactly that reason: the obvious design puts a tenant id
+there, where it is a path segment any caller can retype, and the whole
+point of a TAXII server is that it is pointed at by a third party.
+
+Writes
+------
+Refused. ``can_write`` is in every collection response because the
+specification has the field and clients read it to decide whether to offer
+an upload, and it is always false: an inbound TAXII write is an outside
+party inserting indicators that drive this tenant's detections. That is a
+reach-out capability, and those ship off.
+"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from datetime import UTC, datetime
+from typing import Annotated, Any
+
+from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
+from pydantic import BaseModel, Field
+from sqlalchemy import and_, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.api.v1.deps import AuthUser, require_permission
+from app.db.database import get_db
+from app.models.taxii import TaxiiCollection
+from app.models.threat_intel import ThreatIntelIOC
+from app.services.taxii import (
+ DEFAULT_PAGE_LIMIT,
+ MAX_PAGE_LIMIT,
+ STIX_MEDIA_TYPE,
+ TAXII_MEDIA_TYPE,
+ UNPUBLISHED_IOC_TYPES,
+ FilterError,
+ IndicatorRow,
+ clamp_limit,
+ manifest_entry,
+ next_cursor,
+ parse_cursor,
+ to_stix_indicator,
+ validate_filter,
+)
+
+logger = logging.getLogger(__name__)
+
+#: The single API root this server exposes. A fixed string, not a tenant
+#: id: a tenant in the path is a tenant the caller can retype, and this
+#: endpoint exists to be pointed at by a third party.
+API_ROOT = "feeds"
+
+router = APIRouter(prefix="/taxii2", tags=["taxii"])
+admin_router = APIRouter(prefix="/taxii", tags=["taxii"])
+
+
+def _taxii_response(payload: dict[str, Any], status_code: int = status.HTTP_200_OK) -> Response:
+ """Answer with the one media type TAXII 2.1 defines.
+
+ FastAPI's default ``application/json`` is a conformance failure that
+ some clients refuse outright, and a ``response_model`` cannot set it,
+ so every route here builds its own response.
+ """
+ import json # noqa: PLC0415 — local to keep the module's import graph flat
+
+ return Response(
+ content=json.dumps(payload, separators=(",", ":")),
+ media_type=TAXII_MEDIA_TYPE,
+ status_code=status_code,
+ )
+
+
+def _not_found(message: str) -> HTTPException:
+ """The specification's error object, not FastAPI's ``detail`` shape."""
+ return HTTPException(
+ status_code=status.HTTP_404_NOT_FOUND,
+ detail={"title": "Not found", "description": message, "http_status": "404"},
+ )
+
+
+# ---------------------------------------------------------------------------
+# Discovery and API root
+# ---------------------------------------------------------------------------
+
+
[email protected]("/", dependencies=[Depends(require_permission("threat_intel:read"))])
+async def discovery(request: Request) -> Response:
+ """``GET /taxii2/`` — what this server is and where its API roots are."""
+ base = str(request.url).split("/taxii2/")[0]
+ return _taxii_response(
+ {
+ "title": "AiSOC threat intelligence",
+ "description": "TAXII 2.1 collections over this tenant's indicator store.",
+ "default": f"{base}/taxii2/{API_ROOT}/",
+ "api_roots": [f"{base}/taxii2/{API_ROOT}/"],
+ }
+ )
+
+
[email protected]("/{api_root}/", dependencies=[Depends(require_permission("threat_intel:read"))])
+async def api_root_information(api_root: str) -> Response:
+ """``GET /taxii2/{api-root}/`` — the limits a client must respect."""
+ if api_root != API_ROOT:
+ raise _not_found(f"no API root named {api_root!r}; this server serves {API_ROOT!r}")
+ return _taxii_response(
+ {
+ "title": "AiSOC indicators",
+ "description": "Indicators this tenant has chosen to publish.",
+ "versions": ["application/taxii+json;version=2.1"],
+ # Advertised rather than silently enforced: a client that asks
+ # for more than this gets fewer objects back and, without the
+ # advertised ceiling, no way to tell that from the end of the
+ # collection.
+ "max_content_length": 104_857_600,
+ }
+ )
+
+
+# ---------------------------------------------------------------------------
+# Collections
+# ---------------------------------------------------------------------------
+
+
+def _collection_json(collection: TaxiiCollection) -> dict[str, Any]:
+ return {
+ "id": str(collection.id),
+ "title": collection.title,
+ "description": collection.description or "",
+ "can_read": bool(collection.can_read),
+ # Always false. See the module docstring.
+ "can_write": False,
+ "media_types": [STIX_MEDIA_TYPE],
+ **({"alias": collection.alias} if collection.alias else {}),
+ }
+
+
+async def _load_collection(db: AsyncSession, tenant_id: uuid.UUID, collection_ref: str) -> TaxiiCollection:
+ """Resolve a collection by id or alias, scoped to the caller's tenant.
+
+ The tenant predicate is in the query rather than left to row-level
+ security alone: RLS is defence in depth here, and a collection id is
+ the one value a third party is expected to hold.
+ """
+ conditions = [TaxiiCollection.alias == collection_ref]
+ try:
+ conditions.append(TaxiiCollection.id == uuid.UUID(collection_ref))
+ except ValueError:
+ # Not a UUID, so it can only be an alias. Not an error yet — the
+ # lookup below decides.
+ pass
+
+ result = await db.execute(
+ select(TaxiiCollection).where(
+ and_(
+ TaxiiCollection.tenant_id == tenant_id,
+ TaxiiCollection.is_enabled.is_(True),
+ or_(*conditions),
+ )
+ )
+ )
+ collection = result.scalar_one_or_none()
+ if collection is None:
+ raise _not_found(f"no collection {collection_ref!r}")
+ return collection
+
+
+ "/{api_root}/collections/",
+ dependencies=[Depends(require_permission("threat_intel:read"))],
+)
+async def list_collections(
+ api_root: str,
+ current_user: AuthUser,
+ db: Annotated[AsyncSession, Depends(get_db)],
+) -> Response:
+ """``GET /taxii2/{api-root}/collections/``."""
+ if api_root != API_ROOT:
+ raise _not_found(f"no API root named {api_root!r}")
+ result = await db.execute(
+ select(TaxiiCollection)
+ .where(
+ TaxiiCollection.tenant_id == current_user.tenant_id,
+ TaxiiCollection.is_enabled.is_(True),
+ )
+ .order_by(TaxiiCollection.created_at)
+ )
+ return _taxii_response({"collections": [_collection_json(c) for c in result.scalars().all()]})
+
+
+ "/{api_root}/collections/{collection_ref}/",
+ dependencies=[Depends(require_permission("threat_intel:read"))],
+)
+async def get_collection(
+ api_root: str,
+ collection_ref: str,
+ current_user: AuthUser,
+ db: Annotated[AsyncSession, Depends(get_db)],
+) -> Response:
+ """``GET /taxii2/{api-root}/collections/{id}/``."""
+ if api_root != API_ROOT:
+ raise _not_found(f"no API root named {api_root!r}")
+ collection = await _load_collection(db, current_user.tenant_id, collection_ref)
+ return _taxii_response(_collection_json(collection))
+
+
+# ---------------------------------------------------------------------------
+# Objects and manifest
+# ---------------------------------------------------------------------------
+
+
+def _apply_filter(stmt: Any, ioc_filter: dict[str, Any]) -> Any:
+ """Narrow the IOC query by the collection's declared filter.
+
+ Only keys ``validate_filter`` accepts reach here, so an unknown key
+ cannot arrive and be ignored.
+ """
+ if types := ioc_filter.get("ioc_type"):
+ stmt = stmt.where(ThreatIntelIOC.ioc_type.in_(types))
+ if tlps := ioc_filter.get("tlp"):
+ stmt = stmt.where(ThreatIntelIOC.tlp.in_(tlps))
+ if severities := ioc_filter.get("severity"):
+ stmt = stmt.where(ThreatIntelIOC.severity.in_(severities))
+ if sources := ioc_filter.get("source"):
+ stmt = stmt.where(ThreatIntelIOC.source.in_(sources))
+ if (floor := ioc_filter.get("min_confidence")) is not None:
+ stmt = stmt.where(ThreatIntelIOC.confidence >= floor)
+ if tags := ioc_filter.get("tags"):
+ # Any-match. `overlap` is the array operator; a scalar `in_` here
+ # would compare the whole array to one tag and match nothing.
+ stmt = stmt.where(ThreatIntelIOC.tags.overlap(tags))
+ return stmt
+
+
+async def _page(
+ db: AsyncSession,
+ tenant_id: uuid.UUID,
+ collection: TaxiiCollection,
+ added_after: str | None,
+ next_token: str | None,
+ limit: int,
+ match_id: str | None,
+ match_type: str | None,
+) -> tuple[list[IndicatorRow], bool]:
+ """One page of indicators, plus whether more follow.
+
+ The sort key is ``(updated_at, id)`` and the cursor compares both.
+ A bare ``updated_at >`` would skip every row sharing a timestamp with
+ the last one on the previous page, and indicators written by one feed
+ poll routinely share theirs to the microsecond.
+ """
+ stmt = select(ThreatIntelIOC).where(
+ ThreatIntelIOC.tenant_id == tenant_id,
+ ThreatIntelIOC.is_active.is_(True),
+ ThreatIntelIOC.false_positive.is_(False),
+ )
+ stmt = _apply_filter(stmt, collection.ioc_filter or {})
+
+ # Types with no STIX pattern are excluded in the query rather than
+ # dropped after the fact, so `more` and the page size describe the
+ # same set the client receives.
+ stmt = stmt.where(ThreatIntelIOC.ioc_type.in_(_publishable_types()))
+
+ if match_type is not None:
+ # TAXII `match[type]` filters on the STIX object type. This
+ # collection publishes indicators and nothing else, so anything
+ # other than "indicator" selects nothing — which is the honest
+ # answer rather than ignoring the filter.
+ if "indicator" not in {part.strip() for part in match_type.split(",")}:
+ return [], False
+
+ if match_id is not None:
+ wanted = {part.strip() for part in match_id.split(",")}
+ # A STIX id is derived from the row id, so the filter is applied
+ # after projection rather than translated into SQL. Bounded by the
+ # page limit either way.
+ stmt = stmt.order_by(ThreatIntelIOC.updated_at, ThreatIntelIOC.id)
+ rows = (await db.execute(stmt.limit(MAX_PAGE_LIMIT))).scalars().all()
+ selected = [_row(r) for r in rows]
+ from app.services.taxii import stix_id_for # noqa: PLC0415 — avoids a cycle at import time
+
+ selected = [r for r in selected if stix_id_for(r.id) in wanted]
+ return selected[:limit], len(selected) > limit
+
+ if next_token:
+ try:
+ stamp, row_id = parse_cursor(next_token)
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "title": "Bad next value",
+ "description": str(exc),
+ "http_status": "400",
+ },
+ ) from exc
+ stmt = stmt.where(
+ or_(
+ ThreatIntelIOC.updated_at > stamp,
+ and_(ThreatIntelIOC.updated_at == stamp, ThreatIntelIOC.id > row_id),
+ )
+ )
+ elif added_after:
+ try:
+ boundary = _parse_timestamp(added_after)
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail={
+ "title": "Bad added_after",
+ "description": "added_after must be an RFC 3339 timestamp",
+ "http_status": "400",
+ },
+ ) from exc
+ stmt = stmt.where(ThreatIntelIOC.updated_at > boundary)
+
+ stmt = stmt.order_by(ThreatIntelIOC.updated_at, ThreatIntelIOC.id).limit(limit + 1)
+ rows = (await db.execute(stmt)).scalars().all()
+ more = len(rows) > limit
+ return [_row(r) for r in rows[:limit]], more
+
+
+def _publishable_types() -> list[str]:
+ from app.services.taxii import _STIX_PATTERNS # noqa: PLC0415
+
+ return sorted(_STIX_PATTERNS)
+
+
+def _parse_timestamp(raw: str) -> datetime:
+ value = datetime.fromisoformat(raw.replace("Z", "+00:00"))
+ return value if value.tzinfo else value.replace(tzinfo=UTC)
+
+
+def _row(ioc: ThreatIntelIOC) -> IndicatorRow:
+ return IndicatorRow(
+ id=ioc.id,
+ ioc_type=ioc.ioc_type,
+ value=ioc.value,
+ confidence=ioc.confidence,
+ severity=ioc.severity,
+ tlp=ioc.tlp,
+ threat_actor=ioc.threat_actor,
+ campaign=ioc.campaign,
+ malware_family=ioc.malware_family,
+ tags=list(ioc.tags or []),
+ source=ioc.source,
+ first_seen=ioc.first_seen,
+ last_seen=ioc.last_seen,
+ expires_at=ioc.expires_at,
+ updated_at=ioc.updated_at,
+ created_at=ioc.created_at,
+ )
+
+
+def _envelope_headers(rows: list[IndicatorRow]) -> dict[str, str]:
+ """The two headers a polling client bookmarks.
+
+ Omitted on an empty page rather than set to "now": a client that
+ records a boundary no row was ever written at skips anything that
+ lands in between.
+ """
+ if not rows:
+ return {}
+ stamps = [r.updated_at for r in rows]
+ from app.services.taxii import _rfc3339 # noqa: PLC0415
+
+ return {
+ "X-TAXII-Date-Added-First": _rfc3339(min(stamps)) or "",
+ "X-TAXII-Date-Added-Last": _rfc3339(max(stamps)) or "",
+ }
+
+
+ "/{api_root}/collections/{collection_ref}/objects/",
+ dependencies=[Depends(require_permission("threat_intel:read"))],
+)
+async def get_objects(
+ api_root: str,
+ collection_ref: str,
+ current_user: AuthUser,
+ db: Annotated[AsyncSession, Depends(get_db)],
+ added_after: Annotated[str | None, Query(alias="added_after")] = None,
+ limit: Annotated[int | None, Query(ge=1, le=MAX_PAGE_LIMIT)] = None,
+ next_token: Annotated[str | None, Query(alias="next")] = None,
+ match_id: Annotated[str | None, Query(alias="match[id]")] = None,
+ match_type: Annotated[str | None, Query(alias="match[type]")] = None,
+) -> Response:
+ """``GET /taxii2/{api-root}/collections/{id}/objects/``."""
+ if api_root != API_ROOT:
+ raise _not_found(f"no API root named {api_root!r}")
+ collection = await _load_collection(db, current_user.tenant_id, collection_ref)
+ if not collection.can_read:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail={
+ "title": "Forbidden",
+ "description": "this collection is not readable",
+ "http_status": "403",
+ },
+ )
+
+ page_limit = clamp_limit(limit)
+ rows, more = await _page(db, current_user.tenant_id, collection, added_after, next_token, page_limit, match_id, match_type)
+
+ objects = [obj for obj in (to_stix_indicator(r) for r in rows) if obj is not None]
+ envelope: dict[str, Any] = {"more": more, "objects": objects}
+ if more and rows:
+ envelope["next"] = next_cursor(rows[-1])
+
+ response = _taxii_response(envelope)
+ for header, value in _envelope_headers(rows).items():
+ response.headers[header] = value
+ return response
+
+
+ "/{api_root}/collections/{collection_ref}/manifest/",
+ dependencies=[Depends(require_permission("threat_intel:read"))],
+)
+async def get_manifest(
+ api_root: str,
+ collection_ref: str,
+ current_user: AuthUser,
+ db: Annotated[AsyncSession, Depends(get_db)],
+ added_after: Annotated[str | None, Query(alias="added_after")] = None,
+ limit: Annotated[int | None, Query(ge=1, le=MAX_PAGE_LIMIT)] = None,
+ next_token: Annotated[str | None, Query(alias="next")] = None,
+) -> Response:
+ """``GET /taxii2/{api-root}/collections/{id}/manifest/``.
+
+ The manifest is what a client polls to decide what to fetch, so it
+ pages by the same cursor as ``objects``. Two different orderings would
+ let a client hold a manifest entry it can never reach.
+ """
+ if api_root != API_ROOT:
+ raise _not_found(f"no API root named {api_root!r}")
+ collection = await _load_collection(db, current_user.tenant_id, collection_ref)
+ page_limit = clamp_limit(limit)
+ rows, more = await _page(db, current_user.tenant_id, collection, added_after, next_token, page_limit, None, None)
+
+ envelope: dict[str, Any] = {"more": more, "objects": [manifest_entry(r) for r in rows]}
+ if more and rows:
+ envelope["next"] = next_cursor(rows[-1])
+ response = _taxii_response(envelope)
+ for header, value in _envelope_headers(rows).items():
+ response.headers[header] = value
+ return response
+
+
+ "/{api_root}/collections/{collection_ref}/objects/",
+ dependencies=[Depends(require_permission("threat_intel:read"))],
+)
+async def refuse_write(api_root: str, collection_ref: str) -> Response:
+ """Inbound TAXII writes are refused, and say why.
+
+ A 405 would read as "wrong verb" and send the integrator looking for
+ the right one. This is a deliberate posture, so it is a 403 that names
+ it.
+ """
+ return _taxii_response(
+ {
+ "title": "Writes are not accepted",
+ "description": (
+ "This server publishes indicators and does not accept them. An inbound "
+ "TAXII write is an outside party inserting indicators that drive this "
+ "tenant's detections; add them through the threat-intel API instead."
+ ),
+ "http_status": "403",
+ },
+ status_code=status.HTTP_403_FORBIDDEN,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Management
+# ---------------------------------------------------------------------------
+
+
+class CollectionCreate(BaseModel):
+ title: str = Field(min_length=1, max_length=200)
+ description: str = ""
+ alias: str | None = Field(default=None, max_length=100)
+ ioc_filter: dict[str, Any] = Field(default_factory=dict)
+ is_enabled: bool = True
+
+
+class CollectionOut(BaseModel):
+ id: uuid.UUID
+ title: str
+ description: str
+ alias: str | None
+ can_read: bool
+ can_write: bool
+ ioc_filter: dict[str, Any]
+ is_enabled: bool
+ created_at: datetime
+
+
+@admin_router.get("/collections", response_model=list[CollectionOut])
+async def list_managed_collections(
+ current_user: AuthUser,
+ db: Annotated[AsyncSession, Depends(get_db)],
+ _: Annotated[None, Depends(require_permission("threat_intel:read"))] = None,
+) -> list[CollectionOut]:
+ result = await db.execute(
+ select(TaxiiCollection).where(TaxiiCollection.tenant_id == current_user.tenant_id).order_by(TaxiiCollection.created_at)
+ )
+ return [CollectionOut.model_validate(c, from_attributes=True) for c in result.scalars().all()]
+
+
+@admin_router.post("/collections", response_model=CollectionOut, status_code=status.HTTP_201_CREATED)
+async def create_managed_collection(
+ payload: CollectionCreate,
+ current_user: AuthUser,
+ db: Annotated[AsyncSession, Depends(get_db)],
+ _: Annotated[None, Depends(require_permission("threat_intel:write"))] = None,
+) -> CollectionOut:
+ try:
+ ioc_filter = validate_filter(payload.ioc_filter)
+ except FilterError as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+
+ collection = TaxiiCollection(
+ tenant_id=current_user.tenant_id,
+ title=payload.title,
+ description=payload.description,
+ alias=payload.alias,
+ ioc_filter=ioc_filter,
+ is_enabled=payload.is_enabled,
+ can_read=True,
+ can_write=False,
+ )
+ db.add(collection)
+ await db.commit()
+ await db.refresh(collection)
+ logger.info(
+ "taxii: collection created",
+ extra={"collection_id": str(collection.id), "tenant_id": str(current_user.tenant_id)},
+ )
+ return CollectionOut.model_validate(collection, from_attributes=True)
+
+
+@admin_router.delete("/collections/{collection_id}", status_code=status.HTTP_204_NO_CONTENT)
+async def delete_managed_collection(
+ collection_id: uuid.UUID,
+ current_user: AuthUser,
+ db: Annotated[AsyncSession, Depends(get_db)],
+ _: Annotated[None, Depends(require_permission("threat_intel:write"))] = None,
+) -> Response:
+ result = await db.execute(
+ select(TaxiiCollection).where(
+ TaxiiCollection.id == collection_id,
+ TaxiiCollection.tenant_id == current_user.tenant_id,
+ )
+ )
+ collection = result.scalar_one_or_none()
+ if collection is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="collection not found")
+ await db.delete(collection)
+ await db.commit()
+ return Response(status_code=status.HTTP_204_NO_CONTENT)
+
+
+@admin_router.get("/unpublished-types")
+async def unpublished_types(
+ _: Annotated[None, Depends(require_permission("threat_intel:read"))] = None,
+) -> dict[str, Any]:
+ """Which IOC types this server will not publish, and why.
+
+ An absence a tenant cannot explain reads as a bug. Published as data
+ rather than documented in prose so the answer cannot drift from the
+ table the projection actually uses.
+ """
+ return {
+ "published": _publishable_types(),
+ "unpublished": UNPUBLISHED_IOC_TYPES,
+ "default_page_limit": DEFAULT_PAGE_LIMIT,
+ "max_page_limit": MAX_PAGE_LIMIT,
+ }
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 5cadb3d76..885fa8569 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -92,6 +92,7 @@ from app.api.v1.endpoints import (
tenant_provision,
tenant_skills,
tenants,
+ taxii,
threat_intel,
translation,
usage,
@@ -312,6 +313,8 @@ api_router.include_router(evaluations.router)
api_router.include_router(knowledge_base.router)
# Wave 4 — advanced capabilities
+api_router.include_router(taxii.router)
+api_router.include_router(taxii.admin_router)
api_router.include_router(threat_intel.router)
api_router.include_router(posture.router)
api_router.include_router(easm.router)
diff --git a/services/api/app/models/taxii.py b/services/api/app/models/taxii.py
new file mode 100644
index 000000000..9b6b432f8
--- /dev/null
+++ b/services/api/app/models/taxii.py
@@ -0,0 +1,41 @@
+"""TAXII 2.1 collection ORM model (depth plan 4.2).
+
+A collection is a filtered view over ``threat_intel_iocs``, never a copy of
+it: an indicator edited in the console must not have to be edited twice,
+and the version a partner pulls must not drift from the version this
+tenant's own detections run on.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text
+from sqlalchemy.dialects.postgresql import JSONB, UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+
+class TaxiiCollection(Base):
+ __tablename__ = "taxii_collections"
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False)
+ alias: Mapped[str | None] = mapped_column(String(100), nullable=True)
+ title: Mapped[str] = mapped_column(Text, nullable=False)
+ description: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ can_read: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
+ #: Always false. The server refuses inbound writes; the column exists
+ #: because the specification has it and clients read it to decide
+ #: whether to offer an upload.
+ can_write: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
+ ioc_filter: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict)
+ is_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=lambda: datetime.now(UTC))
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True),
+ default=lambda: datetime.now(UTC),
+ onupdate=lambda: datetime.now(UTC),
+ )
diff --git a/services/api/app/services/taxii.py b/services/api/app/services/taxii.py
new file mode 100644
index 000000000..8be334642
--- /dev/null
+++ b/services/api/app/services/taxii.py
@@ -0,0 +1,303 @@
+"""TAXII 2.1 collections over the tenant IOC store.
+
+Depth plan 4.2 / parity 6.10.
+
+This module holds the two things that are easy to get subtly wrong and
+expensive to discover later: the STIX 2.1 projection of an indicator, and
+the ``added_after`` pagination contract. The HTTP surface in
+``app.api.v1.endpoints.taxii`` is deliberately thin over it.
+
+What a TAXII client actually needs
+----------------------------------
+A client bookmarks a collection id, polls it, and remembers the ``X-TAXII-Date-Added-Last``
+of what it saw. On the next poll it sends that back as ``added_after``. If the
+server's ordering is not total and stable, the client silently loses
+indicators: two rows with the same timestamp either both come back forever or
+one is skipped, depending on which side of the boundary the cursor lands. So
+the sort key here is ``(updated_at, id)`` and the ``added_after`` predicate is
+a row-value comparison, not a bare ``>`` on the timestamp.
+
+Why the server does not store STIX
+----------------------------------
+A collection is a filtered view over ``threat_intel_iocs``, never a copy. An
+indicator edited in the console would otherwise have to be edited twice, and
+the version a partner pulls would drift from the version this tenant's own
+detections run on.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import uuid
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+#: The one media type TAXII 2.1 defines. A client sends it in Accept and a
+#: server must answer with it; a plain ``application/json`` response is a
+#: conformance failure and some clients refuse it outright.
+TAXII_MEDIA_TYPE = "application/taxii+json;version=2.1"
+
+#: The STIX 2.1 bundle media type collections advertise.
+STIX_MEDIA_TYPE = "application/stix+json;version=2.1"
+
+#: Namespace for deterministic STIX identifiers. A STIX id must be stable
+#: across polls — a client deduplicates on it — so it is derived from the
+#: IOC's own primary key rather than generated per response.
+#: Fixed constant, not random: regenerating it would change every published
+#: id and make every client re-ingest the whole collection.
+_STIX_NAMESPACE = uuid.UUID("00abedb4-aa42-466c-9c01-fed23315a9b7")
+
+#: Default and maximum page sizes. The maximum is a server-side cap on what
+#: a client may ask for, because ``?limit=1000000`` on a large store is a
+#: way to make the API service run out of memory from the outside.
+DEFAULT_PAGE_LIMIT = 100
+MAX_PAGE_LIMIT = 1000
+
+#: Which IOC types this server is willing to publish, mapped onto the STIX
+#: pattern each one becomes. A type with no mapping is not published at
+#: all rather than published as a malformed pattern: a client that cannot
+#: parse a pattern usually rejects the whole bundle, so one bad indicator
+#: would cost the tenant every other one in the page.
+_STIX_PATTERNS: dict[str, str] = {
+ "ip": "[ipv4-addr:value = '{value}']",
+ "cidr": "[ipv4-addr:value = '{value}']",
+ "domain": "[domain-name:value = '{value}']",
+ "url": "[url:value = '{value}']",
+ "email": "[email-addr:value = '{value}']",
+ "file_hash_md5": "[file:hashes.'MD5' = '{value}']",
+ "file_hash_sha1": "[file:hashes.'SHA-1' = '{value}']",
+ "file_hash_sha256": "[file:hashes.'SHA-256' = '{value}']",
+ "asn": "[autonomous-system:number = '{value}']",
+}
+
+#: IOC types deliberately not published, each with the reason. Recorded
+#: rather than left as an absence, so "why is my CVE not in the feed" has
+#: an answer in the code.
+UNPUBLISHED_IOC_TYPES: dict[str, str] = {
+ "cve": (
+ "a CVE is a vulnerability identifier, not an observable; STIX models it as a "
+ "vulnerability object a TAXII indicator collection is the wrong carrier for"
+ ),
+}
+
+#: Filter keys a collection may declare. An unknown key is refused at write
+#: time: a filter that does not apply publishes more than the tenant asked
+#: to publish, and it does so silently.
+ALLOWED_FILTER_KEYS = frozenset({"ioc_type", "tlp", "min_confidence", "tags", "source", "severity"})
+
+#: TLP marking-definition ids are fixed by the STIX specification. They are
+#: quoted rather than derived, because a marking a partner's tooling does
+#: not recognise is a sharing control that silently does nothing.
+_TLP_MARKINGS = {
+ "white": "marking-definition--613f2e26-407d-48c7-9eca-b8e91df99dc9",
+ "green": "marking-definition--34098fce-860f-48ae-8e50-ebd3cc5e41da",
+ "amber": "marking-definition--f88d31f6-486f-44da-b317-01333bde0b82",
+ "red": "marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed",
+}
+
+#: Severity is not a STIX field. It is published as a confidence number and
+#: as a label, because dropping it would lose the only ranking a consumer
+#: has, and inventing a STIX extension for it would be a dialect only this
+#: product speaks.
+_SEVERITY_LABELS = {
+ "critical": "malicious-activity",
+ "high": "malicious-activity",
+ "medium": "suspicious-activity",
+ "low": "anomalous-activity",
+ "info": "benign",
+}
+
+
+class FilterError(ValueError):
+ """A collection filter the server will not accept."""
+
+
+def validate_filter(raw: Any) -> dict[str, Any]:
+ """Check a collection's ``ioc_filter`` before it is stored.
+
+ Refuses rather than normalises. A filter key this server does not
+ understand would be ignored at read time, and an ignored restriction
+ publishes more than the tenant asked to publish.
+ """
+ if raw is None:
+ return {}
+ if not isinstance(raw, dict):
+ raise FilterError("ioc_filter must be an object")
+ unknown = sorted(set(raw) - ALLOWED_FILTER_KEYS)
+ if unknown:
+ raise FilterError(
+ f"unknown filter keys {unknown}; this server understands "
+ f"{sorted(ALLOWED_FILTER_KEYS)}. An ignored restriction would publish "
+ "more than you asked to publish"
+ )
+ cleaned: dict[str, Any] = {}
+ for key, value in raw.items():
+ if key == "min_confidence":
+ if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= 100:
+ raise FilterError("min_confidence must be an integer between 0 and 100")
+ cleaned[key] = value
+ continue
+ if isinstance(value, str):
+ value = [value]
+ if not isinstance(value, list) or not value:
+ raise FilterError(f"{key} must be a non-empty list of strings")
+ if not all(isinstance(item, str) and item.strip() for item in value):
+ raise FilterError(f"{key} must contain only non-empty strings")
+ cleaned[key] = [item.strip() for item in value]
+ return cleaned
+
+
+def stix_id_for(ioc_id: uuid.UUID) -> str:
+ """A stable STIX indicator id for one IOC row.
+
+ Derived from the row's primary key so it does not move between polls.
+ A client deduplicates on this id; a fresh uuid4 per response would make
+ every poll look like a store full of new indicators.
+ """
+ derived = uuid.uuid5(_STIX_NAMESPACE, str(ioc_id))
+ return f"indicator--{derived}"
+
+
+def pattern_for(ioc_type: str, value: str) -> str | None:
+ """The STIX pattern for an IOC, or None when this type is not published."""
+ template = _STIX_PATTERNS.get(ioc_type)
+ if template is None:
+ return None
+ # STIX patterns are single-quoted strings. A value containing a quote
+ # would end the literal and produce a pattern the consumer's parser
+ # rejects — taking the whole bundle with it — so the quote is escaped
+ # the way the grammar defines rather than stripped.
+ escaped = value.replace("\\", "\\\\").replace("'", "\\'")
+ return template.format(value=escaped)
+
+
+@dataclass(frozen=True)
+class IndicatorRow:
+ """The IOC fields the projection needs, decoupled from the ORM.
+
+ A dataclass rather than the model so the projection can be driven in a
+ test with no database, and so a column rename shows up here as a type
+ error instead of as a silently absent STIX field.
+ """
+
+ id: uuid.UUID
+ ioc_type: str
+ value: str
+ confidence: int
+ severity: str
+ tlp: str
+ threat_actor: str | None
+ campaign: str | None
+ malware_family: str | None
+ tags: list[str] | None
+ source: str
+ first_seen: datetime
+ last_seen: datetime
+ expires_at: datetime | None
+ updated_at: datetime
+ created_at: datetime
+
+
+def _rfc3339(value: datetime | None) -> str | None:
+ if value is None:
+ return None
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=UTC)
+ # STIX timestamps are RFC 3339 with millisecond precision and a literal
+ # Z. `isoformat()` emits `+00:00`, which several consumers reject.
+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def to_stix_indicator(row: IndicatorRow) -> dict[str, Any] | None:
+ """Project one IOC as a STIX 2.1 indicator, or None if unpublishable."""
+ pattern = pattern_for(row.ioc_type, row.value)
+ if pattern is None:
+ return None
+
+ obj: dict[str, Any] = {
+ "type": "indicator",
+ "spec_version": "2.1",
+ "id": stix_id_for(row.id),
+ "created": _rfc3339(row.created_at),
+ "modified": _rfc3339(row.updated_at),
+ "valid_from": _rfc3339(row.first_seen),
+ "pattern": pattern,
+ "pattern_type": "stix",
+ "indicator_types": [_SEVERITY_LABELS.get(row.severity, "unknown")],
+ "confidence": max(0, min(100, int(row.confidence))),
+ }
+ name_parts = [part for part in (row.threat_actor, row.malware_family, row.campaign) if part]
+ obj["name"] = " / ".join(name_parts) if name_parts else f"{row.ioc_type} {row.value}"
+ if row.expires_at is not None:
+ obj["valid_until"] = _rfc3339(row.expires_at)
+ labels = list(row.tags or [])
+ if row.source:
+ labels.append(f"source:{row.source}")
+ labels.append(f"severity:{row.severity}")
+ obj["labels"] = labels
+ marking = _TLP_MARKINGS.get(row.tlp)
+ if marking:
+ obj["object_marking_refs"] = [marking]
+ return obj
+
+
+def manifest_entry(row: IndicatorRow) -> dict[str, Any]:
+ """One entry in a collection's manifest.
+
+ ``version`` is the STIX modified timestamp and ``date_added`` is when
+ this server would have published it. They are the same value here
+ because a collection is a view: there is no separate publication event
+ to record, and inventing one would be a timestamp that means nothing.
+ """
+ return {
+ "id": stix_id_for(row.id),
+ "date_added": _rfc3339(row.updated_at),
+ "version": _rfc3339(row.updated_at),
+ "media_type": STIX_MEDIA_TYPE,
+ }
+
+
+def next_cursor(row: IndicatorRow) -> str:
+ """An opaque pagination cursor for the last row of a page.
+
+ Encodes ``(updated_at, id)``, which is the total order the query sorts
+ by. A cursor on the timestamp alone would skip or repeat rows that
+ share one, and indicators written by the same feed poll routinely do.
+
+ Opaque by construction rather than by convention: a client that parsed
+ it would couple itself to a sort key the server must be free to change.
+ """
+ raw = f"{row.updated_at.astimezone(UTC).isoformat()}|{row.id}"
+ digest = hashlib.sha256(raw.encode()).hexdigest()[:8]
+ return f"{raw}|{digest}"
+
+
+def parse_cursor(cursor: str) -> tuple[datetime, uuid.UUID]:
+ """Decode a cursor this server issued.
+
+ Raises ``ValueError`` on anything else. The digest is not a security
+ control — the cursor carries no privilege — it is there so a truncated
+ or hand-edited cursor fails loudly instead of silently paging from a
+ different point in the collection.
+ """
+ parts = cursor.split("|")
+ if len(parts) != 3:
+ raise ValueError("not a cursor this server issued")
+ stamp, row_id, digest = parts
+ expected = hashlib.sha256(f"{stamp}|{row_id}".encode()).hexdigest()[:8]
+ if digest != expected:
+ raise ValueError("cursor is corrupt or was not issued by this server")
+ return datetime.fromisoformat(stamp), uuid.UUID(row_id)
+
+
+def clamp_limit(requested: int | None) -> int:
+ """Bound a client's page size.
+
+ An unbounded limit is a way to exhaust this service's memory from the
+ outside, and TAXII explicitly allows a server to return fewer objects
+ than asked for.
+ """
+ if requested is None or requested <= 0:
+ return DEFAULT_PAGE_LIMIT
+ return min(requested, MAX_PAGE_LIMIT)
diff --git a/services/api/migrations/110_taxii_collections.sql b/services/api/migrations/110_taxii_collections.sql
new file mode 100644
index 000000000..da35f7427
--- /dev/null
+++ b/services/api/migrations/110_taxii_collections.sql
@@ -0,0 +1,91 @@
+-- Depth plan 4.2 / parity 6.10 — a real TAXII 2.1 server backed by the
+-- tenant IOC store.
+--
+-- Why a table rather than a derived collection
+-- --------------------------------------------
+-- TAXII clients bookmark a collection by its id and poll it with
+-- `added_after`, so the id has to be stable across restarts and across a
+-- change in what the collection contains. Deriving one collection per
+-- tenant from `threat_intel_iocs` would give a stable id but no way for a
+-- tenant to publish a subset, which is the normal reason to run TAXII at
+-- all: a partner gets the indicators you are willing to share, not your
+-- whole store.
+--
+-- So a collection is a tenant-owned row with a filter over the IOC store.
+-- The objects themselves are never duplicated here — the collection is a
+-- view, and an IOC edited in one place does not have to be edited in two.
+--
+-- `can_write` exists because the specification has the column and a client
+-- reads it to decide whether to offer an upload. It is false on every row
+-- this migration can create and the server refuses writes outright: an
+-- inbound TAXII write is an unauthenticated party inserting indicators
+-- that drive this tenant's detections, and that is a reach-out capability
+-- that ships off.
+
+CREATE TABLE IF NOT EXISTS taxii_collections (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
+ -- The TAXII `alias`, which is what appears in a URL when a client uses
+ -- one. Unique per tenant so a bookmarked alias cannot start resolving
+ -- to a different collection.
+ alias TEXT,
+ title TEXT NOT NULL,
+ description TEXT NOT NULL DEFAULT '',
+ can_read BOOLEAN NOT NULL DEFAULT true,
+ can_write BOOLEAN NOT NULL DEFAULT false,
+ -- Which IOCs this collection publishes. Keys are the ones the server
+ -- knows how to translate into a predicate: ioc_type (list), tlp
+ -- (list), min_confidence (int), tags (list, any-match), source (list).
+ -- An unknown key is refused at write time rather than silently
+ -- ignored, because a filter that does not apply publishes more than
+ -- the tenant asked to publish.
+ ioc_filter JSONB NOT NULL DEFAULT '{}',
+ is_enabled BOOLEAN NOT NULL DEFAULT true,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (tenant_id, alias)
+);
+
+CREATE INDEX IF NOT EXISTS taxii_collections_tenant_idx
+ ON taxii_collections (tenant_id)
+ WHERE is_enabled;
+
+COMMENT ON TABLE taxii_collections IS
+ 'TAXII 2.1 collections. A collection is a filtered view over threat_intel_iocs, never a '
+ 'copy: an indicator edited in one place must not have to be edited in two.';
+
+COMMENT ON COLUMN taxii_collections.can_write IS
+ 'Always false today. The server refuses inbound writes: an authenticated partner inserting '
+ 'indicators that drive this tenant''s detections is a reach-out capability, and those ship off.';
+
+-- `added_after` is the whole of TAXII pagination, and it reads against the
+-- IOC store rather than this table. The IOC table already indexes
+-- (tenant_id) and (tenant_id, ioc_type, value); neither orders by the
+-- column a TAXII client pages on, so a collection poll would sort the
+-- tenant's whole store on every request.
+CREATE INDEX IF NOT EXISTS idx_ioc_taxii_paging
+ ON threat_intel_iocs (tenant_id, updated_at, id)
+ WHERE is_active AND NOT false_positive;
+
+-- Written out per table rather than looped, so the policy stays visible to
+-- grep and to scripts/check_tenant_query_predicates.py.
+DO $$
+BEGIN
+ EXECUTE 'ALTER TABLE taxii_collections ENABLE ROW LEVEL SECURITY';
+ EXECUTE 'ALTER TABLE taxii_collections FORCE ROW LEVEL SECURITY';
+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON taxii_collections';
+ EXECUTE
+ 'CREATE POLICY tenant_isolation ON taxii_collections '
+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '
+ 'WITH CHECK (tenant_id = current_tenant_id())';
+
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN
+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON taxii_collections TO aisoc_app';
+ END IF;
+END
+$$;
+
+DROP TRIGGER IF EXISTS trg_taxii_collection_ts ON taxii_collections;
+CREATE TRIGGER trg_taxii_collection_ts
+ BEFORE UPDATE ON taxii_collections
+ FOR EACH ROW EXECUTE FUNCTION update_ti_ts();
diff --git a/services/api/tests/test_taxii_projection.py b/services/api/tests/test_taxii_projection.py
new file mode 100644
index 000000000..2fc8dec79
--- /dev/null
+++ b/services/api/tests/test_taxii_projection.py
@@ -0,0 +1,298 @@
+"""The STIX 2.1 projection and the TAXII pagination contract (depth 4.2).
+
+These are pure-function tests over ``app.services.taxii`` with no database,
+because the projection *is* pure and the defects that matter here are
+arithmetic and string-grammar ones: an unstable id, a pattern a consumer's
+parser rejects, a cursor that skips rows sharing a timestamp.
+
+The surface that needs a database — tenant scoping, the ``added_after``
+boundary against real rows — is covered in
+``test_taxii_server_live.py`` against real Postgres, because a mocked
+session answers whatever the test asked it to and would hide exactly those.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+
+import pytest
+from app.services.taxii import (
+ ALLOWED_FILTER_KEYS,
+ DEFAULT_PAGE_LIMIT,
+ MAX_PAGE_LIMIT,
+ STIX_MEDIA_TYPE,
+ TAXII_MEDIA_TYPE,
+ UNPUBLISHED_IOC_TYPES,
+ FilterError,
+ IndicatorRow,
+ clamp_limit,
+ manifest_entry,
+ next_cursor,
+ parse_cursor,
+ pattern_for,
+ stix_id_for,
+ to_stix_indicator,
+ validate_filter,
+)
+
+NOW = datetime(2026, 10, 11, 9, 0, 0, tzinfo=UTC)
+
+
+def row(**overrides) -> IndicatorRow:
+ base = {
+ "id": uuid.UUID("11111111-1111-1111-1111-111111111111"),
+ "ioc_type": "domain",
+ "value": "evil.example.com",
+ "confidence": 80,
+ "severity": "high",
+ "tlp": "amber",
+ "threat_actor": None,
+ "campaign": None,
+ "malware_family": None,
+ "tags": None,
+ "source": "internal",
+ "first_seen": NOW - timedelta(days=2),
+ "last_seen": NOW,
+ "expires_at": None,
+ "updated_at": NOW,
+ "created_at": NOW - timedelta(days=2),
+ }
+ base.update(overrides)
+ return IndicatorRow(**base)
+
+
+# ---------------------------------------------------------------------------
+# Identifiers. A client deduplicates on the STIX id.
+# ---------------------------------------------------------------------------
+
+
+def test_the_stix_id_is_stable_across_calls():
+ ioc_id = uuid.uuid4()
+ assert stix_id_for(ioc_id) == stix_id_for(ioc_id)
+
+
+def test_the_stix_id_is_derived_from_the_ioc_not_generated():
+ # A fresh uuid4 per response would make every poll look like a store
+ # full of new indicators, and a client would re-ingest the lot.
+ first, second = uuid.uuid4(), uuid.uuid4()
+ assert stix_id_for(first) != stix_id_for(second)
+ assert stix_id_for(first).startswith("indicator--")
+
+
+# ---------------------------------------------------------------------------
+# Patterns. One malformed pattern usually costs the consumer the whole
+# bundle, so this is where a value with a quote in it matters.
+# ---------------------------------------------------------------------------
+
+
+ ("ioc_type", "value", "expected"),
+ [
+ ("ip", "198.51.100.4", "[ipv4-addr:value = '198.51.100.4']"),
+ ("domain", "evil.example.com", "[domain-name:value = 'evil.example.com']"),
+ ("url", "http://evil.example.com/a", "[url:value = 'http://evil.example.com/a']"),
+ ("file_hash_sha256", "ab" * 32, f"[file:hashes.'SHA-256' = '{'ab' * 32}']"),
+ ("email", "[email protected]", "[email-addr:value = '[email protected]']"),
+ ],
+)
+def test_patterns_match_the_stix_grammar(ioc_type, value, expected):
+ assert pattern_for(ioc_type, value) == expected
+
+
+def test_a_quote_in_a_value_is_escaped_rather_than_ending_the_literal():
+ pattern = pattern_for("domain", "ev'il.example.com")
+ assert pattern == "[domain-name:value = 'ev\\'il.example.com']"
+ # The closing bracket must still be the last character: an unescaped
+ # quote would have terminated the literal early and left a pattern the
+ # consumer's parser rejects, taking every other indicator in the page.
+ assert pattern.endswith("']")
+
+
+def test_a_backslash_is_escaped_before_the_quote_is():
+ # Escaping the quote first and the backslash second would turn
+ # `\` + `'` into `\\'`, which re-opens the literal.
+ assert pattern_for("domain", "a\\b") == "[domain-name:value = 'a\\\\b']"
+
+
+def test_an_unpublishable_type_is_skipped_rather_than_malformed():
+ assert pattern_for("cve", "CVE-2026-1") is None
+ assert to_stix_indicator(row(ioc_type="cve", value="CVE-2026-1")) is None
+
+
+def test_every_unpublished_type_carries_a_reason():
+ assert UNPUBLISHED_IOC_TYPES
+ for ioc_type, reason in UNPUBLISHED_IOC_TYPES.items():
+ assert reason.strip(), f"{ioc_type} is unpublished with no reason"
+ assert pattern_for(ioc_type, "x") is None
+
+
+# ---------------------------------------------------------------------------
+# The indicator object.
+# ---------------------------------------------------------------------------
+
+
+def test_an_indicator_carries_the_fields_a_consumer_reads():
+ obj = to_stix_indicator(
+ row(
+ threat_actor="FIN7",
+ malware_family="Carbanak",
+ tags=["phishing"],
+ expires_at=NOW + timedelta(days=30),
+ )
+ )
+ assert obj["type"] == "indicator"
+ assert obj["spec_version"] == "2.1"
+ assert obj["pattern_type"] == "stix"
+ assert obj["confidence"] == 80
+ assert obj["name"] == "FIN7 / Carbanak"
+ assert "phishing" in obj["labels"]
+ assert "severity:high" in obj["labels"]
+ assert obj["valid_until"].endswith("Z")
+
+
+def test_timestamps_are_rfc3339_with_a_literal_z():
+ obj = to_stix_indicator(row())
+ for field in ("created", "modified", "valid_from"):
+ assert obj[field].endswith("Z"), f"{field} is {obj[field]!r}"
+ assert "+00:00" not in obj[field], "several consumers reject the offset form"
+
+
+def test_a_naive_timestamp_is_treated_as_utc_rather_than_local():
+ naive = datetime(2026, 10, 11, 9, 0, 0)
+ obj = to_stix_indicator(row(updated_at=naive))
+ assert obj["modified"] == "2026-10-11T09:00:00.000Z"
+
+
+def test_the_tlp_marking_is_the_one_the_specification_fixes():
+ obj = to_stix_indicator(row(tlp="red"))
+ assert obj["object_marking_refs"] == ["marking-definition--5e57c739-391a-4eb3-b6be-7d15ca92d5ed"]
+
+
+def test_confidence_is_clamped_to_the_stix_range():
+ assert to_stix_indicator(row(confidence=250))["confidence"] == 100
+ assert to_stix_indicator(row(confidence=-5))["confidence"] == 0
+
+
+def test_an_indicator_with_no_attribution_still_gets_a_name():
+ # A STIX indicator without a name renders as a blank row in most
+ # consumers, which reads as a broken feed rather than an unattributed
+ # indicator.
+ assert to_stix_indicator(row())["name"] == "domain evil.example.com"
+
+
+# ---------------------------------------------------------------------------
+# Pagination. This is the part that silently loses a client's indicators.
+# ---------------------------------------------------------------------------
+
+
+def test_a_cursor_round_trips():
+ r = row()
+ stamp, row_id = parse_cursor(next_cursor(r))
+ assert row_id == r.id
+ assert stamp == r.updated_at
+
+
+def test_two_rows_sharing_a_timestamp_get_different_cursors():
+ # One feed poll writes many indicators with the same updated_at. A
+ # cursor on the timestamp alone would either repeat or skip all but
+ # one of them, depending on which side of the boundary it lands.
+ a = next_cursor(row(id=uuid.UUID("11111111-1111-1111-1111-111111111111")))
+ b = next_cursor(row(id=uuid.UUID("22222222-2222-2222-2222-222222222222")))
+ assert a != b
+
+
+ "bad",
+ [
+ "",
+ "not-a-cursor",
+ "2026-10-11T09:00:00+00:00|11111111-1111-1111-1111-111111111111",
+ "2026-10-11T09:00:00+00:00|11111111-1111-1111-1111-111111111111|deadbeef",
+ ],
+)
+def test_a_corrupt_cursor_fails_loudly_rather_than_paging_from_somewhere_else(bad):
+ with pytest.raises(ValueError):
+ parse_cursor(bad)
+
+
+def test_a_hand_edited_cursor_is_refused():
+ # Not a security control — the cursor carries no privilege — but a
+ # truncated one must not silently restart the collection.
+ original = next_cursor(row())
+ stamp, row_id, digest = original.split("|")
+ tampered = f"{stamp}|22222222-2222-2222-2222-222222222222|{digest}"
+ with pytest.raises(ValueError):
+ parse_cursor(tampered)
+
+
+def test_limits_are_bounded_server_side():
+ assert clamp_limit(None) == DEFAULT_PAGE_LIMIT
+ assert clamp_limit(0) == DEFAULT_PAGE_LIMIT
+ assert clamp_limit(-1) == DEFAULT_PAGE_LIMIT
+ assert clamp_limit(10) == 10
+ # An unbounded limit is a way to exhaust the service's memory from
+ # outside, and TAXII allows a server to return fewer than asked.
+ assert clamp_limit(10_000_000) == MAX_PAGE_LIMIT
+
+
+def test_the_manifest_entry_matches_the_object_it_describes():
+ r = row()
+ entry = manifest_entry(r)
+ assert entry["id"] == to_stix_indicator(r)["id"]
+ assert entry["version"] == to_stix_indicator(r)["modified"]
+ assert entry["media_type"] == STIX_MEDIA_TYPE
+
+
+# ---------------------------------------------------------------------------
+# Collection filters. An ignored restriction publishes more than the tenant
+# asked to publish, and does it silently.
+# ---------------------------------------------------------------------------
+
+
+def test_an_unknown_filter_key_is_refused_rather_than_ignored():
+ with pytest.raises(FilterError) as exc:
+ validate_filter({"ioc_typo": ["ip"]})
+ assert "ioc_typo" in str(exc.value)
+
+
+def test_every_allowed_key_is_accepted():
+ accepted = validate_filter(
+ {
+ "ioc_type": ["ip", "domain"],
+ "tlp": ["green"],
+ "severity": ["high"],
+ "source": ["internal"],
+ "tags": ["apt"],
+ "min_confidence": 70,
+ }
+ )
+ assert set(accepted) == ALLOWED_FILTER_KEYS
+
+
+def test_a_single_string_is_accepted_as_a_one_item_list():
+ assert validate_filter({"ioc_type": "ip"}) == {"ioc_type": ["ip"]}
+
+
+ "bad",
+ [
+ {"min_confidence": "high"},
+ {"min_confidence": 101},
+ {"min_confidence": -1},
+ {"min_confidence": True},
+ {"ioc_type": []},
+ {"ioc_type": [""]},
+ {"ioc_type": [1]},
+ ],
+)
+def test_malformed_filter_values_are_refused(bad):
+ with pytest.raises(FilterError):
+ validate_filter(bad)
+
+
+def test_the_media_type_is_the_one_taxii_fixes():
+ # A plain application/json response is a conformance failure some
+ # clients refuse outright.
+ assert TAXII_MEDIA_TYPE == "application/taxii+json;version=2.1"
+ assert STIX_MEDIA_TYPE == "application/stix+json;version=2.1"