rss-tools/app/http_test.go (view raw)
Oleksandr Smirnov
Oleksandr Smirnov
olexsmir@gmail.com add auth middleware (at the moment only fixed token), 1 month ago
olexsmir@gmail.com add auth middleware (at the moment only fixed token), 1 month ago
| 1 | package app |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "olexsmir.xyz/x/is" |
| 10 | ) |
| 11 | |
| 12 | func TestAuthMiddlewareDisabledWithoutToken(t *testing.T) { |
| 13 | a := &App{Config: &Config{}} |
| 14 | handler := a.authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 15 | w.WriteHeader(http.StatusNoContent) |
| 16 | })) |
| 17 | |
| 18 | r := httptest.NewRequest(http.MethodGet, "/telegram", nil) |
| 19 | w := httptest.NewRecorder() |
| 20 | handler.ServeHTTP(w, r) |
| 21 | |
| 22 | is.Equal(t, http.StatusNoContent, w.Code) |
| 23 | } |
| 24 | |
| 25 | func TestAuthMiddlewareAllowsQueryToken(t *testing.T) { |
| 26 | a := &App{Config: &Config{AuthToken: "secret"}} |
| 27 | handler := a.authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 28 | w.WriteHeader(http.StatusNoContent) |
| 29 | })) |
| 30 | |
| 31 | r := httptest.NewRequest(http.MethodGet, "/telegram?token=secret", nil) |
| 32 | w := httptest.NewRecorder() |
| 33 | handler.ServeHTTP(w, r) |
| 34 | |
| 35 | is.Equal(t, http.StatusNoContent, w.Code) |
| 36 | } |
| 37 | |
| 38 | func TestAuthMiddlewareAllowsAuthorizationHeader(t *testing.T) { |
| 39 | a := &App{Config: &Config{AuthToken: "secret"}} |
| 40 | handler := a.authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 41 | w.WriteHeader(http.StatusNoContent) |
| 42 | })) |
| 43 | |
| 44 | r := httptest.NewRequest(http.MethodGet, "/telegram", nil) |
| 45 | r.Header.Set("Authorization", "secret") |
| 46 | w := httptest.NewRecorder() |
| 47 | handler.ServeHTTP(w, r) |
| 48 | |
| 49 | is.Equal(t, http.StatusNoContent, w.Code) |
| 50 | } |
| 51 | |
| 52 | func TestAuthMiddlewareRejectsBadToken(t *testing.T) { |
| 53 | a := &App{Config: &Config{AuthToken: "secret"}} |
| 54 | handler := a.authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 55 | w.WriteHeader(http.StatusNoContent) |
| 56 | })) |
| 57 | |
| 58 | r := httptest.NewRequest(http.MethodGet, "/telegram?token=bad", nil) |
| 59 | w := httptest.NewRecorder() |
| 60 | handler.ServeHTTP(w, r) |
| 61 | |
| 62 | is.Equal(t, http.StatusUnauthorized, w.Code) |
| 63 | if !strings.Contains(w.Body.String(), "unauthorized") { |
| 64 | t.Fatalf("unexpected body: %q", w.Body.String()) |
| 65 | } |
| 66 | } |