Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

Remove obsolete libsodium migration tests

Manav Rathif068aa932b26
diff --git a/server/pkg/utils/crypto/crypto_bench_test.go b/server/pkg/utils/crypto/crypto_bench_test.go
deleted file mode 100644
index a67438be71..0000000000
--- a/server/pkg/utils/crypto/crypto_bench_test.go
+++ /dev/null
@@ -1,275 +0,0 @@
-package crypto
-
-import (
- "encoding/base64"
- "testing"
-
- "github.com/ente/museum/ente"
-)
-
-// Benchmark encryption operations
-
-func BenchmarkEncryptLibsodium(b *testing.B) {
- benchmarkEncrypt(b, Encrypt)
-}
-
-func BenchmarkEncryptNative(b *testing.B) {
- benchmarkEncrypt(b, EncryptNative)
-}
-
-func benchmarkEncrypt(b *testing.B, encryptFunc func(string, []byte) (ente.EncryptionResult, error)) {
- sizes := []struct {
- name string
- size int
- }{
- {"Small_32B", 32},
- {"Medium_1KB", 1024},
- {"Large_10KB", 10240},
- {"XLarge_100KB", 102400},
- {"Huge_1MB", 1048576},
- }
-
- for _, size := range sizes {
- b.Run(size.name, func(b *testing.B) {
- data := generateLargeText(size.size)
- key := generateTestKey()
-
- b.SetBytes(int64(size.size))
-
- for b.Loop() {
- _, err := encryptFunc(data, key)
- if err != nil {
- b.Fatal(err)
- }
- }
- })
- }
-}
-
-// Benchmark decryption operations
-
-func BenchmarkDecryptLibsodium(b *testing.B) {
- benchmarkDecrypt(b, Encrypt, Decrypt)
-}
-
-func BenchmarkDecryptNative(b *testing.B) {
- benchmarkDecrypt(b, EncryptNative, DecryptNative)
-}
-
-func benchmarkDecrypt(b *testing.B,
- encryptFunc func(string, []byte) (ente.EncryptionResult, error),
- decryptFunc func([]byte, []byte, []byte) (string, error)) {
-
- sizes := []struct {
- name string
- size int
- }{
- {"Small_32B", 32},
- {"Medium_1KB", 1024},
- {"Large_10KB", 10240},
- {"XLarge_100KB", 102400},
- {"Huge_1MB", 1048576},
- }
-
- for _, size := range sizes {
- b.Run(size.name, func(b *testing.B) {
- data := generateLargeText(size.size)
- key := generateTestKey()
-
- // Encrypt once for benchmark
- encResult, err := encryptFunc(data, key)
- if err != nil {
- b.Fatal(err)
- }
-
- cipher := encResult.Cipher
- nonce := encResult.Nonce
-
- b.SetBytes(int64(size.size))
-
- for b.Loop() {
- _, err := decryptFunc(cipher, key, nonce)
- if err != nil {
- b.Fatal(err)
- }
- }
- })
- }
-}
-
-// Benchmark hash operations
-
-func BenchmarkHashLibsodium(b *testing.B) {
- benchmarkHash(b, GetHash)
-}
-
-func BenchmarkHashNative(b *testing.B) {
- benchmarkHash(b, GetHashNative)
-}
-
-func benchmarkHash(b *testing.B, hashFunc func(string, []byte) (string, error)) {
- sizes := []struct {
- name string
- size int
- }{
- {"Small_32B", 32},
- {"Medium_1KB", 1024},
- {"Large_10KB", 10240},
- {"XLarge_100KB", 102400},
- {"Huge_1MB", 1048576},
- }
-
- for _, size := range sizes {
- b.Run(size.name, func(b *testing.B) {
- data := generateLargeText(size.size)
-
- b.SetBytes(int64(size.size))
-
- for b.Loop() {
- _, err := hashFunc(data, nil)
- if err != nil {
- b.Fatal(err)
- }
- }
- })
- }
-}
-
-// Benchmark token encryption (sealed box)
-
-func BenchmarkGetEncryptedTokenLibsodium(b *testing.B) {
- benchmarkGetEncryptedToken(b, GetEncryptedToken)
-}
-
-func BenchmarkGetEncryptedTokenNative(b *testing.B) {
- benchmarkGetEncryptedToken(b, GetEncryptedTokenNative)
-}
-
-func benchmarkGetEncryptedToken(b *testing.B, tokenFunc func(string, string) (string, error)) {
- // Generate test public key
- publicKey := make([]byte, 32)
- for i := range publicKey {
- publicKey[i] = byte(i * 3)
- }
- publicKeyB64 := base64.StdEncoding.EncodeToString(publicKey)
-
- sizes := []struct {
- name string
- size int
- }{
- {"Small_32B", 32},
- {"Medium_256B", 256},
- {"Large_1KB", 1024},
- }
-
- for _, size := range sizes {
- b.Run(size.name, func(b *testing.B) {
- tokenData := generateLargeText(size.size)
- token := base64.URLEncoding.EncodeToString([]byte(tokenData))
-
- b.SetBytes(int64(size.size))
-
- for b.Loop() {
- _, err := tokenFunc(token, publicKeyB64)
- if err != nil {
- b.Fatal(err)
- }
- }
- })
- }
-}
-
-// Combined encryption/decryption cycle benchmark
-
-func BenchmarkFullCycleLibsodium(b *testing.B) {
- benchmarkFullCycle(b, Encrypt, Decrypt)
-}
-
-func BenchmarkFullCycleNative(b *testing.B) {
- benchmarkFullCycle(b, EncryptNative, DecryptNative)
-}
-
-func benchmarkFullCycle(b *testing.B,
- encryptFunc func(string, []byte) (ente.EncryptionResult, error),
- decryptFunc func([]byte, []byte, []byte) (string, error)) {
-
- sizes := []struct {
- name string
- size int
- }{
- {"Small_32B", 32},
- {"Medium_1KB", 1024},
- {"Large_10KB", 10240},
- {"XLarge_100KB", 102400},
- }
-
- for _, size := range sizes {
- b.Run(size.name, func(b *testing.B) {
- data := generateLargeText(size.size)
- key := generateTestKey()
-
- b.SetBytes(int64(size.size * 2)) // Count both encrypt and decrypt
-
- for b.Loop() {
- encResult, err := encryptFunc(data, key)
- if err != nil {
- b.Fatal(err)
- }
-
- cipher := encResult.Cipher
- nonce := encResult.Nonce
-
- _, err = decryptFunc(cipher, key, nonce)
- if err != nil {
- b.Fatal(err)
- }
- }
- })
- }
-}
-
-// Memory allocation benchmarks
-
-func BenchmarkMemoryAllocLibsodium(b *testing.B) {
- b.ReportAllocs()
- data := generateLargeText(1024)
- key := generateTestKey()
-
- for b.Loop() {
- _, _ = Encrypt(data, key)
- }
-}
-
-func BenchmarkMemoryAllocNative(b *testing.B) {
- b.ReportAllocs()
- data := generateLargeText(1024)
- key := generateTestKey()
-
- for b.Loop() {
- _, _ = EncryptNative(data, key)
- }
-}
-
-// Parallel benchmarks to test concurrent performance
-
-func BenchmarkParallelEncryptLibsodium(b *testing.B) {
- data := generateLargeText(1024)
- key := generateTestKey()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- _, _ = Encrypt(data, key)
- }
- })
-}
-
-func BenchmarkParallelEncryptNative(b *testing.B) {
- data := generateLargeText(1024)
- key := generateTestKey()
-
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- _, _ = EncryptNative(data, key)
- }
- })
-}
diff --git a/server/pkg/utils/crypto/crypto_enhanced_test.go b/server/pkg/utils/crypto/crypto_enhanced_test.go
deleted file mode 100644
index 86ad3e3639..0000000000
--- a/server/pkg/utils/crypto/crypto_enhanced_test.go
+++ /dev/null
@@ -1,426 +0,0 @@
-package crypto
-
-import (
- "encoding/base64"
- "fmt"
- "strings"
- "testing"
-
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
-)
-
-// Test real-world scenarios based on codebase usage
-
-func TestRealWorldEmailEncryption(t *testing.T) {
- // Simulating email encryption as used in user controller
- secretEncryptionKey := generateTestKey()
-
- emails := []string{
- // Edge cases found in production
- "user@例え.jp", // IDN domain
- "very.long.email.address.with.many.dots@subdomain.of.a.domain.example.com",
- }
-
- for _, email := range emails {
- t.Run(fmt.Sprintf("email_%s", strings.ReplaceAll(email, "@", "_at_")), func(t *testing.T) {
- // Test with libsodium
- encryptedLib, err := Encrypt(email, secretEncryptionKey)
- require.NoError(t, err)
-
- // Test with native
- encryptedNative, err := EncryptNative(email, secretEncryptionKey)
- require.NoError(t, err)
-
- // Cross-decrypt
- decryptedFromLib, err := DecryptNative(encryptedLib.Cipher, secretEncryptionKey, encryptedLib.Nonce)
- require.NoError(t, err)
- assert.Equal(t, email, decryptedFromLib)
-
- decryptedFromNative, err := Decrypt(encryptedNative.Cipher, secretEncryptionKey, encryptedNative.Nonce)
- require.NoError(t, err)
- assert.Equal(t, email, decryptedFromNative)
- })
- }
-}
-
-func TestRealWorldSecretEncryption(t *testing.T) {
- // Simulating 2FA secret encryption as used in twofactor controller
- secretEncryptionKey := generateTestKey()
-
- secrets := []string{
- "JBSWY3DPEHPK3PXP", // Standard TOTP secret
- "MFRGGZDFMZTWQ2LKNNWG23TPOBYXE43UOV3HO6DZPF4GIZLDOQWXI", // Longer secret
- "abcdefghijklmnopqrstuvwxyz234567", // Base32 alphabet
- "ABCDEFGHIJKLMNOP", // Short secret
- strings.Repeat("A", 256), // Large secret
- }
-
- for _, secret := range secrets {
- t.Run(fmt.Sprintf("secret_len_%d", len(secret)), func(t *testing.T) {
- // Encrypt with both implementations
- encryptedLib, err := Encrypt(secret, secretEncryptionKey)
- require.NoError(t, err)
-
- encryptedNative, err := EncryptNative(secret, secretEncryptionKey)
- require.NoError(t, err)
-
- // Verify both can decrypt each other
- decryptedLib, err := Decrypt(encryptedNative.Cipher, secretEncryptionKey, encryptedNative.Nonce)
- require.NoError(t, err)
- assert.Equal(t, secret, decryptedLib)
-
- decryptedNative, err := DecryptNative(encryptedLib.Cipher, secretEncryptionKey, encryptedLib.Nonce)
- require.NoError(t, err)
- assert.Equal(t, secret, decryptedNative)
- })
- }
-}
-
-func TestRealWorldHashingWithKey(t *testing.T) {
- // Simulating email and secret hashing as used in the codebase
- hashingKeys := [][]byte{
- nil, // Some hashes use nil key
- generateTestKey(), // 32-byte key
- []byte("sixteen-byte-key"), // 16-byte key (minimum for libsodium)
- []byte(strings.Repeat("x", 64)), // 64-byte key (maximum for libsodium)
- }
-
- inputs := []string{
- strings.ToLower("[email protected]"), // Email normalization
- "JBSWY3DPEHPK3PXP", // TOTP secret
- "", // Edge case - empty string (skip for libsodium due to bug)
- strings.Repeat("a", 10000), // Large input
- }
-
- for _, key := range hashingKeys {
- keyName := "nil"
- if key != nil {
- keyName = fmt.Sprintf("key_len_%d", len(key))
- }
-
- for _, input := range inputs {
- if input == "" {
- continue // Skip empty string due to libsodium-go bug
- }
-
- t.Run(fmt.Sprintf("%s_input_%d_chars", keyName, len(input)), func(t *testing.T) {
- hashLib, err := GetHash(input, key)
- require.NoError(t, err)
-
- hashNative, err := GetHashNative(input, key)
- require.NoError(t, err)
-
- assert.Equal(t, hashLib, hashNative, "Hashes should match")
-
- // Verify hash is deterministic
- hashLib2, err := GetHash(input, key)
- require.NoError(t, err)
- assert.Equal(t, hashLib, hashLib2, "Hash should be deterministic")
-
- hashNative2, err := GetHashNative(input, key)
- require.NoError(t, err)
- assert.Equal(t, hashNative, hashNative2, "Native hash should be deterministic")
- })
- }
- }
-}
-
-func TestRealWorldTokenEncryption(t *testing.T) {
- // Simulating token encryption with public keys as used in auth
-
- // Generate test public keys
- publicKey1 := make([]byte, 32)
- for i := range publicKey1 {
- publicKey1[i] = byte(i + 1)
- }
-
- publicKey2 := make([]byte, 32)
- for i := range publicKey2 {
- publicKey2[i] = byte(i * 2)
- }
-
- publicKeys := []string{
- base64.StdEncoding.EncodeToString(publicKey1),
- base64.StdEncoding.EncodeToString(publicKey2),
- }
-
- tokens := []string{
- // JWT-like tokens
- base64.URLEncoding.EncodeToString([]byte("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9")),
- // Session tokens
- base64.URLEncoding.EncodeToString([]byte("session_1234567890")),
- // Random tokens
- base64.URLEncoding.EncodeToString([]byte(strings.Repeat("x", 64))),
- }
-
- for _, publicKey := range publicKeys {
- for i, token := range tokens {
- t.Run(fmt.Sprintf("token_%d", i), func(t *testing.T) {
- // Both implementations should produce valid sealed boxes
- encryptedLib, err := GetEncryptedToken(token, publicKey)
- require.NoError(t, err)
-
- encryptedNative, err := GetEncryptedTokenNative(token, publicKey)
- require.NoError(t, err)
-
- // Verify format (ephemeral public key + ciphertext)
- encryptedLibBytes, err := base64.StdEncoding.DecodeString(encryptedLib)
- require.NoError(t, err)
- assert.GreaterOrEqual(t, len(encryptedLibBytes), 48, "Should have ephemeral key (32) + MAC (16)")
-
- encryptedNativeBytes, err := base64.StdEncoding.DecodeString(encryptedNative)
- require.NoError(t, err)
- assert.GreaterOrEqual(t, len(encryptedNativeBytes), 48, "Should have ephemeral key (32) + MAC (16)")
- })
- }
- }
-}
-
-func TestMigrationScenarios(t *testing.T) {
- // Test scenarios for migrating from libsodium to native
-
- t.Run("existing_encrypted_data_compatibility", func(t *testing.T) {
- // Simulate existing data encrypted with libsodium
- data := "[email protected]"
- key := generateTestKey()
-
- // Encrypt with libsodium (simulating existing data)
- existingEncrypted, err := Encrypt(data, key)
- require.NoError(t, err)
-
- // Ensure native can decrypt existing data
- decrypted, err := DecryptNative(existingEncrypted.Cipher, key, existingEncrypted.Nonce)
- require.NoError(t, err)
- assert.Equal(t, data, decrypted, "Native should decrypt existing libsodium data")
- })
-
- t.Run("new_data_backward_compatibility", func(t *testing.T) {
- // Simulate new data encrypted with native
- data := "[email protected]"
- key := generateTestKey()
-
- // Encrypt with native (new implementation)
- newEncrypted, err := EncryptNative(data, key)
- require.NoError(t, err)
-
- // Ensure libsodium can still decrypt if needed
- decrypted, err := Decrypt(newEncrypted.Cipher, key, newEncrypted.Nonce)
- require.NoError(t, err)
- assert.Equal(t, data, decrypted, "Libsodium should decrypt native encrypted data")
- })
-
- t.Run("hash_consistency_across_migration", func(t *testing.T) {
- // Critical for email lookups and authentication
- email := "[email protected]"
- hashingKey := []byte("production-hashing-key-32-bytes!")
-
- // Hash with both implementations
- hashLib, err := GetHash(email, hashingKey)
- require.NoError(t, err)
-
- hashNative, err := GetHashNative(email, hashingKey)
- require.NoError(t, err)
-
- // MUST be identical for database lookups to work
- assert.Equal(t, hashLib, hashNative, "Hashes must be identical for migration")
- })
-}
-
-func TestProductionEdgeCases(t *testing.T) {
- key := generateTestKey()
-
- t.Run("unicode_data", func(t *testing.T) {
- // Test with various unicode strings
- unicodeStrings := []string{
- "Hello 世界 🌍",
- "Здравствуй мир",
- "مرحبا بالعالم",
- "🔐🔑🗝️",
- "user@日本.jp",
- }
-
- for _, s := range unicodeStrings {
- encLib, err := Encrypt(s, key)
- require.NoError(t, err)
-
- encNative, err := EncryptNative(s, key)
- require.NoError(t, err)
-
- // Cross-decrypt
- decLib, err := DecryptNative(encLib.Cipher, key, encLib.Nonce)
- require.NoError(t, err)
- assert.Equal(t, s, decLib)
-
- decNative, err := Decrypt(encNative.Cipher, key, encNative.Nonce)
- require.NoError(t, err)
- assert.Equal(t, s, decNative)
- }
- })
-
- t.Run("binary_data", func(t *testing.T) {
- // Test with binary data (non-UTF8)
- binaryData := []string{
- string([]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}),
- string([]byte{255, 254, 253, 252, 251}),
- "\x00\x01\x02\x03",
- }
-
- for _, data := range binaryData {
- encLib, err := Encrypt(data, key)
- require.NoError(t, err)
-
- encNative, err := EncryptNative(data, key)
- require.NoError(t, err)
-
- // Both should handle binary data correctly
- decLib, err := DecryptNative(encLib.Cipher, key, encLib.Nonce)
- require.NoError(t, err)
- assert.Equal(t, data, decLib)
-
- decNative, err := Decrypt(encNative.Cipher, key, encNative.Nonce)
- require.NoError(t, err)
- assert.Equal(t, data, decNative)
- }
- })
-
- t.Run("very_large_data", func(t *testing.T) {
- // Test with large data (e.g., large JSON payloads)
- sizes := []int{
- 10 * 1024, // 10KB
- 100 * 1024, // 100KB
- 1024 * 1024, // 1MB
- }
-
- for _, size := range sizes {
- t.Run(fmt.Sprintf("size_%d", size), func(t *testing.T) {
- largeData := strings.Repeat("a", size)
-
- // Encrypt with native (faster based on benchmarks)
- encNative, err := EncryptNative(largeData, key)
- require.NoError(t, err)
-
- // Decrypt with libsodium to verify compatibility
- decLib, err := Decrypt(encNative.Cipher, key, encNative.Nonce)
- require.NoError(t, err)
- assert.Equal(t, largeData, decLib)
- })
- }
- })
-}
-
-func TestConcurrentOperations(t *testing.T) {
- // Test thread-safety of both implementations
- key := generateTestKey()
- hashKey := []byte("concurrent-hash-key-test-32byte!")
-
- t.Run("concurrent_encryption", func(t *testing.T) {
- data := []string{
- }
-
- // Run concurrent encryptions
- results := make(chan bool, len(data)*2)
-
- for _, d := range data {
- go func(text string) {
- enc, err := EncryptNative(text, key)
- assert.NoError(t, err)
- dec, err := DecryptNative(enc.Cipher, key, enc.Nonce)
- assert.NoError(t, err)
- results <- (dec == text)
- }(d)
-
- go func(text string) {
- enc, err := Encrypt(text, key)
- assert.NoError(t, err)
- dec, err := Decrypt(enc.Cipher, key, enc.Nonce)
- assert.NoError(t, err)
- results <- (dec == text)
- }(d)
- }
-
- // Verify all succeeded
- for i := 0; i < len(data)*2; i++ {
- assert.True(t, <-results)
- }
- })
-
- t.Run("concurrent_hashing", func(t *testing.T) {
- inputs := []string{
- }
-
- results := make(chan string, len(inputs)*2)
-
- for _, input := range inputs {
- go func(text string) {
- hash, err := GetHashNative(text, hashKey)
- assert.NoError(t, err)
- results <- hash
- }(input)
-
- go func(text string) {
- hash, err := GetHash(text, hashKey)
- assert.NoError(t, err)
- results <- hash
- }(input)
- }
-
- // Collect and verify consistency
- hashes := make(map[string]int)
- for i := 0; i < len(inputs)*2; i++ {
- h := <-results
- hashes[h]++
- }
-
- // Each input should produce the same hash twice (once from each impl)
- for _, count := range hashes {
- assert.Equal(t, 2, count, "Each hash should appear exactly twice")
- }
- })
-}
-
-func TestDeterministicBehavior(t *testing.T) {
- // Critical test: Ensure deterministic behavior with same nonce
- key := generateTestKey()
- data := "[email protected]"
-
- // Use a fixed nonce for testing
- fixedNonce := make([]byte, SecretBoxNonceBytes)
- for i := range fixedNonce {
- fixedNonce[i] = byte(i * 3)
- }
-
- // Encrypt multiple times with same nonce
- enc1, err := encryptWithNonce(data, key, fixedNonce)
- require.NoError(t, err)
-
- enc2, err := encryptWithNonce(data, key, fixedNonce)
- require.NoError(t, err)
-
- encNative1, err := encryptWithNonceNative(data, key, fixedNonce)
- require.NoError(t, err)
-
- encNative2, err := encryptWithNonceNative(data, key, fixedNonce)
- require.NoError(t, err)
-
- // All should be identical
- assert.Equal(t, enc1.Cipher, enc2.Cipher, "Libsodium should be deterministic with same nonce")
- assert.Equal(t, encNative1.Cipher, encNative2.Cipher, "Native should be deterministic with same nonce")
- assert.Equal(t, enc1.Cipher, encNative1.Cipher, "Both implementations should produce same output with same nonce")
-}
diff --git a/server/pkg/utils/crypto/crypto_test.go b/server/pkg/utils/crypto/crypto_test.go
index 43ce3b19f1..e659ec5d9d 100644
--- a/server/pkg/utils/crypto/crypto_test.go
+++ b/server/pkg/utils/crypto/crypto_test.go
@@ -1,276 +1,55 @@
package crypto
import (
- "crypto/rand"
- "encoding/base64"
"testing"
- "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "golang.org/x/crypto/nacl/box"
)
-func TestEncryptWithSameNonce(t *testing.T) {
- // Test that both implementations produce identical output with the same nonce
- data := "Hello, World!"
- key := generateTestKey()
-
- // Generate a fixed nonce
- nonce := make([]byte, SecretBoxNonceBytes)
- for i := range nonce {
- nonce[i] = byte(i * 7)
- }
-
- // Encrypt with libsodium
- encryptedLibsodium, err := encryptWithNonce(data, key, nonce)
- require.NoError(t, err, "libsodium encryption should succeed")
-
- // Encrypt with native
- encryptedNative, err := encryptWithNonceNative(data, key, nonce)
- require.NoError(t, err, "native encryption should succeed")
-
- // Check that ciphertext is identical
- assert.Equal(t, encryptedLibsodium.Cipher, encryptedNative.Cipher, "ciphertext should be identical")
- assert.Equal(t, encryptedLibsodium.Nonce, encryptedNative.Nonce, "nonce should be identical")
-
- // Verify both can decrypt each other's output
- decryptedFromLibsodium, err := DecryptNative(encryptedLibsodium.Cipher, key, encryptedLibsodium.Nonce)
- require.NoError(t, err, "native should decrypt libsodium ciphertext")
- assert.Equal(t, data, decryptedFromLibsodium)
-
- decryptedFromNative, err := Decrypt(encryptedNative.Cipher, key, encryptedNative.Nonce)
- require.NoError(t, err, "libsodium should decrypt native ciphertext")
- assert.Equal(t, data, decryptedFromNative)
-}
-
-func TestEncryptDecryptCompatibility(t *testing.T) {
- tests := []struct {
- name string
- data string
- key []byte
- }{
- {
- name: "simple text",
- data: "Hello, World!",
- key: generateTestKey(),
- },
- // Skip empty string test - libsodium-go wrapper has a bug with empty strings
- // {
- // name: "empty string",
- // data: "",
- // key: generateTestKey(),
- // },
- {
- name: "special characters",
- data: "!@#$%^&*()_+-=[]{}|;':\",./<>?",
- key: generateTestKey(),
- },
- {
- name: "unicode characters",
- data: "你好世界 🌍 مرحبا بالعالم",
- key: generateTestKey(),
- },
- {
- name: "large text",
- data: generateLargeText(10000),
- key: generateTestKey(),
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Test libsodium encryption -> native decryption
- t.Run("libsodium_encrypt_native_decrypt", func(t *testing.T) {
- encrypted, err := Encrypt(tt.data, tt.key)
- require.NoError(t, err, "libsodium encryption should succeed")
-
- decrypted, err := DecryptNative(encrypted.Cipher, tt.key, encrypted.Nonce)
- require.NoError(t, err, "native decryption should succeed")
- assert.Equal(t, tt.data, decrypted, "decrypted data should match original")
- })
-
- // Test native encryption -> libsodium decryption
- t.Run("native_encrypt_libsodium_decrypt", func(t *testing.T) {
- encrypted, err := EncryptNative(tt.data, tt.key)
- require.NoError(t, err, "native encryption should succeed")
-
- decrypted, err := Decrypt(encrypted.Cipher, tt.key, encrypted.Nonce)
- require.NoError(t, err, "libsodium decryption should succeed")
- assert.Equal(t, tt.data, decrypted, "decrypted data should match original")
- })
-
- // Test self-consistency of native implementation
- t.Run("native_self_consistency", func(t *testing.T) {
- encrypted, err := EncryptNative(tt.data, tt.key)
- require.NoError(t, err, "native encryption should succeed")
-
- decrypted, err := DecryptNative(encrypted.Cipher, tt.key, encrypted.Nonce)
- require.NoError(t, err, "native decryption should succeed")
- assert.Equal(t, tt.data, decrypted, "decrypted data should match original")
- })
-
- // Test self-consistency of libsodium implementation
- t.Run("libsodium_self_consistency", func(t *testing.T) {
- encrypted, err := Encrypt(tt.data, tt.key)
- require.NoError(t, err, "libsodium encryption should succeed")
-
- decrypted, err := Decrypt(encrypted.Cipher, tt.key, encrypted.Nonce)
- require.NoError(t, err, "libsodium decryption should succeed")
- assert.Equal(t, tt.data, decrypted, "decrypted data should match original")
- })
- })
- }
-}
-
-func TestHashCompatibility(t *testing.T) {
- tests := []struct {
- name string
- data string
- }{
- {
- name: "simple text",
- data: "Hello, World!",
- },
- {
- name: "empty string",
- data: "",
- },
- {
- name: "special characters",
- data: "!@#$%^&*()_+-=[]{}|;':\",./<>?",
- },
- {
- name: "unicode characters",
- data: "你好世界 🌍 مرحبا بالعالم",
- },
- {
- name: "large text",
- data: generateLargeText(10000),
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- hashLibsodium, err := GetHash(tt.data, nil)
- require.NoError(t, err, "libsodium hash should succeed")
-
- hashNative, err := GetHashNative(tt.data, nil)
- require.NoError(t, err, "native hash should succeed")
-
- assert.Equal(t, hashLibsodium, hashNative, "hashes should match")
- })
- }
-}
-
-func TestGetEncryptedTokenCompatibility(t *testing.T) {
- // Generate test keypair for recipient
- recipientPublicKey, _ := generateTestKeyPair()
- recipientPublicKeyB64 := base64.StdEncoding.EncodeToString(recipientPublicKey[:])
-
- tests := []struct {
- name string
- token string
- }{
- {
- name: "simple token",
- token: base64.URLEncoding.EncodeToString([]byte("test-token-123")),
- },
- {
- name: "complex token",
- token: base64.URLEncoding.EncodeToString([]byte("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0")),
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- // Test that both implementations produce valid sealed boxes
- // We can't compare the encrypted values directly because they use random ephemeral keys
-
- // Test libsodium implementation produces valid output
- t.Run("libsodium_valid_output", func(t *testing.T) {
- encrypted, err := GetEncryptedToken(tt.token, recipientPublicKeyB64)
- require.NoError(t, err, "libsodium encryption should succeed")
-
- // Verify output format
- encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)
- require.NoError(t, err, "should decode encrypted token")
- // Sealed box format: ephemeral_pk (32 bytes) + ciphertext
- assert.GreaterOrEqual(t, len(encryptedBytes), 32+16, "should have ephemeral key and ciphertext")
- })
-
- // Test native implementation produces valid output
- t.Run("native_valid_output", func(t *testing.T) {
- encrypted, err := GetEncryptedTokenNative(tt.token, recipientPublicKeyB64)
- require.NoError(t, err, "native encryption should succeed")
-
- // Verify output format
- encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)
- require.NoError(t, err, "should decode encrypted token")
- // Sealed box format: ephemeral_pk (32 bytes) + ciphertext
- assert.GreaterOrEqual(t, len(encryptedBytes), 32+16, "should have ephemeral key and ciphertext")
- })
-
- // Test that both can decrypt each other's output
- // Note: We would need the decrypt sealed box function to fully test compatibility
- // For now we just verify the format is correct
- })
- }
-}
-
func TestErrorCases(t *testing.T) {
validKey := generateTestKey()
t.Run("invalid_key_length", func(t *testing.T) {
- // Test with wrong key length
shortKey := []byte("too-short")
- _, err := EncryptNative("test", shortKey)
- assert.Error(t, err, "should error with short key")
+ _, err := Encrypt("test", shortKey)
+ require.Error(t, err)
- _, err = DecryptNative([]byte("test"), shortKey, []byte("nonce"))
- assert.Error(t, err, "should error with short key")
+ _, err = Decrypt([]byte("test"), shortKey, []byte("nonce"))
+ require.Error(t, err)
})
t.Run("invalid_nonce_length", func(t *testing.T) {
- // Test decrypt with wrong nonce length
- encrypted, err := EncryptNative("test", validKey)
+ encrypted, err := Encrypt("test", validKey)
require.NoError(t, err)
- _, err = DecryptNative(encrypted.Cipher, validKey, []byte("short"))
- assert.Error(t, err, "should error with short nonce")
+ _, err = Decrypt(encrypted.Cipher, validKey, []byte("short"))
+ require.Error(t, err)
})
t.Run("tampered_ciphertext", func(t *testing.T) {
- encrypted, err := EncryptNative("test", validKey)
+ encrypted, err := Encrypt("test", validKey)
require.NoError(t, err)
- // Tamper with ciphertext
- cipherBytes := make([]byte, len(encrypted.Cipher))
- copy(cipherBytes, encrypted.Cipher)
- if len(cipherBytes) > 0 {
- cipherBytes[0] ^= 0xFF // Flip bits
- }
+ cipher := append([]byte(nil), encrypted.Cipher...)
+ cipher[0] ^= 0xff
- _, err = DecryptNative(cipherBytes, validKey, encrypted.Nonce)
- assert.Error(t, err, "should error with tampered ciphertext")
+ _, err = Decrypt(cipher, validKey, encrypted.Nonce)
+ require.Error(t, err)
})
- t.Run("wrong_key_decrypt", func(t *testing.T) {
- wrongKey := make([]byte, 32)
- for i := range wrongKey {
- wrongKey[i] = byte(i + 100) // Different pattern from validKey
- }
+ t.Run("wrong_key", func(t *testing.T) {
+ wrongKey := generateTestKey()
+ wrongKey[0] ^= 0xff
- encrypted, err := EncryptNative("test", validKey)
+ encrypted, err := Encrypt("test", validKey)
require.NoError(t, err)
- _, err = DecryptNative(encrypted.Cipher, wrongKey, encrypted.Nonce)
- assert.Error(t, err, "should error with wrong key")
+ _, err = Decrypt(encrypted.Cipher, wrongKey, encrypted.Nonce)
+ require.Error(t, err)
})
}
-// Helper functions
-
func generateTestKey() []byte {
key := make([]byte, SecretBoxKeyBytes)
for i := range key {
@@ -278,21 +57,3 @@ func generateTestKey() []byte {
}
return key
}
-
-func generateTestKeyPair() ([32]byte, [32]byte) {
- // Generate a valid test keypair using nacl/box
- // For tests that need actual crypto operations
- publicKey, privateKey, err := box.GenerateKey(rand.Reader)
- if err != nil {
- panic(err)
- }
- return *publicKey, *privateKey
-}
-
-func generateLargeText(size int) string {
- text := make([]byte, size)
- for i := range text {
- text[i] = byte('a' + (i % 26))
- }
- return string(text)
-}
diff --git a/server/pkg/utils/crypto/sealed_box_deep_test.go b/server/pkg/utils/crypto/sealed_box_deep_test.go
deleted file mode 100644
index 7ba730183b..0000000000
--- a/server/pkg/utils/crypto/sealed_box_deep_test.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package crypto
-
-import (
- "crypto/rand"
- "encoding/base64"
- "testing"
-
- "github.com/stretchr/testify/require"
- "golang.org/x/crypto/blake2b"
- "golang.org/x/crypto/nacl/box"
-)
-
-func deriveSealedBoxNonce(ephemeralPublicKey *[BoxPublicKeyBytes]byte, recipientPublicKey *[BoxPublicKeyBytes]byte) ([SecretBoxNonceBytes]byte, error) {
- nonceInput := make([]byte, BoxPublicKeyBytes*2)
- copy(nonceInput[:BoxPublicKeyBytes], ephemeralPublicKey[:])
- copy(nonceInput[BoxPublicKeyBytes:], recipientPublicKey[:])
-
- hash, err := blake2b.New(SecretBoxNonceBytes, nil)
- if err != nil {
- return [SecretBoxNonceBytes]byte{}, err
- }
- hash.Write(nonceInput)
-
- var nonce [SecretBoxNonceBytes]byte
- copy(nonce[:], hash.Sum(nil))
- return nonce, nil
-}
-
-func TestNonceDerivationInDetail(t *testing.T) {
- recipientPublicKey, _, err := box.GenerateKey(rand.Reader)
- require.NoError(t, err)
-
- ephemeralPublicKey, _, err := box.GenerateKey(rand.Reader)
- require.NoError(t, err)
-
- t.Run("unkeyed_blake2b_derivation_is_deterministic", func(t *testing.T) {
- nonce1, err := deriveSealedBoxNonce(ephemeralPublicKey, recipientPublicKey)
- require.NoError(t, err)
-
- nonce2, err := deriveSealedBoxNonce(ephemeralPublicKey, recipientPublicKey)
- require.NoError(t, err)
-
- require.Equal(t, nonce1, nonce2, "nonce derivation must be deterministic for same inputs")
- })
-
- t.Run("keyed_blake2b_derivation_is_different", func(t *testing.T) {
- expectedNonce, err := deriveSealedBoxNonce(ephemeralPublicKey, recipientPublicKey)
- require.NoError(t, err)
-
- keyedHash, err := blake2b.New(SecretBoxNonceBytes, ephemeralPublicKey[:])
- require.NoError(t, err)
- keyedHash.Write(recipientPublicKey[:])
-
- keyedNonce := keyedHash.Sum(nil)
- require.NotEqual(t, expectedNonce[:], keyedNonce, "keyed derivation must not match sealed-box nonce")
- })
-}
-
-func TestNativeSealedBoxRoundTrip(t *testing.T) {
- recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)
- require.NoError(t, err)
-
- message := []byte("test message for sealed box")
- token := base64.URLEncoding.EncodeToString(message)
- publicKey := base64.StdEncoding.EncodeToString(recipientPublicKey[:])
-
- encrypted, err := GetEncryptedTokenNative(token, publicKey)
- require.NoError(t, err)
-
- encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)
- require.NoError(t, err)
-
- decrypted, err := openSealedBox(encryptedBytes, recipientPublicKey, recipientPrivateKey)
- require.NoError(t, err)
- require.Equal(t, message, decrypted, "decrypted message should match original")
-}
diff --git a/server/pkg/utils/crypto/sealed_box_test.go b/server/pkg/utils/crypto/sealed_box_test.go
index 3d20040ce4..b539291b47 100644
--- a/server/pkg/utils/crypto/sealed_box_test.go
+++ b/server/pkg/utils/crypto/sealed_box_test.go
@@ -11,8 +11,28 @@ import (
"golang.org/x/crypto/nacl/box"
)
-func openSealedBox(sealed []byte, recipientPublicKey *[BoxPublicKeyBytes]byte, recipientPrivateKey *[BoxPublicKeyBytes]byte) ([]byte, error) {
- if len(sealed) < BoxPublicKeyBytes+16 {
+func TestSealedBoxRoundTrip(t *testing.T) {
+ publicKey, privateKey, err := box.GenerateKey(rand.Reader)
+ require.NoError(t, err)
+
+ message := []byte("test-token-12345")
+ sealedBase64, err := GetEncryptedToken(
+ base64.URLEncoding.EncodeToString(message),
+ base64.StdEncoding.EncodeToString(publicKey[:]),
+ )
+ require.NoError(t, err)
+
+ sealed, err := base64.StdEncoding.DecodeString(sealedBase64)
+ require.NoError(t, err)
+ require.Len(t, sealed, BoxPublicKeyBytes+box.Overhead+len(message))
+
+ decrypted, err := openSealedBox(sealed, publicKey, privateKey)
+ require.NoError(t, err)
+ require.Equal(t, message, decrypted)
+}
+
+func openSealedBox(sealed []byte, publicKey, privateKey *[BoxPublicKeyBytes]byte) ([]byte, error) {
+ if len(sealed) < BoxPublicKeyBytes+box.Overhead {
return nil, errors.New("invalid sealed box length")
}
@@ -21,7 +41,7 @@ func openSealedBox(sealed []byte, recipientPublicKey *[BoxPublicKeyBytes]byte, r
nonceInput := make([]byte, BoxPublicKeyBytes*2)
copy(nonceInput[:BoxPublicKeyBytes], ephemeralPublicKey[:])
- copy(nonceInput[BoxPublicKeyBytes:], recipientPublicKey[:])
+ copy(nonceInput[BoxPublicKeyBytes:], publicKey[:])
hash, err := blake2b.New(SecretBoxNonceBytes, nil)
if err != nil {
@@ -32,49 +52,9 @@ func openSealedBox(sealed []byte, recipientPublicKey *[BoxPublicKeyBytes]byte, r
var nonce [SecretBoxNonceBytes]byte
copy(nonce[:], hash.Sum(nil))
- decrypted, ok := box.Open(nil, sealed[BoxPublicKeyBytes:], &nonce, &ephemeralPublicKey, recipientPrivateKey)
+ decrypted, ok := box.Open(nil, sealed[BoxPublicKeyBytes:], &nonce, &ephemeralPublicKey, privateKey)
if !ok {
return nil, errors.New("failed to open sealed box")
}
return decrypted, nil
}
-
-func TestSealedBoxCompatibility(t *testing.T) {
- recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)
- require.NoError(t, err, "should generate keypair")
-
- tokenBytes := []byte("test-token-12345")
- publicKeyBase64 := base64.StdEncoding.EncodeToString(recipientPublicKey[:])
- tokenBase64 := base64.URLEncoding.EncodeToString(tokenBytes)
-
- tests := []struct {
- name string
- encryptFn func(token, publicKey string) (string, error)
- }{
- {
- name: "compat_wrapper",
- encryptFn: GetEncryptedToken,
- },
- {
- name: "native",
- encryptFn: GetEncryptedTokenNative,
- },
- }
-
- for _, tc := range tests {
- t.Run(tc.name, func(t *testing.T) {
- encrypted, err := tc.encryptFn(tokenBase64, publicKeyBase64)
- require.NoError(t, err, "sealed-box encryption should succeed")
-
- encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)
- require.NoError(t, err)
-
- expectedLen := BoxPublicKeyBytes + 16 + len(tokenBytes)
- require.Equal(t, expectedLen, len(encryptedBytes), "sealed box should have correct length")
-
- decrypted, err := openSealedBox(encryptedBytes, recipientPublicKey, recipientPrivateKey)
- require.NoError(t, err, "sealed box should decrypt with recipient keypair")
- require.Equal(t, tokenBytes, decrypted, "decrypted bytes should match original")
- })
- }
-}