Sin descripción

main.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. from fastapi import Depends, FastAPI, HTTPException
  2. from app.adapters.iris import IrisAdapter
  3. from app.adapters.pagerduty import PagerDutyAdapter
  4. from app.adapters.shuffle import ShuffleAdapter
  5. from app.adapters.wazuh import WazuhAdapter
  6. from app.config import settings
  7. from app.db import init_schema
  8. from app.models import (
  9. ActionCreateIncidentRequest,
  10. ApiResponse,
  11. ShuffleLoginRequest,
  12. ShuffleProxyRequest,
  13. TriggerShuffleRequest,
  14. WazuhIngestRequest,
  15. )
  16. from app.repositories.mvp_repo import MvpRepository
  17. from app.routes.mvp import build_mvp_router
  18. from app.security import require_internal_api_key
  19. from app.services.mvp_service import MvpService
  20. app = FastAPI(title=settings.app_name, version="0.1.0")
  21. wazuh_adapter = WazuhAdapter(
  22. base_url=settings.wazuh_base_url,
  23. username=settings.wazuh_username,
  24. password=settings.wazuh_password,
  25. indexer_url=settings.wazuh_indexer_url,
  26. indexer_username=settings.wazuh_indexer_username,
  27. indexer_password=settings.wazuh_indexer_password,
  28. )
  29. shuffle_adapter = ShuffleAdapter(
  30. base_url=settings.shuffle_base_url,
  31. api_key=settings.shuffle_api_key,
  32. )
  33. pagerduty_adapter = PagerDutyAdapter(
  34. base_url=settings.pagerduty_base_url,
  35. api_key=settings.pagerduty_api_key,
  36. )
  37. iris_adapter = IrisAdapter(
  38. base_url=settings.iris_base_url,
  39. api_key=settings.iris_api_key,
  40. )
  41. repo = MvpRepository()
  42. mvp_service = MvpService(
  43. repo=repo,
  44. wazuh_adapter=wazuh_adapter,
  45. shuffle_adapter=shuffle_adapter,
  46. iris_adapter=iris_adapter,
  47. pagerduty_adapter=pagerduty_adapter,
  48. )
  49. app.include_router(build_mvp_router(mvp_service, require_internal_api_key))
  50. @app.on_event("startup")
  51. async def startup() -> None:
  52. init_schema()
  53. repo.ensure_policy()
  54. @app.get("/health", response_model=ApiResponse)
  55. async def health() -> ApiResponse:
  56. return ApiResponse(
  57. data={
  58. "service": settings.app_name,
  59. "env": settings.app_env,
  60. "targets": {
  61. "wazuh": settings.wazuh_base_url,
  62. "shuffle": settings.shuffle_base_url,
  63. "pagerduty": settings.pagerduty_base_url,
  64. "iris": settings.iris_base_url,
  65. },
  66. }
  67. )
  68. @app.post("/ingest/wazuh-alert", response_model=ApiResponse)
  69. async def ingest_wazuh_alert(payload: WazuhIngestRequest) -> ApiResponse:
  70. normalized = {
  71. "source": payload.source,
  72. "alert_id": payload.alert_id,
  73. "rule_id": payload.rule_id,
  74. "severity": payload.severity,
  75. "title": payload.title,
  76. "payload": payload.payload,
  77. }
  78. return ApiResponse(data={"normalized": normalized})
  79. @app.post("/action/create-incident", response_model=ApiResponse)
  80. async def create_incident(payload: ActionCreateIncidentRequest) -> ApiResponse:
  81. incident_payload = {
  82. "title": payload.title,
  83. "urgency": payload.severity,
  84. "incident_key": payload.dedupe_key,
  85. "body": payload.payload,
  86. "source": payload.source,
  87. }
  88. try:
  89. pd_result = await pagerduty_adapter.create_incident(incident_payload)
  90. except Exception as exc:
  91. raise HTTPException(status_code=502, detail=f"PagerDuty call failed: {exc}") from exc
  92. return ApiResponse(data={"pagerduty": pd_result})
  93. @app.post("/action/trigger-shuffle", response_model=ApiResponse)
  94. async def trigger_shuffle(payload: TriggerShuffleRequest) -> ApiResponse:
  95. try:
  96. shuffle_result = await shuffle_adapter.trigger_workflow(
  97. workflow_id=payload.workflow_id,
  98. payload=payload.execution_argument,
  99. )
  100. except Exception as exc:
  101. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  102. return ApiResponse(data={"shuffle": shuffle_result})
  103. @app.get("/shuffle/health", response_model=ApiResponse)
  104. async def shuffle_health() -> ApiResponse:
  105. try:
  106. result = await shuffle_adapter.health()
  107. except Exception as exc:
  108. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  109. return ApiResponse(data={"shuffle": result})
  110. @app.get("/shuffle/auth-test", response_model=ApiResponse)
  111. async def shuffle_auth_test() -> ApiResponse:
  112. try:
  113. result = await shuffle_adapter.auth_test()
  114. except Exception as exc:
  115. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  116. return ApiResponse(data={"shuffle": result})
  117. @app.post("/shuffle/login", response_model=ApiResponse)
  118. async def shuffle_login(payload: ShuffleLoginRequest) -> ApiResponse:
  119. try:
  120. result = await shuffle_adapter.login(payload.username, payload.password)
  121. except Exception as exc:
  122. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  123. return ApiResponse(data={"shuffle": result})
  124. @app.post("/shuffle/generate-apikey", response_model=ApiResponse)
  125. async def shuffle_generate_apikey(payload: ShuffleLoginRequest | None = None) -> ApiResponse:
  126. username = payload.username if payload else settings.shuffle_username
  127. password = payload.password if payload else settings.shuffle_password
  128. if not username or not password:
  129. raise HTTPException(
  130. status_code=400,
  131. detail="Missing shuffle credentials. Provide username/password in body or set SHUFFLE_USERNAME and SHUFFLE_PASSWORD.",
  132. )
  133. try:
  134. result = await shuffle_adapter.generate_apikey_from_login(username, password)
  135. except Exception as exc:
  136. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  137. return ApiResponse(data={"shuffle": result})
  138. @app.get("/shuffle/workflows", response_model=ApiResponse)
  139. async def shuffle_workflows() -> ApiResponse:
  140. try:
  141. result = await shuffle_adapter.list_workflows()
  142. except Exception as exc:
  143. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  144. return ApiResponse(data={"shuffle": result})
  145. @app.get("/shuffle/workflows/{workflow_id}", response_model=ApiResponse)
  146. async def shuffle_workflow(workflow_id: str) -> ApiResponse:
  147. try:
  148. result = await shuffle_adapter.get_workflow(workflow_id)
  149. except Exception as exc:
  150. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  151. return ApiResponse(data={"shuffle": result})
  152. @app.post("/shuffle/workflows/{workflow_id}/execute", response_model=ApiResponse)
  153. async def shuffle_workflow_execute(
  154. workflow_id: str, payload: dict[str, object]
  155. ) -> ApiResponse:
  156. try:
  157. result = await shuffle_adapter.trigger_workflow(workflow_id=workflow_id, payload=payload)
  158. except Exception as exc:
  159. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  160. return ApiResponse(data={"shuffle": result})
  161. @app.get("/shuffle/apps", response_model=ApiResponse)
  162. async def shuffle_apps() -> ApiResponse:
  163. try:
  164. result = await shuffle_adapter.list_apps()
  165. except Exception as exc:
  166. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  167. return ApiResponse(data={"shuffle": result})
  168. @app.post("/shuffle/proxy", response_model=ApiResponse)
  169. async def shuffle_proxy(payload: ShuffleProxyRequest) -> ApiResponse:
  170. path = payload.path if payload.path.startswith("/api/") else f"/api/v1/{payload.path.lstrip('/')}"
  171. try:
  172. result = await shuffle_adapter.proxy(
  173. method=payload.method,
  174. path=path,
  175. params=payload.params,
  176. payload=payload.payload,
  177. )
  178. except Exception as exc:
  179. raise HTTPException(status_code=502, detail=f"Shuffle call failed: {exc}") from exc
  180. return ApiResponse(data={"shuffle": result})
  181. @app.post("/action/create-iris-case", response_model=ApiResponse)
  182. async def create_iris_case(payload: ActionCreateIncidentRequest) -> ApiResponse:
  183. # IRIS v2 expects case_name, case_description, case_customer, case_soc_id.
  184. case_payload = {
  185. "case_name": payload.title,
  186. "case_description": payload.payload.get("description", "Created by soc-integrator"),
  187. "case_customer": payload.payload.get("case_customer", settings.iris_default_customer_id),
  188. "case_soc_id": payload.payload.get("case_soc_id", settings.iris_default_soc_id),
  189. }
  190. try:
  191. iris_result = await iris_adapter.create_case(case_payload)
  192. except Exception as exc:
  193. raise HTTPException(status_code=502, detail=f"IRIS call failed: {exc}") from exc
  194. return ApiResponse(data={"iris": iris_result})
  195. @app.get("/sync/wazuh-version", response_model=ApiResponse)
  196. async def sync_wazuh_version() -> ApiResponse:
  197. try:
  198. wazuh_result = await wazuh_adapter.get_version()
  199. except Exception as exc:
  200. raise HTTPException(status_code=502, detail=f"Wazuh call failed: {exc}") from exc
  201. return ApiResponse(data={"wazuh": wazuh_result})
  202. @app.get("/wazuh/auth-test", response_model=ApiResponse)
  203. async def wazuh_auth_test() -> ApiResponse:
  204. try:
  205. result = await wazuh_adapter.auth_test()
  206. except Exception as exc:
  207. raise HTTPException(status_code=502, detail=f"Wazuh auth failed: {exc}") from exc
  208. return ApiResponse(data={"wazuh": result})
  209. @app.get("/wazuh/manager-info", response_model=ApiResponse)
  210. async def wazuh_manager_info() -> ApiResponse:
  211. try:
  212. result = await wazuh_adapter.get_manager_info()
  213. except Exception as exc:
  214. raise HTTPException(status_code=502, detail=f"Wazuh call failed: {exc}") from exc
  215. return ApiResponse(data={"wazuh": result})
  216. @app.get("/wazuh/agents", response_model=ApiResponse)
  217. async def wazuh_agents(
  218. limit: int = 50,
  219. offset: int = 0,
  220. select: str | None = None,
  221. ) -> ApiResponse:
  222. try:
  223. result = await wazuh_adapter.list_agents(limit=limit, offset=offset, select=select)
  224. except Exception as exc:
  225. raise HTTPException(status_code=502, detail=f"Wazuh call failed: {exc}") from exc
  226. return ApiResponse(data={"wazuh": result})
  227. @app.get("/wazuh/alerts", response_model=ApiResponse)
  228. async def wazuh_alerts(
  229. limit: int = 50,
  230. offset: int = 0,
  231. q: str | None = None,
  232. sort: str | None = None,
  233. ) -> ApiResponse:
  234. try:
  235. # In this Wazuh build, API alerts are exposed via manager logs.
  236. result = await wazuh_adapter.list_manager_logs(
  237. limit=limit, offset=offset, q=q, sort=sort
  238. )
  239. except Exception as exc:
  240. raise HTTPException(status_code=502, detail=f"Wazuh call failed: {exc}") from exc
  241. return ApiResponse(data={"wazuh": result})
  242. @app.get("/wazuh/manager-logs", response_model=ApiResponse)
  243. async def wazuh_manager_logs(
  244. limit: int = 50,
  245. offset: int = 0,
  246. q: str | None = None,
  247. sort: str | None = None,
  248. ) -> ApiResponse:
  249. try:
  250. result = await wazuh_adapter.list_manager_logs(
  251. limit=limit, offset=offset, q=q, sort=sort
  252. )
  253. except Exception as exc:
  254. raise HTTPException(status_code=502, detail=f"Wazuh call failed: {exc}") from exc
  255. return ApiResponse(data={"wazuh": result})
  256. @app.post("/wazuh/sync-to-mvp", response_model=ApiResponse, dependencies=[Depends(require_internal_api_key)])
  257. async def wazuh_sync_to_mvp(
  258. limit: int = 50,
  259. minutes: int = 120,
  260. q: str = "soc_mvp_test=true OR event_type:*",
  261. ) -> ApiResponse:
  262. try:
  263. result = await mvp_service.sync_wazuh_alerts(query=q, limit=limit, minutes=minutes)
  264. except Exception as exc:
  265. raise HTTPException(status_code=502, detail=f"Wazuh sync failed: {exc}") from exc
  266. return ApiResponse(data={"sync": result})