2 Commits

Author SHA1 Message Date
Thom Seddon
320e128a6e Add failing test showing issue 2020-04-14 08:56:03 +01:00
Thom Seddon
3e6ccc8f45 Redirect to login on cookie expiry + simplify ValidateCookie function
Possible fix for #31
2019-06-13 15:13:52 +01:00
6 changed files with 123 additions and 48 deletions

1
go.sum
View File

@@ -55,6 +55,7 @@ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoH
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
github.com/thomseddon/go-flags v1.4.0 h1:cHj56pbnQxlGo2lx2P8f0Dph4TRYKBJzoPuF2lqNvW4=
github.com/thomseddon/go-flags v1.4.0/go.mod h1:NK9eZpNBmSKVxvyB/MExg6jW0Bo9hQyAuCP+b8MJFow=
github.com/thomseddon/go-flags v1.4.1-0.20190507181358-ce437f05b7fb h1:L311/fJ7WXmFDDtuhf22PkVJqZpqLbEsmGSTEGv7ZQY=

View File

@@ -18,41 +18,41 @@ import (
// Request Validation
// Cookie = hash(secret, cookie domain, email, expires)|expires|email
func ValidateCookie(r *http.Request, c *http.Cookie) (bool, string, error) {
func ValidateCookie(r *http.Request, c *http.Cookie) (string, error) {
parts := strings.Split(c.Value, "|")
if len(parts) != 3 {
return false, "", errors.New("Invalid cookie format")
return "", errors.New("Invalid cookie format")
}
mac, err := base64.URLEncoding.DecodeString(parts[0])
if err != nil {
return false, "", errors.New("Unable to decode cookie mac")
return "", errors.New("Unable to decode cookie mac")
}
expectedSignature := cookieSignature(r, parts[2], parts[1])
expected, err := base64.URLEncoding.DecodeString(expectedSignature)
if err != nil {
return false, "", errors.New("Unable to generate mac")
return "", errors.New("Unable to generate mac")
}
// Valid token?
if !hmac.Equal(mac, expected) {
return false, "", errors.New("Invalid cookie mac")
return "", errors.New("Invalid cookie mac")
}
expires, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil {
return false, "", errors.New("Unable to parse cookie expiry")
return "", errors.New("Unable to parse cookie expiry")
}
// Has it expired?
if time.Unix(expires, 0).Before(time.Now()) {
return false, "", errors.New("Cookie has expired")
return "", errors.New("Cookie has expired")
}
// Looks valid
return true, parts[2], nil
return parts[2], nil
}
// Validate email

View File

@@ -24,28 +24,24 @@ func TestAuthValidateCookie(t *testing.T) {
// Should require 3 parts
c.Value = ""
valid, _, err := ValidateCookie(r, c)
assert.False(valid)
_, err := ValidateCookie(r, c)
if assert.Error(err) {
assert.Equal("Invalid cookie format", err.Error())
}
c.Value = "1|2"
valid, _, err = ValidateCookie(r, c)
assert.False(valid)
_, err = ValidateCookie(r, c)
if assert.Error(err) {
assert.Equal("Invalid cookie format", err.Error())
}
c.Value = "1|2|3|4"
valid, _, err = ValidateCookie(r, c)
assert.False(valid)
_, err = ValidateCookie(r, c)
if assert.Error(err) {
assert.Equal("Invalid cookie format", err.Error())
}
// Should catch invalid mac
c.Value = "MQ==|2|3"
valid, _, err = ValidateCookie(r, c)
assert.False(valid)
_, err = ValidateCookie(r, c)
if assert.Error(err) {
assert.Equal("Invalid cookie mac", err.Error())
}
@@ -53,8 +49,7 @@ func TestAuthValidateCookie(t *testing.T) {
// Should catch expired
config.Lifetime = time.Second * time.Duration(-1)
c = MakeCookie(r, "test@test.com")
valid, _, err = ValidateCookie(r, c)
assert.False(valid)
_, err = ValidateCookie(r, c)
if assert.Error(err) {
assert.Equal("Cookie has expired", err.Error())
}
@@ -62,8 +57,7 @@ func TestAuthValidateCookie(t *testing.T) {
// Should accept valid cookie
config.Lifetime = time.Second * time.Duration(10)
c = MakeCookie(r, "test@test.com")
valid, email, err := ValidateCookie(r, c)
assert.True(valid, "valid request should return valid")
email, err := ValidateCookie(r, c)
assert.Nil(err, "valid request should not return an error")
assert.Equal("test@test.com", email, "valid request should return user email")
}
@@ -244,8 +238,8 @@ func TestAuthMakeCookie(t *testing.T) {
assert.Equal("_forward_auth", c.Name)
parts := strings.Split(c.Value, "|")
assert.Len(parts, 3, "cookie should be 3 parts")
valid, _, _ := ValidateCookie(r, c)
assert.True(valid, "should generate valid cookie")
_, err := ValidateCookie(r, c)
assert.Nil(err, "should generate valid cookie")
assert.Equal("/", c.Path)
assert.Equal("app.example.com", c.Domain)
assert.True(c.Secure)

View File

@@ -237,7 +237,7 @@ func TestConfigParseEnvironmentBackwardsCompatability(t *testing.T) {
"COOKIE_SECURE": "false",
"COOKIE_DOMAINS": "test1.com,example.org",
"COOKIE_DOMAIN": "another1.net",
"DOMAIN": "test2.com,example.org",
"DOMAIN": "test2.com,example.org",
"WHITELIST": "test3.com,example.org",
}
for k, v := range vars {

View File

@@ -72,35 +72,25 @@ func (s *Server) AuthHandler(rule string) http.HandlerFunc {
// Get auth cookie
c, err := r.Cookie(config.CookieName)
if err != nil {
// Error indicates no cookie, generate nonce
err, nonce := Nonce()
if err != nil {
logger.Errorf("Error generating nonce, %v", err)
http.Error(w, "Service unavailable", 503)
return
}
// Set the CSRF cookie
http.SetCookie(w, MakeCSRFCookie(r, nonce))
logger.Debug("Set CSRF cookie and redirecting to google login")
// Forward them on
http.Redirect(w, r, GetLoginURL(r, nonce), http.StatusTemporaryRedirect)
logger.Debug("Done")
s.authRedirect(logger, w, r)
return
}
// Validate cookie
valid, email, err := ValidateCookie(r, c)
if !valid {
logger.Errorf("Invalid cookie: %v", err)
http.Error(w, "Not authorized", 401)
email, err := ValidateCookie(r, c)
if err != nil {
if err.Error() == "Cookie has expired" {
logger.Info("Cookie has expired")
s.authRedirect(logger, w, r)
} else {
logger.Errorf("Invalid cookie: %v", err)
http.Error(w, "Not authorized", 401)
}
return
}
// Validate user
valid = ValidateEmail(email)
valid := ValidateEmail(email)
if !valid {
logger.WithFields(logrus.Fields{
"email": email,
@@ -167,6 +157,26 @@ func (s *Server) AuthCallbackHandler() http.HandlerFunc {
}
}
func (s *Server) authRedirect(logger *logrus.Entry, w http.ResponseWriter, r *http.Request) {
// Error indicates no cookie, generate nonce
err, nonce := Nonce()
if err != nil {
logger.Errorf("Error generating nonce, %v", err)
http.Error(w, "Service unavailable", 503)
return
}
// Set the CSRF cookie
http.SetCookie(w, MakeCSRFCookie(r, nonce))
logger.Debug("Set CSRF cookie and redirecting to google login")
// Forward them on
http.Redirect(w, r, GetLoginURL(r, nonce), http.StatusTemporaryRedirect)
logger.Debug("Done")
return
}
func (s *Server) logger(r *http.Request, rule, msg string) *logrus.Entry {
// Create logger
logger := log.WithFields(logrus.Fields{

View File

@@ -8,8 +8,10 @@ import (
"net/url"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TODO:
@@ -27,7 +29,7 @@ func init() {
* Tests
*/
func TestServerAuthHandler(t *testing.T) {
func TestServerAuthHandlerInvalid(t *testing.T) {
assert := assert.New(t)
config, _ = NewConfig([]string{})
@@ -57,13 +59,46 @@ func TestServerAuthHandler(t *testing.T) {
res, _ = doHttpRequest(req, c)
assert.Equal(401, res.StatusCode, "invalid email should not be authorised")
}
func TestServerAuthHandlerExpired(t *testing.T) {
assert := assert.New(t)
config, _ = NewConfig([]string{})
config.Lifetime = time.Second * time.Duration(-1)
config.Domains = []string{"test.com"}
// Should redirect expired cookie
req := newDefaultHttpRequest("/foo")
c := MakeCookie(req, "test@example.com")
res, _ := doHttpRequest(req, c)
assert.Equal(307, res.StatusCode, "request with expired cookie should be redirected")
// Check for CSRF cookie
var cookie *http.Cookie
for _, c := range res.Cookies() {
if c.Name == config.CSRFCookieName {
cookie = c
}
}
assert.NotNil(cookie)
// Check redirection location
fwd, _ := res.Location()
assert.Equal("https", fwd.Scheme, "request with expired cookie should be redirected to google")
assert.Equal("accounts.google.com", fwd.Host, "request with expired cookie should be redirected to google")
assert.Equal("/o/oauth2/auth", fwd.Path, "request with expired cookie should be redirected to google")
}
func TestServerAuthHandlerValid(t *testing.T) {
assert := assert.New(t)
config, _ = NewConfig([]string{})
// Should allow valid request email
req = newDefaultHttpRequest("/foo")
c = MakeCookie(req, "test@example.com")
req := newDefaultHttpRequest("/foo")
c := MakeCookie(req, "test@example.com")
config.Domains = []string{}
res, _ = doHttpRequest(req, c)
res, _ := doHttpRequest(req, c)
assert.Equal(200, res.StatusCode, "valid request should be allowed")
// Should pass through user
@@ -266,6 +301,41 @@ func TestServerRouteQuery(t *testing.T) {
assert.Equal(200, res.StatusCode, "request matching allow rule should be allowed")
}
func TestServerAuthCallbackWithRules(t *testing.T) {
assert := assert.New(t)
config, _ = NewConfig([]string{})
config.Rules = map[string]*Rule{
"1": {
Action: "auth",
Rule: "Host(`example.com`) && Path(`/private`)",
},
"2": {
Action: "allow",
Rule: "Host(`example.com`)",
},
}
// Should allow /test request
req := newHttpRequest("GET", "https://example.com/", "/test")
res, _ := doHttpRequest(req, nil)
assert.Equal(200, res.StatusCode, "request matching allow rule should be allowed")
// Should block /private request
req = newHttpRequest("GET", "https://example.com/", "/private")
res, _ = doHttpRequest(req, nil)
assert.Equal(307, res.StatusCode, "request matching auth rule should require auth")
// Should allow callback request
req = newHttpRequest("GET", "https://example.com/", "/_oauth?state=12345678901234567890123456789012:https://example.com/private")
c := MakeCSRFCookie(req, "12345678901234567890123456789012")
res, _ = doHttpRequest(req, c)
require.Equal(t, 307, res.StatusCode, "callback request should be redirected")
fwd, _ := res.Location()
assert.Equal("http", fwd.Scheme, "callback request should be correctly redirected")
assert.Equal("example.com", fwd.Host, "callback request should be correctly redirected")
assert.Equal("/private", fwd.Path, "callback request should be correctly redirected")
}
/**
* Utilities
*/