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: self-service data lifecycle — retention + transform DSL + custom parsers (Wave 5) (#578)

Beenu Arora4050cc95bd79
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6f3006ace..8bcb457e5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Self-service data lifecycle (Wave 5).** (1) **Configurable retention**
+ (`/data-lifecycle/retention`): per-tenant windows (days) for `raw_events`
+ (lake) / `alerts` / `audit`, clamped to `[1, 3650]`, with a bounded
+ **tenant-scoped** ClickHouse purge and a parameterised Postgres purge (W5.1).
+ (2) A **field-extraction / transform DSL** (`pipeline_transforms`): a safe,
+ whitelisted, no-`eval` pipeline (`rename` / `copy` / `set` / `set_default` /
+ `drop` / `lowercase` / `uppercase` / `coalesce` / grok-style `extract` with
+ dotted paths + named captures) that reshapes events onto OCSF; the `extract`
+ op compiles a `%{TOKEN:name}` template from `re.escape`d literals + a fixed
+ linear-time token map, so it is ReDoS-proof by construction (no raw user
+ regex); validation rejects unknown ops/tokens and oversized pipelines;
+ runtime is fail-open per op and never mutates the input (W5.3). (3) **Runtime custom parsers**
+ (`/data-lifecycle/parsers` + `/parsers/test`): a parser is a named,
+ tenant-scoped, validated transform pipeline you can register and dry-run
+ against a sample event (W5.2). Gated by `test_retention.py` +
+ `test_pipeline_transforms.py`.
- **Customizable dashboard / report builder (Wave 7).** A declarative report is
a list of widgets (whitelisted `type` × data `source`), validated for unknown
types/sources, duplicate ids, and bounded size, then rendered by resolving
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 60f5321d7..40d364880 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -65,9 +65,12 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Security findings/detections map to compliance controls with auto-evidence | README (compliance) | `ci.yml` api job (`test_compliance_cspm.py` — MITRE→control mapping, per-control evidence records for detections + CSPM findings, unknown controls skipped) | GATED | - |
| Alerts fan out to Opsgenie / email / external-SOAR destinations (SSRF-guarded) | README (destinations + SOAR) | `ci.yml` api job (`test_compliance_cspm.py` — Opsgenie priority mapping, email subject/recipients, `aisoc.handoff.v1` SOAR envelope; outbound webhook guard blocks non-http(s) schemes + private/loopback targets) | GATED | - |
+| Per-tenant configurable data retention with tenant-scoped purge | README (data lifecycle) | `ci.yml` api job (`test_retention.py` — defaults + tenant override merge, clamps to [1, 3650] days, mandatory tenant predicate in the ClickHouse purge, parameterised Postgres cutoff never string-interpolated) | GATED | - |
+| Self-service field-extraction / transform pipelines (custom parsers) | README (data lifecycle) | `ci.yml` api job (`test_pipeline_transforms.py` — the whitelisted DSL renames/maps/extracts onto OCSF with dotted paths + ReDoS-proof grok `extract` (re.escape'd literals + fixed token map, no raw user regex); validation rejects unknown ops/tokens / oversized pipelines; fail-open per op never drops an event; input never mutated) | GATED | - |
+
## Summary
-- GATED: 44
+- GATED: 46
- PARTIAL: 9
- NO GATE: 0 (**every claim is now backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The full Fully-Operational roadmap (Phases A1–E1) is complete. The 7 remaining PARTIAL rows are honest, named deferrals to future phases outside the A–E scope — each states the specific gap and the phase that closes it — not unproven claims.)
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 6a05200cb..21671f895 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -9266,6 +9266,147 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/data-lifecycle/retention:
+ get:
+ tags:
+ - data_lifecycle
+ summary: Get Retention
+ operationId: get_retention_api_v1_data_lifecycle_retention_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RetentionOut'
+ security:
+ - HTTPBearer: []
+ put:
+ tags:
+ - data_lifecycle
+ summary: Put Retention
+ operationId: put_retention_api_v1_data_lifecycle_retention_put
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RetentionUpdate'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RetentionOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/data-lifecycle/parsers:
+ get:
+ tags:
+ - data_lifecycle
+ summary: List Parsers
+ operationId: list_parsers_api_v1_data_lifecycle_parsers_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ items:
+ $ref: '#/components/schemas/ParserOut'
+ type: array
+ title: Response List Parsers Api V1 Data Lifecycle Parsers Get
+ security:
+ - HTTPBearer: []
+ post:
+ tags:
+ - data_lifecycle
+ summary: Create Parser
+ operationId: create_parser_api_v1_data_lifecycle_parsers_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ParserIn'
+ required: true
+ responses:
+ '201':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ParserOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/data-lifecycle/parsers/test:
+ post:
+ tags:
+ - data_lifecycle
+ summary: Test Parser
+ description: 'Dry-run a parser pipeline against a sample event — validate +
+ preview
+
+ the reshaped event without persisting anything (W5.2/W5.3).'
+ operationId: test_parser_api_v1_data_lifecycle_parsers_test_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ParserTestIn'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ParserTestOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/data-lifecycle/parsers/{parser_id}:
+ delete:
+ tags:
+ - data_lifecycle
+ summary: Delete Parser
+ operationId: delete_parser_api_v1_data_lifecycle_parsers__parser_id__delete
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: parser_id
+ in: path
+ required: true
+ schema:
+ type: string
+ format: uuid
+ title: Parser Id
+ responses:
+ '204':
+ description: Successful Response
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/feedback/alert-override:
post:
tags:
@@ -21995,6 +22136,93 @@ components:
- parameter_overrides
- created_at
title: PackAssignmentOut
+ ParserIn:
+ properties:
+ name:
+ type: string
+ maxLength: 200
+ minLength: 1
+ title: Name
+ source:
+ type: string
+ title: Source
+ default: generic
+ transforms:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Transforms
+ enabled:
+ type: boolean
+ title: Enabled
+ default: true
+ type: object
+ required:
+ - name
+ title: ParserIn
+ ParserOut:
+ properties:
+ id:
+ type: string
+ format: uuid
+ title: Id
+ name:
+ type: string
+ title: Name
+ source:
+ type: string
+ title: Source
+ transforms:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Transforms
+ enabled:
+ type: boolean
+ title: Enabled
+ type: object
+ required:
+ - id
+ - name
+ - source
+ - transforms
+ - enabled
+ title: ParserOut
+ ParserTestIn:
+ properties:
+ transforms:
+ items:
+ additionalProperties: true
+ type: object
+ type: array
+ title: Transforms
+ sample_event:
+ additionalProperties: true
+ type: object
+ title: Sample Event
+ type: object
+ required:
+ - transforms
+ - sample_event
+ title: ParserTestIn
+ ParserTestOut:
+ properties:
+ event:
+ additionalProperties: true
+ type: object
+ title: Event
+ warnings:
+ items:
+ type: string
+ type: array
+ title: Warnings
+ type: object
+ required:
+ - event
+ - warnings
+ title: ParserTestOut
PasskeyCredentialOut:
properties:
id:
@@ -23151,6 +23379,48 @@ components:
required:
- name
title: ReportDefinitionBody
+ RetentionOut:
+ properties:
+ raw_events_days:
+ type: integer
+ title: Raw Events Days
+ alerts_days:
+ type: integer
+ title: Alerts Days
+ audit_days:
+ type: integer
+ title: Audit Days
+ type: object
+ required:
+ - raw_events_days
+ - alerts_days
+ - audit_days
+ title: RetentionOut
+ RetentionUpdate:
+ properties:
+ raw_events_days:
+ anyOf:
+ - type: integer
+ maximum: 3650.0
+ minimum: 1.0
+ - type: 'null'
+ title: Raw Events Days
+ alerts_days:
+ anyOf:
+ - type: integer
+ maximum: 3650.0
+ minimum: 1.0
+ - type: 'null'
+ title: Alerts Days
+ audit_days:
+ anyOf:
+ - type: integer
+ maximum: 3650.0
+ minimum: 1.0
+ - type: 'null'
+ title: Audit Days
+ type: object
+ title: RetentionUpdate
ReviewAction:
properties:
action:
diff --git a/services/api/app/api/v1/endpoints/data_lifecycle.py b/services/api/app/api/v1/endpoints/data_lifecycle.py
new file mode 100644
index 000000000..c13e27117
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/data_lifecycle.py
@@ -0,0 +1,164 @@
+"""Self-service data lifecycle: retention policies + custom parsers (Wave 5)."""
+
+from __future__ import annotations
+
+import uuid
+from typing import Annotated, Any
+
+from fastapi import APIRouter, Depends, HTTPException, status
+from pydantic import BaseModel, Field
+from sqlalchemy import select
+
+from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.models.data_lifecycle import CustomParserRow, RetentionPolicyRow
+from app.services.pipeline_transforms import TransformError, apply_transforms, validate_transforms
+from app.services.retention import resolve_policy
+
+router = APIRouter(prefix="/data-lifecycle", tags=["data_lifecycle"])
+
+
+# ── Retention (W5.1) ───────────────────────────────────────────────────────
+
+
+class RetentionOut(BaseModel):
+ raw_events_days: int
+ alerts_days: int
+ audit_days: int
+
+
+class RetentionUpdate(BaseModel):
+ raw_events_days: int | None = Field(None, ge=1, le=3650)
+ alerts_days: int | None = Field(None, ge=1, le=3650)
+ audit_days: int | None = Field(None, ge=1, le=3650)
+
+
[email protected]("/retention", response_model=RetentionOut)
+async def get_retention(
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
+ db: DBSession,
+) -> RetentionOut:
+ row = (await db.execute(select(RetentionPolicyRow).where(RetentionPolicyRow.tenant_id == current_user.tenant_id))).scalar_one_or_none()
+ cfg = {} if row is None else {"raw_events_days": row.raw_events_days, "alerts_days": row.alerts_days, "audit_days": row.audit_days}
+ return RetentionOut(**resolve_policy(cfg).as_dict())
+
+
[email protected]("/retention", response_model=RetentionOut)
+async def put_retention(
+ body: RetentionUpdate,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+ db: DBSession,
+) -> RetentionOut:
+ row = (await db.execute(select(RetentionPolicyRow).where(RetentionPolicyRow.tenant_id == current_user.tenant_id))).scalar_one_or_none()
+ if row is None:
+ row = RetentionPolicyRow(tenant_id=current_user.tenant_id)
+ db.add(row)
+ merged = resolve_policy(
+ {
+ "raw_events_days": body.raw_events_days if body.raw_events_days is not None else row.raw_events_days,
+ "alerts_days": body.alerts_days if body.alerts_days is not None else row.alerts_days,
+ "audit_days": body.audit_days if body.audit_days is not None else row.audit_days,
+ }
+ )
+ row.raw_events_days = merged.raw_events_days
+ row.alerts_days = merged.alerts_days
+ row.audit_days = merged.audit_days
+ row.updated_by = current_user.user_id
+ await db.commit()
+ return RetentionOut(**merged.as_dict())
+
+
+# ── Custom parsers (W5.2, built on the W5.3 DSL) ───────────────────────────
+
+
+class ParserIn(BaseModel):
+ name: str = Field(..., min_length=1, max_length=200)
+ source: str = "generic"
+ transforms: list[dict[str, Any]] = Field(default_factory=list)
+ enabled: bool = True
+
+
+class ParserOut(BaseModel):
+ id: uuid.UUID
+ name: str
+ source: str
+ transforms: list[dict[str, Any]]
+ enabled: bool
+
+
+class ParserTestIn(BaseModel):
+ transforms: list[dict[str, Any]]
+ sample_event: dict[str, Any]
+
+
+class ParserTestOut(BaseModel):
+ event: dict[str, Any]
+ warnings: list[str]
+
+
+def _to_out(row: CustomParserRow) -> ParserOut:
+ return ParserOut(id=row.id, name=row.name, source=row.source, transforms=list(row.transforms or []), enabled=row.enabled)
+
+
[email protected]("/parsers", response_model=list[ParserOut])
+async def list_parsers(
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
+ db: DBSession,
+) -> list[ParserOut]:
+ rows = (await db.execute(select(CustomParserRow).where(CustomParserRow.tenant_id == current_user.tenant_id))).scalars().all()
+ return [_to_out(r) for r in rows]
+
+
[email protected]("/parsers", response_model=ParserOut, status_code=status.HTTP_201_CREATED)
+async def create_parser(
+ body: ParserIn,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+ db: DBSession,
+) -> ParserOut:
+ try:
+ validate_transforms(body.transforms)
+ except TransformError as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+ row = CustomParserRow(
+ tenant_id=current_user.tenant_id,
+ name=body.name,
+ source=body.source,
+ transforms=body.transforms,
+ enabled=body.enabled,
+ created_by=current_user.user_id,
+ )
+ db.add(row)
+ await db.commit()
+ await db.refresh(row)
+ return _to_out(row)
+
+
[email protected]("/parsers/test", response_model=ParserTestOut)
+async def test_parser(
+ body: ParserTestIn,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
+) -> ParserTestOut:
+ """Dry-run a parser pipeline against a sample event — validate + preview
+ the reshaped event without persisting anything (W5.2/W5.3)."""
+ try:
+ validate_transforms(body.transforms)
+ except TransformError as exc:
+ raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)) from exc
+ result = apply_transforms(body.sample_event, body.transforms)
+ return ParserTestOut(event=result.event, warnings=result.warnings)
+
+
[email protected]("/parsers/{parser_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
+async def delete_parser(
+ parser_id: uuid.UUID,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+ db: DBSession,
+) -> None:
+ row = (
+ await db.execute(
+ select(CustomParserRow).where(CustomParserRow.id == parser_id, CustomParserRow.tenant_id == current_user.tenant_id)
+ )
+ ).scalar_one_or_none()
+ if row is None:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="parser not found")
+ await db.delete(row)
+ await db.commit()
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 54733b4c9..752d4946d 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -20,6 +20,7 @@ from app.api.v1.endpoints import (
compliance,
connectors,
costs,
+ data_lifecycle,
deployment,
detection_compat,
detection_loop,
@@ -170,6 +171,9 @@ api_router.include_router(mssp.router)
api_router.include_router(insider_threat.router)
api_router.include_router(remediation.router)
+# Wave 5 — self-service data lifecycle (retention + custom parsers)
+api_router.include_router(data_lifecycle.router)
+
# Analyst feedback loop
api_router.include_router(feedback.router)
diff --git a/services/api/app/models/data_lifecycle.py b/services/api/app/models/data_lifecycle.py
new file mode 100644
index 000000000..b678e83ef
--- /dev/null
+++ b/services/api/app/models/data_lifecycle.py
@@ -0,0 +1,42 @@
+"""ORM models for data-lifecycle config (Wave 5): retention + custom parsers."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime
+
+from sqlalchemy import Boolean, DateTime, Integer, String, UniqueConstraint
+from sqlalchemy.dialects.postgresql import JSONB, UUID
+from sqlalchemy.orm import Mapped, mapped_column
+
+from app.db.database import Base
+
+
+class RetentionPolicyRow(Base):
+ __tablename__ = "retention_policies"
+
+ tenant_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
+ raw_events_days: Mapped[int] = mapped_column(Integer, default=90)
+ alerts_days: Mapped[int] = mapped_column(Integer, default=365)
+ audit_days: Mapped[int] = mapped_column(Integer, default=730)
+ updated_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=True)
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), default=lambda: datetime.now(UTC), onupdate=lambda: datetime.now(UTC)
+ )
+
+
+class CustomParserRow(Base):
+ __tablename__ = "custom_parsers"
+ __table_args__ = (UniqueConstraint("tenant_id", "name", name="uq_custom_parsers_tenant_name"),)
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
+ tenant_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False, index=True)
+ name: Mapped[str] = mapped_column(String(200), nullable=False)
+ source: Mapped[str] = mapped_column(String(100), default="generic")
+ transforms: Mapped[list] = mapped_column(JSONB, default=list)
+ enabled: Mapped[bool] = mapped_column(Boolean, default=True)
+ created_by: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), nullable=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/pipeline_transforms.py b/services/api/app/services/pipeline_transforms.py
new file mode 100644
index 000000000..5008b41bf
--- /dev/null
+++ b/services/api/app/services/pipeline_transforms.py
@@ -0,0 +1,191 @@
+"""Self-service field-extraction / transform DSL (Wave 5, W5.3 + W5.2).
+
+A small, safe, declarative pipeline that reshapes an inbound event before it is
+normalised — so a tenant can map their own log schema onto OCSF, extract fields
+out of a message string, and clean values, WITHOUT shipping code. This is the
+engine behind the runtime custom parser (W5.2): a "parser" is just a named,
+tenant-scoped list of these ops.
+
+Deliberately NOT a general expression language — there is no ``eval``, no
+arbitrary code, a bounded op count, and a bounded regex length. Every op is a
+whitelisted verb over a flat/dotted-path event dict.
+
+Supported ops (each a dict with an ``op`` key)::
+
+ {"op": "rename", "from": "src.field", "to": "dst.field"}
+ {"op": "copy", "from": "src", "to": "dst"}
+ {"op": "set", "field": "f", "value": <any>}
+ {"op": "set_default", "field": "f", "value": <any>} # only if missing/None
+ {"op": "drop", "field": "f"}
+ {"op": "lowercase", "field": "f"}
+ {"op": "uppercase", "field": "f"}
+ {"op": "coalesce", "fields": ["a", "b"], "to": "dst"} # first non-None
+ {"op": "extract", "field": "msg", "template": "user=%{WORD:user} src=%{IP:src_ip}"}
+ # grok-style: %{TOKEN:name} named captures become top-level fields.
+ # Literal text is escaped and TOKENs come from a fixed, ReDoS-safe map
+ # (WORD/NUMBER/INT/IP/EMAIL/HOST/NOTSPACE/GREEDY) — never raw regex.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Any
+
+MAX_OPS = 64
+MAX_TEMPLATE_LEN = 512
+# Hard cap on the string an extract pattern is run against — a defence-in-depth
+# bound even though the compiled pattern is ReDoS-safe by construction.
+MAX_MATCH_INPUT = 2048
+_VALID_OPS = frozenset({"rename", "copy", "set", "set_default", "drop", "lowercase", "uppercase", "coalesce", "extract"})
+
+# Grok-style extraction. The user writes a TEMPLATE, not a raw regex — literal
+# text is `re.escape`d and `%{TOKEN:name}` placeholders expand to a FIXED,
+# vetted, linear-time token regex. No user data ever becomes regex
+# metacharacters, so the op is ReDoS-proof by construction (and not a
+# regex-injection sink).
+_GROK_TOKENS: dict[str, str] = {
+ "WORD": r"\w+",
+ "NUMBER": r"\d+",
+ "INT": r"-?\d+",
+ "IP": r"\d{1,3}(?:\.\d{1,3}){3}",
+ "EMAIL": r"[^\s@]+@[^\s@]+",
+ "HOST": r"[\w.-]+",
+ "NOTSPACE": r"\S+",
+ "GREEDY": r".+",
+}
+_GROK_PLACEHOLDER = re.compile(r"%\{(\w+)(?::(\w+))?\}")
+
+
+def compile_grok(template: str) -> str:
+ """Compile a grok template into a regex built only from `re.escape`d
+ literals + constant token patterns (never raw user regex)."""
+ parts: list[str] = []
+ last = 0
+ for m in _GROK_PLACEHOLDER.finditer(template):
+ parts.append(re.escape(template[last : m.start()]))
+ token, name = m.group(1), m.group(2)
+ base = _GROK_TOKENS.get(token.upper())
+ if base is None:
+ raise TransformError(f"unknown grok token %{{{token}}}; use one of {sorted(_GROK_TOKENS)}")
+ parts.append(f"(?P<{name}>{base})" if name else f"(?:{base})")
+ last = m.end()
+ parts.append(re.escape(template[last:]))
+ return "".join(parts)
+
+
+class TransformError(Exception):
+ """A transform pipeline is structurally invalid (rejected at validation)."""
+
+
+@dataclass
+class TransformResult:
+ event: dict[str, Any]
+ warnings: list[str] = field(default_factory=list)
+
+
+def _get(obj: dict[str, Any], path: str) -> Any:
+ cur: Any = obj
+ for part in path.split("."):
+ if not isinstance(cur, dict) or part not in cur:
+ return None
+ cur = cur[part]
+ return cur
+
+
+def _set(obj: dict[str, Any], path: str, value: Any) -> None:
+ parts = path.split(".")
+ cur = obj
+ for part in parts[:-1]:
+ nxt = cur.get(part)
+ if not isinstance(nxt, dict):
+ nxt = {}
+ cur[part] = nxt
+ cur = nxt
+ cur[parts[-1]] = value
+
+
+def _drop(obj: dict[str, Any], path: str) -> None:
+ parts = path.split(".")
+ cur = obj
+ for part in parts[:-1]:
+ cur = cur.get(part)
+ if not isinstance(cur, dict):
+ return
+ cur.pop(parts[-1], None)
+
+
+def validate_transforms(ops: list[dict[str, Any]]) -> None:
+ """Reject a structurally-invalid pipeline up front (used by the API when a
+ tenant registers a parser)."""
+ if not isinstance(ops, list):
+ raise TransformError("transforms must be a list")
+ if len(ops) > MAX_OPS:
+ raise TransformError(f"too many ops ({len(ops)} > {MAX_OPS})")
+ for i, op in enumerate(ops):
+ if not isinstance(op, dict) or "op" not in op:
+ raise TransformError(f"op[{i}] must be a dict with an 'op' key")
+ name = op["op"]
+ if name not in _VALID_OPS:
+ raise TransformError(f"op[{i}] unknown op '{name}'")
+ if name == "extract":
+ template = str(op.get("template", ""))
+ if len(template) > MAX_TEMPLATE_LEN:
+ raise TransformError(f"op[{i}] template too long")
+ try:
+ re.compile(compile_grok(template))
+ except re.error as exc:
+ raise TransformError(f"op[{i}] invalid extract template: {exc}") from exc
+
+
+def apply_transforms(event: dict[str, Any], ops: list[dict[str, Any]]) -> TransformResult:
+ """Apply a validated pipeline to a COPY of ``event``. Never raises on a
+ single bad op at runtime — it records a warning and continues, so one
+ malformed field can't drop the whole event."""
+ result = TransformResult(event=dict(event))
+ ev = result.event
+ for i, op in enumerate(ops[:MAX_OPS]):
+ name = op.get("op")
+ try:
+ if name == "rename":
+ val = _get(ev, op["from"])
+ if val is not None:
+ _set(ev, op["to"], val)
+ _drop(ev, op["from"])
+ elif name == "copy":
+ val = _get(ev, op["from"])
+ if val is not None:
+ _set(ev, op["to"], val)
+ elif name == "set":
+ _set(ev, op["field"], op.get("value"))
+ elif name == "set_default":
+ if _get(ev, op["field"]) is None:
+ _set(ev, op["field"], op.get("value"))
+ elif name == "drop":
+ _drop(ev, op["field"])
+ elif name in ("lowercase", "uppercase"):
+ val = _get(ev, op["field"])
+ if isinstance(val, str):
+ _set(ev, op["field"], val.lower() if name == "lowercase" else val.upper())
+ elif name == "coalesce":
+ for src in op.get("fields", []):
+ val = _get(ev, src)
+ if val is not None:
+ _set(ev, op["to"], val)
+ break
+ elif name == "extract":
+ val = _get(ev, op["field"])
+ if isinstance(val, str):
+ # The pattern is compiled from a grok template: literal text
+ # is re.escape'd and tokens come from a fixed linear-time
+ # map, so it is ReDoS-safe by construction (no raw user
+ # regex). Input is also hard-capped as defence in depth.
+ pattern = compile_grok(str(op.get("template", "")))
+ match = re.search(pattern, val[:MAX_MATCH_INPUT])
+ if match:
+ for key, group in match.groupdict().items():
+ if group is not None:
+ _set(ev, key, group)
+ except Exception as exc: # noqa: BLE001 — a bad op warns, never drops the event
+ result.warnings.append(f"op[{i}] '{name}' failed: {type(exc).__name__}")
+ return result
diff --git a/services/api/app/services/retention.py b/services/api/app/services/retention.py
new file mode 100644
index 000000000..120b6eae1
--- /dev/null
+++ b/services/api/app/services/retention.py
@@ -0,0 +1,67 @@
+"""Configurable data-retention policies (Wave 5, W5.1).
+
+Per-tenant retention windows for each data class, plus the bounded, tenant-
+scoped purge SQL that enforces them. Pure functions — the scheduler/worker that
+runs the purge composes these; the API exposes get/set. Bounds keep a
+misconfiguration (0 days / 100 years) from nuking or never-purging data.
+"""
+
+from __future__ import annotations
+
+import uuid
+from dataclasses import asdict, dataclass
+
+MIN_DAYS = 1
+MAX_DAYS = 3650 # 10 years
+
+# Data classes we retain, with sane defaults (days).
+DEFAULT_RETENTION: dict[str, int] = {
+ "raw_events": 90, # ClickHouse lake
+ "alerts": 365, # Postgres alerts
+ "audit": 730, # audit/ledger — longer for compliance
+}
+
+
+@dataclass(frozen=True)
+class RetentionPolicy:
+ raw_events_days: int = DEFAULT_RETENTION["raw_events"]
+ alerts_days: int = DEFAULT_RETENTION["alerts"]
+ audit_days: int = DEFAULT_RETENTION["audit"]
+
+ def as_dict(self) -> dict[str, int]:
+ return asdict(self)
+
+
+def _clamp(value: int) -> int:
+ return max(MIN_DAYS, min(MAX_DAYS, int(value)))
+
+
+def resolve_policy(config: dict[str, int] | None) -> RetentionPolicy:
+ """Merge a tenant's stored config over defaults, clamped to safe bounds."""
+ cfg = dict(config or {})
+ return RetentionPolicy(
+ raw_events_days=_clamp(cfg.get("raw_events_days", DEFAULT_RETENTION["raw_events"])),
+ alerts_days=_clamp(cfg.get("alerts_days", DEFAULT_RETENTION["alerts"])),
+ audit_days=_clamp(cfg.get("audit_days", DEFAULT_RETENTION["audit"])),
+ )
+
+
+def build_lake_purge_sql(tenant_id: uuid.UUID, days: int) -> str:
+ """Tenant-scoped ClickHouse purge of lake events older than ``days``.
+
+ Uses a lightweight ``ALTER TABLE … DELETE`` (ClickHouse mutation). The
+ tenant predicate is mandatory so a purge can never cross tenants; the day
+ count is clamped and interpolated as an integer literal (never string)."""
+ days = _clamp(days)
+ tid = str(tenant_id)
+ # tenant_id is a UUID (validated by type); days is an int literal.
+ return "ALTER TABLE aisoc.raw_events DELETE " f"WHERE tenant_id = '{tid}' AND event_time < now() - INTERVAL {days} DAY"
+
+
+def build_alert_purge_sql(days: int) -> tuple[str, dict[str, int]]:
+ """Postgres purge of alerts older than ``days`` (RLS scopes the tenant).
+
+ Returns parameterised SQL + params — never string-interpolate the cutoff."""
+ days = _clamp(days)
+ sql = "DELETE FROM alerts WHERE created_at < now() - make_interval(days => :days)"
+ return sql, {"days": days}
diff --git a/services/api/migrations/049_data_lifecycle.sql b/services/api/migrations/049_data_lifecycle.sql
new file mode 100644
index 000000000..d5041b607
--- /dev/null
+++ b/services/api/migrations/049_data_lifecycle.sql
@@ -0,0 +1,42 @@
+-- Wave 5 — data lifecycle + self-service pipelines.
+--
+-- retention_policies: per-tenant retention windows (days) per data class (W5.1).
+-- custom_parsers: per-tenant named transform pipelines — the runtime
+-- custom parser (W5.2), a validated list of transform ops
+-- (W5.3 DSL) applied to reshape events onto OCSF.
+
+CREATE TABLE IF NOT EXISTS retention_policies (
+ tenant_id UUID PRIMARY KEY,
+ raw_events_days INTEGER NOT NULL DEFAULT 90,
+ alerts_days INTEGER NOT NULL DEFAULT 365,
+ audit_days INTEGER NOT NULL DEFAULT 730,
+ updated_by UUID,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+ALTER TABLE retention_policies ENABLE ROW LEVEL SECURITY;
+ALTER TABLE retention_policies FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS retention_policies_tenant ON retention_policies;
+CREATE POLICY retention_policies_tenant ON retention_policies
+ USING (tenant_id = current_setting('app.current_tenant', true)::uuid);
+
+CREATE TABLE IF NOT EXISTS custom_parsers (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ tenant_id UUID NOT NULL,
+ name TEXT NOT NULL,
+ source TEXT NOT NULL DEFAULT 'generic',
+ transforms JSONB NOT NULL DEFAULT '[]'::jsonb,
+ enabled BOOLEAN NOT NULL DEFAULT true,
+ created_by UUID,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (tenant_id, name)
+);
+
+CREATE INDEX IF NOT EXISTS idx_custom_parsers_tenant ON custom_parsers(tenant_id);
+
+ALTER TABLE custom_parsers ENABLE ROW LEVEL SECURITY;
+ALTER TABLE custom_parsers FORCE ROW LEVEL SECURITY;
+DROP POLICY IF EXISTS custom_parsers_tenant ON custom_parsers;
+CREATE POLICY custom_parsers_tenant ON custom_parsers
+ USING (tenant_id = current_setting('app.current_tenant', true)::uuid);
diff --git a/services/api/tests/test_pipeline_transforms.py b/services/api/tests/test_pipeline_transforms.py
new file mode 100644
index 000000000..0be3b6f77
--- /dev/null
+++ b/services/api/tests/test_pipeline_transforms.py
@@ -0,0 +1,108 @@
+"""Wave 5 (W5.3/W5.2) - the field-extraction / transform DSL."""
+
+from __future__ import annotations
+
+import pytest
+from app.services.pipeline_transforms import (
+ TransformError,
+ apply_transforms,
+ validate_transforms,
+)
+
+
+def test_rename_moves_and_removes_source():
+ out = apply_transforms({"src": "v"}, [{"op": "rename", "from": "src", "to": "dst"}])
+ assert out.event == {"dst": "v"}
+
+
+def test_dotted_paths_nest():
+ out = apply_transforms(
+ {"user": "alice"},
+ [{"op": "rename", "from": "user", "to": "actor.name"}],
+ )
+ assert out.event["actor"]["name"] == "alice"
+
+
+def test_set_default_only_when_missing():
+ out = apply_transforms(
+ {"sev": "high"},
+ [
+ {"op": "set_default", "field": "sev", "value": "low"},
+ {"op": "set_default", "field": "conf", "value": 50},
+ ],
+ )
+ assert out.event["sev"] == "high"
+ assert out.event["conf"] == 50
+
+
+def test_lowercase_and_coalesce():
+ out = apply_transforms(
+ {"a": None, "b": "HELLO"},
+ [
+ {"op": "coalesce", "fields": ["a", "b"], "to": "greeting"},
+ {"op": "lowercase", "field": "greeting"},
+ ],
+ )
+ assert out.event["greeting"] == "hello"
+
+
+def test_extract_named_groups():
+ out = apply_transforms(
+ {"msg": "user=bob action=login src=10.0.0.1"},
+ [{"op": "extract", "field": "msg", "template": "user=%{WORD:user} action=%{WORD:action} src=%{IP:src_ip}"}],
+ )
+ assert out.event["user"] == "bob"
+ assert out.event["src_ip"] == "10.0.0.1"
+
+
+def test_bad_op_warns_but_does_not_drop_event():
+ # 'from' present but no 'to' → the op raises, is caught as a warning, and
+ # the rest of the event survives (fail-open per op, never drop the event).
+ out = apply_transforms({"keep": "me", "src": "v"}, [{"op": "rename", "from": "src"}])
+ assert out.event["keep"] == "me"
+ assert out.warnings
+
+
+def test_validate_rejects_unknown_op():
+ with pytest.raises(TransformError):
+ validate_transforms([{"op": "rm -rf"}])
+
+
+def test_validate_rejects_unknown_grok_token():
+ with pytest.raises(TransformError):
+ validate_transforms([{"op": "extract", "field": "m", "template": "x=%{NOPE:v}"}])
+
+
+def test_validate_rejects_too_many_ops():
+ with pytest.raises(TransformError):
+ validate_transforms([{"op": "drop", "field": "x"}] * 200)
+
+
+def test_extract_literals_are_escaped_not_regex():
+ # Regex metacharacters in the template's literal text are matched literally,
+ # never interpreted — so no user data becomes a regex operator (ReDoS-proof).
+ out = apply_transforms(
+ {"m": "a.b=hello"},
+ [{"op": "extract", "field": "m", "template": "a.b=%{WORD:v}"}],
+ )
+ assert out.event["v"] == "hello"
+ # The literal "a.b" must not match "axb" (the dot is escaped).
+ out2 = apply_transforms(
+ {"m": "axb=hello"},
+ [{"op": "extract", "field": "m", "template": "a.b=%{WORD:v}"}],
+ )
+ assert "v" not in out2.event
+
+
+def test_extract_input_is_length_bounded():
+ out = apply_transforms(
+ {"m": "x" * 10000 + " user=zed"},
+ [{"op": "extract", "field": "m", "template": "user=%{WORD:user}"}],
+ )
+ assert "user" not in out.event # trailing token beyond the cap is dropped
+
+
+def test_original_event_is_not_mutated():
+ original = {"src": "v"}
+ apply_transforms(original, [{"op": "rename", "from": "src", "to": "dst"}])
+ assert original == {"src": "v"}
diff --git a/services/api/tests/test_retention.py b/services/api/tests/test_retention.py
new file mode 100644
index 000000000..e8ac79889
--- /dev/null
+++ b/services/api/tests/test_retention.py
@@ -0,0 +1,52 @@
+"""Wave 5 (W5.1) - configurable retention policies + purge SQL."""
+
+from __future__ import annotations
+
+import uuid
+
+from app.services.retention import (
+ MAX_DAYS,
+ MIN_DAYS,
+ build_alert_purge_sql,
+ build_lake_purge_sql,
+ resolve_policy,
+)
+
+
+def test_defaults_when_no_config():
+ policy = resolve_policy(None)
+ assert policy.raw_events_days == 90
+ assert policy.alerts_days == 365
+ assert policy.audit_days == 730
+
+
+def test_tenant_override_merges():
+ policy = resolve_policy({"raw_events_days": 30})
+ assert policy.raw_events_days == 30
+ assert policy.alerts_days == 365 # default preserved
+
+
+def test_bounds_are_clamped():
+ assert resolve_policy({"raw_events_days": 0}).raw_events_days == MIN_DAYS
+ assert resolve_policy({"alerts_days": 99999}).alerts_days == MAX_DAYS
+
+
+def test_lake_purge_sql_is_tenant_scoped():
+ tid = uuid.uuid4()
+ sql = build_lake_purge_sql(tid, 30)
+ assert str(tid) in sql
+ assert "tenant_id" in sql
+ assert "INTERVAL 30 DAY" in sql
+
+
+def test_lake_purge_clamps_days():
+ sql = build_lake_purge_sql(uuid.uuid4(), 0)
+ assert f"INTERVAL {MIN_DAYS} DAY" in sql
+
+
+def test_alert_purge_sql_is_parameterised():
+ sql, params = build_alert_purge_sql(45)
+ assert ":days" in sql
+ assert params == {"days": 45}
+ # never string-interpolate the cutoff
+ assert "45" not in sql