ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
feat(auth): add enterprise multi-tenant SSO (SAML 2.0 & OIDC) and clean login UI
Mafifrizi5629433f8fdd
diff --git a/README.md b/README.mdindex 866e261..2e8c072 100644--- a/README.md+++ b/README.md@@ -109,6 +109,7 @@ The ARES Platform features a high-performance, responsive operator dashboard eng- **ARES Cyber Dragon Ambient Mascot**: Integrated brand mascot watermark on the telemetry pane with calibrated opacity and crimson back-glow, harmonized with frosted glass environment specs.- Live **Dynamic Architectural Grid Canvas**: Low-overhead hardware-accelerated 60 FPS HTML5 canvas with real-time traveling data pulses and cursor proximity illumination.- **Memory-Only Token Isolation**: Short-lived JWTs reside strictly in memory; refresh credentials use host-only, HttpOnly cookies with one-time rotation.+ - **Enterprise Multi-Tenant SSO (SAML 2.0 & OIDC)**: SP-initiated federated authentication with Okta, Azure AD, and Google Workspace. Features App-level Fernet credential encryption, one-time replay protection (`InResponseTo`/`nonce`), JIT role mapping, and strict local password lockout for federated identities. (See [**SSO Setup Guide**](docs/sso-setup.md)).- **HMAC Double-Submit CSRF Protection**: Constant-time verification on all state-mutating requests (`X-ARES-CSRF`).- **Cryptographic Brute-Force Shield**: Enforces exponential backoff and IP-based rate limiting on authentication attempts.@@ -438,6 +439,7 @@ Comprehensive documentation is available in the [`docs/`](docs/) directory:- [**Dashboard Surface-by-Surface Manual**](docs/dashboard-guide.md)- [**Adversary Module Catalog & Schemas**](docs/modules.md)- [**API Endpoint Reference & Payloads**](docs/api-reference.md)+- [**Enterprise SSO Integration Guide (SAML 2.0 / OIDC)**](docs/sso-setup.md)- [**Enterprise Security & Threat Model**](docs/security-model.md)- [**Validation Lab & Test Harness**](docs/validation-lab.md)- [**Module Authoring SDK Guide**](docs/module-development.md)diff --git a/ares/api/server.py b/ares/api/server.pyindex 8cad9ac..5d737a4 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -28,6 +28,7 @@ from uuid import UUIDfrom fastapi import (Depends,FastAPI,+ Form,HTTPException,Query,Request,@@ -37,7 +38,7 @@ from fastapi import ()from fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.trustedhost import TrustedHostMiddleware-from fastapi.responses import FileResponse, JSONResponse+from fastapi.responses import FileResponse, JSONResponse, RedirectResponsefrom fastapi.security import OAuth2PasswordRequestFormfrom pydantic import BaseModel, Field, field_validatorfrom starlette.exceptions import HTTPException as StarletteHTTPException@@ -88,6 +89,14 @@ from ares.core.token_sessions import (SessionIssueStatus,SessionRevocationStatus,)+from ares.core.sso import (+ build_oidc_auth_request,+ build_saml_auth_request,+ decrypt_sso_secret,+ encrypt_sso_secret,+ process_oidc_callback,+ process_saml_response,+)from ares.core.tracing import get_current_trace_id, instrument_fastapi, setup_tracingfrom ares.db.database import AresDatabasefrom ares.db.execution_lifecycle import FixedResult, TrustedPrincipal@@ -1020,9 +1029,17 @@ def _browser_context(request: Request) -> BrowserRequestContext:def _browser_policy(request: Request) -> BrowserSessionPolicy:policy = getattr(request.state, "browser_policy", None)- if not isinstance(policy, BrowserSessionPolicy):+ if isinstance(policy, BrowserSessionPolicy):+ return policy+ app_policy = getattr(request.app.state, "browser_policy", None)+ if isinstance(app_policy, BrowserSessionPolicy):+ return app_policy+ try:+ from ares.core.browser_sessions import build_browser_session_policy+ from ares.core.config import get_settings+ return build_browser_session_policy(get_settings())+ except Exception:raise HTTPException(503, "Browser authentication unavailable")- return policydef _token_response_content(session: Any, settings: AresSettings) -> dict[str, Any]:@@ -1088,6 +1105,10 @@ async def login(expires_minutes=settings.ares_jwt_expire_minutes,)+ user = await db.get_user(form.username)+ if user and user.get("auth_provider") in ("sso", "saml", "oidc"):+ raise HTTPException(401, "Invalid credentials")+try:result = await db.create_login_session(form.username,@@ -1378,6 +1399,354 @@ async def revoke_api_key(return {"status": "revoked"}+# ── Single Sign-On (SAML 2.0 / OIDC) ──────────────────────────────────────────++class SsoConfigRequest(BaseModel):+ protocol: str = Field(..., pattern=r"^(saml|oidc)$")+ issuer_or_entity_id: str = Field("", max_length=512)+ sso_url: str = Field("", max_length=1024)+ idp_certificate: str = Field("", max_length=10000)+ sp_entity_id: str = Field("", max_length=512)+ acs_url: str = Field("", max_length=1024)+ client_id: str = Field("", max_length=256)+ client_secret: str = Field("", max_length=1024)+ jwks_uri: str = Field("", max_length=1024)+ default_role: str = Field("reporter", pattern=r"^(team_lead|operator|recon|reporter)$")+ role_mapping: dict[str, str] = Field(default_factory=dict)+ is_enabled: bool = True++[email protected]("/auth/sso/init", tags=["auth"])+async def sso_initiate(+ request: Request,+ org: str = Query("default"),+ settings: AresSettings = Depends(get_settings),+ db: AresDatabase = Depends(get_db),+) -> dict[str, Any]:+ """Initiate SSO authentication flow for an organization."""+ organization = await db.get_organization(org)+ if not organization or not organization.get("is_active"):+ raise HTTPException(+ 400,+ detail="SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin.",+ )++ sso_config = await db.get_sso_config(organization["id"])+ if not sso_config or not sso_config.get("is_enabled"):+ raise HTTPException(+ 400,+ detail="SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin.",+ )++ base_url = str(request.base_url).rstrip("/")+ forwarded_proto = request.headers.get("x-forwarded-proto")+ forwarded_host = request.headers.get("x-forwarded-host")+ if forwarded_proto and forwarded_host:+ base_url = f"{forwarded_proto}://{forwarded_host}".rstrip("/")++ protocol = sso_config["protocol"]+ if protocol == "saml":+ try:+ redirect_url, request_id = build_saml_auth_request(sso_config, base_url, settings)+ except Exception as exc:+ logger.warning("sso_saml_init_failed", error=str(exc))+ raise HTTPException(400, detail="SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin.") from None++ await db.create_sso_flow_state(organization["id"], "saml", request_id, ttl_minutes=10)+ return {+ "configured": True,+ "protocol": "saml",+ "redirect_url": redirect_url,+ "flow_id": request_id,+ }++ elif protocol == "oidc":+ redirect_uri = f"{base_url}/auth/sso/oidc/callback"+ try:+ redirect_url, state, nonce = build_oidc_auth_request(sso_config, redirect_uri)+ except Exception as exc:+ logger.warning("sso_oidc_init_failed", error=str(exc))+ raise HTTPException(400, detail="SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin.") from None++ await db.create_sso_flow_state(organization["id"], "oidc", state, nonce=nonce, ttl_minutes=10)+ return {+ "configured": True,+ "protocol": "oidc",+ "redirect_url": redirect_url,+ "flow_id": state,+ }++ raise HTTPException(400, detail="Unsupported SSO protocol")++[email protected]("/auth/sso/saml/acs", tags=["auth"])+async def sso_saml_acs(+ request: Request,+ SAMLResponse: str = Form(...),+ RelayState: str = Form(None),+ settings: AresSettings = Depends(get_settings),+ db: AresDatabase = Depends(get_db),+) -> Response:+ """Assertion Consumer Service endpoint for SAML 2.0 (HTTP-POST binding)."""+ import base64+ from urllib.parse import quote+ from lxml import etree++ try:+ xml_bytes = base64.b64decode(SAMLResponse)+ parser = etree.XMLParser(resolve_entities=False, no_network=True)+ root = etree.fromstring(xml_bytes, parser=parser)+ in_response_to = root.get("InResponseTo") or ""+ if not in_response_to:+ scd = root.xpath("//*[local-name()='SubjectConfirmationData']")+ if scd and scd[0].get("InResponseTo"):+ in_response_to = scd[0].get("InResponseTo")+ except Exception as exc:+ logger.warning("saml_xml_parse_error", error=str(exc))+ return RedirectResponse(+ f"/dashboard/login?error={quote('Invalid SAML XML format')}",+ status_code=303,+ )++ if not in_response_to:+ logger.warning("saml_missing_in_response_to")+ return RedirectResponse(+ f"/dashboard/login?error={quote('SAML assertion missing InResponseTo (replay protection)')}",+ status_code=303,+ )++ flow_record = await db.consume_sso_flow_state(in_response_to, "saml")+ if not flow_record:+ logger.warning("saml_replay_or_invalid_flow", request_id=in_response_to)+ return RedirectResponse(+ f"/dashboard/login?error={quote('Invalid or expired SAML request ID (replay rejected)')}",+ status_code=303,+ )++ sso_config = await db.get_sso_config(flow_record["org_id"], protocol="saml")+ if not sso_config:+ return RedirectResponse(+ f"/dashboard/login?error={quote('SSO configuration not found for organization')}",+ status_code=303,+ )++ base_url = str(request.base_url).rstrip("/")+ try:+ profile = process_saml_response(+ sso_config,+ {"SAMLResponse": SAMLResponse, "RelayState": RelayState},+ in_response_to,+ base_url,+ settings,+ )+ except Exception as exc:+ logger.warning("saml_verification_failed", error=str(exc))+ return RedirectResponse(+ f"/dashboard/login?error={quote(str(exc))}",+ status_code=303,+ )++ user = await db.provision_or_get_sso_user(+ org_id=flow_record["org_id"],+ username=profile["username"],+ role=profile["role"],+ external_id=profile["external_id"],+ auth_provider="saml",+ )++ def _token_factory(claims: Mapping[str, Any]) -> str:+ return create_access_token(+ data=dict(claims),+ secret_key=settings.secret_key_value,+ algorithm=settings.ares_jwt_algorithm,+ expires_minutes=settings.ares_jwt_expire_minutes,+ )++ result = await db.create_sso_session(user["id"], _token_factory)+ if result.status is not SessionIssueStatus.ISSUED or result.session is None:+ return RedirectResponse(+ f"/dashboard/login?error={quote('Authentication service unavailable')}",+ status_code=303,+ )++ session = result.session+ target_path = RelayState if (RelayState and RelayState.startswith("/")) else "/dashboard/"+ response = RedirectResponse(target_path, status_code=303)+ publish_session_cookies(+ response,+ _browser_policy(request),+ refresh_token=session.refresh_token,+ absolute_expiry=session.absolute_expires_at,+ )+ return response++[email protected]("/auth/sso/oidc/callback", tags=["auth"])+async def sso_oidc_callback(+ request: Request,+ code: str = Query(None),+ state: str = Query(None),+ error: str = Query(None),+ error_description: str = Query(None),+ settings: AresSettings = Depends(get_settings),+ db: AresDatabase = Depends(get_db),+) -> Response:+ """Authorization Code callback for OpenID Connect."""+ from urllib.parse import quote++ if error:+ msg = error_description or error+ logger.warning("oidc_callback_error", error=msg)+ return RedirectResponse(f"/dashboard/login?error={quote(msg)}", status_code=303)++ if not code or not state:+ return RedirectResponse(+ f"/dashboard/login?error={quote('Missing code or state in OIDC response')}",+ status_code=303,+ )++ flow_record = await db.consume_sso_flow_state(state, "oidc")+ if not flow_record:+ logger.warning("oidc_replay_or_invalid_state", state=state)+ return RedirectResponse(+ f"/dashboard/login?error={quote('Invalid or expired OIDC state (replay rejected)')}",+ status_code=303,+ )++ sso_config = await db.get_sso_config(flow_record["org_id"], protocol="oidc")+ if not sso_config:+ return RedirectResponse(+ f"/dashboard/login?error={quote('SSO configuration not found for organization')}",+ status_code=303,+ )++ base_url = str(request.base_url).rstrip("/")+ redirect_uri = f"{base_url}/auth/sso/oidc/callback"++ try:+ profile = await process_oidc_callback(+ sso_config,+ code,+ redirect_uri,+ expected_nonce=flow_record.get("nonce") or "",+ settings=settings,+ )+ except Exception as exc:+ logger.warning("oidc_verification_failed", error=str(exc))+ return RedirectResponse(+ f"/dashboard/login?error={quote(str(exc))}",+ status_code=303,+ )++ user = await db.provision_or_get_sso_user(+ org_id=flow_record["org_id"],+ username=profile["username"],+ role=profile["role"],+ external_id=profile["external_id"],+ auth_provider="oidc",+ )++ def _token_factory(claims: Mapping[str, Any]) -> str:+ return create_access_token(+ data=dict(claims),+ secret_key=settings.secret_key_value,+ algorithm=settings.ares_jwt_algorithm,+ expires_minutes=settings.ares_jwt_expire_minutes,+ )++ result = await db.create_sso_session(user["id"], _token_factory)+ if result.status is not SessionIssueStatus.ISSUED or result.session is None:+ return RedirectResponse(+ f"/dashboard/login?error={quote('Authentication service unavailable')}",+ status_code=303,+ )++ session = result.session+ response = RedirectResponse("/dashboard/", status_code=303)+ publish_session_cookies(+ response,+ _browser_policy(request),+ refresh_token=session.refresh_token,+ absolute_expiry=session.absolute_expires_at,+ )+ return response++[email protected]("/auth/sso/config/{org_slug}", tags=["auth"])+async def get_sso_configuration(+ org_slug: str,+ actor: AuthenticatedUser = Depends(require_team_lead()),+ db: AresDatabase = Depends(get_db),+) -> dict[str, Any]:+ """Retrieve SSO configuration for an organization (admin only)."""+ org = await db.get_organization(org_slug)+ if not org:+ raise HTTPException(404, "Organization not found")++ cfg = await db.get_sso_config(org["id"])+ if not cfg:+ return {"configured": False, "organization": org}++ return {+ "configured": True,+ "organization": org,+ "protocol": cfg["protocol"],+ "is_enabled": bool(cfg["is_enabled"]),+ "issuer_or_entity_id": cfg["issuer_or_entity_id"],+ "sso_url": cfg["sso_url"],+ "sp_entity_id": cfg["sp_entity_id"],+ "acs_url": cfg["acs_url"],+ "client_id": cfg["client_id"],+ "jwks_uri": cfg["jwks_uri"],+ "default_role": cfg["default_role"],+ "role_mapping_json": cfg["role_mapping_json"],+ "has_certificate": bool(cfg["idp_certificate_enc"]),+ "has_client_secret": bool(cfg["client_secret_enc"]),+ }++[email protected]("/auth/sso/config/{org_slug}", tags=["auth"])+async def save_sso_configuration(+ org_slug: str,+ body: SsoConfigRequest,+ actor: AuthenticatedUser = Depends(require_team_lead()),+ settings: AresSettings = Depends(get_settings),+ db: AresDatabase = Depends(get_db),+) -> dict[str, Any]:+ """Save or update SSO configuration for an organization (admin only)."""+ org = await db.get_organization(org_slug)+ if not org:+ raise HTTPException(404, "Organization not found")++ idp_cert_enc = encrypt_sso_secret(body.idp_certificate, settings) if body.idp_certificate else ""+ client_sec_enc = encrypt_sso_secret(body.client_secret, settings) if body.client_secret else ""++ existing = await db.get_sso_config(org["id"], protocol=body.protocol)+ if existing:+ if not idp_cert_enc and existing.get("idp_certificate_enc"):+ idp_cert_enc = existing["idp_certificate_enc"]+ if not client_sec_enc and existing.get("client_secret_enc"):+ client_sec_enc = existing["client_secret_enc"]++ sso_id = await db.save_sso_config(+ org_id=org["id"],+ protocol=body.protocol,+ issuer_or_entity_id=body.issuer_or_entity_id,+ sso_url=body.sso_url,+ idp_certificate_enc=idp_cert_enc,+ sp_entity_id=body.sp_entity_id,+ acs_url=body.acs_url,+ client_id=body.client_id,+ client_secret_enc=client_sec_enc,+ jwks_uri=body.jwks_uri,+ default_role=body.default_role,+ role_mapping_json=json.dumps(body.role_mapping),+ is_enabled=1 if body.is_enabled else 0,+ )+ await db.audit(actor.username, "sso_config_saved", f"org={org_slug} protocol={body.protocol} id={sso_id}")+ return {"status": "saved", "sso_id": sso_id}++# ── Campaigns ─────────────────────────────────────────────────────────────────diff --git a/ares/core/security.py b/ares/core/security.pyindex 66a3801..e74dafc 100644--- a/ares/core/security.py+++ b/ares/core/security.py@@ -198,6 +198,9 @@ class DataEncryptor:def __init__(self, key: str) -> None:import os as _os+ if not key or len(key) < 32:+ raise ValueError("ARES_ENCRYPTION_KEY must be provided and at least 32 characters long")+self._raw_key = key.encode()self._salt = _os.urandom(16) # fresh random salt per instanceself._salt_hex = self._salt.hex() # 32 hex chars, used as ciphertext prefixdiff --git a/ares/core/sso.py b/ares/core/sso.pynew file mode 100644index 0000000..ed42d6b--- /dev/null+++ b/ares/core/sso.py@@ -0,0 +1,399 @@+"""+ARES Enterprise Single Sign-On (SSO) Core Service.+Supports SAML 2.0 (via python3-saml) and OpenID Connect (via authlib).+Features app-level secret encryption, JIT role mapping, and strict replay protection.+"""++from __future__ import annotations++import json+import secrets+import time+from typing import Any, Mapping+from urllib.parse import urlencode++import httpx+from authlib.jose import JsonWebKey, jwt as authlib_jwt+from onelogin.saml2.auth import OneLogin_Saml2_Auth+from onelogin.saml2.settings import OneLogin_Saml2_Settings++from ares.core.config import AresSettings+from ares.core.logger import get_logger+from ares.core.security import DataEncryptor++logger = get_logger("ares.core.sso")++_ALLOWED_ROLES = frozenset({"team_lead", "operator", "recon", "reporter"})+++# ── App-Level Secret Encryption ───────────────────────────────────────────────++def encrypt_sso_secret(secret: str | None, settings: AresSettings) -> str:+ """Encrypt sensitive credentials (X.509 certs, client secrets) using DataEncryptor."""+ if not secret:+ return ""+ encryptor = DataEncryptor(settings.encryption_key_value)+ encrypted = encryptor.encrypt(secret)+ return encrypted or ""+++def decrypt_sso_secret(encrypted_secret: str | None, settings: AresSettings) -> str:+ """Decrypt sensitive credentials using DataEncryptor."""+ if not encrypted_secret:+ return ""+ encryptor = DataEncryptor(settings.encryption_key_value)+ decrypted = encryptor.decrypt(encrypted_secret)+ return decrypted or ""+++# ── Role Mapping ─────────────────────────────────────────────────────────────++def map_idp_role(+ claims: Mapping[str, Any],+ role_mapping_json: str | None,+ default_role: str = "reporter",+) -> str:+ """+ Map IdP groups/roles to ARES roles.+ Strictly defaults to 'reporter' (least privilege) if no match is found.+ Never defaults to team_lead or operator.+ """+ safe_default = default_role if default_role in _ALLOWED_ROLES else "reporter"++ mapping: dict[str, str] = {}+ if role_mapping_json:+ try:+ parsed = json.loads(role_mapping_json)+ if isinstance(parsed, dict):+ mapping = {str(k): str(v) for k, v in parsed.items()}+ except Exception:+ logger.warning("sso_role_mapping_parse_failed")++ # Inspect common claim keys where IdP sends roles or groups+ candidate_groups: list[str] = []+ group_keys = (+ "roles",+ "groups",+ "role",+ "http://schemas.microsoft.com/ws/2008/06/identity/claims/groups",+ "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",+ "cognito:groups",+ )+ for key in group_keys:+ val = claims.get(key)+ if isinstance(val, list):+ candidate_groups.extend(str(item) for item in val)+ elif isinstance(val, str):+ candidate_groups.append(val)++ # Check realm_access / resource_access (Keycloak standard)+ realm_access = claims.get("realm_access")+ if isinstance(realm_access, dict):+ roles = realm_access.get("roles")+ if isinstance(roles, list):+ candidate_groups.extend(str(r) for r in roles)++ # Map candidate groups to ARES roles+ for group in candidate_groups:+ if group in mapping:+ target_role = mapping[group]+ if target_role in _ALLOWED_ROLES:+ return target_role++ # Direct match if IdP explicitly passed an ARES role name+ for group in candidate_groups:+ lowered = group.lower()+ if lowered in _ALLOWED_ROLES:+ return lowered++ return safe_default+++# ── SAML 2.0 Flow ─────────────────────────────────────────────────────────────++def _build_saml_settings_dict(+ sso_config: Mapping[str, Any],+ base_url: str,+ idp_cert: str,+) -> dict[str, Any]:+ """Construct python3-saml settings dictionary."""+ sp_entity_id = sso_config.get("sp_entity_id") or f"{base_url}/auth/sso/saml/metadata"+ acs_url = sso_config.get("acs_url") or f"{base_url}/auth/sso/saml/acs"+ idp_entity_id = sso_config.get("issuer_or_entity_id", "")+ sso_url = sso_config.get("sso_url", "")++ # Clean certificate formatting (remove PEM headers if present for python3-saml)+ clean_cert = idp_cert.replace("-----BEGIN CERTIFICATE-----", "")+ clean_cert = clean_cert.replace("-----END CERTIFICATE-----", "")+ clean_cert = clean_cert.replace("\r", "").replace("\n", "").strip()++ return {+ "strict": True,+ "debug": False,+ "sp": {+ "entityId": sp_entity_id,+ "assertionConsumerService": {+ "url": acs_url,+ "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST",+ },+ "NameIDFormat": "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified",+ "x509cert": "",+ "privateKey": "",+ },+ "idp": {+ "entityId": idp_entity_id,+ "singleSignOnService": {+ "url": sso_url,+ "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",+ },+ "x509cert": clean_cert,+ },+ "security": {+ "nameIdEncrypted": False,+ "authnRequestsSigned": False,+ "logoutRequestSigned": False,+ "logoutResponseSigned": False,+ "signMetadata": False,+ "wantMessagesSigned": False,+ "wantAssertionsSigned": True, # Require signed assertions+ "wantNameId": True,+ "wantNameIdEncrypted": False,+ "wantAssertionsEncrypted": False,+ "signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",+ "digestAlgorithm": "http://www.w3.org/2001/04/xmlenc#sha256",+ },+ }+++def build_saml_auth_request(+ sso_config: Mapping[str, Any],+ base_url: str,+ settings: AresSettings,+) -> tuple[str, str]:+ """+ Generate SAML AuthnRequest.+ Returns (redirect_url, request_id).+ """+ idp_cert = decrypt_sso_secret(sso_config.get("idp_certificate_enc"), settings)+ saml_settings_dict = _build_saml_settings_dict(sso_config, base_url, idp_cert)+ saml_settings = OneLogin_Saml2_Settings(saml_settings_dict)++ # Empty dummy request for OneLogin_Saml2_Auth initialization+ req = {+ "https": "on" if base_url.startswith("https") else "off",+ "http_host": base_url.split("://")[-1],+ "script_name": "/auth/sso/saml/acs",+ "get_data": {},+ "post_data": {},+ }+ auth = OneLogin_Saml2_Auth(req, old_settings=saml_settings)+ redirect_url = auth.login()+ request_id = auth.get_last_request_id()++ if not request_id:+ request_id = f"ARES_SAML_{secrets.token_hex(16)}"+ return redirect_url, request_id+++def process_saml_response(+ sso_config: Mapping[str, Any],+ post_data: dict[str, Any],+ expected_request_id: str,+ base_url: str,+ settings: AresSettings,+) -> dict[str, Any]:+ """+ Process SAML ACS response (HTTP-POST).+ Validates XML signature, expiration, and InResponseTo.+ Returns extracted user profile and mapped role.+ """+ idp_cert = decrypt_sso_secret(sso_config.get("idp_certificate_enc"), settings)+ saml_settings_dict = _build_saml_settings_dict(sso_config, base_url, idp_cert)+ saml_settings = OneLogin_Saml2_Settings(saml_settings_dict)++ req = {+ "https": "on" if base_url.startswith("https") else "off",+ "http_host": base_url.split("://")[-1],+ "script_name": "/auth/sso/saml/acs",+ "get_data": {},+ "post_data": post_data,+ }+ auth = OneLogin_Saml2_Auth(req, old_settings=saml_settings)+ auth.process_response(request_id=expected_request_id)++ errors = auth.get_errors()+ if errors:+ reason = auth.get_last_error_reason() or ", ".join(errors)+ logger.warning("saml_assertion_validation_failed", error=reason)+ raise ValueError(f"SAML assertion verification failed: {reason}")++ if not auth.is_authenticated():+ reason = auth.get_last_error_reason() or "Assertion not authenticated"+ logger.warning("saml_not_authenticated", error=reason)+ raise ValueError(f"SAML authentication rejected: {reason}")++ nameid = auth.get_nameid()+ attributes = auth.get_attributes()++ # Determine username/email from NameID and attributes+ email = ""+ email_keys = (+ "email",+ "mail",+ "userPrincipalName",+ "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress",+ )+ for ek in email_keys:+ val = attributes.get(ek)+ if val and isinstance(val, list) and len(val) > 0:+ email = str(val[0])+ break++ username = email.split("@")[0] if email and "@" in email else (nameid or f"saml_{secrets.token_hex(4)}")+ role = map_idp_role(+ attributes,+ sso_config.get("role_mapping_json"),+ default_role=sso_config.get("default_role", "reporter"),+ )++ return {+ "username": username,+ "email": email,+ "external_id": nameid,+ "role": role,+ "attributes": attributes,+ }+++# ── OpenID Connect (OIDC) Flow ───────────────────────────────────────────────++def build_oidc_auth_request(+ sso_config: Mapping[str, Any],+ redirect_uri: str,+) -> tuple[str, str, str]:+ """+ Generate OIDC authorization URL with state and nonce.+ Returns (authorization_url, state, nonce).+ """+ client_id = sso_config.get("client_id", "")+ auth_endpoint = sso_config.get("sso_url", "")+ if not auth_endpoint:+ raise ValueError("OIDC sso_url (authorization endpoint) is not configured")++ state = secrets.token_urlsafe(32)+ nonce = secrets.token_urlsafe(32)++ params = {+ "client_id": client_id,+ "response_type": "code",+ "scope": "openid profile email",+ "redirect_uri": redirect_uri,+ "state": state,+ "nonce": nonce,+ }+ delimiter = "&" if "?" in auth_endpoint else "?"+ redirect_url = f"{auth_endpoint}{delimiter}{urlencode(params)}"+ return redirect_url, state, nonce+++async def process_oidc_callback(+ sso_config: Mapping[str, Any],+ code: str,+ redirect_uri: str,+ expected_nonce: str,+ settings: AresSettings,+ http_client: httpx.AsyncClient | None = None,+) -> dict[str, Any]:+ """+ Process OIDC callback code.+ Exchanges code for tokens, validates ID token signature via JWKS,+ enforces iss, aud, exp, and nonce matching.+ """+ client_id = sso_config.get("client_id", "")+ client_secret = decrypt_sso_secret(sso_config.get("client_secret_enc"), settings)+ issuer = sso_config.get("issuer_or_entity_id", "")+ token_endpoint = sso_config.get("acs_url") # In OIDC, acs_url holds token_endpoint+ jwks_uri = sso_config.get("jwks_uri", "")++ if not token_endpoint:+ raise ValueError("OIDC token endpoint (acs_url) is not configured")++ client = http_client or httpx.AsyncClient(timeout=15.0)+ should_close = http_client is None++ try:+ # 1. Exchange authorization code for tokens+ token_resp = await client.post(+ token_endpoint,+ data={+ "grant_type": "authorization_code",+ "code": code,+ "redirect_uri": redirect_uri,+ "client_id": client_id,+ "client_secret": client_secret,+ },+ headers={"Accept": "application/json"},+ )+ if token_resp.status_code >= 400:+ logger.warning("oidc_token_exchange_failed", status=token_resp.status_code, text=token_resp.text)+ raise ValueError(f"OIDC token exchange failed: HTTP {token_resp.status_code}")++ token_data = token_resp.json()+ id_token = token_data.get("id_token")+ if not id_token:+ raise ValueError("OIDC response missing id_token")++ # 2. Fetch JWKS and verify signature+ if jwks_uri:+ jwks_resp = await client.get(jwks_uri)+ if jwks_resp.status_code >= 400:+ raise ValueError(f"Failed to fetch JWKS from {jwks_uri}")+ jwks = jwks_resp.json()+ key_set = JsonWebKey.import_key_set(jwks)+ claims = authlib_jwt.decode(id_token, key_set)+ else:+ # Fallback for mock/symmetric tests: decode without JWKS verification if jwks_uri is empty+ claims = authlib_jwt.decode(id_token, client_secret)++ # 3. Validate standard claims+ now = time.time()+ exp = claims.get("exp")+ if exp and exp < now:+ raise ValueError("OIDC id_token has expired")++ token_iss = claims.get("iss", "")+ if issuer and token_iss != issuer:+ raise ValueError(f"OIDC issuer mismatch: expected {issuer}, got {token_iss}")++ token_aud = claims.get("aud")+ if isinstance(token_aud, list):+ if client_id not in token_aud:+ raise ValueError(f"OIDC aud mismatch: client_id {client_id} not in {token_aud}")+ elif isinstance(token_aud, str):+ if token_aud != client_id:+ raise ValueError(f"OIDC aud mismatch: expected {client_id}, got {token_aud}")++ token_nonce = claims.get("nonce")+ if expected_nonce and token_nonce != expected_nonce:+ raise ValueError("OIDC nonce mismatch (replay protection triggered)")++ sub = str(claims.get("sub", ""))+ email = str(claims.get("email") or claims.get("preferred_username") or "")+ username = email.split("@")[0] if email and "@" in email else (claims.get("preferred_username") or sub)++ role = map_idp_role(+ claims,+ sso_config.get("role_mapping_json"),+ default_role=sso_config.get("default_role", "reporter"),+ )++ return {+ "username": username,+ "email": email,+ "external_id": sub,+ "role": role,+ "claims": dict(claims),+ }+ finally:+ if should_close:+ await client.aclose()diff --git a/ares/db/database.py b/ares/db/database.pyindex e64712e..5fd50d5 100644--- a/ares/db/database.py+++ b/ares/db/database.py@@ -775,6 +775,7 @@ class AresDatabase:if ownership.diagnostic.startswith("ARES-M2B-ADOPTION-READY:"):raise RuntimeError("SQLite database adoption is required")if ownership.diagnostic == "ARES-M2B-ALREADY-MANAGED:0011":+ await self._reconcile_sqlite_schema()await validate_sqlite_admission_authority_catalog_async(self._conn)returnif ownership.exit_code == AdoptionExit.MIGRATION_REQUIRED:@@ -792,6 +793,7 @@ class AresDatabase:raise RuntimeError("SQLite managed initialization failed") from Noneif managed.diagnostic != "ARES-M2B-ALREADY-MANAGED:0011":raise RuntimeError("SQLite managed initialization failed")+ await self._reconcile_sqlite_schema()await validate_sqlite_admission_authority_catalog_async(self._conn)return@@ -871,6 +873,86 @@ class AresDatabase:await self._conn.execute("CREATE INDEX IF NOT EXISTS idx_module_runs_completed ON module_runs(completed_at)")++ # ── Reconcile Organizations & SSO Tables ──────────────────────────────+ await self._conn.execute(+ """+ CREATE TABLE IF NOT EXISTS organizations (+ id TEXT PRIMARY KEY,+ slug TEXT NOT NULL UNIQUE,+ name TEXT NOT NULL,+ is_active INTEGER NOT NULL DEFAULT 1,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+ )+ """+ )+ await self._conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_organizations_slug ON organizations(slug)"+ )+ await self._conn.execute(+ """+ CREATE TABLE IF NOT EXISTS sso_configurations (+ id TEXT PRIMARY KEY,+ org_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,+ protocol TEXT NOT NULL CONSTRAINT ck_sso_protocol CHECK (protocol IN ('saml', 'oidc')),+ is_enabled INTEGER NOT NULL DEFAULT 1,+ issuer_or_entity_id TEXT NOT NULL DEFAULT '',+ sso_url TEXT NOT NULL DEFAULT '',+ idp_certificate_enc TEXT DEFAULT '',+ sp_entity_id TEXT DEFAULT '',+ acs_url TEXT DEFAULT '',+ client_id TEXT DEFAULT '',+ client_secret_enc TEXT DEFAULT '',+ jwks_uri TEXT DEFAULT '',+ default_role TEXT NOT NULL DEFAULT 'reporter',+ role_mapping_json TEXT NOT NULL DEFAULT '{}',+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),+ CONSTRAINT uq_sso_org_protocol UNIQUE (org_id, protocol)+ )+ """+ )+ await self._conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_sso_org ON sso_configurations(org_id)"+ )+ await self._conn.execute(+ """+ CREATE TABLE IF NOT EXISTS sso_flow_states (+ id TEXT PRIMARY KEY,+ org_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,+ flow_type TEXT NOT NULL CONSTRAINT ck_flow_type CHECK (flow_type IN ('saml', 'oidc')),+ flow_id TEXT NOT NULL UNIQUE,+ nonce TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ expires_at TEXT NOT NULL,+ is_consumed INTEGER NOT NULL DEFAULT 0,+ consumed_at TEXT+ )+ """+ )+ await self._conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_sso_flow_lookup ON sso_flow_states(flow_id, is_consumed, expires_at)"+ )++ # ── Reconcile users columns for SSO ──────────────────────────────────+ users_columns = await _columns("users")+ missing_users_columns = [+ ("org_id", "org_id TEXT REFERENCES organizations(id) ON DELETE SET NULL"),+ ("auth_provider", "auth_provider TEXT NOT NULL DEFAULT 'local'"),+ ("external_subject_id", "external_subject_id TEXT DEFAULT NULL"),+ ]+ for name, ddl in missing_users_columns:+ if name not in users_columns:+ await self._conn.execute(f"ALTER TABLE users ADD COLUMN {ddl}")+ users_columns.add(name)++ # Seed default organization if none exists+ async with self._conn.execute("SELECT id FROM organizations WHERE slug='default'") as cur:+ if await cur.fetchone() is None:+ await self._conn.execute(+ "INSERT INTO organizations(id, slug, name) VALUES('default-org-id', 'default', 'Default Organization')"+ )+await self._conn.commit()async def _validate_websocket_ticket_schema(self) -> None:@@ -2129,6 +2211,8 @@ class AresDatabase:async def verify_user(self, username: str, password: str) -> dict[str, Any] | None:user = await self.get_user(username)+ if user and user.get("auth_provider") in ("sso", "saml", "oidc"):+ return None# Always run bcrypt comparison to prevent username enumeration via timing attack.# If user not found, compare against a dummy hash so response time is constant._DUMMY_HASH = "$2b$12$notarealthashXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"@@ -2142,6 +2226,166 @@ class AresDatabase:await self._conn.commit()return user+ # ── SSO & Organizations ───────────────────────────────────────────────────++ async def get_organization(self, slug_or_id: str) -> dict[str, Any] | None:+ """Fetch organization by slug or UUID id."""+ async with self._conn.execute(+ "SELECT * FROM organizations WHERE slug=? OR id=?", (slug_or_id, slug_or_id)+ ) as cur:+ row = await cur.fetchone()+ return dict(row) if row else None++ async def get_sso_config(self, org_id: str, protocol: str | None = None) -> dict[str, Any] | None:+ """Fetch active SSO config for an organization."""+ if protocol:+ query = "SELECT * FROM sso_configurations WHERE org_id=? AND protocol=? AND is_enabled=1"+ params = (org_id, protocol)+ else:+ query = "SELECT * FROM sso_configurations WHERE org_id=? AND is_enabled=1 LIMIT 1"+ params = (org_id,)+ async with self._conn.execute(query, params) as cur:+ row = await cur.fetchone()+ return dict(row) if row else None++ async def save_sso_config(+ self,+ org_id: str,+ protocol: str,+ issuer_or_entity_id: str = "",+ sso_url: str = "",+ idp_certificate_enc: str = "",+ sp_entity_id: str = "",+ acs_url: str = "",+ client_id: str = "",+ client_secret_enc: str = "",+ jwks_uri: str = "",+ default_role: str = "reporter",+ role_mapping_json: str = "{}",+ is_enabled: int = 1,+ ) -> str:+ """Create or update an SSO configuration for an organization."""+ sso_id = str(uuid.uuid4())+ await self._conn.execute(+ """INSERT INTO sso_configurations(+ id, org_id, protocol, is_enabled, issuer_or_entity_id, sso_url,+ idp_certificate_enc, sp_entity_id, acs_url, client_id,+ client_secret_enc, jwks_uri, default_role, role_mapping_json, updated_at+ ) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))+ ON CONFLICT(org_id, protocol) DO UPDATE SET+ is_enabled=excluded.is_enabled,+ issuer_or_entity_id=excluded.issuer_or_entity_id,+ sso_url=excluded.sso_url,+ idp_certificate_enc=excluded.idp_certificate_enc,+ sp_entity_id=excluded.sp_entity_id,+ acs_url=excluded.acs_url,+ client_id=excluded.client_id,+ client_secret_enc=excluded.client_secret_enc,+ jwks_uri=excluded.jwks_uri,+ default_role=excluded.default_role,+ role_mapping_json=excluded.role_mapping_json,+ updated_at=datetime('now')""",+ (+ sso_id, org_id, protocol, is_enabled, issuer_or_entity_id, sso_url,+ idp_certificate_enc, sp_entity_id, acs_url, client_id,+ client_secret_enc, jwks_uri, default_role, role_mapping_json,+ ),+ )+ await self._conn.commit()+ return sso_id++ async def create_sso_flow_state(+ self,+ org_id: str,+ flow_type: str,+ flow_id: str,+ nonce: str = "",+ ttl_minutes: int = 10,+ ) -> str:+ """Record an ephemeral one-time SSO flow state (AuthnRequest ID or OIDC state)."""+ state_id = str(uuid.uuid4())+ expires_at = (datetime.now(timezone.utc) + timedelta(minutes=ttl_minutes)).isoformat()+ await self._conn.execute(+ """INSERT INTO sso_flow_states(id, org_id, flow_type, flow_id, nonce, expires_at)+ VALUES(?, ?, ?, ?, ?, ?)""",+ (state_id, org_id, flow_type, flow_id, nonce, expires_at),+ )+ await self._conn.commit()+ return state_id++ async def consume_sso_flow_state(+ self,+ flow_id: str,+ flow_type: str,+ ) -> dict[str, Any] | None:+ """Atomically validate and consume an SSO flow state, preventing replay attacks."""+ now_str = datetime.now(timezone.utc).isoformat()+ async with self._conn.execute(+ """SELECT * FROM sso_flow_states+ WHERE flow_id=? AND flow_type=? AND is_consumed=0 AND expires_at > ?""",+ (flow_id, flow_type, now_str),+ ) as cur:+ row = await cur.fetchone()+ if not row:+ return None+ record = dict(row)+ await self._conn.execute(+ "UPDATE sso_flow_states SET is_consumed=1, consumed_at=? WHERE id=?",+ (now_str, record["id"]),+ )+ await self._conn.commit()+ return record++ async def provision_or_get_sso_user(+ self,+ org_id: str,+ username: str,+ role: str = "reporter",+ external_id: str = "",+ auth_provider: str = "sso",+ ) -> dict[str, Any]:+ """JIT provision or look up an SSO user adhering to the canonical schema."""+ async with self._conn.execute(+ """SELECT * FROM users+ WHERE (external_subject_id=? AND external_subject_id IS NOT NULL AND external_subject_id != '')+ OR username=?""",+ (external_id, username),+ ) as cur:+ row = await cur.fetchone()++ if row:+ user = dict(row)+ updates = []+ params = []+ if external_id and not user.get("external_subject_id"):+ updates.append("external_subject_id=?")+ params.append(external_id)+ if role and role != user.get("role"):+ updates.append("role=?")+ params.append(role)+ if updates:+ params.append(user["id"])+ await self._conn.execute(+ f"UPDATE users SET {', '.join(updates)} WHERE id=?",+ tuple(params),+ )+ await self._conn.commit()+ async with self._conn.execute("SELECT * FROM users WHERE id=?", (user["id"],)) as cur:+ user = dict(await cur.fetchone())+ return user++ user_id = str(uuid.uuid4())+ dummy_hash = hash_password(secrets.token_urlsafe(32))+ await self._conn.execute(+ """INSERT INTO users(id, username, hashed_password, role, is_active, created_by, org_id, auth_provider, external_subject_id)+ VALUES(?, ?, ?, ?, 1, ?, ?, ?, ?)""",+ (user_id, username, dummy_hash, role, f"sso:{auth_provider}", org_id, auth_provider, external_id),+ )+ await self._conn.commit()+ logger.info("sso_user_provisioned", username=username, role=role, org_id=org_id, provider=auth_provider)+ async with self._conn.execute("SELECT * FROM users WHERE id=?", (user_id,)) as cur:+ return dict(await cur.fetchone())+async def user_exists(self, username: str) -> bool:async with self._conn.execute("SELECT 1 FROM users WHERE username=?", (username,)) as cur:return (await cur.fetchone()) is not None@@ -2930,7 +3174,7 @@ class AresDatabase:) -> SessionIssueResult:async def _login(tx: aiosqlite.Connection) -> SessionIssueResult:async with tx.execute(- "SELECT id,username,hashed_password,role,is_active,auth_epoch "+ "SELECT id,username,hashed_password,role,is_active,auth_epoch,auth_provider ""FROM users WHERE username=?",(username,),) as cursor:@@ -2938,6 +3182,7 @@ class AresDatabase:if (row is Noneor int(row["is_active"]) != 1+ or dict(row).get("auth_provider") in ("sso", "saml", "oidc")or not verify_password(password, row["hashed_password"])):return SessionIssueResult(SessionIssueStatus.INVALID)@@ -2982,6 +3227,63 @@ class AresDatabase:return await self._run_refresh_family_transaction(_login)+ async def create_sso_session(+ self,+ user_id: str,+ token_factory: AccessTokenFactory,+ ) -> SessionIssueResult:+ """Create authenticated session for an SSO-authenticated user."""+ async def _sso_login(tx: aiosqlite.Connection) -> SessionIssueResult:+ async with tx.execute(+ "SELECT id,username,role,is_active,auth_epoch "+ "FROM users WHERE id=?",+ (user_id,),+ ) as cursor:+ row = await cursor.fetchone()+ if row is None or int(row["is_active"]) != 1:+ return SessionIssueResult(SessionIssueStatus.INVALID)+ (+ family_id,+ raw_token,+ absolute_expiry,+ ) = await self._insert_initial_family_token_with_expiry(+ tx,+ user_id=row["id"],+ auth_epoch=int(row["auth_epoch"]),+ )+ access_token = token_factory(+ {+ "sub": row["username"],+ "sid": family_id,+ "ver": int(row["auth_epoch"]),+ }+ )+ await tx.execute(+ "UPDATE users SET last_login=? WHERE id=?",+ (format_sqlite_utc(datetime.now(timezone.utc)), row["id"]),+ )+ await tx.execute(+ "INSERT INTO audit_log(actor,action,detail) VALUES("+ "'auth-sso','sso_session_created',?)",+ (f"user_id={row['id']} username={row['username']}",),+ )+ return SessionIssueResult(+ SessionIssueStatus.ISSUED,+ IssuedTokenSession(+ access_token=access_token,+ refresh_token=raw_token,+ user_id=row["id"],+ subject=row["username"],+ family_id=family_id,+ auth_epoch=int(row["auth_epoch"]),+ absolute_expires_at=absolute_expiry,+ refresh_generation=0,+ role=row["role"],+ ),+ )++ return await self._run_refresh_family_transaction(_sso_login)+async def _legacy_create_refresh_token(self, user_id: str, expires_days: int = 30) -> str:import hashlibdiff --git a/ares/db/schema.py b/ares/db/schema.pyindex cb0b08e..3a3fec1 100644--- a/ares/db/schema.py+++ b/ares/db/schema.py@@ -452,6 +452,52 @@ CREATE INDEX IF NOT EXISTS idx_ws_tickets_api_keyON websocket_tickets(api_key_id);CREATE INDEX IF NOT EXISTS idx_ws_tickets_bearer_familyON websocket_tickets(bearer_family_id);++-- ── Organizations (★ Multi-tenant SSO) ───────────────────────────────────────+CREATE TABLE IF NOT EXISTS organizations (+ id TEXT PRIMARY KEY,+ slug TEXT NOT NULL UNIQUE,+ name TEXT NOT NULL,+ is_active INTEGER NOT NULL DEFAULT 1,+ created_at TEXT NOT NULL DEFAULT (datetime('now'))+);+CREATE INDEX IF NOT EXISTS idx_organizations_slug ON organizations(slug);++-- ── SSO Configurations ────────────────────────────────────────────────────────+CREATE TABLE IF NOT EXISTS sso_configurations (+ id TEXT PRIMARY KEY,+ org_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,+ protocol TEXT NOT NULL CONSTRAINT ck_sso_protocol CHECK (protocol IN ('saml', 'oidc')),+ is_enabled INTEGER NOT NULL DEFAULT 1,+ issuer_or_entity_id TEXT NOT NULL DEFAULT '',+ sso_url TEXT NOT NULL DEFAULT '',+ idp_certificate_enc TEXT DEFAULT '',+ sp_entity_id TEXT DEFAULT '',+ acs_url TEXT DEFAULT '',+ client_id TEXT DEFAULT '',+ client_secret_enc TEXT DEFAULT '',+ jwks_uri TEXT DEFAULT '',+ default_role TEXT NOT NULL DEFAULT 'reporter',+ role_mapping_json TEXT NOT NULL DEFAULT '{}',+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ updated_at TEXT NOT NULL DEFAULT (datetime('now')),+ CONSTRAINT uq_sso_org_protocol UNIQUE (org_id, protocol)+);+CREATE INDEX IF NOT EXISTS idx_sso_org ON sso_configurations(org_id);++-- ── Ephemeral One-Time SSO Flow States (Anti-Replay / CSRF) ─────────────────+CREATE TABLE IF NOT EXISTS sso_flow_states (+ id TEXT PRIMARY KEY,+ org_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,+ flow_type TEXT NOT NULL CONSTRAINT ck_flow_type CHECK (flow_type IN ('saml', 'oidc')),+ flow_id TEXT NOT NULL UNIQUE,+ nonce TEXT,+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ expires_at TEXT NOT NULL,+ is_consumed INTEGER NOT NULL DEFAULT 0,+ consumed_at TEXT+);+CREATE INDEX IF NOT EXISTS idx_sso_flow_lookup ON sso_flow_states(flow_id, is_consumed, expires_at);""" + sqlite_lifecycle_runtime_script() + sqlite_admission_authority_runtime_script()# ── Migration: v4 → v5 ────────────────────────────────────────────────────────diff --git a/docs/assets/screenshots/dashboard-campaigns.png b/docs/assets/screenshots/dashboard-campaigns.pngindex 2b6447d..3c3f34d 100644Binary files a/docs/assets/screenshots/dashboard-campaigns.png and b/docs/assets/screenshots/dashboard-campaigns.png differdiff --git a/docs/assets/screenshots/dashboard-graph.png b/docs/assets/screenshots/dashboard-graph.pngindex 4b729dc..af02a66 100644Binary files a/docs/assets/screenshots/dashboard-graph.png and b/docs/assets/screenshots/dashboard-graph.png differdiff --git a/docs/assets/screenshots/dashboard-modules-catalog.png b/docs/assets/screenshots/dashboard-modules-catalog.pngindex 7f1db11..9627fe4 100644Binary files a/docs/assets/screenshots/dashboard-modules-catalog.png and b/docs/assets/screenshots/dashboard-modules-catalog.png differdiff --git a/docs/assets/screenshots/dashboard-overview.png b/docs/assets/screenshots/dashboard-overview.pngindex 9f8452c..2a8252e 100644Binary files a/docs/assets/screenshots/dashboard-overview.png and b/docs/assets/screenshots/dashboard-overview.png differdiff --git a/docs/assets/screenshots/dashboard-reports.png b/docs/assets/screenshots/dashboard-reports.pngindex c61ce98..d25c494 100644Binary files a/docs/assets/screenshots/dashboard-reports.png and b/docs/assets/screenshots/dashboard-reports.png differdiff --git a/docs/assets/screenshots/dashboard-strategy.png b/docs/assets/screenshots/dashboard-strategy.pngindex 5711a09..7e7933b 100644Binary files a/docs/assets/screenshots/dashboard-strategy.png and b/docs/assets/screenshots/dashboard-strategy.png differdiff --git a/docs/assets/screenshots/login-enclave.png b/docs/assets/screenshots/login-enclave.pngindex d07bb03..3e0bb2f 100644Binary files a/docs/assets/screenshots/login-enclave.png and b/docs/assets/screenshots/login-enclave.png differdiff --git a/docs/sso-setup.md b/docs/sso-setup.mdnew file mode 100644index 0000000..47657d3--- /dev/null+++ b/docs/sso-setup.md@@ -0,0 +1,204 @@+# Panduan & Setup Single Sign-On (SSO) Enterprise — ARES Dashboard++Dokumen ini menjelaskan penggunaan dan konfigurasi **Enterprise Multi-Tenant SSO (SAML 2.0 & OpenID Connect)** di ARES Dashboard, baik untuk pengguna akhir (operator/pentester) maupun administrator sistem.++---++## BAGIAN 1 — Panduan Untuk Pengguna (End-User)++### Kapan Menggunakan "Sign in" Biasa vs "Or continue with SSO"?++| Metode Login | Kapan Digunakan? | Kredensial yang Digunakan |+| :--- | :--- | :--- |+| **"Sign in" Biasa** | Digunakan untuk akun lokal/internal (misalnya akun superadmin awal `admin` atau operator lab yang dibuat langsung di database lokal ARES). | Username dan password lokal yang tersimpan di database ARES (dienkripsi dengan bcrypt). |+| **"Or continue with SSO"** | Digunakan jika organisasi/perusahaan Anda mengelola identitas terpusat melalui Identity Provider (IdP) seperti Okta, Google Workspace, Microsoft Entra ID (Azure AD), Ping Identity, atau Keycloak. | Kredensial akun kantor/organisasi Anda di halaman login resmi IdP Anda. |++> [!NOTE]+> **Proteksi Keamanan Akun SSO**: Jika akun Anda telah terdaftar sebagai pengguna SSO (`auth_provider = 'saml'` atau `'oidc'`), akun Anda **secara otomatis ditolak** jika mencoba login melalui form password lokal. Anda wajib masuk menggunakan tombol **"Or continue with SSO"**.++### Pesan: *"SSO belum dikonfaktorasi untuk organisasi ini. Hubungi admin."*++Jika Anda mengklik tombol **"Or continue with SSO"** dan muncul pesan peringatan warna amber:+> ⚠️ **SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin.**++**Artinya:**+1. Profil SSO (SAML 2.0 atau OIDC) untuk organisasi Anda belum didaftarkan di database ARES atau statusnya sedang dinonaktifkan (`is_enabled = 0`).+2. Backend ARES menolak memulai alur federasi karena tidak memiliki endpoint IdP, sertifikat x.509, atau client ID yang valid.++**Langkah yang Harus Diambil:**+- Jangan mencoba menebak password di form lokal.+- Hubungi Administrator ARES atau tim Security Operations (SecOps) organisasi Anda dan minta mereka mengonfigurasi federasi identitas organisasi Anda mengikuti panduan Bagian 2 di bawah.++---++## BAGIAN 2 — Panduan Untuk Administrator: Setup SSO Organisasi Baru++### 1. Prasyarat: Environment Variable `ARES_ENCRYPTION_KEY`++ARES menerapkan enkripsi tingkat aplikasi (*app-level encryption*) menggunakan modul `DataEncryptor` (berbasis Fernet: `PBKDF2-HMAC-SHA256` 100.000 iterasi + `AES-128-CBC` + `HMAC-SHA256` dengan *salt* acak unik per *record*). Semua sertifikat SAML dan secret OIDC disimpan dalam bentuk terenkripsi di database.++Aplikasi mewajibkan `ARES_ENCRYPTION_KEY` memiliki panjang **minimal 32 karakter**. Jika tidak diset atau kurang dari 32 karakter, ARES akan menolak *startup*.++#### Cara Generate Kunci:+Jalankan perintah Python berikut:+```bash+python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"+```+*Contoh output: `16R2yRp-PWlbNT49xq6sZzp39ArxJJ7Tlap1MqYWp3w=`*++#### Cara Set Environment Variable:+- **Di file `.env` (disarankan):**+ ```env+ ARES_ENCRYPTION_KEY=16R2yRp-PWlbNT49xq6sZzp39ArxJJ7Tlap1MqYWp3w=+ ```+- **Di Linux / macOS (Terminal):**+ ```bash+ export ARES_ENCRYPTION_KEY="16R2yRp-PWlbNT49xq6sZzp39ArxJJ7Tlap1MqYWp3w="+ ```+- **Di Windows (PowerShell):**+ ```powershell+ $env:ARES_ENCRYPTION_KEY="16R2yRp-PWlbNT49xq6sZzp39ArxJJ7Tlap1MqYWp3w="+ ```++---++### 2. Mendaftarkan Konfigurasi SSO ke ARES++Pendaftaran konfigurasi SSO dapat dilakukan melalui **REST API Endpoint Admin** (memerlukan role `team_lead`, yaitu tingkatan role tertinggi dalam hierarki ARES: `team_lead > operator > recon > reporter`; akun bootstrap `admin` secara default memiliki role `team_lead`) atau langsung ke database jika API gateway belum diakses.++> [!IMPORTANT]+> **Kebijakan Arsitektur: SP-Initiated SSO Only**+> ARES saat ini **hanya mendukung SP-initiated SSO**. User harus selalu memulai login dari halaman ARES (klik tombol *"Or continue with SSO"*), bukan dari portal aplikasi IdP mereka (seperti dashboard Okta atau My Apps Azure AD / Entra ID).+> **Sampaikan hal ini ke tim IT organisasi saat onboarding SSO mereka**, karena ini berbeda dari flow yang biasa mereka pakai untuk aplikasi SaaS lain. ARES secara ketat menolak SAML response tanpa parameter `InResponseTo` yang valid serta callback OIDC tanpa token `state` yang terdaftar demi mencegah serangan pemalsuan sesi dan token replay.++#### Opsi A: Melalui REST API Admin (Direkomendasikan)+ARES menyediakan endpoint manajemen SSO (khusus role `team_lead`):+- **`GET /auth/sso/config/{org_slug}`**: Melihat status konfigurasi SSO organisasi.+- **`POST /auth/sso/config/{org_slug}`**: Menyimpan atau memperbarui konfigurasi SSO organisasi.++Format request payload `POST /auth/sso/config/{org_slug}`:+```json+{+ "protocol": "saml", // atau "oidc"+ "issuer_or_entity_id": "https://idp.example.com/entityid",+ "sso_url": "https://idp.example.com/sso/endpoint",+ "idp_certificate": "-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----",+ "client_id": "",+ "client_secret": "",+ "jwks_uri": "",+ "default_role": "reporter",+ "role_mapping": {+ "SecurityAdmins": "team_lead",+ "RedTeam": "operator",+ "Auditors": "reporter"+ },+ "is_enabled": true+}+```+*Catatan: Backend ARES akan secara otomatis mengenkripsi `idp_certificate` dan `client_secret` menggunakan Fernet `DataEncryptor` sebelum menyimpannya ke tabel `sso_configurations`.*++#### Opsi B: Melalui Database SQL Langsung+Jika mendaftarkan langsung melalui SQLite (`ares.db`) atau PostgreSQL:+1. Pastikan organisasi terdaftar di tabel `organizations`:+ ```sql+ INSERT INTO organizations (id, slug, name, is_active)+ VALUES ('org-corp-01', 'corp', 'ACME Corp', 1);+ ```+2. Nilai kolom `idp_certificate_enc` atau `client_secret_enc` harus dienkripsi terlebih dahulu menggunakan helper ARES:+ ```bash+ python -c "from ares.core.config import get_settings; from ares.core.sso import encrypt_sso_secret; print(encrypt_sso_secret('YOUR_SECRET_HERE', get_settings()))"+ ```+3. Masukkan ke tabel `sso_configurations`:+ ```sql+ INSERT INTO sso_configurations (+ id, org_id, protocol, is_enabled,+ issuer_or_entity_id, sso_url, idp_certificate_enc,+ default_role, role_mapping_json+ ) VALUES (+ 'sso-cfg-01', 'org-corp-01', 'saml', 1,+ 'https://idp.example.com/entityid', 'https://idp.example.com/sso', 'HASIL_ENKRIPSI',+ 'reporter', '{"SecAdmins": "team_lead"}'+ );+ ```++---++### 3. Detail Integrasi Protokol SAML 2.0++#### A. Data yang Harus Disiapkan Organisasi dari IdP Mereka:+1. **IdP Entity ID**: URI pengenal unik IdP (misal: `https://sts.windows.net/tenant-uuid/` atau `http://www.okta.com/exk123`).+2. **SSO URL (Single Sign-On Service URL)**: Endpoint HTTP-Redirect atau HTTP-POST milik IdP tempat user diarahkan untuk autentikasi.+3. **IdP x.509 Certificate**: Sertifikat publik IdP dalam format PEM untuk memvalidasi tanda tangan digital (*signature*) XML assertion.++#### B. Data yang Diberikan ARES ke IdP Organisasi:+- **Assertion Consumer Service (ACS) URL**:+ ```+ POST https://<domain-ares>/auth/sso/saml/acs+ ```+ *(Binding: HTTP-POST)*+- **Service Provider (SP) Entity ID / Audience**:+ ```+ https://<domain-ares>/auth/sso/saml/metadata+ ```+- **NameID Format**: Email Address (`urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress`) atau Persistent (`urn:oasis:names:tc:SAML:2.0:nameid-format:persistent`).++---++### 4. Detail Integrasi Protokol OpenID Connect (OIDC)++#### A. Data yang Harus Disiapkan Organisasi dari IdP Mereka:+1. **Issuer URL**: Base URL penyedia identitas (misal: `https://accounts.google.com` atau `https://login.microsoftonline.com/{tenant}/v2.0`).+2. **Client ID & Client Secret**: Kredensial client yang digenerate oleh IdP saat membuat aplikasi ARES.+3. **JWKS URI (Opsional/Direkomendasikan)**: Endpoint kunci publik IdP (misal: `https://idp.example.com/.well-known/jwks.json`) untuk verifikasi tanda tangan ID Token JWT.+4. **Authorization & Token Endpoint**: Endpoint otorisasi OAuth2/OIDC dari IdP.++#### B. Data yang Diberikan ARES ke IdP Organisasi:+- **Redirect URI / Callback URL**:+ ```+ GET https://<domain-ares>/auth/sso/oidc/callback+ ```+- **Response Type**: `code` (Authorization Code Flow).+- **Scope**: `openid email profile`.++---++### 5. Cara Pengujian & Verifikasi (Tanpa Buka Database)++Setelah konfigurasi disimpan, lakukan verifikasi melalui browser:++1. **Cek Respons Endpoint Inisialisasi**:+ Akses di browser atau `curl`:+ ```bash+ curl -i "http://127.0.0.1:8080/auth/sso/init?org=default"+ ```+ **Indikator Sukses**: Mengembalikan status HTTP `200 OK` dengan payload:+ ```json+ {+ "configured": true,+ "protocol": "saml", // atau "oidc"+ "redirect_url": "https://idp.example.com/...",+ "flow_id": "..."+ }+ ```++2. **Uji Melalui UI ARES Dashboard**:+ - Buka `http://127.0.0.1:5173/dashboard/login`.+ - Klik tombol **"Or continue with SSO"**.+ - Browser akan langsung mengarahkan Anda ke halaman login IdP Anda (Okta, Azure AD, atau Google).+ - Masukkan kredensial IdP Anda hingga selesai.+ - IdP akan me-redirect kembali ke ARES, dan Anda akan langsung masuk ke halaman utama Dashboard (`/dashboard/`) dengan sesi login aktif (cookie `ares-dev-refresh` dan `ares-dev-csrf` terpasang).+ - Akun Anda akan otomatis dibuat secara *Just-In-Time* (JIT) di ARES dengan role sesuai mapping atau default (`reporter`).++---++## BAGIAN 3 — Troubleshooting Singkat untuk Admin++Berikut adalah daftar pesan error umum yang dapat muncul pada URL login (`/dashboard/login?error=...`) dan penjelasan solusinya:++| Pesan Error di Login Page | Penyebab Utama | Solusi Tindakan Admin |+| :--- | :--- | :--- |+| **`Invalid or expired OIDC state (replay rejected)`** atau<br>**`Invalid or expired SAML request ID (replay rejected)`** | User membutuhkan waktu lebih dari 10 menit untuk menyelesaikan login di halaman IdP, atau user menekan tombol **Back**, me-refresh halaman callback, atau mencoba memakai link callback yang sama dua kali. | Minta user untuk kembali ke halaman `/dashboard/login` dan mengklik kembali tombol **"Or continue with SSO"** untuk menghasilkan sesi autentikasi baru yang aman. |+| **`SAML assertion missing InResponseTo (replay protection)`** | IdP mengirimkan SAML Assertion tanpa menyertakan ID AuthnRequest asal (*InResponseTo*), yang umumnya terjadi jika login dimulai dari portal IdP (*IdP-initiated SSO*). | ARES secara ketat hanya mengizinkan alur *SP-initiated SSO* demi mencegah serangan replay token SAML. Pastikan user selalu memulai login dari halaman login ARES Dashboard. |+| **`Invalid SAML signature`** atau<br>**`Signature validation failed`** | Sertifikat x.509 IdP yang tersimpan di ARES tidak cocok dengan sertifikat private key yang dipakai IdP saat menandatangani respons SAML (misalnya sertifikat IdP baru saja di-renew atau expired). | Dapatkan sertifikat x.509 publik terbaru dari IdP dan perbarui melalui endpoint `POST /auth/sso/config/{org_slug}` atau update kolom `idp_certificate_enc`. |+| **`Invalid token issuer or audience`** (OIDC) | Klaim `iss` (issuer) atau `aud` (audience) pada ID Token OIDC yang dikirim IdP tidak sesuai dengan `issuer_or_entity_id` atau `client_id` yang terdaftar di konfigurasi ARES. | Periksa kembali apakah nilai `client_id` dan `issuer_or_entity_id` di konfigurasi SSO ARES sudah sama persis dengan yang tertera di konsol IdP Anda. |+| **`SSO configuration not found for organization`** | Organisasi yang diminta tidak memiliki konfigurasi SSO aktif, atau organisasi tersebut berstatus dinonaktifkan (`is_active = 0`). | Pastikan organisasi aktif di tabel `organizations` dan memiliki konfigurasi di tabel `sso_configurations` dengan `is_enabled = 1`. |diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex 7f20dcd..49e4dd8 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -8,7 +8,7 @@ export {refreshAccessToken,withRefreshCookieLock} from "./http";-export { api, buildModuleRunPayload, campaignEventsPath, login, logout, logoutAll } from "./endpoints";+export { api, buildModuleRunPayload, campaignEventsPath, initiateSso, login, logout, logoutAll } from "./endpoints";export {beginIdentityTransition,browserCoordinationAvailable,diff --git a/frontend/src/api/endpoints.ts b/frontend/src/api/endpoints.tsindex c0ca3ed..0c9fd65 100644--- a/frontend/src/api/endpoints.ts+++ b/frontend/src/api/endpoints.ts@@ -136,6 +136,20 @@ export async function login(username: string, password: string): Promise<TokenRereturn token;}+export interface SsoInitiationResponse {+ configured: boolean;+ protocol: "saml" | "oidc";+ redirect_url: string;+ flow_id: string;+}++export async function initiateSso(orgSlug: string = "default"): Promise<SsoInitiationResponse> {+ const query = new URLSearchParams({ org: orgSlug });+ return apiRequest<SsoInitiationResponse>(`/auth/sso/init?${query.toString()}`, {+ method: "GET"+ });+}+export async function logout(): Promise<void> {clearPendingLiveSubmissions();await withRefreshCookieLock(async () => {diff --git a/frontend/src/features/auth/AresIgniteButton.tsx b/frontend/src/features/auth/AresIgniteButton.tsxindex 20daf52..6f35e62 100644--- a/frontend/src/features/auth/AresIgniteButton.tsx+++ b/frontend/src/features/auth/AresIgniteButton.tsx@@ -1,4 +1,4 @@-import { Loader2 } from "lucide-react";+import { Loader2 } from "lucide-react";import { ButtonHTMLAttributes, ReactNode, useEffect, useRef, useState } from "react";interface FireParticle {@@ -72,9 +72,10 @@ function spawnEdgeParticles(}export function AresIgniteButton({- isLoading,+ isLoading = false,children,disabled,+ className = "",...props}: AresIgniteButtonProps) {const wrapRef = useRef<HTMLDivElement>(null);@@ -87,7 +88,12 @@ export function AresIgniteButton({useEffect(() => {const canvas = canvasRef.current;if (!canvas) return;- const ctx = canvas.getContext("2d");+ let ctx: CanvasRenderingContext2D | null = null;+ try {+ ctx = canvas.getContext("2d");+ } catch {+ return;+ }if (!ctx) return;function tick() {@@ -119,11 +125,9 @@ export function AresIgniteButton({p.x += p.vx;p.y += p.vy;- // Very gentle buoyancy — keep fire hugging button, not flying away+ // Gentle buoyancy — fire hugs buttonp.vy -= 0.06;- // Slight turbulencep.vx += (Math.random() - 0.5) * 0.18;- // Damp horizontal so fire doesn't drift too far sidewaysp.vx *= 0.97;p.size *= 0.965;p.life -= 1 / p.maxLife;@@ -136,7 +140,7 @@ export function AresIgniteButton({const alpha = Math.pow(p.life, 0.7);const r = Math.max(0.1, p.size);- // Outer glow — soft halo hugging edge+ // Outer flame glowconst glow = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, r * 2.8);glow.addColorStop(0, `hsla(${p.hue}, 100%, 65%, ${alpha * 0.45})`);glow.addColorStop(0.5, `hsla(${p.hue}, 100%, 45%, ${alpha * 0.2})`);@@ -146,7 +150,7 @@ export function AresIgniteButton({ctx.fillStyle = glow;ctx.fill();- // Inner bright core — white-yellow at center, red at edge+ // Inner bright flame coreconst core = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, r);core.addColorStop(0, `hsla(${p.hue + 25}, 100%, 92%, ${alpha})`);core.addColorStop(0.35, `hsla(${p.hue + 10}, 100%, 65%, ${alpha * 0.85})`);@@ -165,7 +169,7 @@ export function AresIgniteButton({return () => cancelAnimationFrame(rafRef.current);}, []);- // Burst fire on Enter key (even without hover)+ // Burst fire on Enter keyuseEffect(() => {function onKeyDown(e: KeyboardEvent) {if (e.key === "Enter" && !disabled && !isLoading) {@@ -189,7 +193,7 @@ export function AresIgniteButton({setIsHovering(false);}- // Also burst on click for instant impact+ // Burst fire on clickfunction handleMouseDown() {if (disabled || isLoading) return;const wrap = wrapRef.current;@@ -214,24 +218,25 @@ export function AresIgniteButton({onMouseLeave={handleMouseLeave}onMouseDown={handleMouseDown}className={[- "relative z-10 w-full flex items-center justify-center gap-2 rounded-md px-4 py-2.5 text-sm font-semibold",- "transition-all duration-300",- "focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950",- "disabled:cursor-not-allowed",+ "relative z-10 w-full flex items-center justify-center gap-2 rounded-md px-4 py-2.5 text-sm font-medium text-white select-none",+ "transition-all duration-200 ease-out",+ "focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500/60 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-950",+ "disabled:opacity-50 disabled:cursor-not-allowed",isLoading- ? "bg-zinc-950 text-red-400 border border-red-800/60 disabled:opacity-100 focus-visible:ring-red-800/60"+ ? "bg-zinc-900 border border-zinc-800 text-zinc-400": [- "bg-zinc-100 text-zinc-950 shadow-sm",- "active:scale-[0.98] focus-visible:ring-zinc-400 disabled:opacity-50",+ "bg-[#A32D2D] border border-[#C43D3D] shadow-sm",+ "active:bg-[#8E2525] active:scale-[0.98]",isHovering- ? "bg-white shadow-[0_0_22px_4px_rgba(220,38,38,0.45)]"- : "hover:bg-white",+ ? "bg-[#B83535] border-[#D94545] shadow-[0_0_20px_3px_rgba(196,61,61,0.45)]"+ : "hover:bg-[#B83535]",].join(" "),- ].join(" ")}+ className,+ ].filter(Boolean).join(" ")}>{isLoading ? (<>- <Loader2 size={15} className="animate-spin text-red-500 shrink-0" />+ <Loader2 size={15} className="animate-spin text-red-400 shrink-0" /><span>Authenticating...</span></>) : (diff --git a/frontend/src/features/auth/LoginPage.tsx b/frontend/src/features/auth/LoginPage.tsxindex bfdfedd..ec716a9 100644--- a/frontend/src/features/auth/LoginPage.tsx+++ b/frontend/src/features/auth/LoginPage.tsx@@ -1,6 +1,7 @@import { AlertCircle, Eye, EyeOff } from "lucide-react";-import { FormEvent, useState } from "react";+import { FormEvent, useEffect, useState } from "react";import { Navigate, useNavigate } from "react-router-dom";+import { initiateSso } from "../../api/client";import { AresIgniteButton } from "./AresIgniteButton";import { BackgroundAnimationCanvas } from "./BackgroundAnimationCanvas";import { useAuth } from "./authContext";@@ -13,18 +14,29 @@ export function LoginPage() {const [password, setPassword] = useState("");const [showPassword, setShowPassword] = useState(false);const [isSubmitting, setIsSubmitting] = useState(false);+ const [isSsoLoading, setIsSsoLoading] = useState(false);const [error, setError] = useState("");+ const [ssoError, setSsoError] = useState("");const { login, user } = useAuth();const navigate = useNavigate();+ useEffect(() => {+ const searchParams = new URLSearchParams(window.location.search);+ const urlErr = searchParams.get("error");+ if (urlErr) {+ setError(urlErr);+ }+ }, []);+if (user) {return <Navigate to="/" replace />;}async function submit(event: FormEvent) {event.preventDefault();- if (isSubmitting) return;+ if (isSubmitting || isSsoLoading) return;setError("");+ setSsoError("");setIsSubmitting(true);try {await login(username, password);@@ -35,6 +47,25 @@ export function LoginPage() {}}+ async function handleSso() {+ if (isSubmitting || isSsoLoading) return;+ setError("");+ setSsoError("");+ setIsSsoLoading(true);+ try {+ const res = await initiateSso("default");+ if (res?.redirect_url) {+ window.location.href = res.redirect_url;+ } else {+ setSsoError("SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin.");+ }+ } catch (exc) {+ setSsoError("SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin.");+ } finally {+ setIsSsoLoading(false);+ }+ }+return (<div className="min-h-[100dvh] w-full bg-[#09090b] text-[#f4f4f5] grid lg:grid-cols-2 selection:bg-red-700 selection:text-white">@@ -74,7 +105,7 @@ export function LoginPage() {value={username}onChange={(e) => setUsername(e.target.value)}autoComplete="username"- disabled={isSubmitting}+ disabled={isSubmitting || isSsoLoading}required/></div>@@ -92,14 +123,14 @@ export function LoginPage() {onChange={(e) => setPassword(e.target.value)}autoComplete="current-password"placeholder="••••••••••••"- disabled={isSubmitting}+ disabled={isSubmitting || isSsoLoading}required/><buttontype="button"className="absolute inset-y-0 right-0 flex items-center pr-3 text-zinc-500 hover:text-zinc-300 transition-colors disabled:pointer-events-none"onClick={() => setShowPassword((v) => !v)}- disabled={isSubmitting}+ disabled={isSubmitting || isSsoLoading}aria-label={showPassword ? "Hide password" : "Show password"}>{showPassword ? <EyeOff size={16} /> : <Eye size={16} />}@@ -114,9 +145,28 @@ export function LoginPage() {</div>)}- <AresIgniteButton isLoading={isSubmitting} disabled={isSubmitting}>+ <AresIgniteButton isLoading={isSubmitting} disabled={isSubmitting || isSsoLoading}>Sign in</AresIgniteButton>++ <div className="pt-2">+ <button+ id="ares-sso-btn"+ type="button"+ onClick={() => void handleSso()}+ disabled={isSubmitting || isSsoLoading}+ className="w-full flex items-center justify-center gap-2 rounded-md border border-zinc-800/80 bg-transparent hover:bg-zinc-900/60 hover:border-zinc-700 py-2 px-3 text-xs text-zinc-400 hover:text-zinc-200 transition-colors disabled:opacity-50"+ >+ <span>{isSsoLoading ? "Connecting..." : "Or continue with SSO"}</span>+ </button>++ {ssoError && (+ <div className="mt-2 rounded-md border border-amber-900/40 bg-amber-950/20 px-3 py-2 text-xs text-amber-400 flex items-start gap-2 animate-login-enter">+ <AlertCircle size={14} className="mt-0.5 shrink-0 text-amber-400" />+ <span>{ssoError}</span>+ </div>+ )}+ </div></form></div>@@ -150,9 +200,9 @@ export function LoginPage() {<h2 className="text-3xl xl:text-4xl font-semibold text-white tracking-tight leading-tight">Offensive security,<br />- <span className="text-zinc-500 font-normal">engineered for precision.</span>+ <span className="text-zinc-300 font-normal">engineered for precision.</span></h2>- <p className="text-sm text-zinc-400 leading-relaxed mt-3 max-w-sm">+ <p className="text-sm text-zinc-300/80 leading-relaxed mt-3 max-w-sm">Automate multi-stage attack chains with deterministic execution and full audit fidelity.</p></div>@@ -165,24 +215,24 @@ export function LoginPage() {<div className="divide-y divide-zinc-800/60 text-xs font-mono"><div className="flex items-center justify-between py-2.5">- <span className="text-zinc-500">Architecture</span>+ <span className="text-zinc-400">Architecture</span><span className="text-zinc-200">Distributed Core</span></div><div className="flex items-center justify-between py-2.5">- <span className="text-zinc-500">Policy Engine</span>+ <span className="text-zinc-400">Policy Engine</span><span className="text-zinc-200">Deterministic Fail-Closed</span></div><div className="flex items-center justify-between py-2.5">- <span className="text-zinc-500">Isolation Layer</span>+ <span className="text-zinc-400">Isolation Layer</span><span className="text-zinc-200">Hermetic Enclave</span></div><div className="flex items-center justify-between py-2.5">- <span className="text-zinc-500">Audit Protocol</span>+ <span className="text-zinc-400">Audit Protocol</span><span className="text-zinc-200">Cryptographic Verification</span></div></div>- <div className="mt-3 pt-3 border-t border-zinc-800/60 flex items-center justify-between text-[11px] font-mono text-zinc-500">+ <div className="mt-3 pt-3 border-t border-zinc-800/60 flex items-center justify-between text-[11px] font-mono text-zinc-400"><span>Host: 127.0.0.1</span><span>API Gateway: 8080</span></div>diff --git a/frontend/src/features/dashboard/DashboardPages.tsx b/frontend/src/features/dashboard/DashboardPages.tsxindex 78e9a57..0c69901 100644--- a/frontend/src/features/dashboard/DashboardPages.tsx+++ b/frontend/src/features/dashboard/DashboardPages.tsx@@ -1,35 +1,15 @@import {- Activity,AlertTriangle,Bell,- Boxes,CheckCircle2,ChevronDown,Copy,- Database,- Download,- Eye,- FileText,- GitGraph,- KeyRound,- Layers,- LayoutDashboard,- ListChecks,Loader2,- LogOut,Menu,- Play,- Radio,Search,ShieldAlert,ShieldCheck,- Target,- ArrowRight,Trash2,- TrendingUp,- UserCog,- type LucideIcon,- Workflow,X} from "lucide-react";import {@@ -142,16 +122,16 @@ function clearValidationMessage<T extends ValidatableElement>(event: ChangeEvent}const navItems = [- { to: "/", label: "Overview", icon: LayoutDashboard },- { to: "/campaigns", label: "Campaigns", icon: ListChecks },- { to: "/modules", label: "Modules", icon: Boxes },- { to: "/reports", label: "Reports", icon: FileText },- { to: "/graph", label: "Graph", icon: GitGraph },- { to: "/templates", label: "Templates", icon: Workflow },- { to: "/strategy", label: "Strategy", icon: ShieldCheck },- { to: "/security", label: "Security", icon: UserCog },- { to: "/edr", label: "EDR/OPSEC", icon: ShieldAlert },- { to: "/live", label: "Live", icon: Radio }+ { to: "/", label: "Overview", code: "OVR" },+ { to: "/campaigns", label: "Campaigns", code: "CMP" },+ { to: "/modules", label: "Modules", code: "MOD" },+ { to: "/reports", label: "Reports", code: "REP" },+ { to: "/graph", label: "Graph", code: "GRP" },+ { to: "/templates", label: "Templates", code: "TPL" },+ { to: "/strategy", label: "Strategy", code: "STR" },+ { to: "/security", label: "Security", code: "SEC" },+ { to: "/edr", label: "EDR/OPSEC", code: "EDR" },+ { to: "/live", label: "Live", code: "LIV" }];const navGroups = [@@ -161,54 +141,44 @@ const navGroups = [{ label: "Control", items: navItems.slice(7) }];-const pageMeta: Record<string, { icon: LucideIcon; eyebrow: string; description: string }> = {+const pageMeta: Record<string, { eyebrow: string; description: string }> = {Overview: {- icon: LayoutDashboard,eyebrow: "Dashboard",description: "Health, telemetry, campaigns, and activity."},Campaigns: {- icon: ListChecks,eyebrow: "Operations",description: "Scopes, status, findings, and comparisons."},Modules: {- icon: Boxes,eyebrow: "Operations",description: "Catalog, OPSEC, and authorized runs."},Reports: {- icon: FileText,eyebrow: "Operations",description: "Evidence packages and artifacts."},Graph: {- icon: GitGraph,eyebrow: "Intelligence",description: "Entities, relationships, and attack paths."},Templates: {- icon: Workflow,eyebrow: "Intelligence",description: "Reusable campaign plans."},Strategy: {- icon: ShieldCheck,eyebrow: "Intelligence",description: "Authorized objective planning."},Security: {- icon: UserCog,eyebrow: "Control",description: "Account, API keys, audit, and users."},"EDR/OPSEC": {- icon: ShieldAlert,eyebrow: "Control",description: "Detection outcomes and OPSEC feedback."},"Live Events": {- icon: Radio,eyebrow: "Control",description: "Campaign events as they arrive."}@@ -600,12 +570,11 @@ export function DashboardShell({ children }: { children: ReactNode }) {<div className="nav-group-label">{group.label}</div><div className="grid gap-1">{group.items.map((item) => {- const Icon = item.icon;const count = item.to === "/campaigns" ? (campaigns.data ?? []).length : item.to === "/modules" ? (modules.data ?? []).length : null;return (<NavLink key={item.to} to={item.to} end={item.to === "/"} className="nav-link" title={sidebarCollapsed ? item.label : undefined}>- <Icon size={16} />- <span>{item.label}</span>+ <span className="nav-code font-mono">{item.code}</span>+ <span className="nav-label">{item.label}</span>{count !== null && count > 0 && !sidebarCollapsed ? (<span className="nav-count-badge font-mono">{count}</span>) : null}@@ -718,7 +687,7 @@ export function DashboardShell({ children }: { children: ReactNode }) {<aside className="telemetry-popover" aria-label="Enclave telemetry quick view"><div className="telemetry-popover-header"><div className="flex items-center gap-2">- <Activity size={15} className="text-emerald-400" />+ <span className="status-dot online" /><strong>Enclave Subsystem Health</strong></div><button className="icon-button icon-button-small" onClick={() => setTelemetryOpen(false)} aria-label="Close telemetry view" type="button">@@ -825,7 +794,6 @@ export function DashboardShell({ children }: { children: ReactNode }) {}}type="button">- <LogOut size={14} /><span>Logout</span></button><button@@ -837,7 +805,6 @@ export function DashboardShell({ children }: { children: ReactNode }) {}}type="button">- <ShieldAlert size={14} /><span>Logout all devices</span></button></div>@@ -1139,7 +1106,7 @@ function ExecutionChainsPanel({title={moduleIds.has(moduleId) ? `Open ${moduleId} in the run panel` : "Module is not available in the current catalog"}type="button">- <Play size={13} /> {moduleId}+ {moduleId}</button>))}</div>@@ -1475,8 +1442,7 @@ export function ModulesPage() {}}title={`Switch module to ${altId}`}>- <span>Switch to <strong>{altId}</strong></span>- <ArrowRight size={13} className="text-amber-400 shrink-0" />+ <span>Switch to <strong>{altId}</strong> →</span></button>))}</div>@@ -1512,9 +1478,7 @@ export function ModulesPage() {<Loader2 className="spin" size={16} /> Running...</>) : (- <>- <Play size={16} /> Run- </>+ "Execute Module")}</button>{run.isPending && (@@ -1682,9 +1646,7 @@ export function ReportsPage() {<Loader2 className="spin" size={16} /> Generating...</>) : (- <>- <FileText size={16} /> Generate- </>+ "Generate Report")}</button></div>@@ -1723,9 +1685,7 @@ export function ReportsPage() {>{clearReports.isPending ? (<Loader2 className="spin" size={15} />- ) : (- <Trash2 size={15} />- )}+ ) : null}Delete all</button>) : null}@@ -1742,7 +1702,7 @@ export function ReportsPage() {<td>{formatReportDate(item.modified_at)}</td><td><button className="btn" disabled={download.isPending || deleteDisabled} onClick={() => download.mutate(item)}>- <Download size={15} /> Download+ Download</button><buttonclassName="btn btn-danger"@@ -1755,7 +1715,7 @@ export function ReportsPage() {deleteReport.mutate(item);}}>- <Trash2 size={15} /> Delete+ Delete</button></td></tr>@@ -1899,9 +1859,7 @@ export function TemplatesPage() {<Loader2 className="spin" size={16} /> Generating...</>) : (- <>- <Workflow size={16} /> Generate Plan- </>+ "Generate Plan")}</button><TemplatePlanSummary plan={generated} />@@ -1991,9 +1949,7 @@ export function StrategyPage() {<Loader2 className="spin" size={16} /> Engaging...</>) : (- <>- <ShieldCheck size={16} /> Engage- </>+ "Engage Scope")}</button></section>@@ -2167,7 +2123,7 @@ export function SecurityPage() {<input className="field" required type="password" placeholder="Current password" value={currentPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setCurrentPassword(e.target.value); }} /><input className="field" required minLength={12} type="password" placeholder="New password" value={newPassword} onInvalid={setRequiredMessage} onChange={(e) => { clearValidationMessage(e); setNewPassword(e.target.value); }} /><button className="btn" disabled={change.isPending} type="submit">- {change.isPending ? <Loader2 className="spin" size={16} /> : <KeyRound size={16} />}+ {change.isPending && <Loader2 className="spin" size={16} />}Change Password</button></form>@@ -2189,7 +2145,7 @@ export function SecurityPage() {<option value="admin">admin</option></select><button className="btn" disabled={creatingApiKey} type="submit">- {creatingApiKey ? <Loader2 className="spin" size={16} /> : <KeyRound size={16} />}+ {creatingApiKey && <Loader2 className="spin" size={16} />}Create</button></form>@@ -2375,9 +2331,7 @@ export function EdrPage() {<Loader2 className="spin" size={16} /> Saving...</>) : (- <>- <ShieldAlert size={16} /> Report Outcome- </>+ "Report Outcome")}</button></form>@@ -2439,7 +2393,7 @@ export function LivePage() {}setLiveConnected(true);}}>- <Radio size={16} /> {liveConnected ? "Connected" : "Connect"}+ {liveConnected ? "Connected" : "Connect Stream"}</button>{liveConnected && (<button className="btn" onClick={() => setLiveConnected(false)}>@@ -2501,11 +2455,9 @@ function Page({}) {const [fallbackTab, setFallbackTab] = useState(tabs?.[0] ?? "");const meta = pageMeta[title] ?? {- icon: LayoutDashboard,eyebrow: "ARES",description: "Security dashboard workspace."};- const Icon = meta.icon;const selectedTab = activeTab ?? fallbackTab;const setTab = onTabChange ?? setFallbackTab;@@ -2532,9 +2484,6 @@ function Page({<div className="page"><section className="page-header"><div className="page-heading">- <span className="page-icon">- <Icon size={19} />- </span><div><p className="page-eyebrow">{meta.eyebrow}</p><h1>{title}</h1>@@ -2898,10 +2847,7 @@ function DataPanel({return (<section className="panel detail-panel mb-3"><div className="flex items-center justify-between mb-2">- <div className="flex items-center gap-2">- <Database size={14} className="text-zinc-400" />- <strong className="text-xs font-semibold text-zinc-200">{title}</strong>- </div>+ <strong className="text-xs font-semibold text-zinc-200">{title}</strong><div className="flex items-center gap-2">{onClear && (<buttondiff --git a/frontend/src/features/graph/GraphPage.tsx b/frontend/src/features/graph/GraphPage.tsxindex 2b70b01..b64c2e2 100644--- a/frontend/src/features/graph/GraphPage.tsx+++ b/frontend/src/features/graph/GraphPage.tsx@@ -13,7 +13,7 @@ import {} from "@xyflow/react";import "@xyflow/react/dist/style.css";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { AlertTriangle, GitGraph, Loader2, RotateCcw, Route, X } from "lucide-react";+import { AlertTriangle, Loader2, X } from "lucide-react";import { useMemo, useState, type CSSProperties } from "react";import { api } from "../../api/client";import type { AttackPath, Campaign, SafeGraphValue } from "../../api/types";@@ -318,7 +318,6 @@ function GraphWorkspace({ graph, paths, view, filters, onFiltersChange, selected<GraphFiltersPanel graph={graph} filters={filters} onChange={onFiltersChange} />{selectedPath && (<div className="graph-active-path">- <Route size={16} /><span>Highlighting {attackPathSummary(selectedPath)}</span><button className="btn btn-compact" onClick={() => onSelectPath(-1)} type="button"><X size={14} /> Clear selection@@ -335,7 +334,6 @@ function GraphWorkspace({ graph, paths, view, filters, onFiltersChange, selected/><aside className="panel graph-side-panel"><div className="graph-side-heading">- <GitGraph size={16} /><strong>{view === "paths" ? "Top attack paths" : "Safe detail"}</strong></div>{view === "paths"@@ -396,7 +394,6 @@ export default function GraphPage({ campaignId, onCampaignIdChange }: {<section className="page"><header className="page-header"><div className="page-heading">- <span className="page-icon"><GitGraph size={19} /></span><div><p className="page-eyebrow">Intelligence</p><h1>Graph</h1>@@ -405,7 +402,7 @@ export default function GraphPage({ campaignId, onCampaignIdChange }: {</div><div className="page-actions"><span className="status-pill">{safeGraph.nodes.length} nodes / {safeGraph.edges.length} edges</span>- {campaignId && <button className="btn btn-compact" onClick={() => void graphQuery.refetch()} type="button"><RotateCcw size={14} /> Retry</button>}+ {campaignId && <button className="btn btn-compact" onClick={() => void graphQuery.refetch()} type="button">Retry</button>}</div></header><div className="page-tabs" role="tablist" aria-label="Graph sections">@@ -439,7 +436,7 @@ export default function GraphPage({ campaignId, onCampaignIdChange }: {<input className="field" onChange={(event) => setJsonPath(event.target.value)} placeholder="C:\\labs\\bloodhound\\results.json" required value={jsonPath} /></label><button className="btn btn-primary" disabled={ingest.isPending} type="submit">- {ingest.isPending ? <><Loader2 className="spin" size={16} /> Importing…</> : <><GitGraph size={16} /> Request import</>}+ {ingest.isPending ? <><Loader2 className="spin" size={16} /> Importing…</> : "Request import"}</button>{ingestNotice && <p className="notice">{ingestNotice}</p>}{ingest.isError && <p className="notice notice-danger">The import request could not be completed. Confirm the allowed server-local path and retry.</p>}diff --git a/frontend/src/styles.css b/frontend/src/styles.cssindex 679cb2d..c9805bf 100644--- a/frontend/src/styles.css+++ b/frontend/src/styles.css@@ -65,7 +65,7 @@ button:disabled {.sidebar-collapsed .nav-group-label,.sidebar-collapsed .sidebar-footer,.sidebar-collapsed .nav-count-badge,-.sidebar-collapsed .nav-link span {+.sidebar-collapsed .nav-link .nav-label {display: none;}@@ -192,6 +192,42 @@ button:disabled {font-weight: 600;}+.nav-code {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ font-size: 0.65rem;+ font-weight: 700;+ color: #71717a;+ letter-spacing: 0.05em;+ padding: 1px 4px;+ min-width: 28px;+ height: 18px;+ border-radius: 3px;+ background: #141416;+ border: 1px solid #27272a;+ flex-shrink: 0;+ transition: color 120ms ease, border-color 120ms ease, background 120ms ease;+}++.nav-link:hover .nav-code {+ color: #d4d4d8;+ border-color: #3f3f46;+}++.nav-link.active .nav-code {+ color: #f43f5e;+ border-color: rgba(244, 63, 94, 0.4);+ background: rgba(244, 63, 94, 0.1);+}++.sidebar-collapsed .nav-link .nav-code {+ min-width: 32px;+ height: 22px;+ font-size: 0.7rem;+}+.sidebar-footer {margin-top: auto;border-top: 1px solid #222227;@@ -2380,4 +2416,23 @@ textarea.field {.ares-ignite-loading { animation: none; }}+/* Chrome / Edge / Safari Autofill Dark Theme Enforcement */+input:-webkit-autofill,+input:-webkit-autofill:hover,+input:-webkit-autofill:focus,+input:-webkit-autofill:active {+ -webkit-box-shadow: 0 0 0 1000px #09090b inset !important;+ box-shadow: 0 0 0 1000px #09090b inset !important;+ -webkit-text-fill-color: #f4f4f5 !important;+ caret-color: #f4f4f5 !important;+ border-color: #27272a !important;+ transition: background-color 5000s ease-in-out 0s;+}++input:-webkit-autofill:focus {+ border-color: #dc2626 !important;+ -webkit-box-shadow: 0 0 0 1000px #09090b inset, 0 0 0 1px #dc2626 !important;+ box-shadow: 0 0 0 1000px #09090b inset, 0 0 0 1px #dc2626 !important;+}+diff --git a/pyproject.toml b/pyproject.tomlindex 66d9fe0..160c27e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -29,6 +29,8 @@ dependencies = ["bcrypt>=4.0","python-multipart>=0.0.9","websockets>=12.0",+ "authlib>=1.3",+ "python3-saml>=1.16",# HTTP client"httpx>=0.27",diff --git a/tests/unit/test_sso_enterprise.py b/tests/unit/test_sso_enterprise.pynew file mode 100644index 0000000..1e7d146--- /dev/null+++ b/tests/unit/test_sso_enterprise.py@@ -0,0 +1,434 @@+"""+Unit and integration tests for ARES Multi-Tenant Enterprise SSO (SAML 2.0 / OIDC).+Validates:+1. Encryption key length requirement (ARES_ENCRYPTION_KEY >= 32)+2. App-level encryption for certs and secrets+3. Schema reconciliation for organizations and SSO tables+4. One-time ephemeral flow state (Anti-replay protection)+5. JIT user provisioning with role mapping (default to reporter)+6. Explicit blocking of SSO users from local password login+7. Endpoint /auth/sso/init error behavior on unconfigured organizations+8. SAML & OIDC error and callback handling+"""++import asyncio+import json+import os+import secrets+from unittest.mock import AsyncMock, patch+import pytest+from httpx import ASGITransport, AsyncClient++from ares.core.config import AresSettings, get_settings+from ares.core.security import DataEncryptor, hash_password+from ares.core.sso import (+ decrypt_sso_secret,+ encrypt_sso_secret,+ map_idp_role,+)+from ares.db.database import AresDatabase+++def test_settings():+ return AresSettings(+ ares_secret_key="test-secret-key-must-be-min-32-chars-long!",+ ares_encryption_key="test-encryption-key-min-32-chars-fernet!",+ ares_default_admin_password="TestPassword123!",+ )+++async def test_encryption_key_validation():+ """Verify DataEncryptor enforces key length >= 32 and fails otherwise."""+ with pytest.raises(ValueError, match="at least 32 characters"):+ DataEncryptor("short-key")++ encryptor = DataEncryptor("valid-encryption-key-that-is-at-least-32-chars!")+ ciphertext = encryptor.encrypt("super-secret-cert-or-token")+ assert ciphertext is not None+ assert ":" in ciphertext+ decrypted = encryptor.decrypt(ciphertext)+ assert decrypted == "super-secret-cert-or-token"+++async def test_app_level_secret_encryption_helpers(test_settings):+ """Verify encrypt_sso_secret and decrypt_sso_secret."""+ plain = "-----BEGIN CERTIFICATE-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\n-----END CERTIFICATE-----"+ encrypted = encrypt_sso_secret(plain, test_settings)+ assert encrypted != plain+ assert ":" in encrypted+ decrypted = decrypt_sso_secret(encrypted, test_settings)+ assert decrypted == plain+++def test_role_mapping_least_privilege_fallback():+ """Verify IdP claims map to roles, and default strictly to reporter."""+ mapping = json.dumps({+ "SecAdmins": "team_lead",+ "RedTeamers": "operator",+ "Auditors": "reporter",+ })++ # Exact group match+ assert map_idp_role({"groups": ["RedTeamers"]}, mapping) == "operator"+ assert map_idp_role({"roles": ["SecAdmins"]}, mapping) == "team_lead"++ # Unknown group -> strictly reporter+ assert map_idp_role({"groups": ["UnknownGroup"]}, mapping) == "reporter"++ # Empty claims -> strictly reporter+ assert map_idp_role({}, mapping) == "reporter"++ # Direct role name in claim+ assert map_idp_role({"roles": ["operator"]}, None) == "operator"++ # Never escalate to admin on invalid/empty mapping+ assert map_idp_role({"groups": ["CEO"]}, None, default_role="invalid") == "reporter"+++async def test_database_sso_schema_and_operations(tmp_path, test_settings):+ """Test organization, sso config, flow state, and JIT provisioning in SQLite."""+ db_file = tmp_path / "test_sso.db"+ db = AresDatabase(str(db_file))+ await db.connect()++ try:+ # 1. Organization creation & retrieval+ org = await db.get_organization("default")+ assert org is not None+ assert org["slug"] == "default"++ # 2. SSO configuration saving & retrieval+ cert_enc = encrypt_sso_secret("MOCK_CERT", test_settings)+ sec_enc = encrypt_sso_secret("MOCK_SECRET", test_settings)++ sso_id = await db.save_sso_config(+ org_id=org["id"],+ protocol="oidc",+ issuer_or_entity_id="https://idp.example.com",+ sso_url="https://idp.example.com/authorize",+ client_id="ares-client",+ client_secret_enc=sec_enc,+ acs_url="https://idp.example.com/token",+ jwks_uri="https://idp.example.com/.well-known/jwks.json",+ default_role="reporter",+ role_mapping_json=json.dumps({"Engineers": "operator"}),+ )+ assert sso_id is not None++ cfg = await db.get_sso_config(org["id"], protocol="oidc")+ assert cfg is not None+ assert cfg["issuer_or_entity_id"] == "https://idp.example.com"+ assert cfg["client_secret_enc"] == sec_enc++ # 3. Flow state one-time replay protection+ flow_id = "test-state-token-123"+ nonce = "test-nonce-456"+ await db.create_sso_flow_state(org["id"], "oidc", flow_id, nonce=nonce, ttl_minutes=5)++ # First consumption must succeed+ consumed = await db.consume_sso_flow_state(flow_id, "oidc")+ assert consumed is not None+ assert consumed["flow_id"] == flow_id+ assert consumed["nonce"] == nonce++ # Second consumption (replay attack) MUST fail+ replayed = await db.consume_sso_flow_state(flow_id, "oidc")+ assert replayed is None++ # 4. JIT User Provisioning+ user = await db.provision_or_get_sso_user(+ org_id=org["id"],+ username="sso_analyst",+ role="operator",+ external_id="idp-user-sub-999",+ auth_provider="oidc",+ )+ assert user is not None+ assert user["username"] == "sso_analyst"+ assert user["role"] == "operator"+ assert user["auth_provider"] == "oidc"+ assert user["external_subject_id"] == "idp-user-sub-999"++ # Lookup same user on subsequent login+ user2 = await db.provision_or_get_sso_user(+ org_id=org["id"],+ username="sso_analyst",+ role="operator",+ external_id="idp-user-sub-999",+ auth_provider="oidc",+ )+ assert user2["id"] == user["id"]++ # 5. EXPLICIT REJECT: SSO user cannot authenticate via local password+ password_attempt = await db.verify_user("sso_analyst", "AnyPasswordTry")+ assert password_attempt is None++ finally:+ await db.close()+++async def test_sso_init_unconfigured_error(tmp_path):+ """Verify /auth/sso/init returns inline-compatible 400 error on unconfigured org."""+ from ares.api.server import app, get_db++ db_file = tmp_path / "test_api_sso.db"+ db = AresDatabase(str(db_file))+ await db.connect()++ app.dependency_overrides[get_db] = lambda: db++ try:+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://localhost") as client:+ resp = await client.get("/auth/sso/init?org=default")+ assert resp.status_code == 400+ data = resp.json()+ assert "SSO belum dikonfigurasi untuk organisasi ini. Hubungi admin." in data.get("detail", "")+ finally:+ app.dependency_overrides.pop(get_db, None)+ await db.close()+++async def test_sso_init_configured_success(tmp_path, test_settings):+ """Verify /auth/sso/init returns redirect_url and records one-time flow state."""+ from ares.api.server import app, get_db++ db_file = tmp_path / "test_api_sso_configured.db"+ db = AresDatabase(str(db_file))+ await db.connect()++ org = await db.get_organization("default")+ await db.save_sso_config(+ org_id=org["id"],+ protocol="oidc",+ issuer_or_entity_id="https://auth.company.com",+ sso_url="https://auth.company.com/oauth2/v1/authorize",+ client_id="ares-sec",+ acs_url="https://auth.company.com/oauth2/v1/token",+ )++ app.dependency_overrides[get_db] = lambda: db++ try:+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://localhost") as client:+ resp = await client.get("/auth/sso/init?org=default")+ assert resp.status_code == 200+ data = resp.json()+ assert data["configured"] is True+ assert data["protocol"] == "oidc"+ assert "https://auth.company.com/oauth2/v1/authorize" in data["redirect_url"]+ assert "state=" in data["redirect_url"]+ assert "nonce=" in data["redirect_url"]++ # Flow state must be recorded in DB+ flow_id = data["flow_id"]+ flow_row = await db.consume_sso_flow_state(flow_id, "oidc")+ assert flow_row is not None+ assert flow_row["flow_id"] == flow_id+ finally:+ app.dependency_overrides.pop(get_db, None)+ await db.close()+++async def test_sso_user_blocked_at_auth_token_endpoint(tmp_path):+ """Verify /auth/token explicitly rejects login attempts for SSO users, even with bcrypt match."""+ from ares.api.server import app, get_db++ db_file = tmp_path / "test_auth_token_block.db"+ db = AresDatabase(str(db_file))+ await db.connect()++ # Create an SSO-provisioned user in the database+ org = await db.get_organization("default")+ await db.provision_or_get_sso_user(+ org_id=org["id"],+ username="enterprise_sso_user",+ role="operator",+ external_id="ext-123",+ auth_provider="oidc",+ )++ app.dependency_overrides[get_db] = lambda: db++ try:+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://127.0.0.1:5173") as client:+ csrf_res = await client.get("/auth/csrf", headers={"Origin": "http://127.0.0.1:5173"})+ assert csrf_res.status_code == 204+ csrf_token = client.cookies.get("ares-dev-csrf")+ assert csrf_token is not None++ resp = await client.post(+ "/auth/token",+ data={"username": "enterprise_sso_user", "password": "AnyPasswordTry!"},+ headers={+ "Content-Type": "application/x-www-form-urlencoded",+ "Origin": "http://127.0.0.1:5173",+ "Sec-Fetch-Site": "same-origin",+ "X-ARES-CSRF": csrf_token,+ },+ )+ assert resp.status_code == 401+ assert resp.json().get("detail") == "Invalid credentials"+ finally:+ app.dependency_overrides.pop(get_db, None)+ await db.close()+++async def test_oidc_callback_replay_and_state_validation(tmp_path, test_settings):+ """Verify OIDC callback enforces state match, consumes state atomically, and redirects with cookies."""+ from ares.api.server import app, get_db++ db_file = tmp_path / "test_oidc_callback.db"+ db = AresDatabase(str(db_file))+ await db.connect()++ org = await db.get_organization("default")+ await db.save_sso_config(+ org_id=org["id"],+ protocol="oidc",+ issuer_or_entity_id="https://idp.example.com",+ sso_url="https://idp.example.com/auth",+ client_id="ares-app",+ acs_url="https://idp.example.com/token",+ )++ # Pre-create flow state+ valid_state = "valid-state-" + secrets.token_hex(16)+ valid_nonce = "valid-nonce-" + secrets.token_hex(16)+ await db.create_sso_flow_state(org["id"], "oidc", valid_state, nonce=valid_nonce, ttl_minutes=5)++ app.dependency_overrides[get_db] = lambda: db++ try:+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://localhost") as client:+ # 1. Unknown or forged state -> 303 redirect with error param+ forged_resp = await client.get(+ "/auth/sso/oidc/callback?state=forged-state&code=test-code",+ follow_redirects=False,+ )+ assert forged_resp.status_code == 303+ assert "/dashboard/login?error=" in forged_resp.headers["location"]++ # 2. Mock process_oidc_callback to simulate successful IdP response+ with patch("ares.api.server.process_oidc_callback", new_callable=AsyncMock) as mock_oidc:+ mock_oidc.return_value = {+ "external_id": "okta-sub-456",+ "username": "alice_secops",+ "role": "operator",+ "claims": {"sub": "okta-sub-456", "email": "[email protected]"},+ }++ # First callback with valid state -> 303 redirect to /dashboard/ and cookies set+ resp = await client.get(+ f"/auth/sso/oidc/callback?state={valid_state}&code=mock-auth-code",+ follow_redirects=False,+ )+ assert resp.status_code == 303+ assert resp.headers["location"] == "/dashboard/"+ assert ("ares-dev-refresh" in resp.cookies) or ("__Host-ares-refresh" in resp.cookies)+ assert ("ares-dev-csrf" in resp.cookies) or ("__Host-ares-csrf" in resp.cookies)++ # 3. Replay attack: calling the same callback again with same state -> 303 with replay error+ replay_resp = await client.get(+ f"/auth/sso/oidc/callback?state={valid_state}&code=mock-auth-code",+ follow_redirects=False,+ )+ assert replay_resp.status_code == 303+ assert "/dashboard/login?error=" in replay_resp.headers["location"]+ finally:+ app.dependency_overrides.pop(get_db, None)+ await db.close()+++async def test_saml_acs_replay_and_in_response_to_validation(tmp_path, test_settings):+ """Verify SAML ACS callback validates InResponseTo, rejects cross-site replay without CSRF header check."""+ import base64+ from ares.api.server import app, get_db++ db_file = tmp_path / "test_saml_acs.db"+ db = AresDatabase(str(db_file))+ await db.connect()++ org = await db.get_organization("default")+ await db.save_sso_config(+ org_id=org["id"],+ protocol="saml",+ issuer_or_entity_id="https://saml-idp.example.com",+ sso_url="https://saml-idp.example.com/sso",+ sp_entity_id="https://ares.local/auth/sso/saml/metadata",+ acs_url="http://localhost/auth/sso/saml/acs",+ )++ valid_request_id = "REQ-" + secrets.token_hex(16)+ await db.create_sso_flow_state(org["id"], "saml", valid_request_id, ttl_minutes=5)++ app.dependency_overrides[get_db] = lambda: db++ mismatch_xml = base64.b64encode(+ b'<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" InResponseTo="DIFFERENT-REQ-ID"></samlp:Response>'+ ).decode("ascii")+ valid_xml = base64.b64encode(+ f'<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" InResponseTo="{valid_request_id}"></samlp:Response>'.encode("ascii")+ ).decode("ascii")++ try:+ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://localhost") as client:+ # Note: No X-ARES-CSRF header sent! This tests CSRF exemption on ACS endpoint.+ with patch("ares.api.server.process_saml_response") as mock_saml:+ # 1. SAML response with mismatched InResponseTo -> 303 redirect with error+ mismatch_resp = await client.post(+ "/auth/sso/saml/acs",+ data={"SAMLResponse": mismatch_xml},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ follow_redirects=False,+ )+ assert mismatch_resp.status_code == 303+ assert "/dashboard/login?error=" in mismatch_resp.headers["location"]++ # 2. SAML response with matching InResponseTo -> 303 redirect to /dashboard/ + cookies+ mock_saml.return_value = {+ "in_response_to": valid_request_id,+ "name_id": "[email protected]",+ "username": "bob_sso",+ "role": "reporter",+ "external_id": "bob-idp-sub",+ "attributes": {},+ }+ success_resp = await client.post(+ "/auth/sso/saml/acs",+ data={"SAMLResponse": valid_xml},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ follow_redirects=False,+ )+ assert success_resp.status_code == 303+ assert success_resp.headers["location"] == "/dashboard/"+ assert ("ares-dev-refresh" in success_resp.cookies) or ("__Host-ares-refresh" in success_resp.cookies)+ assert ("ares-dev-csrf" in success_resp.cookies) or ("__Host-ares-csrf" in success_resp.cookies)++ # 3. Replay attack with same SAMLResponse / Request ID -> 303 redirect with replay error+ replay_resp = await client.post(+ "/auth/sso/saml/acs",+ data={"SAMLResponse": valid_xml},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ follow_redirects=False,+ )+ assert replay_resp.status_code == 303+ assert "/dashboard/login?error=" in replay_resp.headers["location"]+ finally:+ app.dependency_overrides.pop(get_db, None)+ await db.close()++