From fde1763eefc998c45d0a1ce6e1be20df6a23e18a Mon Sep 17 00:00:00 2001 From: kolaente Date: Thu, 29 Aug 2024 10:12:20 +0200 Subject: [PATCH] fix(api): return 404 response when using a token and the route does not exist --- pkg/integrations/api_tokens_test.go | 16 ++++++++++++++++ pkg/routes/api_tokens.go | 7 +++++++ 2 files changed, 23 insertions(+) diff --git a/pkg/integrations/api_tokens_test.go b/pkg/integrations/api_tokens_test.go index 7fde9e001..c3f98dd5c 100644 --- a/pkg/integrations/api_tokens_test.go +++ b/pkg/integrations/api_tokens_test.go @@ -111,4 +111,20 @@ func TestAPIToken(t *testing.T) { req.Header.Set(echo.HeaderAuthorization, "Bearer "+jwt) require.NoError(t, h(c)) }) + t.Run("nonexisting route", func(t *testing.T) { + e, err := setupTestEnv() + require.NoError(t, err) + req := httptest.NewRequest(http.MethodGet, "/api/v1/nonexisting", nil) + res := httptest.NewRecorder() + c := e.NewContext(req, res) + h := routes.SetupTokenMiddleware()(func(c echo.Context) error { + return c.String(http.StatusNotFound, "test") + }) + + req.Header.Set(echo.HeaderAuthorization, "Bearer tk_a5e6f92ddbad68f49ee2c63e52174db0235008c8") // Token 2 + + err = h(c) + require.NoError(t, err) + assert.Equal(t, 404, c.Response().Status) + }) } diff --git a/pkg/routes/api_tokens.go b/pkg/routes/api_tokens.go index 55596f334..4220dbcf0 100644 --- a/pkg/routes/api_tokens.go +++ b/pkg/routes/api_tokens.go @@ -41,6 +41,13 @@ func SetupTokenMiddleware() echo.MiddlewareFunc { for _, s := range authHeader { if strings.HasPrefix(s, "Bearer "+models.APITokenPrefix) { + // If the route does not exist, skip the current handling and let the rest of echo's logic handle it + findCtx := c.Echo().NewContext(c.Request(), c.Response()) + c.Echo().Router().Find(c.Request().Method, echo.GetPath(c.Request()), findCtx) + if findCtx.Path() == "/api/v1/*" { + return true + } + err := checkAPITokenAndPutItInContext(s, c) return err == nil }