-
Notifications
You must be signed in to change notification settings - Fork 21
/
siwe_test.go
428 lines (334 loc) · 12.2 KB
/
siwe_test.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
package siwe
import (
"crypto/ecdsa"
"encoding/json"
"io/ioutil"
"net/url"
"os"
"strconv"
"testing"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/relvacode/iso8601"
"github.com/stretchr/testify/assert"
)
const domain = "example.com"
const addressStr = "0x71C7656EC7ab88b098defB751B7401B5f6d8976F"
var address = common.HexToAddress(addressStr)
const uri = "https://example.com"
const version = "1"
const statement = "Example statement for SIWE"
var issuedAt = time.Now().UTC().Format(time.RFC3339)
var nonce = GenerateNonce()
const chainId = 1
var expirationTime = time.Now().UTC().Add(48 * time.Hour).Format(time.RFC3339)
var notBefore = time.Now().UTC().Add(-24 * time.Hour).Format(time.RFC3339)
const requestId = "some-id"
var resourcesStr = []string{"https://example.com/resources/1", "https://example.com/resources/2"}
func parsedResources() []url.URL {
parsed := make([]url.URL, len(resourcesStr))
for i, resource := range resourcesStr {
url, _ := url.Parse(resource)
parsed[i] = *url
}
return parsed
}
var resources = parsedResources()
var options = map[string]interface{}{
"statement": statement,
"chainId": chainId,
"issuedAt": issuedAt,
"expirationTime": expirationTime,
"notBefore": notBefore,
"requestId": requestId,
"resources": resources,
}
var message, _ = InitMessage(
domain,
addressStr,
uri,
nonce,
options,
)
func compareMessage(t *testing.T, a, b *Message) {
assert.Equal(t, a.domain, b.domain, "expected %s, found %s", a.domain, b.domain)
assert.Equal(t, a.address, b.address, "expected %s, found %s", a.address, b.address)
assert.Equal(t, a.uri.String(), b.uri.String(), "expected %s, found %s", a.uri, b.uri)
assert.Equal(t, a.version, b.version, "expected %s, found %s", a.version, b.version)
assert.Equal(t, a.statement, b.statement, "expected %s, found %s", a.statement, b.statement)
assert.Equal(t, a.nonce, b.nonce, "expected %s, found %s", a.nonce, b.nonce)
assert.Equal(t, a.chainID, b.chainID, "expected %s, found %s", a.chainID, b.chainID)
assert.Equal(t, a.issuedAt, b.issuedAt, "expected %s, found %s", a.issuedAt, b.issuedAt)
assert.Equal(t, a.expirationTime, b.expirationTime, "expected %s, found %s", a.expirationTime, b.expirationTime)
assert.Equal(t, a.notBefore, b.notBefore, "expected %s, found %s", a.notBefore, b.notBefore)
assert.Equal(t, a.requestID, b.requestID, "expected %s, found %s", a.requestID, b.requestID)
assert.Equal(t, a.resources, b.resources, "expected %v, found %v", a.resources, b.resources)
}
func TestCreate(t *testing.T) {
message, err := InitMessage(
domain,
addressStr,
uri,
nonce,
options,
)
assert.Nil(t, err)
assert.Equal(t, message.domain, domain, "domain should be %s", domain)
assert.Equal(t, message.address, address, "address should be %s", address)
assert.Equal(t, message.uri.String(), uri, "uri should be %s", uri)
assert.Equal(t, message.version, version, "version should be %s", version)
assert.Equal(t, *message.statement, statement, "statement should be %s", statement)
assert.Equal(t, message.nonce, nonce, "nonce should be %s", nonce)
assert.Equal(t, message.chainID, chainId, "chainId should be %s", chainId)
assert.Equal(t, message.issuedAt, issuedAt, "issuedAt should be %v", issuedAt)
assert.Equal(t, *message.expirationTime, expirationTime, "expirationTime should be %s", expirationTime)
assert.Equal(t, *message.notBefore, notBefore, "notBefore should be %s", notBefore)
assert.Equal(t, *message.requestID, requestId, "requestId should be %s", requestId)
assert.Equal(t, message.resources, resources, "resources should be %v", resources)
}
func TestCreateRequired(t *testing.T) {
message, err := InitMessage(domain, addressStr, uri, GenerateNonce(), map[string]interface{}{})
assert.Nil(t, err)
assert.Equal(t, message.domain, domain, "domain should be %s", domain)
assert.Equal(t, message.address, address, "address should be %s", address)
assert.Equal(t, message.uri.String(), uri, "uri should be %s", uri)
assert.Equal(t, message.version, version, "version should be %s", version)
assert.Nil(t, message.statement, "statement should be nil")
assert.NotNil(t, message.nonce, "nonce should be not nil")
assert.NotNil(t, message.chainID, "chainId should not be nil")
assert.NotNil(t, message.issuedAt, "issuedAt should not be nil")
assert.Nil(t, message.expirationTime, "expirationTime should be nil")
assert.Nil(t, message.notBefore, "notBefore should be nil")
assert.Nil(t, message.requestID, "requestId should be nil")
assert.Len(t, message.resources, 0, "resources should be empty")
}
func TestCreateEmpty(t *testing.T) {
var err error
_, err = InitMessage("", addressStr, uri, GenerateNonce(), map[string]interface{}{})
assert.Error(t, err)
_, err = InitMessage(domain, "", uri, GenerateNonce(), map[string]interface{}{})
assert.Error(t, err)
_, err = InitMessage(domain, addressStr, "", GenerateNonce(), map[string]interface{}{})
assert.Error(t, err)
_, err = InitMessage(domain, addressStr, uri, "", map[string]interface{}{})
assert.Error(t, err)
}
func TestPrepareParse(t *testing.T) {
prepare := message.String()
parse, err := ParseMessage(prepare)
assert.Nil(t, err)
compareMessage(t, message, parse)
}
func TestPrepareParseRequired(t *testing.T) {
message, err := InitMessage(domain, addressStr, uri, GenerateNonce(), map[string]interface{}{})
assert.Nil(t, err)
prepare := message.String()
parse, err := ParseMessage(prepare)
assert.Nil(t, err)
compareMessage(t, message, parse)
}
func TestValidateEmpty(t *testing.T) {
_, err := message.Verify("", nil, nil, nil)
if assert.Error(t, err) {
assert.Equal(t, &InvalidSignature{"Signature cannot be empty"}, err)
}
}
func createWallet(t *testing.T) (*ecdsa.PrivateKey, string) {
privateKey, err := crypto.GenerateKey()
assert.Nil(t, err)
publicKey := privateKey.Public()
publicKeyECDSA, _ := publicKey.(*ecdsa.PublicKey)
address := crypto.PubkeyToAddress(*publicKeyECDSA).Hex()
return privateKey, address
}
func TestValidateNotBefore(t *testing.T) {
privateKey, address := createWallet(t)
message, err := InitMessage(domain, address, uri, GenerateNonce(), map[string]interface{}{
"notBefore": time.Now().UTC().Add(24 * time.Hour).Format(time.RFC3339),
})
assert.Nil(t, err)
prepare := message.String()
hash := crypto.Keccak256Hash([]byte(prepare))
signature, err := crypto.Sign(hash.Bytes(), privateKey)
assert.Nil(t, err)
_, err = message.Verify(hexutil.Encode(signature), nil, nil, nil)
if assert.Error(t, err) {
assert.Equal(t, &InvalidMessage{"Message not yet valid"}, err)
}
}
func TestValidateExpirationTime(t *testing.T) {
privateKey, address := createWallet(t)
message, err := InitMessage(domain, address, uri, GenerateNonce(), map[string]interface{}{
"expirationTime": time.Now().UTC().Add(-24 * time.Hour).Format(time.RFC3339),
})
assert.Nil(t, err)
prepare := message.String()
hash := crypto.Keccak256Hash([]byte(prepare))
signature, err := crypto.Sign(hash.Bytes(), privateKey)
assert.Nil(t, err)
_, err = message.Verify(hexutil.Encode(signature), nil, nil, nil)
if assert.Error(t, err) {
assert.Equal(t, &ExpiredMessage{"Message expired"}, err)
}
}
func TestValidate(t *testing.T) {
privateKey, address := createWallet(t)
message, err := InitMessage(domain, address, uri, nonce, options)
assert.Nil(t, err)
hash := message.eip191Hash()
signature, err := crypto.Sign(hash.Bytes(), privateKey)
signature[64] += 27
assert.Nil(t, err)
_, err = message.Verify(hexutil.Encode(signature), nil, nil, nil)
assert.Nil(t, err)
}
func TestValidateTampered(t *testing.T) {
privateKey, address := createWallet(t)
_, otherAddress := createWallet(t)
message, err := InitMessage(domain, address, uri, nonce, options)
assert.Nil(t, err)
hash := message.eip191Hash()
signature, err := crypto.Sign(hash.Bytes(), privateKey)
signature[64] += 27
assert.Nil(t, err)
message, err = InitMessage(domain, otherAddress, uri, nonce, options)
assert.Nil(t, err)
_, err = message.Verify(hexutil.Encode(signature), nil, nil, nil)
if assert.Error(t, err) {
assert.Equal(t, &InvalidSignature{"Signer address must match message address"}, err)
}
}
func assertCase(t *testing.T, fields map[string]interface{}, parsed interface{}, key string) {
if field, ok := fields[key]; ok {
assert.Equal(t, field, parsed, "%s should be %s", key, field)
}
}
func parsingNegative(t *testing.T, cases map[string]interface{}) {
for name, message := range cases {
_, err := ParseMessage(message.(string))
assert.Error(t, err, name)
}
}
func parsingPositive(t *testing.T, cases map[string]interface{}) {
for name, v := range cases {
data := v.(map[string]interface{})
message := data["message"].(string)
fields := data["fields"].(map[string]interface{})
parsed, err := parseMessage(message)
assert.Nil(t, err, name)
assertCase(t, fields, parsed["domain"].(string), "domain")
assertCase(t, fields, parsed["address"].(string), "address")
assertCase(t, fields, parsed["uri"].(string), "uri")
assertCase(t, fields, parsed["version"].(string), "version")
parsedChainId, _ := strconv.Atoi(parsed["chainId"].(string))
expectedChainId := int(fields["chainId"].(float64))
assert.Equal(t, expectedChainId, parsedChainId, "chainId should be %s", expectedChainId)
assertCase(t, fields, parsed["issuedAt"].(string), "issuedAt")
if val, ok := parsed["statement"]; ok {
assertCase(t, fields, val.(string), "statement")
}
if val, ok := parsed["nonce"]; ok {
assertCase(t, fields, val.(string), "nonce")
}
constructed, err := ParseMessage(message)
assert.Nil(t, err)
assert.Equal(t, constructed.String(), message)
}
}
func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
func verificationNegative(t *testing.T, cases map[string]interface{}) {
for name, v := range cases {
data := v.(map[string]interface{})
message, err := InitMessage(
data["domain"].(string),
data["address"].(string),
data["uri"].(string),
data["nonce"].(string),
data,
)
if contains([]string{"invalid issuedAt", "invalid expirationTime", "invalid notBefore"}, name) {
assert.Error(t, err, name)
continue
} else {
assert.Nil(t, err, name)
}
var domainBinding *string
if val, ok := data["domainBinding"]; ok {
value := val.(string)
domainBinding = &value
}
var matchNonce *string
if val, ok := data["matchNonce"]; ok {
value := val.(string)
matchNonce = &value
}
var timestamp *time.Time
if val, ok := data["time"]; ok {
parsed, err := iso8601.ParseString(val.(string))
assert.Nil(t, err)
timestamp = &parsed
}
_, err = message.Verify(data["signature"].(string), domainBinding, matchNonce, timestamp)
assert.Error(t, err, name)
}
}
func verificationPositive(t *testing.T, cases map[string]interface{}) {
for name, v := range cases {
data := v.(map[string]interface{})
message, err := InitMessage(
data["domain"].(string),
data["address"].(string),
data["uri"].(string),
data["nonce"].(string),
data,
)
assert.Nil(t, err)
var timestamp *time.Time
if val, ok := data["time"]; ok {
parsed, err := iso8601.ParseString(val.(string))
assert.Nil(t, err)
timestamp = &parsed
}
_, err = message.Verify(data["signature"].(string), nil, nil, timestamp)
assert.Nil(t, err, name)
}
}
func TestGlobalTestVector(t *testing.T) {
files := make(map[string]*os.File, 4)
for test, filename := range map[string]string{
"parsing-negative": "siwe-js/test/parsing_negative.json",
"parsing-positive": "siwe-js/test/parsing_positive.json",
"verification-negative": "siwe-js/test/verification_negative.json",
"verification-positive": "siwe-js/test/verification_positive.json",
} {
file, err := os.Open(filename)
assert.Nil(t, err)
files[test] = file
defer file.Close()
}
for test, file := range files {
data, _ := ioutil.ReadAll(file)
var result map[string]interface{}
err := json.Unmarshal([]byte(data), &result)
assert.Nil(t, err)
switch test {
case "parsing-negative":
parsingNegative(t, result)
case "parsing-positive":
parsingPositive(t, result)
case "verification-negative":
verificationNegative(t, result)
case "verification-positive":
verificationPositive(t, result)
}
}
}