git » gofer » next » tree

[next] / server / auth_test.go

package server

import (
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"blitiri.com.ar/go/gofer/trace"
)

func TestAuthWrapper(t *testing.T) {
	const twoPassSHA = "f1a9cce4acb4460a32413e943554650d0e8916d18f3c41d85eb5bb8e4ee62249"
	a := &AuthWrapper{
		handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}),
		users: &AuthDB{
			Plain:  map[string]string{"oneuser": "onepass"},
			SHA256: map[string]string{"twouser": twoPassSHA},
		},
	}

	cases := []struct {
		user, pass string
		want       int
	}{
		{"oneuser", "onepass", http.StatusOK},
		{"oneuser", "onepasx", http.StatusUnauthorized},
		{"oneuser", "onepas", http.StatusUnauthorized},
		{"oneuser", "onepasss", http.StatusUnauthorized},
		{"oneuser", "", http.StatusUnauthorized},

		{"twouser", "twopass", http.StatusOK},
		{"twouser", "twopasx", http.StatusUnauthorized},
		{"twouser", "", http.StatusUnauthorized},
		// The stored hash is not a valid password.
		{"twouser", twoPassSHA, http.StatusUnauthorized},

		{"unkuser", "onepass", http.StatusUnauthorized},
	}
	for _, c := range cases {
		req := httptest.NewRequest("GET", "http://unused/", nil)
		req = req.WithContext(trace.NewContext(req.Context(), trace.New("test", "/")))
		req.SetBasicAuth(c.user, c.pass)
		w := httptest.NewRecorder()
		start := time.Now()
		a.ServeHTTP(w, req)
		if d := time.Since(start); d < authDuration {
			t.Errorf("%q:%q: took %v, want at least %v",
				c.user, c.pass, d, authDuration)
		}
		if w.Code != c.want {
			t.Errorf("%q:%q: status = %d, want %d",
				c.user, c.pass, w.Code, c.want)
		}
	}

	// No credentials at all.
	req := httptest.NewRequest("GET", "http://unused/", nil)
	req = req.WithContext(trace.NewContext(req.Context(), trace.New("test", "/")))
	w := httptest.NewRecorder()
	a.ServeHTTP(w, req)
	if w.Code != http.StatusUnauthorized {
		t.Errorf("no credentials: status = %d, want 401", w.Code)
	}
}