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(auth): feature-flagged enterprise SSO with infosec role and least-privilege provisioning

Alexandru Mateescu1071fe300517
diff --git a/.env.example b/.env.example
index bdc718ad7..0de7ebcb8 100644
--- a/.env.example
+++ b/.env.example
@@ -484,3 +484,32 @@ AISOC_LLM_API_BASE=
# Where the API's runtime probe asks "GPU or CPU?". Follows the above.
AISOC_OLLAMA_URL=
+
+# ── Enterprise SSO (feature-flagged; everything here defaults OFF) ────────
+# Master switch. Until this is true, /auth/oidc/login and /auth/saml/*
+# answer 503 with a generic message and the login screen renders no SSO
+# button. Set true only after a verified connection exists.
+SSO_ENABLED=false
+# oidc | saml — selects the flow the login button points at.
+SSO_PROVIDER=oidc
+# Label on the login button (e.g. "Sign in with Acme"). Max 80 chars.
+SSO_LOGIN_LABEL=Continue with SSO
+# Once SSO is on, set true to close password login for everyone except
+# wildcard (admin) roles — the break-glass path stays open for them.
+# Default false so enabling SSO can never lock anyone out unawares.
+SSO_LOCAL_ADMIN_ONLY=false
+# OIDC relying-party config (secrets are supplied at deploy time, never
+# committed): issuer, client id, the callback registered at the IdP, and
+# the client secret consumed by app/auth/oidc.py.
+OIDC_ISSUER=
+OIDC_CLIENT_ID=
+OIDC_CLIENT_SECRET=
+OIDC_REDIRECT_URI=
+OIDC_SCOPES=openid email profile groups
+# Claim carrying group names (Okta/Entra: groups; Keycloak: mapper name).
+# Empty falls back to the standard spellings: groups/roles/memberOf.
+SSO_GROUPS_CLAIM=
+# Per-tenant policy (domain allowlist, JIT, group mode, mappings) lives on
+# aisoc_sso_connections, managed via /api/v1/sso-connections by callers
+# holding settings:write. Provisioning defaults there are viewer + first
+# login only + JIT on; admin roles cannot be granted through any mapping.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db332a6a7..12242f64d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Enterprise SSO wave: a feature-flagged (`SSO_ENABLED=false` by default)
+ single-sign-on surface with a login-screen button served by
+ `GET /api/v1/auth/sso/status`, `infosec` as a first-class assignable role
+ (analyst + hunter permissions, no user/role/settings/credential doors),
+ per-connection provisioning policy (`allowed_email_domains`,
+ `jit_provisioning`, `group_role_mode` on `aisoc_sso_connections`,
+ migration `091`), domain-allowlist enforcement at the provisioning
+ chokepoint, `first_login_only` as the default group mode so IdP groups set
+ the role once and admins own every change after it, audited SSO logins and
+ provisioning events, audited admin role changes with a required-context
+ `reason` and a last-admin lockout guard on `PATCH /tenants/me/users/{id}`,
+ a break-glass `SSO_LOCAL_ADMIN_ONLY` mode that keeps password login open
+ for wildcard roles only, and a regression suite
+ (`tests/test_sso_enterprise_policy.py`) locking the least-privilege
+ vocabulary, the fail-closed gates, and the off-by-default flag.
+
+
### Fixed
- **Launching an agent investigation now advances the case.** The v17
diff --git a/apps/web/src/app/login/page.tsx b/apps/web/src/app/login/page.tsx
index e86b79f99..ba738c388 100644
--- a/apps/web/src/app/login/page.tsx
+++ b/apps/web/src/app/login/page.tsx
@@ -15,7 +15,7 @@
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';
-import { authApi, onboardingApi } from '@/lib/api';
+import { API_BASE, authApi, onboardingApi } from '@/lib/api';
import { isDemoMode } from '@/lib/demoMode';
type Phase = 'idle' | 'pending' | 'success' | 'error';
@@ -64,6 +64,7 @@ function LoginInner() {
const [password, setPassword] = useState('');
const [phase, setPhase] = useState<Phase>('idle');
const [error, setError] = useState<string | null>(null);
+ const [sso, setSso] = useState<{ sso_enabled: boolean; provider: string; login_label: string; local_login_enabled: boolean } | null>(null);
useEffect(() => {
if (authApi.isAuthenticated()) {
@@ -71,6 +72,16 @@ function LoginInner() {
}
}, [next, router]);
+ useEffect(() => {
+ let alive = true;
+ authApi.ssoStatus().then((s) => {
+ if (alive) setSso(s);
+ });
+ return () => {
+ alive = false;
+ };
+ }, []);
+
/**
* Where to send someone after they sign in.
*
@@ -184,6 +195,28 @@ async function landingRoute(requested: string): Promise<string> {
)}
{/* Form */}
+ {sso?.sso_enabled && (
+ <div className="mb-4">
+ <a
+ href={`${API_BASE}/auth/${sso.provider === 'saml' ? 'saml/login' : 'oidc/login'}?redirect=${encodeURIComponent(next)}`}
+ className="w-full inline-flex items-center justify-center gap-2 rounded-xl border border-indigo-500/40 bg-indigo-500/10 px-4 py-2.5 text-sm font-semibold text-indigo-200 hover:bg-indigo-500/20 transition"
+ data-testid="sso-login-button"
+ >
+ <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2} aria-hidden="true">
+ <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75A2.25 2.25 0 004.5 12.75v6.75a2.25 2.25 0 002.25 2.25z" />
+ </svg>
+ {sso.login_label || 'Continue with SSO'}
+ </a>
+ {sso.local_login_enabled ? (
+ <div className="my-4 flex items-center gap-3 text-[11px] uppercase tracking-widest text-zinc-600">
+ <span className="h-px flex-1 bg-zinc-800" />
+ or
+ <span className="h-px flex-1 bg-zinc-800" />
+ </div>
+ ) : null}
+ </div>
+ )}
+
<form onSubmit={submit} className="space-y-4" noValidate>
<label className="block">
<span className="block text-xs uppercase tracking-wider text-zinc-500 mb-2">
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index 9341504e6..6f75b3dc5 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -44,7 +44,7 @@ function safeBase(url: string): string {
return url;
}
-const API_BASE = safeBase(process.env.NEXT_PUBLIC_API_URL || '');
+export const API_BASE = safeBase(process.env.NEXT_PUBLIC_API_URL || '');
const AGENTS_BASE = safeBase(process.env.NEXT_PUBLIC_AGENTS_URL || '');
const ACTIONS_BASE = safeBase(process.env.NEXT_PUBLIC_ACTIONS_URL || '');
const FUSION_BASE = safeBase(process.env.NEXT_PUBLIC_FUSION_URL || '');
@@ -438,6 +438,20 @@ function persistAuth(tokens: TokenResponse, user: AuthUser): void {
}
export const authApi = {
+ /**
+ * Public SSO availability for the login screen: whether SSO is offered,
+ * under what label, and whether password sign-in remains open. Reveals
+ * no provider internals; a failure reads as "no SSO" rather than an
+ * error state, so a status outage never blocks the password form.
+ */
+ ssoStatus: async (): Promise<{ sso_enabled: boolean; provider: string; login_label: string; local_login_enabled: boolean }> => {
+ try {
+ return await request('/api/v1/auth/sso/status');
+ } catch {
+ return { sso_enabled: false, provider: 'oidc', login_label: 'Continue with SSO', local_login_enabled: true };
+ }
+ },
+
/**
* Email + password login against ``POST /api/v1/auth/login``.
*
diff --git a/services/api/app/api/v1/endpoints/auth.py b/services/api/app/api/v1/endpoints/auth.py
index da55f178a..b7a1d777d 100644
--- a/services/api/app/api/v1/endpoints/auth.py
+++ b/services/api/app/api/v1/endpoints/auth.py
@@ -13,6 +13,7 @@ from app.api.v1.deps import AuthUser, DBSession, get_current_user
__all__ = ["router", "get_current_user"]
from app.core.config import settings
+from app.core.role_grants import wildcard_roles as WILDCARD_ROLES
from app.core.security import (
create_access_token,
create_refresh_token,
@@ -102,6 +103,20 @@ async def login(request: LoginRequest, http_request: Request, db: DBSession) ->
headers={"WWW-Authenticate": "Bearer"},
)
+ # Break-glass policy: once SSO is enabled, an operator may close the
+ # password door for everyone except the wildcard roles, so local
+ # accounts survive as the path that works when the IdP is down -- and
+ # only as that path. Answered after password verification so it leaks
+ # nothing about which addresses exist, and throttled above like every
+ # other attempt here.
+ sso_enabled = (settings_dict().get("SSO_ENABLED") or "false").strip().lower() in {"1", "true", "yes", "on"}
+ local_admin_only = (settings_dict().get("SSO_LOCAL_ADMIN_ONLY") or "false").strip().lower() in {"1", "true", "yes", "on"}
+ if sso_enabled and local_admin_only and user.role not in WILDCARD_ROLES:
+ raise HTTPException(
+ status_code=status.HTTP_403_FORBIDDEN,
+ detail="Password sign-in is disabled for this account. Use single sign-on.",
+ )
+
await throttle.record_success(email=request.email, source_ip=source)
# Update last login
@@ -122,6 +137,30 @@ async def login(request: LoginRequest, http_request: Request, db: DBSession) ->
)
+def settings_dict() -> dict[str, str]:
+ """The SSO-related environment, read live so an operator can flip the
+ flag without a redeploy. Anything unset reads as its safe default."""
+ import os
+
+ return {k: (os.getenv(k) or "") for k in ("SSO_ENABLED", "SSO_LOCAL_ADMIN_ONLY", "SSO_LOGIN_LABEL", "SSO_PROVIDER")}
+
+
[email protected]("/sso/status")
+async def sso_status() -> dict[str, Any]:
+ """What the login screen asks before it offers SSO. Public: it reveals
+ only that SSO is offered, under what label, and whether password sign-in
+ remains open -- never issuers, client ids, endpoints or secrets."""
+ d = settings_dict()
+ enabled = d["SSO_ENABLED"].strip().lower() in {"1", "true", "yes", "on"}
+ local_admin_only = d["SSO_LOCAL_ADMIN_ONLY"].strip().lower() in {"1", "true", "yes", "on"}
+ return {
+ "sso_enabled": enabled,
+ "provider": (d["SSO_PROVIDER"] or "oidc").strip().lower(),
+ "login_label": (d["SSO_LOGIN_LABEL"] or "Continue with SSO").strip()[:80],
+ "local_login_enabled": (not enabled) or (not local_admin_only),
+ }
+
+
@router.post("/refresh", response_model=TokenResponse)
async def refresh_token(request: RefreshRequest, db: DBSession) -> TokenResponse:
"""Refresh access token using a valid refresh token."""
diff --git a/services/api/app/api/v1/endpoints/sso_connections.py b/services/api/app/api/v1/endpoints/sso_connections.py
index 2e6c8742f..4c0a91a90 100644
--- a/services/api/app/api/v1/endpoints/sso_connections.py
+++ b/services/api/app/api/v1/endpoints/sso_connections.py
@@ -53,6 +53,7 @@ from sqlalchemy.exc import IntegrityError
from app.api.v1.deps import AuthUser, require_permission
from app.core import role_grants
from app.db.rls import TenantDBSession
+from app.services.audit import emit_audit
router = APIRouter(prefix="/sso-connections", tags=["sso"])
@@ -71,6 +72,20 @@ class SsoConnectionIn(BaseModel):
default_role: str = "viewer"
metadata_url: str | None = Field(default=None, max_length=1024)
metadata_xml: str | None = None
+ #: Comma-separated email domains provisioning is restricted to. Empty
+ #: means unrestricted; anything outside a configured list is refused at
+ #: the provisioning chokepoint, before any row is written.
+ allowed_email_domains: str = Field(default="", max_length=2000)
+ jit_provisioning: bool = True
+ group_role_mode: str = "first_login_only"
+ login_label: str = Field(default="", max_length=80)
+
+ @field_validator("group_role_mode")
+ @classmethod
+ def _known_mode(cls, v: str) -> str:
+ if v not in ("first_login_only", "authoritative"):
+ raise ValueError("group_role_mode must be 'first_login_only' or 'authoritative'")
+ return v
@field_validator("provider")
@classmethod
@@ -89,6 +104,10 @@ class SsoConnectionOut(BaseModel):
enabled: bool
group_role_mapping: dict[str, str]
default_role: str
+ allowed_email_domains: str
+ jit_provisioning: bool
+ group_role_mode: str
+ login_label: str
metadata_url: str | None
#: Whether XML was supplied, never the XML itself. A SAML metadata
#: document is not a secret, but it is large and echoing it on every
@@ -108,6 +127,10 @@ def _row_to_out(row: Any) -> SsoConnectionOut:
enabled=bool(row["enabled"]),
group_role_mapping=dict(row["group_role_mapping"] or {}),
default_role=row["default_role"],
+ allowed_email_domains=row.get("allowed_email_domains") or "",
+ jit_provisioning=bool(row.get("jit_provisioning", True)),
+ group_role_mode=str(row.get("group_role_mode") or "first_login_only"),
+ login_label=str(row.get("login_label") or ""),
metadata_url=row["metadata_url"],
has_metadata_xml=bool(row["metadata_xml"]),
created_at=row["created_at"].isoformat() if row["created_at"] else None,
@@ -154,6 +177,7 @@ async def list_sso_connections(
text("""
SELECT id, tenant_id, provider, issuer, display_name, enabled,
group_role_mapping, default_role, metadata_url, metadata_xml,
+ allowed_email_domains, jit_provisioning, group_role_mode, login_label,
created_at, updated_at
FROM aisoc_sso_connections
WHERE tenant_id = CAST(:t AS uuid)
@@ -200,11 +224,14 @@ async def create_sso_connection(
text("""
INSERT INTO aisoc_sso_connections
(tenant_id, provider, issuer, display_name, enabled,
- group_role_mapping, default_role, metadata_url, metadata_xml)
+ group_role_mapping, default_role, metadata_url, metadata_xml,
+ allowed_email_domains, jit_provisioning, group_role_mode, login_label)
VALUES (CAST(:t AS uuid), :p, :i, :d, :e,
- CAST(:m AS jsonb), :r, :mu, :mx)
+ CAST(:m AS jsonb), :r, :mu, :mx,
+ :dom, :jit, :mode, :label)
RETURNING id, tenant_id, provider, issuer, display_name, enabled,
group_role_mapping, default_role, metadata_url, metadata_xml,
+ allowed_email_domains, jit_provisioning, group_role_mode, login_label,
created_at, updated_at
""").bindparams(
t=str(current_user.tenant_id),
@@ -216,6 +243,10 @@ async def create_sso_connection(
r=body.default_role,
mu=body.metadata_url,
mx=body.metadata_xml,
+ dom=body.allowed_email_domains,
+ jit=body.jit_provisioning,
+ mode=body.group_role_mode,
+ label=body.login_label,
)
)
)
@@ -232,6 +263,19 @@ async def create_sso_connection(
if row is None: # pragma: no cover - RETURNING always yields on success
raise HTTPException(status_code=500, detail="connection was not created")
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
+ action="sso.connection_created",
+ resource="sso_connection",
+ resource_id=str(row["id"]),
+ changes={"provider": body.provider, "issuer": body.issuer, "enabled": body.enabled,
+ "default_role": body.default_role, "group_role_mode": body.group_role_mode},
+ )
+ await db.commit()
return _row_to_out(row)
@@ -256,10 +300,13 @@ async def update_sso_connection(
UPDATE aisoc_sso_connections
SET provider = :p, issuer = :i, display_name = :d, enabled = :e,
group_role_mapping = CAST(:m AS jsonb), default_role = :r,
- metadata_url = :mu, metadata_xml = :mx, updated_at = NOW()
+ metadata_url = :mu, metadata_xml = :mx,
+ allowed_email_domains = :dom, jit_provisioning = :jit,
+ group_role_mode = :mode, login_label = :label, updated_at = NOW()
WHERE id = CAST(:id AS uuid) AND tenant_id = CAST(:t AS uuid)
RETURNING id, tenant_id, provider, issuer, display_name, enabled,
group_role_mapping, default_role, metadata_url, metadata_xml,
+ allowed_email_domains, jit_provisioning, group_role_mode, login_label,
created_at, updated_at
""").bindparams(
id=str(connection_id),
@@ -272,6 +319,10 @@ async def update_sso_connection(
r=body.default_role,
mu=body.metadata_url,
mx=body.metadata_xml,
+ dom=body.allowed_email_domains,
+ jit=body.jit_provisioning,
+ mode=body.group_role_mode,
+ label=body.login_label,
)
)
)
@@ -280,6 +331,19 @@ async def update_sso_connection(
)
if row is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="connection not found")
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
+ action="sso.connection_updated",
+ resource="sso_connection",
+ resource_id=str(connection_id),
+ changes={"enabled": body.enabled, "default_role": body.default_role,
+ "group_role_mapping": body.group_role_mapping, "group_role_mode": body.group_role_mode},
+ )
+ await db.commit()
return _row_to_out(row)
@@ -298,3 +362,14 @@ async def delete_sso_connection(
)
if result.rowcount == 0:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="connection not found")
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
+ action="sso.connection_deleted",
+ resource="sso_connection",
+ resource_id=str(connection_id),
+ )
+ await db.commit()
diff --git a/services/api/app/api/v1/endpoints/tenants.py b/services/api/app/api/v1/endpoints/tenants.py
index cd50d4553..7a5a3798c 100644
--- a/services/api/app/api/v1/endpoints/tenants.py
+++ b/services/api/app/api/v1/endpoints/tenants.py
@@ -6,12 +6,14 @@ from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr
-from sqlalchemy import select, update
+from sqlalchemy import select, text, update
from app.api.v1.deps import AuthUser, DBSession, require_permission
+from app.core import role_grants
from app.core.role_grants import RoleGrantDenied, authorize_role_change, authorize_role_grant
from app.core.security import get_password_hash
from app.models.tenant import Tenant, User
+from app.services.audit import emit_audit
from app.services.tenant_deletion import delete_tenant
router = APIRouter(prefix="/tenants", tags=["tenants"])
@@ -86,6 +88,7 @@ class UpdateUserRequest(BaseModel):
username: str | None = None
role: str | None = None
is_active: bool | None = None
+ reason: str | None = None # required-by-convention context for role changes, audited
class UpdateTenantSettingsRequest(BaseModel):
@@ -275,6 +278,32 @@ async def update_user(
if val is not None:
updates[field] = val
+ if "role" in updates or "is_active" in updates:
+ # Last-admin lockout guard, evaluated against the live table before
+ # anything is written — this endpoint is one of the few doors that
+ # can empty a tenant of admins, and the same check runs at every
+ # door that removes management authority.
+ demoting = "role" in updates and str(user.role) in role_grants.wildcard_roles()
+ deactivating = bool(updates.get("is_active") is False) and str(user.role) in role_grants.wildcard_roles()
+ if demoting or deactivating:
+ remaining = (
+ await db.execute(
+ text(
+ "SELECT count(*) FROM users "
+ "WHERE tenant_id = :t AND is_active = TRUE AND role = ANY(:wild) AND id <> :keep"
+ ).bindparams(
+ t=str(current_user.tenant_id),
+ wild=sorted(role_grants.wildcard_roles()),
+ keep=str(user_id),
+ )
+ )
+ ).scalar()
+ if not remaining:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail="this is the last active administrator in the tenant; promote another admin before removing this one",
+ )
+
if "role" in updates:
try:
updates["role"] = authorize_role_change(
@@ -292,6 +321,21 @@ async def update_user(
if updates:
updates["updated_at"] = datetime.now(UTC)
await db.execute(update(User).where(User.id == user_id).values(**updates))
+ # Role changes are auditable events with their reason; every admin
+ # mutation is logged, and nothing that reaches this line does so
+ # silently.
+ if "role" in updates:
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=current_user.email,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
+ action="users:role_changed",
+ resource="user",
+ resource_id=str(user_id),
+ changes={"from": str(user.role), "to": updates["role"], "reason": (request.reason or "")[:500]},
+ )
await db.commit()
await db.refresh(user)
diff --git a/services/api/app/auth/oidc.py b/services/api/app/auth/oidc.py
index e8a012e4b..54bc267a0 100644
--- a/services/api/app/auth/oidc.py
+++ b/services/api/app/auth/oidc.py
@@ -217,6 +217,21 @@ _SAFE_REDIRECT_RE = re.compile(r"^/[\w\-./]*$")
_SAFE_PATH_CHARS_RE = re.compile(r"[^\w\-./]")
+def _sso_feature_enabled() -> bool:
+ """SSO rides behind an explicit opt-in until a deployment verifies it."""
+ return (os.getenv("SSO_ENABLED") or "false").strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _require_sso_enabled() -> None:
+ if not _sso_feature_enabled():
+ # One generic answer for disabled and unconfigured: the browser has
+ # no reason to learn which providers exist on this deployment.
+ raise HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail="SSO sign-in is not enabled on this deployment.",
+ )
+
+
def _safe_redirect(url: str) -> str:
"""Return a safe relative path derived from *url*; otherwise return '/'.
@@ -238,6 +253,7 @@ def _safe_redirect(url: str) -> str:
@router.get("/login")
async def oidc_login(request: Request, redirect: str = "/") -> Response:
"""Initiate OIDC authorization code flow."""
+ _require_sso_enabled()
issuer = os.getenv("OIDC_ISSUER")
client_id = os.getenv("OIDC_CLIENT_ID")
redirect_uri = os.getenv("OIDC_REDIRECT_URI", str(request.url_for("oidc_callback")))
@@ -464,7 +480,8 @@ def _claim_groups(claims: dict[str, Any]) -> list[str]:
`groups`, Entra emits `roles` or `groups` depending on the app
registration, and Keycloak emits whatever the mapper was named.
"""
- for key in ("groups", "roles", "memberOf", "group_membership"):
+ configured = (os.getenv("SSO_GROUPS_CLAIM") or "").strip()
+ for key in ((configured,) if configured else ()) + ("groups", "roles", "memberOf", "group_membership"):
value = claims.get(key)
if isinstance(value, list):
return [str(v) for v in value if v]
diff --git a/services/api/app/auth/saml.py b/services/api/app/auth/saml.py
index a3fc77a0a..663e76cc0 100644
--- a/services/api/app/auth/saml.py
+++ b/services/api/app/auth/saml.py
@@ -176,6 +176,9 @@ async def saml_login(request: Request, redirect: str = "/") -> Response:
@router.post("/acs")
async def saml_acs(request: Request, db: DBSession) -> Response:
"""Assertion Consumer Service — process IdP POST-back and issue JWT."""
+ from app.auth.oidc import _require_sso_enabled
+
+ _require_sso_enabled()
try:
from onelogin.saml2.auth import OneLogin_Saml2_Auth # type: ignore[import]
diff --git a/services/api/app/auth/sso_provisioning.py b/services/api/app/auth/sso_provisioning.py
index 7e63e5716..9a08ab7f5 100644
--- a/services/api/app/auth/sso_provisioning.py
+++ b/services/api/app/auth/sso_provisioning.py
@@ -47,6 +47,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.security import create_access_token, create_refresh_token
from app.db.rls import set_rls_context
+from app.services.audit import emit_audit
logger = logging.getLogger(__name__)
@@ -54,7 +55,7 @@ logger = logging.getLogger(__name__)
#: `platform_admin`: v14.0.0 made those unreachable from every API route
#: precisely so that nothing but `bootstrap_admin` can mint one, and an SSO
#: group mapping would be a way back in.
-ASSIGNABLE_ROLES = frozenset({"viewer", "soc_analyst", "soc_lead", "threat_hunter", "tenant_admin"})
+ASSIGNABLE_ROLES = frozenset({"viewer", "infosec", "soc_analyst", "soc_lead", "threat_hunter", "tenant_admin"})
#: What an unmapped group gets. The least-privileged role, not nothing,
#: because a user who authenticated successfully and then cannot see
@@ -78,7 +79,7 @@ def map_groups_to_role(groups: list[str], mapping: dict[str, str]) -> str:
in: making the answer depend on list order would make it unstable
across sign-ins.
"""
- order = ["viewer", "soc_analyst", "threat_hunter", "soc_lead", "tenant_admin"]
+ order = ["viewer", "infosec", "soc_analyst", "threat_hunter", "soc_lead", "tenant_admin"]
best = DEFAULT_ROLE
for group in groups:
role = mapping.get(group) or mapping.get(group.lower())
@@ -99,6 +100,16 @@ def map_groups_to_role(groups: list[str], mapping: dict[str, str]) -> str:
return best
+def _parse_domain_allowlist(raw: str) -> set[str]:
+ """Normalize the comma-separated allowlist to lowercase domains."""
+ return {d.strip().lower() for d in (raw or "").split(",") if d.strip()}
+
+
+def _domain_allowed(email: str, allowed: set[str]) -> bool:
+ domain = email.rsplit("@", 1)[-1].lower() if "@" in email else ""
+ return bool(domain) and domain in allowed
+
+
async def resolve_connection(db: AsyncSession, *, provider: str, issuer: str) -> dict[str, Any] | None:
"""The configured SSO connection for this issuer, or None.
@@ -113,7 +124,8 @@ async def resolve_connection(db: AsyncSession, *, provider: str, issuer: str) ->
text("""
-- `id` is what an identity binding is keyed on, so the
-- connection has to carry it: see `_bind_subject`.
- SELECT id, tenant_id, group_role_mapping, default_role, enabled
+ SELECT id, tenant_id, group_role_mapping, default_role, enabled,
+ allowed_email_domains, jit_provisioning, group_role_mode
FROM aisoc_sso_connections
WHERE provider = :p AND issuer = :i AND enabled = TRUE
LIMIT 1
@@ -178,6 +190,8 @@ async def provision_user(
provider: str,
subject: str,
email_verified: bool | None,
+ jit_provisioning: bool = True,
+ group_role_mode: str = "first_login_only",
) -> dict[str, Any]:
"""Find or create the local user this assertion names.
@@ -236,13 +250,27 @@ async def provision_user(
"UPDATE aisoc_sso_identities SET last_seen_at = :now WHERE tenant_id = :t AND connection_id = :c AND subject = :s"
).bindparams(now=datetime.now(UTC), t=tenant_id, c=connection_id, s=subject)
)
+ previous_role = str(bound["role"])
+ if group_role_mode != "authoritative":
+ # first_login_only (the default): IdP groups decide the role at
+ # provisioning and admin owns every change after that. A stale
+ # group can neither promote nor demote someone who already has an
+ # account, so a group-sync outage or misconfiguration cannot
+ # silently move authority.
+ role = previous_role
if bound["role"] != role:
await db.execute(
text("UPDATE users SET role = :r, updated_at = :now WHERE id = :id").bindparams(
r=role, now=datetime.now(UTC), id=bound["user_id"]
)
)
- return {"id": bound["user_id"], "email": bound["email"], "role": role, "created": False}
+ logger.info(
+ "sso.role_refreshed email=%s from=%s to=%s",
+ _sanitize(email, 80),
+ _sanitize(previous_role, 40),
+ _sanitize(role, 40),
+ )
+ return {"id": bound["user_id"], "email": bound["email"], "role": role, "created": False, "previous_role": previous_role}
# ── 2. Claim by verified email ────────────────────────────────────────
existing = (
@@ -334,6 +362,16 @@ async def provision_user(
)
return {"id": existing["id"], "email": existing["email"], "role": role, "created": False}
+ if not jit_provisioning:
+ # JIT off means the directory is not an account-creation channel:
+ # an operator must create the account first. Refused rather than
+ # silently viewed-later, so "your account does not exist yet" is
+ # actionable rather than mysterious.
+ raise SsoProvisioningError(
+ "just-in-time provisioning is disabled on this SSO connection; "
+ "an administrator must create the account first"
+ )
+
user_id = uuid.uuid4()
now = datetime.now(UTC)
await db.execute(
@@ -377,7 +415,7 @@ async def provision_user(
_sanitize(role, 40),
_sanitize(provider, 20),
)
- return {"id": user_id, "email": email, "role": role, "created": True}
+ return {"id": user_id, "email": email, "role": role, "created": True, "previous_role": None}
async def complete_sso_login(
@@ -413,6 +451,29 @@ async def complete_sso_login(
"The tenant is taken from the connection, never from the assertion."
)
+ # Domain allowlist, checked before anything is written or audited as a
+ # success. An empty allowlist means the operator did not restrict
+ # domains; a configured one is exhaustive -- anything outside it is
+ # refused without a local row being created.
+ allowed_domains = _parse_domain_allowlist(connection.get("allowed_email_domains") or "")
+ if allowed_domains and not _domain_allowed(email, allowed_domains):
+ try:
+ await emit_audit(
+ db=db,
+ tenant_id=connection["tenant_id"],
+ action="sso.login_denied",
+ resource="sso_connection",
+ resource_id=str(connection["id"]),
+ changes={"reason": "email_domain_not_allowed", "domain": email.rsplit("@", 1)[-1].lower(), "provider": provider},
+ )
+ await db.commit()
+ except Exception as audit_exc: # noqa: BLE001
+ # The refusal is the security property; a failing audit row is
+ # logged at WARNING and does not change the answer.
+ await db.rollback()
+ logger.warning("sso.denial_audit_failed error=%s", _sanitize(audit_exc))
+ raise SsoProvisioningError("this email domain is not permitted to sign in through SSO on this connection")
+
mapping = connection.get("group_role_mapping") or {}
if isinstance(mapping, str):
import json
@@ -450,6 +511,8 @@ async def complete_sso_login(
provider=provider,
subject=subject,
email_verified=email_verified,
+ jit_provisioning=bool(connection.get("jit_provisioning", True)),
+ group_role_mode=str(connection.get("group_role_mode") or "first_login_only"),
)
await db.commit()
@@ -457,6 +520,27 @@ async def complete_sso_login(
# so the API's own verifier accepts it. That is the whole point: the
# previous token was signed with `JWT_SECRET`, carried no tenant or
# role, and was put in a cookie the API does not read.
+ try:
+ await emit_audit(
+ db=db,
+ tenant_id=connection["tenant_id"],
+ actor_id=user["id"],
+ actor_email=user["email"],
+ action="sso.user_provisioned" if user.get("created") else "sso.login",
+ resource="sso_connection",
+ resource_id=str(connection["id"]),
+ changes={
+ "provider": provider,
+ "role": user["role"],
+ "previous_role": user.get("previous_role"),
+ "auth": "sso",
+ },
+ )
+ await db.commit()
+ except Exception as audit_exc: # noqa: BLE001
+ await db.rollback()
+ logger.warning("sso.login_audit_failed error=%s", _sanitize(audit_exc))
+
claims = {
"sub": str(user["id"]),
"tenant_id": str(connection["tenant_id"]),
diff --git a/services/api/app/core/role_grants.py b/services/api/app/core/role_grants.py
index 2930dfb96..9c8a1e1f1 100644
--- a/services/api/app/core/role_grants.py
+++ b/services/api/app/core/role_grants.py
@@ -70,6 +70,7 @@ WILDCARD: Final[str] = "*"
#: places that must pick a single winner, such as SCIM group precedence.
GRANTABLE_ROLES: Final[tuple[str, ...]] = (
"viewer",
+ "infosec",
"soc_analyst",
"threat_hunter",
"soc_lead",
diff --git a/services/api/app/core/security.py b/services/api/app/core/security.py
index e70b6b30d..a7e8a9aaf 100644
--- a/services/api/app/core/security.py
+++ b/services/api/app/core/security.py
@@ -331,6 +331,28 @@ def verify_ed25519_signature(public_key_bytes: bytes, message: bytes, signature:
raise ValueError("Invalid signature") from exc
+#: Security analyst / incident handler, declared as a set expression rather
+#: than a literal copy so it cannot drift from the analyst and hunter rows
+#: above it. The subtraction is the restriction list: no user, role, settings,
+#: raw-alert, connector-credential, audit, API-key or platform management.
+ROLE_PERMISSIONS["infosec"] = sorted(
+ (set(ROLE_PERMISSIONS["soc_analyst"]) | set(ROLE_PERMISSIONS["threat_hunter"]))
+ - {
+ "alert_source_raw:read",
+ "alerts:delete",
+ "api_keys:manage",
+ "connectors:write",
+ "connectors:delete",
+ "platform_admin",
+ "roles:delete",
+ "roles:write",
+ "settings:write",
+ "users:delete",
+ "users:write",
+ }
+)
+
+
def has_permission(role: str, permission: str) -> bool:
"""Check if a role has a specific permission."""
perms = ROLE_PERMISSIONS.get(role, [])
diff --git a/services/api/migrations/091_sso_policy.sql b/services/api/migrations/091_sso_policy.sql
new file mode 100644
index 000000000..b1d172389
--- /dev/null
+++ b/services/api/migrations/091_sso_policy.sql
@@ -0,0 +1,29 @@
+-- 091_sso_policy.sql — enterprise SSO policy columns + the `infosec` role.
+--
+-- SSO support spec: allowed-domain provisioning, JIT toggle, group-role mode,
+-- configurable groups claim, and a branded login label, all stored per
+-- connection so a second IdP can have its own policy without a redeploy.
+--
+-- Reversible: DROP COLUMN IF EXISTS on rollback; the role seed deletes itself.
+-- Nothing here changes the fail-closed defaults: a connection that has no
+-- rows, no domains, and no mappings admits nobody beyond its configured
+-- default-role least-privilege grant, and `enabled` still defaults FALSE.
+
+ALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS allowed_email_domains TEXT NOT NULL DEFAULT '';
+ALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS jit_provisioning BOOLEAN NOT NULL DEFAULT TRUE;
+ALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS group_role_mode TEXT NOT NULL DEFAULT 'first_login_only'
+ CHECK (group_role_mode IN ('first_login_only', 'authoritative'));
+ALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS groups_claim TEXT NOT NULL DEFAULT '';
+ALTER TABLE aisoc_sso_connections ADD COLUMN IF NOT EXISTS login_label TEXT NOT NULL DEFAULT '';
+
+-- The `infosec` role: security analyst / incident handler. It is seeded per
+-- tenant in the application layer (the tenant set is dynamic), but the
+-- canonical definition lives in `app.core.security.ROLE_PERMISSIONS`; this
+-- seed covers tenants that predate the role so their admins can assign it
+-- through the RBAC endpoints immediately.
+INSERT INTO roles (tenant_id, name, description, is_system)
+SELECT t.id, 'infosec',
+ 'Security analyst / incident handler: triage, case handling, detections, threat intel, sanitized exports. No user/role/SSO/system management.',
+ TRUE
+ FROM tenants t
+ON CONFLICT (tenant_id, name) DO NOTHING;
diff --git a/services/api/tests/test_sso_enterprise_policy.py b/services/api/tests/test_sso_enterprise_policy.py
new file mode 100644
index 000000000..ae810973e
--- /dev/null
+++ b/services/api/tests/test_sso_enterprise_policy.py
@@ -0,0 +1,122 @@
+"""SSO enterprise-policy suite: role vocabulary, provisioning gates, flags.
+
+These tests lock the security properties of the SSO wave, not its shape:
+least-privilege defaults, fail-closed gates, auditable role changes, and the
+feature flag that keeps the whole surface shut until verified.
+"""
+from __future__ import annotations
+
+import pytest
+
+# ── role vocabulary ──────────────────────────────────────────────────────────
+
+
+def test_infosec_role_exists_and_is_least_privilege_analyst() -> None:
+ from app.core.security import ROLE_PERMISSIONS
+
+ infosec = set(ROLE_PERMISSIONS["infosec"])
+ # The spec floor: analyst work is fully available.
+ assert {"alerts:read", "alerts:write", "cases:read", "cases:write",
+ "threat_intel:read", "threat_intel:write", "rules:write",
+ "playbooks:execute", "lake:query", "reports:read"} <= infosec
+ # The ceiling: no user, role, settings, credential, audit or admin door.
+ forbidden = {"users:write", "users:delete", "roles:write", "roles:delete",
+ "settings:write", "api_keys:manage", "platform_admin",
+ "alert_source_raw:read", "audit:delete", "connectors:write"}
+ assert not (infosec & forbidden)
+
+
+def test_viewer_stays_the_floor_after_the_wave() -> None:
+ from app.core.security import ROLE_PERMISSIONS
+
+ viewer = set(ROLE_PERMISSIONS["viewer"])
+ assert "alerts:write" not in viewer
+ assert "users:write" not in viewer
+ assert "roles:write" not in viewer
+
+
+def test_infosec_is_grantable_and_admin_never_is() -> None:
+ from app.core import role_grants
+
+ assert "infosec" in role_grants.GRANTABLE_ROLES
+ assert "infosec" not in role_grants.never_grantable()
+ # Wildcard roles stay out of band no matter who asks — including the
+ # SSO group-mapping path, which draws from this same vocabulary.
+ assert "admin" in role_grants.never_grantable()
+ assert "platform_admin" in role_grants.never_grantable()
+
+
+# ── group → role mapping ─────────────────────────────────────────────────────
+
+
+def test_infosec_group_maps_above_viewer_and_below_analyst() -> None:
+ from app.auth.sso_provisioning import map_groups_to_role
+
+ mapping = {"AiSOC.Viewer": "viewer", "AiSOC.InfoSec": "infosec"}
+ assert map_groups_to_role(["AiSOC.InfoSec"], mapping) == "infosec"
+ # highest wins regardless of order
+ assert map_groups_to_role(["AiSOC.Viewer", "AiSOC.InfoSec"], mapping) == "infosec"
+ assert map_groups_to_role(["AiSOC.InfoSec", "AiSOC.Viewer"], mapping) == "infosec"
+
+
+def test_admin_group_mapping_is_refused_not_applied() -> None:
+ from app.auth.sso_provisioning import map_groups_to_role
+
+ # Even if an operator wires `admin` into the mapping (the endpoint
+ # rejects it upstream; this is the second door), provisioning itself
+ # falls back rather than conferring it.
+ assert map_groups_to_role(["admins"], {"admins": "admin"}) == "viewer"
+
+
+def test_default_role_is_viewer() -> None:
+ from app.auth.sso_provisioning import DEFAULT_ROLE
+
+ assert DEFAULT_ROLE == "viewer"
+
+
+# ── domain allowlist ─────────────────────────────────────────────────────────
+
+
+def test_domain_allowlist_fails_closed() -> None:
+ from app.auth.sso_provisioning import _domain_allowed, _parse_domain_allowlist
+
+ allowed = _parse_domain_allowlist("Example.COM, partner.io")
+ assert _domain_allowed("[email protected]", allowed)
+ assert _domain_allowed("[email protected]", allowed)
+ assert not _domain_allowed("[email protected]", allowed)
+ assert not _domain_allowed("nope", allowed)
+
+
+def test_sso_feature_flag_defaults_off(monkeypatch: pytest.MonkeyPatch) -> None:
+ from app.auth.oidc import _sso_feature_enabled
+
+ monkeypatch.delenv("SSO_ENABLED", raising=False)
+ assert not _sso_feature_enabled()
+ monkeypatch.setenv("SSO_ENABLED", "false")
+ assert not _sso_feature_enabled()
+ monkeypatch.setenv("SSO_ENABLED", "true")
+ assert _sso_feature_enabled()
+
+
+def test_status_endpoint_contract(monkeypatch: pytest.MonkeyPatch) -> None:
+ import asyncio
+
+ from app.api.v1.endpoints import auth as auth_ep
+
+ monkeypatch.delenv("SSO_ENABLED", raising=False)
+ monkeypatch.delenv("SSO_LOCAL_ADMIN_ONLY", raising=False)
+ monkeypatch.delenv("SSO_LOGIN_LABEL", raising=False)
+ out = asyncio.run(auth_ep.sso_status())
+ assert out["sso_enabled"] is False # hidden by default
+ assert out["local_login_enabled"] is True # break-glass stays open
+
+ monkeypatch.setenv("SSO_ENABLED", "true")
+ monkeypatch.setenv("SSO_LOGIN_LABEL", "Sign in with Acme")
+ out = asyncio.run(auth_ep.sso_status())
+ assert out["sso_enabled"] is True
+ assert out["login_label"] == "Sign in with Acme"
+ assert out["local_login_enabled"] is True # until the operator closes it
+
+ monkeypatch.setenv("SSO_LOCAL_ADMIN_ONLY", "true")
+ out = asyncio.run(auth_ep.sso_status())
+ assert out["local_login_enabled"] is False