diff --git a/internal/beater/auth/apikey.go b/internal/beater/auth/apikey.go index 324b97d983b..74c0481e400 100644 --- a/internal/beater/auth/apikey.go +++ b/internal/beater/auth/apikey.go @@ -20,7 +20,9 @@ package auth import ( "bytes" "context" + "crypto/sha256" "encoding/base64" + "encoding/hex" "errors" "fmt" "net/http" @@ -91,7 +93,7 @@ func (a *apikeyAuth) authenticate(ctx context.Context, credentials string) (*API id := string(before) // Check that the user has any privileges for the internal resource. - response, err := a.hasPrivileges(ctx, id, credentials, ResourceInternal) + response, err := a.hasPrivileges(ctx, credentials, ResourceInternal) if err != nil { return nil, nil, err } @@ -110,8 +112,9 @@ func (a *apikeyAuth) authenticate(ctx context.Context, credentials string) (*API return details, &apikeyAuthorizer{permissions}, nil } -func (a *apikeyAuth) hasPrivileges(ctx context.Context, id, credentials string, resource es.Resource) (*es.HasPrivilegesResponse, error) { - cacheKey := id + "_" + string(resource) +func (a *apikeyAuth) hasPrivileges(ctx context.Context, credentials string, resource es.Resource) (*es.HasPrivilegesResponse, error) { + sum := sha256.Sum256([]byte(credentials)) + cacheKey := hex.EncodeToString(sum[:]) + "_" + string(resource) if response, ok := a.cache.get(cacheKey); ok { if response == nil { return nil, ErrAuthFailed diff --git a/internal/beater/auth/authenticator_test.go b/internal/beater/auth/authenticator_test.go index 954b78974f4..270220d7ce6 100644 --- a/internal/beater/auth/authenticator_test.go +++ b/internal/beater/auth/authenticator_test.go @@ -235,7 +235,7 @@ func TestAuthenticatorAPIKeyCache(t *testing.T) { } } }`)) - case invalidCredentials: + case validCredentials2, invalidCredentials: w.WriteHeader(http.StatusUnauthorized) default: panic("unexpected credentials: " + credentials) @@ -248,7 +248,7 @@ func TestAuthenticatorAPIKeyCache(t *testing.T) { esConfig := elasticsearch.DefaultConfig() esConfig.Hosts = elasticsearch.Hosts{srv.URL} - apikeyAuthConfig := config.APIKeyAgentAuth{Enabled: true, LimitPerMin: 2, ESConfig: esConfig} + apikeyAuthConfig := config.APIKeyAgentAuth{Enabled: true, LimitPerMin: 3, ESConfig: esConfig} authenticator, err := NewAuthenticator(config.AgentAuth{APIKey: apikeyAuthConfig}, tp, logptest.NewTestingLogger(t, "")) require.NoError(t, err) @@ -261,8 +261,12 @@ func TestAuthenticatorAPIKeyCache(t *testing.T) { assert.Equal(t, "Elasticsearch: GET _security/user/_has_privileges", spans[0].Name()) exporter.clear() - // API Key checks are cached based on the API Key ID, not the full credential. _, _, err = authenticator.Authenticate(context.Background(), headers.APIKey, validCredentials2) + assert.Equal(t, ErrAuthFailed, err) + assert.Len(t, exporter.payloads(), 1) + exporter.clear() + + _, _, err = authenticator.Authenticate(context.Background(), headers.APIKey, validCredentials) assert.NoError(t, err) assert.Len(t, exporter.payloads(), 0) exporter.clear()