-
Notifications
You must be signed in to change notification settings - Fork 0
/
digestvalidate.go
61 lines (53 loc) · 1.34 KB
/
digestvalidate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package validator
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
)
// TODO: support more digest
// ErrInvalidDigest error when sha256 of body do not match with submitted digest
var ErrInvalidDigest = &gin.Error{
Err: errors.New("sha256 of body is not match with digest"),
Type: gin.ErrorTypePublic,
}
// DigestValidator checking digest in header match body
type DigestValidator struct{}
// NewDigestValidator return pointer of new DigestValidator
func NewDigestValidator() *DigestValidator {
return &DigestValidator{}
}
// Validate return error when checking digest match body
func (v *DigestValidator) Validate(r *http.Request) error {
headerDigest := r.Header.Get("digest")
digest, err := calculateDigest(r)
if err != nil {
return err
}
if digest != headerDigest {
return ErrInvalidDigest
}
return nil
}
func calculateDigest(r *http.Request) (string, error) {
if r.ContentLength == 0 {
return "", nil
}
// TODO: Read body using buffer to prevent using too much memory
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return "", err
}
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
h := sha256.New()
h.Write(body)
if err != nil {
return "", err
}
digest := fmt.Sprintf("SHA-256=%s", base64.StdEncoding.EncodeToString(h.Sum(nil)))
return digest, nil
}