security_test.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package controller
  2. import (
  3. "html/template"
  4. "net/http"
  5. "net/http/httptest"
  6. "strings"
  7. "testing"
  8. "git.aetherial.dev/aeth/keiji/pkg/auth"
  9. "git.aetherial.dev/aeth/keiji/pkg/storage"
  10. "github.com/gin-gonic/gin"
  11. )
  12. type securitySource struct{}
  13. func (securitySource) AdminUsername() string { return "admin" }
  14. func (securitySource) AdminPassword() string { return "password" }
  15. type securityRepo struct{ storage.DocumentIO }
  16. func (securityRepo) GetAdminTables() storage.AdminPage { return storage.AdminPage{} }
  17. func (securityRepo) GetNavBarLinks() []storage.NavBarItem { return nil }
  18. func (securityRepo) GetDropdownElements() []storage.LinkPair { return nil }
  19. func TestAuthCookieSecurity(t *testing.T) {
  20. gin.SetMode(gin.TestMode)
  21. for _, insecure := range []bool{false, true} {
  22. t.Run(map[bool]string{false: "production", true: "development"}[insecure], func(t *testing.T) {
  23. if insecure {
  24. t.Setenv("KEIJI_INSECURE_COOKIE", "true")
  25. } else {
  26. t.Setenv("KEIJI_INSECURE_COOKIE", "")
  27. }
  28. c := NewController("example.com", securityRepo{}, nil, securitySource{})
  29. r := gin.New()
  30. r.SetHTMLTemplate(template.Must(template.New("admin").Parse(`{{define "admin"}}ok{{end}}`)))
  31. r.POST("/login", c.Auth)
  32. req := httptest.NewRequest("POST", "/login", strings.NewReader(`{"username":"admin","password":"password"}`))
  33. req.Header.Set("Content-Type", "application/json")
  34. rec := httptest.NewRecorder()
  35. r.ServeHTTP(rec, req)
  36. cookies := rec.Result().Cookies()
  37. if rec.Code != 200 || len(cookies) != 1 {
  38. t.Fatalf("status %d cookies %v", rec.Code, cookies)
  39. }
  40. cookie := cookies[0]
  41. if cookie.Name != AUTH_COOKIE_NAME || cookie.Domain != "" || cookie.Path != "/" || cookie.Secure == insecure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode || cookie.MaxAge != 1200 || !c.Cache.Read(cookie.Value) {
  42. t.Fatalf("bad cookie: %+v", cookie)
  43. }
  44. })
  45. }
  46. }
  47. func TestSameOrigin(t *testing.T) {
  48. gin.SetMode(gin.TestMode)
  49. t.Setenv("KEIJI_INSECURE_COOKIE", "")
  50. r := gin.New()
  51. r.Any("/", SameOrigin, func(c *gin.Context) { c.Status(204) })
  52. for _, tc := range []struct {
  53. method, origin, referer string
  54. want int
  55. }{
  56. {"GET", "", "", 204}, {"POST", "https://example.com", "", 204},
  57. {"PATCH", "", "https://example.com/edit?q=x", 204}, {"DELETE", "https://evil.com", "https://example.com/", 403},
  58. {"POST", "null", "", 403}, {"POST", "", "", 403}, {"POST", "http://example.com", "", 403},
  59. {"POST", "https://example.com.evil.com", "", 403}, {"POST", "https://example.com/path", "", 403},
  60. {"POST", "https://example.com:444", "", 403},
  61. } {
  62. req := httptest.NewRequest(tc.method, "https://example.com/", nil)
  63. req.Header.Set("Origin", tc.origin)
  64. req.Header.Set("Referer", tc.referer)
  65. rec := httptest.NewRecorder()
  66. r.ServeHTTP(rec, req)
  67. if rec.Code != tc.want {
  68. t.Errorf("%s %q %q: %d want %d", tc.method, tc.origin, tc.referer, rec.Code, tc.want)
  69. }
  70. }
  71. t.Setenv("KEIJI_INSECURE_COOKIE", "true")
  72. req := httptest.NewRequest("POST", "http://example.com/", nil)
  73. req.Header.Set("Origin", "http://example.com")
  74. rec := httptest.NewRecorder()
  75. r.ServeHTTP(rec, req)
  76. if rec.Code != 204 {
  77. t.Fatal(rec.Code)
  78. }
  79. }
  80. func TestLoginRateLimitProxy(t *testing.T) {
  81. gin.SetMode(gin.TestMode)
  82. for _, trusted := range []bool{false, true} {
  83. t.Run(map[bool]string{false: "untrusted", true: "trusted"}[trusted], func(t *testing.T) {
  84. if trusted {
  85. t.Setenv("KEIJI_TRUSTED_PROXIES", "10.0.0.0/8")
  86. } else {
  87. t.Setenv("KEIJI_TRUSTED_PROXIES", "")
  88. }
  89. r := gin.New()
  90. r.POST("/", LoginRateLimit(), func(c *gin.Context) { c.Status(204) })
  91. request := func(remote, xff string) int {
  92. req := httptest.NewRequest("POST", "/", nil)
  93. req.RemoteAddr = remote
  94. req.Header.Set("X-Forwarded-For", xff)
  95. rec := httptest.NewRecorder()
  96. r.ServeHTTP(rec, req)
  97. return rec.Code
  98. }
  99. for i := 0; i < 10; i++ {
  100. if got := request("10.0.0.1:123", "1.1.1.1"); got != 204 {
  101. t.Fatal(got)
  102. }
  103. }
  104. if got := request("10.0.0.1:123", "1.1.1.1"); got != 429 {
  105. t.Fatal(got)
  106. }
  107. want := 429
  108. if trusted {
  109. want = 204
  110. }
  111. if got := request("10.0.0.1:123", "2.2.2.2"); got != want {
  112. t.Fatalf("got %d want %d", got, want)
  113. }
  114. if trusted {
  115. if got := request("10.0.0.1:123", "2.2.2.2, 1.1.1.1"); got != 429 {
  116. t.Fatalf("spoofed chain: %d", got)
  117. }
  118. }
  119. })
  120. }
  121. }
  122. func TestAuthenticationStopsHandler(t *testing.T) {
  123. gin.SetMode(gin.TestMode)
  124. c := &Controller{Cache: auth.NewCache()}
  125. r := gin.New()
  126. r.GET("/admin", c.IsAuthenticated, func(c *gin.Context) { c.Status(204) })
  127. rec := httptest.NewRecorder()
  128. r.ServeHTTP(rec, httptest.NewRequest("GET", "/admin", nil))
  129. if rec.Code != 302 || rec.Header().Get("Location") != "/login" {
  130. t.Fatalf("%d %v", rec.Code, rec.Header())
  131. }
  132. }
  133. func TestAuthenticatedAdminRequiresOriginForMutation(t *testing.T) {
  134. gin.SetMode(gin.TestMode)
  135. t.Setenv("KEIJI_INSECURE_COOKIE", "")
  136. c := &Controller{Cache: auth.NewCache()}
  137. session, err := auth.Authorize(&auth.Credentials{Username: "admin", Password: "password"}, c.Cache, securitySource{})
  138. if err != nil {
  139. t.Fatal(err)
  140. }
  141. r := gin.New()
  142. group := r.Group("/admin", c.IsAuthenticated, SameOrigin)
  143. group.GET("/test", func(c *gin.Context) { c.Status(204) })
  144. group.POST("/test", func(c *gin.Context) { c.Status(204) })
  145. group.PATCH("/test", func(c *gin.Context) { c.Status(204) })
  146. group.DELETE("/test", func(c *gin.Context) { c.Status(204) })
  147. for _, tc := range []struct {
  148. method, origin string
  149. want int
  150. }{{"GET", "", 204}, {"POST", "", 403}, {"POST", "https://evil.example", 403}, {"POST", "https://example.com", 204}, {"PATCH", "https://example.com", 204}, {"DELETE", "https://example.com", 204}} {
  151. req := httptest.NewRequest(tc.method, "https://example.com/admin/test", nil)
  152. req.AddCookie(&http.Cookie{Name: AUTH_COOKIE_NAME, Value: session})
  153. req.Header.Set("Origin", tc.origin)
  154. rec := httptest.NewRecorder()
  155. r.ServeHTTP(rec, req)
  156. if rec.Code != tc.want {
  157. t.Errorf("%s origin %q: got %d want %d", tc.method, tc.origin, rec.Code, tc.want)
  158. }
  159. }
  160. }