| 1 | from fastapi import HTTPException |
| 2 | from loguru import logger |
| 3 | from sqlalchemy import select |
| 4 | from sqlalchemy.ext.asyncio import AsyncSession |
| 5 | |
| 6 | from app.connectors.wazuh_indexer.utils.universal import AlertsQueryBuilder |
| 7 | from app.connectors.wazuh_indexer.utils.universal import ( |
| 8 | create_wazuh_indexer_client_async, |
| 9 | ) |
| 10 | from app.db.universal_models import EventSources |
| 11 | from app.siem.schema.events import EventsQueryParams |
| 12 | from app.siem.schema.events import EventsQueryResponse |
| 13 | from app.siem.schema.events import FieldMapping |
| 14 | from app.siem.schema.events import FieldMappingsResponse |
| 15 | |
| 16 | |
| 17 | async def get_event_source_by_customer_and_name( |
| 18 | customer_code: str, |
| 19 | source_name: str, |
| 20 | db: AsyncSession, |
| 21 | ) -> EventSources: |
| 22 | result = await db.execute( |
| 23 | select(EventSources).where( |
| 24 | EventSources.customer_code == customer_code, |
| 25 | EventSources.name == source_name, |
| 26 | ), |
| 27 | ) |
| 28 | event_source = result.scalars().first() |
| 29 | if not event_source: |
| 30 | raise HTTPException( |
| 31 | status_code=404, |
| 32 | detail=f"Event source '{source_name}' not found for customer {customer_code}", |
| 33 | ) |
| 34 | if not event_source.enabled: |
| 35 | raise HTTPException( |
| 36 | status_code=400, |
| 37 | detail=f"Event source '{source_name}' is disabled", |
| 38 | ) |
| 39 | return event_source |
| 40 | |
| 41 | |
| 42 | async def query_events( |
| 43 | customer_code: str, |
| 44 | source_name: str, |
| 45 | params: EventsQueryParams, |
| 46 | db: AsyncSession, |
| 47 | ) -> EventsQueryResponse: |
| 48 | logger.info(f"Querying events for customer {customer_code}, source {source_name}") |
| 49 | |
| 50 | # If a scroll_id is provided, continue scrolling |
| 51 | if params.scroll_id: |
| 52 | return await _scroll_next_page(params.scroll_id) |
| 53 | |
| 54 | # Look up event source to get index_pattern and time_field |
| 55 | event_source = await get_event_source_by_customer_and_name(customer_code, source_name, db) |
| 56 | |
| 57 | return await _initial_search( |
| 58 | index_pattern=event_source.index_pattern, |
| 59 | time_field=event_source.time_field, |
| 60 | timerange=params.timerange, |
| 61 | page_size=params.page_size, |
| 62 | query=params.query, |
| 63 | time_from=params.time_from, |
| 64 | time_to=params.time_to, |
| 65 | ) |
| 66 | |
| 67 | |
| 68 | async def _initial_search( |
| 69 | index_pattern: str, |
| 70 | time_field: str, |
| 71 | timerange: str, |
| 72 | page_size: int, |
| 73 | query: str = None, |
| 74 | time_from: str = None, |
| 75 | time_to: str = None, |
| 76 | ) -> EventsQueryResponse: |
| 77 | es_client = await create_wazuh_indexer_client_async("Wazuh-Indexer") |
| 78 | try: |
| 79 | query_builder = AlertsQueryBuilder() |
| 80 | if time_from and time_to: |
| 81 | query_builder.add_absolute_time_range(time_from=time_from, time_to=time_to, timestamp_field=time_field) |
| 82 | else: |
| 83 | query_builder.add_time_range(timerange=timerange, timestamp_field=time_field) |
| 84 | query_builder.add_sort(time_field, order="desc") |
| 85 | |
| 86 | # Add Lucene query_string if provided |
| 87 | if query: |
| 88 | query_builder.query["query"]["bool"]["must"].append( |
| 89 | {"query_string": {"query": query, "default_operator": "AND"}}, |
| 90 | ) |
| 91 | |
| 92 | query = query_builder.build() |
| 93 | |
| 94 | response = await es_client.search( |
| 95 | index=index_pattern, |
| 96 | body=query, |
| 97 | size=page_size, |
| 98 | scroll="5m", |
| 99 | ) |
| 100 | |
| 101 | hits = response["hits"]["hits"] |
| 102 | total = response["hits"]["total"]["value"] if isinstance(response["hits"]["total"], dict) else response["hits"]["total"] |
| 103 | scroll_id = response.get("_scroll_id") |
| 104 | |
| 105 | # If all results fit in one page, clear the scroll context |
| 106 | if len(hits) >= total: |
| 107 | if scroll_id: |
| 108 | await _clear_scroll(es_client, scroll_id) |
| 109 | scroll_id = None |
| 110 | |
| 111 | return EventsQueryResponse( |
| 112 | events=[hit["_source"] for hit in hits], |
| 113 | total=total, |
| 114 | scroll_id=scroll_id, |
| 115 | page_size=page_size, |
| 116 | success=True, |
| 117 | message=f"Retrieved {len(hits)} of {total} events", |
| 118 | ) |
| 119 | except Exception as e: |
| 120 | logger.error(f"Error querying events: {e}") |
| 121 | raise HTTPException(status_code=500, detail=f"Error querying events: {e}") |
| 122 | finally: |
| 123 | await es_client.close() |
| 124 | |
| 125 | |
| 126 | async def _scroll_next_page(scroll_id: str) -> EventsQueryResponse: |
| 127 | es_client = await create_wazuh_indexer_client_async("Wazuh-Indexer") |
| 128 | try: |
| 129 | response = await es_client.scroll(scroll_id=scroll_id, scroll="5m") |
| 130 | hits = response["hits"]["hits"] |
| 131 | total = response["hits"]["total"]["value"] if isinstance(response["hits"]["total"], dict) else response["hits"]["total"] |
| 132 | new_scroll_id = response.get("_scroll_id") |
| 133 | |
| 134 | # If no more results, clear the scroll context |
| 135 | if not hits: |
| 136 | if new_scroll_id: |
| 137 | await _clear_scroll(es_client, new_scroll_id) |
| 138 | return EventsQueryResponse( |
| 139 | events=[], |
| 140 | total=total, |
| 141 | scroll_id=None, |
| 142 | page_size=0, |
| 143 | success=True, |
| 144 | message="No more results", |
| 145 | ) |
| 146 | |
| 147 | return EventsQueryResponse( |
| 148 | events=[hit["_source"] for hit in hits], |
| 149 | total=total, |
| 150 | scroll_id=new_scroll_id, |
| 151 | page_size=len(hits), |
| 152 | success=True, |
| 153 | message=f"Retrieved {len(hits)} of {total} events", |
| 154 | ) |
| 155 | except Exception as e: |
| 156 | logger.error(f"Error scrolling events: {e}") |
| 157 | raise HTTPException(status_code=500, detail=f"Error scrolling events: {e}") |
| 158 | finally: |
| 159 | await es_client.close() |
| 160 | |
| 161 | |
| 162 | async def _clear_scroll(es_client, scroll_id: str) -> None: |
| 163 | try: |
| 164 | await es_client.clear_scroll(scroll_id=scroll_id) |
| 165 | except Exception as e: |
| 166 | logger.warning(f"Failed to clear scroll context: {e}") |
| 167 | |
| 168 | |
| 169 | async def get_field_mappings( |
| 170 | customer_code: str, |
| 171 | source_name: str, |
| 172 | db: AsyncSession, |
| 173 | ) -> FieldMappingsResponse: |
| 174 | """Retrieve index field name mappings for a customer's event source.""" |
| 175 | event_source = await get_event_source_by_customer_and_name(customer_code, source_name, db) |
| 176 | es_client = await create_wazuh_indexer_client_async("Wazuh-Indexer") |
| 177 | try: |
| 178 | mapping_response = await es_client.indices.get_mapping(index=event_source.index_pattern) |
| 179 | |
| 180 | # Flatten nested mappings into dot-notation field list |
| 181 | fields = [] |
| 182 | for index_name in mapping_response: |
| 183 | properties = mapping_response[index_name].get("mappings", {}).get("properties", {}) |
| 184 | _flatten_properties(properties, "", fields) |
| 185 | break # All indices matching pattern share the same mapping |
| 186 | |
| 187 | # Deduplicate and sort |
| 188 | seen = set() |
| 189 | unique_fields = [] |
| 190 | for f in fields: |
| 191 | if f.field not in seen: |
| 192 | seen.add(f.field) |
| 193 | unique_fields.append(f) |
| 194 | unique_fields.sort(key=lambda x: x.field) |
| 195 | |
| 196 | return FieldMappingsResponse( |
| 197 | fields=unique_fields, |
| 198 | total=len(unique_fields), |
| 199 | index_pattern=event_source.index_pattern, |
| 200 | success=True, |
| 201 | message=f"Retrieved {len(unique_fields)} field mappings", |
| 202 | ) |
| 203 | except Exception as e: |
| 204 | logger.error(f"Error retrieving field mappings: {e}") |
| 205 | raise HTTPException(status_code=500, detail=f"Error retrieving field mappings: {e}") |
| 206 | finally: |
| 207 | await es_client.close() |
| 208 | |
| 209 | |
| 210 | def _flatten_properties(properties: dict, prefix: str, fields: list) -> None: |
| 211 | """Recursively flatten OpenSearch mapping properties into FieldMapping objects.""" |
| 212 | for field_name, field_info in properties.items(): |
| 213 | full_name = f"{prefix}{field_name}" if not prefix else f"{prefix}_{field_name}" |
| 214 | field_type = field_info.get("type") |
| 215 | if field_type: |
| 216 | fields.append(FieldMapping(field=full_name, type=field_type)) |
| 217 | # Recurse into nested properties |
| 218 | if "properties" in field_info: |
| 219 | _flatten_properties(field_info["properties"], full_name, fields) |