siphai-core 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- siphai_core/__init__.py +21 -0
- siphai_core/agent/__init__.py +0 -0
- siphai_core/agent/memory/__init__.py +0 -0
- siphai_core/agent/prompts/__init__.py +0 -0
- siphai_core/agent/tools/__init__.py +0 -0
- siphai_core/core/__init__.py +0 -0
- siphai_core/core/config/__init__.py +0 -0
- siphai_core/core/config/settings.py +82 -0
- siphai_core/core/interfaces/__init__.py +0 -0
- siphai_core/core/interfaces/alert_provider.py +148 -0
- siphai_core/core/interfaces/case_provider.py +275 -0
- siphai_core/core/interfaces/notification_provider.py +16 -0
- siphai_core/core/logging_config.py +82 -0
- siphai_core/core/models/__init__.py +0 -0
- siphai_core/core/models/schemas.py +370 -0
- siphai_core/core/services/__init__.py +0 -0
- siphai_core/core/services/aggregator.py +484 -0
- siphai_core/integrations/__init__.py +0 -0
- siphai_core/integrations/elasticsearch/__init__.py +0 -0
- siphai_core/integrations/elasticsearch/service.py +294 -0
- siphai_core/integrations/external/__init__.py +0 -0
- siphai_core/integrations/external/abuseipdb.py +97 -0
- siphai_core/integrations/external/cache.py +102 -0
- siphai_core/integrations/external/enrichment.py +365 -0
- siphai_core/integrations/external/greynoise.py +76 -0
- siphai_core/integrations/external/rate_limiter.py +96 -0
- siphai_core/integrations/external/virustotal.py +106 -0
- siphai_core/integrations/slack/__init__.py +0 -0
- siphai_core/integrations/telegram/__init__.py +0 -0
- siphai_core/integrations/telegram/service.py +111 -0
- siphai_core/integrations/wazuh/__init__.py +0 -0
- siphai_core/mcp/__init__.py +0 -0
- siphai_core/mcp/handlers/__init__.py +0 -0
- siphai_core/mcp/handlers/errors.py +7 -0
- siphai_core/mcp/server.py +46 -0
- siphai_core/mcp/tools/__init__.py +0 -0
- siphai_core/mcp/tools/health_check.py +28 -0
- siphai_core/utils/__init__.py +0 -0
- siphai_core-0.1.0.dist-info/METADATA +202 -0
- siphai_core-0.1.0.dist-info/RECORD +41 -0
- siphai_core-0.1.0.dist-info/WHEEL +4 -0
siphai_core/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""SiphAI Core — AI-Managed SOC Triage Alert System.
|
|
2
|
+
|
|
3
|
+
Usage: ``import siphai_core as sc``. Top-level exports stay light
|
|
4
|
+
(config + logging); import subpackages for services and integrations::
|
|
5
|
+
|
|
6
|
+
from siphai_core.core.services.aggregator import AggregatorService
|
|
7
|
+
from siphai_core.integrations.elasticsearch import ElasticsearchService
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from importlib.metadata import PackageNotFoundError
|
|
11
|
+
from importlib.metadata import version as _pkg_version
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
__version__ = _pkg_version("siphai-core")
|
|
15
|
+
except PackageNotFoundError: # running from a source checkout, not installed
|
|
16
|
+
__version__ = "0.0.0.dev0"
|
|
17
|
+
|
|
18
|
+
from siphai_core.core.config.settings import Settings, get_settings
|
|
19
|
+
from siphai_core.core.logging_config import setup_logging
|
|
20
|
+
|
|
21
|
+
__all__ = ["Settings", "get_settings", "setup_logging"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from functools import lru_cache
|
|
2
|
+
|
|
3
|
+
from pydantic import Field
|
|
4
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
5
|
+
|
|
6
|
+
# pydantic_settings.BaseSettings: .env dosyasındaki değişkenleri okuyup python class'a çevirir.
|
|
7
|
+
# functools.lru_cache : İlk çağrıda .env okunur, sonraki çağrılarda cache'den döner.
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
# Settings class (BaseSettings'ten kalıtım alır)
|
|
11
|
+
# Her .env değişkeni için bir field tanımlanır.
|
|
12
|
+
# Field'lar default değerler ve validation içerir. -> .env okunamazsa değerlerin yerine geçerler.
|
|
13
|
+
class Settings(BaseSettings):
|
|
14
|
+
# Pydantic v2 standardı (Config class yerine)
|
|
15
|
+
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
|
|
16
|
+
|
|
17
|
+
app_name: str = "ai-soc-triage"
|
|
18
|
+
debug: bool = False
|
|
19
|
+
log_level: str = "INFO"
|
|
20
|
+
# structlog renderer: "json" | "console" | None (None -> based on debug; see SiphAI-SOC/docs design/software/logging.md)
|
|
21
|
+
log_format: str | None = None
|
|
22
|
+
elasticsearch_host: str = "http://localhost:9200"
|
|
23
|
+
elasticsearch_username: str = "elastic"
|
|
24
|
+
elasticsearch_password: str = "changeme"
|
|
25
|
+
elasticsearch_ca_certs: str | None = None
|
|
26
|
+
# Verilirse basic_auth yerine API key ile bağlanılır
|
|
27
|
+
elasticsearch_api_key: str | None = None
|
|
28
|
+
# Case write işlemleri için ayrı (yüksek yetkili) API key
|
|
29
|
+
elasticsearch_case_api_key: str | None = None
|
|
30
|
+
# Case write işlemleri için named user (restricted index yazımı) — basic auth
|
|
31
|
+
elasticsearch_case_username: str | None = None
|
|
32
|
+
elasticsearch_case_password: str | None = None
|
|
33
|
+
# Case oluşturulurken created_by.profile_uid olarak yazılan kullanıcı profil UID'si
|
|
34
|
+
elasticsearch_profile_uid: str | None = None
|
|
35
|
+
|
|
36
|
+
telegram_bot_token: str = ""
|
|
37
|
+
telegram_chat_id: str = ""
|
|
38
|
+
virustotal_api_key: str = ""
|
|
39
|
+
abuseipdb_api_key: str = ""
|
|
40
|
+
greynoise_api_key: str = ""
|
|
41
|
+
openai_api_key: str = ""
|
|
42
|
+
openai_model: str = "gpt-4o"
|
|
43
|
+
mcp_transport: str = "stdio"
|
|
44
|
+
|
|
45
|
+
redis_url: str = "redis://localhost:6379"
|
|
46
|
+
redis_cache_ttl: int = 86400
|
|
47
|
+
|
|
48
|
+
rest_api_host: str = "0.0.0.0"
|
|
49
|
+
rest_api_port: int = 8001
|
|
50
|
+
mcp_server_port: int = 8000
|
|
51
|
+
|
|
52
|
+
jwt_secret_key: str = "your-secret-key"
|
|
53
|
+
jwt_algorithm: str = "HS256"
|
|
54
|
+
webhook_secret: str = ""
|
|
55
|
+
|
|
56
|
+
# Elasticsearch retry / timeout (elasticsearch_client.py için)
|
|
57
|
+
max_retries: int = 3
|
|
58
|
+
request_timeout: int = 30
|
|
59
|
+
|
|
60
|
+
rate_limit_requests: int = 100
|
|
61
|
+
rate_limit_window: int = 60
|
|
62
|
+
|
|
63
|
+
# Verdict skorlaması: her kaynağın 0-100 normalize alt skorunun ağırlıklı ortalaması.
|
|
64
|
+
# Başlangıçta eşit (1.0); ileride gerçek veriyle kalibre edilecek (docs/ENRICHMENT_PIPELINE.md).
|
|
65
|
+
# Negatif ağırlık anlamsız ve skorlamayı bozar — ge=0 ile engellenir.
|
|
66
|
+
verdict_weight_virustotal: float = Field(default=1.0, ge=0)
|
|
67
|
+
verdict_weight_abuseipdb: float = Field(default=1.0, ge=0)
|
|
68
|
+
verdict_weight_greynoise: float = Field(default=1.0, ge=0)
|
|
69
|
+
|
|
70
|
+
# Aggregation (alert gruplama)
|
|
71
|
+
aggregation_enabled: bool = True
|
|
72
|
+
aggregation_dedup_window_seconds: int = 300 # 5 dk
|
|
73
|
+
aggregation_time_window_seconds: int = 900 # 15 dk
|
|
74
|
+
aggregation_correlation_window_seconds: int = 3600 # 1 saat
|
|
75
|
+
aggregation_max_alerts_per_group: int = 100
|
|
76
|
+
aggregation_poll_interval_seconds: int = 30
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# get_settings() fonksiyonu (@lru_cache decorator ile)
|
|
80
|
+
@lru_cache
|
|
81
|
+
def get_settings() -> Settings:
|
|
82
|
+
return Settings()
|
|
File without changes
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Any
|
|
3
|
+
|
|
4
|
+
from siphai_core.integrations.elasticsearch.service import ElasticsearchService
|
|
5
|
+
|
|
6
|
+
# Kibana'nın rule tipi bağımsız (security, observability threshold, vb.) tüm
|
|
7
|
+
# alert'leri yazdığı sistem index deseni. Başındaki nokta önemli, "alerts-*" değil.
|
|
8
|
+
ALERTS_INDEX = ".alerts-*"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AlertProvider(ABC):
|
|
12
|
+
"""Alert sorgulama sözleşmesi. Farklı kaynaklar (Elastic, mock, vb.) bunu implemente eder."""
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
async def search_alerts(
|
|
16
|
+
self,
|
|
17
|
+
kql_query: str | None = None,
|
|
18
|
+
severity: str | None = None,
|
|
19
|
+
status: str | None = None,
|
|
20
|
+
time_range_start: str | None = None,
|
|
21
|
+
time_range_end: str | None = None,
|
|
22
|
+
page: int = 1,
|
|
23
|
+
page_size: int = 50,
|
|
24
|
+
) -> dict[str, Any]:
|
|
25
|
+
"""Filtrelere göre alert listesi + toplam sayı + sayfa bilgisi döner."""
|
|
26
|
+
...
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
async def get_alert_by_id(self, alert_id: str) -> dict[str, Any] | None:
|
|
30
|
+
"""Tek bir alert document'ını id ile getirir, yoksa None döner."""
|
|
31
|
+
...
|
|
32
|
+
|
|
33
|
+
@abstractmethod
|
|
34
|
+
async def get_alert_fields(self, alert_id: str) -> dict[str, Any] | None:
|
|
35
|
+
"""Alert'in önemli field'larını yapılandırılmış dict olarak döndürür."""
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
async def update_alert_status(
|
|
40
|
+
self, alert_id: str, status: str, comment: str | None = None
|
|
41
|
+
) -> bool:
|
|
42
|
+
"""Alert durumunu günceller (new/in_progress/resolved/false_positive)."""
|
|
43
|
+
...
|
|
44
|
+
|
|
45
|
+
@abstractmethod
|
|
46
|
+
async def add_alert_tags(self, alert_id: str, tags: list[str]) -> bool:
|
|
47
|
+
"""Alert'e duplicate kontrolü yaparak tag(ler) ekler."""
|
|
48
|
+
...
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class ElasticsearchAlertProvider(AlertProvider):
|
|
52
|
+
"""AlertProvider'ın Elasticsearch implementasyonu. Bağlı bir ElasticsearchService kullanır."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, es_service: ElasticsearchService):
|
|
55
|
+
self.es = es_service
|
|
56
|
+
|
|
57
|
+
def _build_query(
|
|
58
|
+
self,
|
|
59
|
+
kql_query: str | None,
|
|
60
|
+
severity: str | None,
|
|
61
|
+
status: str | None,
|
|
62
|
+
time_range_start: str | None,
|
|
63
|
+
time_range_end: str | None,
|
|
64
|
+
) -> dict[str, Any]:
|
|
65
|
+
"""Filtrelerden Elasticsearch bool query'si kurar."""
|
|
66
|
+
filters: list[dict[str, Any]] = []
|
|
67
|
+
|
|
68
|
+
# zaman aralığı varsa @timestamp üzerinden range filtresi ekle
|
|
69
|
+
if time_range_start or time_range_end:
|
|
70
|
+
time_range: dict[str, Any] = {}
|
|
71
|
+
if time_range_start:
|
|
72
|
+
time_range["gte"] = time_range_start
|
|
73
|
+
if time_range_end:
|
|
74
|
+
time_range["lte"] = time_range_end
|
|
75
|
+
filters.append({"range": {"@timestamp": time_range}})
|
|
76
|
+
|
|
77
|
+
# severity/status verildiyse exact-match term filtresi ekle
|
|
78
|
+
if severity:
|
|
79
|
+
filters.append({"term": {"kibana.alert.severity": severity}})
|
|
80
|
+
if status:
|
|
81
|
+
filters.append({"term": {"kibana.alert.workflow_status": status}})
|
|
82
|
+
|
|
83
|
+
# hiç filtre yoksa tüm dokümanları kapsayan match_all kullan
|
|
84
|
+
query: dict[str, Any] = {"bool": {"filter": filters}} if filters else {"match_all": {}}
|
|
85
|
+
|
|
86
|
+
# serbest metin KQL varsa query_string ile must clause olarak ekle
|
|
87
|
+
if kql_query:
|
|
88
|
+
query = {
|
|
89
|
+
"bool": {
|
|
90
|
+
"filter": filters,
|
|
91
|
+
"must": [{"query_string": {"query": kql_query}}],
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return query
|
|
96
|
+
|
|
97
|
+
async def search_alerts(
|
|
98
|
+
self,
|
|
99
|
+
kql_query: str | None = None,
|
|
100
|
+
severity: str | None = None,
|
|
101
|
+
status: str | None = None,
|
|
102
|
+
time_range_start: str | None = None,
|
|
103
|
+
time_range_end: str | None = None,
|
|
104
|
+
page: int = 1,
|
|
105
|
+
page_size: int = 50,
|
|
106
|
+
) -> dict[str, Any]:
|
|
107
|
+
query = self._build_query(kql_query, severity, status, time_range_start, time_range_end)
|
|
108
|
+
|
|
109
|
+
response = await self.es.client.search(
|
|
110
|
+
index=ALERTS_INDEX,
|
|
111
|
+
query=query,
|
|
112
|
+
sort=[{"@timestamp": {"order": "desc"}}],
|
|
113
|
+
from_=(page - 1) * page_size,
|
|
114
|
+
size=page_size,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
# her hit'in _id'sini _source ile birleştirip düz bir alert dict'ine çevir
|
|
118
|
+
alerts = [{"_id": hit["_id"], **hit["_source"]} for hit in response["hits"]["hits"]]
|
|
119
|
+
total = response["hits"]["total"]["value"]
|
|
120
|
+
|
|
121
|
+
return {"alerts": alerts, "total": total, "page": page, "page_size": page_size}
|
|
122
|
+
|
|
123
|
+
async def get_alert_by_id(self, alert_id: str) -> dict[str, Any] | None:
|
|
124
|
+
# index="alerts-*" wildcard olduğu için client.get() kullanılamıyor
|
|
125
|
+
# (get API wildcard desteklemiyor), bu yüzden ids query ile search() kullanılıyor
|
|
126
|
+
response = await self.es.client.search(
|
|
127
|
+
index=ALERTS_INDEX,
|
|
128
|
+
query={"ids": {"values": [alert_id]}},
|
|
129
|
+
size=1,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
hits = response["hits"]["hits"]
|
|
133
|
+
if not hits:
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
hit = hits[0]
|
|
137
|
+
return {"_id": hit["_id"], **hit["_source"]}
|
|
138
|
+
|
|
139
|
+
async def get_alert_fields(self, alert_id: str) -> dict[str, Any] | None:
|
|
140
|
+
return await self.es.get_alert_fields(alert_id)
|
|
141
|
+
|
|
142
|
+
async def update_alert_status(
|
|
143
|
+
self, alert_id: str, status: str, comment: str | None = None
|
|
144
|
+
) -> bool:
|
|
145
|
+
return await self.es.update_alert_status(alert_id, status, comment)
|
|
146
|
+
|
|
147
|
+
async def add_alert_tags(self, alert_id: str, tags: list[str]) -> bool:
|
|
148
|
+
return await self.es.add_alert_tags(alert_id, tags)
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""Case Provider: Case CRUD operations on Elasticsearch."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from datetime import UTC, datetime
|
|
6
|
+
from typing import Any, ClassVar
|
|
7
|
+
from uuid import uuid4
|
|
8
|
+
|
|
9
|
+
import structlog
|
|
10
|
+
from elasticsearch import AsyncElasticsearch, ConflictError
|
|
11
|
+
from elasticsearch.exceptions import NotFoundError
|
|
12
|
+
|
|
13
|
+
from siphai_core.core.models.schemas import ES_TO_CASE_STATUS
|
|
14
|
+
from siphai_core.integrations.elasticsearch.service import ElasticsearchService
|
|
15
|
+
|
|
16
|
+
# Index where Kibana cases are written
|
|
17
|
+
# Warning: This is a system index; direct access may be restricted in the future.
|
|
18
|
+
CASE_INDEX = ".kibana_alerting_cases_9.5.0_001"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class CaseProvider(ABC):
|
|
22
|
+
"""Contract for querying/creating/updating cases."""
|
|
23
|
+
|
|
24
|
+
@abstractmethod
|
|
25
|
+
async def create_case(
|
|
26
|
+
self,
|
|
27
|
+
title: str,
|
|
28
|
+
description: str,
|
|
29
|
+
severity: int,
|
|
30
|
+
alert_ids: list[str] | None = None,
|
|
31
|
+
author: str | None = None,
|
|
32
|
+
) -> dict[str, Any]:
|
|
33
|
+
"""Creates a new case and returns the case_id."""
|
|
34
|
+
...
|
|
35
|
+
|
|
36
|
+
@abstractmethod
|
|
37
|
+
async def get_case(self, case_id: str) -> dict[str, Any] | None:
|
|
38
|
+
"""Fetches a single case by ID and returns None if it does not exist."""
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
@abstractmethod
|
|
42
|
+
async def update_case_status(self, case_id: str, status: int) -> bool:
|
|
43
|
+
"""Updates the case status (0=open, 10=in-progress, 20=closed)."""
|
|
44
|
+
...
|
|
45
|
+
|
|
46
|
+
@abstractmethod
|
|
47
|
+
async def add_comment(self, case_id: str, comment: str, author: str) -> bool:
|
|
48
|
+
"""Adds a comment to the case."""
|
|
49
|
+
...
|
|
50
|
+
|
|
51
|
+
@abstractmethod
|
|
52
|
+
async def list_cases(
|
|
53
|
+
self,
|
|
54
|
+
status: int | None = None,
|
|
55
|
+
severity: int | None = None,
|
|
56
|
+
page: int = 1,
|
|
57
|
+
page_size: int = 20,
|
|
58
|
+
) -> dict[str, Any]:
|
|
59
|
+
"""Returns a list of cases (filtering + pagination)."""
|
|
60
|
+
...
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ElasticsearchCaseProvider(CaseProvider):
|
|
64
|
+
"""Elasticsearch implementation."""
|
|
65
|
+
|
|
66
|
+
# OCC yeniden deneme üst sınırı: kalıcı çakışmada sonsuz döngüye girme.
|
|
67
|
+
MAX_COUNTER_ATTEMPTS: ClassVar[int] = 5
|
|
68
|
+
|
|
69
|
+
def __init__(self, es_service: ElasticsearchService):
|
|
70
|
+
self.es = es_service
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def client(self) -> AsyncElasticsearch:
|
|
74
|
+
"""Case işlemleri için client (restricted index yazımı).
|
|
75
|
+
|
|
76
|
+
es.case_client, ELASTICSEARCH_CASE_USERNAME/PASSWORD ile
|
|
77
|
+
ayrı bir basic-auth client döndürür; tanımlı değilse ana client'a döner."""
|
|
78
|
+
return self.es.case_client
|
|
79
|
+
|
|
80
|
+
async def close(self) -> None:
|
|
81
|
+
# Named user yaklaşımında ayrı client kapattığımız bir şey yok
|
|
82
|
+
# (her çağrıda yeniden oluşturulmaz, cached'dir).
|
|
83
|
+
pass
|
|
84
|
+
|
|
85
|
+
async def create_case(
|
|
86
|
+
self,
|
|
87
|
+
title: str,
|
|
88
|
+
description: str,
|
|
89
|
+
severity: int,
|
|
90
|
+
alert_ids: list[str] | None = None,
|
|
91
|
+
author: str = "", # required; raises ValueError if left empty
|
|
92
|
+
) -> dict[str, Any]:
|
|
93
|
+
if not author:
|
|
94
|
+
raise ValueError("create_case requires an explicit 'author' — silent attribution is not allowed")
|
|
95
|
+
|
|
96
|
+
now = datetime.now(UTC).isoformat()
|
|
97
|
+
|
|
98
|
+
# references: alert connections (if any)
|
|
99
|
+
references = []
|
|
100
|
+
if alert_ids:
|
|
101
|
+
references = [{"id": aid, "type": "alert", "name": ""} for aid in alert_ids]
|
|
102
|
+
|
|
103
|
+
created_by: dict[str, str] = {"username": author}
|
|
104
|
+
if self.es.settings.elasticsearch_profile_uid:
|
|
105
|
+
created_by["profile_uid"] = self.es.settings.elasticsearch_profile_uid
|
|
106
|
+
|
|
107
|
+
document = {
|
|
108
|
+
"type": "cases",
|
|
109
|
+
"namespaces": ["default"],
|
|
110
|
+
"coreMigrationVersion": "8.8.0",
|
|
111
|
+
"typeMigrationVersion": "10.10.0",
|
|
112
|
+
"managed": False,
|
|
113
|
+
"references": references,
|
|
114
|
+
"cases": {
|
|
115
|
+
"title": title,
|
|
116
|
+
"description": description,
|
|
117
|
+
"severity": severity,
|
|
118
|
+
"status": 0, # open
|
|
119
|
+
"owner": "securitySolution",
|
|
120
|
+
"created_by": created_by,
|
|
121
|
+
"created_at": now,
|
|
122
|
+
"settings": {
|
|
123
|
+
"syncAlerts": True,
|
|
124
|
+
"extractObservables": False
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
# Kibana convention: case document IDs use the cases:{uuid} format.
|
|
130
|
+
case_id = f"cases:{uuid4()}"
|
|
131
|
+
result = await self.client.index(
|
|
132
|
+
index=CASE_INDEX,
|
|
133
|
+
document=document,
|
|
134
|
+
id=case_id,
|
|
135
|
+
refresh="wait_for",
|
|
136
|
+
)
|
|
137
|
+
return {"id": result["_id"], **document}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
async def get_case(self, case_id: str) -> dict[str, Any] | None:
|
|
141
|
+
try:
|
|
142
|
+
response = await self.client.get(index=CASE_INDEX, id=case_id)
|
|
143
|
+
return {"id": response["_id"], **response["_source"]}
|
|
144
|
+
except NotFoundError:
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
async def update_case_status(self, case_id: str, status: int) -> bool:
|
|
148
|
+
if status not in ES_TO_CASE_STATUS:
|
|
149
|
+
raise ValueError(f"invalid case status: {status!r} (expected one of {sorted(ES_TO_CASE_STATUS)})")
|
|
150
|
+
|
|
151
|
+
for _attempt in range(self.MAX_COUNTER_ATTEMPTS):
|
|
152
|
+
try:
|
|
153
|
+
response = await self.client.get(index=CASE_INDEX, id=case_id)
|
|
154
|
+
except NotFoundError:
|
|
155
|
+
return False
|
|
156
|
+
|
|
157
|
+
case = response["_source"]
|
|
158
|
+
now_iso = datetime.now(UTC).isoformat()
|
|
159
|
+
cases_update: dict[str, Any] = {
|
|
160
|
+
"status": status,
|
|
161
|
+
"updated_at": now_iso,
|
|
162
|
+
}
|
|
163
|
+
# write-once: stamp in_progress_at only on the first transition;
|
|
164
|
+
# the existing value (if any) is read from the fetched source.
|
|
165
|
+
if status == 10 and not ((case.get("cases") or {}).get("in_progress_at")):
|
|
166
|
+
cases_update["in_progress_at"] = now_iso
|
|
167
|
+
|
|
168
|
+
try:
|
|
169
|
+
await self.client.update(
|
|
170
|
+
index=CASE_INDEX,
|
|
171
|
+
id=case_id,
|
|
172
|
+
doc={"cases": cases_update}, # partial — only changed fields
|
|
173
|
+
if_seq_no=response["_seq_no"], # OCC guard
|
|
174
|
+
if_primary_term=response["_primary_term"], # OCC guard
|
|
175
|
+
refresh="wait_for",
|
|
176
|
+
)
|
|
177
|
+
return True
|
|
178
|
+
except ConflictError:
|
|
179
|
+
continue # taze oku, yeniden dene
|
|
180
|
+
|
|
181
|
+
raise RuntimeError(
|
|
182
|
+
f"update_case_status: could not update after {self.MAX_COUNTER_ATTEMPTS} "
|
|
183
|
+
f"attempts (persistent concurrent modification)"
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
async def add_comment(self, case_id: str, comment: str, author: str) -> bool:
|
|
187
|
+
if not author:
|
|
188
|
+
raise ValueError("add_comment requires an explicit 'author' — silent attribution is not allowed")
|
|
189
|
+
now = datetime.now(UTC).isoformat()
|
|
190
|
+
# Deterministic attachment id: a retry of the same logical comment
|
|
191
|
+
# (same case + comment + author) writes the SAME _id, so ES overwrites
|
|
192
|
+
# instead of creating a duplicate when the caller retries a
|
|
193
|
+
# partially-succeeded add_comment.
|
|
194
|
+
attachment_id = hashlib.sha256(f"{case_id}|{comment}|{author}".encode()).hexdigest()[:32]
|
|
195
|
+
|
|
196
|
+
document = {
|
|
197
|
+
"case": {"id": case_id},
|
|
198
|
+
"attachment": {
|
|
199
|
+
"attachment_id": attachment_id,
|
|
200
|
+
"comment": comment,
|
|
201
|
+
"type": "comment"
|
|
202
|
+
},
|
|
203
|
+
"created_at": now,
|
|
204
|
+
"created_by": {"username": author},
|
|
205
|
+
"owner": "securitySolution",
|
|
206
|
+
"space_id": "default"
|
|
207
|
+
}
|
|
208
|
+
await self.client.index(index=".cases-attachments", document=document, refresh="wait_for")
|
|
209
|
+
|
|
210
|
+
# Increment the case.total_comments counter in Python (proje kuralı:
|
|
211
|
+
# Painless yasak). Optimistic concurrency: sürüm korumalı kısmi güncelleme;
|
|
212
|
+
# okuma ile yazma arasına eşzamanlı bir yazım girerse (409) taze sürümle
|
|
213
|
+
# yeniden denenir.
|
|
214
|
+
for _attempt in range(self.MAX_COUNTER_ATTEMPTS):
|
|
215
|
+
current = await self.client.get(index=CASE_INDEX, id=case_id)
|
|
216
|
+
total = ((current["_source"].get("cases") or {}).get("total_comments")) or 0
|
|
217
|
+
try:
|
|
218
|
+
await self.client.update(
|
|
219
|
+
index=CASE_INDEX,
|
|
220
|
+
id=case_id,
|
|
221
|
+
doc={"cases": {"total_comments": total + 1}},
|
|
222
|
+
if_seq_no=current["_seq_no"],
|
|
223
|
+
if_primary_term=current["_primary_term"],
|
|
224
|
+
refresh="wait_for",
|
|
225
|
+
)
|
|
226
|
+
return True
|
|
227
|
+
except ConflictError:
|
|
228
|
+
continue
|
|
229
|
+
|
|
230
|
+
# Attachment is already written; the counter could not be incremented.
|
|
231
|
+
# No cross-document transaction exists, so the count is now out of sync.
|
|
232
|
+
# Log it loudly for a future reconciliation job (recount total_comments
|
|
233
|
+
# from .cases-attachments for this case).
|
|
234
|
+
structlog.get_logger().error(
|
|
235
|
+
"add_comment_counter_desync",
|
|
236
|
+
case_id=case_id,
|
|
237
|
+
attachment_id=attachment_id,
|
|
238
|
+
attempts=self.MAX_COUNTER_ATTEMPTS,
|
|
239
|
+
)
|
|
240
|
+
raise RuntimeError(
|
|
241
|
+
f"add_comment: total_comments could not be updated after "
|
|
242
|
+
f"{self.MAX_COUNTER_ATTEMPTS} attempts (persistent concurrent modification)"
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
async def list_cases(
|
|
246
|
+
self,
|
|
247
|
+
status: int | None = None,
|
|
248
|
+
severity: int | None = None,
|
|
249
|
+
page: int = 1,
|
|
250
|
+
page_size: int = 20,
|
|
251
|
+
) -> dict[str, Any]:
|
|
252
|
+
filters: list[dict[str, Any]] = [
|
|
253
|
+
{"term": {"type": "cases"}} # get only cases (no alert/comments)
|
|
254
|
+
]
|
|
255
|
+
if status is not None:
|
|
256
|
+
filters.append({"term": {"cases.status": status}})
|
|
257
|
+
if severity is not None:
|
|
258
|
+
filters.append({"term": {"cases.severity": severity}})
|
|
259
|
+
|
|
260
|
+
query = {"bool": {"filter": filters}} if filters else {"match_all": {}}
|
|
261
|
+
|
|
262
|
+
response = await self.client.search(
|
|
263
|
+
index=CASE_INDEX,
|
|
264
|
+
query=query,
|
|
265
|
+
sort=[{"cases.created_at": {"order": "desc"}}],
|
|
266
|
+
from_=(page - 1) * page_size,
|
|
267
|
+
size=page_size,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
cases = [{"_id": hit["_id"], **hit["_source"]} for hit in response["hits"]["hits"]]
|
|
271
|
+
total = response["hits"]["total"]["value"]
|
|
272
|
+
|
|
273
|
+
return {"cases": cases, "total": total, "page": page, "page_size": page_size}
|
|
274
|
+
|
|
275
|
+
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Notification provider interface: Telegram, Slack, etc."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class NotificationProvider(ABC):
|
|
8
|
+
@abstractmethod
|
|
9
|
+
async def send_alert(self, alert: dict[str, Any]) -> bool:
|
|
10
|
+
"""Send an alert notification and return True on success."""
|
|
11
|
+
...
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
async def send_case_notification(self, case: dict[str, Any]) -> bool:
|
|
15
|
+
"""Send a case notification and return True on success."""
|
|
16
|
+
...
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Centralized structlog logging configuration."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import MutableMapping
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import structlog
|
|
8
|
+
|
|
9
|
+
from siphai_core.core.config.settings import Settings
|
|
10
|
+
|
|
11
|
+
# Event dict keys whose values may contain credentials; masked before rendering.
|
|
12
|
+
_CENSOR_MARKERS = (
|
|
13
|
+
"password",
|
|
14
|
+
"secret",
|
|
15
|
+
"token",
|
|
16
|
+
"api_key",
|
|
17
|
+
"apikey",
|
|
18
|
+
"authorization",
|
|
19
|
+
"credential",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _censor_sensitive(
|
|
24
|
+
logger: Any, method_name: str, event_dict: MutableMapping[str, Any]
|
|
25
|
+
) -> MutableMapping[str, Any]:
|
|
26
|
+
"""Mask sensitive values (password/api_key/token/secret/...) with '***'.
|
|
27
|
+
|
|
28
|
+
Cheap insurance now that all logs are centralized — a stray credential in a
|
|
29
|
+
log field never reaches the output. Runs before the renderer.
|
|
30
|
+
"""
|
|
31
|
+
for key in list(event_dict):
|
|
32
|
+
if any(marker in key.lower() for marker in _CENSOR_MARKERS):
|
|
33
|
+
event_dict[key] = "***"
|
|
34
|
+
return event_dict
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _base_processors() -> list[structlog.types.Processor]:
|
|
38
|
+
"""Shared processor pipeline applied to every log record."""
|
|
39
|
+
return [
|
|
40
|
+
structlog.contextvars.merge_contextvars,
|
|
41
|
+
structlog.processors.add_log_level,
|
|
42
|
+
structlog.processors.TimeStamper(fmt="iso", utc=True),
|
|
43
|
+
structlog.processors.StackInfoRenderer(),
|
|
44
|
+
structlog.processors.format_exc_info,
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _renderer(settings: Settings) -> structlog.types.Processor:
|
|
49
|
+
"""Renderer selection: JSON in prod, human-readable console in dev.
|
|
50
|
+
|
|
51
|
+
Controlled by Settings.log_format ("json"/"console"); falls back to
|
|
52
|
+
settings.debug when unset. LOG_FORMAT is also mapped from .env.
|
|
53
|
+
An unsupported log_format raises ValueError instead of silently falling
|
|
54
|
+
back to JSON (config typos must not be silent).
|
|
55
|
+
"""
|
|
56
|
+
fmt = (settings.log_format or "").lower()
|
|
57
|
+
if fmt and fmt not in ("json", "console"):
|
|
58
|
+
raise ValueError(f"invalid log_format: {settings.log_format!r} (expected 'json' | 'console' | None)")
|
|
59
|
+
if fmt == "console" or (not fmt and settings.debug):
|
|
60
|
+
return structlog.dev.ConsoleRenderer()
|
|
61
|
+
return structlog.processors.JSONRenderer()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def setup_logging(settings: Settings) -> None:
|
|
65
|
+
"""Configure structlog globally; call once at startup, before any logging."""
|
|
66
|
+
# Normalize case + reject invalid levels loudly. `logging.getLevelName`
|
|
67
|
+
# would return a "Level X" string for an unknown name, which silently breaks
|
|
68
|
+
# filtering; validate against the real level-name mapping instead.
|
|
69
|
+
level_name = settings.log_level.strip().upper()
|
|
70
|
+
level_map = logging.getLevelNamesMapping() # Python 3.11+
|
|
71
|
+
if level_name not in level_map:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
f"invalid log_level: {settings.log_level!r} "
|
|
74
|
+
"(expected DEBUG/INFO/WARNING/ERROR/CRITICAL)"
|
|
75
|
+
)
|
|
76
|
+
structlog.configure(
|
|
77
|
+
processors=[*_base_processors(), _censor_sensitive, _renderer(settings)],
|
|
78
|
+
wrapper_class=structlog.make_filtering_bound_logger(level_map[level_name]),
|
|
79
|
+
# Default logger factory (PrintLoggerFactory) writes one line per record
|
|
80
|
+
# to stdout, producing JSON Lines.
|
|
81
|
+
cache_logger_on_first_use=True,
|
|
82
|
+
)
|
|
File without changes
|