Skip to content

Commit

Permalink
chore(deps): bump golang.org/x/oauth2 to v0.20.0
Browse files Browse the repository at this point in the history
  • Loading branch information
clambin committed May 6, 2024
1 parent 9281924 commit 63da4da
Show file tree
Hide file tree
Showing 21 changed files with 61 additions and 50 deletions.
4 changes: 2 additions & 2 deletions cmd/traefik-simple-auth/traefik-simple-auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"context"
"fmt"
"github.com/clambin/traefik-simple-auth/internal/cmd"
"github.com/clambin/traefik-simple-auth/internal/server"
"github.com/clambin/traefik-simple-auth/internal/server/configuration"
"github.com/prometheus/client_golang/prometheus"
"os"
"os/signal"
Expand All @@ -17,7 +17,7 @@ func main() {
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()

cfg, err := server.GetConfiguration()
cfg, err := configuration.GetConfiguration()
if err == nil {
err = cmd.Run(ctx, cfg, prometheus.DefaultRegisterer, os.Stderr, version)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ require (
github.com/oauth2-proxy/mockoidc v0.0.0-20240214162133-caebfff84d25
github.com/prometheus/client_golang v1.19.0
github.com/stretchr/testify v1.9.0
golang.org/x/oauth2 v0.19.0
golang.org/x/oauth2 v0.20.0
)

require (
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
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/oauth2 v0.20.0 h1:4mQdhULixXKP1rwYBW0vAijoXnkTG0BLCDRzfe1idMo=
golang.org/x/oauth2 v0.20.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
Expand Down
5 changes: 3 additions & 2 deletions internal/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import (
"context"
"errors"
"github.com/clambin/traefik-simple-auth/internal/server"
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/internal/server/configuration"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"github.com/clambin/traefik-simple-auth/pkg/state"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
Expand All @@ -14,7 +15,7 @@ import (
"time"
)

func Run(ctx context.Context, cfg server.Configuration, registry prometheus.Registerer, logOutput io.Writer, version string) error {
func Run(ctx context.Context, cfg configuration.Configuration, registry prometheus.Registerer, logOutput io.Writer, version string) error {
var opts slog.HandlerOptions
if cfg.Debug {
opts.Level = slog.LevelDebug
Expand Down
6 changes: 3 additions & 3 deletions internal/cmd/run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cmd
import (
"context"
"fmt"
"github.com/clambin/traefik-simple-auth/internal/server"
"github.com/clambin/traefik-simple-auth/internal/server/configuration"
"github.com/clambin/traefik-simple-auth/internal/server/testutils"
"github.com/clambin/traefik-simple-auth/pkg/domains"
"github.com/clambin/traefik-simple-auth/pkg/whitelist"
Expand All @@ -28,7 +28,7 @@ func TestRun(t *testing.T) {
<-ctx.Done()
require.NoError(t, oidcServer.Shutdown())
}()
cfg := server.Configuration{
cfg := configuration.Configuration{
Debug: true,
Addr: ":8081",
PromAddr: ":9091",
Expand Down Expand Up @@ -112,7 +112,7 @@ func TestRun_Fail(t *testing.T) {
<-ctx.Done()
require.NoError(t, oidcServer.Shutdown())
}()
cfg := server.Configuration{
cfg := configuration.Configuration{
Debug: true,
Addr: ":-1",
PromAddr: ":-1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package server
package configuration

import (
"encoding/base64"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package server
package configuration

import (
"github.com/clambin/traefik-simple-auth/pkg/domains"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package server
package extractor

import (
"context"
"errors"
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"log/slog"
"net/http"
)
Expand All @@ -17,7 +17,7 @@ func SessionExtractor(sessions sessions.Sessions, logger *slog.Logger) func(next
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if userSession, err := sessions.Validate(r); err == nil {
r = r.WithContext(context.WithValue(r.Context(), sessionKey, userSession))
r = WithSession(r, userSession)
} else if !errors.Is(err, http.ErrNoCookie) {
logger.Warn("received invalid session cookie", "err", err)
}
Expand All @@ -31,3 +31,7 @@ func GetSession(r *http.Request) (sessions.Session, bool) {
userSession, ok := r.Context().Value(sessionKey).(sessions.Session)
return userSession, ok
}

func WithSession(r *http.Request, userSession sessions.Session) *http.Request {
return r.WithContext(context.WithValue(r.Context(), sessionKey, userSession))
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package server
package extractor

import (
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"log/slog"
Expand Down
18 changes: 10 additions & 8 deletions internal/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package server
import (
"encoding/json"
"errors"
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/internal/server/extractor"
"github.com/clambin/traefik-simple-auth/internal/server/logging"
"github.com/clambin/traefik-simple-auth/pkg/domains"
"github.com/clambin/traefik-simple-auth/pkg/oauth"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"github.com/clambin/traefik-simple-auth/pkg/state"
"github.com/clambin/traefik-simple-auth/pkg/whitelist"
"golang.org/x/oauth2"
Expand All @@ -20,7 +22,7 @@ import (
// forwards the request to the originally requested destination.
func ForwardAuthHandler(domains domains.Domains, oauthHandlers map[domains.Domain]oauth.Handler, states state.States[string], logger *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Debug("request received", "request", loggedRequest(r))
logger.Debug("request received", "request", logging.Request(r))

// check that the request is for one of the configured domains
domain, ok := domains.Domain(r.URL)
Expand All @@ -31,7 +33,7 @@ func ForwardAuthHandler(domains domains.Domains, oauthHandlers map[domains.Domai
}

// validate that the request has a valid session cookie
if sess, ok := GetSession(r); ok {
if sess, ok := extractor.GetSession(r); ok {
logger.Debug("allowing valid request", slog.String("email", sess.Email))
w.Header().Set("X-Forwarded-User", sess.Email)
w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -60,10 +62,10 @@ func ForwardAuthHandler(domains domains.Domains, oauthHandlers map[domains.Domai
// This means that the user's next request has an invalid cookie, triggering a new oauth flow.
func LogoutHandler(domains domains.Domains, sessionStore sessions.Sessions, logger *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Debug("request received", "request", loggedRequest(r))
logger.Debug("request received", "request", logging.Request(r))

// remove the cached cookie
session, ok := GetSession(r)
session, ok := extractor.GetSession(r)
if !ok {
http.Error(w, "Invalid session", http.StatusUnauthorized)
return
Expand All @@ -74,7 +76,7 @@ func LogoutHandler(domains domains.Domains, sessionStore sessions.Sessions, logg

// Write a blank session cookie to override the current valid one.
domain, _ := domains.Domain(r.URL)
http.SetCookie(w, sessionStore.Cookie(sessions.Session{}, domain))
http.SetCookie(w, sessionStore.Cookie(sessions.Session{}, string(domain)))

http.Error(w, "You have been logged out", http.StatusUnauthorized)
logger.Info("user has been logged out", "user", session.Email)
Expand All @@ -94,7 +96,7 @@ func AuthCallbackHandler(
logger *slog.Logger,
) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Debug("request received", "request", loggedRequest(r))
logger.Debug("request received", "request", logging.Request(r))

// Look up the (random) state to find the final destination.
encodedState := r.URL.Query().Get("state")
Expand Down Expand Up @@ -134,7 +136,7 @@ func AuthCallbackHandler(

// GetUserEmailAddress successful. Create a session and redirect the user to the final destination.
session := sessions.Session(user)
http.SetCookie(w, sessions.Cookie(session, domain))
http.SetCookie(w, sessions.Cookie(session, string(domain)))

logger.Info("user logged in. redirecting ...", "user", user, "url", targetURL)
http.Redirect(w, r, targetURL, http.StatusTemporaryRedirect)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package server
package logging

import (
"log/slog"
Expand All @@ -10,7 +10,7 @@ var _ slog.LogValuer = request{}

type request struct{ request *http.Request }

func loggedRequest(r *http.Request) slog.LogValuer {
func Request(r *http.Request) slog.LogValuer {
return request{request: r}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package server
package logging

import (
"bytes"
Expand All @@ -15,7 +15,7 @@ func Test_loggedRequest(t *testing.T) {

var out bytes.Buffer
l := logtest.NewJSONLogger(&out, slog.LevelInfo)
l.Info("request", "r", loggedRequest(r))
l.Info("request", "r", Request(r))

want := `{"level":"INFO","msg":"request","r":{"url":"https://example.com/","X-Forwarded-For":"127.0.0.1:0"}}
`
Expand Down
11 changes: 6 additions & 5 deletions internal/server/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package server

import (
"github.com/clambin/go-common/http/metrics"
"github.com/clambin/traefik-simple-auth/internal/server/extractor"
"github.com/prometheus/client_golang/prometheus"
"net/http"
"strconv"
Expand Down Expand Up @@ -52,15 +53,15 @@ func NewMetrics(namespace, subsystem string, constLabels map[string]string, buck
}
}

func (m Metrics) Measure(req *http.Request, statusCode int, duration time.Duration) {
sess, _ := GetSession(req)
func (m Metrics) Measure(r *http.Request, statusCode int, duration time.Duration) {
sess, _ := extractor.GetSession(r)
code := strconv.Itoa(statusCode)
path := req.URL.Path
path := r.URL.Path
if path != OAUTHPath && path != OAUTHPath+"/logout" {
path = "/"
}
m.requestCounter.WithLabelValues(sess.Email, req.URL.Host, path, code).Inc()
m.requestDuration.WithLabelValues(sess.Email, req.URL.Host, path, code).Observe(duration.Seconds())
m.requestCounter.WithLabelValues(sess.Email, r.URL.Host, path, code).Inc()
m.requestDuration.WithLabelValues(sess.Email, r.URL.Host, path, code).Observe(duration.Seconds())
}

func (m Metrics) Describe(ch chan<- *prometheus.Desc) {
Expand Down
2 changes: 1 addition & 1 deletion internal/server/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package server

import (
"context"
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/internal/server/testutils"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"net/http"
Expand Down
5 changes: 3 additions & 2 deletions internal/server/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package server

import (
"github.com/clambin/go-common/http/middleware"
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/internal/server/extractor"
"github.com/clambin/traefik-simple-auth/pkg/domains"
"github.com/clambin/traefik-simple-auth/pkg/oauth"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"github.com/clambin/traefik-simple-auth/pkg/state"
"github.com/clambin/traefik-simple-auth/pkg/whitelist"
"log/slog"
Expand Down Expand Up @@ -40,7 +41,7 @@ func addRoutes(

func forwardAuthMiddleware(sessions sessions.Sessions, m *Metrics, logger *slog.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return SessionExtractor(sessions, logger.With("middleware", "sessionExtractor"))( // extract & validate the session cookie from the request
return extractor.SessionExtractor(sessions, logger.With("middleware", "sessionExtractor"))( // extract & validate the session cookie from the request
withMetrics(m)( // measure request metrics
next,
),
Expand Down
7 changes: 4 additions & 3 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package server

import (
"context"
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/internal/server/configuration"
"github.com/clambin/traefik-simple-auth/pkg/domains"
"github.com/clambin/traefik-simple-auth/pkg/oauth"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"github.com/clambin/traefik-simple-auth/pkg/state"
"log/slog"
"net/http"
Expand All @@ -17,7 +18,7 @@ const OAUTHPath = "/_oauth"

// New returns a new http.Handler that handles traefik's forward-auth requests, and the associated oauth flow.
// It panics if config.Provider is invalid.
func New(ctx context.Context, sessions sessions.Sessions, states state.States[string], config Configuration, metrics *Metrics, logger *slog.Logger) http.Handler {
func New(ctx context.Context, sessions sessions.Sessions, states state.States[string], config configuration.Configuration, metrics *Metrics, logger *slog.Logger) http.Handler {
logger = logger.With("provider", config.Provider)

oauthHandlers := make(map[domains.Domain]oauth.Handler)
Expand Down Expand Up @@ -68,7 +69,7 @@ func makeAuthURL(authPrefix string, domain domains.Domain, OAUTHPath string) str
}

// traefikForwardAuthParser takes a request passed by traefik's forwardAuth middleware and reconstructs the original request.
func traefikForwardAuthParser(logger *slog.Logger) func(next http.Handler) http.Handler {
func traefikForwardAuthParser(_ *slog.Logger) func(next http.Handler) http.Handler {
//logger = logger.With("handler", "traefikForwardAuthParser")
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand Down
16 changes: 9 additions & 7 deletions internal/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package server

import (
"context"
"github.com/clambin/traefik-simple-auth/internal/server/sessions"
"github.com/clambin/traefik-simple-auth/internal/server/configuration"
"github.com/clambin/traefik-simple-auth/internal/server/extractor"
"github.com/clambin/traefik-simple-auth/internal/server/testutils"
"github.com/clambin/traefik-simple-auth/pkg/domains"
"github.com/clambin/traefik-simple-auth/pkg/sessions"
"github.com/clambin/traefik-simple-auth/pkg/state"
"github.com/clambin/traefik-simple-auth/pkg/whitelist"
"github.com/oauth2-proxy/mockoidc"
Expand All @@ -26,7 +28,7 @@ func TestServer_Panics(t *testing.T) {
panics = true
}
}()
cfg := Configuration{
cfg := configuration.Configuration{
Provider: "foobar",
Domains: domains.Domains{"example.com"},
}
Expand Down Expand Up @@ -96,7 +98,7 @@ func TestForwardAuthHandler(t *testing.T) {
r := testutils.ForwardAuthRequest(http.MethodGet, tt.args.target, "/")
w := httptest.NewRecorder()
if tt.args.session != nil {
r = r.WithContext(context.WithValue(r.Context(), sessionKey, *tt.args.session))
r = extractor.WithSession(r, *tt.args.session)
}

h.ServeHTTP(w, r)
Expand All @@ -120,7 +122,7 @@ func TestLogoutHandler(t *testing.T) {
t.Run("logging out clears the session cookie", func(t *testing.T) {
r := testutils.ForwardAuthRequest(http.MethodGet, "example.com", "/_oauth/logout")
session := sessionStore.Session("foo@example.com")
r = r.WithContext(context.WithValue(r.Context(), sessionKey, session))
r = extractor.WithSession(r, session)
w := httptest.NewRecorder()
s.ServeHTTP(w, r)
require.Equal(t, http.StatusUnauthorized, w.Code)
Expand Down Expand Up @@ -244,7 +246,7 @@ func setupServer(ctx context.Context, t *testing.T, metrics *Metrics) (sessions.
}()

list, _ := whitelist.New([]string{"foo@example.com"})
cfg := Configuration{
cfg := configuration.Configuration{
Provider: "oidc",
AuthPrefix: "auth",
ClientID: oidcServer.ClientID,
Expand Down Expand Up @@ -305,7 +307,7 @@ func Test_getOriginalTarget(t *testing.T) {
// before:
// Benchmark_authHandler-16 927531 1194 ns/op 941 B/op 14 allocs/op
func Benchmark_authHandler(b *testing.B) {
config := Configuration{
config := configuration.Configuration{
Domains: domains.Domains{"example.com"},
Whitelist: map[string]struct{}{"foo@example.com": {}},
Provider: "google",
Expand All @@ -315,7 +317,7 @@ func Benchmark_authHandler(b *testing.B) {
s := New(context.Background(), sessionStore, stateStore, config, nil, slog.Default())
sess := sessionStore.SessionWithExpiration("foo@example.com", time.Hour)
r := testutils.ForwardAuthRequest(http.MethodGet, "example.com", "/foo")
r.AddCookie(sessionStore.Cookie(sess, config.Domains[0]))
r.AddCookie(sessionStore.Cookie(sess, string(config.Domains[0])))
w := httptest.NewRecorder()

b.ResetTimer()
Expand Down
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit 63da4da

Please # to comment.