go-zero/rest/handler/contentsecurityhandler.go

64 lines
2.2 KiB
Go
Raw Normal View History

2020-07-29 18:00:04 +08:00
package handler
2020-07-26 17:09:05 +08:00
import (
"net/http"
"time"
"github.com/zeromicro/go-zero/core/codec"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"github.com/zeromicro/go-zero/rest/internal/security"
2020-07-26 17:09:05 +08:00
)
const contentSecurity = "X-Content-Security"
2021-03-01 19:15:35 +08:00
// UnsignedCallback defines the method of the unsigned callback.
2020-07-26 17:09:05 +08:00
type UnsignedCallback func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int)
2021-03-01 19:15:35 +08:00
// ContentSecurityHandler returns a middleware to verify content security.
2020-07-26 17:09:05 +08:00
func ContentSecurityHandler(decrypters map[string]codec.RsaDecrypter, tolerance time.Duration,
strict bool, callbacks ...UnsignedCallback) func(http.Handler) http.Handler {
if len(callbacks) == 0 {
callbacks = append(callbacks, handleVerificationFailure)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodDelete, http.MethodGet, http.MethodPost, http.MethodPut:
2020-07-29 18:00:04 +08:00
header, err := security.ParseContentSecurity(decrypters, r)
2020-07-26 17:09:05 +08:00
if err != nil {
logx.Errorf("Signature parse failed, X-Content-Security: %s, error: %s",
2020-07-26 17:09:05 +08:00
r.Header.Get(contentSecurity), err.Error())
executeCallbacks(w, r, next, strict, httpx.CodeSignatureInvalidHeader, callbacks)
2020-07-29 18:00:04 +08:00
} else if code := security.VerifySignature(r, header, tolerance); code != httpx.CodeSignaturePass {
logx.Errorf("Signature verification failed, X-Content-Security: %s",
2020-07-26 17:09:05 +08:00
r.Header.Get(contentSecurity))
executeCallbacks(w, r, next, strict, code, callbacks)
} else if r.ContentLength > 0 && header.Encrypted() {
CryptionHandler(header.Key)(next).ServeHTTP(w, r)
} else {
next.ServeHTTP(w, r)
}
default:
next.ServeHTTP(w, r)
}
})
}
}
func executeCallbacks(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool,
code int, callbacks []UnsignedCallback) {
for _, callback := range callbacks {
callback(w, r, next, strict, code)
}
}
func handleVerificationFailure(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int) {
if strict {
w.WriteHeader(http.StatusForbidden)
2020-07-26 17:09:05 +08:00
} else {
next.ServeHTTP(w, r)
}
}