-
Notifications
You must be signed in to change notification settings - Fork 1
/
hmac.go
126 lines (114 loc) · 3.54 KB
/
hmac.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package hmac
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
const emptyBracketLength = 2
var (
logger = log.New(io.Discard, "[go-grpc-hmac] ", log.LstdFlags|log.LUTC)
ErrInvalidHmacKeyID = status.Errorf(codes.Unauthenticated, "invalid x-hmac-key-id")
ErrInvalidHmacSignature = status.Errorf(codes.Unauthenticated, "invalid x-hmac-signature")
ErrMissingHmac = status.Errorf(codes.Unauthenticated, "missing x-hmac-signature metadata")
ErrMissingHmacKeyID = status.Errorf(codes.Unauthenticated, "missing x-hmac-key-id metadata")
ErrMissingMetadata = status.Errorf(codes.Unauthenticated, "missing hmac metadata")
)
func init() {
lvl, _ := os.LookupEnv("GO_GRPC_HMAC_LOG")
if strings.ToLower(lvl) == "true" {
EnableLogging()
}
}
// EnableLogging for this module.
func EnableLogging() {
logger.SetOutput(os.Stderr)
}
// DisableLogging for this module.
func DisableLogging() {
logger.SetOutput(io.Discard)
}
// NewMessage returns a string representation of the request and method.
func NewMessage(req interface{}, method string) (string, error) {
buf := new(bytes.Buffer)
if req == nil {
logger.Println("warning: no request, using only method name as message")
return "method=" + method, nil
}
reqBuf := new(bytes.Buffer)
if err := json.NewEncoder(reqBuf).Encode(req); err != nil {
if strings.Contains(err.Error(), "has no exported fields") {
logger.Println("warning: no exported fields in request, using only method name as message")
goto ADDMETHOD
}
return "", fmt.Errorf("failed to encode request: %w", err)
}
reqBuf.Truncate(reqBuf.Len() - 1) // remove trailing newline
if reqBuf.Len() > emptyBracketLength {
buf.WriteString("request=")
buf.Write(reqBuf.Bytes())
buf.WriteString(";")
}
ADDMETHOD:
buf.WriteString("method=" + method)
return buf.String(), nil
}
// Bytes generate a HMAC signature and return it as a base64 encoded []byte.
func Bytes(secretKey string, message string) []byte {
logger.Printf("generating signature for message %q", message)
mac := hmac.New(sha512.New512_256, []byte(secretKey))
mac.Write([]byte(message))
in := mac.Sum(nil)
data := make([]byte, base64.StdEncoding.EncodedLen(len(in)))
base64.StdEncoding.Encode(data, in)
return data
}
// String generates a HMAC signature and returns it as a base64 encoded string.
func String(secretKey string, message string) string {
return string(Bytes(secretKey, message))
}
func authForSecrets(getSecret GetSecret) func(ctx context.Context, message string) error {
return func(ctx context.Context, message string) error {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return ErrMissingMetadata
}
hmacSign := getFirst(md, "x-hmac-signature")
if hmacSign == "" {
return ErrMissingHmac
}
hmacKeyID := getFirst(md, "x-hmac-key-id")
if hmacKeyID == "" {
return ErrMissingHmacKeyID
}
secretKey, err := getSecret(ctx, hmacKeyID)
if err != nil {
log.Printf("internal error getting secret for keyID %s: %q", hmacKeyID, err)
return status.Errorf(codes.Internal, err.Error())
}
if secretKey == "" {
logger.Printf("no secret found for keyID %s", hmacKeyID)
return ErrInvalidHmacKeyID
}
if !hmac.Equal([]byte(hmacSign), Bytes(secretKey, message)) {
return ErrInvalidHmacSignature
}
return nil
}
}
func getFirst(md metadata.MD, key string) string {
if len(md[key]) > 0 {
return md[key][0]
}
return ""
}