http_test.go 9.85 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5
package server

import (
	"context"
	"crypto/tls"
6
	"encoding/json"
ale's avatar
ale committed
7
	"errors"
8
	"io"
ale's avatar
ale committed
9 10 11 12 13 14 15 16 17 18 19
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"net/http/httptest"
	"net/url"
	"os"
	"regexp"
	"strings"
	"testing"

	"git.autistici.org/id/auth"
20
	"git.autistici.org/id/keystore"
ale's avatar
ale committed
21 22 23 24 25 26
)

type fakeAuthClient struct{}

func (c *fakeAuthClient) Authenticate(_ context.Context, req *auth.Request) (*auth.Response, error) {
	p := string(req.Password)
27
	info := &auth.UserInfo{Shard: "shard1"}
ale's avatar
ale committed
28 29
	switch {
	case req.Username == "testuser" && p == "password":
30
		return &auth.Response{Status: auth.StatusOK, UserInfo: info}, nil
ale's avatar
ale committed
31
	case req.Username == "test2fa" && p == "password" && req.OTP == "123456":
32
		return &auth.Response{Status: auth.StatusOK, UserInfo: info}, nil
ale's avatar
ale committed
33 34 35 36 37 38 39 40 41 42
	case req.Username == "test2fa" && p == "password":
		return &auth.Response{
			Status:    auth.StatusInsufficientCredentials,
			TFAMethod: auth.TFAMethodOTP,
		}, nil
	}

	return &auth.Response{Status: auth.StatusError}, nil
}

43
func createTestHTTPServer(t testing.TB, config *Config) *httptest.Server {
ale's avatar
ale committed
44 45 46 47 48 49 50 51 52 53
	svc, err := NewLoginService(config)
	if err != nil {
		t.Fatal("NewLoginService():", err)
	}

	srv, err := New(svc, &fakeAuthClient{}, config)
	if err != nil {
		t.Fatal("New():", err)
	}

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
	return httptest.NewTLSServer(srv.Handler())
}

func startTestHTTPServer(t testing.TB) (string, *httptest.Server) {
	tmpdir, _ := ioutil.TempDir("", "")
	config := testConfig(t, tmpdir, "")
	return tmpdir, createTestHTTPServer(t, config)
}

func startTestHTTPServerWithKeyStore(t testing.TB) (string, *httptest.Server) {
	ks := createFakeKeyStore(t, "testuser", "password")

	tmpdir, _ := ioutil.TempDir("", "")
	config := testConfig(t, tmpdir, ks.URL)
	return tmpdir, createTestHTTPServer(t, config)
ale's avatar
ale committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
}

func newTestHTTPClient() *http.Client {
	jar, _ := cookiejar.New(nil)
	transport := NewLoggedTransport(&http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}, DefaultLogger{Dump: true})
	return &http.Client{
		Jar:       jar,
		Transport: transport,
		// This client will only follow redirects to localhost.
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			if len(via) > 10 {
				return errors.New("too many redirects")
			}
			if !strings.HasPrefix(req.URL.Host, "127.0.0.1:") {
				return http.ErrUseLastResponse
			}
			return nil
		},
	}
}

func TestHTTP_ServeStaticAsset(t *testing.T) {
	tmpdir, httpSrv := startTestHTTPServer(t)
	defer os.RemoveAll(tmpdir)
	defer httpSrv.Close()

	c := newTestHTTPClient()
	resp, err := c.Get(httpSrv.URL + "/static/js/jquery-3.2.1.min.js")
	if err != nil {
		t.Fatal("http.Get():", err)
	}
	if resp.StatusCode != 200 {
		t.Fatalf("bad status: %s", resp.Status)
	}
}

func doGet(t testing.TB, srv *httptest.Server, c *http.Client, relativeURL string, checkResponse ...func(testing.TB, *http.Response)) {
	resp, err := c.Get(srv.URL + relativeURL)
	if err != nil {
		t.Fatalf("http.Get(%s): %v", relativeURL, err)
	}
	defer resp.Body.Close()
	for _, f := range checkResponse {
		f(t, resp)
	}
}

func doPostForm(t testing.TB, srv *httptest.Server, c *http.Client, relativeURL string, v url.Values, checkResponse ...func(testing.TB, *http.Response)) {
	resp, err := c.PostForm(srv.URL+relativeURL, v)
	if err != nil {
		t.Fatalf("http.Get(%s): %v", relativeURL, err)
	}
	defer resp.Body.Close()
	for _, f := range checkResponse {
		f(t, resp)
	}
}

func checkStatusOk(t testing.TB, resp *http.Response) {
	if resp.StatusCode != 200 {
		t.Fatalf("expected status 200, got %s", resp.Status)
	}
}

func checkRedirectToTargetService(t testing.TB, resp *http.Response) {
	if resp.StatusCode != 302 {
		t.Fatalf("expected status 302, got %s", resp.Status)
	}
	if !strings.HasPrefix(resp.Header.Get("Location"), "https://service.example.com/sso_login?") {
		t.Fatalf("redirect is not to target service: %v", resp.Header.Get("Location"))
	}
}

var usernameFieldRx = regexp.MustCompile(`<input[^>]*name="username"`)

func checkLoginPasswordPage(t testing.TB, resp *http.Response) {
	if resp.Request.URL.Path != "/login" {
		t.Errorf("request path is not /login (%s)", resp.Request.URL.String())
	}
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("reading body: %v", err)
	}
	if !usernameFieldRx.Match(data) {
		t.Fatalf("not the password login page:\n%s", string(data))
	}
}

var otpFieldRx = regexp.MustCompile(`<input[^>]*name="otp"`)

func checkLoginOTPPage(t testing.TB, resp *http.Response) {
	if resp.Request.URL.Path != "/login" {
		t.Errorf("request path is not /login (%s)", resp.Request.URL.String())
	}
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("reading body: %v", err)
	}
	if !otpFieldRx.Match(data) {
		t.Fatalf("not the OTP login page:\n%s", string(data))
	}
}

func TestHTTP_Login(t *testing.T) {
	tmpdir, httpSrv := startTestHTTPServer(t)
	defer os.RemoveAll(tmpdir)
	defer httpSrv.Close()

	c := newTestHTTPClient()

	// Simulate an authorization request from a service, expect to
	// see the login page.
	v := make(url.Values)
	v.Set("s", "service.example.com/")
	v.Set("d", "https://service.example.com/admin/")
	v.Set("n", "averysecretnonce")
	doGet(t, httpSrv, c, "/?"+v.Encode(), checkStatusOk, checkLoginPasswordPage)

	// Attempt to login by submitting the form. We expect the
	// result to be a 302 redirect to the target service.
	v = make(url.Values)
	v.Set("username", "testuser")
	v.Set("password", "password")
	doPostForm(t, httpSrv, c, "/login", v, checkRedirectToTargetService)
}

ale's avatar
ale committed
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
func TestHTTP_LoginOnSecondAttempt(t *testing.T) {
	tmpdir, httpSrv := startTestHTTPServer(t)
	defer os.RemoveAll(tmpdir)
	defer httpSrv.Close()

	c := newTestHTTPClient()

	// Simulate an authorization request from a service, expect to
	// see the login page.
	v := make(url.Values)
	v.Set("s", "service.example.com/")
	v.Set("d", "https://service.example.com/admin/")
	v.Set("n", "averysecretnonce")
	doGet(t, httpSrv, c, "/?"+v.Encode(), checkStatusOk, checkLoginPasswordPage)

	// Attempt to login with wrong credentials.
	v = make(url.Values)
	v.Set("username", "testuser")
	v.Set("password", "badpassword")
	doPostForm(t, httpSrv, c, "/login", v, checkStatusOk, checkLoginPasswordPage)

	// Attempt to login by submitting the form. We expect the
	// result to be a 302 redirect to the target service.
	v = make(url.Values)
	v.Set("username", "testuser")
	v.Set("password", "password")
	doPostForm(t, httpSrv, c, "/login", v, checkRedirectToTargetService)
}

func TestHTTP_LoginAndLogout(t *testing.T) {
	tmpdir, httpSrv := startTestHTTPServer(t)
	defer os.RemoveAll(tmpdir)
	defer httpSrv.Close()

	c := newTestHTTPClient()

	// Simulate an authorization request from a service, expect to
	// see the login page.
	v := make(url.Values)
	v.Set("s", "service.example.com/")
	v.Set("d", "https://service.example.com/admin/")
	v.Set("n", "averysecretnonce")
	doGet(t, httpSrv, c, "/?"+v.Encode(), checkStatusOk, checkLoginPasswordPage)

	// Attempt to login by submitting the form. We expect the
	// result to be a 302 redirect to the target service.
	v = make(url.Values)
	v.Set("username", "testuser")
	v.Set("password", "password")
	doPostForm(t, httpSrv, c, "/login", v, checkRedirectToTargetService)

	// Make a logout request.
	doGet(t, httpSrv, c, "/logout", checkStatusOk)
	doPostForm(t, httpSrv, c, "/logout", nil, checkStatusOk)

	// This new authorization request should send us to the login page.
	v = make(url.Values)
	v.Set("s", "service.example.com/")
	v.Set("d", "https://service.example.com/admin/")
	v.Set("n", "averysecretnonce")
	doGet(t, httpSrv, c, "/?"+v.Encode(), checkStatusOk, checkLoginPasswordPage)
}

ale's avatar
ale committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
func TestHTTP_LoginOTP(t *testing.T) {
	tmpdir, httpSrv := startTestHTTPServer(t)
	defer os.RemoveAll(tmpdir)
	defer httpSrv.Close()

	c := newTestHTTPClient()

	// Simulate an authorization request from a service, expect to
	// see the login page.
	v := make(url.Values)
	v.Set("s", "service.example.com/")
	v.Set("d", "https://service.example.com/admin/")
	v.Set("n", "averysecretnonce")
	doGet(t, httpSrv, c, "/?"+v.Encode(), checkStatusOk, checkLoginPasswordPage)

	// Attempt to login by submitting the form. We should see the OTP page.
	v = make(url.Values)
	v.Set("username", "test2fa")
	v.Set("password", "password")
	doPostForm(t, httpSrv, c, "/login", v, checkStatusOk, checkLoginOTPPage)

	// Submit the correct OTP token. We expect the result to be a
	// 302 redirect to the target service.
	v = make(url.Values)
	v.Set("otp", "123456")
	doPostForm(t, httpSrv, c, "/login", v, checkRedirectToTargetService)
}
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

func createFakeKeyStore(t testing.TB, username, password string) *httptest.Server {
	h := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.URL.Path != "/api/open" {
			http.NotFound(w, req)
			return
		}
		var openReq keystore.OpenRequest
		if err := json.NewDecoder(req.Body).Decode(&openReq); err != nil {
			t.Errorf("bad JSON body: %v", err)
			return
		}
		if openReq.Username != username {
			t.Errorf("bad username in keystore Open request: expected %s, got %s", username, openReq.Username)
		}
		if openReq.Password != password {
			t.Errorf("bad password in keystore Open request: expected %s, got %s", password, openReq.Password)
		}
		w.Header().Set("Content-Type", "application/json")
		io.WriteString(w, "{}")
	})
	return httptest.NewServer(h)
}

func TestHTTP_LoginWithKeyStore(t *testing.T) {
	tmpdir, httpSrv := startTestHTTPServerWithKeyStore(t)
	defer os.RemoveAll(tmpdir)
	defer httpSrv.Close()

	c := newTestHTTPClient()

	// Simulate an authorization request from a service, expect to
	// see the login page.
	v := make(url.Values)
	v.Set("s", "service.example.com/")
	v.Set("d", "https://service.example.com/admin/")
	v.Set("n", "averysecretnonce")
	doGet(t, httpSrv, c, "/?"+v.Encode(), checkStatusOk, checkLoginPasswordPage)

	// Attempt to login by submitting the form. We expect the
	// result to be a 302 redirect to the target service.
	v = make(url.Values)
	v.Set("username", "testuser")
	v.Set("password", "password")
	doPostForm(t, httpSrv, c, "/login", v, checkRedirectToTargetService)
}