Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 859d4fa458 | |||
| 894614cd54 | |||
| c34f5b7d0d | |||
| f4a2452a94 | |||
| eda7c79ab6 | |||
| f72529aea5 | |||
|
|
116afe7930 |
@@ -27,7 +27,7 @@ func main() {
|
||||
r.Use(middleware1, middleware2)
|
||||
|
||||
// let's add a route
|
||||
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
r.GET("/hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("i am route /hello"))
|
||||
})
|
||||
// r.Post(pattern string, h http.HandlerFunc)
|
||||
@@ -37,7 +37,7 @@ func main() {
|
||||
// you can inline middleware(s) to a route
|
||||
r.
|
||||
With(mwInline).
|
||||
Get("/hello-2", func(w http.ResponseWriter, r *http.Request) {
|
||||
GET("/hello-2", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("i am route /hello-2 with my own middleware"))
|
||||
})
|
||||
|
||||
@@ -64,13 +64,13 @@ func main() {
|
||||
// create a group of few routes with their own middlewares
|
||||
r.Group(func(grp *mux.Router) {
|
||||
grp.Use(mwGroup)
|
||||
grp.Get("/group", func(w http.ResponseWriter, r *http.Request) {
|
||||
grp.GET("/group", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("i am route /group"))
|
||||
})
|
||||
})
|
||||
|
||||
// catches all
|
||||
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
r.GET("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("hello there"))
|
||||
})
|
||||
|
||||
|
||||
@@ -5,11 +5,16 @@ import (
|
||||
"net/http"
|
||||
|
||||
"gitserver.in/patialtech/mux"
|
||||
"gitserver.in/patialtech/mux/middleware"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// create a new router
|
||||
r := mux.NewRouter()
|
||||
r.Use(middleware.CORS(middleware.CORSOption{
|
||||
AllowedOrigins: []string{"*"},
|
||||
MaxAge: 60,
|
||||
}))
|
||||
|
||||
// you can use any middleware that is: "func(http.Handler) http.Handler"
|
||||
// so you can use any of it
|
||||
@@ -20,7 +25,7 @@ func main() {
|
||||
r.Use(middleware1, middleware2)
|
||||
|
||||
// let's add a route
|
||||
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
r.GET("/hello", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("i am route /hello"))
|
||||
})
|
||||
// r.Post(pattern string, h http.HandlerFunc)
|
||||
@@ -30,13 +35,13 @@ func main() {
|
||||
// you can inline middleware(s) to a route
|
||||
r.
|
||||
With(mwInline).
|
||||
Get("/hello-2", func(w http.ResponseWriter, r *http.Request) {
|
||||
GET("/hello-2", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("i am route /hello-2 with my own middleware"))
|
||||
})
|
||||
|
||||
// define a resource
|
||||
r.Resource("/photos", func(resource *mux.Resource) {
|
||||
// rails style resource routes
|
||||
// Rails style resource routes
|
||||
// GET /photos
|
||||
// GET /photos/new
|
||||
// POST /photos
|
||||
@@ -57,13 +62,13 @@ func main() {
|
||||
// create a group of few routes with their own middlewares
|
||||
r.Group(func(grp *mux.Router) {
|
||||
grp.Use(mwGroup)
|
||||
grp.Get("/group", func(w http.ResponseWriter, r *http.Request) {
|
||||
grp.GET("/group", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("i am route /group"))
|
||||
})
|
||||
})
|
||||
|
||||
// catches all
|
||||
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
r.GET("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("hello there"))
|
||||
})
|
||||
|
||||
|
||||
322
middleware/cors.go
Normal file
322
middleware/cors.go
Normal file
@@ -0,0 +1,322 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// copied from https://github.com/gorilla/handlers/blob/main/cors.go
|
||||
// with some editing to fit in
|
||||
//
|
||||
|
||||
// CORSOption represents a functional option for configuring the CORS middleware.
|
||||
type CORSOption struct {
|
||||
// AllowedOrigins list, including "*" will allow all
|
||||
AllowedOrigins []string
|
||||
|
||||
// AllowedHeaders are a list of headers clients are allowed to use with.
|
||||
// default: []string{"Accept", "Accept-Language", "Content-Language", "Origin"}
|
||||
AllowedHeaders []string
|
||||
|
||||
// AllowedMethods are a list of methods clients are allowed to use.
|
||||
//
|
||||
// default: []string{"HEAD", "GET", "POST"}
|
||||
AllowedMethods []string
|
||||
|
||||
ExposedHeaders []string
|
||||
// MaxAge in seconds, max allowed value is 600
|
||||
MaxAge uint
|
||||
AllowCredentials bool
|
||||
}
|
||||
|
||||
type cors struct {
|
||||
h http.Handler
|
||||
allowedHeaders []string
|
||||
allowedMethods []string
|
||||
allowedOrigins []string
|
||||
allowedOriginValidator OriginValidator
|
||||
exposedHeaders []string
|
||||
maxAge uint
|
||||
ignoreOptions bool
|
||||
allowCredentials bool
|
||||
optionStatusCode int
|
||||
}
|
||||
|
||||
// OriginValidator takes an origin string and returns whether that origin is allowed.
|
||||
type OriginValidator func(string) bool
|
||||
|
||||
var (
|
||||
defaultCorsOptionStatusCode = http.StatusOK
|
||||
defaultCorsMethods = []string{http.MethodHead, http.MethodGet, http.MethodPost}
|
||||
defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Type", "Content-Language", "Origin"}
|
||||
// (WebKit/Safari v9 sends the Origin header by default in AJAX requests).
|
||||
)
|
||||
|
||||
const (
|
||||
corsOptionMethod string = http.MethodOptions
|
||||
corsAllowOriginHeader string = "Access-Control-Allow-Origin"
|
||||
corsExposeHeadersHeader string = "Access-Control-Expose-Headers"
|
||||
corsMaxAgeHeader string = "Access-Control-Max-Age"
|
||||
corsAllowMethodsHeader string = "Access-Control-Allow-Methods"
|
||||
corsAllowHeadersHeader string = "Access-Control-Allow-Headers"
|
||||
corsAllowCredentialsHeader string = "Access-Control-Allow-Credentials"
|
||||
corsRequestMethodHeader string = "Access-Control-Request-Method"
|
||||
corsRequestHeadersHeader string = "Access-Control-Request-Headers"
|
||||
corsOriginHeader string = "Origin"
|
||||
corsVaryHeader string = "Vary"
|
||||
corsOriginMatchAll string = "*"
|
||||
)
|
||||
|
||||
// CORS provides Cross-Origin Resource Sharing middleware.
|
||||
// Example:
|
||||
//
|
||||
// import (
|
||||
// "net/http"
|
||||
// "gitserver.in/patialtech/mux/middleware"
|
||||
// "gitserver.in/patialtech/mux"
|
||||
// )
|
||||
//
|
||||
// func main() {
|
||||
// r := mux.NewRouter()
|
||||
// r.Use(middleware.CORS(middleware.CORSOption{
|
||||
// AllowedOrigins: []string{"*"},
|
||||
// MaxAge: 60,
|
||||
// }))
|
||||
//
|
||||
// r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
// w.Write([]byte("hello there"))
|
||||
// })
|
||||
//
|
||||
// r.Serve(func(srv *http.Server) error {
|
||||
// srv.Addr = ":3001"
|
||||
// slog.Info("listening on http://localhost" + srv.Addr)
|
||||
// return srv.ListenAndServe()
|
||||
// })
|
||||
// }
|
||||
func CORS(opts CORSOption) func(http.Handler) http.Handler {
|
||||
return func(h http.Handler) http.Handler {
|
||||
ch := &cors{
|
||||
h: h,
|
||||
allowedMethods: defaultCorsMethods,
|
||||
allowedHeaders: defaultCorsHeaders,
|
||||
allowedOrigins: []string{},
|
||||
optionStatusCode: defaultCorsOptionStatusCode,
|
||||
}
|
||||
|
||||
ch.setAllowedOrigins(opts.AllowedOrigins)
|
||||
ch.setAllowedHeaders(opts.AllowedHeaders)
|
||||
ch.setAllowedMethods(opts.AllowedMethods)
|
||||
ch.setExposedHeaders(opts.ExposedHeaders)
|
||||
ch.setMaxAge(opts.MaxAge)
|
||||
ch.maxAge = opts.MaxAge
|
||||
ch.allowCredentials = opts.AllowCredentials
|
||||
|
||||
return ch
|
||||
}
|
||||
}
|
||||
|
||||
func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
origin := r.Header.Get(corsOriginHeader)
|
||||
if !ch.isOriginAllowed(origin) {
|
||||
if r.Method != corsOptionMethod || ch.ignoreOptions {
|
||||
ch.h.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == corsOptionMethod {
|
||||
if ch.ignoreOptions {
|
||||
ch.h.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
if _, ok := r.Header[corsRequestMethodHeader]; !ok {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
method := r.Header.Get(corsRequestMethodHeader)
|
||||
if !ch.isMatch(method, ch.allowedMethods) {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
requestHeaders := strings.Split(r.Header.Get(corsRequestHeadersHeader), ",")
|
||||
var allowedHeaders []string
|
||||
for _, v := range requestHeaders {
|
||||
canonicalHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
|
||||
if canonicalHeader == "" || ch.isMatch(canonicalHeader, defaultCorsHeaders) {
|
||||
continue
|
||||
}
|
||||
|
||||
if !ch.isMatch(canonicalHeader, ch.allowedHeaders) {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
allowedHeaders = append(allowedHeaders, canonicalHeader)
|
||||
}
|
||||
|
||||
if len(allowedHeaders) > 0 {
|
||||
w.Header().Set(corsAllowHeadersHeader, strings.Join(allowedHeaders, ","))
|
||||
}
|
||||
|
||||
if ch.maxAge > 0 {
|
||||
w.Header().Set(corsMaxAgeHeader, strconv.Itoa(int(ch.maxAge)))
|
||||
}
|
||||
|
||||
if !ch.isMatch(method, defaultCorsMethods) {
|
||||
w.Header().Set(corsAllowMethodsHeader, method)
|
||||
}
|
||||
} else if len(ch.exposedHeaders) > 0 {
|
||||
w.Header().Set(corsExposeHeadersHeader, strings.Join(ch.exposedHeaders, ","))
|
||||
}
|
||||
|
||||
if ch.allowCredentials {
|
||||
w.Header().Set(corsAllowCredentialsHeader, "true")
|
||||
}
|
||||
|
||||
if len(ch.allowedOrigins) > 1 {
|
||||
w.Header().Set(corsVaryHeader, corsOriginHeader)
|
||||
}
|
||||
|
||||
returnOrigin := origin
|
||||
if ch.allowedOriginValidator == nil && len(ch.allowedOrigins) == 0 {
|
||||
returnOrigin = "*"
|
||||
} else {
|
||||
for _, o := range ch.allowedOrigins {
|
||||
// A configuration of * is different from explicitly setting an allowed
|
||||
// origin. Returning arbitrary origin headers in an access control allow
|
||||
// origin header is unsafe and is not required by any use case.
|
||||
if o == corsOriginMatchAll {
|
||||
returnOrigin = "*"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
w.Header().Set(corsAllowOriginHeader, returnOrigin)
|
||||
|
||||
if r.Method == corsOptionMethod {
|
||||
w.WriteHeader(ch.optionStatusCode)
|
||||
return
|
||||
}
|
||||
ch.h.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// AllowedOrigins sets the allowed origins for CORS requests, as used in the
|
||||
// 'Allow-Access-Control-Origin' HTTP header.
|
||||
// Note: Passing in a []string{"*"} will allow any domain.
|
||||
func (ch *cors) setAllowedOrigins(origins []string) {
|
||||
// look for "*"
|
||||
for _, v := range origins {
|
||||
if v == corsOriginMatchAll {
|
||||
ch.allowedOrigins = []string{corsOriginMatchAll}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ch.allowedOrigins = origins
|
||||
}
|
||||
|
||||
// setAllowedHeaders adds the provided headers to the list of allowed headers in a
|
||||
// CORS request.
|
||||
// This is an appended operation, so the headers Accept, Accept-Language,
|
||||
// and Content-Language are always allowed.
|
||||
// Content-Type must be explicitly declared if accepting Content-Types other than
|
||||
// application/x-www-form-urlencoded, multipart/form-data, or text/plain.
|
||||
func (ch *cors) setAllowedHeaders(headers []string) {
|
||||
for _, v := range headers {
|
||||
normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
|
||||
if normalizedHeader == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if !ch.isMatch(normalizedHeader, ch.allowedHeaders) {
|
||||
ch.allowedHeaders = append(ch.allowedHeaders, normalizedHeader)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// AllowedMethods can be used to explicitly allow methods in the
|
||||
// Access-Control-Allow-Methods header.
|
||||
// This is a replacement operation, so you must also
|
||||
// pass GET, HEAD, and POST if you wish to support those methods.
|
||||
func (ch *cors) setAllowedMethods(methods []string) {
|
||||
if len(methods) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
ch.allowedMethods = []string{}
|
||||
for _, v := range methods {
|
||||
normalizedMethod := strings.ToUpper(strings.TrimSpace(v))
|
||||
if normalizedMethod == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if !ch.isMatch(normalizedMethod, ch.allowedMethods) {
|
||||
ch.allowedMethods = append(ch.allowedMethods, normalizedMethod)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ExposedHeaders can be used to specify headers that are available
|
||||
// and will not be stripped out by the user-agent.
|
||||
func (ch *cors) setExposedHeaders(headers []string) {
|
||||
ch.exposedHeaders = []string{}
|
||||
for _, v := range headers {
|
||||
normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
|
||||
if normalizedHeader == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
if !ch.isMatch(normalizedHeader, ch.exposedHeaders) {
|
||||
ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MaxAge determines the maximum age (in seconds) between preflight requests. A
|
||||
// maximum of 10 minutes is allowed. An age above this value will default to 10
|
||||
// minutes.
|
||||
func (ch *cors) setMaxAge(age uint) {
|
||||
// Maximum of 10 minutes.
|
||||
if age > 600 {
|
||||
age = 600
|
||||
}
|
||||
|
||||
ch.maxAge = age
|
||||
}
|
||||
|
||||
func (ch *cors) isOriginAllowed(origin string) bool {
|
||||
if origin == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if ch.allowedOriginValidator != nil {
|
||||
return ch.allowedOriginValidator(origin)
|
||||
}
|
||||
|
||||
if len(ch.allowedOrigins) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, allowedOrigin := range ch.allowedOrigins {
|
||||
if allowedOrigin == origin || allowedOrigin == corsOriginMatchAll {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (ch *cors) isMatch(needle string, haystack []string) bool {
|
||||
for _, v := range haystack {
|
||||
if v == needle {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
351
middleware/helmet.go
Normal file
351
middleware/helmet.go
Normal file
@@ -0,0 +1,351 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// inspired from Helmet.js
|
||||
// https://github.com/helmetjs/helmet/tree/main
|
||||
|
||||
type (
|
||||
HelmetOption struct {
|
||||
ContentSecurityPolicy CSP
|
||||
|
||||
StrictTransportSecurity *TransportSecurity
|
||||
|
||||
// "require-corp" will be the default policy
|
||||
CrossOriginEmbedderPolicy Embedder
|
||||
|
||||
// "same-origin" will be the default policy
|
||||
CrossOriginOpenerPolicy Opener
|
||||
|
||||
// "same-origin" will be the default policy
|
||||
CrossOriginResourcePolicy Resource
|
||||
|
||||
// "no-referrer" will be the default policy
|
||||
ReferrerPolicy []Referrer
|
||||
|
||||
OriginAgentCluster bool
|
||||
|
||||
// set true to remove header "X-Content-Type-Options"
|
||||
DisableSniffMimeType bool
|
||||
|
||||
// set true for header "X-DNS-Prefetch-Control: off"
|
||||
//
|
||||
// default is "X-DNS-Prefetch-Control: on"
|
||||
DisableDNSPrefetch bool
|
||||
|
||||
// set true to remove header "X-Download-Options: noopen"
|
||||
DisableXDownload bool
|
||||
|
||||
// X-Frame-Options
|
||||
XFrameOption XFrame
|
||||
|
||||
// X-Permitted-Cross-Domain-Policies
|
||||
//
|
||||
// default value will be "none"
|
||||
CrossDomainPolicies CDP
|
||||
|
||||
// X-XSS-Protection
|
||||
//
|
||||
// default is off
|
||||
XssProtection bool
|
||||
}
|
||||
|
||||
// CSP is Content-Security-Policy settings
|
||||
//
|
||||
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/Sources
|
||||
CSP struct {
|
||||
// default-src, default value will be 'self'
|
||||
DefaultSrc []string
|
||||
// script-src, default value will be 'self'
|
||||
ScriptSrc []string
|
||||
// script-src-attr, default value will be 'none'
|
||||
ScriptSrcAttr []string
|
||||
// style-src, default value will be 'self' https: 'unsafe-inline'
|
||||
StyleSrc []string
|
||||
// img-src, default value will be 'self' data:
|
||||
ImgSrc []string
|
||||
// object-src, default value will be 'none'
|
||||
ObjectSrc []string
|
||||
// base-uri, default value will be 'self'
|
||||
BaseUri []string
|
||||
// font-src, default value will be 'self' https: data:
|
||||
FontSrc []string
|
||||
// form-action, default value will be 'self'
|
||||
FormAction []string
|
||||
// frame-ancestors, default value will be 'self'
|
||||
FrameAncestors []string
|
||||
|
||||
UpgradeInsecureRequests bool
|
||||
}
|
||||
|
||||
TransportSecurity struct {
|
||||
// Age in seconts
|
||||
MaxAge uint
|
||||
IncludeSubDomains bool
|
||||
Preload bool
|
||||
}
|
||||
|
||||
Embedder string
|
||||
Opener string
|
||||
Resource string
|
||||
Referrer string
|
||||
// CDP Cross-Domain-Policy
|
||||
CDP string
|
||||
XFrame string
|
||||
)
|
||||
|
||||
const (
|
||||
YearDuration = 365 * 24 * 60 * 60
|
||||
|
||||
// EmbedderDefault default value will be "require-corp"
|
||||
EmbedderDefault Embedder = ""
|
||||
EmbedderRequireCorp Embedder = "require-corp"
|
||||
EmbedderCredentialLess Embedder = "credentialless"
|
||||
EmbedderUnsafeNone Embedder = "unsafe-none"
|
||||
|
||||
// OpenerDefault default value will be "same-origin"
|
||||
OpenerDefault Opener = ""
|
||||
OpenerSameOrigin Opener = "same-origin"
|
||||
OpenerSameOriginAllowPopups Opener = "same-origin-allow-popups"
|
||||
OpenerUnsafeNone Opener = "unsafe-none"
|
||||
|
||||
// ResourceDefault default value will be "same-origin"
|
||||
ResourceDefault Resource = ""
|
||||
ResourceSameOrigin Resource = "same-origin"
|
||||
ResourceSameSite Resource = "same-site"
|
||||
ResourceCrossOrigin Resource = "cross-origin"
|
||||
|
||||
NoReferrer Referrer = "no-referrer"
|
||||
NoReferrerWhenDowngrade Referrer = "no-referrer-when-downgrade"
|
||||
SameOrigin Referrer = "same-origin"
|
||||
Origin Referrer = "origin"
|
||||
StrictOrigin Referrer = "strict-origin"
|
||||
OriginWhenCrossOrigin Referrer = "origin-when-cross-origin"
|
||||
StrictOriginWhenCrossOrigin Referrer = "strict-origin-when-cross-origin"
|
||||
UnsafeUrl Referrer = "unsafe-url"
|
||||
|
||||
// CDPDefault default value is "none"
|
||||
CDPDefault CDP = ""
|
||||
CDPNone CDP = "none"
|
||||
CDPMasterOnly CDP = "master-only"
|
||||
CDPByContentType CDP = "by-content-type"
|
||||
CDPAll CDP = "all"
|
||||
|
||||
// XFrameDefault default value will be "sameorigin"
|
||||
XFrameDefault XFrame = ""
|
||||
XFrameSameOrigin XFrame = "sameorigin"
|
||||
XFrameDeny XFrame = "deny"
|
||||
)
|
||||
|
||||
// Helmet headers to secure server response
|
||||
func Helmet(opt HelmetOption) func(http.Handler) http.Handler {
|
||||
return func(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Add("Content-Security-Policy", opt.ContentSecurityPolicy.value())
|
||||
|
||||
// Cross-Origin-Embedder-Policy, if nil set default
|
||||
if opt.CrossOriginEmbedderPolicy == EmbedderDefault {
|
||||
w.Header().Add("Cross-Origin-Embedder-Policy", string(EmbedderRequireCorp))
|
||||
} else {
|
||||
w.Header().Add("Cross-Origin-Embedder-Policy", string(opt.CrossOriginEmbedderPolicy))
|
||||
}
|
||||
|
||||
// Cross-Origin-Opener-Policy, if nil set default
|
||||
if opt.CrossOriginOpenerPolicy == OpenerDefault {
|
||||
w.Header().Add("Cross-Origin-Opener-Policy", string(OpenerSameOrigin))
|
||||
} else {
|
||||
w.Header().Add("Cross-Origin-Opener-Policy", string(opt.CrossOriginOpenerPolicy))
|
||||
}
|
||||
|
||||
// Cross-Origin-Resource-Policy, if nil set default
|
||||
if opt.CrossOriginResourcePolicy == ResourceDefault {
|
||||
w.Header().Add("Cross-Origin-Resource-Policy", string(ResourceSameOrigin))
|
||||
} else {
|
||||
w.Header().Add("Cross-Origin-Resource-Policy", string(opt.CrossOriginResourcePolicy))
|
||||
}
|
||||
|
||||
// Referrer-Policy
|
||||
rpCount := len(opt.ReferrerPolicy)
|
||||
if rpCount > 0 {
|
||||
refP := make([]string, rpCount)
|
||||
for i, r := range opt.ReferrerPolicy {
|
||||
refP[i] = string(r)
|
||||
}
|
||||
w.Header().Add("Referrer-Policy", string(NoReferrer))
|
||||
} else {
|
||||
// default no referer
|
||||
w.Header().Add("Referrer-Policy", string(NoReferrer))
|
||||
}
|
||||
|
||||
// Origin-Agent-Cluster
|
||||
if opt.OriginAgentCluster {
|
||||
w.Header().Add("Origin-Agent-Cluster", "?1")
|
||||
}
|
||||
|
||||
// Strict-Transport-Security
|
||||
if opt.StrictTransportSecurity != nil {
|
||||
var sb strings.Builder
|
||||
|
||||
if opt.StrictTransportSecurity.MaxAge == 0 {
|
||||
opt.StrictTransportSecurity.MaxAge = YearDuration
|
||||
}
|
||||
|
||||
sb.WriteString(fmt.Sprintf("max-age=%d", opt.StrictTransportSecurity.MaxAge))
|
||||
if opt.StrictTransportSecurity.IncludeSubDomains {
|
||||
sb.WriteString("; includeSubDomains")
|
||||
}
|
||||
|
||||
if opt.StrictTransportSecurity.Preload {
|
||||
sb.WriteString("; preload")
|
||||
}
|
||||
|
||||
w.Header().Add("Strict-Transport-Security", sb.String())
|
||||
}
|
||||
|
||||
if !opt.DisableSniffMimeType {
|
||||
// MIME types advertised in the Content-Current headers should be followed and not be changed
|
||||
w.Header().Add("X-Content-Type-Options", "nosniff")
|
||||
}
|
||||
|
||||
if opt.DisableDNSPrefetch {
|
||||
w.Header().Add("X-DNS-Prefetch-Control", "off")
|
||||
} else {
|
||||
w.Header().Add("X-DNS-Prefetch-Control", "on")
|
||||
}
|
||||
|
||||
if !opt.DisableXDownload {
|
||||
// Instructs Internet Explorer not to open the file directly but to offer it for download first.
|
||||
w.Header().Add("X-Download-Options", "noopen")
|
||||
}
|
||||
|
||||
// indicate whether a browser should be allowed to render a page in iframe | frame | embed | object
|
||||
if opt.XFrameOption == XFrameDefault {
|
||||
w.Header().Add("X-Frame-Options", string(XFrameSameOrigin))
|
||||
} else {
|
||||
w.Header().Add("X-Frame-Options", string(opt.XFrameOption))
|
||||
}
|
||||
|
||||
if opt.CrossDomainPolicies == CDPDefault {
|
||||
w.Header().Add("X-Permitted-Cross-Domain-Policies", string(CDPNone))
|
||||
} else {
|
||||
w.Header().Add("X-Permitted-Cross-Domain-Policies", string(opt.CrossDomainPolicies))
|
||||
}
|
||||
|
||||
w.Header().Del("X-Powered-By")
|
||||
|
||||
if opt.XssProtection {
|
||||
// feature of IE, Chrome and Safari that stops pages from loading when they detect reflected
|
||||
// cross-site scripting (XSS) attacks.
|
||||
w.Header().Add("X-Xss-Protection", "1; mode=block")
|
||||
} else {
|
||||
// Following a decision by Google Chrome developers to disable Auditor,
|
||||
// developers should be able to disable the auditor for older browsers and set it to 0.
|
||||
// The X-XSS-PROTECTION header was found to have a multitude of issues, instead of helping the
|
||||
// developers protect their application.
|
||||
w.Header().Add("X-Xss-Protection", "0")
|
||||
}
|
||||
|
||||
h.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (csp *CSP) value() string {
|
||||
var sb strings.Builder
|
||||
|
||||
// should be the first thing
|
||||
if csp.UpgradeInsecureRequests {
|
||||
sb.WriteString("upgrade-insecure-requests;")
|
||||
}
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"default-src %s; ",
|
||||
cspNormalised(csp.DefaultSrc, []string{"self"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"script-src %s; ",
|
||||
cspNormalised(csp.ScriptSrc, []string{"self"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"script-src-attr %s; ",
|
||||
cspNormalised(csp.ScriptSrcAttr, []string{"none"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"style-src %s; ",
|
||||
cspNormalised(csp.StyleSrc, []string{"self", "https:", "unsafe-inline"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"img-src %s; ",
|
||||
cspNormalised(csp.ImgSrc, []string{"self", "data:"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"object-src %s; ",
|
||||
cspNormalised(csp.ObjectSrc, []string{"none"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"base-uri %s; ",
|
||||
cspNormalised(csp.BaseUri, []string{"self"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"font-src %s; ",
|
||||
cspNormalised(csp.FontSrc, []string{"self", "https:", "data:"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"form-action %s; ",
|
||||
cspNormalised(csp.FormAction, []string{"self"}),
|
||||
))
|
||||
|
||||
sb.WriteString(fmt.Sprintf(
|
||||
"frame-ancestors %s; ",
|
||||
cspNormalised(csp.FrameAncestors, []string{"self"}),
|
||||
))
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func cspNormalised(v, defaultVal []string) string {
|
||||
if len(v) == 0 {
|
||||
v = defaultVal
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
for _, val := range v {
|
||||
val = strings.TrimSpace(val)
|
||||
if val == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
sb.WriteString(" " + cspQuoted(val))
|
||||
}
|
||||
|
||||
return strings.TrimSpace(sb.String())
|
||||
}
|
||||
|
||||
func cspQuoted(v string) string {
|
||||
switch v {
|
||||
case "none",
|
||||
"self",
|
||||
"strict-dynamic",
|
||||
"report-sample",
|
||||
"inline-speculation-rules",
|
||||
"unsafe-inline",
|
||||
"unsafe-eval",
|
||||
"unsafe-hashes",
|
||||
"wasm-unsafe-eval":
|
||||
return fmt.Sprintf("'%s'", v)
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
52
middleware/helmet_test.go
Normal file
52
middleware/helmet_test.go
Normal file
@@ -0,0 +1,52 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"gitserver.in/patialtech/mux"
|
||||
)
|
||||
|
||||
func TestHelmet(t *testing.T) {
|
||||
r := mux.NewRouter()
|
||||
r.Use(Helmet(HelmetOption{}))
|
||||
r.Get("/hello", func(writer http.ResponseWriter, request *http.Request) {
|
||||
_, _ = writer.Write([]byte("hello there"))
|
||||
})
|
||||
|
||||
srv := httptest.NewServer(r)
|
||||
defer srv.Close()
|
||||
w, _ := testRequest(t, srv, "GET", "/hello", nil)
|
||||
|
||||
csp := w.Header.Get("Content-Security-Policy")
|
||||
// must not have a csp header, technically no header related to helmet but lets test with one.
|
||||
if csp == "" {
|
||||
t.Error("csp header is expected")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (*http.Response, string) {
|
||||
req, err := http.NewRequest(method, ts.URL+path, body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
respBody, err := io.ReadAll(io.Reader(resp.Body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
return nil, ""
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
return resp, string(respBody)
|
||||
}
|
||||
43
router.go
43
router.go
@@ -14,9 +14,10 @@ type Router struct {
|
||||
}
|
||||
|
||||
func NewRouter() *Router {
|
||||
return &Router{
|
||||
r := &Router{
|
||||
mux: http.NewServeMux(),
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// Use will register middleware(s) with router stack
|
||||
@@ -27,48 +28,46 @@ func (r *Router) Use(h ...func(http.Handler) http.Handler) {
|
||||
r.middlewares = append(r.middlewares, h...)
|
||||
}
|
||||
|
||||
// Get method route
|
||||
func (r *Router) Get(pattern string, h http.HandlerFunc) {
|
||||
// GET method route
|
||||
func (r *Router) GET(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodGet, pattern, h)
|
||||
}
|
||||
|
||||
// Head method route
|
||||
func (r *Router) Head(pattern string, h http.HandlerFunc) {
|
||||
// HEAD method route
|
||||
func (r *Router) HEAD(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodHead, pattern, h)
|
||||
}
|
||||
|
||||
// Post method route
|
||||
func (r *Router) Post(pattern string, h http.HandlerFunc) {
|
||||
// POST method route
|
||||
func (r *Router) POST(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodPost, pattern, h)
|
||||
}
|
||||
|
||||
// Put method route
|
||||
func (r *Router) Put(pattern string, h http.HandlerFunc) {
|
||||
// PUT method route
|
||||
func (r *Router) PUT(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodPut, pattern, h)
|
||||
}
|
||||
|
||||
// Patch method route
|
||||
func (r *Router) Patch(pattern string, h http.HandlerFunc) {
|
||||
// PATCH method route
|
||||
func (r *Router) PATCH(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodPatch, pattern, h)
|
||||
}
|
||||
|
||||
// Delete method route
|
||||
func (r *Router) Delete(pattern string, h http.HandlerFunc) {
|
||||
// DELETE method route
|
||||
func (r *Router) DELETE(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodDelete, pattern, h)
|
||||
}
|
||||
|
||||
// Connect method route
|
||||
func (r *Router) Connect(pattern string, h http.HandlerFunc) {
|
||||
// CONNECT method route
|
||||
func (r *Router) CONNECT(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodConnect, pattern, h)
|
||||
}
|
||||
|
||||
// Options method route
|
||||
func (r *Router) Options(pattern string, h http.HandlerFunc) {
|
||||
} // OPTIONS method route
|
||||
func (r *Router) OPTIONS(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodOptions, pattern, h)
|
||||
}
|
||||
|
||||
// Trace method route
|
||||
func (r *Router) Trace(pattern string, h http.HandlerFunc) {
|
||||
// TRACE method route
|
||||
func (r *Router) TRACE(pattern string, h http.HandlerFunc) {
|
||||
r.handlerFunc(http.MethodTrace, pattern, h)
|
||||
}
|
||||
|
||||
@@ -144,6 +143,8 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
r.mux.ServeHTTP(w, req)
|
||||
}
|
||||
|
||||
// TODO: proxy for aws lambda
|
||||
|
||||
// stack middlewares(http handler) in order they are passed (FIFO)
|
||||
func stack(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
|
||||
// Return ahead of time if there aren't any middlewares for the chain
|
||||
|
||||
@@ -3,6 +3,7 @@ package mux
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -13,6 +14,21 @@ type ServeCB func(srv *http.Server) error
|
||||
|
||||
// Serve with graceful shutdown
|
||||
func (r *Router) Serve(cb ServeCB) {
|
||||
// catch all options
|
||||
// lets get it thorugh all middlewares
|
||||
r.OPTIONS("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Length", "0")
|
||||
if r.ContentLength != 0 {
|
||||
// Read up to 4KB of OPTIONS body (as mentioned in the
|
||||
// spec as being reserved for future use), but anything
|
||||
// over that is considered a waste of server resources
|
||||
// (or an attack) and we abort and close the connection,
|
||||
// courtesy of MaxBytesReader's EOF behavior.
|
||||
mb := http.MaxBytesReader(w, r.Body, 4<<10)
|
||||
io.Copy(io.Discard, mb)
|
||||
}
|
||||
})
|
||||
|
||||
srv := &http.Server{
|
||||
Handler: r,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user