cookie_test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. package auth
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "testing"
  7. "devt.de/krotik/common/httputil"
  8. "devt.de/krotik/common/httputil/user"
  9. )
  10. func TestCookieAuth(t *testing.T) {
  11. // Set a very fast session expiry
  12. user.UserSessionManager.Provider.(*user.MemorySessionProvider).SetExpiry(1)
  13. // Create a wrapper for basic auth
  14. ca := NewCookieAuthHandleFuncWrapper(func(pattern string,
  15. handler func(http.ResponseWriter, *http.Request)) {
  16. // Ignore the pattern and just replace the wrappedHandleFunction
  17. wrappedHandleFunction = handler
  18. })
  19. ca.SetExpiry(42)
  20. if res := ca.Expiry(); res != 42 {
  21. t.Error("Unexpected result:", res)
  22. return
  23. }
  24. // Ensure custom handle function is set back
  25. defer func() { handleCallback = func(w http.ResponseWriter, r *http.Request) {} }()
  26. // Wrap the originalHandleFunction and let the previous code set it
  27. // as wrappedHandleFunction
  28. ca.HandleFunc("/", originalHandleFunction)
  29. // Test that basic authentication is active
  30. res, _ := sendTestRequest(TESTQUERYURL, "GET", nil, nil, nil)
  31. if res != "Unauthorized" {
  32. t.Error("Unexpected result:", res)
  33. return
  34. }
  35. // Test disabling authentication temporarily
  36. TestCookieAuthDisabled = true
  37. res, _ = sendTestRequest(TESTQUERYURL, "GET", nil, nil, nil)
  38. if res != "Content" {
  39. t.Error("Unexpected result:", res)
  40. return
  41. }
  42. TestCookieAuthDisabled = false
  43. res, _ = sendTestRequest(TESTQUERYURL, "GET", nil, nil, nil)
  44. if res != "Unauthorized" {
  45. t.Error("Unexpected result:", res)
  46. return
  47. }
  48. // Register credentials and try to authenticate
  49. ca.SetAuthFunc(func(user, pass string) bool {
  50. return user == "yams" && pass == "yams"
  51. })
  52. // Test authentication
  53. if testres := ca.AuthUser("yams", "yams", true); testres != "ok" {
  54. t.Error("Unexpected result:", testres)
  55. }
  56. ca.AddPublicPage("/foo/pic", httputil.SingleFileServer("test.jpg", nil).ServeHTTP)
  57. // Simulate authentication
  58. ca.AddPublicPage("/foo/login", func(w http.ResponseWriter, r *http.Request) {
  59. // Create a token
  60. token := ca.AuthUser(r.Header.Get("user1"), r.Header.Get("pass1"), false)
  61. // Set the cookie
  62. ca.SetAuthCookie(token, w)
  63. })
  64. ca.AddPublicPage("/foo/logout", func(w http.ResponseWriter, r *http.Request) {
  65. ca.InvalidateAuthCookie(r)
  66. ca.RemoveAuthCookie(w)
  67. })
  68. // Get some public content
  69. res, resp := sendTestRequest(TESTQUERYURL+"/pic", "GET", nil, nil, nil)
  70. if res != "testpic" {
  71. t.Error("Unexpected result:", res)
  72. return
  73. }
  74. // Login request
  75. _, resp = sendTestRequest(TESTQUERYURL+"/login", "GET", map[string]string{
  76. "user1": "yams",
  77. "pass1": "yams",
  78. }, nil, nil)
  79. // Send first request which creates a session
  80. res, resp = sendTestRequest(TESTQUERYURL, "GET", nil, resp.Cookies(), nil)
  81. if res != "Content - User session: yams" {
  82. t.Error("Unexpected result:", res)
  83. return
  84. }
  85. // Test access denied
  86. ca.SetAccessFunc(func(w http.ResponseWriter, r *http.Request, user string) bool {
  87. if strings.HasPrefix(r.URL.Path, "/foo/bar") {
  88. http.Error(w, "Page is restricted", http.StatusForbidden)
  89. return false
  90. }
  91. return true
  92. })
  93. res, resp = sendTestRequest(TESTQUERYURL+"/bar", "GET", nil, resp.Cookies(), nil)
  94. if res != "Page is restricted" {
  95. t.Error("Unexpected result:", res)
  96. return
  97. }
  98. // Check we have a valid session
  99. cookies := resp.Cookies()
  100. sessions, _ := user.UserSessionManager.Provider.GetAll()
  101. if len(sessions) != 1 {
  102. t.Error("Unexpected number of active sessions:", sessions)
  103. return
  104. }
  105. if user, ok := ca.CheckAuth(resp.Request); !ok || user != "yams" {
  106. t.Error("Unexpected result:", ok, user)
  107. return
  108. }
  109. var theSession user.Session
  110. for _, v := range sessions {
  111. theSession = v.(user.Session)
  112. break
  113. }
  114. var theAuth string
  115. for k := range ca.tokenMap.GetAll() {
  116. theAuth = k
  117. break
  118. }
  119. if len(cookies) != 2 ||
  120. cookies[0].Raw != fmt.Sprintf("~sid=%v; Path=/; Max-Age=%v; HttpOnly",
  121. theSession.ID(), CookieMaxLifetime) ||
  122. cookies[1].Raw != fmt.Sprintf("~aid=%v; Path=/; Max-Age=42; HttpOnly", theAuth) {
  123. t.Error("Unexpected cookie:", cookies)
  124. return
  125. }
  126. // Test session expiry
  127. user.UserSessionManager.Provider.Destroy(theSession.ID())
  128. res, _ = sendTestRequest(TESTQUERYURL, "GET", nil, cookies, nil)
  129. if res != "Session expired" {
  130. t.Error("Unexpected result:", res)
  131. return
  132. }
  133. // Test a logout
  134. _, resp2 := sendTestRequest(TESTQUERYURL+"/logout", "GET", nil, resp.Cookies(), nil)
  135. cookies = resp2.Cookies()
  136. if len(cookies) != 1 ||
  137. cookies[0].Raw != "~aid=; Path=/; Max-Age=0; HttpOnly" {
  138. t.Error("Unexpected cookie:", cookies)
  139. return
  140. }
  141. cookies = resp.Cookies()
  142. // The next request will no longer have access to a session
  143. res, resp = sendTestRequest(TESTQUERYURL, "GET", nil, cookies, nil)
  144. if res != "Unauthorized" {
  145. t.Error("Unexpected result:", res)
  146. return
  147. }
  148. cookies = resp.Cookies()
  149. if len(cookies) != 0 {
  150. t.Error("Unexpected cookie:", cookies)
  151. return
  152. }
  153. // Test error cases
  154. // Wrong credentials - error message depends on custom handler
  155. _, resp = sendTestRequest(TESTQUERYURL+"/login", "GET", map[string]string{
  156. "user1": "yams",
  157. "pass1": "yams1",
  158. }, nil, nil)
  159. cookies = resp.Cookies()
  160. if len(cookies) != 0 {
  161. t.Error("Unexpected cookie:", cookies)
  162. return
  163. }
  164. }