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): SCIM manager attribute and tenant verification opt-in

Beenu Arora3359325ad36c
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 36056e700..ca629c8e3 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -12230,6 +12230,89 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/verification-policies:
+ get:
+ tags:
+ - settings
+ summary: List Policies
+ description: Every class this tenant has opted into. Empty means none.
+ operationId: list_policies_api_v1_verification_policies_get
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ items:
+ $ref: '#/components/schemas/VerificationPolicyOut'
+ type: array
+ title: Response List Policies Api V1 Verification Policies Get
+ security:
+ - HTTPBearer: []
+ put:
+ tags:
+ - settings
+ summary: Enable Class
+ description: 'Allow automatic verification prompts for one alert class.
+
+
+ Idempotent: re-enabling an already-enabled class re-stamps who asked for
+
+ it and when, which is the record a review after a complaint needs.'
+ operationId: enable_class_api_v1_verification_policies_put
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/VerificationPolicyIn'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/VerificationPolicyOut'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
+ /api/v1/verification-policies/{alert_class}:
+ delete:
+ tags:
+ - settings
+ summary: Disable Class
+ description: 'Stop automatic prompts for one class.
+
+
+ Answers 204 whether or not a row existed. A tenant revoking a grant
+
+ wants it gone; telling them it was already gone is not useful and a 404
+
+ here would read as "the revocation failed".'
+ operationId: disable_class_api_v1_verification_policies__alert_class__delete
+ security:
+ - HTTPBearer: []
+ parameters:
+ - name: alert_class
+ in: path
+ required: true
+ schema:
+ type: string
+ title: Alert Class
+ responses:
+ '204':
+ description: Successful Response
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
/api/v1/sso-connections:
get:
tags:
@@ -38083,6 +38166,39 @@ components:
pass-through would let a caller supply their own vendor credential and
have the read run somewhere else entirely.'
+ VerificationPolicyIn:
+ properties:
+ alert_class:
+ type: string
+ maxLength: 200
+ minLength: 1
+ title: Alert Class
+ description: An alert's rule_id, category or alert_class. Matched case-insensitively.
+ type: object
+ required:
+ - alert_class
+ title: VerificationPolicyIn
+ VerificationPolicyOut:
+ properties:
+ alert_class:
+ type: string
+ title: Alert Class
+ enabled_by:
+ anyOf:
+ - type: string
+ format: uuid
+ - type: 'null'
+ title: Enabled By
+ enabled_at:
+ type: string
+ format: date-time
+ title: Enabled At
+ type: object
+ required:
+ - alert_class
+ - enabled_by
+ - enabled_at
+ title: VerificationPolicyOut
VerifyRequest:
properties:
mfa_token:
diff --git a/services/api/app/api/v1/endpoints/scim.py b/services/api/app/api/v1/endpoints/scim.py
index d38249a48..9d08d1073 100644
--- a/services/api/app/api/v1/endpoints/scim.py
+++ b/services/api/app/api/v1/endpoints/scim.py
@@ -209,6 +209,7 @@ async def _render_user(db: AsyncSession, user: User, meta: ScimUser | None) -> d
created_at=user.created_at,
updated_at=meta.updated_at if meta else user.created_at,
groups=await _user_groups(db, user.tenant_id, user.id),
+ manager_ref=meta.manager_ref if meta else None,
)
@@ -271,6 +272,36 @@ def _extract_names(body: dict[str, Any]) -> tuple[str | None, str | None]:
return given, family
+#: The SCIM enterprise user extension, where `manager` lives. Matched
+#: case-insensitively because providers differ on the casing of the URN's
+#: final segment and a case-sensitive read silently finds nothing.
+_ENTERPRISE_SCHEMA = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:user"
+
+
+def _extract_manager(body: dict[str, Any]) -> str | None:
+ """``manager.value`` from the enterprise extension, if the IdP sent one.
+
+ Both shapes are accepted because both are in the wild: ``manager`` as an
+ object with a ``value`` (the specification's complex attribute) and as a
+ bare string (what several providers send when the directory stores a
+ username rather than an id). Reading only the first finds nothing on the
+ second, which looks identical to "this person has no manager" — and that
+ distinction is load-bearing for the escalation that reads this column.
+ """
+ for key, extension in body.items():
+ if not isinstance(key, str) or key.casefold() != _ENTERPRISE_SCHEMA:
+ continue
+ if not isinstance(extension, dict):
+ return None
+ for attribute, value in extension.items():
+ if not isinstance(attribute, str) or attribute.casefold() != "manager":
+ continue
+ if isinstance(value, dict):
+ return _string_attr(value.get("value")) or _string_attr(value.get("$ref"))
+ return _string_attr(value)
+ return None
+
+
def _extract_username(body: dict[str, Any]) -> str | None:
"""Read ``userName``, falling back to a primary work email.
@@ -422,6 +453,7 @@ async def create_user(body: dict[str, Any], principal: ScimAuth, db: ScimDB, req
external_id=external_id,
given_name=given,
family_name=family,
+ manager_ref=_extract_manager(body),
token_id=principal.token_id,
)
db.add(meta)
@@ -482,6 +514,10 @@ async def replace_user(user_id: str, body: dict[str, Any], principal: ScimAuth,
given, family = _extract_names(body)
meta.given_name = given
meta.family_name = family
+ # Overwritten rather than merged, like the names above: a PUT replaces
+ # the resource, so an IdP that stopped sending a manager is saying the
+ # reporting line is gone.
+ meta.manager_ref = _extract_manager(body)
external_id = _string_attr(body.get("externalId"))
if external_id is not None:
meta.external_id = external_id
@@ -570,6 +606,18 @@ async def patch_user(user_id: str, body: dict[str, Any], principal: ScimAuth, db
db.add(meta)
meta.external_id = _string_attr(op.value)
changes["external_id"] = meta.external_id
+ elif attribute.endswith("manager") or attribute.endswith("manager.value"):
+ # The enterprise extension's attribute arrives with its URN
+ # prefix intact on some providers and stripped on others, so
+ # this matches the suffix. Without it a manager change is
+ # silently filed under `ignored_attributes` and the escalation
+ # keeps asking last year's manager.
+ if meta is None:
+ meta = ScimUser(user_id=user.id, tenant_id=principal.tenant_id, token_id=principal.token_id)
+ db.add(meta)
+ value = op.value
+ meta.manager_ref = _string_attr(value.get("value")) if isinstance(value, dict) else _string_attr(value)
+ changes["manager_ref"] = meta.manager_ref
elif attribute == "name":
# A pathless replace sends the whole complex attribute.
if isinstance(op.value, dict):
diff --git a/services/api/app/api/v1/endpoints/verification_policies.py b/services/api/app/api/v1/endpoints/verification_policies.py
new file mode 100644
index 000000000..9fd88cacf
--- /dev/null
+++ b/services/api/app/api/v1/endpoints/verification_policies.py
@@ -0,0 +1,163 @@
+"""Which alert classes a tenant lets AiSOC ask its own people about.
+
+Depth plan 5.4. The playbook engine refuses to send an automatic
+verification prompt unless a row exists here for the alert's class, and a
+tenant with no rows auto-sends nothing. Without this surface that table
+would have a reader and no writer — the shape this repository keeps finding,
+where the control is real, fails closed, and can never be switched on, so
+the feature reads as broken rather than as governed.
+
+Why opt-in per class rather than one switch
+--------------------------------------------
+"Ask the user" is reasonable for an impossible-travel sign-in and absurd for
+a malware detection on a server. One boolean forces a tenant to choose
+between never using it and using it everywhere, and the second choice is the
+one that gets the feature turned off again after the first complaint.
+
+Why there is no "ask on everything" value
+------------------------------------------
+Because the refusal that matters — never on a confirmed true positive — is
+not expressible as a class, and a wildcard would invite somebody to reach
+for it instead of listing what they mean. The list is short in practice:
+sign-in anomalies, MFA prompts, new-device registrations.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, Request, status
+from pydantic import BaseModel, Field, field_validator
+from sqlalchemy import text
+
+from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.services.audit import emit_audit
+
+router = APIRouter(prefix="/verification-policies", tags=["settings"])
+
+#: Classes are compared case-insensitively against the alert's `rule_id`,
+#: `category` or `alert_class`, so they are stored lower-cased and the
+#: comparison has one spelling rather than two.
+_MAX_CLASS_LENGTH = 200
+
+
+class VerificationPolicyIn(BaseModel):
+ alert_class: str = Field(
+ ...,
+ min_length=1,
+ max_length=_MAX_CLASS_LENGTH,
+ description="An alert's rule_id, category or alert_class. Matched case-insensitively.",
+ )
+
+ @field_validator("alert_class")
+ @classmethod
+ def _normalise(cls, value: str) -> str:
+ folded = value.strip().lower()
+ if not folded:
+ raise ValueError("alert_class cannot be blank")
+ if folded == "*":
+ # Refused rather than silently stored. A wildcard here would be
+ # a tenant-wide grant to message every employee on any alert,
+ # entered in a text box.
+ raise ValueError("a wildcard is not accepted; name the alert classes you mean")
+ return folded
+
+
+class VerificationPolicyOut(BaseModel):
+ alert_class: str
+ enabled_by: uuid.UUID | None
+ enabled_at: datetime
+
+
[email protected]("", response_model=list[VerificationPolicyOut])
+async def list_policies(
+ db: DBSession,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:read"))],
+) -> list[VerificationPolicyOut]:
+ """Every class this tenant has opted into. Empty means none."""
+ rows = await db.execute(
+ text(
+ "SELECT alert_class, enabled_by, enabled_at FROM aisoc_verification_policies "
+ "WHERE tenant_id = CAST(:tenant AS uuid) ORDER BY alert_class"
+ ).bindparams(tenant=str(current_user.tenant_id))
+ )
+ return [VerificationPolicyOut(alert_class=r.alert_class, enabled_by=r.enabled_by, enabled_at=r.enabled_at) for r in rows]
+
+
[email protected]("", response_model=VerificationPolicyOut, status_code=status.HTTP_200_OK)
+async def enable_class(
+ body: VerificationPolicyIn,
+ db: DBSession,
+ request: Request,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+) -> VerificationPolicyOut:
+ """Allow automatic verification prompts for one alert class.
+
+ Idempotent: re-enabling an already-enabled class re-stamps who asked for
+ it and when, which is the record a review after a complaint needs.
+ """
+ tenant = str(current_user.tenant_id)
+ await db.execute(
+ text(
+ "INSERT INTO aisoc_verification_policies (tenant_id, alert_class, enabled_by) "
+ "VALUES (CAST(:tenant AS uuid), :alert_class, CAST(:actor AS uuid)) "
+ "ON CONFLICT (tenant_id, alert_class) DO UPDATE "
+ "SET enabled_by = EXCLUDED.enabled_by, enabled_at = NOW()"
+ ).bindparams(tenant=tenant, alert_class=body.alert_class, actor=str(current_user.user_id))
+ )
+ row = (
+ await db.execute(
+ text(
+ "SELECT alert_class, enabled_by, enabled_at FROM aisoc_verification_policies "
+ "WHERE tenant_id = CAST(:tenant AS uuid) AND alert_class = :alert_class"
+ ).bindparams(tenant=tenant, alert_class=body.alert_class)
+ )
+ ).one()
+ await emit_audit(
+ db=db,
+ request=request,
+ action="verification_policy:enable",
+ resource="verification_policy",
+ resource_id=body.alert_class,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ changes={"alert_class": body.alert_class},
+ )
+ await db.commit()
+ return VerificationPolicyOut(alert_class=row.alert_class, enabled_by=row.enabled_by, enabled_at=row.enabled_at)
+
+
[email protected]("/{alert_class}", status_code=status.HTTP_204_NO_CONTENT)
+async def disable_class(
+ alert_class: str,
+ db: DBSession,
+ request: Request,
+ current_user: Annotated[AuthUser, Depends(require_permission("settings:write"))],
+) -> None:
+ """Stop automatic prompts for one class.
+
+ Answers 204 whether or not a row existed. A tenant revoking a grant
+ wants it gone; telling them it was already gone is not useful and a 404
+ here would read as "the revocation failed".
+ """
+ folded = alert_class.strip().lower()[:_MAX_CLASS_LENGTH]
+ await db.execute(
+ text("DELETE FROM aisoc_verification_policies WHERE tenant_id = CAST(:tenant AS uuid) AND alert_class = :alert_class").bindparams(
+ tenant=str(current_user.tenant_id), alert_class=folded
+ )
+ )
+ await emit_audit(
+ db=db,
+ request=request,
+ action="verification_policy:disable",
+ resource="verification_policy",
+ resource_id=folded,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ changes={"alert_class": folded},
+ )
+ await db.commit()
diff --git a/services/api/app/api/v1/router.py b/services/api/app/api/v1/router.py
index 5cadb3d76..a35e254e0 100644
--- a/services/api/app/api/v1/router.py
+++ b/services/api/app/api/v1/router.py
@@ -95,6 +95,7 @@ from app.api.v1.endpoints import (
threat_intel,
translation,
usage,
+ verification_policies,
waitlist,
workload_identities,
)
@@ -248,6 +249,7 @@ api_router.include_router(saved_views.router)
# Administering SCIM credentials, which is a console action. The SCIM
# surface those credentials authenticate is mounted at /scim/v2 in main.py.
api_router.include_router(scim_tokens.router)
+api_router.include_router(verification_policies.router)
api_router.include_router(sso_connections.router)
# Wave 3 — operational maturity
diff --git a/services/api/app/models/scim.py b/services/api/app/models/scim.py
index 89e69f2b3..2e8cadb0a 100644
--- a/services/api/app/models/scim.py
+++ b/services/api/app/models/scim.py
@@ -62,6 +62,12 @@ class ScimUser(Base):
external_id: Mapped[str | None] = mapped_column(Text, nullable=True)
given_name: Mapped[str | None] = mapped_column(Text, nullable=True)
family_name: Mapped[str | None] = mapped_column(Text, nullable=True)
+ #: ``manager.value`` from the SCIM enterprise user extension, stored as
+ #: the provider's own reference rather than resolved to a local user id
+ #: — the manager is frequently not an AiSOC user at all. Read by the
+ #: playbook verification escalation (depth 5.4), which is the only thing
+ #: in the platform that needs to know who somebody reports to.
+ manager_ref: Mapped[str | None] = mapped_column(Text, nullable=True)
token_id: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("aisoc_scim_tokens.id", ondelete="SET NULL"), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=lambda: datetime.now(UTC))
updated_at: Mapped[datetime] = mapped_column(
diff --git a/services/api/app/services/scim/resources.py b/services/api/app/services/scim/resources.py
index d792e8118..ee5b0f4a4 100644
--- a/services/api/app/services/scim/resources.py
+++ b/services/api/app/services/scim/resources.py
@@ -17,6 +17,9 @@ from typing import Any, Final
USER_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:User"
GROUP_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:Group"
+#: The enterprise extension, which is where `manager` lives. Only ever
+#: emitted when there is a manager to emit.
+ENTERPRISE_USER_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"
LIST_RESPONSE_SCHEMA: Final[str] = "urn:ietf:params:scim:api:messages:2.0:ListResponse"
ERROR_SCHEMA: Final[str] = "urn:ietf:params:scim:api:messages:2.0:Error"
SERVICE_PROVIDER_CONFIG_SCHEMA: Final[str] = "urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"
@@ -49,6 +52,7 @@ def user_resource(
created_at: datetime | None,
updated_at: datetime | None,
groups: list[tuple[uuid.UUID, str]] | None = None,
+ manager_ref: str | None = None,
) -> dict[str, Any]:
"""One SCIM User.
@@ -86,6 +90,12 @@ def user_resource(
resource["groups"] = [
{"value": str(group_id), "display": display, "$ref": f"{SCIM_BASE}/Groups/{group_id}"} for group_id, display in groups
]
+ if manager_ref:
+ # Echoed back, and the extension URN added to `schemas` alongside
+ # it. A provider that sent `manager` and reads a resource without
+ # it concludes the write was dropped and re-sends on every sync.
+ resource["schemas"] = [*resource["schemas"], ENTERPRISE_USER_SCHEMA]
+ resource[ENTERPRISE_USER_SCHEMA] = {"manager": {"value": manager_ref}}
return resource