summaryrefslogtreecommitdiffstats
path: root/pkg/crypto/crypto_test.go
blob: 1d76767c5186e9a2e6f1eaabdcfe01615f55cae2 (plain) (blame)
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
429
430
431
432
433
434
435
436
437
438
439
440
package crypto

import (
	"bytes"
	"crypto/cipher"
	"net"
	"testing"
	"time"
)

func TestPadMessage(t *testing.T) {
	tests := []struct {
		name     string
		input    []byte
		wantSize int // Expected padded size (2 + paddedLen)
	}{
		{"empty", []byte{}, 2 + MessageBlockSize},
		{"small", []byte("hello"), 2 + MessageBlockSize},
		{"exact block minus header", make([]byte, MessageBlockSize-2), 2 + MessageBlockSize},
		{"one block", make([]byte, MessageBlockSize), 2 + MessageBlockSize*2},
		{"large", make([]byte, MessageBlockSize*2+50), 2 + MessageBlockSize*3},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			padded, err := PadMessage(tt.input)
			if err != nil {
				t.Fatalf("PadMessage() error = %v", err)
			}

			if len(padded) != tt.wantSize {
				t.Errorf("PadMessage() size = %d, want %d", len(padded), tt.wantSize)
			}

			// Verify we can unpad correctly
			unpadded, err := UnpadMessage(padded)
			if err != nil {
				t.Fatalf("UnpadMessage() error = %v", err)
			}

			if !bytes.Equal(unpadded, tt.input) {
				t.Errorf("UnpadMessage() = %v, want %v", unpadded, tt.input)
			}
		})
	}
}

func TestUnpadMessage_Errors(t *testing.T) {
	tests := []struct {
		name    string
		input   []byte
		wantErr bool
	}{
		{"nil", nil, true},
		{"empty", []byte{}, true},
		{"too short", []byte{0x00}, true},
		{"invalid length", []byte{0xFF, 0xFF, 0x00}, true}, // Claims 65535 bytes but only has 1
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := UnpadMessage(tt.input)
			if (err != nil) != tt.wantErr {
				t.Errorf("UnpadMessage() error = %v, wantErr %v", err, tt.wantErr)
			}
		})
	}
}

func TestPadUnpadRoundTrip(t *testing.T) {
	messages := []string{
		"",
		"Hello, World!",
		"This is a longer message that spans multiple words",
		string(make([]byte, 1000)), // Large message
	}

	for _, msg := range messages {
		padded, err := PadMessage([]byte(msg))
		if err != nil {
			t.Fatalf("PadMessage(%q) error = %v", msg, err)
		}

		unpadded, err := UnpadMessage(padded)
		if err != nil {
			t.Fatalf("UnpadMessage() error = %v", err)
		}

		if string(unpadded) != msg {
			t.Errorf("Round trip failed: got %q, want %q", string(unpadded), msg)
		}
	}
}

func TestDeriveIdentity(t *testing.T) {
	pubKey := []byte("test-public-key-32-bytes-long!!!")

	identity := DeriveIdentity(pubKey)

	// Should start with "anon_"
	if len(identity) < 5 || identity[:5] != "anon_" {
		t.Errorf("DeriveIdentity() = %q, should start with 'anon_'", identity)
	}

	// Should be deterministic
	identity2 := DeriveIdentity(pubKey)
	if identity != identity2 {
		t.Errorf("DeriveIdentity() not deterministic: %q != %q", identity, identity2)
	}

	// Different input should produce different output
	identity3 := DeriveIdentity([]byte("different-key-32-bytes-long!!!!"))
	if identity == identity3 {
		t.Error("DeriveIdentity() should produce different output for different input")
	}
}

func TestDeriveFingerprint(t *testing.T) {
	pubKey := []byte("test-public-key-32-bytes-long!!!")

	fp := DeriveFingerprint(pubKey)

	// Should be 32 hex chars (16 bytes)
	if len(fp) != 32 {
		t.Errorf("DeriveFingerprint() length = %d, want 32", len(fp))
	}

	// Should be deterministic
	fp2 := DeriveFingerprint(pubKey)
	if fp != fp2 {
		t.Errorf("DeriveFingerprint() not deterministic: %q != %q", fp, fp2)
	}
}

func TestSetupAESGCM(t *testing.T) {
	// Valid 32-byte key
	validKey := make([]byte, 32)
	for i := range validKey {
		validKey[i] = byte(i)
	}

	gcm, err := SetupAESGCM(validKey)
	if err != nil {
		t.Fatalf("SetupAESGCM() error = %v", err)
	}

	if gcm == nil {
		t.Error("SetupAESGCM() returned nil")
	}

	// Too short key
	_, err = SetupAESGCM([]byte("short"))
	if err == nil {
		t.Error("SetupAESGCM() should fail with short key")
	}
}

func TestEncryptDecrypt(t *testing.T) {
	key := make([]byte, 32)
	for i := range key {
		key[i] = byte(i)
	}

	gcm, err := SetupAESGCM(key)
	if err != nil {
		t.Fatalf("SetupAESGCM() error = %v", err)
	}

	plaintext := []byte("Hello, secure world!")

	// Encrypt
	ciphertext, err := Encrypt(gcm, plaintext)
	if err != nil {
		t.Fatalf("Encrypt() error = %v", err)
	}

	// Ciphertext should be different from plaintext
	if bytes.Equal(ciphertext, plaintext) {
		t.Error("Encrypt() ciphertext equals plaintext")
	}

	// Should include nonce (12 bytes) + ciphertext + tag
	if len(ciphertext) < NonceSize+len(plaintext) {
		t.Errorf("Encrypt() ciphertext too short: %d", len(ciphertext))
	}

	// Decrypt
	decrypted, err := Decrypt(gcm, ciphertext)
	if err != nil {
		t.Fatalf("Decrypt() error = %v", err)
	}

	if !bytes.Equal(decrypted, plaintext) {
		t.Errorf("Decrypt() = %q, want %q", string(decrypted), string(plaintext))
	}
}

func TestEncryptDecrypt_DifferentNonces(t *testing.T) {
	key := make([]byte, 32)
	gcm, _ := SetupAESGCM(key)

	plaintext := []byte("Same message")

	// Encrypt twice
	ct1, _ := Encrypt(gcm, plaintext)
	ct2, _ := Encrypt(gcm, plaintext)

	// Ciphertexts should be different (different nonces)
	if bytes.Equal(ct1, ct2) {
		t.Error("Encrypt() should produce different ciphertext each time (different nonces)")
	}

	// But both should decrypt to same plaintext
	pt1, _ := Decrypt(gcm, ct1)
	pt2, _ := Decrypt(gcm, ct2)

	if !bytes.Equal(pt1, pt2) {
		t.Error("Both ciphertexts should decrypt to same plaintext")
	}
}

func TestDecrypt_Errors(t *testing.T) {
	key := make([]byte, 32)
	gcm, _ := SetupAESGCM(key)

	tests := []struct {
		name  string
		input []byte
	}{
		{"nil", nil},
		{"empty", []byte{}},
		{"too short", []byte("short")},
		{"invalid ciphertext", make([]byte, 50)}, // Random bytes won't decrypt
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			_, err := Decrypt(gcm, tt.input)
			if err == nil {
				t.Error("Decrypt() should fail")
			}
		})
	}
}

func TestEncryptDecryptMessage(t *testing.T) {
	key := make([]byte, 32)
	gcm, _ := SetupAESGCM(key)

	message := "Hello, this is a test message!"

	// Encrypt (note: this includes random delay, may be slow)
	encrypted, err := EncryptMessage(gcm, message)
	if err != nil {
		t.Fatalf("EncryptMessage() error = %v", err)
	}

	// Decrypt
	decrypted, err := DecryptMessage(gcm, encrypted)
	if err != nil {
		t.Fatalf("DecryptMessage() error = %v", err)
	}

	if decrypted != message {
		t.Errorf("DecryptMessage() = %q, want %q", decrypted, message)
	}
}

func TestGenerateX25519KeyPair(t *testing.T) {
	key1, err := GenerateX25519KeyPair()
	if err != nil {
		t.Fatalf("GenerateX25519KeyPair() error = %v", err)
	}

	if key1 == nil {
		t.Fatal("GenerateX25519KeyPair() returned nil")
	}

	// Public key should be 32 bytes
	pubKey := key1.PublicKey().Bytes()
	if len(pubKey) != 32 {
		t.Errorf("Public key length = %d, want 32", len(pubKey))
	}

	// Generate another - should be different
	key2, _ := GenerateX25519KeyPair()
	if bytes.Equal(key1.PublicKey().Bytes(), key2.PublicKey().Bytes()) {
		t.Error("Two generated keys should be different")
	}
}

func TestPerformECDH(t *testing.T) {
	// Generate two key pairs
	aliceKey, _ := GenerateX25519KeyPair()
	bobKey, _ := GenerateX25519KeyPair()

	// Alice computes shared secret with Bob's public key
	aliceShared, err := PerformECDH(aliceKey, bobKey.PublicKey().Bytes())
	if err != nil {
		t.Fatalf("PerformECDH(alice) error = %v", err)
	}

	// Bob computes shared secret with Alice's public key
	bobShared, err := PerformECDH(bobKey, aliceKey.PublicKey().Bytes())
	if err != nil {
		t.Fatalf("PerformECDH(bob) error = %v", err)
	}

	// Both should arrive at the same shared secret
	if !bytes.Equal(aliceShared, bobShared) {
		t.Error("ECDH shared secrets don't match")
	}

	// Shared secret should be 32 bytes
	if len(aliceShared) != 32 {
		t.Errorf("Shared secret length = %d, want 32", len(aliceShared))
	}
}

func TestPerformECDH_InvalidKey(t *testing.T) {
	aliceKey, _ := GenerateX25519KeyPair()

	// Invalid public key (wrong size)
	_, err := PerformECDH(aliceKey, []byte("too short"))
	if err == nil {
		t.Error("PerformECDH() should fail with invalid public key")
	}
}

func TestSecureBuffer(t *testing.T) {
	secret := []byte("super-secret-data-here!")

	enclave := SecureBuffer(secret)
	if enclave == nil {
		t.Fatal("SecureBuffer() returned nil")
	}

	// Original data should be zeroed (memguard behavior)
	// We can't easily test this without accessing memguard internals
}

// Mock connection for auth tests
type mockConn struct {
	readBuf  *bytes.Buffer
	writeBuf *bytes.Buffer
}

func newMockConnPair() (*mockConn, *mockConn) {
	buf1 := &bytes.Buffer{}
	buf2 := &bytes.Buffer{}
	return &mockConn{readBuf: buf1, writeBuf: buf2},
		&mockConn{readBuf: buf2, writeBuf: buf1}
}

func (m *mockConn) Read(b []byte) (n int, err error)   { return m.readBuf.Read(b) }
func (m *mockConn) Write(b []byte) (n int, err error)  { return m.writeBuf.Write(b) }
func (m *mockConn) Close() error                       { return nil }
func (m *mockConn) LocalAddr() net.Addr                { return nil }
func (m *mockConn) RemoteAddr() net.Addr               { return nil }
func (m *mockConn) SetDeadline(t time.Time) error      { return nil }
func (m *mockConn) SetReadDeadline(t time.Time) error  { return nil }
func (m *mockConn) SetWriteDeadline(t time.Time) error { return nil }

func TestMutualAuth(t *testing.T) {
	sharedSecret := make([]byte, 32)
	for i := range sharedSecret {
		sharedSecret[i] = byte(i)
	}

	// Create connected mock pair
	serverConn, clientConn := newMockConnPair()

	// Run server auth in goroutine
	serverErr := make(chan error, 1)
	go func() {
		serverErr <- PerformServerAuth(serverConn, sharedSecret)
	}()

	// Small delay to ensure server sends challenge first
	time.Sleep(10 * time.Millisecond)

	// Run client auth
	err := PerformClientAuth(clientConn, sharedSecret)
	if err != nil {
		t.Fatalf("PerformClientAuth() error = %v", err)
	}

	// Check server result
	select {
	case err := <-serverErr:
		if err != nil {
			t.Fatalf("PerformServerAuth() error = %v", err)
		}
	case <-time.After(time.Second):
		t.Fatal("Server auth timed out")
	}
}

func TestRandomDelay(t *testing.T) {
	start := time.Now()
	err := RandomDelay()
	elapsed := time.Since(start)

	if err != nil {
		t.Fatalf("RandomDelay() error = %v", err)
	}

	// Should be at least MinRandomDelay
	if elapsed < time.Duration(MinRandomDelay)*time.Millisecond {
		t.Errorf("RandomDelay() too fast: %v", elapsed)
	}

	// Should be at most MaxRandomDelay (with some buffer)
	if elapsed > time.Duration(MaxRandomDelay+50)*time.Millisecond {
		t.Errorf("RandomDelay() too slow: %v", elapsed)
	}
}

// Benchmark tests
func BenchmarkPadMessage(b *testing.B) {
	msg := []byte("This is a test message for benchmarking")
	for i := 0; i < b.N; i++ {
		PadMessage(msg)
	}
}

func BenchmarkEncryptDecrypt(b *testing.B) {
	key := make([]byte, 32)
	gcm, _ := SetupAESGCM(key)
	plaintext := []byte("Benchmark message for encryption testing")

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		ct, _ := Encrypt(gcm, plaintext)
		Decrypt(gcm, ct)
	}
}

// Helper to satisfy cipher.AEAD interface check
var _ cipher.AEAD = (cipher.AEAD)(nil)