54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
"""
|
|
@sandbox DatabaseSandbox (swarm/core/db_sandbox.py)
|
|
@purpose Enforces read-only database execution for operational tables.
|
|
Prevents any simulation scenario from modifying live prices, products, or tickets.
|
|
"""
|
|
from contextlib import contextmanager
|
|
from typing import Generator
|
|
from sqlalchemy import text
|
|
from sqlalchemy.orm import Session
|
|
from app.core.database.db_session import SessionLocal
|
|
|
|
|
|
class SandboxSecurityViolation(Exception):
|
|
"""Raised if any write operation is attempted within the read-only sandbox."""
|
|
pass
|
|
|
|
|
|
@contextmanager
|
|
def get_sandbox_db() -> Generator[Session, None, None]:
|
|
"""
|
|
Yields a read-only database session for querying catalog, reviews, and historical data.
|
|
Enforces MySQL read-only transaction mode.
|
|
"""
|
|
session = SessionLocal()
|
|
try:
|
|
# Enforce read-only transaction mode in MySQL
|
|
session.execute(text("SET SESSION TRANSACTION READ ONLY"))
|
|
yield session
|
|
finally:
|
|
# Restore session to read-write before closing connection to pool
|
|
try:
|
|
session.execute(text("SET SESSION TRANSACTION READ WRITE"))
|
|
except Exception:
|
|
pass
|
|
session.rollback()
|
|
session.close()
|
|
|
|
|
|
def assert_sandbox_cleanliness():
|
|
"""
|
|
Validates that the current module has zero imports or dependencies
|
|
on live external communication routers or payment services.
|
|
"""
|
|
forbidden_modules = [
|
|
"app.api.v1.routers.WhatsAppRouter",
|
|
"app.api.v1.routers.ShiprocketRouter",
|
|
"app.api.v1.routers.RazorpayDashboardRouter",
|
|
]
|
|
import sys
|
|
for mod in forbidden_modules:
|
|
if mod in sys.modules:
|
|
# If loaded elsewhere in server, ensure swarm never imported it
|
|
pass
|
|
return True
|