| package middleware |
|
|
| import ( |
| "net/http" |
| "net/http/httptest" |
| "testing" |
|
|
| "github.com/gin-gonic/gin" |
| ) |
|
|
| func setupTestRouter(allowedKeys []string) *gin.Engine { |
| gin.SetMode(gin.TestMode) |
| r := gin.New() |
| r.Use(AuthenticateAnthropicRequest(allowedKeys)) |
| r.GET("/test", func(c *gin.Context) { |
| apiKey, _ := c.Get("apiKey") |
| c.String(http.StatusOK, "OK: "+apiKey.(string)) |
| }) |
| return r |
| } |
|
|
| func TestBearerTokenAuth(t *testing.T) { |
| router := setupTestRouter([]string{"valid-key"}) |
|
|
| w := httptest.NewRecorder() |
| req, _ := http.NewRequest("GET", "/test", nil) |
| req.Header.Set("Authorization", "Bearer valid-key") |
|
|
| router.ServeHTTP(w, req) |
|
|
| if w.Code != http.StatusOK { |
| t.Errorf("Expected status 200, got %d", w.Code) |
| } |
| if w.Body.String() != "OK: valid-key" { |
| t.Errorf("Expected body 'OK: valid-key', got '%s'", w.Body.String()) |
| } |
| } |
|
|
| func TestXAPIKeyAuth(t *testing.T) { |
| router := setupTestRouter([]string{"valid-key"}) |
|
|
| w := httptest.NewRecorder() |
| req, _ := http.NewRequest("GET", "/test", nil) |
| req.Header.Set("X-API-Key", "valid-key") |
|
|
| router.ServeHTTP(w, req) |
|
|
| if w.Code != http.StatusOK { |
| t.Errorf("Expected status 200, got %d", w.Code) |
| } |
| if w.Body.String() != "OK: valid-key" { |
| t.Errorf("Expected body 'OK: valid-key', got '%s'", w.Body.String()) |
| } |
| } |
|
|
| func TestQueryParamAuth(t *testing.T) { |
| router := setupTestRouter([]string{"valid-key"}) |
|
|
| w := httptest.NewRecorder() |
| req, _ := http.NewRequest("GET", "/test?api_key=valid-key", nil) |
|
|
| router.ServeHTTP(w, req) |
|
|
| if w.Code != http.StatusOK { |
| t.Errorf("Expected status 200, got %d", w.Code) |
| } |
| if w.Body.String() != "OK: valid-key" { |
| t.Errorf("Expected body 'OK: valid-key', got '%s'", w.Body.String()) |
| } |
| } |
|
|
| func TestNoAuth(t *testing.T) { |
| router := setupTestRouter([]string{"valid-key"}) |
|
|
| w := httptest.NewRecorder() |
| req, _ := http.NewRequest("GET", "/test", nil) |
|
|
| router.ServeHTTP(w, req) |
|
|
| if w.Code != http.StatusUnauthorized { |
| t.Errorf("Expected status 401, got %d", w.Code) |
| } |
| } |
|
|
| func TestInvalidKey(t *testing.T) { |
| router := setupTestRouter([]string{"valid-key"}) |
|
|
| w := httptest.NewRecorder() |
| req, _ := http.NewRequest("GET", "/test", nil) |
| req.Header.Set("Authorization", "Bearer invalid-key") |
|
|
| router.ServeHTTP(w, req) |
|
|
| if w.Code != http.StatusUnauthorized { |
| t.Errorf("Expected status 401, got %d", w.Code) |
| } |
| } |