/
key.go
211 lines (175 loc) · 5.9 KB
/
key.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package payment
import (
"context"
"crypto"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"net/http"
"os"
"time"
"github.com/brave-intl/bat-go/middleware"
"github.com/brave-intl/bat-go/utils/cryptography"
"github.com/brave-intl/bat-go/utils/httpsignature"
uuid "github.com/satori/go.uuid"
)
// EncryptionKey for encrypting secrets
var EncryptionKey = os.Getenv("ENCRYPTION_KEY")
var byteEncryptionKey [32]byte
// What the merchant key length should be
var keyLength = 24
type caveatsCtxKey struct{}
type merchantCtxKey struct{}
// Key represents a merchant's keys to validate skus
type Key struct {
ID string `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Merchant string `json:"merchant" db:"merchant_id"`
EncryptedSecretKey string `json:"-" db:"encrypted_secret_key"`
Nonce string `json:"-" db:"nonce"`
CreatedAt time.Time `json:"createdAt" db:"created_at"`
Expiry *time.Time `json:"expiry" db:"expiry"`
}
// InitEncryptionKeys copies the specified encryption key into memory once
func InitEncryptionKeys() {
copy(byteEncryptionKey[:], []byte(EncryptionKey))
}
// GetSecretKey decrypts the secret key from the database
func (key *Key) GetSecretKey() (*string, error) {
encrypted, err := hex.DecodeString(key.EncryptedSecretKey)
if err != nil {
return nil, err
}
nonce, err := hex.DecodeString(key.Nonce)
if err != nil {
return nil, err
}
secretKey, err := cryptography.DecryptMessage(byteEncryptionKey, encrypted, nonce)
if err != nil {
return nil, err
}
return &secretKey, nil
}
func randomString(n int) (string, error) {
b := make([]byte, n)
_, err := rand.Read(b)
// Note that err == nil only if we read len(b) bytes.
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// GenerateSecret creates a random key for merchants
func GenerateSecret() (secret string, nonce string, err error) {
unencryptedSecret, err := randomString(keyLength)
if err != nil {
return "", "", err
}
unencryptedSecret = cryptography.SecretTokenPrefix + unencryptedSecret
encryptedBytes, nonceBytes, err := cryptography.EncryptMessage(byteEncryptionKey, []byte(unencryptedSecret))
return fmt.Sprintf("%x", encryptedBytes), fmt.Sprintf("%x", nonceBytes), err
}
// LookupVerifier returns the merchant key corresponding to the keyID used for verifying requests
func (service *Service) LookupVerifier(ctx context.Context, keyID string) (context.Context, *httpsignature.Verifier, error) {
rootKeyIDStr, caveats, err := cryptography.DecodeKeyID(keyID)
if err != nil {
return nil, nil, err
}
rootKeyID, err := uuid.FromString(rootKeyIDStr)
if err != nil {
return nil, nil, fmt.Errorf("root key id must be a uuid: %v", err)
}
key, err := service.Datastore.GetKey(rootKeyID, false)
if err != nil {
return nil, nil, err
}
secretKey, err := key.GetSecretKey()
if err != nil {
return nil, nil, err
}
if secretKey == nil {
return nil, nil, errors.New("missing secret key")
}
secretKeyStr := *secretKey
if caveats != nil {
_, secretKeyStr, err = cryptography.Attenuate(rootKeyID.String(), secretKeyStr, caveats)
if err != nil {
return nil, nil, err
}
ctx = context.WithValue(ctx, caveatsCtxKey{}, caveats)
}
ctx = context.WithValue(ctx, merchantCtxKey{}, key.Merchant)
verifier := httpsignature.Verifier(httpsignature.HMACKey(secretKeyStr))
return ctx, &verifier, nil
}
// MerchantSignedMiddleware requires that requests are signed by valid merchant keys
func (service *Service) MerchantSignedMiddleware() func(http.Handler) http.Handler {
merchantVerifier := httpsignature.ParameterizedKeystoreVerifier{
SignatureParams: httpsignature.SignatureParams{
Algorithm: httpsignature.HS2019,
Headers: []string{
"(request-target)", "host", "date", "digest", "content-length", "content-type",
},
},
Keystore: service,
Opts: crypto.Hash(0),
}
// TODO replace with returning VerifyHTTPSignedOnly once we've migrated
// subscriptions server auth off simple token
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(r.Header.Get("Signature")) == 0 {
// Assume legacy simple token auth
ctx := context.WithValue(r.Context(), merchantCtxKey{}, "brave.com")
middleware.SimpleTokenAuthorizedOnly(next).ServeHTTP(w, r.WithContext(ctx))
return
}
middleware.VerifyHTTPSignedOnly(merchantVerifier)(next).ServeHTTP(w, r)
})
}
}
// GetCaveats returns any authorized caveats that have been stored in the context
func GetCaveats(ctx context.Context) map[string]string {
caveats, ok := ctx.Value(caveatsCtxKey{}).(map[string]string)
if !ok {
return nil
}
return caveats
}
// GetMerchant returns any authorized merchant that has been stored in the context
func GetMerchant(ctx context.Context) (string, error) {
merchant, ok := ctx.Value(merchantCtxKey{}).(string)
if !ok {
return "", errors.New("merchant was missing from context")
}
return merchant, nil
}
// ValidateOrderMerchantAndCaveats checks that the current authentication of the request has
// permissions to this order by cross-checking the merchant and caveats in context
func (service *Service) ValidateOrderMerchantAndCaveats(r *http.Request, orderID uuid.UUID) error {
merchant, err := GetMerchant(r.Context())
if err != nil {
return err
}
caveats := GetCaveats(r.Context())
order, err := service.Datastore.GetOrder(orderID)
if err != nil {
return err
}
if order.MerchantID != merchant {
return errors.New("Order merchant does not match authentication")
}
if caveats != nil {
if location, ok := caveats["location"]; ok {
if order.Location.Valid && order.Location.String != location {
return errors.New("Order location does not match authentication")
}
}
if _, ok := caveats["sku"]; ok {
return errors.New("SKU caveat is not supported on order endpoints")
}
}
return nil
}