sessions: check idp id to detect provider changes to force session invalidation (#3707)

* sessions: check idp id to detect provider changes to force session invalidation

* remove dead code

* fix test
This commit is contained in:
Caleb Doxsey 2022-10-25 16:20:32 -06:00 committed by GitHub
parent 3f7a482815
commit 30bdae3d9e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 265 additions and 193 deletions

View file

@ -111,9 +111,9 @@ func (a *Authenticate) mountDashboard(r *mux.Router) {
cr.Path("/").Handler(a.requireValidSignature(a.Callback)).Methods(http.MethodGet)
}
// RetrieveSession is the middleware used retrieve session by the sessionLoaders
// RetrieveSession is the middleware used retrieve session by the sessionLoader
func (a *Authenticate) RetrieveSession(next http.Handler) http.Handler {
return sessions.RetrieveSession(a.state.Load().sessionLoaders...)(next)
return sessions.RetrieveSession(a.state.Load().sessionLoader)(next)
}
// VerifySession is the middleware used to enforce a valid authentication

View file

@ -42,7 +42,7 @@ type authenticateState struct {
sessionStore sessions.SessionStore
// sessionLoaders are a collection of session loaders to attempt to pull
// a user's session state from
sessionLoaders []sessions.SessionLoader
sessionLoader sessions.SessionLoader
jwk *jose.JSONWebKeySet
@ -120,7 +120,7 @@ func newAuthenticateStateFromConfig(cfg *config.Config) (*authenticateState, err
}
state.sessionStore = cookieStore
state.sessionLoaders = []sessions.SessionLoader{cookieStore}
state.sessionLoader = cookieStore
state.jwk = new(jose.JSONWebKeySet)
signingKey, err := cfg.Options.GetSigningKey()
if err != nil {

View file

@ -19,7 +19,6 @@ import (
"github.com/pomerium/pomerium/authorize/internal/store"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/atomicutil"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/testutil"
"github.com/pomerium/pomerium/pkg/policy/criteria"
)
@ -68,8 +67,6 @@ func TestAuthorize_okResponse(t *testing.T) {
JWTClaimsHeaders: config.NewJWTClaimHeaders("email"),
}
a := &Authorize{currentOptions: config.NewAtomicOptions(), state: atomicutil.NewValue(new(authorizeState))}
encoder, _ := jws.NewHS256Signer([]byte{0, 0, 0, 0})
a.state.Load().encoder = encoder
a.currentOptions.Store(opt)
a.store = store.New()
pe, err := newPolicyEvaluator(opt, a.store)
@ -124,8 +121,6 @@ func TestAuthorize_okResponse(t *testing.T) {
func TestAuthorize_deniedResponse(t *testing.T) {
a := &Authorize{currentOptions: config.NewAtomicOptions(), state: atomicutil.NewValue(new(authorizeState))}
encoder, _ := jws.NewHS256Signer([]byte{0, 0, 0, 0})
a.state.Load().encoder = encoder
a.currentOptions.Store(&config.Options{
Policies: []config.Policy{{
Source: &config.StringURL{URL: &url.URL{Host: "example.com"}},

View file

@ -55,8 +55,7 @@ func (a *Authorize) Check(ctx context.Context, in *envoy_service_auth_v3.CheckRe
}
}
rawJWT, _ := loadRawSession(hreq, a.currentOptions.Load(), state.encoder)
sessionState, _ := loadSession(state.encoder, rawJWT)
sessionState, _ := state.sessionStore.LoadSessionState(hreq)
var s sessionOrServiceAccount
var u *user.User

View file

@ -16,7 +16,6 @@ import (
"github.com/pomerium/pomerium/authorize/evaluator"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/atomicutil"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/pkg/grpc/databroker"
@ -48,8 +47,6 @@ yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
func Test_getEvaluatorRequest(t *testing.T) {
a := &Authorize{currentOptions: config.NewAtomicOptions(), state: atomicutil.NewValue(new(authorizeState))}
encoder, _ := jws.NewHS256Signer([]byte{0, 0, 0, 0})
a.state.Load().encoder = encoder
a.currentOptions.Store(&config.Options{
Policies: []config.Policy{{
Source: &config.StringURL{URL: &url.URL{Host: "example.com"}},
@ -262,8 +259,6 @@ func Test_handleForwardAuth(t *testing.T) {
func Test_getEvaluatorRequestWithPortInHostHeader(t *testing.T) {
a := &Authorize{currentOptions: config.NewAtomicOptions(), state: atomicutil.NewValue(new(authorizeState))}
encoder, _ := jws.NewHS256Signer([]byte{0, 0, 0, 0})
a.state.Load().encoder = encoder
a.currentOptions.Store(&config.Options{
Policies: []config.Policy{{
Source: &config.StringURL{URL: &url.URL{Host: "example.com"}},

View file

@ -1,63 +0,0 @@
package authorize
import (
"errors"
"net/http"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/internal/sessions/cookie"
"github.com/pomerium/pomerium/internal/sessions/header"
"github.com/pomerium/pomerium/internal/sessions/queryparam"
"github.com/pomerium/pomerium/internal/urlutil"
)
func loadRawSession(req *http.Request, options *config.Options, encoder encoding.MarshalUnmarshaler) ([]byte, error) {
var loaders []sessions.SessionLoader
cookieStore, err := getCookieStore(options, encoder)
if err != nil {
return nil, err
}
loaders = append(loaders,
cookieStore,
header.NewStore(encoder),
queryparam.NewStore(encoder, urlutil.QuerySession),
)
for _, loader := range loaders {
sess, err := loader.LoadSession(req)
if err != nil && !errors.Is(err, sessions.ErrNoSessionFound) {
return nil, err
} else if err == nil {
return []byte(sess), nil
}
}
return nil, sessions.ErrNoSessionFound
}
func loadSession(encoder encoding.MarshalUnmarshaler, rawJWT []byte) (*sessions.State, error) {
var s sessions.State
err := encoder.Unmarshal(rawJWT, &s)
if err != nil {
return nil, err
}
return &s, nil
}
func getCookieStore(options *config.Options, encoder encoding.MarshalUnmarshaler) (sessions.SessionStore, error) {
cookieStore, err := cookie.NewStore(func() cookie.Options {
return cookie.Options{
Name: options.CookieName,
Domain: options.CookieDomain,
Secure: options.CookieSecure,
HTTPOnly: options.CookieHTTPOnly,
Expire: options.CookieExpire,
}
}, encoder)
if err != nil {
return nil, err
}
return cookieStore, nil
}

View file

@ -1,76 +0,0 @@
package authorize
import (
"net/url"
"testing"
envoy_service_auth_v3 "github.com/envoyproxy/go-control-plane/envoy/service/auth/v3"
"github.com/stretchr/testify/assert"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/sessions"
)
func TestLoadSession(t *testing.T) {
opts := config.NewDefaultOptions()
encoder, err := jws.NewHS256Signer(nil)
if !assert.NoError(t, err) {
return
}
state := &sessions.State{ID: "xyz"}
rawjwt, err := encoder.Marshal(state)
if !assert.NoError(t, err) {
return
}
load := func(t *testing.T, hattrs *envoy_service_auth_v3.AttributeContext_HttpRequest) (*sessions.State, error) {
req := getHTTPRequestFromCheckRequest(&envoy_service_auth_v3.CheckRequest{
Attributes: &envoy_service_auth_v3.AttributeContext{
Request: &envoy_service_auth_v3.AttributeContext_Request{
Http: hattrs,
},
},
})
raw, err := loadRawSession(req, opts, encoder)
if err != nil {
return nil, err
}
var state sessions.State
err = encoder.Unmarshal(raw, &state)
if err != nil {
return nil, err
}
return &state, nil
}
t.Run("header", func(t *testing.T) {
hattrs := &envoy_service_auth_v3.AttributeContext_HttpRequest{
Id: "req-1",
Method: "GET",
Headers: map[string]string{
"Authorization": "Pomerium " + string(rawjwt),
},
Path: "/hello/world",
Host: "example.com",
Scheme: "https",
}
sess, err := load(t, hattrs)
assert.NoError(t, err)
assert.NotNil(t, sess)
})
t.Run("query param", func(t *testing.T) {
hattrs := &envoy_service_auth_v3.AttributeContext_HttpRequest{
Id: "req-1",
Method: "GET",
Path: "/hello/world?" + url.Values{
"pomerium_session": []string{string(rawjwt)},
}.Encode(),
Host: "example.com",
Scheme: "https",
}
sess, err := load(t, hattrs)
assert.NoError(t, err)
assert.NotNil(t, sess)
})
}

View file

@ -9,8 +9,6 @@ import (
"github.com/pomerium/pomerium/authorize/evaluator"
"github.com/pomerium/pomerium/authorize/internal/store"
"github.com/pomerium/pomerium/config"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/pkg/grpc"
"github.com/pomerium/pomerium/pkg/grpc/databroker"
"github.com/pomerium/pomerium/pkg/protoutil"
@ -21,10 +19,10 @@ var outboundGRPCConnection = new(grpc.CachedOutboundGRPClientConn)
type authorizeState struct {
sharedKey []byte
evaluator *evaluator.Evaluator
encoder encoding.MarshalUnmarshaler
dataBrokerClientConnection *googlegrpc.ClientConn
dataBrokerClient databroker.DataBrokerServiceClient
auditEncryptor *protoutil.Encryptor
sessionStore *config.SessionStore
}
func newAuthorizeStateFromConfig(cfg *config.Config, store *store.Store) (*authorizeState, error) {
@ -46,11 +44,6 @@ func newAuthorizeStateFromConfig(cfg *config.Config, store *store.Store) (*autho
return nil, err
}
state.encoder, err = jws.NewHS256Signer(state.sharedKey)
if err != nil {
return nil, err
}
sharedKey, err := cfg.Options.GetSharedKey()
if err != nil {
return nil, err
@ -76,5 +69,10 @@ func newAuthorizeStateFromConfig(cfg *config.Config, store *store.Store) (*autho
state.auditEncryptor = protoutil.NewEncryptor(auditKey)
}
state.sessionStore, err = config.NewSessionStore(cfg.Options)
if err != nil {
return nil, fmt.Errorf("authorize: invalid session store: %w", err)
}
return state, nil
}

View file

@ -1,14 +1,16 @@
package config
import (
"github.com/pomerium/pomerium/internal/urlutil"
"github.com/pomerium/pomerium/pkg/grpc/identity"
)
// GetIdentityProviderForID returns the identity provider associated with the given IDP id.
// If none is found the default provider is returned.
func (o *Options) GetIdentityProviderForID(idpID string) (*identity.Provider, error) {
for _, policy := range o.GetAllPolicies() {
idp, err := o.GetIdentityProviderForPolicy(&policy) //nolint
for _, p := range o.GetAllPolicies() {
p := p
idp, err := o.GetIdentityProviderForPolicy(&p)
if err != nil {
return nil, err
}
@ -48,3 +50,19 @@ func (o *Options) GetIdentityProviderForPolicy(policy *Policy) (*identity.Provid
idp.Id = idp.Hash()
return idp, nil
}
// GetIdentityProviderForRequestURL gets the identity provider associated with the given request URL.
func (o *Options) GetIdentityProviderForRequestURL(requestURL string) (*identity.Provider, error) {
u, err := urlutil.ParseAndValidateURL(requestURL)
if err != nil {
return nil, err
}
for _, p := range o.GetAllPolicies() {
p := p
if p.Matches(*u) {
return o.GetIdentityProviderForPolicy(&p)
}
}
return o.GetIdentityProviderForPolicy(nil)
}

83
config/session.go Normal file
View file

@ -0,0 +1,83 @@
package config
import (
"fmt"
"net/http"
"github.com/pomerium/pomerium/internal/encoding"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/internal/sessions/cookie"
"github.com/pomerium/pomerium/internal/sessions/header"
"github.com/pomerium/pomerium/internal/sessions/queryparam"
"github.com/pomerium/pomerium/internal/urlutil"
)
// A SessionStore saves and loads sessions based on the options.
type SessionStore struct {
options *Options
encoder encoding.MarshalUnmarshaler
loader sessions.SessionLoader
}
// NewSessionStore creates a new SessionStore from the Options.
func NewSessionStore(options *Options) (*SessionStore, error) {
store := &SessionStore{
options: options,
}
sharedKey, err := options.GetSharedKey()
if err != nil {
return nil, fmt.Errorf("config/sessions: shared_key is required: %w", err)
}
store.encoder, err = jws.NewHS256Signer(sharedKey)
if err != nil {
return nil, fmt.Errorf("config/sessions: invalid session encoder: %w", err)
}
cookieStore, err := cookie.NewStore(func() cookie.Options {
return cookie.Options{
Name: options.CookieName,
Domain: options.CookieDomain,
Secure: options.CookieSecure,
HTTPOnly: options.CookieHTTPOnly,
Expire: options.CookieExpire,
}
}, store.encoder)
if err != nil {
return nil, err
}
headerStore := header.NewStore(store.encoder)
queryParamStore := queryparam.NewStore(store.encoder, urlutil.QuerySession)
store.loader = sessions.MultiSessionLoader(cookieStore, headerStore, queryParamStore)
return store, nil
}
// LoadSessionState loads the session state from a request.
func (store *SessionStore) LoadSessionState(r *http.Request) (*sessions.State, error) {
rawJWT, err := store.loader.LoadSession(r)
if err != nil {
return nil, err
}
var state sessions.State
err = store.encoder.Unmarshal([]byte(rawJWT), &state)
if err != nil {
return nil, err
}
// confirm that the identity provider id matches the state
idp, err := store.options.GetIdentityProviderForRequestURL(urlutil.GetAbsoluteURL(r).String())
if err != nil {
return nil, err
}
if idp.GetId() != state.IdentityProviderID {
return nil, fmt.Errorf("unexpected session state identity provider id: %s != %s",
idp.GetId(), state.IdentityProviderID)
}
return &state, nil
}

128
config/session_test.go Normal file
View file

@ -0,0 +1,128 @@
package config
import (
"encoding/base64"
"net/http"
"net/url"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/httputil"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/internal/urlutil"
"github.com/pomerium/pomerium/pkg/cryptutil"
)
func TestSessionStore_LoadSessionState(t *testing.T) {
t.Parallel()
sharedKey := cryptutil.NewKey()
options := NewDefaultOptions()
options.SharedKey = base64.StdEncoding.EncodeToString(sharedKey)
options.Provider = "oidc"
options.ProviderURL = "https://oidc.example.com"
options.ClientID = "client_id"
options.ClientSecret = "client_secret"
options.Policies = append(options.Policies,
Policy{
From: "https://p1.example.com",
To: mustParseWeightedURLs(t, "https://p1"),
IDPClientID: "client_id_1",
IDPClientSecret: "client_secret_1",
},
Policy{
From: "https://p2.example.com",
To: mustParseWeightedURLs(t, "https://p2"),
IDPClientID: "client_id_2",
IDPClientSecret: "client_secret_2",
})
require.NoError(t, options.Validate())
store, err := NewSessionStore(options)
require.NoError(t, err)
idp1, err := options.GetIdentityProviderForPolicy(nil)
require.NoError(t, err)
require.NotNil(t, idp1)
idp2, err := options.GetIdentityProviderForPolicy(&options.Policies[0])
require.NoError(t, err)
require.NotNil(t, idp2)
idp3, err := options.GetIdentityProviderForPolicy(&options.Policies[1])
require.NoError(t, err)
require.NotNil(t, idp3)
makeJWS := func(t *testing.T, state *sessions.State) string {
e, err := jws.NewHS256Signer(sharedKey)
require.NoError(t, err)
rawJWS, err := e.Marshal(state)
require.NoError(t, err)
return string(rawJWS)
}
t.Run("mssing", func(t *testing.T) {
r, err := http.NewRequest(http.MethodGet, "https://p1.example.com", nil)
require.NoError(t, err)
s, err := store.LoadSessionState(r)
assert.ErrorIs(t, err, sessions.ErrNoSessionFound)
assert.Nil(t, s)
})
t.Run("query", func(t *testing.T) {
rawJWS := makeJWS(t, &sessions.State{
Issuer: "authenticate.example.com",
ID: "example",
IdentityProviderID: idp2.GetId(),
})
r, err := http.NewRequest(http.MethodGet, "https://p1.example.com?"+url.Values{
urlutil.QuerySession: {rawJWS},
}.Encode(), nil)
require.NoError(t, err)
s, err := store.LoadSessionState(r)
assert.NoError(t, err)
assert.Empty(t, cmp.Diff(&sessions.State{
Issuer: "authenticate.example.com",
ID: "example",
IdentityProviderID: idp2.GetId(),
}, s))
})
t.Run("header", func(t *testing.T) {
rawJWS := makeJWS(t, &sessions.State{
Issuer: "authenticate.example.com",
ID: "example",
IdentityProviderID: idp3.GetId(),
})
r, err := http.NewRequest(http.MethodGet, "https://p2.example.com", nil)
require.NoError(t, err)
r.Header.Set(httputil.HeaderPomeriumAuthorization, rawJWS)
s, err := store.LoadSessionState(r)
assert.NoError(t, err)
assert.Empty(t, cmp.Diff(&sessions.State{
Issuer: "authenticate.example.com",
ID: "example",
IdentityProviderID: idp3.GetId(),
}, s))
})
t.Run("wrong idp", func(t *testing.T) {
rawJWS := makeJWS(t, &sessions.State{
Issuer: "authenticate.example.com",
ID: "example",
IdentityProviderID: idp1.GetId(),
})
r, err := http.NewRequest(http.MethodGet, "https://p2.example.com", nil)
require.NoError(t, err)
r.Header.Set(httputil.HeaderPomeriumAuthorization, rawJWS)
s, err := store.LoadSessionState(r)
assert.Error(t, err)
assert.Nil(t, s)
})
}

View file

@ -2,7 +2,6 @@ package sessions
import (
"context"
"errors"
"net/http"
)
@ -14,17 +13,17 @@ var (
// RetrieveSession takes a slice of session loaders and tries to find a valid
// session in the order they were supplied and is added to the request's context
func RetrieveSession(s ...SessionLoader) func(http.Handler) http.Handler {
func RetrieveSession(s SessionLoader) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return retrieve(s...)(next)
return retrieve(s)(next)
}
}
func retrieve(s ...SessionLoader) func(http.Handler) http.Handler {
func retrieve(s SessionLoader) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
hfn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
jwt, err := retrieveFromRequest(r, s...)
jwt, err := s.LoadSession(r)
ctx = NewContext(ctx, jwt, err)
next.ServeHTTP(w, r.WithContext(ctx))
}
@ -32,21 +31,6 @@ func retrieve(s ...SessionLoader) func(http.Handler) http.Handler {
}
}
// retrieveFromRequest extracts sessions state from the request by calling
// token find functions in the order they where provided.
func retrieveFromRequest(r *http.Request, sessions ...SessionLoader) (string, error) {
for _, s := range sessions {
jwt, err := s.LoadSession(r)
if err != nil && !errors.Is(err, ErrNoSessionFound) {
return "", err
} else if err == nil {
return jwt, nil
}
}
return "", ErrNoSessionFound
}
// NewContext sets context values for the user session state and error.
func NewContext(ctx context.Context, jwt string, err error) context.Context {
ctx = context.WithValue(ctx, SessionCtxKey, jwt)

View file

@ -3,6 +3,7 @@
package sessions
import (
"errors"
"net/http"
)
@ -17,3 +18,21 @@ type SessionStore interface {
type SessionLoader interface {
LoadSession(*http.Request) (string, error)
}
type multiSessionLoader []SessionLoader
func (l multiSessionLoader) LoadSession(r *http.Request) (string, error) {
for _, ll := range l {
s, err := ll.LoadSession(r)
if errors.Is(err, ErrNoSessionFound) {
continue
}
return s, err
}
return "", ErrNoSessionFound
}
// MultiSessionLoader returns a session loader that returns the first session available.
func MultiSessionLoader(loaders ...SessionLoader) SessionLoader {
return multiSessionLoader(loaders)
}

View file

@ -9,8 +9,6 @@ import (
"github.com/pomerium/pomerium/internal/encoding/jws"
"github.com/pomerium/pomerium/internal/sessions"
"github.com/pomerium/pomerium/internal/sessions/cookie"
"github.com/pomerium/pomerium/internal/sessions/header"
"github.com/pomerium/pomerium/internal/sessions/queryparam"
"github.com/pomerium/pomerium/pkg/cryptutil"
)
@ -26,7 +24,6 @@ type proxyState struct {
encoder encoding.MarshalUnmarshaler
cookieSecret []byte
sessionStore sessions.SessionStore
sessionLoaders []sessions.SessionLoader
jwtClaimHeaders config.JWTClaimHeaders
programmaticRedirectDomainWhitelist []string
@ -84,11 +81,6 @@ func newProxyStateFromConfig(cfg *config.Config) (*proxyState, error) {
if err != nil {
return nil, err
}
state.sessionLoaders = []sessions.SessionLoader{
state.sessionStore,
header.NewStore(state.encoder),
queryparam.NewStore(state.encoder, "pomerium_session"),
}
state.programmaticRedirectDomainWhitelist = cfg.Options.ProgrammaticRedirectDomainWhitelist
return state, nil