middleware_scope_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package auth
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. )
  7. type fakeTokenValidator struct {
  8. user *User
  9. scope string
  10. }
  11. func (f fakeTokenValidator) ValidateBearer(string) (*User, string) {
  12. return f.user, f.scope
  13. }
  14. func scopeHandler(scope string, admin bool) http.Handler {
  15. var next http.Handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
  16. w.WriteHeader(http.StatusOK)
  17. })
  18. if admin {
  19. next = RequireAdmin(next)
  20. }
  21. return RequireAuth(nil, "secret", fakeTokenValidator{
  22. user: &User{ID: 1, Username: "admin", Role: "admin"},
  23. scope: scope,
  24. }, next)
  25. }
  26. func TestScopeAllowsMethodFailClosed(t *testing.T) {
  27. admin := &User{ID: 1, Username: "admin", Role: "admin"}
  28. for _, tc := range []struct {
  29. name string
  30. scope string
  31. method string
  32. want int
  33. }{
  34. {"read get", ScopeRead, http.MethodGet, http.StatusOK},
  35. {"read head", ScopeRead, http.MethodHead, http.StatusOK},
  36. {"read post", ScopeRead, http.MethodPost, http.StatusForbidden},
  37. {"read delete", ScopeRead, http.MethodDelete, http.StatusForbidden},
  38. {"write post", ScopeWrite, http.MethodPost, http.StatusOK},
  39. {"admin post", ScopeAdmin, http.MethodPost, http.StatusOK},
  40. {"unknown scope get", "bogus", http.MethodGet, http.StatusForbidden},
  41. {"empty scope get", "", http.MethodGet, http.StatusForbidden},
  42. } {
  43. t.Run(tc.name, func(t *testing.T) {
  44. h := RequireAuth(nil, "secret", fakeTokenValidator{user: admin, scope: tc.scope},
  45. http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }))
  46. req := httptest.NewRequest(tc.method, "/api/overview", nil)
  47. req.Header.Set("Authorization", "Bearer np_test")
  48. rec := httptest.NewRecorder()
  49. h.ServeHTTP(rec, req)
  50. if rec.Code != tc.want {
  51. t.Fatalf("got %d want %d (body %s)", rec.Code, tc.want, rec.Body.String())
  52. }
  53. })
  54. }
  55. }
  56. func TestRequireAdminRejectsNonAdminTokenScope(t *testing.T) {
  57. for _, tc := range []struct {
  58. scope string
  59. want int
  60. }{
  61. {ScopeRead, http.StatusForbidden},
  62. {ScopeWrite, http.StatusForbidden},
  63. {ScopeAdmin, http.StatusOK},
  64. } {
  65. t.Run(tc.scope, func(t *testing.T) {
  66. req := httptest.NewRequest(http.MethodGet, "/api/settings/backup", nil)
  67. req.Header.Set("Authorization", "Bearer np_test")
  68. rec := httptest.NewRecorder()
  69. scopeHandler(tc.scope, true).ServeHTTP(rec, req)
  70. if rec.Code != tc.want {
  71. t.Fatalf("got %d want %d (body %s)", rec.Code, tc.want, rec.Body.String())
  72. }
  73. })
  74. }
  75. }