middleware_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package fever // import "miniflux.app/v2/internal/fever"
  4. import (
  5. "encoding/json"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. )
  11. func TestMiddlewareRejectsMissingAPIKey(t *testing.T) {
  12. newPostRequest := func(body string) *http.Request {
  13. request := httptest.NewRequest(http.MethodPost, "/fever/?api", strings.NewReader(body))
  14. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  15. return request
  16. }
  17. scenarios := []struct {
  18. name string
  19. request *http.Request
  20. }{
  21. {"GET without api_key", httptest.NewRequest(http.MethodGet, "/fever/?api&groups", nil)},
  22. {"GET with an empty api_key", httptest.NewRequest(http.MethodGet, "/fever/?api&groups&api_key=", nil)},
  23. {"POST without api_key", newPostRequest("mark=item&as=read&id=1")},
  24. {"POST with an empty api_key", newPostRequest("api_key=&mark=item&as=read&id=1")},
  25. }
  26. // The store is nil: every request must be rejected before the store is queried.
  27. middleware := Middleware(nil)
  28. next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  29. t.Fatal("next handler should not be called")
  30. })
  31. for _, scenario := range scenarios {
  32. t.Run(scenario.name, func(t *testing.T) {
  33. recorder := httptest.NewRecorder()
  34. middleware(next).ServeHTTP(recorder, scenario.request)
  35. if recorder.Code != http.StatusOK {
  36. t.Fatalf(`Expected status %d, got %d`, http.StatusOK, recorder.Code)
  37. }
  38. var result baseResponse
  39. if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
  40. t.Fatalf(`Unable to decode %s: %v`, recorder.Body.Bytes(), err)
  41. }
  42. if result.Version != 3 || result.Authenticated != 0 {
  43. t.Errorf(`Expected an authentication failure for API version 3, got %s`, recorder.Body.Bytes())
  44. }
  45. })
  46. }
  47. }