-
Notifications
You must be signed in to change notification settings - Fork 1
/
authenticator.go
87 lines (69 loc) · 2.03 KB
/
authenticator.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package webhook
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"log"
"strings"
"github.com/aws/aws-lambda-go/events"
)
type Authenticator interface {
Authenticate(req events.LambdaFunctionURLRequest) error
}
var AuthFailedErr = errors.New("authentication failed")
type HeaderAuthenticator struct {
Header string
Secret string
}
func (a *HeaderAuthenticator) Authenticate(req events.LambdaFunctionURLRequest) error {
if secret, ok := req.Headers[a.Header]; ok {
if secret == a.Secret {
return nil
}
}
return AuthFailedErr
}
type FailAuthenticator struct{}
func (a *FailAuthenticator) Authenticate(_ events.LambdaFunctionURLRequest) error {
return AuthFailedErr
}
type NoopAuthenticator struct{}
func (a *NoopAuthenticator) Authenticate(_ events.LambdaFunctionURLRequest) error {
return nil
}
// SignatureAuthenticator implements SHA256 HMAC signature verification
type SignatureAuthenticator struct {
SigningSecret string
// Header is the name of the header that contains the signature, defaults to "X-Signature" if left empty.
Header string
}
func (a *SignatureAuthenticator) Authenticate(req events.LambdaFunctionURLRequest) error {
header := "x-signature"
if a.Header != "" {
header = a.Header
}
header = strings.ToLower(header)
signatureFromHeader, ok := req.Headers[header]
if !ok {
log.Printf("header %s not found", header)
return AuthFailedErr
}
if strings.Contains(signatureFromHeader, "=") {
parts := strings.SplitN(signatureFromHeader, "=", 2)
if len(parts) != 2 {
log.Printf("invalid signature format: %s", signatureFromHeader)
return AuthFailedErr
}
signatureFromHeader = parts[1]
}
h := hmac.New(sha256.New, []byte(a.SigningSecret))
h.Write([]byte(req.Body))
calculatedSignature := hex.EncodeToString(h.Sum(nil))
// Compare the calculated HMAC with the one from the header
if hmac.Equal([]byte(calculatedSignature), []byte(signatureFromHeader)) {
return nil
}
log.Printf("signature mismatch: %s != %s", calculatedSignature, signatureFromHeader)
return AuthFailedErr
}