Compare commits

..

2 commits

Author SHA1 Message Date
Stefan Kürzeder
9b3558f598 File refactor 2020-06-04 18:46:33 +02:00
Stefan Kürzeder
8807ea42bb Started with logout 2020-06-04 18:14:16 +02:00
12 changed files with 167 additions and 106 deletions

View file

@ -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

View file

@ -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"]

21
go.mod
View file

@ -1,19 +1,14 @@
module github.com/StiviiK/keycloak-traefik-forward-auth
go 1.21
toolchain go1.22.2
go 1.14
require (
github.com/caarlos0/env v3.5.0+incompatible
github.com/coreos/go-oidc/v3 v3.10.0
github.com/google/uuid v1.6.0
github.com/sirupsen/logrus v1.9.3
golang.org/x/oauth2 v0.19.0
)
require (
github.com/go-jose/go-jose/v4 v4.0.1 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/sys v0.19.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
)

61
go.sum
View file

@ -1,32 +1,37 @@
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.10.0 h1:tDnXHnLyiTVyT/2zLDGj09pFPkhND8Gl8lnTRhoEaJU=
github.com/coreos/go-oidc/v3 v3.10.0/go.mod h1:5j11xcw0D3+SGxn6Z/WFADsgcWVMyNAlSQupk0KK3ac=
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.0.1 h1:QVEPDE3OluqXBQZDcnNvQrInro2h0e4eqNbnZSWqS6U=
github.com/go-jose/go-jose/v4 v4.0.1/go.mod h1:WVf9LFMHh/QVrmqrOfqun0C45tMe3RoiKJMPvgWwLfY=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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/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.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
golang.org/x/oauth2 v0.19.0 h1:9+E/EZBCbTLNrbN35fHv/a/d/mOBatymz1zbtQrXpIg=
golang.org/x/oauth2 v0.19.0/go.mod h1:vYi7skDa1x015PmRRYZ7+s1cWyPgrPiSYRe4rnsexc8=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
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=

View file

@ -24,10 +24,10 @@ 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 = "__auth_csrf"
cookie.Value = fmt.Sprintf("%s|%s", fw.GetReturnUri(r), state)
cookie.Value = fmt.Sprintf("%s|%s", redirect, state)
cookie.Expires = time.Now().Local().Add(time.Hour)
return cookie

View file

@ -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,6 +19,12 @@ type ForwardAuth struct {
OidcProvider *oidc.Provider
OAuth2Config oauth2.Config
OidcVefifier *oidc.IDTokenVerifier
OidcProviderClaims *OidcProviderClaims
}
type OidcProviderClaims struct {
EndSessionURL string `json:"end_session_endpoint"`
}
// Claims represents the claims struct which we get from the identity provider
@ -37,7 +42,6 @@ type Claims struct {
Picture string `json:"picture"`
Locale string `json:"locale"`
PreferedUsername string `json:"preferred_username"`
Groups []string `json:"groups"`
}
// Create creates a new fw auth client from our options
@ -51,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,
OidcVefifier: verifier,
OidcProviderClaims: &providerClaims,
OAuth2Config: oauth2.Config{
ClientID: options.ClientID,
ClientSecret: options.ClientSecret,
@ -65,8 +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,
}, nil
}

View file

@ -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()
}

View file

@ -12,10 +12,10 @@ import (
)
// 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

View file

@ -14,11 +14,12 @@ import (
)
// 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) {
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": root.forwardAuth.GetReturnUri(r),
"Path": forwardedURI.Path,
"RequestTarget": redirect,
"Path": "/",
})
claims, err := root.forwardAuth.IsAuthenticated(r.Context(), logger, w, r, root.options)
@ -30,29 +31,11 @@ func (root *HttpHandler) rootHandler(w http.ResponseWriter, r *http.Request, for
//http.SetCookie(w, root.forwardAuth.ClearRefreshAuthCookie(root.options))
state := uuid.New().String()
http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, state))
http.SetCookie(w, root.forwardAuth.MakeCSRFCookie(w, r, root.options, redirect, 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
w.WriteHeader(http.StatusOK)
}

View file

@ -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)
case uri.Path == root.options.RedirectURL:
root.authCallbackHandler(w, r, uri)
return
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
}
}
// Handles forward auth
h.rootHandler(w, r, uri, r.URL)
}
}

View file

@ -0,0 +1,49 @@
/*
Copyright (c) 2020 Stefan Kürzeder <info@stivik.de>
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)
}

View file

@ -18,7 +18,7 @@ type Options struct {
CookieDomain string `env:"COOKIE_DOMAIN"`
Port int `env:"PORT" envDefault:"4181"`
RedirectURL string `env:"REDIRECT_URL" envDefault:"/auth/resp"`
Scopes string `env:"SCOPES"`
LogoutUrl string `env:"LOGOUT_URL" envDefault:"/auth/logout"`
}
// LoadOptions parses the environment vars and the options