Skip to content

Commit

Permalink
Support auth against OpenSearch (#1030)
Browse files Browse the repository at this point in the history
Little hackish, as it involves additional call to the backend (in order
to decide whether use OpenSearch or Elasticsearch security endpoint)
**but** given that we have auth header cache I think we might get away
with that 😉


FWIW, Elasticsearch 7 uses the same [endpoint
(`_security/_authenticate`)](https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api-authenticate.html)
as Elasticsearch 8 for auth (just verified 😌)
  • Loading branch information
mieciu authored Nov 22, 2024
1 parent 213d0db commit 54ce30f
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions quesma/elasticsearch/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ import (
"time"
)

const esRequestTimeout = 5 * time.Second
const (
esRequestTimeout = 5 * time.Second
elasticsearchSecurityEndpoint = "_security/_authenticate"
openSearchSecurityEndpoint = "_plugins/_security/api/account"
)

type SimpleClient struct {
client *http.Client
Expand Down Expand Up @@ -41,7 +45,22 @@ func (es *SimpleClient) RequestWithHeaders(ctx context.Context, method, endpoint
}

func (es *SimpleClient) Authenticate(ctx context.Context, authHeader string) bool {
resp, err := es.doRequest(ctx, "GET", "_security/_authenticate", nil, http.Header{"Authorization": {authHeader}})
var authEndpoint string
// This is really suboptimal, and we should find a better way to set this systematically (config perhaps?)
// OTOH, since we have auth cache in place, I am not concerned about this additional backend call - at least for the time being.
r, err := es.doRequest(ctx, "GET", "/", nil, http.Header{"Authorization": {authHeader}})
if err != nil {
logger.ErrorWithCtx(ctx).Msgf("error sending request: %v", err)
return false
}
defer r.Body.Close()

if isResponseFromElasticsearch(r) {
authEndpoint = elasticsearchSecurityEndpoint
} else {
authEndpoint = openSearchSecurityEndpoint
}
resp, err := es.doRequest(ctx, "GET", authEndpoint, nil, http.Header{"Authorization": {authHeader}})
if err != nil {
logger.ErrorWithCtx(ctx).Msgf("error sending request: %v", err)
return false
Expand All @@ -66,3 +85,7 @@ func (es *SimpleClient) doRequest(ctx context.Context, method, endpoint string,
}
return es.client.Do(req)
}

func isResponseFromElasticsearch(resp *http.Response) bool {
return resp.Header.Get("X-Elastic-Product") != ""
}

0 comments on commit 54ce30f

Please sign in to comment.