From aefcea034a2d93d4f020beca15ba480e0d8b11c3 Mon Sep 17 00:00:00 2001 From: Nicola Murino Date: Fri, 8 Sep 2023 18:54:11 +0200 Subject: [PATCH] validate API key scope Signed-off-by: Nicola Murino --- internal/httpd/httpd_test.go | 16 ++++++++++++++++ internal/httpd/middleware.go | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/internal/httpd/httpd_test.go b/internal/httpd/httpd_test.go index 9055b676..8e6e7988 100644 --- a/internal/httpd/httpd_test.go +++ b/internal/httpd/httpd_test.go @@ -15008,6 +15008,13 @@ func TestUserAPIKey(t *testing.T) { apiKey, _, err = httpdtest.AddAPIKey(apiKey, http.StatusCreated) assert.NoError(t, err) + adminAPIKey := dataprovider.APIKey{ + Name: "testadminkey", + Scope: dataprovider.APIKeyScopeAdmin, + } + adminAPIKey, _, err = httpdtest.AddAPIKey(adminAPIKey, http.StatusCreated) + assert.NoError(t, err) + body := new(bytes.Buffer) writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("filenames", "filenametest") @@ -15036,6 +15043,12 @@ func TestUserAPIKey(t *testing.T) { assert.NoError(t, err) assert.Len(t, dirEntries, 1) + req, err = http.NewRequest(http.MethodGet, userDirsPath, nil) + assert.NoError(t, err) + setAPIKeyForReq(req, adminAPIKey.Key, user.Username) + rr = executeRequest(req) + checkResponseCode(t, http.StatusForbidden, rr) + user.Status = 0 user, _, err = httpdtest.UpdateUser(user, http.StatusOK, "") assert.NoError(t, err) @@ -15112,6 +15125,9 @@ func TestUserAPIKey(t *testing.T) { _, err = httpdtest.RemoveAPIKey(apiKeyNew, http.StatusOK) assert.NoError(t, err) + + _, err = httpdtest.RemoveAPIKey(adminAPIKey, http.StatusOK) + assert.NoError(t, err) } func TestWebClientViewPDF(t *testing.T) { diff --git a/internal/httpd/middleware.go b/internal/httpd/middleware.go index 4c2828ba..095b68a9 100644 --- a/internal/httpd/middleware.go +++ b/internal/httpd/middleware.go @@ -384,6 +384,13 @@ func checkAPIKeyAuth(tokenAuth *jwtauth.JWTAuth, scope dataprovider.APIKeyScope) sendAPIResponse(w, r, errors.New("the provided api key is not valid"), "", http.StatusBadRequest) return } + if k.Scope != scope { + handleDefenderEventLoginFailed(util.GetIPFromRemoteAddress(r.RemoteAddr), dataprovider.ErrInvalidCredentials) //nolint:errcheck + logger.Debug(logSender, "", "unable to authenticate api key %q: invalid scope: got %d, wnated: %d", + apiKey, k.Scope, scope) + sendAPIResponse(w, r, fmt.Errorf("the provided api key is invalid for this request"), "", http.StatusForbidden) + return + } if err := k.Authenticate(key); err != nil { handleDefenderEventLoginFailed(util.GetIPFromRemoteAddress(r.RemoteAddr), dataprovider.ErrInvalidCredentials) //nolint:errcheck logger.Debug(logSender, "", "unable to authenticate api key %q: %v", apiKey, err)