mirror of
https://github.com/labstack/echo.git
synced 2025-01-24 03:16:14 +02:00
6ef5f77bf2
WIP: make default logger implemented custom writer for jsonlike logs WIP: improve examples WIP: defaultErrorHandler use errors.As to unwrap errors. Update readme WIP: default logger logs json, restore e.Start method WIP: clean router.Match a bit WIP: func types/fields have echo.Context has first element WIP: remove yaml tags as functions etc can not be serialized anyway WIP: change BindPathParams,BindQueryParams,BindHeaders from methods to functions and reverse arguments to be like DefaultBinder.Bind is WIP: improved comments, logger now extracts status from error WIP: go mod tidy WIP: rebase with 4.5.0 WIP: * removed todos. * removed StartAutoTLS and StartH2CServer methods from `StartConfig` * KeyAuth middleware errorhandler can swallow the error and resume next middleware WIP: add RouterConfig.UseEscapedPathForMatching to use escaped path for matching request against routes WIP: FIXMEs WIP: upgrade golang-jwt/jwt to `v4` WIP: refactor http methods to return RouteInfo WIP: refactor static not creating multiple routes WIP: refactor route and middleware adding functions not to return error directly WIP: Use 401 for problematic/missing headers for key auth and JWT middleware (#1552, #1402). > In summary, a 401 Unauthorized response should be used for missing or bad authentication WIP: replace `HTTPError.SetInternal` with `HTTPError.WithInternal` so we could not mutate global error variables WIP: add RouteInfo and RouteMatchType into Context what we could know from in middleware what route was matched and/or type of that match (200/404/405) WIP: make notFoundHandler and methodNotAllowedHandler private. encourage that all errors be handled in Echo.HTTPErrorHandler WIP: server cleanup ideas WIP: routable.ForGroup WIP: note about logger middleware WIP: bind should not default values on second try. use crypto rand for better randomness WIP: router add route as interface and returns info as interface WIP: improve flaky test (remains still flaky) WIP: add notes about bind default values WIP: every route can have their own path params names WIP: routerCreator and different tests WIP: different things WIP: remove route implementation WIP: support custom method types WIP: extractor tests WIP: v5.0.x proposal over v4.4.0
146 lines
5.4 KiB
Go
146 lines
5.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
// SecureConfig defines the config for Secure middleware.
|
|
type SecureConfig struct {
|
|
// Skipper defines a function to skip middleware.
|
|
Skipper Skipper
|
|
|
|
// XSSProtection provides protection against cross-site scripting attack (XSS)
|
|
// by setting the `X-XSS-Protection` header.
|
|
// Optional. Default value "1; mode=block".
|
|
XSSProtection string
|
|
|
|
// ContentTypeNosniff provides protection against overriding Content-Type
|
|
// header by setting the `X-Content-Type-Options` header.
|
|
// Optional. Default value "nosniff".
|
|
ContentTypeNosniff string
|
|
|
|
// XFrameOptions can be used to indicate whether or not a browser should
|
|
// be allowed to render a page in a <frame>, <iframe> or <object> .
|
|
// Sites can use this to avoid clickjacking attacks, by ensuring that their
|
|
// content is not embedded into other sites.provides protection against
|
|
// clickjacking.
|
|
// Optional. Default value "SAMEORIGIN".
|
|
// Possible values:
|
|
// - "SAMEORIGIN" - The page can only be displayed in a frame on the same origin as the page itself.
|
|
// - "DENY" - The page cannot be displayed in a frame, regardless of the site attempting to do so.
|
|
// - "ALLOW-FROM uri" - The page can only be displayed in a frame on the specified origin.
|
|
XFrameOptions string
|
|
|
|
// HSTSMaxAge sets the `Strict-Transport-Security` header to indicate how
|
|
// long (in seconds) browsers should remember that this site is only to
|
|
// be accessed using HTTPS. This reduces your exposure to some SSL-stripping
|
|
// man-in-the-middle (MITM) attacks.
|
|
// Optional. Default value 0.
|
|
HSTSMaxAge int
|
|
|
|
// HSTSExcludeSubdomains won't include subdomains tag in the `Strict Transport Security`
|
|
// header, excluding all subdomains from security policy. It has no effect
|
|
// unless HSTSMaxAge is set to a non-zero value.
|
|
// Optional. Default value false.
|
|
HSTSExcludeSubdomains bool
|
|
|
|
// ContentSecurityPolicy sets the `Content-Security-Policy` header providing
|
|
// security against cross-site scripting (XSS), clickjacking and other code
|
|
// injection attacks resulting from execution of malicious content in the
|
|
// trusted web page context.
|
|
// Optional. Default value "".
|
|
ContentSecurityPolicy string
|
|
|
|
// CSPReportOnly would use the `Content-Security-Policy-Report-Only` header instead
|
|
// of the `Content-Security-Policy` header. This allows iterative updates of the
|
|
// content security policy by only reporting the violations that would
|
|
// have occurred instead of blocking the resource.
|
|
// Optional. Default value false.
|
|
CSPReportOnly bool
|
|
|
|
// HSTSPreloadEnabled will add the preload tag in the `Strict Transport Security`
|
|
// header, which enables the domain to be included in the HSTS preload list
|
|
// maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/
|
|
// Optional. Default value false.
|
|
HSTSPreloadEnabled bool
|
|
|
|
// ReferrerPolicy sets the `Referrer-Policy` header providing security against
|
|
// leaking potentially sensitive request paths to third parties.
|
|
// Optional. Default value "".
|
|
ReferrerPolicy string
|
|
}
|
|
|
|
// DefaultSecureConfig is the default Secure middleware config.
|
|
var DefaultSecureConfig = SecureConfig{
|
|
Skipper: DefaultSkipper,
|
|
XSSProtection: "1; mode=block",
|
|
ContentTypeNosniff: "nosniff",
|
|
XFrameOptions: "SAMEORIGIN",
|
|
HSTSPreloadEnabled: false,
|
|
}
|
|
|
|
// Secure returns a Secure middleware.
|
|
// Secure middleware provides protection against cross-site scripting (XSS) attack,
|
|
// content type sniffing, clickjacking, insecure connection and other code injection
|
|
// attacks.
|
|
func Secure() echo.MiddlewareFunc {
|
|
return SecureWithConfig(DefaultSecureConfig)
|
|
}
|
|
|
|
// SecureWithConfig returns a Secure middleware with config or panics on invalid configuration.
|
|
func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc {
|
|
return toMiddlewareOrPanic(config)
|
|
}
|
|
|
|
// ToMiddleware converts SecureConfig to middleware or returns an error for invalid configuration
|
|
func (config SecureConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
|
|
// Defaults
|
|
if config.Skipper == nil {
|
|
config.Skipper = DefaultSecureConfig.Skipper
|
|
}
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
if config.Skipper(c) {
|
|
return next(c)
|
|
}
|
|
|
|
req := c.Request()
|
|
res := c.Response()
|
|
|
|
if config.XSSProtection != "" {
|
|
res.Header().Set(echo.HeaderXXSSProtection, config.XSSProtection)
|
|
}
|
|
if config.ContentTypeNosniff != "" {
|
|
res.Header().Set(echo.HeaderXContentTypeOptions, config.ContentTypeNosniff)
|
|
}
|
|
if config.XFrameOptions != "" {
|
|
res.Header().Set(echo.HeaderXFrameOptions, config.XFrameOptions)
|
|
}
|
|
if (c.IsTLS() || (req.Header.Get(echo.HeaderXForwardedProto) == "https")) && config.HSTSMaxAge != 0 {
|
|
subdomains := ""
|
|
if !config.HSTSExcludeSubdomains {
|
|
subdomains = "; includeSubdomains"
|
|
}
|
|
if config.HSTSPreloadEnabled {
|
|
subdomains = fmt.Sprintf("%s; preload", subdomains)
|
|
}
|
|
res.Header().Set(echo.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains))
|
|
}
|
|
if config.ContentSecurityPolicy != "" {
|
|
if config.CSPReportOnly {
|
|
res.Header().Set(echo.HeaderContentSecurityPolicyReportOnly, config.ContentSecurityPolicy)
|
|
} else {
|
|
res.Header().Set(echo.HeaderContentSecurityPolicy, config.ContentSecurityPolicy)
|
|
}
|
|
}
|
|
if config.ReferrerPolicy != "" {
|
|
res.Header().Set(echo.HeaderReferrerPolicy, config.ReferrerPolicy)
|
|
}
|
|
return next(c)
|
|
}
|
|
}, nil
|
|
}
|