traefik/pkg/middlewares/headers/headers.go

280 lines
8 KiB
Go
Raw Normal View History

2018-11-14 09:18:03 +00:00
// Package headers Middleware based on https://github.com/unrolled/secure.
package headers
import (
"context"
"errors"
"net/http"
2019-04-02 08:40:04 +00:00
"strconv"
"strings"
2018-11-14 09:18:03 +00:00
2019-08-03 01:58:23 +00:00
"github.com/containous/traefik/v2/pkg/config/dynamic"
2019-09-13 17:28:04 +00:00
"github.com/containous/traefik/v2/pkg/log"
2019-08-03 01:58:23 +00:00
"github.com/containous/traefik/v2/pkg/middlewares"
"github.com/containous/traefik/v2/pkg/tracing"
2018-11-14 09:18:03 +00:00
"github.com/opentracing/opentracing-go/ext"
"github.com/unrolled/secure"
)
const (
2019-07-12 09:46:04 +00:00
typeName = "Headers"
2018-11-14 09:18:03 +00:00
)
func handleDeprecation(ctx context.Context, cfg *dynamic.Headers) {
if cfg.AccessControlAllowOrigin != "" {
log.FromContext(ctx).Warn("accessControlAllowOrigin is deprecated, please use accessControlAllowOriginList instead.")
cfg.AccessControlAllowOriginList = append(cfg.AccessControlAllowOriginList, cfg.AccessControlAllowOrigin)
cfg.AccessControlAllowOrigin = ""
}
}
2018-11-14 09:18:03 +00:00
type headers struct {
name string
handler http.Handler
}
// New creates a Headers middleware.
func New(ctx context.Context, next http.Handler, cfg dynamic.Headers, name string) (http.Handler, error) {
2018-11-14 09:18:03 +00:00
// HeaderMiddleware -> SecureMiddleWare -> next
mCtx := middlewares.GetLoggerCtx(ctx, name, typeName)
logger := log.FromContext(mCtx)
2018-11-14 09:18:03 +00:00
logger.Debug("Creating middleware")
2019-09-13 17:28:04 +00:00
handleDeprecation(mCtx, &cfg)
hasSecureHeaders := cfg.HasSecureHeadersDefined()
hasCustomHeaders := cfg.HasCustomHeadersDefined()
hasCorsHeaders := cfg.HasCorsHeadersDefined()
2019-04-02 08:40:04 +00:00
if !hasSecureHeaders && !hasCustomHeaders && !hasCorsHeaders {
2018-11-14 09:18:03 +00:00
return nil, errors.New("headers configuration not valid")
}
var handler http.Handler
nextHandler := next
2019-04-02 08:40:04 +00:00
if hasSecureHeaders {
logger.Debug("Setting up secureHeaders from %v", cfg)
handler = newSecure(next, cfg)
2018-11-14 09:18:03 +00:00
nextHandler = handler
}
2019-04-02 08:40:04 +00:00
if hasCustomHeaders || hasCorsHeaders {
logger.Debug("Setting up customHeaders/Cors from %v", cfg)
handler = NewHeader(nextHandler, cfg)
2018-11-14 09:18:03 +00:00
}
return &headers{
handler: handler,
name: name,
}, nil
}
func (h *headers) GetTracingInformation() (string, ext.SpanKindEnum) {
return h.name, tracing.SpanKindNoneEnum
}
func (h *headers) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
h.handler.ServeHTTP(rw, req)
}
type secureHeader struct {
next http.Handler
secure *secure.Secure
}
// newSecure constructs a new secure instance with supplied options.
func newSecure(next http.Handler, cfg dynamic.Headers) *secureHeader {
2018-11-14 09:18:03 +00:00
opt := secure.Options{
BrowserXssFilter: cfg.BrowserXSSFilter,
ContentTypeNosniff: cfg.ContentTypeNosniff,
ForceSTSHeader: cfg.ForceSTSHeader,
FrameDeny: cfg.FrameDeny,
IsDevelopment: cfg.IsDevelopment,
SSLRedirect: cfg.SSLRedirect,
SSLForceHost: cfg.SSLForceHost,
SSLTemporaryRedirect: cfg.SSLTemporaryRedirect,
STSIncludeSubdomains: cfg.STSIncludeSubdomains,
STSPreload: cfg.STSPreload,
ContentSecurityPolicy: cfg.ContentSecurityPolicy,
CustomBrowserXssValue: cfg.CustomBrowserXSSValue,
CustomFrameOptionsValue: cfg.CustomFrameOptionsValue,
PublicKey: cfg.PublicKey,
ReferrerPolicy: cfg.ReferrerPolicy,
SSLHost: cfg.SSLHost,
AllowedHosts: cfg.AllowedHosts,
HostsProxyHeaders: cfg.HostsProxyHeaders,
SSLProxyHeaders: cfg.SSLProxyHeaders,
STSSeconds: cfg.STSSeconds,
FeaturePolicy: cfg.FeaturePolicy,
2018-11-14 09:18:03 +00:00
}
return &secureHeader{
next: next,
secure: secure.New(opt),
}
}
func (s secureHeader) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
s.secure.HandlerFuncWithNextForRequestOnly(rw, req, s.next.ServeHTTP)
}
2019-07-12 09:46:04 +00:00
// Header is a middleware that helps setup a few basic security features.
// A single headerOptions struct can be provided to configure which features should be enabled,
// and the ability to override a few of the default values.
2019-04-02 08:40:04 +00:00
type Header struct {
2019-07-12 09:46:04 +00:00
next http.Handler
hasCustomHeaders bool
hasCorsHeaders bool
headers *dynamic.Headers
2018-11-14 09:18:03 +00:00
}
// NewHeader constructs a new header instance from supplied frontend header struct.
func NewHeader(next http.Handler, cfg dynamic.Headers) *Header {
hasCustomHeaders := cfg.HasCustomHeadersDefined()
hasCorsHeaders := cfg.HasCorsHeadersDefined()
ctx := log.With(context.Background(), log.Str(log.MiddlewareType, typeName))
handleDeprecation(ctx, &cfg)
2019-07-12 09:46:04 +00:00
2019-04-02 08:40:04 +00:00
return &Header{
2019-07-12 09:46:04 +00:00
next: next,
headers: &cfg,
2019-07-12 09:46:04 +00:00
hasCustomHeaders: hasCustomHeaders,
hasCorsHeaders: hasCorsHeaders,
2018-11-14 09:18:03 +00:00
}
}
2019-04-02 08:40:04 +00:00
func (s *Header) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
2019-07-12 09:46:04 +00:00
// Handle Cors headers and preflight if configured.
if isPreflight := s.processCorsHeaders(rw, req); isPreflight {
2019-04-02 08:40:04 +00:00
return
}
2019-07-12 09:46:04 +00:00
if s.hasCustomHeaders {
s.modifyCustomRequestHeaders(req)
2019-04-02 08:40:04 +00:00
}
// If there is a next, call it.
if s.next != nil {
s.next.ServeHTTP(rw, req)
}
2018-11-14 09:18:03 +00:00
}
2019-07-12 09:46:04 +00:00
// modifyCustomRequestHeaders sets or deletes custom request headers.
func (s *Header) modifyCustomRequestHeaders(req *http.Request) {
2018-11-14 09:18:03 +00:00
// Loop through Custom request headers
2019-04-02 08:40:04 +00:00
for header, value := range s.headers.CustomRequestHeaders {
2020-03-17 23:54:04 +00:00
switch {
case value == "":
2018-11-14 09:18:03 +00:00
req.Header.Del(header)
2020-03-17 23:54:04 +00:00
case strings.EqualFold(header, "Host"):
req.Host = value
default:
2018-11-14 09:18:03 +00:00
req.Header.Set(header, value)
}
}
}
2019-04-02 08:40:04 +00:00
2019-07-12 09:46:04 +00:00
// PostRequestModifyResponseHeaders set or delete response headers.
// This method is called AFTER the response is generated from the backend
// and can merge/override headers from the backend response.
func (s *Header) PostRequestModifyResponseHeaders(res *http.Response) error {
2019-04-02 08:40:04 +00:00
// Loop through Custom response headers
for header, value := range s.headers.CustomResponseHeaders {
if value == "" {
res.Header.Del(header)
} else {
res.Header.Set(header, value)
}
}
if res != nil && res.Request != nil {
originHeader := res.Request.Header.Get("Origin")
allowed, match := s.isOriginAllowed(originHeader)
if allowed {
res.Header.Set("Access-Control-Allow-Origin", match)
}
}
if s.headers.AccessControlAllowCredentials {
res.Header.Set("Access-Control-Allow-Credentials", "true")
}
if len(s.headers.AccessControlExposeHeaders) > 0 {
exposeHeaders := strings.Join(s.headers.AccessControlExposeHeaders, ",")
res.Header.Set("Access-Control-Expose-Headers", exposeHeaders)
}
2019-07-12 09:46:04 +00:00
if !s.headers.AddVaryHeader {
return nil
}
2019-04-02 08:40:04 +00:00
2019-07-12 09:46:04 +00:00
varyHeader := res.Header.Get("Vary")
if varyHeader == "Origin" {
return nil
}
2019-04-02 08:40:04 +00:00
2019-07-12 09:46:04 +00:00
if varyHeader != "" {
varyHeader += ","
2019-04-02 08:40:04 +00:00
}
2019-07-12 09:46:04 +00:00
varyHeader += "Origin"
2019-04-02 08:40:04 +00:00
2019-07-12 09:46:04 +00:00
res.Header.Set("Vary", varyHeader)
return nil
}
// processCorsHeaders processes the incoming request,
// and returns if it is a preflight request.
// If not a preflight, it handles the preRequestModifyCorsResponseHeaders.
func (s *Header) processCorsHeaders(rw http.ResponseWriter, req *http.Request) bool {
if !s.hasCorsHeaders {
return false
2019-04-02 08:40:04 +00:00
}
2019-07-12 09:46:04 +00:00
reqAcMethod := req.Header.Get("Access-Control-Request-Method")
originHeader := req.Header.Get("Origin")
if reqAcMethod != "" && originHeader != "" && req.Method == http.MethodOptions {
2019-07-12 09:46:04 +00:00
// If the request is an OPTIONS request with an Access-Control-Request-Method header,
// and Origin headers, then it is a CORS preflight request,
2019-07-12 09:46:04 +00:00
// and we need to build a custom response: https://www.w3.org/TR/cors/#preflight-request
if s.headers.AccessControlAllowCredentials {
rw.Header().Set("Access-Control-Allow-Credentials", "true")
}
allowHeaders := strings.Join(s.headers.AccessControlAllowHeaders, ",")
if allowHeaders != "" {
rw.Header().Set("Access-Control-Allow-Headers", allowHeaders)
}
allowMethods := strings.Join(s.headers.AccessControlAllowMethods, ",")
if allowMethods != "" {
rw.Header().Set("Access-Control-Allow-Methods", allowMethods)
}
allowed, match := s.isOriginAllowed(originHeader)
if allowed {
rw.Header().Set("Access-Control-Allow-Origin", match)
2019-07-12 09:46:04 +00:00
}
rw.Header().Set("Access-Control-Max-Age", strconv.Itoa(int(s.headers.AccessControlMaxAge)))
return true
2019-04-02 08:40:04 +00:00
}
2019-07-12 09:46:04 +00:00
return false
2019-04-02 08:40:04 +00:00
}
func (s *Header) isOriginAllowed(origin string) (bool, string) {
for _, item := range s.headers.AccessControlAllowOriginList {
if item == "*" || item == origin {
return true, item
2019-04-02 08:40:04 +00:00
}
}
return false, ""
2019-04-02 08:40:04 +00:00
}