forked from natesmalley/jarvis_coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
260 lines (226 loc) · 6.54 KB
/
Copy pathmain.py
File metadata and controls
260 lines (226 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""
Jarvis Coding API - Main Application
Security Event Generation Platform
"""
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
from pydantic import ValidationError
import logging
import sys
import uuid
from pathlib import Path
# Add parent directories to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from app.core.config import settings
from app.routers import generators, parsers, health, scenarios, export, metrics, search, categories, destinations, uploads, parser_sync, alerts, threat_intel
from app.routers import settings as settings_router
from app.utils.logging import setup_logging
from app.core.simple_auth import validate_api_keys_config
from app.services.destination_service import init_db
# Setup logging
setup_logging()
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage application lifecycle"""
# Startup
logger.info(f"Starting {settings.PROJECT_NAME} v{settings.PROJECT_VERSION}")
logger.info(f"Generators path: {settings.GENERATORS_PATH}")
logger.info(f"Parsers path: {settings.PARSERS_PATH}")
# Initialize database
await init_db()
# Initialize and validate authentication
auth_config = validate_api_keys_config()
yield
# Shutdown
logger.info("Shutting down API server")
# Create FastAPI application
app = FastAPI(
title=settings.PROJECT_NAME,
description=settings.PROJECT_DESCRIPTION,
version=settings.PROJECT_VERSION,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
docs_url=f"{settings.API_V1_STR}/docs",
redoc_url=f"{settings.API_V1_STR}/redoc",
lifespan=lifespan
)
# Configure CORS
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
else:
# Development mode - allow all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Exception handlers
@app.exception_handler(ValidationError)
async def validation_exception_handler(request: Request, exc: ValidationError):
return JSONResponse(
status_code=422,
content={
"success": False,
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": exc.errors()
}
}
)
@app.exception_handler(422)
async def unprocessable_entity_handler(request: Request, exc):
return JSONResponse(
status_code=422,
content={
"success": False,
"error": {
"code": "UNPROCESSABLE_ENTITY",
"message": "The request was well-formed but contains semantic errors"
}
}
)
@app.exception_handler(404)
async def not_found_handler(request: Request, exc):
return JSONResponse(
status_code=404,
content={
"success": False,
"error": {
"code": "NOT_FOUND",
"message": f"Path {request.url.path} not found"
}
}
)
@app.exception_handler(500)
async def internal_error_handler(request: Request, exc):
logger.error(f"Internal server error: {exc}")
return JSONResponse(
status_code=500,
content={
"success": False,
"error": {
"code": "INTERNAL_ERROR",
"message": "An internal server error occurred"
}
}
)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
logger.error(f"Unhandled exception: {exc}", exc_info=True)
return JSONResponse(
status_code=500,
content={
"success": False,
"error": {
"code": "INTERNAL_SERVER_ERROR",
"message": "An unexpected error occurred",
"request_id": str(uuid.uuid4()) # For tracking
}
}
)
# Root endpoint
@app.get("/")
async def root():
"""Root endpoint"""
return {
"name": settings.PROJECT_NAME,
"version": settings.PROJECT_VERSION,
"description": settings.PROJECT_DESCRIPTION,
"docs": f"{settings.API_V1_STR}/docs",
"health": f"{settings.API_V1_STR}/health",
"authentication": {
"enabled": not settings.DISABLE_AUTH,
"methods": ["X-API-Key header", "api_key query parameter"] if not settings.DISABLE_AUTH else ["disabled"]
}
}
# Include routers
app.include_router(
health.router,
prefix=f"{settings.API_V1_STR}/health",
tags=["health"]
)
app.include_router(
generators.router,
prefix=f"{settings.API_V1_STR}/generators",
tags=["generators"]
)
app.include_router(
parsers.router,
prefix=f"{settings.API_V1_STR}/parsers",
tags=["parsers"]
)
app.include_router(
scenarios.router,
prefix=f"{settings.API_V1_STR}/scenarios",
tags=["scenarios"]
)
app.include_router(
export.router,
prefix=f"{settings.API_V1_STR}/export",
tags=["export"]
)
app.include_router(
metrics.router,
prefix=f"{settings.API_V1_STR}/metrics",
tags=["metrics"]
)
app.include_router(
search.router,
prefix=f"{settings.API_V1_STR}/search",
tags=["search"]
)
app.include_router(
categories.router,
prefix=f"{settings.API_V1_STR}/categories",
tags=["categories"]
)
app.include_router(
destinations.router,
prefix=f"{settings.API_V1_STR}/destinations",
tags=["destinations"]
)
app.include_router(
uploads.router,
prefix=f"{settings.API_V1_STR}/uploads",
tags=["uploads"]
)
app.include_router(
parser_sync.router,
prefix=f"{settings.API_V1_STR}/parser-sync",
tags=["parser-sync"]
)
app.include_router(
settings_router.router,
prefix=f"{settings.API_V1_STR}/settings",
tags=["settings"]
)
app.include_router(
alerts.router,
prefix=f"{settings.API_V1_STR}/alerts",
tags=["alerts"]
)
app.include_router(
threat_intel.router,
prefix=f"{settings.API_V1_STR}/threat-intel",
tags=["threat-intel"]
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app.main:app",
host=settings.HOST,
port=settings.PORT,
reload=settings.RELOAD,
log_level=settings.LOG_LEVEL
)