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(db): add enterprise PostgreSQL multi-tenant SSO support and dual-backend parity
Mafifrizic0f0be758123
diff --git a/ares/api/server.py b/ares/api/server.pyindex 8060be3..b751c9e 100644--- a/ares/api/server.py+++ b/ares/api/server.py@@ -334,7 +334,7 @@ def _setup_otel(app: FastAPI, settings: Any) -> None:# ── App-level singletons ──────────────────────────────────────────────────────_engine: AresEngine | None = None-_db: AresDatabase | None = None+_db: Any | None = None# WebSocket registry: campaign_id → opaque authenticated connection contexts.@dataclass(eq=False)@@ -459,10 +459,21 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:settings = get_settings()app.state.browser_policy = build_browser_session_policy(settings)canonical_noncredentialed_origins(settings.cors_origins_list)- _db = await AresDatabase.create(- db_path=settings.db_path,- encryption_key=settings.encryption_key_value,- )+ db_url = settings.ares_database_url+ if db_url.startswith(("postgresql://", "postgresql+asyncpg://")):+ from ares.db.postgres import PostgresDatabase++ _db = await PostgresDatabase.create(+ dsn=db_url,+ encryption_key=settings.encryption_key_value,+ )+ logger.info("ares_database_backend_initialized", backend="postgresql")+ else:+ _db = await AresDatabase.create(+ db_path=settings.db_path,+ encryption_key=settings.encryption_key_value,+ )+ logger.info("ares_database_backend_initialized", backend="sqlite")app.state.db = _dbawait _db.ensure_default_admin(settings.ares_default_admin_password)@@ -769,7 +780,7 @@ async def _require_campaign_access(raise HTTPException(404, "Campaign not found")-def get_db(request: Request) -> AresDatabase:+def get_db(request: Request) -> Any:return request.app.state.dbdiff --git a/ares/db/postgres.py b/ares/db/postgres.pyindex 81a8d14..5f1ac1a 100644--- a/ares/db/postgres.py+++ b/ares/db/postgres.py@@ -3775,6 +3775,7 @@ class PostgresDatabase:await self._validate_managed_schema(conn)await self._validate_websocket_ticket_schema(conn)await validate_postgresql_admission_authority_catalog(conn)+ await self._ensure_sso_schema(conn)except _PostgresMigrationRequiredError:raiseexcept _PostgresStartupDiagnosticError as exc:@@ -5707,6 +5708,337 @@ class PostgresDatabase:return Truereturn False+ # ── Multi-Tenant & Enterprise SSO ─────────────────────────────────────────++ @staticmethod+ async def _ensure_sso_schema(connection: Any) -> None:+ """Ensure enterprise SSO and multi-tenant schema exists in PostgreSQL."""+ await connection.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 TIMESTAMPTZ NOT NULL DEFAULT NOW()+ );+ CREATE INDEX IF NOT EXISTS idx_organizations_slug ON organizations (slug);++ 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,+ 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 TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ CONSTRAINT ck_sso_protocol CHECK (protocol IN ('saml', 'oidc')),+ CONSTRAINT uq_sso_org_protocol UNIQUE (org_id, protocol)+ );+ CREATE INDEX IF NOT EXISTS idx_sso_org ON sso_configurations (org_id);++ 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,+ flow_id TEXT NOT NULL UNIQUE,+ nonce TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ expires_at TIMESTAMPTZ NOT NULL,+ is_consumed INTEGER NOT NULL DEFAULT 0,+ consumed_at TIMESTAMPTZ,+ CONSTRAINT ck_flow_type CHECK (flow_type IN ('saml', 'oidc'))+ );+ CREATE INDEX IF NOT EXISTS idx_sso_flow_lookup+ ON sso_flow_states (flow_id, is_consumed, expires_at);++ ALTER TABLE users ADD COLUMN IF NOT EXISTS org_id TEXT;+ ALTER TABLE users ADD COLUMN IF NOT EXISTS auth_provider TEXT NOT NULL DEFAULT 'local';+ ALTER TABLE users ADD COLUMN IF NOT EXISTS external_subject_id TEXT DEFAULT NULL;++ INSERT INTO organizations (id, slug, name, is_active)+ VALUES ('00000000-0000-0000-0000-000000000001', 'default', 'Default Organization', 1)+ ON CONFLICT (slug) DO NOTHING;+ """+ )++ async def get_organization(self, slug_or_id: str) -> dict[str, Any] | None:+ async with self._pool.acquire() as conn:+ row = await conn.fetchrow(+ "SELECT * FROM organizations WHERE slug=$1 OR id=$1",+ slug_or_id,+ )+ if row:+ return self._row_to_dict(row)+ if slug_or_id == "default":+ default_id = "00000000-0000-0000-0000-000000000001"+ await conn.execute(+ """INSERT INTO organizations(id, slug, name, is_active)+ VALUES($1, $2, $3, 1)+ ON CONFLICT (slug) DO NOTHING""",+ default_id,+ "default",+ "Default Organization",+ )+ row = await conn.fetchrow("SELECT * FROM organizations WHERE slug='default'")+ return self._row_to_dict(row) if row else None+ return None++ async def get_sso_config(+ self, org_id: str, protocol: str | None = None+ ) -> dict[str, Any] | None:+ async with self._pool.acquire() as conn:+ if protocol:+ row = await conn.fetchrow(+ "SELECT * FROM sso_configurations "+ "WHERE org_id=$1 AND protocol=$2 AND is_enabled=1",+ org_id,+ protocol,+ )+ else:+ row = await conn.fetchrow(+ "SELECT * FROM sso_configurations WHERE org_id=$1 AND is_enabled=1 LIMIT 1",+ org_id,+ )+ return self._row_to_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: bool = True,+ ) -> str:+ sso_id = str(uuid.uuid4())+ async with self._pool.acquire() as conn:+ await 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($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, 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=now()""",+ sso_id,+ org_id,+ protocol,+ 1 if is_enabled else 0,+ 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,+ )+ return sso_id++ async def create_sso_flow_state(+ self,+ org_id: str,+ flow_type: str,+ flow_id: str,+ nonce: str | None = None,+ ttl_minutes: int = 10,+ ) -> str:+ state_id = str(uuid.uuid4())+ async with self._pool.acquire() as conn:+ await conn.execute(+ """INSERT INTO sso_flow_states(+ id, org_id, flow_type, flow_id, nonce, created_at, expires_at+ ) VALUES($1, $2, $3, $4, $5, now(), now() + ($6 || ' minutes')::interval)""",+ state_id,+ org_id,+ flow_type,+ flow_id,+ nonce,+ str(int(ttl_minutes)),+ )+ return state_id++ async def consume_sso_flow_state(+ self,+ flow_id: str,+ flow_type: str,+ ) -> dict[str, Any] | None:+ async with self._pool.acquire() as conn:+ async with conn.transaction():+ row = await conn.fetchrow(+ """SELECT * FROM sso_flow_states+ WHERE flow_id=$1 AND flow_type=$2 AND is_consumed=0 AND expires_at > now()+ FOR UPDATE""",+ flow_id,+ flow_type,+ )+ if not row:+ return None+ record = self._row_to_dict(row)+ await conn.execute(+ "UPDATE sso_flow_states SET is_consumed=1, consumed_at=now() WHERE id=$1",+ record["id"],+ )+ 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._pool.acquire() as conn:+ async with conn.transaction():+ row = await conn.fetchrow(+ """SELECT * FROM users+ WHERE (+ external_subject_id=$1+ AND external_subject_id IS NOT NULL+ AND external_subject_id != ''+ ) OR username=$2+ FOR UPDATE""",+ external_id,+ username,+ )+ if row:+ user = self._row_to_dict(row)+ updates = []+ params: list[Any] = []+ idx = 1+ if external_id and not user.get("external_subject_id"):+ updates.append(f"external_subject_id=${idx}")+ params.append(external_id)+ idx += 1+ if role and role != user.get("role"):+ updates.append(f"role=${idx}")+ params.append(role)+ idx += 1+ if updates:+ params.append(user["id"])+ await conn.execute(+ f"UPDATE users SET {', '.join(updates)} WHERE id=${idx}", # noqa: S608+ *params,+ )+ updated_row = await conn.fetchrow(+ "SELECT * FROM users WHERE id=$1", user["id"]+ )+ user = self._row_to_dict(updated_row) if updated_row else user+ return user++ user_id = str(uuid.uuid4())+ dummy_hash = hash_password(secrets.token_urlsafe(32))+ await conn.execute(+ """INSERT INTO users(+ id, username, hashed_password, role, is_active,+ created_by, org_id, auth_provider, external_subject_id+ ) VALUES($1, $2, $3, $4, 1, $5, $6, $7, $8)""",+ user_id,+ username,+ dummy_hash,+ role,+ f"sso:{auth_provider}",+ org_id,+ auth_provider,+ external_id,+ )+ logger.info(+ "sso_user_provisioned",+ username=username,+ role=role,+ org_id=org_id,+ provider=auth_provider,+ )+ new_row = await conn.fetchrow("SELECT * FROM users WHERE id=$1", user_id)+ return self._row_to_dict(new_row)++ async def create_sso_session(+ self,+ user_id: str,+ token_factory: AccessTokenFactory,+ ) -> SessionIssueResult:+ """Create authenticated session for an SSO-authenticated user."""+ async with self._pool.acquire() as conn:+ async with conn.transaction():+ row = await conn.fetchrow(+ "SELECT id,username,role,is_active,auth_epoch "+ "FROM users WHERE id=$1 FOR UPDATE",+ user_id,+ )+ if row is None or not bool(row["is_active"]):+ return SessionIssueResult(SessionIssueStatus.INVALID)+ (+ family_id,+ raw_token,+ absolute_expiry,+ ) = await self._insert_initial_family_token_with_expiry(+ conn,+ 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 conn.execute(+ "UPDATE users SET last_login=now() WHERE id=$1",+ row["id"],+ )+ await conn.execute(+ "INSERT INTO audit_log(actor,action,detail) VALUES("+ "'auth-system','sso_login_family_created','')"+ )+ 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"],+ ),+ )+# ── API Keys ───────────────────────────────────────────────────────────────async def create_api_key(diff --git a/docs/sso-setup.md b/docs/sso-setup.mdindex cdace3d..dcbe061 100644--- a/docs/sso-setup.md+++ b/docs/sso-setup.md@@ -99,28 +99,58 @@ Request payload for `POST /auth/sso/config/{org_slug}`:*Note: The backend automatically encrypts `idp_certificate` and `client_secret` via `DataEncryptor` before persisting to `sso_configurations`.*#### Option B: Direct SQL Database Insertion-If provisioning directly via SQLite (`ares.db`):+ARES automatically manages and provisions the required multi-tenant SSO tables (`organizations`, `sso_configurations`, `sso_flow_states`, and JIT federated user attributes) across both supported storage backends:+- **SQLite** (`ares.db` for local development and single-operator red team deployments)+- **Enterprise PostgreSQL** (`postgresql+asyncpg://` or `postgresql://` for high-concurrency multi-tenant team server deployments)++If provisioning directly via SQL:1. Ensure the organization exists in the `organizations` table:```sqlINSERT INTO organizations (id, slug, name, is_active)- VALUES ('org-corp-01', 'corp', 'ACME Corp', 1);+ VALUES ('org-corp-01', 'corp', 'ACME Corp', 1)+ ON CONFLICT (slug) DO NOTHING;```2. Encrypt certificates or client secrets using the ARES CLI helper:```bashpython -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. Insert into `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', '<ENCRYPTED_VALUE>',- 'reporter', '{"SecAdmins": "team_lead"}'- );- ```+ - **For SQLite**:+ ```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', '<ENCRYPTED_VALUE>',+ 'reporter', '{"SecAdmins": "team_lead"}'+ )+ 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,+ updated_at=datetime('now');+ ```+ - **For PostgreSQL**:+ ```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', '<ENCRYPTED_VALUE>',+ 'reporter', '{"SecAdmins": "team_lead"}'+ )+ 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,+ updated_at=now();+ ```---diff --git a/tests/unit/test_postgres_sso_parity.py b/tests/unit/test_postgres_sso_parity.pynew file mode 100644index 0000000..a2da7f8--- /dev/null+++ b/tests/unit/test_postgres_sso_parity.py@@ -0,0 +1,170 @@+"""Unit tests for PostgreSQL Enterprise SSO interface and schema parity."""+from __future__ import annotations++import inspect+from unittest.mock import AsyncMock, MagicMock++import pytest++from ares.db.database import AresDatabase+from ares.db.postgres import (+ _POSTGRES_MANAGED_REVISION,+ _POSTGRES_MANAGED_TABLES,+ _POSTGRES_OLDER_REVISIONS,+ PostgresDatabase,+)+++def test_sso_method_interface_parity():+ """Verify that PostgresDatabase implements all SSO methods from AresDatabase."""+ sso_methods = [+ "get_organization",+ "get_sso_config",+ "save_sso_config",+ "create_sso_flow_state",+ "consume_sso_flow_state",+ "provision_or_get_sso_user",+ "create_sso_session",+ ]++ for method_name in sso_methods:+ assert hasattr(AresDatabase, method_name), f"AresDatabase missing {method_name}"+ assert hasattr(PostgresDatabase, method_name), f"PostgresDatabase missing {method_name}"++ ares_sig = inspect.signature(getattr(AresDatabase, method_name))+ pg_sig = inspect.signature(getattr(PostgresDatabase, method_name))++ # Ensure parameters match+ ares_params = list(ares_sig.parameters.keys())+ pg_params = list(pg_sig.parameters.keys())+ assert ares_params == pg_params, (+ f"Parameter mismatch on {method_name}: {ares_params} vs {pg_params}"+ )+++def test_postgres_baseline_schema_invariants():+ """Verify that Postgres schema invariant constants preserve baseline revision 0011 contract."""+ # 1. Revision progression frozen at 0011+ assert _POSTGRES_MANAGED_REVISION == "0011"+ assert "0010" in _POSTGRES_OLDER_REVISIONS++ # 2. Managed tables: 14 baseline tables+ assert len(_POSTGRES_MANAGED_TABLES) == 14+ assert "campaigns" in _POSTGRES_MANAGED_TABLES+ assert "users" in _POSTGRES_MANAGED_TABLES+ assert "websocket_tickets" in _POSTGRES_MANAGED_TABLES+++async def test_postgres_ensure_sso_schema_ddl():+ """Verify that _ensure_sso_schema executes DDL for enterprise SSO tables and columns."""+ mock_conn = AsyncMock()+ await PostgresDatabase._ensure_sso_schema(mock_conn)++ assert mock_conn.execute.called+ ddl_call_args = mock_conn.execute.call_args[0][0]+ assert "CREATE TABLE IF NOT EXISTS organizations" in ddl_call_args+ assert "CREATE TABLE IF NOT EXISTS sso_configurations" in ddl_call_args+ assert "CREATE TABLE IF NOT EXISTS sso_flow_states" in ddl_call_args+ assert "ALTER TABLE users ADD COLUMN IF NOT EXISTS org_id" in ddl_call_args+ assert "ALTER TABLE users ADD COLUMN IF NOT EXISTS auth_provider" in ddl_call_args+ assert "ALTER TABLE users ADD COLUMN IF NOT EXISTS external_subject_id" in ddl_call_args+ assert "INSERT INTO organizations" in ddl_call_args+++async def test_postgres_database_sso_mocked_flow():+ """Verify PostgresDatabase SSO queries using mocked asyncpg pool."""+ db = PostgresDatabase("postgresql://ares:secret@localhost:5432/ares_db")+ mock_pool = MagicMock()+ mock_conn = AsyncMock()++ # Context manager setup for acquire()+ acquire_ctx = AsyncMock()+ acquire_ctx.__aenter__.return_value = mock_conn+ acquire_ctx.__aexit__.return_value = None+ mock_pool.acquire.return_value = acquire_ctx++ # Context manager setup for conn.transaction()+ tx_ctx = AsyncMock()+ tx_ctx.__aenter__.return_value = None+ tx_ctx.__aexit__.return_value = None+ mock_conn.transaction = MagicMock(return_value=tx_ctx)++ db._pool = mock_pool++ # 1. Test get_organization+ mock_conn.fetchrow.return_value = {+ "id": "org-123",+ "slug": "enterprise",+ "name": "Enterprise Corp",+ "is_active": 1,+ }+ org = await db.get_organization("enterprise")+ assert org is not None+ assert org["id"] == "org-123"+ mock_conn.fetchrow.assert_called_with(+ "SELECT * FROM organizations WHERE slug=$1 OR id=$1",+ "enterprise",+ )++ # 2. Test get_sso_config+ mock_conn.fetchrow.return_value = {+ "id": "cfg-123",+ "org_id": "org-123",+ "protocol": "saml",+ "is_enabled": 1,+ "sso_url": "https://idp.example.com/sso",+ }+ cfg = await db.get_sso_config("org-123", protocol="saml")+ assert cfg is not None+ assert cfg["protocol"] == "saml"++ # 3. Test save_sso_config+ sso_id = await db.save_sso_config(+ org_id="org-123",+ protocol="oidc",+ client_id="ares-app",+ sso_url="https://idp.example.com/auth",+ )+ assert len(sso_id) == 36 # UUIDv4 format+ assert mock_conn.execute.called++ # 4. Test create_sso_flow_state+ state_id = await db.create_sso_flow_state(+ org_id="org-123",+ flow_type="saml",+ flow_id="req-123",+ ttl_minutes=10,+ )+ assert len(state_id) == 36+ assert mock_conn.execute.called++ # 5. Test consume_sso_flow_state (atomic transaction)+ mock_conn.fetchrow.return_value = {+ "id": "state-uuid",+ "org_id": "org-123",+ "flow_type": "saml",+ "flow_id": "req-123",+ "is_consumed": 0,+ }+ consumed = await db.consume_sso_flow_state("req-123", "saml")+ assert consumed is not None+ assert consumed["id"] == "state-uuid"+ assert mock_conn.transaction.called++ # 6. Test provision_or_get_sso_user+ mock_conn.fetchrow.return_value = {+ "id": "user-uuid",+ "username": "[email protected]",+ "role": "operator",+ "is_active": 1,+ }+ user = await db.provision_or_get_sso_user(+ org_id="org-123",+ username="[email protected]",+ role="operator",+ auth_provider="saml",+ )+ assert user is not None+ assert user["username"] == "[email protected]"