@cryptotaxi247 / CoPilot / commits / c3ca5b1e

precommit fixes

Taylor committed Oct 10, 2023 at 09:01 UTC c3ca5b1e3b669d9d68bb440d85554ec912839dfc
43 files changed +124 -399
backend/app/agents/routes/agents.py
+3 -3
@@ -32,7 +32,7 @@ def verify_admin(user):
32
33 @agents_router.get("", response_model=AgentsResponse, description="Get all disabled rules")
34 async def get_agents() -> AgentsResponse:
35 - logger.info(f"Fetching all agents")
35 + logger.info("Fetching all agents")
36 agents = session.query(Agents).all()
37 return AgentsResponse(agents=agents, success=True, message="Agents fetched successfully")
38
@@ -81,7 +81,7 @@ async def get_agent_vulnerabilities(agent_id: str) -> WazuhAgentVulnerabilitiesR
81
82 @agents_router.get("/wazuh/outdated", response_model=OutdatedWazuhAgentsResponse, description="Get all outdated Wazuh agents")
83 async def get_outdated_wazuh_agents() -> OutdatedWazuhAgentsResponse:
84 - logger.info(f"Fetching all outdated Wazuh agents")
84 + logger.info("Fetching all outdated Wazuh agents")
85 return get_outdated_agents_wazuh()
86
87
@@ -91,7 +91,7 @@ async def get_outdated_wazuh_agents() -> OutdatedWazuhAgentsResponse:
91 description="Get all outdated Velociraptor agents",
92 )
93 async def get_outdated_velociraptor_agents() -> OutdatedVelociraptorAgentsResponse:
94 - logger.info(f"Fetching all outdated Velociraptor agents")
94 + logger.info("Fetching all outdated Velociraptor agents")
95 return get_outdated_agents_velociraptor()
96
97
backend/app/agents/services/modify.py
-2
@@ -1,5 +1,3 @@
1 -from typing import List
2 -
1 from fastapi import HTTPException
2
3 import app.agents.wazuh.services.agents as wazuh_services
backend/app/agents/velociraptor/services/agents.py
-1
@@ -4,7 +4,6 @@ from loguru import logger
4
5 from app.agents.schema.agents import AgentsResponse
6 from app.agents.velociraptor.schema.agents import VelociraptorAgent
7 -from app.agents.velociraptor.utils.universal import parse_date
7 from app.connectors.velociraptor.services.artifacts import ArtifactsService
8 from app.connectors.velociraptor.utils.universal import UniversalService
9
backend/app/auth/routes/auth.py
+2 -2
@@ -33,7 +33,7 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
33 headers={"WWW-Authenticate": "Bearer"},
34 )
35 access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
36 - access_token = auth_handler.encode_token(user.username) # replace with actual scopes
36 + access_token = auth_handler.encode_token(user.username, access_token_expires)
37 return {"access_token": access_token, "token_type": "bearer"}
38
39
@@ -49,7 +49,7 @@ def register(user: UserInput):
49 return {"message": "User created successfully", "success": True}
50
51
52 -@user_router.post("/login", response_model=UserLoginResponse, description="Login user")
52 +@user_router.post("/login", response_model=UserLoginResponse, description="Login user", deprecated=True)
53 def login(user: UserLogin):
54 user_found = find_user(user.username)
55 if not user_found:
backend/app/auth/utils.py
+8 -3
@@ -18,7 +18,7 @@ class AuthHandler:
18 scopes={"admin": "Admin users", "analyst": "SOC Analysts"},
19 )
20 pwd_context = CryptContext(schemes=["bcrypt"])
21 - secret = "supersecret"
21 + secret = "bL4unrkoxtFs1MT6A7Ns2yMLkduyuqrkTxDV9CjlbNc="
22
23 def get_password_hash(self, password):
24 return self.pwd_context.hash(password)
@@ -32,8 +32,13 @@ class AuthHandler:
32 return False
33 return user
34
35 - def encode_token(self, username: str):
36 - payload = {"exp": datetime.utcnow() + timedelta(hours=8), "iat": datetime.utcnow(), "sub": username, "scopes": [get_role(username)]}
35 + def encode_token(self, username: str, access_token_expires: timedelta = timedelta(minutes=60)):
36 + payload = {
37 + "exp": datetime.utcnow() + access_token_expires,
38 + "iat": datetime.utcnow(),
39 + "sub": username,
40 + "scopes": [get_role(username)],
41 + }
42 return jwt.encode(payload, self.secret, algorithm="HS256")
43
44 def decode_token(self, token):
backend/app/auth/utils_backup.py
+53 -52
@@ -1,52 +1,53 @@
1 -import datetime
2 -
3 -import jwt
4 -from fastapi import HTTPException
5 -from fastapi import Security
6 -from fastapi.security import HTTPAuthorizationCredentials, OAuth2PasswordBearer
7 -from fastapi.security import HTTPBearer
8 -from passlib.context import CryptContext
9 -from typing import Optional
10 -from starlette import status
11 -
12 -from app.auth.services.universal import find_user
13 -from app.auth.models.users import User
14 -
15 -
16 -class AuthHandler:
17 - security = HTTPBearer()
18 - pwd_context = CryptContext(schemes=["bcrypt"])
19 - secret = "supersecret"
20 -
21 - def get_password_hash(self, password):
22 - return self.pwd_context.hash(password)
23 -
24 - def verify_password(self, pwd, hashed_pwd):
25 - return self.pwd_context.verify(pwd, hashed_pwd)
26 -
27 - def encode_token(self, user_id):
28 - payload = {"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=8), "iat": datetime.datetime.utcnow(), "sub": user_id}
29 - return jwt.encode(payload, self.secret, algorithm="HS256")
30 -
31 - def decode_token(self, token):
32 - try:
33 - payload = jwt.decode(token, self.secret, algorithms=["HS256"])
34 - return payload["sub"]
35 - except jwt.ExpiredSignatureError:
36 - raise HTTPException(status_code=401, detail="Expired signature")
37 - except jwt.InvalidTokenError:
38 - raise HTTPException(status_code=401, detail="Invalid token")
39 -
40 - def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)):
41 - return self.decode_token(auth.credentials)
42 -
43 - def get_current_user(self, auth: HTTPAuthorizationCredentials = Security(security)):
44 - credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials")
45 - username = self.decode_token(auth.credentials)
46 - if username is None:
47 - raise credentials_exception
48 - user = find_user(username)
49 - if user is None:
50 - raise credentials_exception
51 - return user
52 -
1 +#### ! COMMENTING OUT FOR PRECOMMIT TO PASS ####
2 +# import datetime
3 +# from typing import Optional
4 +#### ! COMMENTING OUT FOR PRECOMMIT TO PASS ####
5 +# import jwt
6 +# from fastapi import HTTPException
7 +# from fastapi import Security
8 +# from fastapi.security import HTTPAuthorizationCredentials
9 +# from fastapi.security import HTTPBearer
10 +# from fastapi.security import OAuth2PasswordBearer
11 +# from passlib.context import CryptContext
12 +# from starlette import status
13 +
14 +# from app.auth.models.users import User
15 +# from app.auth.services.universal import find_user
16 +
17 +
18 +# class AuthHandler:
19 +# security = HTTPBearer()
20 +# pwd_context = CryptContext(schemes=["bcrypt"])
21 +# secret = "supersecret"
22 +
23 +# def get_password_hash(self, password):
24 +# return self.pwd_context.hash(password)
25 +
26 +# def verify_password(self, pwd, hashed_pwd):
27 +# return self.pwd_context.verify(pwd, hashed_pwd)
28 +
29 +# def encode_token(self, user_id):
30 +# payload = {"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=8), "iat": datetime.datetime.utcnow(), "sub": user_id}
31 +# return jwt.encode(payload, self.secret, algorithm="HS256")
32 +
33 +# def decode_token(self, token):
34 +# try:
35 +# payload = jwt.decode(token, self.secret, algorithms=["HS256"])
36 +# return payload["sub"]
37 +# except jwt.ExpiredSignatureError:
38 +# raise HTTPException(status_code=401, detail="Expired signature")
39 +# except jwt.InvalidTokenError:
40 +# raise HTTPException(status_code=401, detail="Invalid token")
41 +
42 +# def auth_wrapper(self, auth: HTTPAuthorizationCredentials = Security(security)):
43 +# return self.decode_token(auth.credentials)
44 +
45 +# def get_current_user(self, auth: HTTPAuthorizationCredentials = Security(security)):
46 +# credentials_exception = HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials")
47 +# username = self.decode_token(auth.credentials)
48 +# if username is None:
49 +# raise credentials_exception
50 +# user = find_user(username)
51 +# if user is None:
52 +# raise credentials_exception
53 +# return user
backend/app/connectors/cortex/routes/analyzers.py
+1 -2
@@ -10,7 +10,6 @@ from app.connectors.cortex.schema.analyzers import RunAnalyzerBody
10 from app.connectors.cortex.schema.analyzers import RunAnalyzerResponse
11 from app.connectors.cortex.services.analyzers import get_analyzers
12 from app.connectors.cortex.services.analyzers import run_analyzer
13 -from app.db.db_session import session
13
14 # App specific imports
15
@@ -31,7 +30,7 @@ def verify_analyzer_exists(run_analyzer_body: RunAnalyzerBody) -> RunAnalyzerBod
30
31 @cortex_analyzer_router.get("", response_model=AnalyzersResponse, description="Get all analyzers")
32 async def get_all_analyzers() -> AnalyzersResponse:
34 - logger.info(f"Fetching all analyzers")
33 + logger.info("Fetching all analyzers")
34 return get_analyzers()
35
36
backend/app/connectors/cortex/services/analyzers.py
+1 -47
@@ -5,15 +5,10 @@ from typing import List
5 from typing import Union
6
7 from cortex4py.api import Api
8 -from dfir_iris_client.alert import (
9 - Alert, # Assuming this import is needed in your context
10 -)
8 from fastapi import HTTPException
9 from loguru import logger
10
14 -from app.connectors.cortex.schema.analyzers import (
15 - AnalyzerJobData, # Assuming this import is needed
16 -)
11 +from app.connectors.cortex.schema.analyzers import AnalyzerJobData
12 from app.connectors.cortex.schema.analyzers import AnalyzersResponse
13 from app.connectors.cortex.schema.analyzers import RunAnalyzerBody
14 from app.connectors.cortex.schema.analyzers import RunAnalyzerResponse
@@ -24,47 +19,6 @@ from app.connectors.cortex.utils.universal import (
19 run_and_wait_for_analyzer, # Importing from universal.py
20 )
21
27 -############################# Helpful to find the attributes of the analyzer object
28 -# def fetch_analyzers(api: Api) -> List[Dict]:
29 -# analyzers = api.analyzers.find_all({}, range="all")
30 -# if analyzers: # Check if the list is not empty
31 -# # Log the attributes of the first analyzer object to understand its structure
32 -# logger.info(f"Attributes of the Analyzer object: {dir(analyzers[0])}")
33 -# return analyzers
34 -
35 -
36 -# def fetch_analyzers(api: Api) -> List[Dict]:
37 -# return api.analyzers.find_all({}, range="all")
38 -
39 -# def build_analyzer_response(analyzers: List[Dict]) -> Dict[str, Union[bool, str, List[str]]]:
40 -# try:
41 -# analyzer_names = [analyzer.name for analyzer in analyzers]
42 -# return analyzer_names
43 -# except Exception as e:
44 -# logger.error(f"Error processing analyzers: {e}")
45 -# raise HTTPException(status_code=500, detail=f"Error processing analyzers: {e}")
46 -
47 -# def get_analyzers() -> Dict[str, Union[bool, str, List[str]]]:
48 -# api = create_cortex_client('Cortex')
49 -# if api is None:
50 -# return {"success": False, "message": "API initialization failed"}
51 -
52 -# analyzers = fetch_analyzers(api)
53 -# return AnalyzersResponse(success=True, message="Successfully fetched analyzers", analyzers=build_analyzer_response(analyzers))
54 -
55 -# def run_analyzer(run_analyzer_body: RunAnalyzerBody) -> Dict[str, Union[bool, str, List[str]]]:
56 -# api = create_cortex_client('Cortex')
57 -# if api is None:
58 -# return {"success": False, "message": "API initialization failed"}
59 -
60 -# analyzer_name = run_analyzer_body.analyzer_name
61 -# analyzer_data = run_analyzer_body.analyzer_data
62 -# job_data = AnalyzerJobData(data=analyzer_data, dataType='ip')
63 -# result = run_and_wait_for_analyzer(analyzer_name=analyzer_name, job_data=job_data)
64 -# if result is None:
65 -# raise HTTPException(status_code=500, detail=f"Failed to run analyzer {analyzer_name}")
66 -# return RunAnalyzerResponse(success=True, message="Successfully ran analyzer", report=result["report"])
67 -
22
23 def fetch_analyzers(api: Api) -> List[Dict]:
24 return api.analyzers.find_all({}, range="all")
backend/app/connectors/cortex/utils/universal.py
+2 -29
@@ -1,29 +1,13 @@
1 import time
2 import traceback
3 -from datetime import datetime
4 -from datetime import timedelta
3 from typing import Any
4 from typing import Dict
7 -from typing import Generator
8 -from typing import Iterable
9 -from typing import List
10 -from typing import Tuple
11 -from typing import Type
5
13 -import requests
6 from cortex4py.api import Api
15 -from elasticsearch7 import Elasticsearch
7 from loguru import logger
17 -from sqlmodel import Session
18 -from sqlmodel import select
8
9 from app.connectors.cortex.schema.analyzers import AnalyzerJobData
21 -from app.connectors.models import Connectors
22 -from app.connectors.schema import ConnectorResponse
10 from app.connectors.utils import get_connector_info_from_db
24 -from app.connectors.wazuh_indexer.schema.indices import IndexConfigModel
25 -from app.connectors.wazuh_indexer.schema.indices import Indices
26 -from app.db.db_session import engine
11
12
13 def verify_cortex_credentials(attributes: Dict[str, Any]) -> Dict[str, Any]:
@@ -43,8 +27,8 @@ def verify_cortex_credentials(attributes: Dict[str, Any]) -> Dict[str, Any]:
27 logger.debug("Cortex connection successful")
28 return {"connectionSuccessful": True, "message": "Cortex connection successful"}
29 else:
46 - logger.error(f"Connection to {attributes['connector_url']} failed with error: {e}")
47 - return {"connectionSuccessful": False, "message": f"Connection to {attributes['connector_url']} failed with error: {e}"}
30 + logger.error(f"Connection to {attributes['connector_url']} failed with error.")
31 + return {"connectionSuccessful": False, "message": f"Connection to {attributes['connector_url']} failed with error."}
32 except Exception as e:
33 logger.error(f"Connection to {attributes['connector_url']} failed with error: {e}")
34 return {"connectionSuccessful": False, "message": f"Connection to {attributes['connector_url']} failed with error: {e}"}
@@ -83,17 +67,6 @@ def run_and_wait_for_analyzer(analyzer_name: str, job_data: AnalyzerJobData) ->
67 if api is None:
68 return {"success": False, "message": "API initialization failed"}
69 try:
86 - # job = api.analyzers.run_by_name(
87 - # analyzer_name,
88 - # {
89 - # "data": ioc_value,
90 - # "dataType": data_type,
91 - # "tlp": 1,
92 - # "message": "custom message sent to analyzer",
93 - # },
94 - # force=1,
95 - # )
96 - job_query = job_data.dict()
70 job = api.analyzers.run_by_name(analyzer_name, job_data.dict(), force=1)
71 return monitor_analyzer_job(api, job)
72 except Exception as e:
backend/app/connectors/dfir_iris/routes/alerts.py
+4 -13
@@ -1,18 +1,8 @@
1 -from datetime import timedelta
2 -from typing import Dict
3 -from typing import List
4 -from typing import Optional
5 -from typing import Union
6 -
1 from fastapi import APIRouter
2 from fastapi import Depends
3 from fastapi import HTTPException
10 -from fastapi import Security
4 from loguru import logger
12 -from starlette.status import HTTP_401_UNAUTHORIZED
5
14 -# App specific imports
15 -from app.auth.routes.auth import auth_handler
6 from app.connectors.dfir_iris.schema.alerts import AlertResponse
7 from app.connectors.dfir_iris.schema.alerts import AlertsResponse
8 from app.connectors.dfir_iris.schema.alerts import BookmarkedAlertsResponse
@@ -20,7 +10,8 @@ from app.connectors.dfir_iris.services.alerts import bookmark_alert
10 from app.connectors.dfir_iris.services.alerts import get_alerts
11 from app.connectors.dfir_iris.services.alerts import get_bookmarked_alerts
12 from app.connectors.dfir_iris.utils.universal import check_alert_exists
23 -from app.db.db_session import session
13 +
14 +# App specific imports
15
16
17 def verify_alert_exists(alert_id: str) -> str:
@@ -34,13 +25,13 @@ dfir_iris_alerts_router = APIRouter()
25
26 @dfir_iris_alerts_router.get("", response_model=AlertsResponse, description="Get all alerts")
27 async def get_all_alerts() -> AlertsResponse:
37 - logger.info(f"Fetching all alerts")
28 + logger.info("Fetching all alerts")
29 return get_alerts()
30
31
32 @dfir_iris_alerts_router.get("/bookmark", response_model=BookmarkedAlertsResponse, description="Get all bookmarked alerts")
33 async def get_all_bookmarked_alerts() -> BookmarkedAlertsResponse:
43 - logger.info(f"Fetching all bookmarked alerts")
34 + logger.info("Fetching all bookmarked alerts")
35 return get_bookmarked_alerts()
36
37
backend/app/connectors/dfir_iris/routes/assets.py
+2 -12
@@ -1,23 +1,13 @@
1 -from datetime import timedelta
2 -from typing import Dict
3 -from typing import List
4 -from typing import Optional
5 -from typing import Union
6 -
1 from fastapi import APIRouter
2 from fastapi import Depends
3 from fastapi import HTTPException
10 -from fastapi import Security
4 from loguru import logger
12 -from starlette.status import HTTP_401_UNAUTHORIZED
5
14 -# App specific imports
15 -from app.auth.routes.auth import auth_handler
6 from app.connectors.dfir_iris.schema.assets import AssetResponse
7 from app.connectors.dfir_iris.services.assets import get_case_assets
8 from app.connectors.dfir_iris.utils.universal import check_case_exists
19 -from app.connectors.wazuh_indexer.utils.universal import collect_indices
20 -from app.db.db_session import session
9 +
10 +# App specific imports
11
12
13 def verify_case_exists(case_id: int) -> int:
backend/app/connectors/dfir_iris/routes/cases.py
+1 -13
@@ -1,32 +1,20 @@
1 from datetime import timedelta
2 -from typing import Dict
3 -from typing import List
4 -from typing import Optional
5 -from typing import Union
2
3 from fastapi import APIRouter
4 from fastapi import Depends
5 from fastapi import HTTPException
10 -from fastapi import Security
6 from loguru import logger
12 -from starlette.status import HTTP_401_UNAUTHORIZED
7
14 -# App specific imports
15 -from app.auth.routes.auth import auth_handler
8 from app.connectors.dfir_iris.schema.cases import CaseOlderThanBody
9 from app.connectors.dfir_iris.schema.cases import CaseResponse
10 from app.connectors.dfir_iris.schema.cases import CasesBreachedResponse
11 from app.connectors.dfir_iris.schema.cases import SingleCaseBody
12 from app.connectors.dfir_iris.schema.cases import SingleCaseResponse
13 from app.connectors.dfir_iris.schema.cases import TimeUnit
22 -from app.connectors.dfir_iris.schema.notes import NotesQueryParams
23 -from app.connectors.dfir_iris.schema.notes import NotesResponse
14 from app.connectors.dfir_iris.services.cases import get_all_cases
15 from app.connectors.dfir_iris.services.cases import get_cases_older_than
16 from app.connectors.dfir_iris.services.cases import get_single_case
17 from app.connectors.dfir_iris.utils.universal import check_case_exists
28 -from app.connectors.wazuh_indexer.utils.universal import collect_indices
29 -from app.db.db_session import session
18
19
20 def verify_case_exists(case_id: int) -> int:
@@ -51,7 +39,7 @@ def get_timedelta(older_than: int, time_unit: TimeUnit) -> CaseOlderThanBody:
39
40 @cases_router.get("", response_model=CaseResponse, description="Get all cases")
41 async def get_cases_route() -> CaseResponse:
54 - logger.info(f"Fetching all cases")
42 + logger.info("Fetching all cases")
43 return get_all_cases()
44
45
backend/app/connectors/dfir_iris/routes/notes.py
-12
@@ -1,28 +1,16 @@
1 -from datetime import timedelta
2 -from typing import Dict
3 -from typing import List
1 from typing import Optional
5 -from typing import Union
2
3 from fastapi import APIRouter
4 from fastapi import Depends
5 from fastapi import HTTPException
10 -from fastapi import Security
6 from loguru import logger
12 -from starlette.status import HTTP_401_UNAUTHORIZED
7
14 -# App specific imports
15 -from app.auth.routes.auth import auth_handler
16 -from app.connectors.dfir_iris.schema.cases import SingleCaseBody
8 from app.connectors.dfir_iris.schema.notes import NoteCreationBody
9 from app.connectors.dfir_iris.schema.notes import NoteCreationResponse
19 -from app.connectors.dfir_iris.schema.notes import NotesQueryParams
10 from app.connectors.dfir_iris.schema.notes import NotesResponse
11 from app.connectors.dfir_iris.services.notes import create_case_note
12 from app.connectors.dfir_iris.services.notes import get_case_notes
13 from app.connectors.dfir_iris.utils.universal import check_case_exists
24 -from app.connectors.wazuh_indexer.utils.universal import collect_indices
25 -from app.db.db_session import session
14
15
16 def verify_case_exists(case_id: int) -> int:
backend/app/connectors/dfir_iris/routes/users.py
+1 -12
@@ -1,18 +1,8 @@
1 -from datetime import timedelta
2 -from typing import Dict
3 -from typing import List
4 -from typing import Optional
5 -from typing import Union
6 -
1 from fastapi import APIRouter
2 from fastapi import Depends
3 from fastapi import HTTPException
10 -from fastapi import Security
4 from loguru import logger
12 -from starlette.status import HTTP_401_UNAUTHORIZED
5
14 -# App specific imports
15 -from app.auth.routes.auth import auth_handler
6 from app.connectors.dfir_iris.schema.alerts import AlertResponse
7 from app.connectors.dfir_iris.schema.users import User
8 from app.connectors.dfir_iris.schema.users import UsersResponse
@@ -20,7 +10,6 @@ from app.connectors.dfir_iris.services.users import assign_user_to_alert
10 from app.connectors.dfir_iris.services.users import get_users
11 from app.connectors.dfir_iris.utils.universal import check_alert_exists
12 from app.connectors.dfir_iris.utils.universal import check_user_exists
23 -from app.db.db_session import session
13
14
15 def verify_user_exists(user_id: int) -> int:
@@ -40,7 +29,7 @@ dfir_iris_users_router = APIRouter()
29
30 @dfir_iris_users_router.get("", response_model=UsersResponse, description="Get all users")
31 async def get_all_users() -> UsersResponse:
43 - logger.info(f"Fetching all users")
32 + logger.info("Fetching all users")
33 return get_users()
34
35
backend/app/connectors/dfir_iris/schema/cases.py
-1
@@ -1,4 +1,3 @@
1 -from datetime import datetime
1 from datetime import timedelta
2 from enum import Enum
3 from typing import Dict
backend/app/connectors/dfir_iris/schema/notes.py
-1
@@ -1,4 +1,3 @@
1 -from datetime import datetime
1 from typing import Dict
2 from typing import List
3 from typing import Optional
backend/app/connectors/dfir_iris/services/alerts.py
-13
@@ -1,19 +1,6 @@
1 -from datetime import datetime
2 -from typing import Any
3 -from typing import Callable
4 -from typing import Dict
5 -from typing import List
6 -from typing import Tuple
7 -
8 -from dfir_iris_client.alert import Alert
9 -from fastapi import HTTPException
10 -from loguru import logger
11 -
1 from app.connectors.dfir_iris.schema.alerts import AlertResponse
2 from app.connectors.dfir_iris.schema.alerts import AlertsResponse
3 from app.connectors.dfir_iris.schema.alerts import BookmarkedAlertsResponse
15 -from app.connectors.dfir_iris.utils.universal import create_dfir_iris_client
16 -from app.connectors.dfir_iris.utils.universal import fetch_and_parse_data
4 from app.connectors.dfir_iris.utils.universal import fetch_and_validate_data
5 from app.connectors.dfir_iris.utils.universal import initialize_client_and_alert
6
backend/app/connectors/dfir_iris/services/assets.py
-14
@@ -1,21 +1,7 @@
1 -from datetime import datetime
2 -from typing import Any
3 -from typing import Callable
4 -from typing import Dict
5 -from typing import List
6 -from typing import Tuple
7 -
8 -from dfir_iris_client.case import Case
9 -from fastapi import HTTPException
10 -from loguru import logger
11 -
1 from app.connectors.dfir_iris.schema.assets import Asset
2 from app.connectors.dfir_iris.schema.assets import AssetResponse
3 from app.connectors.dfir_iris.schema.assets import AssetState
15 -from app.connectors.dfir_iris.utils.universal import create_dfir_iris_client
16 -from app.connectors.dfir_iris.utils.universal import fetch_and_parse_data
4 from app.connectors.dfir_iris.utils.universal import fetch_and_validate_data
18 -from app.connectors.dfir_iris.utils.universal import handle_error
5 from app.connectors.dfir_iris.utils.universal import initialize_client_and_case
6
7
backend/app/connectors/dfir_iris/services/cases.py
-8
@@ -1,24 +1,16 @@
1 from datetime import datetime
2 -from typing import Any
3 -from typing import Callable
2 from typing import Dict
3 from typing import List
6 -from typing import Tuple
4
5 from dfir_iris_client.case import Case
6 from fastapi import HTTPException
7 from loguru import logger
8
12 -from app.connectors.dfir_iris.schema.cases import CaseModel
9 from app.connectors.dfir_iris.schema.cases import CaseOlderThanBody
10 from app.connectors.dfir_iris.schema.cases import CaseResponse
11 from app.connectors.dfir_iris.schema.cases import CasesBreachedResponse
12 from app.connectors.dfir_iris.schema.cases import SingleCaseBody
13 from app.connectors.dfir_iris.schema.cases import SingleCaseResponse
18 -from app.connectors.dfir_iris.schema.notes import NoteDetails
19 -from app.connectors.dfir_iris.schema.notes import NoteDetailsResponse
20 -from app.connectors.dfir_iris.schema.notes import NotesQueryParams
21 -from app.connectors.dfir_iris.schema.notes import NotesResponse
14 from app.connectors.dfir_iris.utils.universal import create_dfir_iris_client
15 from app.connectors.dfir_iris.utils.universal import fetch_and_parse_data
16
backend/app/connectors/dfir_iris/services/notes.py
-14
@@ -1,30 +1,16 @@
1 -from datetime import datetime
1 from typing import Any
3 -from typing import Callable
2 from typing import Dict
3 from typing import List
6 -from typing import Tuple
4
5 from dfir_iris_client.case import Case
9 -from fastapi import HTTPException
6 from loguru import logger
7
12 -from app.connectors.dfir_iris.schema.cases import CaseModel
13 -from app.connectors.dfir_iris.schema.cases import CaseOlderThanBody
14 -from app.connectors.dfir_iris.schema.cases import CaseResponse
15 -from app.connectors.dfir_iris.schema.cases import CasesBreachedResponse
16 -from app.connectors.dfir_iris.schema.cases import SingleCaseBody
17 -from app.connectors.dfir_iris.schema.cases import SingleCaseResponse
8 from app.connectors.dfir_iris.schema.notes import NoteCreationBody
9 from app.connectors.dfir_iris.schema.notes import NoteCreationResponse
10 from app.connectors.dfir_iris.schema.notes import NoteDetails
11 from app.connectors.dfir_iris.schema.notes import NoteDetailsResponse
22 -from app.connectors.dfir_iris.schema.notes import NotesQueryParams
12 from app.connectors.dfir_iris.schema.notes import NotesResponse
24 -from app.connectors.dfir_iris.utils.universal import create_dfir_iris_client
25 -from app.connectors.dfir_iris.utils.universal import fetch_and_parse_data
13 from app.connectors.dfir_iris.utils.universal import fetch_and_validate_data
27 -from app.connectors.dfir_iris.utils.universal import handle_error
14 from app.connectors.dfir_iris.utils.universal import initialize_client_and_case
15
16
backend/app/connectors/dfir_iris/services/users.py
-14
@@ -1,19 +1,5 @@
1 -from datetime import datetime
2 -from typing import Any
3 -from typing import Callable
4 -from typing import Dict
5 -from typing import List
6 -from typing import Tuple
7 -
8 -from dfir_iris_client.alert import Alert
9 -from fastapi import HTTPException
10 -from loguru import logger
11 -
1 from app.connectors.dfir_iris.schema.alerts import AlertResponse
13 -from app.connectors.dfir_iris.schema.users import User
2 from app.connectors.dfir_iris.schema.users import UsersResponse
15 -from app.connectors.dfir_iris.utils.universal import create_dfir_iris_client
16 -from app.connectors.dfir_iris.utils.universal import fetch_and_parse_data
3 from app.connectors.dfir_iris.utils.universal import fetch_and_validate_data
4 from app.connectors.dfir_iris.utils.universal import initialize_client_and_alert
5 from app.connectors.dfir_iris.utils.universal import initialize_client_and_user
backend/app/connectors/dfir_iris/utils/universal.py
-14
@@ -1,14 +1,8 @@
1 -from datetime import datetime
2 -from datetime import timedelta
1 from typing import Any
2 from typing import Callable
3 from typing import Dict
6 -from typing import Generator
7 -from typing import Iterable
8 -from typing import List
4 from typing import Optional
5 from typing import Tuple
11 -from typing import Type
6 from typing import Union
7
8 import requests
@@ -18,18 +12,10 @@ from dfir_iris_client.helper.utils import assert_api_resp
12 from dfir_iris_client.helper.utils import get_data_from_resp
13 from dfir_iris_client.session import ClientSession
14 from dfir_iris_client.users import User
21 -from elasticsearch7 import Elasticsearch
15 from fastapi import HTTPException
16 from loguru import logger
24 -from sqlmodel import Session
25 -from sqlmodel import select
17
27 -from app.connectors.models import Connectors
28 -from app.connectors.schema import ConnectorResponse
18 from app.connectors.utils import get_connector_info_from_db
30 -from app.connectors.wazuh_indexer.schema.indices import IndexConfigModel
31 -from app.connectors.wazuh_indexer.schema.indices import Indices
32 -from app.db.db_session import engine
19
20
21 def verify_dfir_iris_credentials(attributes: Dict[str, Any]) -> Dict[str, Any]:
backend/app/connectors/graylog/routes/collector.py
+7 -13
@@ -1,14 +1,6 @@
1 -from typing import List
2 -
1 from fastapi import APIRouter
4 -from fastapi import Depends
5 -from fastapi import HTTPException
6 -from fastapi import Security
2 from loguru import logger
8 -from starlette.status import HTTP_401_UNAUTHORIZED
3
10 -# App specific imports
11 -from app.auth.routes.auth import auth_handler
4 from app.connectors.graylog.schema.collector import ConfiguredInputsResponse
5 from app.connectors.graylog.schema.collector import GraylogIndicesResponse
6 from app.connectors.graylog.schema.collector import GraylogInputsResponse
@@ -17,30 +9,32 @@ from app.connectors.graylog.services.collector import get_indices_full
9 from app.connectors.graylog.services.collector import get_inputs
10 from app.connectors.graylog.services.collector import get_inputs_configured
11 from app.connectors.graylog.services.collector import get_inputs_running
20 -from app.db.db_session import session
12 +
13 +# App specific imports
14 +
15
16 graylog_collector_router = APIRouter()
17
18
19 @graylog_collector_router.get("/indices", response_model=GraylogIndicesResponse, description="Get all indices")
20 async def get_all_indices() -> GraylogIndicesResponse:
27 - logger.info(f"Fetching all graylog indices")
21 + logger.info("Fetching all graylog indices")
22 return get_indices_full()
23
24
25 @graylog_collector_router.get("/inputs", response_model=GraylogInputsResponse, description="Get all inputs")
26 async def get_all_inputs() -> GraylogInputsResponse:
33 - logger.info(f"Fetching all graylog inputs")
27 + logger.info("Fetching all graylog inputs")
28 return get_inputs()
29
30
31 @graylog_collector_router.get("/inputs/running", response_model=RunningInputsResponse, description="Get all running inputs")
32 async def get_all_running_inputs() -> RunningInputsResponse:
39 - logger.info(f"Fetching all graylog running inputs")
33 + logger.info("Fetching all graylog running inputs")
34 return get_inputs_running()
35
36
37 @graylog_collector_router.get("/inputs/configured", response_model=ConfiguredInputsResponse, description="Get all configured inputs")
38 async def get_all_configured_inputs() -> ConfiguredInputsResponse:
45 - logger.info(f"Fetching all graylog configured inputs")
39 + logger.info("Fetching all graylog configured inputs")
40 return get_inputs_configured()
backend/app/connectors/graylog/routes/events.py
+5 -11
@@ -1,31 +1,25 @@
1 -from typing import List
2 -
1 from fastapi import APIRouter
4 -from fastapi import Depends
5 -from fastapi import HTTPException
6 -from fastapi import Security
2 from loguru import logger
8 -from starlette.status import HTTP_401_UNAUTHORIZED
3
10 -# App specific imports
11 -from app.auth.routes.auth import auth_handler
4 from app.connectors.graylog.schema.events import AlertQuery
5 from app.connectors.graylog.schema.events import GraylogAlertsResponse
6 from app.connectors.graylog.schema.events import GraylogEventDefinitionsResponse
7 from app.connectors.graylog.services.events import get_alerts
8 from app.connectors.graylog.services.events import get_event_definitions
17 -from app.db.db_session import session
9 +
10 +# App specific imports
11 +
12
13 graylog_events_router = APIRouter()
14
15
16 @graylog_events_router.get("/event/definitions", response_model=GraylogEventDefinitionsResponse, description="Get all event definitions")
17 async def get_all_event_definitions() -> GraylogEventDefinitionsResponse:
24 - logger.info(f"Fetching all graylog event definitions")
18 + logger.info("Fetching all graylog event definitions")
19 return get_event_definitions()
20
21
22 @graylog_events_router.post("/event/alerts", response_model=GraylogAlertsResponse, description="Get all alerts")
23 async def get_all_alerts(alert_query: AlertQuery) -> GraylogAlertsResponse:
30 - logger.info(f"Fetching all graylog alerts")
24 + logger.info("Fetching all graylog alerts")
25 return get_alerts(alert_query)
backend/app/connectors/graylog/routes/management.py
-5
@@ -3,12 +3,8 @@ from typing import List
3 from fastapi import APIRouter
4 from fastapi import Depends
5 from fastapi import HTTPException
6 -from fastapi import Security
6 from loguru import logger
8 -from starlette.status import HTTP_401_UNAUTHORIZED
7
10 -# App specific imports
11 -from app.auth.routes.auth import auth_handler
8 from app.connectors.graylog.schema.management import DeletedIndexBody
9 from app.connectors.graylog.schema.management import DeletedIndexResponse
10 from app.connectors.graylog.schema.management import StartInputBody
@@ -27,7 +23,6 @@ from app.connectors.graylog.services.management import start_stream
23 from app.connectors.graylog.services.management import stop_input
24 from app.connectors.graylog.services.management import stop_stream
25 from app.connectors.graylog.services.streams import get_stream_ids
30 -from app.db.db_session import session
26
27 graylog_management_router = APIRouter()
28
backend/app/connectors/graylog/routes/monitoring.py
+5 -12
@@ -1,32 +1,25 @@
1 -from typing import List
2 -
1 from fastapi import APIRouter
4 -from fastapi import Depends
5 -from fastapi import HTTPException
6 -from fastapi import Security
2 from loguru import logger
8 -from starlette.status import HTTP_401_UNAUTHORIZED
3
10 -# App specific imports
11 -from app.auth.routes.auth import auth_handler
12 -from app.connectors.graylog.schema.monitoring import GraylogMessages
4 from app.connectors.graylog.schema.monitoring import GraylogMessagesResponse
5 from app.connectors.graylog.schema.monitoring import GraylogMetricsResponse
6 from app.connectors.graylog.services.monitoring import get_messages
7 from app.connectors.graylog.services.monitoring import get_metrics
17 -from app.db.db_session import session
8 +
9 +# App specific imports
10 +
11
12 graylog_monitoring_router = APIRouter()
13
14
15 @graylog_monitoring_router.get("/messages", response_model=GraylogMessagesResponse, description="Get all messages")
16 async def get_all_messages(page_number: int = 1) -> GraylogMessagesResponse:
24 - logger.info(f"Fetching all graylog messages")
17 + logger.info("Fetching all graylog messages")
18 logger.info(f"Page number: {page_number}")
19 return get_messages(page_number)
20
21
22 @graylog_monitoring_router.get("/metrics", response_model=GraylogMetricsResponse, description="Get all metrics")
23 async def get_all_metrics() -> GraylogMetricsResponse:
31 - logger.info(f"Fetching all graylog metrics")
24 + logger.info("Fetching all graylog metrics")
25 return get_metrics()
backend/app/connectors/graylog/routes/pipelines.py
+5 -11
@@ -1,30 +1,24 @@
1 -from typing import List
2 -
1 from fastapi import APIRouter
4 -from fastapi import Depends
5 -from fastapi import HTTPException
6 -from fastapi import Security
2 from loguru import logger
8 -from starlette.status import HTTP_401_UNAUTHORIZED
3
10 -# App specific imports
11 -from app.auth.routes.auth import auth_handler
4 from app.connectors.graylog.schema.pipelines import GraylogPipelinesResponse
5 from app.connectors.graylog.schema.pipelines import PipelineRulesResponse
6 from app.connectors.graylog.services.pipelines import get_pipeline_rules
7 from app.connectors.graylog.services.pipelines import get_pipelines
16 -from app.db.db_session import session
8 +
9 +# App specific imports
10 +
11
12 graylog_pipelines_router = APIRouter()
13
14
15 @graylog_pipelines_router.get("/pipelines", response_model=GraylogPipelinesResponse, description="Get all pipelines")
16 async def get_all_pipelines() -> GraylogPipelinesResponse:
23 - logger.info(f"Fetching all graylog pipelines")
17 + logger.info("Fetching all graylog pipelines")
18 return get_pipelines()
19
20
21 @graylog_pipelines_router.get("/pipeline/rules", response_model=PipelineRulesResponse, description="Get all pipeline rules")
22 async def get_all_pipeline_rules() -> PipelineRulesResponse:
29 - logger.info(f"Fetching all graylog pipeline rules")
23 + logger.info("Fetching all graylog pipeline rules")
24 return get_pipeline_rules()
backend/app/connectors/graylog/routes/streams.py
+4 -12
@@ -1,24 +1,16 @@
1 -from typing import List
2 -
1 from fastapi import APIRouter
4 -from fastapi import Depends
5 -from fastapi import HTTPException
6 -from fastapi import Security
2 from loguru import logger
8 -from starlette.status import HTTP_401_UNAUTHORIZED
3
10 -# App specific imports
11 -from app.auth.routes.auth import auth_handler
4 from app.connectors.graylog.schema.streams import GraylogStreamsResponse
13 -from app.connectors.graylog.schema.streams import Rule
14 -from app.connectors.graylog.schema.streams import Stream
5 from app.connectors.graylog.services.streams import get_streams
16 -from app.db.db_session import session
6 +
7 +# App specific imports
8 +
9
10 graylog_streams_router = APIRouter()
11
12
13 @graylog_streams_router.get("/streams", response_model=GraylogStreamsResponse, description="Get all streams")
14 async def get_all_streams() -> GraylogStreamsResponse:
23 - logger.info(f"Fetching all graylog streams")
15 + logger.info("Fetching all graylog streams")
16 return get_streams()
backend/app/connectors/graylog/schema/management.py
-5
@@ -1,8 +1,3 @@
1 -from typing import Dict
2 -from typing import List
3 -from typing import Optional
4 -from typing import Union
5 -
1 from pydantic import BaseModel
2
3
backend/app/connectors/graylog/schema/pipelines.py
-1
@@ -2,7 +2,6 @@ from typing import List
2 from typing import Optional
3
4 from pydantic import BaseModel
5 -from pydantic import Field
5
6
7 class Stage(BaseModel):
backend/app/connectors/graylog/services/collector.py
+1 -1
@@ -15,7 +15,7 @@ from app.connectors.graylog.utils.universal import send_get_request
15
16 def get_indices_full() -> GraylogIndicesResponse:
17 """Get indices from Graylog."""
18 - logger.info(f"Getting indices from Graylog")
18 + logger.info("Getting indices from Graylog")
19 indices_collected = send_get_request(endpoint="/api/system/indexer/indices")
20 if indices_collected["success"]:
21 indices_data = indices_collected["data"]["all"]["indices"]
backend/app/connectors/graylog/services/events.py
+1 -1
@@ -14,7 +14,7 @@ from app.connectors.graylog.utils.universal import send_post_request
14
15 def get_event_definitions() -> GraylogEventDefinitionsResponse:
16 """Get event definitions from Graylog."""
17 - logger.info(f"Getting event definitions from Graylog")
17 + logger.info("Getting event definitions from Graylog")
18 event_definitions_collected = send_get_request(endpoint="/api/events/definitions")
19 if event_definitions_collected["success"]:
20 event_definitions_data = event_definitions_collected["data"]["event_definitions"]
backend/app/connectors/graylog/services/monitoring.py
+1 -1
@@ -11,7 +11,7 @@ from app.connectors.graylog.utils.universal import send_get_request
11
12 def get_messages(page_number: int) -> GraylogMessagesResponse:
13 """Get messages from Graylog."""
14 - logger.info(f"Getting messages from Graylog")
14 + logger.info("Getting messages from Graylog")
15 params = {"page": page_number}
16 messages_collected = send_get_request(endpoint="/api/system/messages", params=params)
17 if messages_collected["success"]:
backend/app/connectors/graylog/services/pipelines.py
+2 -5
@@ -1,6 +1,3 @@
1 -from typing import Any
2 -from typing import Dict
3 -
1 from loguru import logger
2
3 from app.connectors.graylog.schema.pipelines import GraylogPipelinesResponse
@@ -12,7 +9,7 @@ from app.connectors.graylog.utils.universal import send_get_request
9
10 def get_pipelines() -> GraylogPipelinesResponse:
11 """Get pipelines from Graylog."""
15 - logger.info(f"Getting pipelines from Graylog")
12 + logger.info("Getting pipelines from Graylog")
13 pipelines_collected = send_get_request(endpoint="/api/system/pipelines/pipeline")
14 if pipelines_collected["success"]:
15 pipelines_list = [Pipeline(**pipeline_data) for pipeline_data in pipelines_collected["data"]]
@@ -23,7 +20,7 @@ def get_pipelines() -> GraylogPipelinesResponse:
20
21 def get_pipeline_rules() -> PipelineRulesResponse:
22 """Get pipeline rules from Graylog."""
26 - logger.info(f"Getting pipeline rules from Graylog")
23 + logger.info("Getting pipeline rules from Graylog")
24 pipeline_rules_collected = send_get_request(endpoint="/api/system/pipelines/rule")
25 if pipeline_rules_collected["success"]:
26 pipeline_rules_list = [PipelineRule(**pipeline_rule_data) for pipeline_rule_data in pipeline_rules_collected["data"]]
backend/app/connectors/graylog/services/streams.py
+2 -2
@@ -9,7 +9,7 @@ from app.connectors.graylog.utils.universal import send_get_request
9
10 def get_streams() -> GraylogStreamsResponse:
11 """Get streams from Graylog."""
12 - logger.info(f"Getting streams from Graylog")
12 + logger.info("Getting streams from Graylog")
13 streams_collected = send_get_request(endpoint="/api/streams")
14 if streams_collected["success"]:
15 streams_list = [Stream(**stream_data) for stream_data in streams_collected["data"]["streams"]]
@@ -25,7 +25,7 @@ def get_streams() -> GraylogStreamsResponse:
25
26 def get_stream_ids() -> List[str]:
27 """Get stream IDs from Graylog."""
28 - logger.info(f"Getting stream IDs from Graylog")
28 + logger.info("Getting stream IDs from Graylog")
29 streams_collected = send_get_request(endpoint="/api/streams")
30 if streams_collected["success"]:
31 return [stream_data["id"] for stream_data in streams_collected["data"]["streams"]]
backend/app/connectors/routes.py
-10
@@ -1,23 +1,13 @@
1 -from functools import wraps
2 -from http import HTTPStatus
3 -from typing import Callable
4 -from typing import List
1 from typing import Union
2
3 ## Auth Things
4 from fastapi import APIRouter
9 -from fastapi import Depends
5 from fastapi import File
6 from fastapi import HTTPException
12 -from fastapi import Request
7 from fastapi import Security
8 from fastapi import UploadFile
15 -from fastapi.security import HTTPAuthorizationCredentials
16 -from fastapi.security import HTTPBearer
9 from loguru import logger
18 -from starlette.status import HTTP_401_UNAUTHORIZED
10
20 -from app.auth.routes.auth import auth_handler
11 from app.auth.utils import AuthHandler
12 from app.connectors.schema import ConnectorListResponse
13 from app.connectors.schema import ConnectorResponse
backend/app/connectors/shuffle/routes/workflows.py
+2 -6
@@ -7,23 +7,19 @@ from app.connectors.shuffle.schema.workflows import WorkflowExecutionResponseMod
7 from app.connectors.shuffle.schema.workflows import WorkflowsResponse
8 from app.connectors.shuffle.services.workflows import get_workflow_executions
9 from app.connectors.shuffle.services.workflows import get_workflows
10 -from app.db.db_session import session
11 -
12 -# App specific imports
13 -
10
11 shuffle_workflows_router = APIRouter()
12
13
14 @shuffle_workflows_router.get("", response_model=WorkflowsResponse, description="Get all workflows")
15 async def get_all_workflows() -> WorkflowsResponse:
20 - logger.info(f"Fetching all workflows")
16 + logger.info("Fetching all workflows")
17 return get_workflows()
18
19
20 @shuffle_workflows_router.get("/executions", response_model=WorkflowExecutionResponseModel, description="Get all workflow executions")
21 async def get_all_workflow_executions() -> WorkflowExecutionResponseModel:
26 - logger.info(f"Fetching all workflow executions")
22 + logger.info("Fetching all workflow executions")
23
24 # Initialize an empty list for storing workflow details
25 workflow_details = []
backend/app/connectors/sublime/routes/alerts.py
+1 -1
@@ -31,5 +31,5 @@ async def get_sublime_alerts() -> SublimeAlertsResponse:
31 Returns:
32 jsonify: A JSON response containing all the alerts stored in the `sublimealerts` table.
33 """
34 - logger.info(f"Fetching all alerts from Sublime")
34 + logger.info("Fetching all alerts from Sublime")
35 return collect_alerts()
backend/app/connectors/sublime/services/alerts.py
-1
@@ -16,7 +16,6 @@ from app.connectors.sublime.schema.alerts import SublimeAlertsResponse
16 from app.connectors.sublime.schema.alerts import SublimeAlertsSchema
17 from app.connectors.sublime.utils.universal import send_get_request
18 from app.db.db_session import session
19 -from app.db.universal_models import Agents
19
20
21 def create_sublime_alert(alert_request_body: AlertRequestBody) -> SublimeAlerts:
backend/app/connectors/wazuh_indexer/routes/alerts.py
+4 -4
@@ -48,7 +48,7 @@ def verify_index_name(index_alerts_search_body: IndexAlertsSearchBody) -> IndexA
48
49 @wazuh_indexer_alerts_router.post("", response_model=AlertsSearchResponse, description="Get all alerts")
50 async def get_all_alerts(alerts_search_body: AlertsSearchBody) -> AlertsSearchResponse:
51 - logger.info(f"Fetching all alerts")
51 + logger.info("Fetching all alerts")
52 return get_alerts(alerts_search_body)
53
54
@@ -68,13 +68,13 @@ async def get_all_alerts_for_index(
68
69 @wazuh_indexer_alerts_router.post("/hosts/all", response_model=AlertsByHostResponse, description="Get number of all alerts for all hosts")
70 async def get_all_alerts_by_host(alerts_search_body: AlertsSearchBody) -> AlertsByHostResponse:
71 - logger.info(f"Fetching number of all alerts for all hosts")
71 + logger.info("Fetching number of all alerts for all hosts")
72 return get_alerts_by_host(alerts_search_body)
73
74
75 @wazuh_indexer_alerts_router.post("/rules/all", response_model=AlertsByRuleResponse, description="Get number of all alerts for all rules")
76 async def get_all_alerts_by_rule(alerts_search_body: AlertsSearchBody) -> AlertsByRuleResponse:
77 - logger.info(f"Fetching number of all alerts for all rules")
77 + logger.info("Fetching number of all alerts for all rules")
78 return get_alerts_by_rule(alerts_search_body)
79
80
@@ -93,5 +93,5 @@ async def get_all_alerts_by_rule_per_host(alerts_search_body: AlertsSearchBody)
93 Returns:
94 AlertsByRulePerHostResponse: _description_
95 """
96 - logger.info(f"Fetching number of all alerts for all rules per host")
96 + logger.info("Fetching number of all alerts for all rules per host")
97 return get_alerts_by_rule_per_host(alerts_search_body)
backend/app/connectors/wazuh_indexer/routes/monitoring.py
+1 -10
@@ -1,17 +1,8 @@
1 -from typing import List
1 from typing import Union
2
3 from fastapi import APIRouter
4 from fastapi import HTTPException
6 -from fastapi import Request
7 -from fastapi.responses import JSONResponse
8 -from loguru import logger
9 -
10 -from app.connectors.schema import ConnectorListResponse
11 -from app.connectors.schema import ConnectorResponse
12 -from app.connectors.schema import ConnectorsListResponse
13 -from app.connectors.schema import VerifyConnectorResponse
14 -from app.connectors.services import ConnectorServices
5 +
6 from app.connectors.wazuh_indexer.schema.monitoring import ClusterHealthResponse
7 from app.connectors.wazuh_indexer.schema.monitoring import IndicesStatsResponse
8 from app.connectors.wazuh_indexer.schema.monitoring import NodeAllocationResponse
backend/app/connectors/wazuh_manager/services/rules.py
-1
@@ -1,4 +1,3 @@
1 -import re
1 from typing import Any
2 from typing import Dict
3 from typing import List
backend/app/customers/routes/customers.py
+5 -4
@@ -17,8 +17,9 @@ from app.db.db_session import session
17 from app.db.universal_models import Agents
18 from app.db.universal_models import Customers
19 from app.db.universal_models import CustomersMeta
20 +
21 +# from app.healthchecks.agents.schema.agents import AgentModel
22 from app.healthchecks.agents.schema.agents import AgentHealthCheckResponse
21 -from app.healthchecks.agents.schema.agents import AgentModel
23 from app.healthchecks.agents.schema.agents import TimeCriteriaModel
24 from app.healthchecks.agents.services.agents import velociraptor_agents_healthcheck
25 from app.healthchecks.agents.services.agents import wazuh_agents_healthcheck
@@ -49,7 +50,7 @@ async def create_customer(customer: CustomerRequestBody) -> CustomerResponse:
50
51 @customers_router.get("", response_model=CustomersResponse, description="Get all customers")
52 async def get_customers() -> CustomersResponse:
52 - logger.info(f"Fetching all customers")
53 + logger.info("Fetching all customers")
54 customers = session.query(Customers).all()
55 # Explode the customers list into a list of Customer objects
56 customers = [CustomerRequestBody.parse_obj(customer.__dict__) for customer in customers]
@@ -198,7 +199,7 @@ async def get_agents(customer_code: str) -> AgentsResponse:
199 response_model=AgentHealthCheckResponse,
200 description="Get agents healthcheck for the given customer_code",
201 )
201 -async def get_agents_healthcheck(
202 +async def get_wazuh_agents_healthcheck(
203 customer_code: str,
204 minutes: int = Query(60, description="Number of minutes within which the agent should have been last seen to be considered healthy."),
205 hours: int = Query(0, description="Number of hours within which the agent should have been last seen to be considered healthy."),
@@ -221,7 +222,7 @@ async def get_agents_healthcheck(
222 response_model=AgentHealthCheckResponse,
223 description="Get agents healthcheck for the given customer_code",
224 )
224 -async def get_agents_healthcheck(
225 +async def get_velociraptor_agents_healthcheck(
226 customer_code: str,
227 minutes: int = Query(60, description="Number of minutes within which the agent should have been last seen to be considered healthy."),
228 hours: int = Query(0, description="Number of hours within which the agent should have been last seen to be considered healthy."),