| 22 | ) |
| 23 | |
| 24 | func TestCallbackHandlerDocumentRoot(t *testing.T) { |
| 25 | handlerL := http.HandlerFunc(LoginHandler) |
| 26 | handlerA := http.HandlerFunc(CallbackHandler) |
| 27 | |
| 28 | tests := []struct { |
| 29 | name string |
| 30 | configFile string |
| 31 | wantcode int |
| 32 | }{ |
| 33 | {"should have URL that begins with DocumentRoot", "/config/testing/handler_login_url_document_root.yml", http.StatusFound}, |
| 34 | {"should have URL that does not begin with DocumentRoot", "/config/testing/handler_login_url.yml", http.StatusFound}, |
| 35 | } |
| 36 | |
| 37 | for _, tt := range tests { |
| 38 | t.Run(tt.name, func(t *testing.T) { |
| 39 | setUp(tt.configFile) |
| 40 | |
| 41 | // first make a request of /login to set the session cookie |
| 42 | reqLogin, err := http.NewRequest("GET", cfg.Cfg.DocumentRoot+"/login?url=http://myapp.example.com/logout", nil) |
| 43 | reqLogin.Header.Set("Host", "my.example.com") |
| 44 | if err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | rrL := httptest.NewRecorder() |
| 48 | handlerL.ServeHTTP(rrL, reqLogin) |
| 49 | |
| 50 | // grab the state from the session cookie to |
| 51 | session, err := sessstore.Get(reqLogin, cfg.Cfg.Session.Name) |
| 52 | state := session.Values["state"].(string) |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | |
| 57 | // now mimic an IdP returning the state variable back to us |
| 58 | reqAuth, err := http.NewRequest("GET", cfg.Cfg.DocumentRoot+"/auth?state="+state, nil) |
| 59 | reqAuth.Header.Set("Host", "my.example.com") |
| 60 | if err != nil { |
| 61 | t.Fatal(err) |
| 62 | } |
| 63 | // transfer the cookie from rrL to reqAuth |
| 64 | rrA := httptest.NewRecorder() |
| 65 | |
| 66 | handlerA.ServeHTTP(rrA, reqAuth) |
| 67 | if rrA.Code != tt.wantcode { |
| 68 | t.Errorf("LoginHandler() status = %v, want %v", rrA.Code, tt.wantcode) |
| 69 | } |
| 70 | |
| 71 | // confirm the requst to $DocumentRoot/auth is redirected to $DocumentRoot/auth/$state |
| 72 | redirectURL, err := url.Parse(rrA.Header()["Location"][0]) |
| 73 | if err != nil { |
| 74 | t.Fatal(err) |
| 75 | } |
| 76 | assert.Equal(t, fmt.Sprintf("%s/auth/%s/", cfg.Cfg.DocumentRoot, state), redirectURL.Path) |
| 77 | |
| 78 | }) |
| 79 | } |
| 80 | } |
| 81 | |