mirror of
https://github.com/pomerium/pomerium.git
synced 2025-07-17 00:36:09 +02:00
authenticate: move properties to atomically updated state (#1277)
* authenticate: remove cookie options * authenticate: remove shared key field * authenticate: remove shared cipher property * authenticate: move properties to separate state struct
This commit is contained in:
parent
598102f587
commit
d608526998
5 changed files with 256 additions and 210 deletions
|
@ -3,29 +3,15 @@
|
|||
package authenticate
|
||||
|
||||
import (
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/url"
|
||||
"sync"
|
||||
|
||||
"gopkg.in/square/go-jose.v2"
|
||||
|
||||
"github.com/pomerium/pomerium/config"
|
||||
"github.com/pomerium/pomerium/internal/encoding"
|
||||
"github.com/pomerium/pomerium/internal/encoding/ecjson"
|
||||
"github.com/pomerium/pomerium/internal/encoding/jws"
|
||||
"github.com/pomerium/pomerium/internal/frontend"
|
||||
"github.com/pomerium/pomerium/internal/httputil"
|
||||
"github.com/pomerium/pomerium/internal/identity"
|
||||
"github.com/pomerium/pomerium/internal/identity/oauth"
|
||||
"github.com/pomerium/pomerium/internal/log"
|
||||
"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"
|
||||
"github.com/pomerium/pomerium/pkg/cryptutil"
|
||||
"github.com/pomerium/pomerium/pkg/grpc"
|
||||
|
@ -64,51 +50,14 @@ func ValidateOptions(o *config.Options) error {
|
|||
|
||||
// Authenticate contains data required to run the authenticate service.
|
||||
type Authenticate struct {
|
||||
// RedirectURL is the authenticate service's externally accessible
|
||||
// url that the identity provider (IdP) will callback to following
|
||||
// authentication flow
|
||||
RedirectURL *url.URL
|
||||
|
||||
// values related to cross service communication
|
||||
//
|
||||
// sharedKey is used to encrypt and authenticate data between services
|
||||
sharedKey string
|
||||
// sharedCipher is used to encrypt data for use between services
|
||||
sharedCipher cipher.AEAD
|
||||
// sharedEncoder is the encoder to use to serialize data to be consumed
|
||||
// by other services
|
||||
sharedEncoder encoding.MarshalUnmarshaler
|
||||
|
||||
// values related to user sessions
|
||||
//
|
||||
// cookieSecret is the secret to encrypt and authenticate session data
|
||||
cookieSecret []byte
|
||||
// cookieCipher is the cipher to use to encrypt/decrypt session data
|
||||
cookieCipher cipher.AEAD
|
||||
// encryptedEncoder is the encoder used to marshal and unmarshal session data
|
||||
encryptedEncoder encoding.MarshalUnmarshaler
|
||||
// sessionStore is the session store used to persist a user's session
|
||||
sessionStore sessions.SessionStore
|
||||
cookieOptions *cookie.Options
|
||||
|
||||
// sessionLoaders are a collection of session loaders to attempt to pull
|
||||
// a user's session state from
|
||||
sessionLoaders []sessions.SessionLoader
|
||||
|
||||
// dataBrokerClient is used to retrieve sessions
|
||||
dataBrokerClient databroker.DataBrokerServiceClient
|
||||
|
||||
// guard administrator below.
|
||||
administratorMu sync.Mutex
|
||||
// administrators keeps track of administrator users.
|
||||
administrator map[string]struct{}
|
||||
|
||||
jwk *jose.JSONWebKeySet
|
||||
|
||||
templates *template.Template
|
||||
|
||||
options *config.AtomicOptions
|
||||
provider *identity.AtomicAuthenticator
|
||||
state *atomicAuthenticateState
|
||||
}
|
||||
|
||||
// New validates and creates a new authenticate service from a set of Options.
|
||||
|
@ -117,26 +66,6 @@ func New(cfg *config.Config) (*Authenticate, error) {
|
|||
return nil, err
|
||||
}
|
||||
|
||||
// shared state encoder setup
|
||||
sharedCipher, _ := cryptutil.NewAEADCipherFromBase64(cfg.Options.SharedKey)
|
||||
sharedEncoder, err := jws.NewHS256Signer([]byte(cfg.Options.SharedKey), cfg.Options.GetAuthenticateURL().Host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// private state encoder setup, used to encrypt oauth2 tokens
|
||||
decodedCookieSecret, _ := base64.StdEncoding.DecodeString(cfg.Options.CookieSecret)
|
||||
cookieCipher, _ := cryptutil.NewAEADCipher(decodedCookieSecret)
|
||||
encryptedEncoder := ecjson.New(cookieCipher)
|
||||
|
||||
cookieOptions := &cookie.Options{
|
||||
Name: cfg.Options.CookieName,
|
||||
Domain: cfg.Options.CookieDomain,
|
||||
Secure: cfg.Options.CookieSecure,
|
||||
HTTPOnly: cfg.Options.CookieHTTPOnly,
|
||||
Expire: cfg.Options.CookieExpire,
|
||||
}
|
||||
|
||||
dataBrokerConn, err := grpc.NewGRPCClientConn(
|
||||
&grpc.Options{
|
||||
Addr: cfg.Options.DataBrokerURL,
|
||||
|
@ -154,33 +83,13 @@ func New(cfg *config.Config) (*Authenticate, error) {
|
|||
|
||||
dataBrokerClient := databroker.NewDataBrokerServiceClient(dataBrokerConn)
|
||||
|
||||
qpStore := queryparam.NewStore(encryptedEncoder, urlutil.QueryProgrammaticToken)
|
||||
headerStore := header.NewStore(encryptedEncoder, httputil.AuthorizationTypePomerium)
|
||||
|
||||
redirectURL, _ := urlutil.DeepCopy(cfg.Options.AuthenticateURL)
|
||||
redirectURL.Path = cfg.Options.AuthenticateCallbackPath
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
a := &Authenticate{
|
||||
RedirectURL: redirectURL,
|
||||
// shared state
|
||||
sharedKey: cfg.Options.SharedKey,
|
||||
sharedCipher: sharedCipher,
|
||||
sharedEncoder: sharedEncoder,
|
||||
// private state
|
||||
cookieSecret: decodedCookieSecret,
|
||||
cookieCipher: cookieCipher,
|
||||
cookieOptions: cookieOptions,
|
||||
encryptedEncoder: encryptedEncoder,
|
||||
// grpc client for cache
|
||||
dataBrokerClient: dataBrokerClient,
|
||||
jwk: &jose.JSONWebKeySet{},
|
||||
templates: template.Must(frontend.NewTemplates()),
|
||||
options: config.NewAtomicOptions(),
|
||||
provider: identity.NewAtomicAuthenticator(),
|
||||
state: newAtomicAuthenticateState(newAuthenticateState()),
|
||||
}
|
||||
|
||||
err = a.updateProvider(cfg)
|
||||
|
@ -188,48 +97,15 @@ func New(cfg *config.Config) (*Authenticate, error) {
|
|||
return nil, err
|
||||
}
|
||||
|
||||
cookieStore, err := cookie.NewStore(func() cookie.Options {
|
||||
opts := a.options.Load()
|
||||
return cookie.Options{
|
||||
Name: opts.CookieName,
|
||||
Domain: opts.CookieDomain,
|
||||
Secure: opts.CookieSecure,
|
||||
HTTPOnly: opts.CookieHTTPOnly,
|
||||
Expire: opts.CookieExpire,
|
||||
}
|
||||
}, sharedEncoder)
|
||||
state, err := newAuthenticateStateFromConfig(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
a.sessionStore = cookieStore
|
||||
a.sessionLoaders = []sessions.SessionLoader{qpStore, headerStore, cookieStore}
|
||||
|
||||
if cfg.Options.SigningKey != "" {
|
||||
decodedCert, err := base64.StdEncoding.DecodeString(cfg.Options.SigningKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authenticate: failed to decode signing key: %w", err)
|
||||
}
|
||||
jwk, err := cryptutil.PublicJWKFromBytes(decodedCert, jose.ES256)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authenticate: failed to convert jwks: %w", err)
|
||||
}
|
||||
a.jwk.Keys = append(a.jwk.Keys, *jwk)
|
||||
}
|
||||
a.state.Store(state)
|
||||
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (a *Authenticate) setAdminUsers(opts *config.Options) {
|
||||
a.administratorMu.Lock()
|
||||
defer a.administratorMu.Unlock()
|
||||
|
||||
a.administrator = make(map[string]struct{}, len(opts.Administrators))
|
||||
for _, admin := range opts.Administrators {
|
||||
a.administrator[admin] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// OnConfigChange updates internal structures based on config.Options
|
||||
func (a *Authenticate) OnConfigChange(cfg *config.Config) {
|
||||
if a == nil {
|
||||
|
@ -238,10 +114,14 @@ func (a *Authenticate) OnConfigChange(cfg *config.Config) {
|
|||
|
||||
log.Info().Str("checksum", fmt.Sprintf("%x", cfg.Options.Checksum())).Msg("authenticate: updating options")
|
||||
a.options.Store(cfg.Options)
|
||||
a.setAdminUsers(cfg.Options)
|
||||
if err := a.updateProvider(cfg); err != nil {
|
||||
log.Error().Err(err).Msg("authenticate: failed to update identity provider")
|
||||
}
|
||||
if state, err := newAuthenticateStateFromConfig(cfg); err != nil {
|
||||
log.Error().Err(err).Msg("authenticate: failed to update state")
|
||||
} else {
|
||||
a.state.Store(state)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Authenticate) updateProvider(cfg *config.Config) error {
|
||||
|
|
|
@ -44,15 +44,19 @@ func (a *Authenticate) Handler() http.Handler {
|
|||
func (a *Authenticate) Mount(r *mux.Router) {
|
||||
r.StrictSlash(true)
|
||||
r.Use(middleware.SetHeaders(httputil.HeadersContentSecurityPolicy))
|
||||
r.Use(csrf.Protect(
|
||||
a.cookieSecret,
|
||||
csrf.Secure(a.cookieOptions.Secure),
|
||||
csrf.Path("/"),
|
||||
csrf.UnsafePaths([]string{a.RedirectURL.Path}), // enforce CSRF on "safe" handler
|
||||
csrf.FormValueName("state"), // rfc6749 section-10.12
|
||||
csrf.CookieName(fmt.Sprintf("%s_csrf", a.cookieOptions.Name)),
|
||||
csrf.ErrorHandler(httputil.HandlerFunc(httputil.CSRFFailureHandler)),
|
||||
))
|
||||
r.Use(func(h http.Handler) http.Handler {
|
||||
options := a.options.Load()
|
||||
state := a.state.Load()
|
||||
return csrf.Protect(
|
||||
state.cookieSecret,
|
||||
csrf.Secure(options.CookieSecure),
|
||||
csrf.Path("/"),
|
||||
csrf.UnsafePaths([]string{state.redirectURL.Path}), // enforce CSRF on "safe" handler
|
||||
csrf.FormValueName("state"), // rfc6749 section-10.12
|
||||
csrf.CookieName(fmt.Sprintf("%s_csrf", options.CookieName)),
|
||||
csrf.ErrorHandler(httputil.HandlerFunc(httputil.CSRFFailureHandler)),
|
||||
)(h)
|
||||
})
|
||||
|
||||
r.Path("/robots.txt").HandlerFunc(a.RobotsTxt).Methods(http.MethodGet)
|
||||
// Identity Provider (IdP) endpoints
|
||||
|
@ -62,7 +66,8 @@ func (a *Authenticate) Mount(r *mux.Router) {
|
|||
v := r.PathPrefix("/.pomerium").Subrouter()
|
||||
c := cors.New(cors.Options{
|
||||
AllowOriginRequestFunc: func(r *http.Request, _ string) bool {
|
||||
err := middleware.ValidateRequestURL(r, a.sharedKey)
|
||||
options := a.options.Load()
|
||||
err := middleware.ValidateRequestURL(r, options.SharedKey)
|
||||
if err != nil {
|
||||
log.FromRequest(r).Info().Err(err).Msg("authenticate: origin blocked")
|
||||
}
|
||||
|
@ -72,7 +77,9 @@ func (a *Authenticate) Mount(r *mux.Router) {
|
|||
AllowedHeaders: []string{"*"},
|
||||
})
|
||||
v.Use(c.Handler)
|
||||
v.Use(sessions.RetrieveSession(a.sessionLoaders...))
|
||||
v.Use(func(h http.Handler) http.Handler {
|
||||
return sessions.RetrieveSession(a.state.Load().sessionLoaders...)(h)
|
||||
})
|
||||
v.Use(a.VerifySession)
|
||||
v.Path("/").Handler(httputil.HandlerFunc(a.Dashboard))
|
||||
v.Path("/sign_in").Handler(httputil.HandlerFunc(a.SignIn))
|
||||
|
@ -85,12 +92,16 @@ func (a *Authenticate) Mount(r *mux.Router) {
|
|||
|
||||
// programmatic access api endpoint
|
||||
api := r.PathPrefix("/api").Subrouter()
|
||||
api.Use(sessions.RetrieveSession(a.sessionLoaders...))
|
||||
api.Use(func(h http.Handler) http.Handler {
|
||||
return sessions.RetrieveSession(a.state.Load().sessionLoaders...)(h)
|
||||
})
|
||||
}
|
||||
|
||||
// Well-Known Uniform Resource Identifiers (URIs)
|
||||
// https://en.wikipedia.org/wiki/List_of_/.well-known/_services_offered_by_webservers
|
||||
func (a *Authenticate) wellKnown(w http.ResponseWriter, r *http.Request) error {
|
||||
state := a.state.Load()
|
||||
|
||||
wellKnownURLS := struct {
|
||||
// URL string referencing the client's JSON Web Key (JWK) Set
|
||||
// RFC7517 document, which contains the client's public keys.
|
||||
|
@ -98,9 +109,9 @@ func (a *Authenticate) wellKnown(w http.ResponseWriter, r *http.Request) error {
|
|||
OAuth2Callback string `json:"authentication_callback_endpoint"`
|
||||
ProgrammaticRefreshAPI string `json:"api_refresh_endpoint"`
|
||||
}{
|
||||
a.RedirectURL.ResolveReference(&url.URL{Path: "/.well-known/pomerium/jwks.json"}).String(),
|
||||
a.RedirectURL.ResolveReference(&url.URL{Path: "/oauth2/callback"}).String(),
|
||||
a.RedirectURL.ResolveReference(&url.URL{Path: "/api/v1/refresh"}).String(),
|
||||
state.redirectURL.ResolveReference(&url.URL{Path: "/.well-known/pomerium/jwks.json"}).String(),
|
||||
state.redirectURL.ResolveReference(&url.URL{Path: "/oauth2/callback"}).String(),
|
||||
state.redirectURL.ResolveReference(&url.URL{Path: "/api/v1/refresh"}).String(),
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
|
@ -114,9 +125,11 @@ func (a *Authenticate) wellKnown(w http.ResponseWriter, r *http.Request) error {
|
|||
}
|
||||
|
||||
func (a *Authenticate) jwks(w http.ResponseWriter, r *http.Request) error {
|
||||
state := a.state.Load()
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
jBytes, err := json.Marshal(a.jwk)
|
||||
jBytes, err := json.Marshal(state.jwk)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -162,12 +175,20 @@ func (a *Authenticate) SignIn(w http.ResponseWriter, r *http.Request) error {
|
|||
ctx, span := trace.StartSpan(r.Context(), "authenticate.SignIn")
|
||||
defer span.End()
|
||||
|
||||
options := a.options.Load()
|
||||
state := a.state.Load()
|
||||
|
||||
sharedCipher, err := cryptutil.NewAEADCipherFromBase64(options.SharedKey)
|
||||
if err != nil {
|
||||
return httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
|
||||
redirectURL, err := urlutil.ParseAndValidateURL(r.FormValue(urlutil.QueryRedirectURI))
|
||||
if err != nil {
|
||||
return httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
|
||||
jwtAudience := []string{a.RedirectURL.Host, redirectURL.Host}
|
||||
jwtAudience := []string{state.redirectURL.Host, redirectURL.Host}
|
||||
|
||||
var callbackURL *url.URL
|
||||
// if the callback is explicitly set, set it and add an additional audience
|
||||
|
@ -191,7 +212,7 @@ func (a *Authenticate) SignIn(w http.ResponseWriter, r *http.Request) error {
|
|||
|
||||
s, err := a.getSessionFromCtx(ctx)
|
||||
if err != nil {
|
||||
a.sessionStore.ClearSession(w, r)
|
||||
state.sessionStore.ClearSession(w, r)
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -199,10 +220,10 @@ func (a *Authenticate) SignIn(w http.ResponseWriter, r *http.Request) error {
|
|||
if impersonate := r.FormValue(urlutil.QueryImpersonateAction); impersonate != "" {
|
||||
s.SetImpersonation(r.FormValue(urlutil.QueryImpersonateEmail), r.FormValue(urlutil.QueryImpersonateGroups))
|
||||
}
|
||||
newSession := sessions.NewSession(s, a.RedirectURL.Host, jwtAudience)
|
||||
newSession := sessions.NewSession(s, state.redirectURL.Host, jwtAudience)
|
||||
|
||||
// re-persist the session, useful when session was evicted from session
|
||||
if err := a.sessionStore.SaveSession(w, r, s); err != nil {
|
||||
if err := state.sessionStore.SaveSession(w, r, s); err != nil {
|
||||
return httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
|
||||
|
@ -216,7 +237,7 @@ func (a *Authenticate) SignIn(w http.ResponseWriter, r *http.Request) error {
|
|||
return httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
|
||||
encSession, err := a.encryptedEncoder.Marshal(pbSession.GetOauthToken())
|
||||
encSession, err := state.encryptedEncoder.Marshal(pbSession.GetOauthToken())
|
||||
if err != nil {
|
||||
return httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
|
@ -225,13 +246,13 @@ func (a *Authenticate) SignIn(w http.ResponseWriter, r *http.Request) error {
|
|||
}
|
||||
|
||||
// sign the route session, as a JWT
|
||||
signedJWT, err := a.sharedEncoder.Marshal(newSession)
|
||||
signedJWT, err := state.sharedEncoder.Marshal(newSession)
|
||||
if err != nil {
|
||||
return httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
|
||||
// encrypt our route-based token JWT avoiding any accidental logging
|
||||
encryptedJWT := cryptutil.Encrypt(a.sharedCipher, signedJWT, nil)
|
||||
encryptedJWT := cryptutil.Encrypt(sharedCipher, signedJWT, nil)
|
||||
// base64 our encrypted payload for URL-friendlyness
|
||||
encodedJWT := base64.URLEncoding.EncodeToString(encryptedJWT)
|
||||
|
||||
|
@ -242,7 +263,7 @@ func (a *Authenticate) SignIn(w http.ResponseWriter, r *http.Request) error {
|
|||
|
||||
// build our hmac-d redirect URL with our session, pointing back to the
|
||||
// proxy's callback URL which is responsible for setting our new route-session
|
||||
uri := urlutil.NewSignedURL(a.sharedKey, callbackURL)
|
||||
uri := urlutil.NewSignedURL(options.SharedKey, callbackURL)
|
||||
httputil.Redirect(w, r, uri.String(), http.StatusFound)
|
||||
return nil
|
||||
}
|
||||
|
@ -253,6 +274,8 @@ func (a *Authenticate) SignOut(w http.ResponseWriter, r *http.Request) error {
|
|||
ctx, span := trace.StartSpan(r.Context(), "authenticate.SignOut")
|
||||
defer span.End()
|
||||
|
||||
state := a.state.Load()
|
||||
|
||||
sessionState, err := a.getSessionFromCtx(ctx)
|
||||
if err == nil {
|
||||
if s, _ := session.Get(ctx, a.dataBrokerClient, sessionState.ID); s != nil && s.OauthToken != nil {
|
||||
|
@ -267,7 +290,7 @@ func (a *Authenticate) SignOut(w http.ResponseWriter, r *http.Request) error {
|
|||
}
|
||||
|
||||
// no matter what happens, we want to clear the session store
|
||||
a.sessionStore.ClearSession(w, r)
|
||||
state.sessionStore.ClearSession(w, r)
|
||||
redirectString := r.FormValue(urlutil.QueryRedirectURI)
|
||||
endSessionURL, err := a.provider.Load().LogOut()
|
||||
if err == nil {
|
||||
|
@ -288,6 +311,8 @@ func (a *Authenticate) SignOut(w http.ResponseWriter, r *http.Request) error {
|
|||
// to the user's current user sessions state if the user is currently an
|
||||
// administrative user. Requests are redirected back to the user dashboard.
|
||||
func (a *Authenticate) Impersonate(w http.ResponseWriter, r *http.Request) error {
|
||||
options := a.options.Load()
|
||||
|
||||
redirectURL := urlutil.GetAbsoluteURL(r).ResolveReference(&url.URL{
|
||||
Path: "/.pomerium",
|
||||
})
|
||||
|
@ -303,7 +328,7 @@ func (a *Authenticate) Impersonate(w http.ResponseWriter, r *http.Request) error
|
|||
q.Set(urlutil.QueryImpersonateEmail, r.FormValue(urlutil.QueryImpersonateEmail))
|
||||
q.Set(urlutil.QueryImpersonateGroups, r.FormValue(urlutil.QueryImpersonateGroups))
|
||||
signinURL.RawQuery = q.Encode()
|
||||
httputil.Redirect(w, r, urlutil.NewSignedURL(a.sharedKey, signinURL).String(), http.StatusFound)
|
||||
httputil.Redirect(w, r, urlutil.NewSignedURL(options.SharedKey, signinURL).String(), http.StatusFound)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
@ -318,17 +343,18 @@ func (a *Authenticate) Impersonate(w http.ResponseWriter, r *http.Request) error
|
|||
// https://tools.ietf.org/html/rfc6749#section-4.2.1
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
|
||||
func (a *Authenticate) reauthenticateOrFail(w http.ResponseWriter, r *http.Request, err error) error {
|
||||
state := a.state.Load()
|
||||
// If request AJAX/XHR request, return a 401 instead because the redirect
|
||||
// will almost certainly violate their CORs policy
|
||||
if reqType := r.Header.Get("X-Requested-With"); strings.EqualFold(reqType, "XmlHttpRequest") {
|
||||
return httputil.NewError(http.StatusUnauthorized, err)
|
||||
}
|
||||
a.sessionStore.ClearSession(w, r)
|
||||
redirectURL := a.RedirectURL.ResolveReference(r.URL)
|
||||
state.sessionStore.ClearSession(w, r)
|
||||
redirectURL := state.redirectURL.ResolveReference(r.URL)
|
||||
nonce := csrf.Token(r)
|
||||
now := time.Now().Unix()
|
||||
b := []byte(fmt.Sprintf("%s|%d|", nonce, now))
|
||||
enc := cryptutil.Encrypt(a.cookieCipher, []byte(redirectURL.String()), b)
|
||||
enc := cryptutil.Encrypt(state.cookieCipher, []byte(redirectURL.String()), b)
|
||||
b = append(b, enc...)
|
||||
encodedState := base64.URLEncoding.EncodeToString(b)
|
||||
httputil.Redirect(w, r, a.provider.Load().GetSignInURL(encodedState), http.StatusFound)
|
||||
|
@ -361,6 +387,8 @@ func (a *Authenticate) getOAuthCallback(w http.ResponseWriter, r *http.Request)
|
|||
ctx, span := trace.StartSpan(r.Context(), "authenticate.getOAuthCallback")
|
||||
defer span.End()
|
||||
|
||||
state := a.state.Load()
|
||||
|
||||
// Error Authentication Response: rfc6749#section-4.1.2.1 & OIDC#3.1.2.6
|
||||
//
|
||||
// first, check if the identity provider returned an error
|
||||
|
@ -389,8 +417,8 @@ func (a *Authenticate) getOAuthCallback(w http.ResponseWriter, r *http.Request)
|
|||
|
||||
newState := sessions.NewSession(
|
||||
&s,
|
||||
a.RedirectURL.Hostname(),
|
||||
[]string{a.RedirectURL.Hostname()})
|
||||
state.redirectURL.Hostname(),
|
||||
[]string{state.redirectURL.Hostname()})
|
||||
|
||||
// state includes a csrf nonce (validated by middleware) and redirect uri
|
||||
bytes, err := base64.URLEncoding.DecodeString(r.FormValue("state"))
|
||||
|
@ -414,7 +442,7 @@ func (a *Authenticate) getOAuthCallback(w http.ResponseWriter, r *http.Request)
|
|||
// mac: to validate the nonce again, and above timestamp
|
||||
// decrypt: to prevent leaking 'redirect_uri' to IdP or logs
|
||||
b := []byte(fmt.Sprint(statePayload[0], "|", statePayload[1], "|"))
|
||||
redirectString, err := cryptutil.Decrypt(a.cookieCipher, []byte(statePayload[2]), b)
|
||||
redirectString, err := cryptutil.Decrypt(state.cookieCipher, []byte(statePayload[2]), b)
|
||||
if err != nil {
|
||||
return nil, httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
|
@ -425,19 +453,21 @@ func (a *Authenticate) getOAuthCallback(w http.ResponseWriter, r *http.Request)
|
|||
}
|
||||
|
||||
// ... and the user state to local storage.
|
||||
if err := a.sessionStore.SaveSession(w, r, &newState); err != nil {
|
||||
if err := state.sessionStore.SaveSession(w, r, &newState); err != nil {
|
||||
return nil, fmt.Errorf("failed saving new session: %w", err)
|
||||
}
|
||||
return redirectURL, nil
|
||||
}
|
||||
|
||||
func (a *Authenticate) getSessionFromCtx(ctx context.Context) (*sessions.State, error) {
|
||||
state := a.state.Load()
|
||||
|
||||
jwt, err := sessions.FromContext(ctx)
|
||||
if err != nil {
|
||||
return nil, httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
var s sessions.State
|
||||
if err := a.sharedEncoder.Unmarshal([]byte(jwt), &s); err != nil {
|
||||
if err := state.sharedEncoder.Unmarshal([]byte(jwt), &s); err != nil {
|
||||
return nil, httputil.NewError(http.StatusBadRequest, err)
|
||||
}
|
||||
return &s, nil
|
||||
|
@ -452,10 +482,8 @@ func (a *Authenticate) deleteSession(ctx context.Context, sessionID string) erro
|
|||
}
|
||||
|
||||
func (a *Authenticate) isAdmin(user string) bool {
|
||||
a.administratorMu.Lock()
|
||||
defer a.administratorMu.Unlock()
|
||||
|
||||
_, ok := a.administrator[user]
|
||||
state := a.state.Load()
|
||||
_, ok := state.administrators[user]
|
||||
return ok
|
||||
}
|
||||
|
||||
|
@ -532,7 +560,9 @@ func (a *Authenticate) saveSessionToDataBroker(ctx context.Context, sessionState
|
|||
return nil
|
||||
}
|
||||
|
||||
sessionExpiry, _ := ptypes.TimestampProto(time.Now().Add(a.cookieOptions.Expire))
|
||||
options := a.options.Load()
|
||||
|
||||
sessionExpiry, _ := ptypes.TimestampProto(time.Now().Add(options.CookieExpire))
|
||||
sessionState.Expiry = jwt.NewNumericDate(sessionExpiry.AsTime())
|
||||
idTokenIssuedAt, _ := ptypes.TimestampProto(sessionState.IssuedAt.Time())
|
||||
|
||||
|
|
|
@ -25,7 +25,6 @@ import (
|
|||
"github.com/pomerium/pomerium/internal/identity"
|
||||
"github.com/pomerium/pomerium/internal/identity/oidc"
|
||||
"github.com/pomerium/pomerium/internal/sessions"
|
||||
"github.com/pomerium/pomerium/internal/sessions/cookie"
|
||||
mstore "github.com/pomerium/pomerium/internal/sessions/mock"
|
||||
"github.com/pomerium/pomerium/internal/urlutil"
|
||||
"github.com/pomerium/pomerium/pkg/cryptutil"
|
||||
|
@ -42,12 +41,17 @@ import (
|
|||
)
|
||||
|
||||
func testAuthenticate() *Authenticate {
|
||||
redirectURL, _ := url.Parse("https://auth.example.com/oauth/callback")
|
||||
var auth Authenticate
|
||||
auth.RedirectURL, _ = url.Parse("https://auth.example.com/oauth/callback")
|
||||
auth.sharedKey = cryptutil.NewBase64Key()
|
||||
auth.cookieSecret = cryptutil.NewKey()
|
||||
auth.cookieOptions = &cookie.Options{Name: "name"}
|
||||
auth.state = newAtomicAuthenticateState(&authenticateState{
|
||||
redirectURL: redirectURL,
|
||||
cookieSecret: cryptutil.NewKey(),
|
||||
})
|
||||
auth.templates = template.Must(frontend.NewTemplates())
|
||||
auth.options = config.NewAtomicOptions()
|
||||
auth.options.Store(&config.Options{
|
||||
SharedKey: cryptutil.NewBase64Key(),
|
||||
})
|
||||
return &auth
|
||||
}
|
||||
|
||||
|
@ -110,10 +114,6 @@ func TestAuthenticate_Handler(t *testing.T) {
|
|||
|
||||
func TestAuthenticate_SignIn(t *testing.T) {
|
||||
t.Parallel()
|
||||
aead, err := chacha20poly1305.NewX(cryptutil.NewKey())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
|
@ -147,16 +147,12 @@ func TestAuthenticate_SignIn(t *testing.T) {
|
|||
defer ctrl.Finish()
|
||||
|
||||
a := &Authenticate{
|
||||
sessionStore: tt.session,
|
||||
RedirectURL: uriParseHelper("https://some.example"),
|
||||
sharedKey: "secret",
|
||||
sharedEncoder: tt.encoder,
|
||||
encryptedEncoder: tt.encoder,
|
||||
sharedCipher: aead,
|
||||
cookieOptions: &cookie.Options{
|
||||
Name: "cookie",
|
||||
Domain: "foo",
|
||||
},
|
||||
state: newAtomicAuthenticateState(&authenticateState{
|
||||
sessionStore: tt.session,
|
||||
redirectURL: uriParseHelper("https://some.example"),
|
||||
sharedEncoder: tt.encoder,
|
||||
encryptedEncoder: tt.encoder,
|
||||
}),
|
||||
dataBrokerClient: mockDataBrokerServiceClient{
|
||||
get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) {
|
||||
data, err := ptypes.MarshalAny(&session.Session{
|
||||
|
@ -176,8 +172,10 @@ func TestAuthenticate_SignIn(t *testing.T) {
|
|||
}, nil
|
||||
},
|
||||
},
|
||||
options: config.NewAtomicOptions(),
|
||||
provider: identity.NewAtomicAuthenticator(),
|
||||
}
|
||||
a.options.Store(&config.Options{SharedKey: base64.StdEncoding.EncodeToString(cryptutil.NewKey())})
|
||||
a.provider.Store(tt.provider)
|
||||
uri := &url.URL{Scheme: tt.scheme, Host: tt.host}
|
||||
|
||||
|
@ -235,10 +233,12 @@ func TestAuthenticate_SignOut(t *testing.T) {
|
|||
ctrl := gomock.NewController(t)
|
||||
defer ctrl.Finish()
|
||||
a := &Authenticate{
|
||||
sessionStore: tt.sessionStore,
|
||||
encryptedEncoder: mock.Encoder{},
|
||||
templates: template.Must(frontend.NewTemplates()),
|
||||
sharedEncoder: mock.Encoder{},
|
||||
state: newAtomicAuthenticateState(&authenticateState{
|
||||
sessionStore: tt.sessionStore,
|
||||
encryptedEncoder: mock.Encoder{},
|
||||
sharedEncoder: mock.Encoder{},
|
||||
}),
|
||||
templates: template.Must(frontend.NewTemplates()),
|
||||
dataBrokerClient: mockDataBrokerServiceClient{
|
||||
delete: func(ctx context.Context, in *databroker.DeleteRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
return nil, nil
|
||||
|
@ -261,6 +261,7 @@ func TestAuthenticate_SignOut(t *testing.T) {
|
|||
}, nil
|
||||
},
|
||||
},
|
||||
options: config.NewAtomicOptions(),
|
||||
provider: identity.NewAtomicAuthenticator(),
|
||||
}
|
||||
a.provider.Store(tt.provider)
|
||||
|
@ -345,11 +346,14 @@ func TestAuthenticate_OAuthCallback(t *testing.T) {
|
|||
}
|
||||
authURL, _ := url.Parse(tt.authenticateURL)
|
||||
a := &Authenticate{
|
||||
RedirectURL: authURL,
|
||||
sessionStore: tt.session,
|
||||
cookieCipher: aead,
|
||||
encryptedEncoder: signer,
|
||||
provider: identity.NewAtomicAuthenticator(),
|
||||
state: newAtomicAuthenticateState(&authenticateState{
|
||||
redirectURL: authURL,
|
||||
sessionStore: tt.session,
|
||||
cookieCipher: aead,
|
||||
encryptedEncoder: signer,
|
||||
}),
|
||||
options: config.NewAtomicOptions(),
|
||||
provider: identity.NewAtomicAuthenticator(),
|
||||
}
|
||||
a.provider.Store(tt.provider)
|
||||
u, _ := url.Parse("/oauthGet")
|
||||
|
@ -360,7 +364,7 @@ func TestAuthenticate_OAuthCallback(t *testing.T) {
|
|||
// (nonce|timestamp|redirect_url|encrypt(redirect_url),mac(nonce,ts))
|
||||
b := []byte(fmt.Sprintf("%s|%d|%s", nonce, tt.ts, tt.extraMac))
|
||||
|
||||
enc := cryptutil.Encrypt(a.cookieCipher, []byte(tt.redirectURI), b)
|
||||
enc := cryptutil.Encrypt(a.state.Load().cookieCipher, []byte(tt.redirectURI), b)
|
||||
b = append(b, enc...)
|
||||
encodedState := base64.URLEncoding.EncodeToString(b)
|
||||
if tt.extraState != "" {
|
||||
|
@ -466,13 +470,14 @@ func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) {
|
|||
t.Fatal(err)
|
||||
}
|
||||
a := Authenticate{
|
||||
sharedKey: cryptutil.NewBase64Key(),
|
||||
cookieSecret: cryptutil.NewKey(),
|
||||
RedirectURL: uriParseHelper("https://authenticate.corp.beyondperimeter.com"),
|
||||
sessionStore: tt.session,
|
||||
cookieCipher: aead,
|
||||
encryptedEncoder: signer,
|
||||
sharedEncoder: signer,
|
||||
state: newAtomicAuthenticateState(&authenticateState{
|
||||
cookieSecret: cryptutil.NewKey(),
|
||||
redirectURL: uriParseHelper("https://authenticate.corp.beyondperimeter.com"),
|
||||
sessionStore: tt.session,
|
||||
cookieCipher: aead,
|
||||
encryptedEncoder: signer,
|
||||
sharedEncoder: signer,
|
||||
}),
|
||||
dataBrokerClient: mockDataBrokerServiceClient{
|
||||
get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) {
|
||||
data, err := ptypes.MarshalAny(&session.Session{
|
||||
|
@ -492,6 +497,7 @@ func TestAuthenticate_SessionValidatorMiddleware(t *testing.T) {
|
|||
}, nil
|
||||
},
|
||||
},
|
||||
options: config.NewAtomicOptions(),
|
||||
provider: identity.NewAtomicAuthenticator(),
|
||||
}
|
||||
a.provider.Store(tt.provider)
|
||||
|
@ -543,6 +549,7 @@ func TestJwksEndpoint(t *testing.T) {
|
|||
auth, err := New(&config.Config{Options: o})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return
|
||||
}
|
||||
h := auth.Handler()
|
||||
if h == nil {
|
||||
|
@ -554,7 +561,7 @@ func TestJwksEndpoint(t *testing.T) {
|
|||
h.ServeHTTP(rr, req)
|
||||
body := rr.Body.String()
|
||||
expected := `{"keys":[{"use":"sig","kty":"EC","kid":"5b419ade1895fec2d2def6cd33b1b9a018df60db231dc5ecb85cbed6d942813c","crv":"P-256","alg":"ES256","x":"UG5xCP0JTT1H6Iol8jKuTIPVLM04CgW9PlEypNRmWlo","y":"KChF0fR09zm884ymInM29PtSsFdnzExNfLsP-ta1AgQ"}]}`
|
||||
assert.Equal(t, body, expected)
|
||||
assert.Equal(t, expected, body)
|
||||
}
|
||||
func TestAuthenticate_Dashboard(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
@ -582,10 +589,12 @@ func TestAuthenticate_Dashboard(t *testing.T) {
|
|||
t.Fatal(err)
|
||||
}
|
||||
a := &Authenticate{
|
||||
sessionStore: tt.sessionStore,
|
||||
encryptedEncoder: signer,
|
||||
sharedEncoder: signer,
|
||||
templates: template.Must(frontend.NewTemplates()),
|
||||
state: newAtomicAuthenticateState(&authenticateState{
|
||||
sessionStore: tt.sessionStore,
|
||||
encryptedEncoder: signer,
|
||||
sharedEncoder: signer,
|
||||
}),
|
||||
templates: template.Must(frontend.NewTemplates()),
|
||||
dataBrokerClient: mockDataBrokerServiceClient{
|
||||
get: func(ctx context.Context, in *databroker.GetRequest, opts ...grpc.CallOption) (*databroker.GetResponse, error) {
|
||||
data, err := ptypes.MarshalAny(&session.Session{
|
||||
|
|
128
authenticate/state.go
Normal file
128
authenticate/state.go
Normal file
|
@ -0,0 +1,128 @@
|
|||
package authenticate
|
||||
|
||||
import (
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sync/atomic"
|
||||
|
||||
"gopkg.in/square/go-jose.v2"
|
||||
|
||||
"github.com/pomerium/pomerium/config"
|
||||
"github.com/pomerium/pomerium/internal/encoding"
|
||||
"github.com/pomerium/pomerium/internal/encoding/ecjson"
|
||||
"github.com/pomerium/pomerium/internal/encoding/jws"
|
||||
"github.com/pomerium/pomerium/internal/httputil"
|
||||
"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"
|
||||
"github.com/pomerium/pomerium/pkg/cryptutil"
|
||||
)
|
||||
|
||||
type authenticateState struct {
|
||||
redirectURL *url.URL
|
||||
// administrators keeps track of administrator users.
|
||||
administrators map[string]struct{}
|
||||
// sharedEncoder is the encoder to use to serialize data to be consumed
|
||||
// by other services
|
||||
sharedEncoder encoding.MarshalUnmarshaler
|
||||
// cookieSecret is the secret to encrypt and authenticate session data
|
||||
cookieSecret []byte
|
||||
// cookieCipher is the cipher to use to encrypt/decrypt session data
|
||||
cookieCipher cipher.AEAD
|
||||
// encryptedEncoder is the encoder used to marshal and unmarshal session data
|
||||
encryptedEncoder encoding.MarshalUnmarshaler
|
||||
// sessionStore is the session store used to persist a user's session
|
||||
sessionStore sessions.SessionStore
|
||||
// sessionLoaders are a collection of session loaders to attempt to pull
|
||||
// a user's session state from
|
||||
sessionLoaders []sessions.SessionLoader
|
||||
|
||||
jwk *jose.JSONWebKeySet
|
||||
}
|
||||
|
||||
func newAuthenticateState() *authenticateState {
|
||||
return &authenticateState{
|
||||
administrators: map[string]struct{}{},
|
||||
jwk: new(jose.JSONWebKeySet),
|
||||
}
|
||||
}
|
||||
|
||||
func newAuthenticateStateFromConfig(cfg *config.Config) (*authenticateState, error) {
|
||||
state := &authenticateState{}
|
||||
|
||||
state.redirectURL, _ = urlutil.DeepCopy(cfg.Options.AuthenticateURL)
|
||||
state.redirectURL.Path = cfg.Options.AuthenticateCallbackPath
|
||||
|
||||
state.administrators = make(map[string]struct{}, len(cfg.Options.Administrators))
|
||||
for _, admin := range cfg.Options.Administrators {
|
||||
state.administrators[admin] = struct{}{}
|
||||
}
|
||||
|
||||
// shared state encoder setup
|
||||
var err error
|
||||
state.sharedEncoder, err = jws.NewHS256Signer([]byte(cfg.Options.SharedKey), cfg.Options.GetAuthenticateURL().Host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// private state encoder setup, used to encrypt oauth2 tokens
|
||||
state.cookieSecret, _ = base64.StdEncoding.DecodeString(cfg.Options.CookieSecret)
|
||||
state.cookieCipher, _ = cryptutil.NewAEADCipher(state.cookieSecret)
|
||||
state.encryptedEncoder = ecjson.New(state.cookieCipher)
|
||||
|
||||
qpStore := queryparam.NewStore(state.encryptedEncoder, urlutil.QueryProgrammaticToken)
|
||||
headerStore := header.NewStore(state.encryptedEncoder, httputil.AuthorizationTypePomerium)
|
||||
|
||||
cookieStore, err := cookie.NewStore(func() cookie.Options {
|
||||
return cookie.Options{
|
||||
Name: cfg.Options.CookieName,
|
||||
Domain: cfg.Options.CookieDomain,
|
||||
Secure: cfg.Options.CookieSecure,
|
||||
HTTPOnly: cfg.Options.CookieHTTPOnly,
|
||||
Expire: cfg.Options.CookieExpire,
|
||||
}
|
||||
}, state.sharedEncoder)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
state.sessionStore = cookieStore
|
||||
state.sessionLoaders = []sessions.SessionLoader{qpStore, headerStore, cookieStore}
|
||||
|
||||
state.jwk = new(jose.JSONWebKeySet)
|
||||
if cfg.Options.SigningKey != "" {
|
||||
decodedCert, err := base64.StdEncoding.DecodeString(cfg.Options.SigningKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authenticate: failed to decode signing key: %w", err)
|
||||
}
|
||||
jwk, err := cryptutil.PublicJWKFromBytes(decodedCert, jose.ES256)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("authenticate: failed to convert jwks: %w", err)
|
||||
}
|
||||
state.jwk.Keys = append(state.jwk.Keys, *jwk)
|
||||
}
|
||||
|
||||
return state, nil
|
||||
}
|
||||
|
||||
type atomicAuthenticateState struct {
|
||||
atomic.Value
|
||||
}
|
||||
|
||||
func newAtomicAuthenticateState(state *authenticateState) *atomicAuthenticateState {
|
||||
aas := new(atomicAuthenticateState)
|
||||
aas.Store(state)
|
||||
return aas
|
||||
}
|
||||
|
||||
func (aas *atomicAuthenticateState) Load() *authenticateState {
|
||||
return aas.Value.Load().(*authenticateState)
|
||||
}
|
||||
|
||||
func (aas *atomicAuthenticateState) Store(state *authenticateState) {
|
||||
aas.Value.Store(state)
|
||||
}
|
|
@ -14,7 +14,6 @@ func NewAEADCipher(secret []byte) (cipher.AEAD, error) {
|
|||
return nil, fmt.Errorf("cryptutil: got %d bytes but want 32", len(secret))
|
||||
}
|
||||
return chacha20poly1305.NewX(secret)
|
||||
|
||||
}
|
||||
|
||||
// NewAEADCipherFromBase64 takes a base64 encoded secret key and returns a new XChacha20poly1305 cipher.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue