1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-02-09 13:46:51 +02:00
oauth2-proxy/pkg/sessions/redis/redis_store.go

204 lines
5.8 KiB
Go
Raw Normal View History

2019-05-09 16:09:22 -07:00
package redis
import (
"context"
"crypto/tls"
2019-11-07 11:04:40 +01:00
"crypto/x509"
2019-05-09 16:09:22 -07:00
"fmt"
2019-11-07 11:04:40 +01:00
"io/ioutil"
2019-05-09 16:09:22 -07:00
"time"
"github.com/go-redis/redis/v8"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/sessions/persistence"
2019-05-09 16:09:22 -07:00
)
// SessionStore is an implementation of the persistence.Store
2019-05-09 16:09:22 -07:00
// interface that stores sessions in redis
type SessionStore struct {
Client Client
2019-05-09 16:09:22 -07:00
}
// NewRedisSessionStore initialises a new instance of the SessionStore and wraps
// it in a persistence.Manager
2020-05-25 12:43:24 +01:00
func NewRedisSessionStore(opts *options.SessionOptions, cookieOpts *options.Cookie) (sessions.SessionStore, error) {
client, err := NewRedisClient(opts.Redis)
if err != nil {
return nil, fmt.Errorf("error constructing redis client: %v", err)
}
rs := &SessionStore{
Client: client,
}
return persistence.NewManager(rs, cookieOpts), nil
}
// Save takes a sessions.SessionState and stores the information from it
Add redis lock feature (#1063) * Add sensible logging flag to default setup for logger * Add Redis lock * Fix default value flag for sensitive logging * Split RefreshSessionIfNeeded in two methods and use Redis lock * Small adjustments to doc and code * Remove sensible logging * Fix method names in ticket.go * Revert "Fix method names in ticket.go" This reverts commit 408ba1a1a5c55a3cad507a0be8634af1977769cb. * Fix methods name in ticket.go * Remove block in Redis client get * Increase lock time to 1 second * Perform retries, if session store is locked * Reverse if condition, because it should return if session does not have to be refreshed * Update go.sum * Update MockStore * Return error if loading session fails * Fix and update tests * Change validSession to session in docs and strings * Change validSession to session in docs and strings * Fix docs * Fix wrong field name * Fix linting * Fix imports for linting * Revert changes except from locking functionality * Add lock feature on session state * Update from master * Remove errors package, because it is not used * Only pass context instead of request to lock * Use lock key * By default use NoOpLock * Remove debug output * Update ticket_test.go * Map internal error to sessions error * Add ErrLockNotObtained * Enable lock peek for all redis clients * Use lock key prefix consistent * Fix imports * Use exists method for peek lock * Fix imports * Fix imports * Fix imports * Remove own Dockerfile * Fix imports * Fix tests for ticket and session store * Fix session store test * Update pkg/apis/sessions/interfaces.go Co-authored-by: Joel Speed <Joel.speed@hotmail.co.uk> * Do not wrap lock method Co-authored-by: Joel Speed <Joel.speed@hotmail.co.uk> * Use errors package for lock constants * Use better naming for initLock function * Add comments * Add session store lock test * Fix tests * Fix tests * Fix tests * Fix tests * Add cookies after saving session * Add mock lock * Fix imports for mock_lock.go * Store mock lock for key * Apply elapsed time on mock lock * Check if lock is initially applied * Reuse existing lock * Test all lock methods * Update CHANGELOG.md * Use redis client methods in redis.lock for release an refresh * Use lock key suffix instead of prefix for lock key * Add comments for Lock interface * Update comment for Lock interface * Update CHANGELOG.md * Change LockSuffix to const * Check lock on already loaded session * Use global var for loadedSession in lock tests * Use lock instance for refreshing and releasing of lock * Update possible error type for Refresh Co-authored-by: Joel Speed <Joel.speed@hotmail.co.uk>
2021-06-02 20:08:19 +02:00
// to redis, and adds a new persistence cookie on the HTTP response writer
func (store *SessionStore) Save(ctx context.Context, key string, value []byte, exp time.Duration) error {
err := store.Client.Set(ctx, key, value, exp)
2019-05-09 16:09:22 -07:00
if err != nil {
return fmt.Errorf("error saving redis session: %v", err)
2019-05-09 16:09:22 -07:00
}
return nil
}
2019-05-09 16:09:22 -07:00
// Load reads sessions.SessionState information from a persistence
// cookie within the HTTP request object
func (store *SessionStore) Load(ctx context.Context, key string) ([]byte, error) {
value, err := store.Client.Get(ctx, key)
if err != nil {
return nil, fmt.Errorf("error loading redis session: %v", err)
2019-05-09 16:09:22 -07:00
}
return value, nil
}
2019-05-09 16:09:22 -07:00
// Clear clears any saved session information for a given persistence cookie
// from redis, and then clears the session
func (store *SessionStore) Clear(ctx context.Context, key string) error {
err := store.Client.Del(ctx, key)
if err != nil {
return fmt.Errorf("error clearing the session from redis: %v", err)
}
return nil
2019-05-09 16:09:22 -07:00
}
Add redis lock feature (#1063) * Add sensible logging flag to default setup for logger * Add Redis lock * Fix default value flag for sensitive logging * Split RefreshSessionIfNeeded in two methods and use Redis lock * Small adjustments to doc and code * Remove sensible logging * Fix method names in ticket.go * Revert "Fix method names in ticket.go" This reverts commit 408ba1a1a5c55a3cad507a0be8634af1977769cb. * Fix methods name in ticket.go * Remove block in Redis client get * Increase lock time to 1 second * Perform retries, if session store is locked * Reverse if condition, because it should return if session does not have to be refreshed * Update go.sum * Update MockStore * Return error if loading session fails * Fix and update tests * Change validSession to session in docs and strings * Change validSession to session in docs and strings * Fix docs * Fix wrong field name * Fix linting * Fix imports for linting * Revert changes except from locking functionality * Add lock feature on session state * Update from master * Remove errors package, because it is not used * Only pass context instead of request to lock * Use lock key * By default use NoOpLock * Remove debug output * Update ticket_test.go * Map internal error to sessions error * Add ErrLockNotObtained * Enable lock peek for all redis clients * Use lock key prefix consistent * Fix imports * Use exists method for peek lock * Fix imports * Fix imports * Fix imports * Remove own Dockerfile * Fix imports * Fix tests for ticket and session store * Fix session store test * Update pkg/apis/sessions/interfaces.go Co-authored-by: Joel Speed <Joel.speed@hotmail.co.uk> * Do not wrap lock method Co-authored-by: Joel Speed <Joel.speed@hotmail.co.uk> * Use errors package for lock constants * Use better naming for initLock function * Add comments * Add session store lock test * Fix tests * Fix tests * Fix tests * Fix tests * Add cookies after saving session * Add mock lock * Fix imports for mock_lock.go * Store mock lock for key * Apply elapsed time on mock lock * Check if lock is initially applied * Reuse existing lock * Test all lock methods * Update CHANGELOG.md * Use redis client methods in redis.lock for release an refresh * Use lock key suffix instead of prefix for lock key * Add comments for Lock interface * Update comment for Lock interface * Update CHANGELOG.md * Change LockSuffix to const * Check lock on already loaded session * Use global var for loadedSession in lock tests * Use lock instance for refreshing and releasing of lock * Update possible error type for Refresh Co-authored-by: Joel Speed <Joel.speed@hotmail.co.uk>
2021-06-02 20:08:19 +02:00
// Lock creates a lock object for sessions.SessionState
func (store *SessionStore) Lock(key string) sessions.Lock {
return store.Client.Lock(key)
}
// NewRedisClient makes a redis.Client (either standalone, sentinel aware, or
// redis cluster)
func NewRedisClient(opts options.RedisStoreOptions) (Client, error) {
if opts.UseSentinel && opts.UseCluster {
return nil, fmt.Errorf("options redis-use-sentinel and redis-use-cluster are mutually exclusive")
}
if opts.UseSentinel {
return buildSentinelClient(opts)
}
if opts.UseCluster {
return buildClusterClient(opts)
}
return buildStandaloneClient(opts)
}
// buildSentinelClient makes a redis.Client that connects to Redis Sentinel
// for Primary/Replica Redis node coordination
func buildSentinelClient(opts options.RedisStoreOptions) (Client, error) {
addrs, opt, err := parseRedisURLs(opts.SentinelConnectionURLs)
if err != nil {
return nil, fmt.Errorf("could not parse redis urls: %v", err)
}
if err := setupTLSConfig(opts, opt); err != nil {
return nil, err
}
client := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: opts.SentinelMasterName,
SentinelAddrs: addrs,
SentinelPassword: opts.SentinelPassword,
Password: opts.Password,
TLSConfig: opt.TLSConfig,
})
return newClient(client), nil
}
// buildClusterClient makes a redis.Client that is Redis Cluster aware
func buildClusterClient(opts options.RedisStoreOptions) (Client, error) {
addrs, opt, err := parseRedisURLs(opts.ClusterConnectionURLs)
if err != nil {
return nil, fmt.Errorf("could not parse redis urls: %v", err)
}
if err := setupTLSConfig(opts, opt); err != nil {
return nil, err
}
client := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: addrs,
Password: opts.Password,
TLSConfig: opt.TLSConfig,
})
return newClusterClient(client), nil
}
// buildStandaloneClient makes a redis.Client that connects to a simple
// Redis node
func buildStandaloneClient(opts options.RedisStoreOptions) (Client, error) {
opt, err := redis.ParseURL(opts.ConnectionURL)
if err != nil {
return nil, fmt.Errorf("unable to parse redis url: %s", err)
}
if opts.Password != "" {
opt.Password = opts.Password
}
if err := setupTLSConfig(opts, opt); err != nil {
return nil, err
}
client := redis.NewClient(opt)
return newClient(client), nil
}
// setupTLSConfig sets the TLSConfig if the TLS option is given in redis.Options
func setupTLSConfig(opts options.RedisStoreOptions, opt *redis.Options) error {
if opts.InsecureSkipTLSVerify {
if opt.TLSConfig == nil {
/* #nosec */
opt.TLSConfig = &tls.Config{}
}
2019-11-07 11:04:40 +01:00
opt.TLSConfig.InsecureSkipVerify = true
}
if opts.CAPath != "" {
rootCAs, err := x509.SystemCertPool()
if err != nil {
logger.Errorf("failed to load system cert pool for redis connection, falling back to empty cert pool")
}
2019-11-07 11:04:40 +01:00
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
certs, err := ioutil.ReadFile(opts.CAPath)
2019-11-07 11:04:40 +01:00
if err != nil {
return fmt.Errorf("failed to load %q, %v", opts.CAPath, err)
2019-11-07 11:04:40 +01:00
}
// Append our cert to the system pool
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
logger.Errorf("no certs appended, using system certs only")
2019-11-07 11:04:40 +01:00
}
if opt.TLSConfig == nil {
/* #nosec */
opt.TLSConfig = &tls.Config{}
}
2019-11-07 11:04:40 +01:00
opt.TLSConfig.RootCAs = rootCAs
}
return nil
}
// parseRedisURLs parses a list of redis urls and returns a list
// of addresses in the form of host:port and redis.Options that can be used to connect to Redis
func parseRedisURLs(urls []string) ([]string, *redis.Options, error) {
addrs := []string{}
var redisOptions *redis.Options
for _, u := range urls {
parsedURL, err := redis.ParseURL(u)
if err != nil {
return nil, nil, fmt.Errorf("unable to parse redis url: %v", err)
}
addrs = append(addrs, parsedURL.Addr)
redisOptions = parsedURL
}
return addrs, redisOptions, nil
}