summaryrefslogtreecommitdiff
path: root/network/netidentity_test.go
blob: 9650069224deab68a69b856a2a76af3d88a2996d (plain)
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
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package network

import (
	"encoding/base64"
	"net/http"
	"testing"

	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/test/partitiontest"
	"github.com/stretchr/testify/require"
)

// if the scheme has a dedup name, attach to headers. otherwise, don't
func TestIdentityChallengeSchemeAttachIfEnabled(t *testing.T) {
	partitiontest.PartitionTest(t)

	h := http.Header{}
	i := NewIdentityChallengeScheme("")
	chal := i.AttachChallenge(h, "other")
	require.Empty(t, h.Get(IdentityChallengeHeader))
	require.Empty(t, chal)

	j := NewIdentityChallengeScheme("yes")
	chal = j.AttachChallenge(h, "other")
	require.NotEmpty(t, h.Get(IdentityChallengeHeader))
	require.NotEmpty(t, chal)
}

// TestIdentityChallengeSchemeVerifyRequestAndAttachResponse will confirm that the scheme
// attaches responses only if dedup name is set and the provided challenge verifies
func TestIdentityChallengeSchemeVerifyRequestAndAttachResponse(t *testing.T) {
	partitiontest.PartitionTest(t)

	i := NewIdentityChallengeScheme("i1")
	// author a challenge to the other scheme
	h := http.Header{}
	i.AttachChallenge(h, "i2")
	require.NotEmpty(t, h.Get(IdentityChallengeHeader))

	// without a dedup name, no response and no error
	h = http.Header{}
	i.AttachChallenge(h, "i2")
	r := http.Header{}
	i2 := NewIdentityChallengeScheme("")
	chal, key, err := i2.VerifyRequestAndAttachResponse(r, h)
	require.Empty(t, r.Get(IdentityChallengeHeader))
	require.Empty(t, chal)
	require.Empty(t, key)
	require.NoError(t, err)

	// if dedup name doesn't match, no response and no error
	h = http.Header{}
	i.AttachChallenge(h, "i2")
	r = http.Header{}
	i2 = NewIdentityChallengeScheme("not i2")
	chal, key, err = i2.VerifyRequestAndAttachResponse(r, h)
	require.Empty(t, r.Get(IdentityChallengeHeader))
	require.Empty(t, chal)
	require.Empty(t, key)
	require.NoError(t, err)

	// if the challenge can't be decoded or verified, error
	h = http.Header{}
	h.Add(IdentityChallengeHeader, "garbage")
	r = http.Header{}
	i2 = NewIdentityChallengeScheme("i2")
	chal, key, err = i2.VerifyRequestAndAttachResponse(r, h)
	require.Empty(t, r.Get(IdentityChallengeHeader))
	require.Empty(t, chal)
	require.Empty(t, key)
	require.Error(t, err)

	// happy path: response should be attached here
	h = http.Header{}
	i.AttachChallenge(h, "i2")
	r = http.Header{}
	i2 = NewIdentityChallengeScheme("i2")
	chal, key, err = i2.VerifyRequestAndAttachResponse(r, h)
	require.NotEmpty(t, r.Get(IdentityChallengeHeader))
	require.NotEmpty(t, chal)
	require.NotEmpty(t, key)
	require.NoError(t, err)
}

func TestIdentityChallengeNoErrorWhenNotParticipating(t *testing.T) {
	partitiontest.PartitionTest(t)

	// blank deduplication name will make the scheme a no-op
	iNotParticipate := NewIdentityChallengeScheme("")

	// create a request header first
	h := http.Header{}
	i := NewIdentityChallengeScheme("i1")
	origChal := i.AttachChallenge(h, "i1")
	require.NotEmpty(t, h.Get(IdentityChallengeHeader))
	require.NotEmpty(t, origChal)

	// confirm a nil scheme will not return values or error
	c, k, err := iNotParticipate.VerifyRequestAndAttachResponse(http.Header{}, h)
	require.Empty(t, c)
	require.Empty(t, k)
	require.NoError(t, err)

	// create a response
	h2 := http.Header{}
	i2 := NewIdentityChallengeScheme("i2")
	i2.VerifyRequestAndAttachResponse(h2, h)

	// confirm a nil scheme will not return values or error
	k2, bytes, err := iNotParticipate.VerifyResponse(h2, identityChallengeValue{})
	require.Empty(t, k2)
	require.Empty(t, bytes)
	require.NoError(t, err)

	// add broken payload to a new header and try inspecting it with the empty scheme
	h3 := http.Header{}
	h3.Add(IdentityChallengeHeader, "broken text!")
	c, k, err = iNotParticipate.VerifyRequestAndAttachResponse(http.Header{}, h)
	require.Empty(t, c)
	require.Empty(t, k)
	require.NoError(t, err)
	k2, bytes, err = iNotParticipate.VerifyResponse(h2, identityChallengeValue{})
	require.Empty(t, k2)
	require.Empty(t, bytes)
	require.NoError(t, err)
}

// TestIdentityChallengeSchemeVerifyResponse confirms the scheme will
// attach responses only if dedup name is set and the provided challenge verifies
func TestIdentityChallengeSchemeVerifyResponse(t *testing.T) {
	partitiontest.PartitionTest(t)

	h := http.Header{}
	i := NewIdentityChallengeScheme("i1")
	// author a challenge to ourselves
	origChal := i.AttachChallenge(h, "i1")
	require.NotEmpty(t, h.Get(IdentityChallengeHeader))
	require.NotEmpty(t, origChal)
	r := http.Header{}

	respChal, key, err := i.VerifyRequestAndAttachResponse(r, h)
	require.NotEmpty(t, r.Get(IdentityChallengeHeader))
	require.NotEmpty(t, respChal)
	require.NotEmpty(t, key)
	require.NoError(t, err)

	// respChal2 should match respChal as it is being passed back to the original peer
	// while origChal will be used for verification
	key2, verificationMsg, err := i.VerifyResponse(r, origChal)
	require.NotEmpty(t, verificationMsg)
	require.NoError(t, err)
	// because we sent this to ourselves, we can confirm the keys match
	require.Equal(t, key, key2)
}

// TestIdentityChallengeSchemeBadSignature tests that the  scheme will
// fail to verify and attach if the challenge is incorrectly signed
func TestIdentityChallengeSchemeBadSignature(t *testing.T) {
	partitiontest.PartitionTest(t)

	h := http.Header{}
	i := NewIdentityChallengeScheme("i1")
	// Copy the logic of attaching the header and signing so we can sign it wrong
	c := identityChallengeSigned{
		Msg: identityChallenge{
			Key:           i.identityKeys.SignatureVerifier,
			Challenge:     newIdentityChallengeValue(),
			PublicAddress: []byte("i1"),
		}}
	c.Signature = i.identityKeys.SignBytes([]byte("WRONG BYTES SIGNED"))
	enc := protocol.Encode(&c)
	b64enc := base64.StdEncoding.EncodeToString(enc)
	h.Add(IdentityChallengeHeader, b64enc)

	// observe that VerifyRequestAndAttachResponse returns error on bad signature
	r := http.Header{}
	respChal, key, err := i.VerifyRequestAndAttachResponse(r, h)
	require.Empty(t, r.Get(IdentityChallengeHeader))
	require.Empty(t, respChal)
	require.Empty(t, key)
	require.Error(t, err)
}

// TestIdentityChallengeSchemeBadPayload tests that the  scheme will
// fail to verify if the challenge can't be B64 decoded
func TestIdentityChallengeSchemeBadPayload(t *testing.T) {
	partitiontest.PartitionTest(t)

	h := http.Header{}
	i := NewIdentityChallengeScheme("i1")
	h.Add(IdentityChallengeHeader, "NOT VALID BASE 64! :)")

	// observe that VerifyRequestAndAttachResponse won't do anything on bad signature
	r := http.Header{}
	respChal, key, err := i.VerifyRequestAndAttachResponse(r, h)
	require.Empty(t, r.Get(IdentityChallengeHeader))
	require.Empty(t, respChal)
	require.Empty(t, key)
	require.Error(t, err)
}

// TestIdentityChallengeSchemeBadResponseSignature tests that the  scheme will
// fail to verify if the challenge response is incorrectly signed
func TestIdentityChallengeSchemeBadResponseSignature(t *testing.T) {
	partitiontest.PartitionTest(t)

	h := http.Header{}
	i := NewIdentityChallengeScheme("i1")
	// author a challenge to ourselves
	origChal := i.AttachChallenge(h, "i1")
	require.NotEmpty(t, h.Get(IdentityChallengeHeader))
	require.NotEmpty(t, origChal)

	// use the code to sign and encode responses so we can sign incorrectly
	r := http.Header{}
	resp := identityChallengeResponseSigned{
		Msg: identityChallengeResponse{
			Key:               i.identityKeys.SignatureVerifier,
			Challenge:         origChal,
			ResponseChallenge: newIdentityChallengeValue(),
		}}
	resp.Signature = i.identityKeys.SignBytes([]byte("BAD BYTES FOR SIGNING"))
	enc := protocol.Encode(&resp)
	b64enc := base64.StdEncoding.EncodeToString(enc)
	r.Add(IdentityChallengeHeader, b64enc)

	key2, verificationMsg, err := i.VerifyResponse(r, origChal)
	require.Empty(t, key2)
	require.Empty(t, verificationMsg)
	require.Error(t, err)
}

// TestIdentityChallengeSchemeBadResponsePayload tests that the  scheme will
// fail to verify if the challenge response can't be B64 decoded
func TestIdentityChallengeSchemeBadResponsePayload(t *testing.T) {
	partitiontest.PartitionTest(t)

	h := http.Header{}
	i := NewIdentityChallengeScheme("i1")
	// author a challenge to ourselves
	origChal := i.AttachChallenge(h, "i1")
	require.NotEmpty(t, h.Get(IdentityChallengeHeader))
	require.NotEmpty(t, origChal)

	// generate a bad payload that should not decode
	r := http.Header{}
	r.Add(IdentityChallengeHeader, "BAD B64 ENCODING :)")

	key2, verificationMsg, err := i.VerifyResponse(r, origChal)
	require.Empty(t, key2)
	require.Empty(t, verificationMsg)
	require.Error(t, err)
}

// TestIdentityChallengeSchemeWrongChallenge the scheme will
// return "0" if the challenge does not match upon return
func TestIdentityChallengeSchemeWrongChallenge(t *testing.T) {
	partitiontest.PartitionTest(t)

	h := http.Header{}
	i := NewIdentityChallengeScheme("i1")
	// author a challenge to ourselves
	origChal := i.AttachChallenge(h, "i1")
	require.NotEmpty(t, h.Get(IdentityChallengeHeader))
	require.NotEmpty(t, origChal)

	r := http.Header{}
	respChal, key, err := i.VerifyRequestAndAttachResponse(r, h)
	require.NotEmpty(t, r.Get(IdentityChallengeHeader))
	require.NotEmpty(t, respChal)
	require.NotEmpty(t, key)
	require.NoError(t, err)

	// Attempt to verify against the wrong challenge
	key2, verificationMsg, err := i.VerifyResponse(r, newIdentityChallengeValue())
	require.Empty(t, key2)
	require.Empty(t, verificationMsg)
	require.Error(t, err)
}

func TestNewIdentityTracker(t *testing.T) {
	partitiontest.PartitionTest(t)

	tracker := NewIdentityTracker()
	require.Empty(t, tracker.peersByID)
}

func TestIdentityTrackerRemoveIdentity(t *testing.T) {
	partitiontest.PartitionTest(t)

	tracker := NewIdentityTracker()
	id := crypto.PublicKey{}
	p := wsPeer{identity: id}

	id2 := crypto.PublicKey{}
	p2 := wsPeer{identity: id2}

	// Ensure the first attempt to insert populates the map
	_, exists := tracker.peersByID[p.identity]
	require.False(t, exists)
	require.True(t, tracker.setIdentity(&p))
	_, exists = tracker.peersByID[p.identity]
	require.True(t, exists)

	// check that removing a peer who does not exist in the map (but whos identity does)
	// not not result in the wrong peer being removed
	tracker.removeIdentity(&p2)
	_, exists = tracker.peersByID[p.identity]
	require.True(t, exists)

	tracker.removeIdentity(&p)
	_, exists = tracker.peersByID[p.identity]
	require.False(t, exists)
}

func TestIdentityTrackerSetIdentity(t *testing.T) {
	partitiontest.PartitionTest(t)

	tracker := NewIdentityTracker()
	id := crypto.PublicKey{}
	p := wsPeer{identity: id}

	// Ensure the first attempt to insert populates the map
	_, exists := tracker.peersByID[p.identity]
	require.False(t, exists)
	require.True(t, tracker.setIdentity(&p))
	_, exists = tracker.peersByID[p.identity]
	require.True(t, exists)

	// Ensure the next attempt to insert also returns true
	require.True(t, tracker.setIdentity(&p))

	// Ensure a different peer cannot take the map entry
	otherP := wsPeer{identity: id}
	require.False(t, tracker.setIdentity(&otherP))

	// Ensure the entry in the map wasn't changed
	require.Equal(t, tracker.peersByID[p.identity], &p)
}

// Just tests that if a peer is already verified, it just returns OutgoingMessage{}
func TestIdentityTrackerHandlerGuard(t *testing.T) {
	partitiontest.PartitionTest(t)
	p := wsPeer{}
	p.identityVerified.Store(1)
	msg := IncomingMessage{
		Sender: &p,
		Net:    &WebsocketNetwork{},
	}
	require.Equal(t, OutgoingMessage{}, identityVerificationHandler(msg))
}