You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.9 KiB
Go
62 lines
1.9 KiB
Go
4 years ago
|
package handler
|
||
4 years ago
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"zero/core/codec"
|
||
|
"zero/core/logx"
|
||
4 years ago
|
"zero/rest/httpx"
|
||
|
"zero/rest/internal/security"
|
||
4 years ago
|
)
|
||
|
|
||
|
const contentSecurity = "X-Content-Security"
|
||
|
|
||
|
type UnsignedCallback func(w http.ResponseWriter, r *http.Request, next http.Handler, strict bool, code int)
|
||
|
|
||
|
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:
|
||
4 years ago
|
header, err := security.ParseContentSecurity(decrypters, r)
|
||
4 years ago
|
if err != nil {
|
||
|
logx.Infof("Signature parse failed, X-Content-Security: %s, error: %s",
|
||
|
r.Header.Get(contentSecurity), err.Error())
|
||
|
executeCallbacks(w, r, next, strict, httpx.CodeSignatureInvalidHeader, callbacks)
|
||
4 years ago
|
} else if code := security.VerifySignature(r, header, tolerance); code != httpx.CodeSignaturePass {
|
||
4 years ago
|
logx.Infof("Signature verification failed, X-Content-Security: %s",
|
||
|
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.StatusUnauthorized)
|
||
|
} else {
|
||
|
next.ServeHTTP(w, r)
|
||
|
}
|
||
|
}
|