Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x](backport #3935) Fix bad error handling in api key auth #3937

Merged
merged 1 commit into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Kind can be one of:
# - breaking-change: a change to previously-documented behavior
# - deprecation: functionality that is being removed in a later release
# - bug-fix: fixes a problem in a previous version
# - enhancement: extends functionality but does not break or fix existing behavior
# - feature: new functionality
# - known-issue: problems that we are aware of in a given version
# - security: impacts on the security of a product or a user’s deployment.
# - upgrade: important information for someone upgrading from a prior version
# - other: does not fit into any of the other categories
kind: bug-fix

# Change summary; a 80ish characters long description of the change.
summary: Fix authentication return error code

# Long description; in case the summary is not enough to describe the change
# this field accommodate a description without length limits.
# NOTE: This field will be rendered only for breaking-change and known-issue kinds at the moment.
description: |
A non-401 error code from elasticsearch will no longer result in a 401 error code being returned to the caller.

# Affected component; usually one of "elastic-agent", "fleet-server", "filebeat", "metricbeat", "auditbeat", "all", etc.
component:

# PR URL; optional; the PR number that added the changeset.
# If not present is automatically filled by the tooling finding the PR where this changelog fragment has been added.
# NOTE: the tooling supports backports, so it's able to fill the original PR number instead of the backport PR number.
# Please provide it if you are adding a fragment for a different PR.
pr: https://github.com/elastic/fleet-server/pull/3935

# Issue URL; optional; the GitHub issue related to this changeset (either closes or is part of).
# If not present is automatically filled by the tooling with the issue linked to the PR number.
issue: https://github.com/elastic/fleet-server/issues/3929
20 changes: 15 additions & 5 deletions internal/pkg/apikey/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@
"encoding/json"
"errors"
"fmt"
"net/http"

"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/esapi"

"github.com/elastic/fleet-server/v7/internal/pkg/es"
)

var (
Expand All @@ -33,15 +36,15 @@

// Authenticate will return the SecurityInfo associated with the APIKey (retrieved from Elasticsearch).
// Note: Prefer the bulk wrapper on this API
func (k APIKey) Authenticate(ctx context.Context, es *elasticsearch.Client) (*SecurityInfo, error) {
func (k APIKey) Authenticate(ctx context.Context, client *elasticsearch.Client) (*SecurityInfo, error) {

Check failure on line 39 in internal/pkg/apikey/auth.go

View workflow job for this annotation

GitHub Actions / lint (linux)

undefined: elasticsearch (typecheck)

token := fmt.Sprintf("%s%s", authPrefix, k.Token())

Check failure on line 41 in internal/pkg/apikey/auth.go

View workflow job for this annotation

GitHub Actions / lint (linux)

token declared and not used (typecheck)

req := esapi.SecurityAuthenticateRequest{
Header: map[string][]string{AuthKey: []string{token}},
}

res, err := req.Do(ctx, es)
res, err := req.Do(ctx, client)

if err != nil {
return nil, fmt.Errorf("apikey auth request %s: %w", k.ID, err)
Expand All @@ -52,11 +55,18 @@
}

if res.IsError() {
returnError := ErrUnauthorized
if res.StatusCode == 429 {
var returnError error
switch res.StatusCode {
case http.StatusUnauthorized:
returnError = ErrUnauthorized
case http.StatusTooManyRequests:
returnError = ErrElasticsearchAuthLimit
}
return nil, fmt.Errorf("%w: %w", returnError, fmt.Errorf("apikey auth response %s: %s", k.ID, res.String()))
if returnError != nil {
return nil, fmt.Errorf("%w: %w", returnError, fmt.Errorf("apikey auth response %s: %s", k.ID, res.String()))
}
// body is not parsed to not give the caller too much information
return nil, es.TranslateError(res.StatusCode, nil)
}

var info SecurityInfo
Expand Down
31 changes: 29 additions & 2 deletions internal/pkg/apikey/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import (
"context"
"encoding/base64"
"fmt"
"net/http"
"testing"

Expand All @@ -19,7 +20,7 @@
rawToken = " foo:bar"
)

func setup(t *testing.T, statusCode int) (context.Context, *APIKey, *elasticsearch.Client) {

Check failure on line 23 in internal/pkg/apikey/auth_test.go

View workflow job for this annotation

GitHub Actions / lint (linux)

undefined: elasticsearch (typecheck)
token := base64.StdEncoding.EncodeToString([]byte(rawToken))
apiKey, err := NewAPIKeyFromToken(token)
assert.NoError(t, err)
Expand All @@ -32,15 +33,41 @@
}

func TestAuth429(t *testing.T) {
ctx, apiKey, mockES := setup(t, 429)
ctx, apiKey, mockES := setup(t, http.StatusTooManyRequests)
_, err := apiKey.Authenticate(ctx, mockES)

assert.Equal(t, "elasticsearch auth limit: apikey auth response foo: [429 Too Many Requests] ", err.Error())
}

func TestAuth401(t *testing.T) {
ctx, apiKey, mockES := setup(t, 401)
ctx, apiKey, mockES := setup(t, http.StatusUnauthorized)
_, err := apiKey.Authenticate(ctx, mockES)

assert.Equal(t, "unauthorized: apikey auth response foo: [401 Unauthorized] ", err.Error())
}

func TestAuthOtherErrors(t *testing.T) {
scenarios := []struct {
StatusCode int
}{
{StatusCode: http.StatusBadRequest},
// 401 is handled in TestAuth401
{StatusCode: http.StatusForbidden},
{StatusCode: http.StatusNotFound},
{StatusCode: http.StatusMethodNotAllowed},
{StatusCode: http.StatusConflict},
// 429 is handled in TestAuth429
{StatusCode: http.StatusInternalServerError},
{StatusCode: http.StatusBadGateway},
{StatusCode: http.StatusServiceUnavailable},
{StatusCode: http.StatusGatewayTimeout},
}
for _, scenario := range scenarios {
t.Run(fmt.Sprintf("%d", scenario.StatusCode), func(t *testing.T) {
ctx, apiKey, mockES := setup(t, scenario.StatusCode)
_, err := apiKey.Authenticate(ctx, mockES)

assert.Equal(t, fmt.Sprintf("elastic fail %d", scenario.StatusCode), err.Error())
})
}
}
Loading