1
0
mirror of https://github.com/oauth2-proxy/oauth2-proxy.git synced 2025-01-26 05:27:28 +02:00
oauth2-proxy/pkg/sessions/redis/redis_store.go
Kevin Kreitner f648c54d87
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 19:08:19 +01:00

171 lines
5.1 KiB
Go

package redis
import (
"context"
"crypto/x509"
"fmt"
"io/ioutil"
"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"
)
// SessionStore is an implementation of the persistence.Store
// interface that stores sessions in redis
type SessionStore struct {
Client Client
}
// NewRedisSessionStore initialises a new instance of the SessionStore and wraps
// it in a persistence.Manager
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
// 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)
if err != nil {
return fmt.Errorf("error saving redis session: %v", err)
}
return nil
}
// 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)
}
return value, nil
}
// 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
}
// 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, err := parseRedisURLs(opts.SentinelConnectionURLs)
if err != nil {
return nil, fmt.Errorf("could not parse redis urls: %v", err)
}
client := redis.NewFailoverClient(&redis.FailoverOptions{
MasterName: opts.SentinelMasterName,
SentinelAddrs: addrs,
SentinelPassword: opts.SentinelPassword,
Password: opts.Password,
})
return newClient(client), nil
}
// buildClusterClient makes a redis.Client that is Redis Cluster aware
func buildClusterClient(opts options.RedisStoreOptions) (Client, error) {
addrs, err := parseRedisURLs(opts.ClusterConnectionURLs)
if err != nil {
return nil, fmt.Errorf("could not parse redis urls: %v", err)
}
client := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: addrs,
Password: opts.Password,
})
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 opts.InsecureSkipTLSVerify {
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")
}
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
certs, err := ioutil.ReadFile(opts.CAPath)
if err != nil {
return nil, fmt.Errorf("failed to load %q, %v", opts.CAPath, err)
}
// Append our cert to the system pool
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
logger.Errorf("no certs appended, using system certs only")
}
opt.TLSConfig.RootCAs = rootCAs
}
client := redis.NewClient(opt)
return newClient(client), nil
}
// parseRedisURLs parses a list of redis urls and returns a list
// of addresses in the form of host:port that can be used to connect to Redis
func parseRedisURLs(urls []string) ([]string, error) {
addrs := []string{}
for _, u := range urls {
parsedURL, err := redis.ParseURL(u)
if err != nil {
return nil, fmt.Errorf("unable to parse redis url: %v", err)
}
addrs = append(addrs, parsedURL.Addr)
}
return addrs, nil
}