Skip to content

Commit

Permalink
feat: update dal key validation (#1747)
Browse files Browse the repository at this point in the history
  • Loading branch information
nick-bisonai authored Jul 8, 2024
1 parent 766e9dc commit 91cf5b3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 14 deletions.
24 changes: 24 additions & 0 deletions node/pkg/dal/tests/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"bisonai.com/orakl/node/pkg/aggregator"
"bisonai.com/orakl/node/pkg/dal/api"
"bisonai.com/orakl/node/pkg/dal/common"
"bisonai.com/orakl/node/pkg/utils/request"
wsfcommon "bisonai.com/orakl/node/pkg/websocketfetcher/common"
"bisonai.com/orakl/node/pkg/wss"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -78,6 +79,29 @@ func TestApiGetLatestAll(t *testing.T) {
}
}

func TestShouldFailWithoutApiKey(t *testing.T) {
ctx := context.Background()
clean, testItems, err := setup(ctx)
if err != nil {
t.Fatalf("error setting up test: %v", err)
}
defer func() {
if cleanupErr := clean(); cleanupErr != nil {
t.Logf("Cleanup failed: %v", cleanupErr)
}
}()

testItems.Controller.Start(ctx)
go testItems.App.Listen(":8090")
resp, err := request.RequestRaw(request.WithEndpoint("http://localhost:8090/api/v1"))

if err != nil {
t.Fatalf("error getting latest data: %v", err)
}

assert.Equal(t, 401, resp.StatusCode)
}

func TestApiGetLatest(t *testing.T) {
ctx := context.Background()
clean, testItems, err := setup(ctx)
Expand Down
28 changes: 14 additions & 14 deletions node/pkg/dal/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,22 @@ import (

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/keyauth"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/rs/zerolog/log"
)

func APIKeyMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
apiKey := c.Get("X-API-Key")

validAPIKey := os.Getenv("API_KEY")

if apiKey != validAPIKey {
log.Warn().Msg("Unauthorized access attempt")
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
"error": "Unauthorized",
})
}
func validator(ctx *fiber.Ctx, s string) (bool, error) {
key := os.Getenv("API_KEY")
if s == "" {
return false, fmt.Errorf("missing api key")
}

return c.Next()
if s == key {
return true, nil
}

return false, fmt.Errorf("invalid api key")
}

func Setup(ctx context.Context) (*fiber.App, error) {
Expand Down Expand Up @@ -61,7 +58,10 @@ func Setup(ctx context.Context) (*fiber.App, error) {
))

app.Use(cors.New())
app.Use(APIKeyMiddleware())
app.Use(keyauth.New(keyauth.Config{
KeyLookup: "header:X-API-Key",
Validator: validator,
}))
return app, nil
}

Expand Down

0 comments on commit 91cf5b3

Please sign in to comment.