Move cookie to pkg/encryption

This commit is contained in:
Joel Speed 2019-05-24 17:06:48 +01:00
parent 8027cc454e
commit d1ef14becc
No known key found for this signature in database
GPG Key ID: 6E80578D6751DEFB
14 changed files with 43 additions and 45 deletions

View File

@ -14,9 +14,9 @@ import (
"time" "time"
"github.com/mbland/hmacauth" "github.com/mbland/hmacauth"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/logger" "github.com/pusher/oauth2_proxy/logger"
sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions" sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/encryption"
"github.com/pusher/oauth2_proxy/providers" "github.com/pusher/oauth2_proxy/providers"
"github.com/yhat/wsutil" "github.com/yhat/wsutil"
) )
@ -555,7 +555,7 @@ func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
// OAuthStart starts the OAuth2 authentication flow // OAuthStart starts the OAuth2 authentication flow
func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) { func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) {
nonce, err := cookie.Nonce() nonce, err := encryption.Nonce()
if err != nil { if err != nil {
logger.Printf("Error obtaining nonce: %s", err.Error()) logger.Printf("Error obtaining nonce: %s", err.Error())
p.ErrorPage(rw, 500, "Internal Error", err.Error()) p.ErrorPage(rw, 500, "Internal Error", err.Error())

View File

@ -17,10 +17,10 @@ import (
oidc "github.com/coreos/go-oidc" oidc "github.com/coreos/go-oidc"
"github.com/dgrijalva/jwt-go" "github.com/dgrijalva/jwt-go"
"github.com/mbland/hmacauth" "github.com/mbland/hmacauth"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/logger" "github.com/pusher/oauth2_proxy/logger"
"github.com/pusher/oauth2_proxy/pkg/apis/options" "github.com/pusher/oauth2_proxy/pkg/apis/options"
sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions" sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/encryption"
"github.com/pusher/oauth2_proxy/pkg/sessions" "github.com/pusher/oauth2_proxy/pkg/sessions"
"github.com/pusher/oauth2_proxy/providers" "github.com/pusher/oauth2_proxy/providers"
"gopkg.in/natefinch/lumberjack.v2" "gopkg.in/natefinch/lumberjack.v2"
@ -268,7 +268,7 @@ func (o *Options) Validate() error {
} }
msgs = parseProviderInfo(o, msgs) msgs = parseProviderInfo(o, msgs)
var cipher *cookie.Cipher var cipher *encryption.Cipher
if o.PassAccessToken || o.SetAuthorization || o.PassAuthorization || (o.CookieRefresh != time.Duration(0)) { if o.PassAccessToken || o.SetAuthorization || o.PassAuthorization || (o.CookieRefresh != time.Duration(0)) {
validCookieSecretSize := false validCookieSecretSize := false
for _, i := range []int{16, 24, 32} { for _, i := range []int{16, 24, 32} {
@ -293,7 +293,7 @@ func (o *Options) Validate() error {
len(secretBytes(o.CookieSecret)), suffix)) len(secretBytes(o.CookieSecret)), suffix))
} else { } else {
var err error var err error
cipher, err = cookie.NewCipher(secretBytes(o.CookieSecret)) cipher, err = encryption.NewCipher(secretBytes(o.CookieSecret))
if err != nil { if err != nil {
msgs = append(msgs, fmt.Sprintf("cookie-secret error: %v", err)) msgs = append(msgs, fmt.Sprintf("cookie-secret error: %v", err))
} }

View File

@ -1,13 +1,11 @@
package options package options
import ( import "github.com/pusher/oauth2_proxy/pkg/encryption"
"github.com/pusher/oauth2_proxy/cookie"
)
// SessionOptions contains configuration options for the SessionStore providers. // SessionOptions contains configuration options for the SessionStore providers.
type SessionOptions struct { type SessionOptions struct {
Type string `flag:"session-store-type" cfg:"session_store_type" env:"OAUTH2_PROXY_SESSION_STORE_TYPE"` Type string `flag:"session-store-type" cfg:"session_store_type" env:"OAUTH2_PROXY_SESSION_STORE_TYPE"`
Cipher *cookie.Cipher Cipher *encryption.Cipher
CookieStoreOptions CookieStoreOptions
RedisStoreOptions RedisStoreOptions
} }

View File

@ -7,7 +7,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/pusher/oauth2_proxy/cookie" "github.com/pusher/oauth2_proxy/pkg/encryption"
) )
// SessionState is used to store information about the currently authenticated user session // SessionState is used to store information about the currently authenticated user session
@ -66,7 +66,7 @@ func (s *SessionState) String() string {
} }
// EncodeSessionState returns string representation of the current session // EncodeSessionState returns string representation of the current session
func (s *SessionState) EncodeSessionState(c *cookie.Cipher) (string, error) { func (s *SessionState) EncodeSessionState(c *encryption.Cipher) (string, error) {
var ss SessionState var ss SessionState
if c == nil { if c == nil {
// Store only Email and User when cipher is unavailable // Store only Email and User when cipher is unavailable
@ -133,7 +133,7 @@ func legacyDecodeSessionStatePlain(v string) (*SessionState, error) {
// legacyDecodeSessionState attempts to decode the session state string // legacyDecodeSessionState attempts to decode the session state string
// generated by v3.1.0 or older // generated by v3.1.0 or older
func legacyDecodeSessionState(v string, c *cookie.Cipher) (*SessionState, error) { func legacyDecodeSessionState(v string, c *encryption.Cipher) (*SessionState, error) {
chunks := strings.Split(v, "|") chunks := strings.Split(v, "|")
if c == nil { if c == nil {
@ -176,7 +176,7 @@ func legacyDecodeSessionState(v string, c *cookie.Cipher) (*SessionState, error)
} }
// DecodeSessionState decodes the session cookie string into a SessionState // DecodeSessionState decodes the session cookie string into a SessionState
func DecodeSessionState(v string, c *cookie.Cipher) (*SessionState, error) { func DecodeSessionState(v string, c *encryption.Cipher) (*SessionState, error) {
var ssj SessionStateJSON var ssj SessionStateJSON
var ss *SessionState var ss *SessionState
err := json.Unmarshal([]byte(v), &ssj) err := json.Unmarshal([]byte(v), &ssj)

View File

@ -5,8 +5,8 @@ import (
"testing" "testing"
"time" "time"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions" "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/encryption"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -14,9 +14,9 @@ const secret = "0123456789abcdefghijklmnopqrstuv"
const altSecret = "0000000000abcdefghijklmnopqrstuv" const altSecret = "0000000000abcdefghijklmnopqrstuv"
func TestSessionStateSerialization(t *testing.T) { func TestSessionStateSerialization(t *testing.T) {
c, err := cookie.NewCipher([]byte(secret)) c, err := encryption.NewCipher([]byte(secret))
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
c2, err := cookie.NewCipher([]byte(altSecret)) c2, err := encryption.NewCipher([]byte(altSecret))
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
s := &sessions.SessionState{ s := &sessions.SessionState{
Email: "user@domain.com", Email: "user@domain.com",
@ -54,9 +54,9 @@ func TestSessionStateSerialization(t *testing.T) {
} }
func TestSessionStateSerializationWithUser(t *testing.T) { func TestSessionStateSerializationWithUser(t *testing.T) {
c, err := cookie.NewCipher([]byte(secret)) c, err := encryption.NewCipher([]byte(secret))
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
c2, err := cookie.NewCipher([]byte(altSecret)) c2, err := encryption.NewCipher([]byte(altSecret))
assert.Equal(t, nil, err) assert.Equal(t, nil, err)
s := &sessions.SessionState{ s := &sessions.SessionState{
User: "just-user", User: "just-user",
@ -146,7 +146,7 @@ func TestExpired(t *testing.T) {
type testCase struct { type testCase struct {
sessions.SessionState sessions.SessionState
Encoded string Encoded string
Cipher *cookie.Cipher Cipher *encryption.Cipher
Error bool Error bool
} }
@ -203,7 +203,7 @@ func TestDecodeSessionState(t *testing.T) {
eString := string(eJSON) eString := string(eJSON)
eUnix := e.Unix() eUnix := e.Unix()
c, err := cookie.NewCipher([]byte(secret)) c, err := encryption.NewCipher([]byte(secret))
assert.NoError(t, err) assert.NoError(t, err)
testCases := []testCase{ testCases := []testCase{

View File

@ -1,4 +1,4 @@
package cookie package encryption
import ( import (
"crypto/aes" "crypto/aes"

View File

@ -1,4 +1,4 @@
package cookie package encryption
import ( import (
"encoding/base64" "encoding/base64"

View File

@ -1,4 +1,4 @@
package cookie package encryption
import ( import (
"crypto/rand" "crypto/rand"

View File

@ -8,10 +8,10 @@ import (
"strings" "strings"
"time" "time"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/options" "github.com/pusher/oauth2_proxy/pkg/apis/options"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions" "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/cookies" "github.com/pusher/oauth2_proxy/pkg/cookies"
"github.com/pusher/oauth2_proxy/pkg/encryption"
"github.com/pusher/oauth2_proxy/pkg/sessions/utils" "github.com/pusher/oauth2_proxy/pkg/sessions/utils"
) )
@ -28,7 +28,7 @@ var _ sessions.SessionStore = &SessionStore{}
// interface that stores sessions in client side cookies // interface that stores sessions in client side cookies
type SessionStore struct { type SessionStore struct {
CookieOptions *options.CookieOptions CookieOptions *options.CookieOptions
CookieCipher *cookie.Cipher CookieCipher *encryption.Cipher
} }
// Save takes a sessions.SessionState and stores the information from it // Save takes a sessions.SessionState and stores the information from it
@ -53,7 +53,7 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
// always http.ErrNoCookie // always http.ErrNoCookie
return nil, fmt.Errorf("Cookie %q not present", s.CookieOptions.CookieName) return nil, fmt.Errorf("Cookie %q not present", s.CookieOptions.CookieName)
} }
val, _, ok := cookie.Validate(c, s.CookieOptions.CookieSecret, s.CookieOptions.CookieExpire) val, _, ok := encryption.Validate(c, s.CookieOptions.CookieSecret, s.CookieOptions.CookieExpire)
if !ok { if !ok {
return nil, errors.New("Cookie Signature not valid") return nil, errors.New("Cookie Signature not valid")
} }
@ -96,7 +96,7 @@ func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Reques
// authentication details // authentication details
func (s *SessionStore) makeSessionCookie(req *http.Request, value string, now time.Time) []*http.Cookie { func (s *SessionStore) makeSessionCookie(req *http.Request, value string, now time.Time) []*http.Cookie {
if value != "" { if value != "" {
value = cookie.SignedValue(s.CookieOptions.CookieSecret, s.CookieOptions.CookieName, value, now) value = encryption.SignedValue(s.CookieOptions.CookieSecret, s.CookieOptions.CookieName, value, now)
} }
c := s.makeCookie(req, s.CookieOptions.CookieName, value, s.CookieOptions.CookieExpire, now) c := s.makeCookie(req, s.CookieOptions.CookieName, value, s.CookieOptions.CookieExpire, now)
if len(c.Value) > 4096-len(s.CookieOptions.CookieName) { if len(c.Value) > 4096-len(s.CookieOptions.CookieName) {

View File

@ -13,10 +13,10 @@ import (
"time" "time"
"github.com/go-redis/redis" "github.com/go-redis/redis"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/options" "github.com/pusher/oauth2_proxy/pkg/apis/options"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions" "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/cookies" "github.com/pusher/oauth2_proxy/pkg/cookies"
"github.com/pusher/oauth2_proxy/pkg/encryption"
) )
// TicketData is a structure representing the ticket used in server session storage // TicketData is a structure representing the ticket used in server session storage
@ -28,7 +28,7 @@ type TicketData struct {
// SessionStore is an implementation of the sessions.SessionStore // SessionStore is an implementation of the sessions.SessionStore
// interface that stores sessions in redis // interface that stores sessions in redis
type SessionStore struct { type SessionStore struct {
CookieCipher *cookie.Cipher CookieCipher *encryption.Cipher
CookieOptions *options.CookieOptions CookieOptions *options.CookieOptions
Client *redis.Client Client *redis.Client
} }
@ -106,7 +106,7 @@ func (store *SessionStore) Load(req *http.Request) (*sessions.SessionState, erro
return nil, fmt.Errorf("error loading session: %s", err) return nil, fmt.Errorf("error loading session: %s", err)
} }
val, _, ok := cookie.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire) val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
if !ok { if !ok {
return nil, fmt.Errorf("Cookie Signature not valid") return nil, fmt.Errorf("Cookie Signature not valid")
} }
@ -166,7 +166,7 @@ func (store *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) erro
return fmt.Errorf("error retrieving cookie: %v", err) return fmt.Errorf("error retrieving cookie: %v", err)
} }
val, _, ok := cookie.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire) val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
if !ok { if !ok {
return fmt.Errorf("Cookie Signature not valid") return fmt.Errorf("Cookie Signature not valid")
} }
@ -186,7 +186,7 @@ func (store *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) erro
// makeCookie makes a cookie, signing the value if present // makeCookie makes a cookie, signing the value if present
func (store *SessionStore) makeCookie(req *http.Request, value string, expires time.Duration, now time.Time) *http.Cookie { func (store *SessionStore) makeCookie(req *http.Request, value string, expires time.Duration, now time.Time) *http.Cookie {
if value != "" { if value != "" {
value = cookie.SignedValue(store.CookieOptions.CookieSecret, store.CookieOptions.CookieName, value, now) value = encryption.SignedValue(store.CookieOptions.CookieSecret, store.CookieOptions.CookieName, value, now)
} }
return cookies.MakeCookieFromOptions( return cookies.MakeCookieFromOptions(
req, req,
@ -230,7 +230,7 @@ func (store *SessionStore) getTicket(requestCookie *http.Cookie) (*TicketData, e
} }
// An existing cookie exists, try to retrieve the ticket // An existing cookie exists, try to retrieve the ticket
val, _, ok := cookie.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire) val, _, ok := encryption.Validate(requestCookie, store.CookieOptions.CookieSecret, store.CookieOptions.CookieExpire)
if !ok { if !ok {
// Cookie is invalid, create a new ticket // Cookie is invalid, create a new ticket
return newTicket() return newTicket()

View File

@ -13,10 +13,10 @@ import (
"github.com/alicebob/miniredis" "github.com/alicebob/miniredis"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/options" "github.com/pusher/oauth2_proxy/pkg/apis/options"
sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions" sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/cookies" "github.com/pusher/oauth2_proxy/pkg/cookies"
"github.com/pusher/oauth2_proxy/pkg/encryption"
"github.com/pusher/oauth2_proxy/pkg/sessions" "github.com/pusher/oauth2_proxy/pkg/sessions"
sessionscookie "github.com/pusher/oauth2_proxy/pkg/sessions/cookie" sessionscookie "github.com/pusher/oauth2_proxy/pkg/sessions/cookie"
"github.com/pusher/oauth2_proxy/pkg/sessions/redis" "github.com/pusher/oauth2_proxy/pkg/sessions/redis"
@ -158,7 +158,7 @@ var _ = Describe("NewSessionStore", func() {
BeforeEach(func() { BeforeEach(func() {
By("Using a valid cookie with a different providers session encoding") By("Using a valid cookie with a different providers session encoding")
broken := "BrokenSessionFromADifferentSessionImplementation" broken := "BrokenSessionFromADifferentSessionImplementation"
value := cookie.SignedValue(cookieOpts.CookieSecret, cookieOpts.CookieName, broken, time.Now()) value := encryption.SignedValue(cookieOpts.CookieSecret, cookieOpts.CookieName, broken, time.Now())
cookie := cookies.MakeCookieFromOptions(request, cookieOpts.CookieName, value, cookieOpts, cookieOpts.CookieExpire, time.Now()) cookie := cookies.MakeCookieFromOptions(request, cookieOpts.CookieName, value, cookieOpts, cookieOpts.CookieExpire, time.Now())
request.AddCookie(cookie) request.AddCookie(cookie)
@ -354,7 +354,7 @@ var _ = Describe("NewSessionStore", func() {
_, err := rand.Read(secret) _, err := rand.Read(secret)
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
cookieOpts.CookieSecret = base64.URLEncoding.EncodeToString(secret) cookieOpts.CookieSecret = base64.URLEncoding.EncodeToString(secret)
cipher, err := cookie.NewCipher(utils.SecretBytes(cookieOpts.CookieSecret)) cipher, err := encryption.NewCipher(utils.SecretBytes(cookieOpts.CookieSecret))
Expect(err).ToNot(HaveOccurred()) Expect(err).ToNot(HaveOccurred())
Expect(cipher).ToNot(BeNil()) Expect(cipher).ToNot(BeNil())
opts.Cipher = cipher opts.Cipher = cipher

View File

@ -3,17 +3,17 @@ package utils
import ( import (
"encoding/base64" "encoding/base64"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions" "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/encryption"
) )
// CookieForSession serializes a session state for storage in a cookie // CookieForSession serializes a session state for storage in a cookie
func CookieForSession(s *sessions.SessionState, c *cookie.Cipher) (string, error) { func CookieForSession(s *sessions.SessionState, c *encryption.Cipher) (string, error) {
return s.EncodeSessionState(c) return s.EncodeSessionState(c)
} }
// SessionFromCookie deserializes a session from a cookie value // SessionFromCookie deserializes a session from a cookie value
func SessionFromCookie(v string, c *cookie.Cipher) (s *sessions.SessionState, err error) { func SessionFromCookie(v string, c *encryption.Cipher) (s *sessions.SessionState, err error) {
return sessions.DecodeSessionState(v, c) return sessions.DecodeSessionState(v, c)
} }

View File

@ -10,8 +10,8 @@ import (
"net/url" "net/url"
"time" "time"
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions" "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/encryption"
) )
// Redeem provides a default implementation of the OAuth2 token redemption process // Redeem provides a default implementation of the OAuth2 token redemption process
@ -96,12 +96,12 @@ func (p *ProviderData) GetLoginURL(redirectURI, state string) string {
} }
// CookieForSession serializes a session state for storage in a cookie // CookieForSession serializes a session state for storage in a cookie
func (p *ProviderData) CookieForSession(s *sessions.SessionState, c *cookie.Cipher) (string, error) { func (p *ProviderData) CookieForSession(s *sessions.SessionState, c *encryption.Cipher) (string, error) {
return s.EncodeSessionState(c) return s.EncodeSessionState(c)
} }
// SessionFromCookie deserializes a session from a cookie value // SessionFromCookie deserializes a session from a cookie value
func (p *ProviderData) SessionFromCookie(v string, c *cookie.Cipher) (s *sessions.SessionState, err error) { func (p *ProviderData) SessionFromCookie(v string, c *encryption.Cipher) (s *sessions.SessionState, err error) {
return sessions.DecodeSessionState(v, c) return sessions.DecodeSessionState(v, c)
} }

View File

@ -1,8 +1,8 @@
package providers package providers
import ( import (
"github.com/pusher/oauth2_proxy/cookie"
"github.com/pusher/oauth2_proxy/pkg/apis/sessions" "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
"github.com/pusher/oauth2_proxy/pkg/encryption"
) )
// Provider represents an upstream identity provider implementation // Provider represents an upstream identity provider implementation
@ -15,8 +15,8 @@ type Provider interface {
ValidateSessionState(*sessions.SessionState) bool ValidateSessionState(*sessions.SessionState) bool
GetLoginURL(redirectURI, finalRedirect string) string GetLoginURL(redirectURI, finalRedirect string) string
RefreshSessionIfNeeded(*sessions.SessionState) (bool, error) RefreshSessionIfNeeded(*sessions.SessionState) (bool, error)
SessionFromCookie(string, *cookie.Cipher) (*sessions.SessionState, error) SessionFromCookie(string, *encryption.Cipher) (*sessions.SessionState, error)
CookieForSession(*sessions.SessionState, *cookie.Cipher) (string, error) CookieForSession(*sessions.SessionState, *encryption.Cipher) (string, error)
} }
// New provides a new Provider based on the configured provider string // New provides a new Provider based on the configured provider string