Skip to content

Add oidc pkce support #183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ OIDC Provider:
--providers.oidc.client-id= Client ID [$PROVIDERS_OIDC_CLIENT_ID]
--providers.oidc.client-secret= Client Secret [$PROVIDERS_OIDC_CLIENT_SECRET]
--providers.oidc.resource= Optional resource indicator [$PROVIDERS_OIDC_RESOURCE]
--providers.oidc.pkce_required= Optional pkce required indicator [$PROVIDERS_OIDC_PKCE_REQUIRED]

Generic OAuth2 Provider:
--providers.generic-oauth.auth-url= Auth/Login URL [$PROVIDERS_GENERIC_OAUTH_AUTH_URL]
Expand Down
6 changes: 1 addition & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,22 @@ require (
require (
github.com/containous/alice v0.0.0-20181107144136-d83ebdd94cbd // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/gorilla/mux v1.8.1 // indirect
github.com/gravitational/trace v1.4.0 // indirect
github.com/jonboulle/clockwork v0.4.0 // indirect
github.com/miekg/dns v1.1.59 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/pquerna/cachecontrol v0.2.0 // indirect
github.com/stretchr/objx v0.5.1 // indirect
github.com/traefik/paerser v0.2.0 // indirect
github.com/vulcand/predicate v1.2.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/term v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/tools v0.21.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

Expand Down
56 changes: 13 additions & 43 deletions go.sum

Large diffs are not rendered by default.

88 changes: 88 additions & 0 deletions internal/cookie/cookie.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package cookie

import (
"errors"
"net/http"
"time"
)

// CookieStore interface defines methods for setting and getting cookies
type CookieStore interface {
SetCookie(name, value string, opts ...CookieOption)
GetCookie(name string) (string, error)
DeleteCookie(name string)
}

// CookieOption is a function type that modifies cookie attributes
type CookieOption func(*http.Cookie)

// WithMaxAge sets the max age of the cookie
func WithMaxAge(seconds int) CookieOption {
return func(c *http.Cookie) {
c.MaxAge = seconds
}
}

// WithSameSite sets the SameSite attribute of the cookie
func WithSameSite(v http.SameSite) CookieOption {
return func(c *http.Cookie) {
c.SameSite = v
}
}

// CookieStoreImpl is a concrete implementation of the CookieStore interface
type CookieStoreImpl struct {
writer http.ResponseWriter
request *http.Request
secure bool
}

// NewCookieStore creates a new instance of CookieStoreImpl
func NewCookieStore(w http.ResponseWriter, r *http.Request, secure bool) *CookieStoreImpl {
return &CookieStoreImpl{
writer: w,
request: r,
secure: secure,
}
}

// SetCookie sets a cookie with the given name, value, and attributes
func (c *CookieStoreImpl) SetCookie(name, value string, opts ...CookieOption) {
cookie := &http.Cookie{
Name: name,
Value: value,
Path: "/",
Secure: c.secure,
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
}

// Apply any provided options
for _, opt := range opts {
opt(cookie)
}

http.SetCookie(c.writer, cookie)
}

// DeleteCookie removes a cookie with the given name
func (c *CookieStoreImpl) DeleteCookie(name string) {
cookie := &http.Cookie{
Name: name,
Value: "",
Path: "/",
MaxAge: -1,
Expires: time.Unix(0, 0),
}

http.SetCookie(c.writer, cookie)
}

// GetCookie retrieves the value of the cookie with the given name
func (c *CookieStoreImpl) GetCookie(name string) (string, error) {
cookie, err := c.request.Cookie(name)
if err != nil {
return "", errors.New("cookie not found")
}
return cookie.Value, nil
}
78 changes: 78 additions & 0 deletions internal/pkce/verifier.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package pkce

import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"io"
)

// CodeVerifier represents a PKCE code verifier as defined in RFC 7636
type CodeVerifier struct {
Value string
}

const (
// MinVerifierLength is the minimum allowed length for a code verifier
MinVerifierLength = 32
// MaxVerifierLength is the maximum allowed length for a code verifier
MaxVerifierLength = 96
// DefaultVerifierLength is the default length for generated code verifiers
DefaultVerifierLength = 64
)

// CreateCodeVerifier generates a new code verifier with default length
func CreateCodeVerifier() (*CodeVerifier, error) {
return CreateCodeVerifierWithLength(DefaultVerifierLength)
}

// CreateCodeVerifierWithLength generates a new code verifier with specified length
func CreateCodeVerifierWithLength(length int) (*CodeVerifier, error) {
if length < MinVerifierLength || length > MaxVerifierLength {
return nil, fmt.Errorf("code verifier length must be between %d and %d", MinVerifierLength, MaxVerifierLength)
}

secureRandomString, err := generateSecureRandomString(length)
if err != nil {
return nil, fmt.Errorf("failed to create code verifier: %w", err)
}
return &CodeVerifier{Value: secureRandomString}, nil
}

// CreateCodeVerifierWithCode creates a code verifier from an existing code
func CreateCodeVerifierWithCode(code string) (*CodeVerifier, error) {
if len(code) < MinVerifierLength || len(code) > MaxVerifierLength {
return nil, fmt.Errorf("code verifier length must be between %d and %d", MinVerifierLength, MaxVerifierLength)
}
return &CodeVerifier{Value: code}, nil
}

// String returns the string representation of the code verifier
func (v *CodeVerifier) String() string {
return v.Value
}

// CodeChallengeS256 generates the S256 PKCE code challenge as defined in RFC 7636
func (v *CodeVerifier) CodeChallengeS256() string {
h := sha256.New()
h.Write([]byte(v.Value))
return encode(h.Sum(nil))
}

// GenerateNonce generates a cryptographically secure nonce
func GenerateNonce() (string, error) {
return generateSecureRandomString(DefaultVerifierLength)
}

func generateSecureRandomString(length int) (string, error) {
bytes := make([]byte, length)
if _, err := io.ReadFull(rand.Reader, bytes); err != nil {
return "", fmt.Errorf("failed to generate secure random string: %w", err)
}
return base64.RawURLEncoding.EncodeToString(bytes), nil
}

func encode(msg []byte) string {
return base64.RawURLEncoding.EncodeToString(msg)
}
7 changes: 4 additions & 3 deletions internal/provider/generic_oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"net/http"

"github.com/thomseddon/traefik-forward-auth/internal/cookie"
"golang.org/x/oauth2"
)

Expand Down Expand Up @@ -52,12 +53,12 @@ func (o *GenericOAuth) Setup() error {
}

// GetLoginURL provides the login url for the given redirect uri and state
func (o *GenericOAuth) GetLoginURL(redirectURI, state string) string {
return o.OAuthGetLoginURL(redirectURI, state)
func (o *GenericOAuth) GetLoginURL(redirectURI, state string, _ cookie.CookieStore) (string, error) {
return o.OAuthGetLoginURL(redirectURI, state), nil
}

// ExchangeCode exchanges the given redirect uri and code for a token
func (o *GenericOAuth) ExchangeCode(redirectURI, code string) (string, error) {
func (o *GenericOAuth) ExchangeCode(redirectURI, code string, _ cookie.CookieStore) (string, error) {
token, err := o.OAuthExchangeCode(redirectURI, code)
if err != nil {
return "", err
Expand Down
5 changes: 3 additions & 2 deletions internal/provider/generic_oauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ func TestGenericOAuthGetLoginURL(t *testing.T) {
}

// Check url
uri, err := url.Parse(p.GetLoginURL("http://example.com/_oauth", "state"))
loginURL, _ := p.GetLoginURL("http://example.com/_oauth", "state", nil)
uri, err := url.Parse(loginURL)
assert.Nil(err)
assert.Equal("https", uri.Scheme)
assert.Equal("provider.com", uri.Host)
Expand Down Expand Up @@ -104,7 +105,7 @@ func TestGenericOAuthExchangeCode(t *testing.T) {
// AuthStyleInHeader is attempted
p.Config.Endpoint.AuthStyle = oauth2.AuthStyleInParams

token, err := p.ExchangeCode("http://example.com/_oauth", "code")
token, err := p.ExchangeCode("http://example.com/_oauth", "code", nil)
assert.Nil(err)
assert.Equal("123456789", token)
}
Expand Down
8 changes: 5 additions & 3 deletions internal/provider/google.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"fmt"
"net/http"
"net/url"

"github.com/thomseddon/traefik-forward-auth/internal/cookie"
)

// Google provider
Expand Down Expand Up @@ -53,7 +55,7 @@ func (g *Google) Setup() error {
}

// GetLoginURL provides the login url for the given redirect uri and state
func (g *Google) GetLoginURL(redirectURI, state string) string {
func (g *Google) GetLoginURL(redirectURI, state string, _ cookie.CookieStore) (string, error) {
q := url.Values{}
q.Set("client_id", g.ClientID)
q.Set("response_type", "code")
Expand All @@ -68,11 +70,11 @@ func (g *Google) GetLoginURL(redirectURI, state string) string {
u = *g.LoginURL
u.RawQuery = q.Encode()

return u.String()
return u.String(), nil
}

// ExchangeCode exchanges the given redirect uri and code for a token
func (g *Google) ExchangeCode(redirectURI, code string) (string, error) {
func (g *Google) ExchangeCode(redirectURI, code string, _ cookie.CookieStore) (string, error) {
form := url.Values{}
form.Set("client_id", g.ClientID)
form.Set("client_secret", g.ClientSecret)
Expand Down
5 changes: 3 additions & 2 deletions internal/provider/google_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ func TestGoogleGetLoginURL(t *testing.T) {
}

// Check url
uri, err := url.Parse(p.GetLoginURL("http://example.com/_oauth", "state"))
loginUrl, _ := p.GetLoginURL("http://example.com/_oauth", "state", nil)
uri, err := url.Parse(loginUrl)
assert.Nil(err)
assert.Equal("https", uri.Scheme)
assert.Equal("google.com", uri.Host)
Expand Down Expand Up @@ -116,7 +117,7 @@ func TestGoogleExchangeCode(t *testing.T) {
},
}

token, err := p.ExchangeCode("http://example.com/_oauth", "code")
token, err := p.ExchangeCode("http://example.com/_oauth", "code", nil)
assert.Nil(err)
assert.Equal("123456789", token)
}
Expand Down
Loading