Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

fix(api): bcrypt 4.x compat + idempotent SQL migration runner

Beenu Arora48b34c511e83
diff --git a/services/api/app/core/security.py b/services/api/app/core/security.py
index 426e2d064..6de5ceabf 100644
--- a/services/api/app/core/security.py
+++ b/services/api/app/core/security.py
@@ -7,12 +7,17 @@ import secrets
from datetime import UTC, datetime, timedelta
from typing import Any
+import bcrypt
from jose import jwt
-from passlib.context import CryptContext
from app.core.config import settings
-pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
+# bcrypt has a hard 72-byte limit on inputs. We mirror what passlib used to do
+# but without the version-introspection that breaks against newer bcrypt
+# releases (passlib 1.7.4 reads `_bcrypt.__about__.__version__`, which was
+# removed in bcrypt 4.x and causes a misleading 72-byte error to surface even
+# for short passwords).
+_BCRYPT_MAX_BYTES = 72
ROLE_PERMISSIONS: dict[str, list[str]] = {
"platform_admin": ["*"],
@@ -98,12 +103,22 @@ ROLE_PERMISSIONS: dict[str, list[str]] = {
}
+def _to_bcrypt_input(password: str) -> bytes:
+ encoded = password.encode("utf-8")
+ if len(encoded) > _BCRYPT_MAX_BYTES:
+ encoded = encoded[:_BCRYPT_MAX_BYTES]
+ return encoded
+
+
def verify_password(plain_password: str, hashed_password: str) -> bool:
- return pwd_context.verify(plain_password, hashed_password)
+ try:
+ return bcrypt.checkpw(_to_bcrypt_input(plain_password), hashed_password.encode("utf-8"))
+ except (ValueError, TypeError):
+ return False
def get_password_hash(password: str) -> str:
- return pwd_context.hash(password)
+ return bcrypt.hashpw(_to_bcrypt_input(password), bcrypt.gensalt()).decode("utf-8")
def create_access_token(data: dict[str, Any], expires_delta: timedelta | None = None) -> str:
diff --git a/services/api/app/main.py b/services/api/app/main.py
index cc30be19d..bf4ec1003 100644
--- a/services/api/app/main.py
+++ b/services/api/app/main.py
@@ -66,6 +66,22 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
# Tables already exist or another worker beat us to it — safe to ignore in dev.
logger.warning("create_all skipped (likely already applied)", error=str(exc))
+ # Apply raw-SQL migrations (services/api/migrations/*.sql). These cover
+ # tables that aren't part of the SQLAlchemy ORM (aisoc_cases, MSSP, EASM,
+ # connector schema-drift, etc.). The runner is idempotent: each migration
+ # is tracked in aisoc_schema_migrations so it only runs once. We exclude
+ # production for now since prod is expected to have a managed migration
+ # pipeline; demo / dev environments bootstrap themselves on boot so the
+ # first deploy of a new feature is usable immediately.
+ if settings.ENVIRONMENT in _DEV_ENVIRONMENTS:
+ try:
+ from app.scripts.run_migrations import main as run_sql_migrations # noqa: PLC0415
+
+ await run_sql_migrations()
+ logger.info("SQL migrations applied", environment=settings.ENVIRONMENT)
+ except Exception as exc:
+ logger.warning("SQL migration run failed", error=str(exc))
+
# Initialize Neo4j graph layer
try:
await init_neo4j()
diff --git a/services/api/app/scripts/run_migrations.py b/services/api/app/scripts/run_migrations.py
new file mode 100644
index 000000000..190dcc279
--- /dev/null
+++ b/services/api/app/scripts/run_migrations.py
@@ -0,0 +1,97 @@
+"""Apply raw SQL migrations under ``services/api/migrations``.
+
+This is a lightweight, idempotent migration runner. Each migration is executed
+inside a transaction and tracked in an ``aisoc_schema_migrations`` table so it
+will not be re-applied on subsequent runs. Migrations themselves are written
+defensively (``CREATE TABLE IF NOT EXISTS``, ``ALTER TABLE … ADD COLUMN IF NOT
+EXISTS``) so partial re-applies are safe.
+
+Run via:
+
+ python -m app.scripts.run_migrations
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from pathlib import Path
+
+from sqlalchemy import text
+
+from app.db.database import engine
+
+logger = logging.getLogger(__name__)
+logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
+
+MIGRATIONS_DIR = Path(__file__).resolve().parents[2] / "migrations"
+
+
+CREATE_MIGRATIONS_TABLE = """
+CREATE TABLE IF NOT EXISTS aisoc_schema_migrations (
+ name TEXT PRIMARY KEY,
+ applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+"""
+
+
+async def _applied(conn) -> set[str]:
+ res = await conn.execute(text("SELECT name FROM aisoc_schema_migrations"))
+ return {row[0] for row in res}
+
+
+async def _record(conn, name: str) -> None:
+ await conn.execute(
+ text("INSERT INTO aisoc_schema_migrations(name) VALUES (:n) ON CONFLICT DO NOTHING").bindparams(n=name)
+ )
+
+
+async def _apply_one(name: str, sql: str) -> tuple[str, bool, str | None]:
+ """Apply a single migration in its own transaction.
+
+ Returns (name, ok, error). Failures are recorded but don't crash the runner
+ so later migrations (which may not depend on the failing one) can still
+ apply. The deploy log will surface which migrations failed.
+ """
+ try:
+ async with engine.begin() as conn:
+ await conn.execute(text(sql))
+ await _record(conn, name)
+ return name, True, None
+ except Exception as exc: # noqa: BLE001 — we intentionally continue on failure
+ return name, False, str(exc)
+
+
+async def main() -> None:
+ if not MIGRATIONS_DIR.exists():
+ logger.warning("migrations dir not found: %s", MIGRATIONS_DIR)
+ return
+
+ files = sorted(p for p in MIGRATIONS_DIR.iterdir() if p.suffix == ".sql")
+ logger.info("Found %d migration files", len(files))
+
+ async with engine.begin() as conn:
+ await conn.execute(text(CREATE_MIGRATIONS_TABLE))
+
+ async with engine.connect() as conn:
+ already = await _applied(conn)
+
+ pending = [p for p in files if p.name not in already]
+ logger.info("%d migrations already applied; %d pending", len(already), len(pending))
+
+ failures: list[tuple[str, str]] = []
+ for path in pending:
+ sql = path.read_text(encoding="utf-8")
+ name, ok, err = await _apply_one(path.name, sql)
+ if ok:
+ logger.info("✓ applied %s", name)
+ else:
+ logger.error("✗ failed %s: %s", name, err)
+ failures.append((name, err or ""))
+
+ if failures:
+ logger.warning("%d migrations failed; see logs above", len(failures))
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/services/api/pyproject.toml b/services/api/pyproject.toml
index e86482401..df991bf52 100644
--- a/services/api/pyproject.toml
+++ b/services/api/pyproject.toml
@@ -20,7 +20,7 @@ httpx = ">=0.27,<0.29"
python-jose = { version = "^3.3.0", extras = ["cryptography"] }
PyJWT = "^2.8.0" # Used by OIDC and SAML auth flows (separate from python-jose)
cryptography = "^42.0.0" # Direct dep for credential vault Fernet
-passlib = { version = "^1.7.4", extras = ["bcrypt"] }
+bcrypt = "^4.1.2" # Used directly by app.core.security (passlib is no longer compatible with bcrypt >= 4)
python-multipart = "^0.0.9"
tenacity = ">=8.3,<10.0"
structlog = "^24.1.0"