internal/sessions: make user state domain scoped

internal/sessions: session state is domain scoped
internal/sessions: infer csrf cookie, route scoped
proxy & authenticate: use shared cookie name
proxy & authenticate: prevent resaving unchanged session
proxy & authenticate: redirect instead of error for no session on login
internal/config: merge cookies
proxy: remove favicon specific route
proxy: use mock server for tests
proxy: add tests for failures
This commit is contained in:
Bobby DeSimone 2019-05-20 19:22:22 -07:00
parent 2eb2eb0620
commit 3eff6cce13
No known key found for this signature in database
GPG key ID: AEE4CF12FE86D07E
12 changed files with 231 additions and 348 deletions

View file

@ -2,7 +2,6 @@ package proxy // import "github.com/pomerium/pomerium/proxy"
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
@ -18,11 +17,6 @@ import (
"github.com/pomerium/pomerium/internal/sessions"
)
var (
// ErrUserNotAuthorized is set when user is not authorized to access a resource.
ErrUserNotAuthorized = errors.New("user not authorized")
)
// StateParameter holds the redirect id along with the session id.
type StateParameter struct {
SessionID string `json:"session_id"`
@ -38,7 +32,6 @@ func (p *Proxy) Handler() http.Handler {
return ok
}))
mux := http.NewServeMux()
mux.HandleFunc("/favicon.ico", p.Favicon)
mux.HandleFunc("/robots.txt", p.RobotsTxt)
mux.HandleFunc("/.pomerium/sign_out", p.SignOut)
mux.HandleFunc("/.pomerium/callback", p.OAuthCallback)
@ -53,21 +46,10 @@ func (p *Proxy) RobotsTxt(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "User-agent: *\nDisallow: /")
}
// Favicon will proxy the request as usual if the user is already authenticated but responds
// with a 404 otherwise, to avoid spurious and confusing authenticate attempts when a browser
// automatically requests the favicon on an error page.
func (p *Proxy) Favicon(w http.ResponseWriter, r *http.Request) {
err := p.Authenticate(w, r)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
p.Proxy(w, r)
}
// SignOut redirects the request to the sign out url.
// SignOut redirects the request to the sign out url. It's the responsibility
// of the authenticate service to revoke the remote session and clear
// the local session state.
func (p *Proxy) SignOut(w http.ResponseWriter, r *http.Request) {
p.sessionStore.ClearSession(w, r)
redirectURL := &url.URL{
Scheme: "https",
Host: r.Host,
@ -198,7 +180,6 @@ func (p *Proxy) OAuthCallback(w http.ResponseWriter, r *http.Request) {
// Conditions should be few in number and have strong justifications.
func (p *Proxy) shouldSkipAuthentication(r *http.Request) bool {
pol, foundPolicy := p.policy(r)
if isCORSPreflight(r) && foundPolicy && pol.CORSAllowPreflight {
log.FromRequest(r).Debug().Msg("proxy: skipping authentication for valid CORS preflight request")
return true
@ -221,13 +202,12 @@ func isCORSPreflight(r *http.Request) bool {
// or starting the authenticate service for validation if not.
func (p *Proxy) Proxy(w http.ResponseWriter, r *http.Request) {
if !p.shouldSkipAuthentication(r) {
err := p.Authenticate(w, r)
// If the authenticate is not successful we proceed to start the OAuth Flow with
// OAuthStart. If successful, we proceed to proxy to the configured upstream.
session, err := p.sessionStore.LoadSession(r)
if err != nil {
switch err {
case http.ErrNoCookie, sessions.ErrLifetimeExpired, sessions.ErrInvalidSession:
log.FromRequest(r).Debug().Err(err).Msg("proxy: starting auth flow")
log.FromRequest(r).Debug().Err(err).Msg("proxy: invalid session")
p.sessionStore.ClearSession(w, r)
p.OAuthStart(w, r)
return
default:
@ -236,18 +216,24 @@ func (p *Proxy) Proxy(w http.ResponseWriter, r *http.Request) {
return
}
}
// remove dupe session call
session, err := p.sessionStore.LoadSession(r)
err = p.authenticate(w, r, session)
if err != nil {
p.sessionStore.ClearSession(w, r)
log.Debug().Err(err).Msg("proxy: user unauthenticated")
httputil.ErrorResponse(w, r, "User unauthenticated", http.StatusForbidden)
return
}
authorized, err := p.AuthorizeClient.Authorize(r.Context(), r.Host, session)
if !authorized || err != nil {
if err != nil || !authorized {
log.FromRequest(r).Warn().Err(err).Msg("proxy: user unauthorized")
httputil.ErrorResponse(w, r, "Access unauthorized", http.StatusForbidden)
return
}
// append
r.Header.Set(HeaderUserID, session.User)
r.Header.Set(HeaderEmail, session.Email)
r.Header.Set(HeaderGroups, strings.Join(session.Groups, ","))
}
// We have validated the users request and now proxy their request to the provided upstream.
@ -289,35 +275,22 @@ func (p *Proxy) Proxy(w http.ResponseWriter, r *http.Request) {
// Authenticate authenticates a request by checking for a session cookie, and validating its expiration,
// clearing the session cookie if it's invalid and returning an error if necessary..
func (p *Proxy) Authenticate(w http.ResponseWriter, r *http.Request) (err error) {
session, err := p.sessionStore.LoadSession(r)
if err != nil {
p.sessionStore.ClearSession(w, r)
return err
}
func (p *Proxy) authenticate(w http.ResponseWriter, r *http.Request, session *sessions.SessionState) error {
if session.RefreshPeriodExpired() {
// AccessToken's usually expire after 60 or so minutes. If offline_access scope is set, a
// refresh token (which doesn't change) can be used to request a new access-token. If access
// is revoked by identity provider, or no refresh token is set, request will return an error
session, err = p.AuthenticateClient.Refresh(r.Context(), session)
session, err := p.AuthenticateClient.Refresh(r.Context(), session)
if err != nil {
p.sessionStore.ClearSession(w, r)
log.FromRequest(r).Warn().Err(err).Msg("proxy: refresh failed")
return err
return fmt.Errorf("proxy: session refresh failed : %v", err)
}
err = p.sessionStore.SaveSession(w, r, session)
if err != nil {
return fmt.Errorf("proxy: refresh failed : %v", err)
}
} else {
valid, err := p.AuthenticateClient.Validate(r.Context(), session.IDToken)
if err != nil || !valid {
return fmt.Errorf("proxy: session valid: %v : %v", valid, err)
}
}
err = p.sessionStore.SaveSession(w, r, session)
if err != nil {
p.sessionStore.ClearSession(w, r)
return err
}
// pass user & user-email details to client applications
r.Header.Set(HeaderUserID, session.User)
r.Header.Set(HeaderEmail, session.Email)
r.Header.Set(HeaderGroups, strings.Join(session.Groups, ","))
// This user has been OK'd. Allow the request!
return nil
}

View file

@ -147,19 +147,6 @@ func TestProxy_GetSignInURL(t *testing.T) {
}
}
func TestProxy_Favicon(t *testing.T) {
proxy, err := New(testOptions())
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("GET", "/favicon.ico", nil)
rr := httptest.NewRecorder()
proxy.Favicon(rr, req)
if status := rr.Code; status != http.StatusNotFound {
t.Errorf("handler returned wrong status code: got %v want %v", status, http.StatusNotFound)
}
}
func TestProxy_Signout(t *testing.T) {
proxy, err := New(testOptions())
if err != nil {
@ -349,14 +336,16 @@ func TestProxy_Proxy(t *testing.T) {
RefreshDeadline: time.Now().Add(10 * time.Second),
}
opts := testOptions()
optsCORS := testOptionsWithCORS()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "RVSI FILIVS CAISAR")
}))
defer ts.Close()
opts := testOptionsTestServer(ts.URL)
optsCORS := testOptionsWithCORS(ts.URL)
defaultHeaders, goodCORSHeaders, badCORSHeaders := http.Header{}, http.Header{}, http.Header{}
goodCORSHeaders.Set("origin", "anything")
goodCORSHeaders.Set("access-control-request-method", "anything")
// missing "Origin"
badCORSHeaders.Set("access-control-request-method", "anything")
@ -372,16 +361,22 @@ func TestProxy_Proxy(t *testing.T) {
wantStatus int
}{
// weirdly, we want 503 here because that means proxy is trying to route a domain (example.com) that we dont control. Weird. I know.
{"good", opts, http.MethodGet, defaultHeaders, "https://corp.example.notatld/test", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusBadGateway},
{"good cors preflight", optsCORS, http.MethodOptions, goodCORSHeaders, "https://corp.example.notatld/test", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusForbidden},
{"good", opts, http.MethodGet, defaultHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusOK},
{"good cors preflight", optsCORS, http.MethodOptions, goodCORSHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusOK},
// same request as above, but with cors_allow_preflight=false in the policy
{"valid cors, but not allowed", opts, http.MethodOptions, goodCORSHeaders, "https://corp.example.com/test", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusForbidden},
{"valid cors, but not allowed", opts, http.MethodOptions, goodCORSHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusForbidden},
// cors allowed, but the request is missing proper headers
{"invalid cors headers", optsCORS, http.MethodOptions, badCORSHeaders, "https://corp.example.com/test", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusForbidden},
{"unexpected error", opts, http.MethodGet, defaultHeaders, "https://corp.example.com/test", &sessions.MockSessionStore{LoadError: errors.New("ok")}, clients.MockAuthenticate{}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusInternalServerError},
{"invalid cors headers", optsCORS, http.MethodOptions, badCORSHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusForbidden},
{"unexpected error", opts, http.MethodGet, defaultHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{LoadError: errors.New("ok")}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusInternalServerError},
// redirect to start auth process
{"unknown host", opts, http.MethodGet, defaultHeaders, "https://notcorp.example.com/test", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusNotFound},
{"user forbidden", opts, http.MethodGet, defaultHeaders, "https://notcorp.example.com/test", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusForbidden},
{"unknown host", opts, http.MethodGet, defaultHeaders, "https://nothttpbin.corp.example", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusNotFound},
{"user forbidden", opts, http.MethodGet, defaultHeaders, "https://nothttpbin.corp.example", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: false}, http.StatusForbidden},
// authenticate errors
{"no session error", opts, http.MethodGet, defaultHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{LoadError: http.ErrNoCookie, Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusFound},
{"weird load session error", opts, http.MethodGet, defaultHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{LoadError: errors.New("weird"), Session: goodSession}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusInternalServerError},
{"failed refreshed session", opts, http.MethodGet, defaultHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{Session: &sessions.SessionState{RefreshDeadline: time.Now().Add(-10 * time.Second)}}, clients.MockAuthenticate{RefreshError: errors.New("refresh error")}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusForbidden},
{"cannot resave refreshed session", opts, http.MethodGet, defaultHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{SaveError: errors.New("weird"), Session: &sessions.SessionState{RefreshDeadline: time.Now().Add(-10 * time.Second)}}, clients.MockAuthenticate{ValidateResponse: true}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusForbidden},
{"authenticate validation error", opts, http.MethodGet, defaultHeaders, "https://httpbin.corp.example", &sessions.MockSessionStore{Session: goodSession}, clients.MockAuthenticate{ValidateResponse: false}, clients.MockAuthorize{AuthorizeResponse: true}, http.StatusForbidden},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@ -399,138 +394,13 @@ func TestProxy_Proxy(t *testing.T) {
w := httptest.NewRecorder()
p.Proxy(w, r)
if status := w.Code; status != tt.wantStatus {
t.Errorf("handler returned wrong status code: got %v want %v \n body %s", status, tt.wantStatus, w.Body.String())
t.Errorf("handler returned wrong status code: got %v want %v", status, tt.wantStatus)
t.Errorf("\n%+v", w.Body.String())
t.Errorf("\n%+v", opts)
t.Errorf("\n%+v", ts.URL)
}
})
}
}
func TestProxy_Authenticate(t *testing.T) {
configBlob := `[{"from":"corp.example.com","to":"example.com"}]` //valid yaml
policy := base64.URLEncoding.EncodeToString([]byte(configBlob))
goodSession := &sessions.SessionState{
User: "user",
Email: "email@email.com",
Groups: []string{"group1"},
AccessToken: "AccessToken",
RefreshToken: "RefreshToken",
LifetimeDeadline: time.Now().Add(10 * time.Second),
RefreshDeadline: time.Now().Add(10 * time.Second),
}
testAuth := clients.MockAuthenticate{
RedeemResponse: goodSession,
}
tests := []struct {
name string
host string
mux string
session sessions.SessionStore
authenticator clients.Authenticator
wantErr bool
}{
{"cannot save session",
"https://corp.example.com/",
policy,
&sessions.MockSessionStore{Session: &sessions.SessionState{
User: "user",
Email: "email@email.com",
Groups: []string{"group1"},
AccessToken: "AccessToken",
RefreshToken: "RefreshToken",
LifetimeDeadline: time.Now().Add(10 * time.Second),
RefreshDeadline: time.Now().Add(10 * time.Second),
}, SaveError: errors.New("error")},
testAuth, true},
{"cannot load session",
"https://corp.example.com/",
policy,
&sessions.MockSessionStore{LoadError: errors.New("error")}, testAuth, true},
{"expired session",
"https://corp.example.com/",
policy,
&sessions.MockSessionStore{
Session: &sessions.SessionState{
User: "user",
Email: "email@email.com",
Groups: []string{"group1"},
AccessToken: "AccessToken",
RefreshToken: "RefreshToken",
LifetimeDeadline: time.Now().Add(10 * time.Second),
RefreshDeadline: time.Now().Add(-10 * time.Second),
}},
clients.MockAuthenticate{
RefreshError: errors.New("error"),
RefreshResponse: &sessions.SessionState{
User: "user",
Email: "email@email.com",
Groups: []string{"group1"},
AccessToken: "AccessToken",
RefreshToken: "RefreshToken",
LifetimeDeadline: time.Now().Add(10 * time.Second),
RefreshDeadline: time.Now().Add(-10 * time.Second),
}}, true},
{"bad refresh authenticator",
"https://corp.example.com/",
policy,
&sessions.MockSessionStore{
Session: &sessions.SessionState{
User: "user",
Email: "email@email.com",
Groups: []string{"group1"},
AccessToken: "AccessToken",
RefreshToken: "RefreshToken",
LifetimeDeadline: time.Now().Add(10 * time.Second),
RefreshDeadline: time.Now().Add(-10 * time.Second),
},
},
clients.MockAuthenticate{
RefreshError: errors.New("error"),
RefreshResponse: &sessions.SessionState{
User: "user",
Email: "email@email.com",
Groups: []string{"group1"},
AccessToken: "AccessToken",
RefreshToken: "RefreshToken",
LifetimeDeadline: time.Now().Add(10 * time.Second),
RefreshDeadline: time.Now().Add(-10 * time.Second),
}},
true},
{"good",
"https://corp.example.com/",
policy,
&sessions.MockSessionStore{Session: &sessions.SessionState{
User: "user",
Email: "email@email.com",
Groups: []string{"group1"},
AccessToken: "AccessToken",
RefreshToken: "RefreshToken",
LifetimeDeadline: time.Now().Add(10 * time.Second),
RefreshDeadline: time.Now().Add(10 * time.Second),
}}, testAuth, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
opts := testOptions()
opts.Policy = tt.mux
p, err := New(opts)
if err != nil {
t.Fatal(err)
}
p.sessionStore = tt.session
p.AuthenticateClient = tt.authenticator
p.cipher = mockCipher{}
r := httptest.NewRequest("GET", tt.host, nil)
w := httptest.NewRecorder()
fmt.Printf("%s", tt.name)
if err := p.Authenticate(w, r); (err != nil) != tt.wantErr {
t.Errorf("Proxy.Authenticate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}

View file

@ -140,7 +140,7 @@ func New(opts *config.Options) (*Proxy, error) {
cookieStore, err := sessions.NewCookieStore(
&sessions.CookieStoreOptions{
Name: opts.ProxyCookieName,
Name: opts.CookieName,
CookieDomain: opts.CookieDomain,
CookieSecure: opts.CookieSecure,
CookieHTTPOnly: opts.CookieHTTPOnly,
@ -267,7 +267,7 @@ func NewReverseProxyHandler(o *config.Options, proxy *httputil.ReverseProxy, rou
up := &UpstreamProxy{
name: route.Destination.Host,
handler: proxy,
cookieName: o.ProxyCookieName,
cookieName: o.CookieName,
}
if len(o.SigningKey) != 0 {
decodedSigningKey, _ := base64.StdEncoding.DecodeString(o.SigningKey)

View file

@ -2,6 +2,7 @@ package proxy // import "github.com/pomerium/pomerium/proxy"
import (
"encoding/base64"
"fmt"
"io/ioutil"
"net"
"net/http"
@ -82,7 +83,7 @@ func TestNewReverseProxyHandler(t *testing.T) {
func testOptions() *config.Options {
authenticateService, _ := url.Parse("https://authenticate.corp.beyondperimeter.com")
authorizeService, _ := url.Parse("https://authorize.corp.beyondperimeter.com")
configBlob := `[{"from":"corp.example.notatld","to":"example.notatld"}]` //valid yaml
configBlob := `[{"from":"corp.example.notatld","to":"example.notatld"}]`
policy := base64.URLEncoding.EncodeToString([]byte(configBlob))
opts := config.NewOptions()
@ -91,13 +92,30 @@ func testOptions() *config.Options {
opts.AuthorizeURL = authorizeService
opts.SharedKey = "80ldlrU2d7w+wVpKNfevk6fmb8otEx6CqOfshj2LwhQ="
opts.CookieSecret = "OromP1gurwGWjQPYb1nNgSxtbVB5NnLzX6z5WOKr0Yw="
opts.ProxyCookieName = "pomerium"
opts.CookieName = "pomerium"
return opts
}
func testOptionsWithCORS() *config.Options {
configBlob := `[{"from":"corp.example.com","to":"example.com","cors_allow_preflight":true}]` //valid yaml
opts := testOptions()
func testOptionsTestServer(uri string) *config.Options {
authenticateService, _ := url.Parse("https://authenticate.corp.beyondperimeter.com")
authorizeService, _ := url.Parse("https://authorize.corp.beyondperimeter.com")
// RFC 2606
configBlob := fmt.Sprintf(`[{"from":"httpbin.corp.example","to":"%s"}]`, uri)
policy := base64.URLEncoding.EncodeToString([]byte(configBlob))
opts := config.NewOptions()
opts.Policy = policy
opts.AuthenticateURL = authenticateService
opts.AuthorizeURL = authorizeService
opts.SharedKey = "80ldlrU2d7w+wVpKNfevk6fmb8otEx6CqOfshj2LwhQ="
opts.CookieSecret = "OromP1gurwGWjQPYb1nNgSxtbVB5NnLzX6z5WOKr0Yw="
opts.CookieName = "pomerium"
return opts
}
func testOptionsWithCORS(uri string) *config.Options {
configBlob := fmt.Sprintf(`[{"from":"httpbin.corp.example","to":"%s","cors_allow_preflight":true}]`, uri)
opts := testOptionsTestServer(uri)
opts.Policy = base64.URLEncoding.EncodeToString([]byte(configBlob))
return opts
}