diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 6fbd41c..85e8d71 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -16,4 +16,4 @@ Please select relevant options: - [ ] I have added tests that prove my fix is effective or that my feature works - [ ] I have checked my code and corrected any misspellings -Reviewer: @stiviik +Reviewer: @nmeisenzahl diff --git a/Dockerfile b/Dockerfile index 53f2648..7d4aefe 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Builder -FROM golang:alpine AS builder +FROM golang:alpine as builder WORKDIR /app # Install git + SSL ca certificates. @@ -31,7 +31,7 @@ RUN go mod download RUN go mod verify # Build the binary. -RUN CGO_ENABLED=0 go build -a -installsuffix cgo -ldflags="-w -s" -o /go/bin/oidc-forward-auth +RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -ldflags="-w -s" -o /go/bin/oidc-forward-auth # Runner FROM scratch @@ -52,10 +52,10 @@ USER appuser:appuser ARG BUILD_DATE ARG VCS_REF -# Good docker practice -LABEL org.opencontainers.image.created=$BUILD_DATE \ - org.opencontainers.image.authors="StiviiK" \ - org.opencontainers.image.source="https://code.thetadev.de/ThetaDev/oidc-forward-auth" \ - org.opencontainers.image.revision=$VCS_REF +# Good docker practice, plus we get microbadger badges +LABEL org.label-schema.build-date=$BUILD_DATE \ + org.label-schema.vcs-url="https://github.com/StiviiK/oidc-forward-auth.git" \ + org.label-schema.vcs-ref=$VCS_REF \ + org.label-schema.schema-version="1.0" ENTRYPOINT ["/go/bin/oidc-forward-auth"] \ No newline at end of file diff --git a/go.mod b/go.mod index 721a60e..c0c5497 100644 --- a/go.mod +++ b/go.mod @@ -1,25 +1,14 @@ module github.com/StiviiK/keycloak-traefik-forward-auth -go 1.24 - -toolchain go1.24.2 +go 1.14 require ( github.com/caarlos0/env v3.5.0+incompatible - github.com/coreos/go-oidc/v3 v3.14.1 - github.com/google/uuid v1.6.0 - github.com/sirupsen/logrus v1.9.3 - golang.org/x/oauth2 v0.30.0 -) - -require ( - github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 // indirect - github.com/pzentenoe/go-cache v1.0.0 // indirect -) - -require ( - github.com/go-jose/go-jose/v4 v4.1.0 // indirect - github.com/tg123/go-htpasswd v1.2.4 - golang.org/x/crypto v0.38.0 // indirect - golang.org/x/sys v0.33.0 // indirect + github.com/coreos/go-oidc v2.2.1+incompatible + github.com/google/uuid v1.1.1 + github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 // indirect + github.com/sirupsen/logrus v1.6.0 + golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 // indirect + golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d + gopkg.in/square/go-jose.v2 v2.5.1 // indirect ) diff --git a/go.sum b/go.sum index e30aad2..a85c5b0 100644 --- a/go.sum +++ b/go.sum @@ -1,38 +1,37 @@ -github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5 h1:IEjq88XO4PuBDcvmjQJcQGg+w+UaafSy8G5Kcb5tBhI= -github.com/GehirnInc/crypt v0.0.0-20230320061759-8cc1b52080c5/go.mod h1:exZ0C/1emQJAw5tHOaUDyY1ycttqBAPcxuzf7QbY6ec= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/caarlos0/env v3.5.0+incompatible h1:Yy0UN8o9Wtr/jGHZDpCBLpNrzcFLLM2yixi/rBrKyJs= github.com/caarlos0/env v3.5.0+incompatible/go.mod h1:tdCsowwCzMLdkqRYDlHpZCp2UooDD3MspDBjZ2AD02Y= -github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= -github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/coreos/go-oidc v2.2.1+incompatible h1:mh48q/BqXqgjVHpy2ZY7WnWAbenxRjsz9N1i1YxjHAk= +github.com/coreos/go-oidc v2.2.1+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/go-jose/go-jose/v4 v4.1.0 h1:cYSYxd3pw5zd2FSXk2vGdn9igQU2PS8MuxrCOCl0FdY= -github.com/go-jose/go-jose/v4 v4.1.0/go.mod h1:GG/vqmYm3Von2nYiB2vGTXzdoNKE5tix5tuc6iAd+sw= -github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= -github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= -github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/pzentenoe/go-cache v1.0.0 h1:6jHsrh4CGKSBBmvNrEDn+EN9cJd4qOqLsHb7xWWEPBM= -github.com/pzentenoe/go-cache v1.0.0/go.mod h1:1JaNc73+p1tmcbNJwK55vtPR40h0hIoqqjlnhBZevBw= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= -github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= -github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/tg123/go-htpasswd v1.2.4 h1:HgH8KKCjdmo7jjXWN9k1nefPBd7Be3tFCTjc2jPraPU= -github.com/tg123/go-htpasswd v1.2.4/go.mod h1:EKThQok9xHkun6NBMynNv6Jmu24A33XdZzzl4Q7H1+0= -golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= -golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= -golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= -golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= -golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35 h1:J9b7z+QKAmPf4YLrFg6oQUotqHQeUNWwkvo7jZp1GLU= +github.com/pquerna/cachecontrol v0.0.0-20180517163645-1555304b9b35/go.mod h1:prYjPmNq4d1NPVmpShWobRqXY3q7Vp+80DqgxxUrUIA= +github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37 h1:cg5LA/zNPRzIXIWSCxQW10Rvpy94aQh3LT/ShoCpkHw= +golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 h1:0GoQqolDA55aaLxZyTzK/Y2ePZzZTUrRacwib7cNsYQ= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d h1:TzXSXBo42m9gQenoE3b9BGiEpg5IG2JkU5FkPIawgtw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +gopkg.in/square/go-jose.v2 v2.5.1 h1:7odma5RETjNHWJnR32wx8t+Io4djHE1PqxCFx3iiZ2w= +gopkg.in/square/go-jose.v2 v2.5.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= diff --git a/pkg/forwardauth/auth.go b/pkg/forwardauth/auth.go index 1d1d98a..13e38b5 100644 --- a/pkg/forwardauth/auth.go +++ b/pkg/forwardauth/auth.go @@ -44,22 +44,15 @@ func (fw *ForwardAuth) IsAuthenticated(context context.Context, logger *logrus.E var claims Claims logger = logger.WithField("FunctionSource", "IsAuthenticated") - // Check if we have a session cookie - cookie, err := fw.GetSessionCookie(r, options) + // Check if we have an Auth cookie + cookie, err := fw.GetAuthCookie(r) if err != nil { logger.Error(err.Error()) return &claims, err } - sessionId := cookie.Value - session := fw.SessionCache.Get(sessionId) - if session == nil { - err = errors.New("session not found") - return &claims, err - } - // check if the token is valid - idToken, err := fw.OidcVefifier.Verify(context, session.IDToken) + idToken, err := fw.OidcVefifier.Verify(context, cookie.Value) switch { case err == nil: // Token is valid @@ -72,24 +65,36 @@ func (fw *ForwardAuth) IsAuthenticated(context context.Context, logger *logrus.E } return &claims, nil + + // Todo: Updating the cookies does sadly not work here case strings.Contains(err.Error(), "expired"): // Token is expired logger.Info("Received expired token, trying to refesh it.") - result, err := fw.RefreshToken(context, session.RefreshToken) + refreshCookie, err := fw.GetRefreshAuthCookie(r) if err != nil { - fw.SessionCache.Delete(sessionId) logger.Error(err.Error()) return &claims, err } - newSession := SessionCacheItem{IDToken: result.IDToken, RefreshToken: result.RefreshToken} - fw.SessionCache.Update(sessionId, &newSession) + result, err := fw.RefreshToken(context, refreshCookie.Value) + if err != nil { + logger.Error(err.Error()) + return &claims, err + } + + http.SetCookie(w, fw.MakeAuthCookie(options, result)) + if len(result.RefreshToken) > 0 { // Do we have an refresh token? + http.SetCookie(w, fw.MakeRefreshAuthCookie(options, result)) + } return result.IDTokenClaims, nil - default: // Other error - fw.SessionCache.Delete(sessionId) + case err != nil: // Other error logger.Error(err.Error()) return &claims, err + + default: + logger.Error("default case, should not happen") + return &claims, errors.New("default case") } } diff --git a/pkg/forwardauth/cookies.go b/pkg/forwardauth/cookies.go index 3b7f61d..25ce666 100644 --- a/pkg/forwardauth/cookies.go +++ b/pkg/forwardauth/cookies.go @@ -24,17 +24,17 @@ func getBaseCookie(options *options.Options) *http.Cookie { } } -func (fw *ForwardAuth) MakeCSRFCookie(w http.ResponseWriter, r *http.Request, options *options.Options, state string) *http.Cookie { +func (fw *ForwardAuth) MakeCSRFCookie(w http.ResponseWriter, r *http.Request, options *options.Options, redirect string, state string) *http.Cookie { cookie := getBaseCookie(options) - cookie.Name = options.CookiePrefix + "csrf" - cookie.Value = fmt.Sprintf("%s|%s", fw.GetReturnUri(r), state) + cookie.Name = "__auth_csrf" + cookie.Value = fmt.Sprintf("%s|%s", redirect, state) cookie.Expires = time.Now().Local().Add(time.Hour) return cookie } -func (fw *ForwardAuth) ValidateCSRFCookie(r *http.Request, options *options.Options) (state string, redirect string, error error) { - csrfCookie, err := r.Cookie(options.CookiePrefix + "csrf") +func (fw *ForwardAuth) ValidateCSRFCookie(r *http.Request) (state string, redirect string, error error) { + csrfCookie, err := r.Cookie("__auth_csrf") if err != nil { return "", "", errors.New("Missing csrf cookie") } @@ -58,30 +58,49 @@ func (fw *ForwardAuth) ValidateCSRFCookie(r *http.Request, options *options.Opti func (fw *ForwardAuth) ClearCSRFCookie(options *options.Options) *http.Cookie { cookie := getBaseCookie(options) - cookie.Name = options.CookiePrefix + "csrf" + cookie.Name = "__auth_csrf" cookie.Expires = time.Now().Local().Add(time.Hour * -1) return cookie } -func (fw *ForwardAuth) MakeSessionCookie(options *options.Options, sessionId string) *http.Cookie { +func (fw *ForwardAuth) MakeAuthCookie(options *options.Options, authResult *AuthenticatationResult) *http.Cookie { cookie := getBaseCookie(options) - cookie.Name = options.CookiePrefix + "session" - cookie.Value = sessionId - if options.SessionLifetime > 0 { - cookie.Expires = time.Now().Local().Add(time.Hour * time.Duration(options.SessionLifetime)) - } + cookie.Name = "__auth" + cookie.Value = authResult.IDToken + cookie.Expires = time.Now().Local().Add(time.Hour * 24) return cookie } -func (fw *ForwardAuth) GetSessionCookie(r *http.Request, options *options.Options) (*http.Cookie, error) { - return r.Cookie(options.CookiePrefix + "session") +func (fw *ForwardAuth) GetAuthCookie(r *http.Request) (*http.Cookie, error) { + return r.Cookie("__auth") } -func (fw *ForwardAuth) ClearSessionCookie(options *options.Options) *http.Cookie { +func (fw *ForwardAuth) ClearAuthCookie(options *options.Options) *http.Cookie { cookie := getBaseCookie(options) - cookie.Name = options.CookiePrefix + "session" + cookie.Name = "__auth" + cookie.Expires = time.Now().Local().Add(time.Hour * -1) + + return cookie +} + +func (fw *ForwardAuth) MakeRefreshAuthCookie(options *options.Options, authResult *AuthenticatationResult) *http.Cookie { + cookie := getBaseCookie(options) + cookie.Name = "__auth_refresh" + cookie.Value = authResult.RefreshToken + cookie.Expires = time.Now().Local().Add(time.Hour * 24) + + return cookie +} + +func (fw *ForwardAuth) GetRefreshAuthCookie(r *http.Request) (*http.Cookie, error) { + return r.Cookie("__auth_refresh") +} + +func (fw *ForwardAuth) ClearRefreshAuthCookie(options *options.Options) *http.Cookie { + cookie := getBaseCookie(options) + cookie.Name = "__auth_refresh" cookie.Expires = time.Now().Local().Add(time.Hour * -1) return cookie diff --git a/pkg/forwardauth/forwardauth.go b/pkg/forwardauth/forwardauth.go index 3177a9e..271b300 100644 --- a/pkg/forwardauth/forwardauth.go +++ b/pkg/forwardauth/forwardauth.go @@ -7,11 +7,10 @@ package forwardauth import ( "context" "fmt" - "strings" "github.com/StiviiK/keycloak-traefik-forward-auth/pkg/options" "github.com/StiviiK/keycloak-traefik-forward-auth/pkg/utils" - "github.com/coreos/go-oidc/v3/oidc" + "github.com/coreos/go-oidc" "golang.org/x/oauth2" ) @@ -20,7 +19,12 @@ type ForwardAuth struct { OidcProvider *oidc.Provider OAuth2Config oauth2.Config OidcVefifier *oidc.IDTokenVerifier - SessionCache SessionCache + + OidcProviderClaims *OidcProviderClaims +} + +type OidcProviderClaims struct { + EndSessionURL string `json:"end_session_endpoint"` } // Claims represents the claims struct which we get from the identity provider @@ -30,15 +34,14 @@ type Claims struct { IssuedAt utils.Time `json:"iat"` Expiration utils.Time `json:"exp"` - Name string `json:"name"` - GivenName string `json:"given_name"` - FamilyName string `json:"family_name"` - Email string `json:"email"` - VerifiedMail bool `json:"email_verified"` - Picture string `json:"picture"` - Locale string `json:"locale"` - PreferedUsername string `json:"preferred_username"` - Groups []string `json:"groups"` + Name string `json:"name"` + GivenName string `json:"given_name"` + FamilyName string `json:"family_name"` + Email string `json:"email"` + VerifiedMail bool `json:"email_verified"` + Picture string `json:"picture"` + Locale string `json:"locale"` + PreferedUsername string `json:"preferred_username"` } // Create creates a new fw auth client from our options @@ -52,11 +55,16 @@ func Create(ctx context.Context, options *options.Options) (*ForwardAuth, error) ClientID: options.ClientID, }) - scopes := []string{oidc.ScopeOpenID, "profile", "email"} - scopes = append(scopes, strings.Split(options.Scopes, " ")...) + providerClaims := OidcProviderClaims{} + if err = provider.Claims(&providerClaims); err != nil { + return nil, err + } return &ForwardAuth{ - OidcProvider: provider, + OidcProvider: provider, + OidcVefifier: verifier, + OidcProviderClaims: &providerClaims, + OAuth2Config: oauth2.Config{ ClientID: options.ClientID, ClientSecret: options.ClientSecret, @@ -66,9 +74,7 @@ func Create(ctx context.Context, options *options.Options) (*ForwardAuth, error) Endpoint: provider.Endpoint(), // "openid" is a required scope for OpenID Connect flows. - Scopes: scopes, + Scopes: []string{oidc.ScopeOpenID, "profile", "email"}, }, - OidcVefifier: verifier, - SessionCache: newSessionCache(options), }, nil } diff --git a/pkg/forwardauth/session.go b/pkg/forwardauth/session.go deleted file mode 100644 index 2d800a5..0000000 --- a/pkg/forwardauth/session.go +++ /dev/null @@ -1,61 +0,0 @@ -package forwardauth - -import ( - "time" - - "github.com/StiviiK/keycloak-traefik-forward-auth/pkg/options" - "github.com/google/uuid" - "github.com/pzentenoe/go-cache" -) - -type SessionCache struct { - internal *cache.Cache - longLived bool -} - -type SessionCacheItem struct { - IDToken string - RefreshToken string -} - -func newSessionCache(options *options.Options) SessionCache { - longLived := options.SessionLifetime > 0 - var nd int - if longLived { - nd = options.SessionLifetime - } else { - nd = 12 - } - - return SessionCache{ - internal: cache.New(time.Hour*time.Duration(nd), time.Hour), - longLived: longLived, - } -} - -func (c *SessionCache) Get(sessionId string) *SessionCacheItem { - itm, _ := c.internal.Get(sessionId) - if itm == nil { - return nil - } - return itm.(*SessionCacheItem) -} - -func (c *SessionCache) Create(session *SessionCacheItem) string { - sessionId := uuid.New().String() - c.internal.SetDefault(sessionId, session) - return sessionId -} - -func (c *SessionCache) Update(sessionId string, session *SessionCacheItem) { - _, exp, found := c.internal.GetWithExpiration(sessionId) - if found && c.longLived { - c.internal.Set(sessionId, session, exp.Sub(time.Now())) - } else { - c.internal.SetDefault(sessionId, session) - } -} - -func (c *SessionCache) Delete(sessionId string) { - c.internal.Delete(sessionId) -} diff --git a/pkg/forwardauth/utils.go b/pkg/forwardauth/utils.go index d94fb6a..b882696 100644 --- a/pkg/forwardauth/utils.go +++ b/pkg/forwardauth/utils.go @@ -7,6 +7,7 @@ package forwardauth import ( "fmt" "net/http" + "net/url" ) func (fw *ForwardAuth) GetReturnUri(r *http.Request) string { @@ -16,3 +17,19 @@ func (fw *ForwardAuth) GetReturnUri(r *http.Request) string { return fmt.Sprintf("%s://%s%s", proto, host, path) } + +func (fw *ForwardAuth) GetLogoutUri(redirectURL string, state string) string { + logoutURL, err := url.Parse(fw.OidcProviderClaims.EndSessionURL) + if err != nil { + return "" + } + query := logoutURL.Query() + if redirectURL != "" { + query.Set("post_logout_redirect_uri", redirectURL) + } + if state != "" { + query.Set("state", state) + } + logoutURL.RawQuery = query.Encode() + return logoutURL.String() +} diff --git a/pkg/httphandler/callback.go b/pkg/httphandler/auth_callback.go similarity index 66% rename from pkg/httphandler/callback.go rename to pkg/httphandler/auth_callback.go index 78ae503..f1ae63f 100644 --- a/pkg/httphandler/callback.go +++ b/pkg/httphandler/auth_callback.go @@ -8,19 +8,18 @@ import ( "net/http" "net/url" - "github.com/StiviiK/keycloak-traefik-forward-auth/pkg/forwardauth" "github.com/sirupsen/logrus" ) // CallbackHandler returns a handler function which handles the callback from oidc provider -func (root *HttpHandler) callbackHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) { +func (root *HttpHandler) authCallbackHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) { logger := logrus.WithFields(logrus.Fields{ "SourceIP": r.Header.Get("X-Forwarded-For"), - "Path": forwardedURI.Path, + "Path": "/auth/resp", }) // check for the csrf cookie - state, redirect, err := root.forwardAuth.ValidateCSRFCookie(r, root.options) + state, redirect, err := root.forwardAuth.ValidateCSRFCookie(r) if err != nil { http.Error(w, err.Error(), http.StatusUnauthorized) return @@ -42,9 +41,9 @@ func (root *HttpHandler) callbackHandler(w http.ResponseWriter, r *http.Request, // clear the csrf cookie http.SetCookie(w, root.forwardAuth.ClearCSRFCookie(root.options)) - newSession := forwardauth.SessionCacheItem{IDToken: authResult.IDToken, RefreshToken: authResult.RefreshToken} - sessionId := root.forwardAuth.SessionCache.Create(&newSession) - - http.SetCookie(w, root.forwardAuth.MakeSessionCookie(root.options, sessionId)) + http.SetCookie(w, root.forwardAuth.MakeAuthCookie(root.options, authResult)) + //if len(authResult.RefreshToken) > 0 { // Do we have an refresh token? + // http.SetCookie(w, root.forwardAuth.MakeRefreshAuthCookie(root.options, authResult)) + //} http.Redirect(w, r, redirect, http.StatusTemporaryRedirect) } diff --git a/pkg/httphandler/auth_root.go b/pkg/httphandler/auth_root.go new file mode 100644 index 0000000..c42ed74 --- /dev/null +++ b/pkg/httphandler/auth_root.go @@ -0,0 +1,41 @@ +/* +Copyright (c) 2020 Stefan Kürzeder +This code is licensed under MIT license (see LICENSE for details) +*/ +package httphandler + +import ( + "fmt" + "net/http" + "net/url" + + "github.com/google/uuid" + "github.com/sirupsen/logrus" +) + +// RootHandler returns a handler function which handles all requests to the root +func (root *HttpHandler) authRootHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) { + redirect := fmt.Sprintf("%s://%s%s", r.Header.Get("X-Forwarded-Proto"), r.Header.Get("X-Forwarded-Host"), r.Header.Get("X-Forwarded-Uri")) + logger := logrus.WithFields(logrus.Fields{ + "SourceIP": r.Header.Get("X-Forwarded-For"), + "RequestTarget": redirect, + "Path": "/", + }) + + claims, err := root.forwardAuth.IsAuthenticated(r.Context(), logger, w, r, root.options) + if err != nil { + logger = logger.WithField("FunctionSource", "RootHandler") + logger.Warn("IsAuthenticated failed, initating login flow.") + + http.SetCookie(w, root.forwardAuth.ClearAuthCookie(root.options)) + //http.SetCookie(w, root.forwardAuth.ClearRefreshAuthCookie(root.options)) + + state := uuid.New().String() + http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, redirect, state)) + http.Redirect(w, r, root.forwardAuth.OAuth2Config.AuthCodeURL(state), http.StatusTemporaryRedirect) + return + } + + w.Header().Set("X-Forwarded-User", claims.Email) + w.WriteHeader(http.StatusOK) +} diff --git a/pkg/httphandler/handler.go b/pkg/httphandler/handler.go index 35d6f66..1315d2e 100644 --- a/pkg/httphandler/handler.go +++ b/pkg/httphandler/handler.go @@ -5,6 +5,7 @@ This code is licensed under MIT license (see LICENSE for details) package httphandler import ( + "fmt" "net/http" "net/url" @@ -24,25 +25,28 @@ func Create(fw *forwardauth.ForwardAuth, options *options.Options) *HttpHandler } } -func (h *HttpHandler) Entrypoint() func(http.ResponseWriter, *http.Request) { +func (root *HttpHandler) Entrypoint() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { uri, err := url.Parse(r.Header.Get("X-Forwarded-Uri")) - host := r.Header.Get("X-Forwarded-Host") - - if err != nil { + switch { + case err != nil: http.Error(w, err.Error(), http.StatusInternalServerError) return - } - if host == h.options.AuthDomain { - // Handles OIDC callback - if uri.Path == h.options.RedirectURL { - h.callbackHandler(w, r, uri) - return - } - } + case uri.Path == root.options.RedirectURL: + root.authCallbackHandler(w, r, uri) + return - // Handles forward auth - h.rootHandler(w, r, uri, r.URL) + case uri.Path == root.options.LogoutUrl: + root.logoutHandler(w, r, uri) + return + + case uri.Path == fmt.Sprintf("%s/resp", root.options.LogoutUrl): + return + + default: + root.authRootHandler(w, r, uri) + return + } } } diff --git a/pkg/httphandler/logout_root.go b/pkg/httphandler/logout_root.go new file mode 100644 index 0000000..a8c8b73 --- /dev/null +++ b/pkg/httphandler/logout_root.go @@ -0,0 +1,49 @@ +/* +Copyright (c) 2020 Stefan Kürzeder +This code is licensed under MIT license (see LICENSE for details) +*/ +package httphandler + +import ( + "fmt" + "net/http" + "net/url" + + "github.com/google/uuid" + "github.com/sirupsen/logrus" +) + +// RootHandler returns a handler function which handles all requests to the root +func (root *HttpHandler) logoutHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL) { + logger := logrus.WithFields(logrus.Fields{ + "SourceIP": r.Header.Get("X-Forwarded-For"), + "RequestTarget": root.forwardAuth.GetReturnUri(r), + "Path": root.options.LogoutUrl, + }) + + // check for the csrf cookie + state, redirect, err := root.forwardAuth.ValidateCSRFCookie(r) + if err != nil { + state := uuid.New().String() + redirect := fmt.Sprintf("%s://%s", r.Header.Get("X-Forwarded-Proto"), r.Header.Get("X-Forwarded-Host")) + + http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, redirect, state)) + + responseURL := fmt.Sprintf("https://%s%s/resp", root.options.AuthDomain, root.options.LogoutUrl) + http.Redirect(w, r, root.forwardAuth.GetLogoutUri(responseURL, state), http.StatusTemporaryRedirect) + return + } + + // verify the state + if forwardedURI.Query().Get("state") != state { + http.Error(w, "state did not match", http.StatusBadRequest) + return + } + + // Clear the auth information + logger.Info("Destroying auth cookie.") + http.SetCookie(w, root.forwardAuth.ClearAuthCookie(root.options)) + + // Redirect to the base + http.Redirect(w, r, redirect, http.StatusFound) +} diff --git a/pkg/httphandler/root.go b/pkg/httphandler/root.go deleted file mode 100644 index 736b47f..0000000 --- a/pkg/httphandler/root.go +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright (c) 2020 Stefan Kürzeder -This code is licensed under MIT license (see LICENSE for details) -*/ -package httphandler - -import ( - "fmt" - "net/http" - "net/url" - - "github.com/google/uuid" - "github.com/sirupsen/logrus" -) - -// RootHandler returns a handler function which handles all requests to the root -func (root *HttpHandler) rootHandler(w http.ResponseWriter, r *http.Request, forwardedURI *url.URL, queryURI *url.URL) { - logger := logrus.WithFields(logrus.Fields{ - "SourceIP": r.Header.Get("X-Forwarded-For"), - "RequestTarget": root.forwardAuth.GetReturnUri(r), - "Path": forwardedURI.Path, - }) - - user, pass, usesBasicAuth := r.BasicAuth() - if usesBasicAuth && root.options.BypassPwd != nil { - if root.options.BypassPwd.Match(user, pass) { - logger.Infof("Basic auth successful: %s", user) - w.Header().Set("X-Forwarded-User", "bypass@example.com") - w.WriteHeader(200) - return - } else { - logger.Errorf("Basic auth failed: %s", user) - } - } - - claims, err := root.forwardAuth.IsAuthenticated(r.Context(), logger, w, r, root.options) - if err != nil { - logger = logger.WithField("FunctionSource", "RootHandler") - logger.Warn("IsAuthenticated failed, initating login flow.") - - http.SetCookie(w, root.forwardAuth.ClearSessionCookie(root.options)) - - state := uuid.New().String() - http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, state)) - http.Redirect(w, r, root.forwardAuth.OAuth2Config.AuthCodeURL(state), http.StatusTemporaryRedirect) - return - } - - // Check group - group := queryURI.Query().Get("group") - if len(group) > 0 { - if !contains(claims.Groups, group) { - logger.Warnf("User %s not member of group %s", claims.PreferedUsername, group) - http.Error(w, fmt.Sprintf("You need to be a member of the group '%s' to access this site", group), http.StatusForbidden) - } - } - - w.Header().Set("X-Forwarded-User", claims.Email) - w.WriteHeader(200) -} - -func contains(s []string, e string) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} diff --git a/pkg/options/options.go b/pkg/options/options.go index 0a9c3c7..3653e68 100644 --- a/pkg/options/options.go +++ b/pkg/options/options.go @@ -6,26 +6,19 @@ package options import ( "fmt" - "strings" "github.com/caarlos0/env" - "github.com/tg123/go-htpasswd" ) type Options struct { - Issuer string `env:"ISSUER"` - ClientID string `env:"CLIENT_ID"` - ClientSecret string `env:"CLIENT_SECRET"` - AuthDomain string `env:"AUTH_DOMAIN"` - CookieDomain string `env:"COOKIE_DOMAIN"` - CookiePrefix string `env:"COOKIE_PREFIX" envDefault:"oidca_"` - Port int `env:"PORT" envDefault:"4181"` - RedirectURL string `env:"REDIRECT_URL" envDefault:"/auth/resp"` - Scopes string `env:"SCOPES"` - BypassUser string `env:"BYPASS_USER"` - BypassFile string `env:"BYPASS_FILE"` - BypassPwd *htpasswd.File - SessionLifetime int `env:"SESSION_LIFETIME" envDefault:"0"` + Issuer string `env:"ISSUER"` + ClientID string `env:"CLIENT_ID"` + ClientSecret string `env:"CLIENT_SECRET"` + AuthDomain string `env:"AUTH_DOMAIN"` + CookieDomain string `env:"COOKIE_DOMAIN"` + Port int `env:"PORT" envDefault:"4181"` + RedirectURL string `env:"REDIRECT_URL" envDefault:"/auth/resp"` + LogoutUrl string `env:"LOGOUT_URL" envDefault:"/auth/logout"` } // LoadOptions parses the environment vars and the options @@ -35,20 +28,5 @@ func LoadOptions() (*Options, error) { return nil, fmt.Errorf("failed to parse options: %s", err) } - if options.BypassFile != "" { - parsed, err := htpasswd.New(options.BypassFile, htpasswd.DefaultSystems, func(err error) {}) - if err != nil { - return nil, err - } - options.BypassPwd = parsed - } else if options.BypassUser != "" { - prep := strings.ReplaceAll(options.BypassUser, ";", "\n") - parsed, err := htpasswd.NewFromReader(strings.NewReader(prep), htpasswd.DefaultSystems, func(err error) {}) - if err != nil { - return nil, err - } - options.BypassPwd = parsed - } - return &options, nil }