2017-09-18 15:48:07 +00:00
|
|
|
package auth
|
|
|
|
|
|
|
|
import (
|
2018-11-14 09:18:03 +00:00
|
|
|
"context"
|
2020-11-06 08:26:03 +00:00
|
|
|
"errors"
|
2018-11-14 09:18:03 +00:00
|
|
|
"fmt"
|
2021-03-04 19:08:03 +00:00
|
|
|
"io"
|
2017-09-18 15:48:07 +00:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2020-10-29 14:10:04 +00:00
|
|
|
"regexp"
|
2017-09-18 15:48:07 +00:00
|
|
|
"strings"
|
2020-02-03 17:44:04 +00:00
|
|
|
"time"
|
2017-09-18 15:48:07 +00:00
|
|
|
|
2023-02-03 14:24:05 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/config/dynamic"
|
|
|
|
"github.com/traefik/traefik/v3/pkg/middlewares"
|
2024-07-29 12:30:05 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/middlewares/accesslog"
|
2024-03-12 08:48:04 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/middlewares/observability"
|
2023-02-03 14:24:05 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/tracing"
|
2024-01-29 16:32:05 +00:00
|
|
|
"github.com/traefik/traefik/v3/pkg/types"
|
2022-11-21 17:36:05 +00:00
|
|
|
"github.com/vulcand/oxy/v2/forward"
|
|
|
|
"github.com/vulcand/oxy/v2/utils"
|
2024-01-08 08:10:06 +00:00
|
|
|
"go.opentelemetry.io/otel/trace"
|
2017-09-18 15:48:07 +00:00
|
|
|
)
|
|
|
|
|
2017-12-09 23:58:21 +00:00
|
|
|
const (
|
2024-01-08 08:10:06 +00:00
|
|
|
xForwardedURI = "X-Forwarded-Uri"
|
|
|
|
xForwardedMethod = "X-Forwarded-Method"
|
2017-12-09 23:58:21 +00:00
|
|
|
)
|
|
|
|
|
2024-01-08 08:10:06 +00:00
|
|
|
const typeNameForward = "ForwardAuth"
|
|
|
|
|
2021-01-21 17:34:04 +00:00
|
|
|
// hopHeaders Hop-by-hop headers to be removed in the authentication request.
|
|
|
|
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
|
|
|
|
// Proxy-Authorization header is forwarded to the authentication server (see https://tools.ietf.org/html/rfc7235#section-4.4).
|
|
|
|
var hopHeaders = []string{
|
|
|
|
forward.Connection,
|
|
|
|
forward.KeepAlive,
|
|
|
|
forward.Te, // canonicalized version of "TE"
|
|
|
|
forward.Trailers,
|
|
|
|
forward.TransferEncoding,
|
|
|
|
forward.Upgrade,
|
|
|
|
}
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
type forwardAuth struct {
|
2020-10-29 14:10:04 +00:00
|
|
|
address string
|
|
|
|
authResponseHeaders []string
|
|
|
|
authResponseHeadersRegex *regexp.Regexp
|
|
|
|
next http.Handler
|
|
|
|
name string
|
|
|
|
client http.Client
|
|
|
|
trustForwardHeader bool
|
|
|
|
authRequestHeaders []string
|
2024-01-15 15:14:05 +00:00
|
|
|
addAuthCookiesToResponse map[string]struct{}
|
2024-07-29 12:30:05 +00:00
|
|
|
headerField string
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewForward creates a forward auth middleware.
|
2019-07-10 07:26:04 +00:00
|
|
|
func NewForward(ctx context.Context, next http.Handler, config dynamic.ForwardAuth, name string) (http.Handler, error) {
|
2024-01-29 16:32:05 +00:00
|
|
|
logger := middlewares.GetLogger(ctx, name, typeNameForward)
|
|
|
|
logger.Debug().Msg("Creating middleware")
|
2018-11-14 09:18:03 +00:00
|
|
|
|
2024-01-15 15:14:05 +00:00
|
|
|
addAuthCookiesToResponse := make(map[string]struct{})
|
|
|
|
for _, cookieName := range config.AddAuthCookiesToResponse {
|
|
|
|
addAuthCookiesToResponse[cookieName] = struct{}{}
|
|
|
|
}
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
fa := &forwardAuth{
|
2024-01-15 15:14:05 +00:00
|
|
|
address: config.Address,
|
|
|
|
authResponseHeaders: config.AuthResponseHeaders,
|
|
|
|
next: next,
|
|
|
|
name: name,
|
|
|
|
trustForwardHeader: config.TrustForwardHeader,
|
|
|
|
authRequestHeaders: config.AuthRequestHeaders,
|
|
|
|
addAuthCookiesToResponse: addAuthCookiesToResponse,
|
2024-07-29 12:30:05 +00:00
|
|
|
headerField: config.HeaderField,
|
2017-11-02 10:06:03 +00:00
|
|
|
}
|
2018-04-23 13:28:04 +00:00
|
|
|
|
2020-02-03 17:44:04 +00:00
|
|
|
// Ensure our request client does not follow redirects
|
|
|
|
fa.client = http.Client{
|
|
|
|
CheckRedirect: func(r *http.Request, via []*http.Request) error {
|
|
|
|
return http.ErrUseLastResponse
|
|
|
|
},
|
|
|
|
Timeout: 30 * time.Second,
|
|
|
|
}
|
|
|
|
|
2017-09-18 15:48:07 +00:00
|
|
|
if config.TLS != nil {
|
2024-01-29 16:32:05 +00:00
|
|
|
if config.TLS.CAOptional != nil {
|
|
|
|
logger.Warn().Msg("CAOptional option is deprecated, TLS client authentication is a server side option, please remove any usage of this option.")
|
|
|
|
}
|
|
|
|
|
|
|
|
clientTLS := &types.ClientTLS{
|
|
|
|
CA: config.TLS.CA,
|
|
|
|
Cert: config.TLS.Cert,
|
|
|
|
Key: config.TLS.Key,
|
|
|
|
InsecureSkipVerify: config.TLS.InsecureSkipVerify,
|
|
|
|
}
|
|
|
|
|
|
|
|
tlsConfig, err := clientTLS.CreateTLSConfig(ctx)
|
2017-09-18 15:48:07 +00:00
|
|
|
if err != nil {
|
2021-10-26 08:54:11 +00:00
|
|
|
return nil, fmt.Errorf("unable to create client TLS configuration: %w", err)
|
2017-09-18 15:48:07 +00:00
|
|
|
}
|
2018-04-23 13:28:04 +00:00
|
|
|
|
2020-02-03 17:44:04 +00:00
|
|
|
tr := http.DefaultTransport.(*http.Transport).Clone()
|
|
|
|
tr.TLSClientConfig = tlsConfig
|
|
|
|
fa.client.Transport = tr
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
2020-10-29 14:10:04 +00:00
|
|
|
if config.AuthResponseHeadersRegex != "" {
|
|
|
|
re, err := regexp.Compile(config.AuthResponseHeadersRegex)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("error compiling regular expression %s: %w", config.AuthResponseHeadersRegex, err)
|
|
|
|
}
|
|
|
|
fa.authResponseHeadersRegex = re
|
|
|
|
}
|
|
|
|
|
2024-01-08 08:10:06 +00:00
|
|
|
return fa, nil
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
2024-01-08 08:10:06 +00:00
|
|
|
func (fa *forwardAuth) GetTracingInformation() (string, string, trace.SpanKind) {
|
|
|
|
return fa.name, typeNameForward, trace.SpanKindInternal
|
2018-11-14 09:18:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
|
2024-01-08 08:10:06 +00:00
|
|
|
logger := middlewares.GetLogger(req.Context(), fa.name, typeNameForward)
|
|
|
|
|
|
|
|
forwardReq, err := http.NewRequestWithContext(req.Context(), http.MethodGet, fa.address, nil)
|
2017-09-18 15:48:07 +00:00
|
|
|
if err != nil {
|
2024-08-28 14:11:38 +00:00
|
|
|
logger.Debug().Msgf("Error calling %s. Cause %s", fa.address, err)
|
|
|
|
observability.SetStatusErrorf(req.Context(), "Error calling %s. Cause %s", fa.address, err)
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
2017-09-18 15:48:07 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-03-11 10:50:04 +00:00
|
|
|
writeHeader(req, forwardReq, fa.trustForwardHeader, fa.authRequestHeaders)
|
|
|
|
|
2024-01-08 08:10:06 +00:00
|
|
|
var forwardSpan trace.Span
|
2024-03-11 10:50:04 +00:00
|
|
|
var tracer *tracing.Tracer
|
|
|
|
if tracer = tracing.TracerFromContext(req.Context()); tracer != nil {
|
2024-01-08 08:10:06 +00:00
|
|
|
var tracingCtx context.Context
|
|
|
|
tracingCtx, forwardSpan = tracer.Start(req.Context(), "AuthRequest", trace.WithSpanKind(trace.SpanKindClient))
|
|
|
|
defer forwardSpan.End()
|
|
|
|
|
|
|
|
forwardReq = forwardReq.WithContext(tracingCtx)
|
|
|
|
|
|
|
|
tracing.InjectContextIntoCarrier(forwardReq)
|
2024-03-11 10:50:04 +00:00
|
|
|
tracer.CaptureClientRequest(forwardSpan, forwardReq)
|
2024-01-08 08:10:06 +00:00
|
|
|
}
|
2017-09-18 15:48:07 +00:00
|
|
|
|
2020-02-03 17:44:04 +00:00
|
|
|
forwardResponse, forwardErr := fa.client.Do(forwardReq)
|
2017-09-18 15:48:07 +00:00
|
|
|
if forwardErr != nil {
|
2024-08-28 14:11:38 +00:00
|
|
|
logger.Debug().Msgf("Error calling %s. Cause: %s", fa.address, forwardErr)
|
|
|
|
observability.SetStatusErrorf(req.Context(), "Error calling %s. Cause: %s", fa.address, forwardErr)
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
2017-09-18 15:48:07 +00:00
|
|
|
return
|
|
|
|
}
|
2023-09-09 10:36:05 +00:00
|
|
|
defer forwardResponse.Body.Close()
|
2017-09-18 15:48:07 +00:00
|
|
|
|
2021-03-04 19:08:03 +00:00
|
|
|
body, readError := io.ReadAll(forwardResponse.Body)
|
2017-09-18 15:48:07 +00:00
|
|
|
if readError != nil {
|
2024-08-28 14:11:38 +00:00
|
|
|
logger.Debug().Msgf("Error reading body %s. Cause: %s", fa.address, readError)
|
|
|
|
observability.SetStatusErrorf(req.Context(), "Error reading body %s. Cause: %s", fa.address, readError)
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
2017-09-18 15:48:07 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-01-08 08:10:06 +00:00
|
|
|
// Ending the forward request span as soon as the response is handled.
|
|
|
|
// If any errors happen earlier, this span will be close by the defer instruction.
|
|
|
|
if forwardSpan != nil {
|
|
|
|
forwardSpan.End()
|
|
|
|
}
|
|
|
|
|
2024-07-29 12:30:05 +00:00
|
|
|
if fa.headerField != "" {
|
|
|
|
if elems := forwardResponse.Header[http.CanonicalHeaderKey(fa.headerField)]; len(elems) > 0 {
|
|
|
|
logData := accesslog.GetLogData(req)
|
|
|
|
if logData != nil {
|
|
|
|
logData.Core[accesslog.ClientUsername] = elems[0]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-02 10:06:03 +00:00
|
|
|
// Pass the forward response's body and selected headers if it
|
|
|
|
// didn't return a response within the range of [200, 300).
|
2017-09-18 15:48:07 +00:00
|
|
|
if forwardResponse.StatusCode < http.StatusOK || forwardResponse.StatusCode >= http.StatusMultipleChoices {
|
2022-11-21 17:36:05 +00:00
|
|
|
logger.Debug().Msgf("Remote error %s. StatusCode: %d", fa.address, forwardResponse.StatusCode)
|
2017-11-02 10:06:03 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
utils.CopyHeaders(rw.Header(), forwardResponse.Header)
|
2021-01-21 17:34:04 +00:00
|
|
|
utils.RemoveHeaders(rw.Header(), hopHeaders...)
|
2018-04-23 13:28:04 +00:00
|
|
|
|
2017-11-02 10:06:03 +00:00
|
|
|
// Grab the location header, if any.
|
|
|
|
redirectURL, err := forwardResponse.Location()
|
|
|
|
|
|
|
|
if err != nil {
|
2020-11-06 08:26:03 +00:00
|
|
|
if !errors.Is(err, http.ErrNoLocation) {
|
2024-08-28 14:11:38 +00:00
|
|
|
logger.Debug().Msgf("Error reading response location header %s. Cause: %s", fa.address, err)
|
|
|
|
observability.SetStatusErrorf(req.Context(), "Error reading response location header %s. Cause: %s", fa.address, err)
|
2018-11-14 09:18:03 +00:00
|
|
|
|
|
|
|
rw.WriteHeader(http.StatusInternalServerError)
|
2017-11-02 10:06:03 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
} else if redirectURL.String() != "" {
|
|
|
|
// Set the location in our response if one was sent back.
|
2018-11-14 09:18:03 +00:00
|
|
|
rw.Header().Set("Location", redirectURL.String())
|
2017-11-02 10:06:03 +00:00
|
|
|
}
|
|
|
|
|
2024-03-11 10:50:04 +00:00
|
|
|
tracer.CaptureResponse(forwardSpan, forwardResponse.Header, forwardResponse.StatusCode, trace.SpanKindClient)
|
2018-11-14 09:18:03 +00:00
|
|
|
rw.WriteHeader(forwardResponse.StatusCode)
|
2018-08-06 18:00:03 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
if _, err = rw.Write(body); err != nil {
|
2022-11-21 17:36:05 +00:00
|
|
|
logger.Error().Err(err).Send()
|
2018-08-06 18:00:03 +00:00
|
|
|
}
|
2017-09-18 15:48:07 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
for _, headerName := range fa.authResponseHeaders {
|
2019-04-10 15:18:06 +00:00
|
|
|
headerKey := http.CanonicalHeaderKey(headerName)
|
|
|
|
req.Header.Del(headerKey)
|
|
|
|
if len(forwardResponse.Header[headerKey]) > 0 {
|
|
|
|
req.Header[headerKey] = append([]string(nil), forwardResponse.Header[headerKey]...)
|
|
|
|
}
|
2018-06-30 05:54:03 +00:00
|
|
|
}
|
|
|
|
|
2020-10-29 14:10:04 +00:00
|
|
|
if fa.authResponseHeadersRegex != nil {
|
|
|
|
for headerKey := range req.Header {
|
|
|
|
if fa.authResponseHeadersRegex.MatchString(headerKey) {
|
|
|
|
req.Header.Del(headerKey)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for headerKey, headerValues := range forwardResponse.Header {
|
|
|
|
if fa.authResponseHeadersRegex.MatchString(headerKey) {
|
|
|
|
req.Header[headerKey] = append([]string(nil), headerValues...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-11 10:50:04 +00:00
|
|
|
tracer.CaptureResponse(forwardSpan, forwardResponse.Header, forwardResponse.StatusCode, trace.SpanKindClient)
|
2024-01-08 08:10:06 +00:00
|
|
|
|
2018-11-14 09:18:03 +00:00
|
|
|
req.RequestURI = req.URL.RequestURI()
|
2024-01-15 15:14:05 +00:00
|
|
|
|
|
|
|
authCookies := forwardResponse.Cookies()
|
|
|
|
if len(authCookies) == 0 {
|
|
|
|
fa.next.ServeHTTP(rw, req)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
fa.next.ServeHTTP(middlewares.NewResponseModifier(rw, req, fa.buildModifier(authCookies)), req)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (fa *forwardAuth) buildModifier(authCookies []*http.Cookie) func(res *http.Response) error {
|
|
|
|
return func(res *http.Response) error {
|
|
|
|
cookies := res.Cookies()
|
|
|
|
res.Header.Del("Set-Cookie")
|
|
|
|
|
|
|
|
for _, cookie := range cookies {
|
|
|
|
if _, found := fa.addAuthCookiesToResponse[cookie.Name]; !found {
|
|
|
|
res.Header.Add("Set-Cookie", cookie.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, cookie := range authCookies {
|
|
|
|
if _, found := fa.addAuthCookiesToResponse[cookie.Name]; found {
|
|
|
|
res.Header.Add("Set-Cookie", cookie.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2017-09-18 15:48:07 +00:00
|
|
|
}
|
|
|
|
|
2020-10-07 14:36:04 +00:00
|
|
|
func writeHeader(req, forwardReq *http.Request, trustForwardHeader bool, allowedHeaders []string) {
|
2017-09-18 15:48:07 +00:00
|
|
|
utils.CopyHeaders(forwardReq.Header, req.Header)
|
2024-09-27 09:18:05 +00:00
|
|
|
|
|
|
|
RemoveConnectionHeaders(forwardReq)
|
2021-01-21 17:34:04 +00:00
|
|
|
utils.RemoveHeaders(forwardReq.Header, hopHeaders...)
|
2017-09-18 15:48:07 +00:00
|
|
|
|
2020-10-07 14:36:04 +00:00
|
|
|
forwardReq.Header = filterForwardRequestHeaders(forwardReq.Header, allowedHeaders)
|
|
|
|
|
2017-09-18 15:48:07 +00:00
|
|
|
if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
|
|
|
|
if trustForwardHeader {
|
|
|
|
if prior, ok := req.Header[forward.XForwardedFor]; ok {
|
|
|
|
clientIP = strings.Join(prior, ", ") + ", " + clientIP
|
|
|
|
}
|
|
|
|
}
|
|
|
|
forwardReq.Header.Set(forward.XForwardedFor, clientIP)
|
|
|
|
}
|
|
|
|
|
2019-02-05 16:10:03 +00:00
|
|
|
xMethod := req.Header.Get(xForwardedMethod)
|
|
|
|
switch {
|
|
|
|
case xMethod != "" && trustForwardHeader:
|
2018-06-13 13:14:03 +00:00
|
|
|
forwardReq.Header.Set(xForwardedMethod, xMethod)
|
2019-02-05 16:10:03 +00:00
|
|
|
case req.Method != "":
|
2018-06-13 13:14:03 +00:00
|
|
|
forwardReq.Header.Set(xForwardedMethod, req.Method)
|
2019-02-05 16:10:03 +00:00
|
|
|
default:
|
2018-06-13 13:14:03 +00:00
|
|
|
forwardReq.Header.Del(xForwardedMethod)
|
|
|
|
}
|
|
|
|
|
2019-02-05 16:10:03 +00:00
|
|
|
xfp := req.Header.Get(forward.XForwardedProto)
|
|
|
|
switch {
|
|
|
|
case xfp != "" && trustForwardHeader:
|
2017-09-18 15:48:07 +00:00
|
|
|
forwardReq.Header.Set(forward.XForwardedProto, xfp)
|
2019-02-05 16:10:03 +00:00
|
|
|
case req.TLS != nil:
|
2017-09-18 15:48:07 +00:00
|
|
|
forwardReq.Header.Set(forward.XForwardedProto, "https")
|
2019-02-05 16:10:03 +00:00
|
|
|
default:
|
2017-09-18 15:48:07 +00:00
|
|
|
forwardReq.Header.Set(forward.XForwardedProto, "http")
|
|
|
|
}
|
|
|
|
|
|
|
|
if xfp := req.Header.Get(forward.XForwardedPort); xfp != "" && trustForwardHeader {
|
|
|
|
forwardReq.Header.Set(forward.XForwardedPort, xfp)
|
|
|
|
}
|
|
|
|
|
2019-02-05 16:10:03 +00:00
|
|
|
xfh := req.Header.Get(forward.XForwardedHost)
|
|
|
|
switch {
|
|
|
|
case xfh != "" && trustForwardHeader:
|
2017-09-18 15:48:07 +00:00
|
|
|
forwardReq.Header.Set(forward.XForwardedHost, xfh)
|
2019-02-05 16:10:03 +00:00
|
|
|
case req.Host != "":
|
2017-09-18 15:48:07 +00:00
|
|
|
forwardReq.Header.Set(forward.XForwardedHost, req.Host)
|
2019-02-05 16:10:03 +00:00
|
|
|
default:
|
2017-09-18 15:48:07 +00:00
|
|
|
forwardReq.Header.Del(forward.XForwardedHost)
|
|
|
|
}
|
2017-12-09 23:58:21 +00:00
|
|
|
|
2019-02-05 16:10:03 +00:00
|
|
|
xfURI := req.Header.Get(xForwardedURI)
|
|
|
|
switch {
|
|
|
|
case xfURI != "" && trustForwardHeader:
|
2017-12-09 23:58:21 +00:00
|
|
|
forwardReq.Header.Set(xForwardedURI, xfURI)
|
2019-02-05 16:10:03 +00:00
|
|
|
case req.URL.RequestURI() != "":
|
2017-12-09 23:58:21 +00:00
|
|
|
forwardReq.Header.Set(xForwardedURI, req.URL.RequestURI())
|
2019-02-05 16:10:03 +00:00
|
|
|
default:
|
2017-12-09 23:58:21 +00:00
|
|
|
forwardReq.Header.Del(xForwardedURI)
|
|
|
|
}
|
2017-09-18 15:48:07 +00:00
|
|
|
}
|
2020-10-07 14:36:04 +00:00
|
|
|
|
|
|
|
func filterForwardRequestHeaders(forwardRequestHeaders http.Header, allowedHeaders []string) http.Header {
|
|
|
|
if len(allowedHeaders) == 0 {
|
|
|
|
return forwardRequestHeaders
|
|
|
|
}
|
|
|
|
|
|
|
|
filteredHeaders := http.Header{}
|
|
|
|
for _, headerName := range allowedHeaders {
|
|
|
|
values := forwardRequestHeaders.Values(headerName)
|
|
|
|
if len(values) > 0 {
|
|
|
|
filteredHeaders[http.CanonicalHeaderKey(headerName)] = append([]string(nil), values...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return filteredHeaders
|
|
|
|
}
|