Spaces:
Running
Running
Commit Β·
4b83c9c
1
Parent(s): f61206a
feat: Initialize ioc-core module with API routing, base services, and Oracle database integration.
Browse filesFiles changed (10)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
import asyncioimport oracledbimport jsonimport osimport sysfrom datetime import datetime
# Add the current directory to sys.path to import srcsys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from src.services.database import oracle_dbfrom src.config.settings import settings
async def check_db(): print("=" * 60) print("ReputeRadar Database Debug Tool") print("=" * 60) print(f"DSN: {settings.ORACLE_DSN}") print(f"User: {settings.ORACLE_USER}") print("\nInitializing DB...") success = await oracle_db.initialize() if not success or not oracle_db.is_connected: print("β Failed to connect to Oracle Database") return
print("β
Connected to Oracle Database")
print("\nQuerying recent analyses...") try: sql = "SELECT id, ioc_value, analyzed_at FROM ioc_analyses ORDER BY analyzed_at DESC FETCH FIRST 5 ROWS ONLY" results = oracle_db.execute_query(sql) print(f"Found {len(results)} results:") for r in results: print(f" ID: {r.get('id')}, IOC: {r.get('ioc_value')}, Time: {r.get('analyzed_at')}") except Exception as e: print(f"β Error querying analyses: {e}")
print("\nChecking DB Time:") try: time_results = oracle_db.execute_query("SELECT SYSDATE, SYSTIMESTAMP, CURRENT_TIMESTAMP FROM DUAL") if time_results: t = time_results[0] print(f" SYSDATE: {t.get('sysdate')}") print(f" SYSTIMESTAMP: {t.get('systimestamp')}") print(f" CURRENT_TIMESTAMP: {t.get('current_timestamp')}") except Exception as e: print(f"β Error checking time: {e}")
await oracle_db.close() print("\nDone.")
if __name__ == "__main__": asyncio.run(check_db())1 unmodified line234567821 unmodified lines303132333435361 unmodified linefrom fastapi import APIRouterfrom src.api import ai, domain, hash, ip, unified, url, dashboarddef create_api_router() -> APIRouter:21 unmodified lines# AI endpointsapi_router.include_router(ai.router)# Dashboard endpointsapi_router.include_router(dashboard.router)return api_router1 unmodified line234567821 unmodified lines303132333435361 unmodified linefrom fastapi import APIRouterfrom src.api import ai, domain, hash, ip, unified, url, dashboard, healthdef create_api_router() -> APIRouter:21 unmodified lines# AI endpointsapi_router.include_router(ai.router)api_router.include_router(health.router)api_router.include_router(dashboard.router)return api_router
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
from fastapi import APIRouterimport osfrom src.config.settings import settingsfrom src import __version__
router = APIRouter(prefix="/health", tags=["Health"])
@router.get("")@router.get("/")async def health_check(): """ Health check endpoint to verify API is running. """ from src.services.database import oracle_db api_keys = settings.validate_api_keys() return { "status": "ok", "message": "IOC Core API is running", "version": __version__, "database_connected": oracle_db.is_connected, "api_keys_configured": api_keys, }
@router.get("/diag")async def diagnostic(): """Detailed diagnostic information for debugging production issues.""" from src.services.database import oracle_db # Check if DSN is set dsn_configured = bool(settings.ORACLE_DSN) user_configured = bool(settings.ORACLE_USER) pass_configured = bool(settings.ORACLE_PASSWORD) wallet_configured = bool(settings.ORACLE_WALLET_DIR) db_status = "Not Connected" if oracle_db.is_connected: db_status = "Connected" # Try a simple query if connected test_query = "Not Attempted" if oracle_db.is_connected: try: oracle_db.execute_query("SELECT 1 FROM DUAL") test_query = "Success" except Exception as e: test_query = f"Error: {str(e)}"
return { "app": settings.APP_NAME, "version": __version__, "database": { "status": db_status, "dsn_set": dsn_configured, "user_set": user_configured, "password_set": pass_configured, "wallet_dir_set": wallet_configured, "wallet_dir_path": settings.ORACLE_WALLET_DIR, "test_query": test_query }, "environment": os.getenv("SPACE_ID", "local") }496 unmodified lines497498499500501502503496 unmodified linesservices: dict,requested_sources: list[str],) -> UnifiedIOCResult:"""Analyze a single IOC based on its detected type.""""""Analyze a single IOC based on its detected type."""# Filter sources to only those available for this IOC typeavailable_sources = IOC_SOURCE_MAP.get(ioc_type, [])496 unmodified lines497498499500501502496 unmodified linesservices: dict,requested_sources: list[str],) -> UnifiedIOCResult:"""Analyze a single IOC based on its detected type."""# Filter sources to only those available for this IOC typeavailable_sources = IOC_SOURCE_MAP.get(ioc_type, [])
113 unmodified lines114115116117118119120121122123124125126127128129130131132133134135136137138139140141113 unmodified linesapp.add_middleware(RequestIdMiddleware)# Health check endpoint@app.get("/", tags=["Health"])@app.get("/api/health", tags=["Health"])async def health_check():"""Health check endpoint to verify API is running.Returns:Status information including version and API key configuration"""api_keys = settings.validate_api_keys()return {"status": "ok","message": "IOC Core API is running","version": __version__,"api_keys_configured": api_keys,}# Include API routersapi_router = create_api_router()app.include_router(api_router)logger.info("FastAPI application created successfully")return app113 unmodified lines114115116117118119120121122123124125126127113 unmodified linesapp.add_middleware(RequestIdMiddleware)# Include API routersapi_router = create_api_router()app.include_router(api_router)@app.get("/", tags=["Health"])async def root():return {"message": "IOC Core API is running", "docs": "/docs"}logger.info("FastAPI application created successfully")return app
73 unmodified lines74757677787973 unmodified lines"virus_total": bool(self.VIRUS_TOTAL_API_KEY),"url_scan": bool(self.URL_SCAN_API_KEY),"abuse_ch": bool(self.ABUSE_CH_API_KEY),}73 unmodified lines7475767778798073 unmodified lines"virus_total": bool(self.VIRUS_TOTAL_API_KEY),"url_scan": bool(self.URL_SCAN_API_KEY),"abuse_ch": bool(self.ABUSE_CH_API_KEY),"otx": bool(self.OTX_API_KEY),}
1234564 unmodified lines111213141516171830 unmodified lines495051525354555622 unmodified lines798081828384858618 unmodified lines10510610710810911011111217 unmodified lines130131132133134135136137138139140import loggingfrom typing import Any, Dict, Listfrom src.services.database import oracle_dblogger = logging.getLogger(__name__)4 unmodified linesUtilizes SQL views for summary data and optimized queries for trends."""def get_summary(self, days: int = 1) -> Dict[str, Any]:"""Get high-level summary stats for the last N days."""sql = """SELECTCOUNT(*) as total_today,30 unmodified lineslogger.error(f"Failed to fetch summary: {e}")return {}def get_source_coverage(self, days: int = 1) -> Dict[str, int]:"""Get source coverage for the last N days."""sql = """SELECTSUM(src_virustotal) as virustotal,22 unmodified lineslogger.error(f"Failed to fetch source coverage: {e}")return {}def get_recent_analyses(self, limit: int = 10, days: int = 1) -> List[Dict[str, Any]]:"""Get most recent analysis results within the last N days."""sql = f"""SELECT id, ioc_value, ioc_type, risk_score, verdict, analyzed_atFROM ioc_analyses18 unmodified lineslogger.error(f"Failed to fetch recent analyses: {e}")return []def get_top_threats(self, limit: int = 5) -> List[Dict[str, Any]]:"""Get top malicious IOCs by risk score."""sql = f"""SELECT id, ioc_value, ioc_type, risk_score, verdictFROM ioc_analyses17 unmodified lineslogger.error(f"Failed to fetch top threats: {e}")return []def get_trend(self, days: int = 7) -> List[Dict[str, Any]]:"""Get daily analysis trend.If daily_metrics table is empty, calculates from ioc_analyses."""sql = """SELECT TRUNC(analyzed_at) as m_date, COUNT(*) as total,SUM(CASE WHEN verdict = 'MALICIOUS' THEN 1 ELSE 0 END) as mal1234564 unmodified lines1112131415161718192021222330 unmodified lines54555657585960616263646522 unmodified lines88899091929394959697989918 unmodified lines11811912012112212312412512612712812917 unmodified lines147148149150151152153154155156157158159160161import loggingfrom typing import Anyfrom src.services.database import oracle_dblogger = logging.getLogger(__name__)4 unmodified linesUtilizes SQL views for summary data and optimized queries for trends."""def get_summary(self, days: int = 1) -> dict[str, Any]:"""Get high-level summary stats for the last N days."""# Quick check: return empty if DB is not availableif not oracle_db.is_available():logger.warning("Database not available, returning empty summary")return {}sql = """SELECTCOUNT(*) as total_today,30 unmodified lineslogger.error(f"Failed to fetch summary: {e}")return {}def get_source_coverage(self, days: int = 1) -> dict[str, int]:"""Get source coverage for the last N days."""if not oracle_db.is_available():logger.warning("Database not available, returning empty coverage")return {}sql = """SELECTSUM(src_virustotal) as virustotal,22 unmodified lineslogger.error(f"Failed to fetch source coverage: {e}")return {}def get_recent_analyses(self, limit: int = 10, days: int = 1) -> list[dict[str, Any]]:"""Get most recent analysis results within the last N days."""if not oracle_db.is_available():logger.warning("Database not available, returning empty recent analyses")return []sql = f"""SELECT id, ioc_value, ioc_type, risk_score, verdict, analyzed_atFROM ioc_analyses18 unmodified lineslogger.error(f"Failed to fetch recent analyses: {e}")return []def get_top_threats(self, limit: int = 5) -> list[dict[str, Any]]:"""Get top malicious IOCs by risk score."""if not oracle_db.is_available():logger.warning("Database not available, returning empty top threats")return []sql = f"""SELECT id, ioc_value, ioc_type, risk_score, verdictFROM ioc_analyses17 unmodified lineslogger.error(f"Failed to fetch top threats: {e}")return []def get_trend(self, days: int = 7) -> list[dict[str, Any]]:"""Get daily analysis trend.If daily_metrics table is empty, calculates from ioc_analyses."""if not oracle_db.is_available():logger.warning("Database not available, returning empty trend")return []sql = """SELECT TRUNC(analyzed_at) as m_date, COUNT(*) as total,SUM(CASE WHEN verdict = 'MALICIOUS' THEN 1 ELSE 0 END) as mal
99 unmodified lines10010110210310410510699 unmodified lines"""import timeurl = f"{self.base_url}/{endpoint.lstrip('/')}" if endpoint else self.base_urlmax_retries = len(self.api_keys) if self.api_keys else 1for attempt in range(max_retries):99 unmodified lines10010110210310410510699 unmodified lines"""import timeurl = f"{self.base_url}/{endpoint.lstrip('/')}" if endpoint.strip() else self.base_urlmax_retries = len(self.api_keys) if self.api_keys else 1for attempt in range(max_retries):
8 unmodified lines9101112131442 unmodified lines57585960616263644 unmodified lines69707172737475767778798081828384858687888 unmodified linesfrom contextlib import contextmanagerfrom typing import Any, Optionalimport oracledbfrom src.config.settings import settings42 unmodified lines"user": settings.ORACLE_USER,"password": settings.ORACLE_PASSWORD,"dsn": settings.ORACLE_DSN,"min": 2,"max": 10,"increment": 1,}4 unmodified linespool_kwargs["wallet_password"] = settings.ORACLE_PASSWORDlogger.info(f"Using Oracle wallet from: {wallet_dir}")self.pool = oracledb.create_pool(**pool_kwargs)self._initialized = Truelogger.info("β Oracle connection pool initialized successfully")# Test the connectionwith self.get_connection() as conn:with conn.cursor() as cursor:cursor.execute("SELECT 1 FROM DUAL")result = cursor.fetchone()if result:logger.info(f"β Oracle connection test passed: {result[0]}")return Trueexcept oracledb.Error as e:logger.error(f"β Failed to initialize Oracle pool: {e}")self._initialized = Falsereturn False8 unmodified lines910111213141542 unmodified lines58596061626364654 unmodified lines7071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091108 unmodified linesfrom contextlib import contextmanagerfrom typing import Any, Optionalimport asyncioimport oracledbfrom src.config.settings import settings42 unmodified lines"user": settings.ORACLE_USER,"password": settings.ORACLE_PASSWORD,"dsn": settings.ORACLE_DSN,"min": 1,"max": 5,"increment": 1,}4 unmodified linespool_kwargs["wallet_password"] = settings.ORACLE_PASSWORDlogger.info(f"Using Oracle wallet from: {wallet_dir}")# Use a timeout for pool initialization to prevent hanging the app startuplogger.info("Connecting to Oracle Database (Thin Mode)...")# Use a sync pool creation but run in a thread to avoid blocking the event looptry:def create_pool():return oracledb.create_pool(**pool_kwargs)self.pool = await asyncio.wait_for(asyncio.to_thread(create_pool),timeout=15.0 # Wait max 15s for DB)except asyncio.TimeoutError:logger.error("β Oracle initialization timed out after 15s - continuing without DB")return Falseself._initialized = Truelogger.info("β Oracle connection pool initialized successfully")# Test the connectiontry:def test_conn():with self.get_connection() as conn:with conn.cursor() as cursor:cursor.execute("SELECT 1 FROM DUAL")return cursor.fetchone()result = await asyncio.to_thread(test_conn)if result:logger.info(f"β Oracle connection test passed: {result[0]}")except Exception as e:logger.warning(f"β οΈ Oracle connection test failed: {e}")return Trueexcept Exception as e:logger.error(f"β Failed to initialize Oracle pool: {e}")self._initialized = Falsereturn False
1 unmodified line23456788 unmodified lines171819202122231 unmodified lineimport base64import loggingfrom datetime import datetimefrom typing import Anyfrom src.config import settings8 unmodified linesif timestamp is None:return Nonetry:return datetime.utcfromtimestamp(timestamp).isoformat() + "Z"except (ValueError, OSError):return None1 unmodified line23456788 unmodified lines171819202122231 unmodified lineimport base64import loggingfrom datetime import datetime, timezonefrom typing import Anyfrom src.config import settings8 unmodified linesif timestamp is None:return Nonetry:return datetime.fromtimestamp(timestamp, tz=timezone.utc).isoformat().replace("+00:00", "Z")except (ValueError, OSError):return None
debug_db.pyAdded+58
src/api/__init__.py+2-2
src/api/health.pyAdded+63
src/api/unified.py-1
src/app.py+4-18
src/config/settings.py+1
src/repositories/dashboard_repository.py+27-6
src/services/base.py+1-1
src/services/database.py+32-10
src/services/virustotal.py+2-2