token_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package token
  2. import (
  3. "net/http"
  4. "net/url"
  5. "testing"
  6. )
  7. func TestHandleRedirects_AttachOrgToken(t *testing.T) {
  8. req, _ := http.NewRequest("GET", "http://example.com/cdn-cgi/access/login", nil)
  9. via := []*http.Request{}
  10. orgToken := "orgTokenValue"
  11. handleRedirects(req, via, orgToken)
  12. // Check if the orgToken cookie is attached
  13. cookies := req.Cookies()
  14. found := false
  15. for _, cookie := range cookies {
  16. if cookie.Name == tokenCookie && cookie.Value == orgToken {
  17. found = true
  18. break
  19. }
  20. }
  21. if !found {
  22. t.Errorf("OrgToken cookie not attached to the request.")
  23. }
  24. }
  25. func TestHandleRedirects_AttachAppSessionCookie(t *testing.T) {
  26. req, _ := http.NewRequest("GET", "http://example.com/cdn-cgi/access/authorized", nil)
  27. via := []*http.Request{
  28. {
  29. URL: &url.URL{Path: "/cdn-cgi/access/login"},
  30. Response: &http.Response{
  31. Header: http.Header{"Set-Cookie": {"CF_AppSession=appSessionValue"}},
  32. },
  33. },
  34. }
  35. orgToken := "orgTokenValue"
  36. err := handleRedirects(req, via, orgToken)
  37. // Check if the appSessionCookie is attached to the request
  38. cookies := req.Cookies()
  39. found := false
  40. for _, cookie := range cookies {
  41. if cookie.Name == appSessionCookie && cookie.Value == "appSessionValue" {
  42. found = true
  43. break
  44. }
  45. }
  46. if !found {
  47. t.Errorf("AppSessionCookie not attached to the request.")
  48. }
  49. if err != nil {
  50. t.Errorf("Expected no error, got %v", err)
  51. }
  52. }
  53. func TestHandleRedirects_StopAtAuthorizedEndpoint(t *testing.T) {
  54. req, _ := http.NewRequest("GET", "http://example.com/cdn-cgi/access/authorized", nil)
  55. via := []*http.Request{
  56. {
  57. URL: &url.URL{Path: "other"},
  58. },
  59. {
  60. URL: &url.URL{Path: AccessAuthorizedWorkerPath},
  61. },
  62. }
  63. orgToken := "orgTokenValue"
  64. err := handleRedirects(req, via, orgToken)
  65. // Check if ErrUseLastResponse is returned
  66. if err != http.ErrUseLastResponse {
  67. t.Errorf("Expected ErrUseLastResponse, got %v", err)
  68. }
  69. }