Skip to content

Commit 9bd42f4

Browse files
committed
fix: auth header in different ES versions
1 parent 1120394 commit 9bd42f4

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

src/clients/base.py

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from abc import ABC
22
import logging
33
import warnings
4-
from typing import Dict
4+
from typing import Dict, Optional
55

66
from elasticsearch import Elasticsearch
77
import httpx
@@ -39,10 +39,13 @@ def __init__(self, config: Dict, engine_type: str):
3939

4040
# Initialize client based on engine type
4141
if engine_type == "elasticsearch":
42+
# Get auth parameters based on elasticsearch package version
43+
auth_params = self._get_elasticsearch_auth_params(username, password)
44+
4245
self.client = Elasticsearch(
4346
hosts=hosts,
44-
basic_auth=(username, password) if username and password else None,
45-
verify_certs=verify_certs
47+
verify_certs=verify_certs,
48+
**auth_params
4649
)
4750
self.logger.info(f"Elasticsearch client initialized with hosts: {hosts}")
4851
elif engine_type == "opensearch":
@@ -64,9 +67,38 @@ def __init__(self, config: Dict, engine_type: str):
6467
verify_certs=verify_certs,
6568
)
6669

70+
def _get_elasticsearch_auth_params(self, username: Optional[str], password: Optional[str]) -> Dict:
71+
"""
72+
Get authentication parameters for Elasticsearch client based on package version.
73+
74+
Args:
75+
username: Username for authentication
76+
password: Password for authentication
77+
78+
Returns:
79+
Dictionary with appropriate auth parameters for the ES version
80+
"""
81+
if not username or not password:
82+
return {}
83+
84+
# Check Elasticsearch package version to determine auth parameter name
85+
try:
86+
from elasticsearch import __version__ as es_version
87+
major_version = int(es_version.split('.')[0])
88+
89+
if major_version >= 8:
90+
# ES 8+ uses basic_auth
91+
return {"basic_auth": (username, password)}
92+
else:
93+
# ES 7 and below use http_auth
94+
return {"http_auth": (username, password)}
95+
except (ImportError, ValueError, AttributeError):
96+
# If we can't detect version, try basic_auth first (ES 8+ default)
97+
return {"basic_auth": (username, password)}
98+
6799
class GeneralRestClient:
68-
def __init__(self, base_url: str, username: str, password: str, verify_certs: bool):
69-
self.base_url = base_url.rstrip("/")
100+
def __init__(self, base_url: Optional[str], username: Optional[str], password: Optional[str], verify_certs: bool):
101+
self.base_url = base_url.rstrip("/") if base_url else ""
70102
self.auth = (username, password) if username and password else None
71103
self.verify_certs = verify_certs
72104

0 commit comments

Comments
 (0)