π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[server] Remove libsodium dependency
Neeraj Guptadc31417cc778
diff --git a/server/Dockerfile b/server/Dockerfileindex 8a3ee192c3..dc1306c20f 100644--- a/server/Dockerfile+++ b/server/Dockerfile@@ -1,5 +1,5 @@FROM golang:1.23.4-alpine3.21 AS builder-RUN apk add --no-cache gcc musl-dev git build-base pkgconfig libsodium-dev+RUN apk add --no-cache gcc musl-dev git build-base pkgconfigENV GOOS=linux@@ -14,7 +14,6 @@ RUN --mount=type=cache,target=/root/.cache/go-build \go build -o museum cmd/museum/main.goFROM alpine:3.21-COPY --from=builder /usr/lib/libsodium.so* /usr/libCOPY --from=builder /etc/ente/museum .COPY configurations configurationsCOPY migrations migrationsdiff --git a/server/RUNNING.md b/server/RUNNING.mdindex 3ce49230b4..226ae5c6ef 100644--- a/server/RUNNING.md+++ b/server/RUNNING.md@@ -132,7 +132,6 @@ brew install go```shbrew install postgresql@15-brew install libsodiumbrew install pkg-config```diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 092f325a4c..7d8efb523f 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -35,7 +35,6 @@ import ("github.com/ente-io/museum/pkg/controller/offer""github.com/ente-io/museum/pkg/controller/usercache"- "github.com/GoKillers/libsodium-go/sodium""github.com/dlmiddlecote/sqlstats""github.com/ente-io/museum/ente/jwt""github.com/ente-io/museum/pkg/api"@@ -131,8 +130,6 @@ func main() {db := setupDatabase()defer db.Close()- sodium.Init()-hostName, err := os.Hostname()if err != nil {log.Fatal("Could not get host name", err)diff --git a/server/go.mod b/server/go.modindex 5e49388ff1..cee0224634 100644--- a/server/go.mod+++ b/server/go.mod@@ -6,7 +6,6 @@ toolchain go1.23.3require (firebase.google.com/go v3.13.0+incompatible- github.com/GoKillers/libsodium-go v0.0.0-20171022220152-dd733721c3cbgithub.com/TwiN/go-away v1.6.13github.com/avct/uasurfer v0.0.0-20191028135549-26b5daa857f1github.com/awa/go-iap v1.3.16diff --git a/server/go.sum b/server/go.sumindex e7d4ef4dc1..d30ce3607a 100644--- a/server/go.sum+++ b/server/go.sum@@ -61,8 +61,6 @@ github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQgithub.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=github.com/ClickHouse/clickhouse-go v1.3.12/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI=-github.com/GoKillers/libsodium-go v0.0.0-20171022220152-dd733721c3cb h1:ilqSFSbR1fq6x88heeHrvAqlg+ES+tZk2ZcaCmiH1gI=-github.com/GoKillers/libsodium-go v0.0.0-20171022220152-dd733721c3cb/go.mod h1:72TQeEkiDH9QMXZa5nJJvZre0UjqqO67X2QEIoOwCRU=github.com/Microsoft/go-winio v0.4.11/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU=github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA=diff --git a/server/pkg/utils/crypto/crypto.go b/server/pkg/utils/crypto/crypto.goindex d89929547c..d07157634b 100644--- a/server/pkg/utils/crypto/crypto.go+++ b/server/pkg/utils/crypto/crypto.go@@ -1,15 +1,7 @@package cryptoimport (- "encoding/base64"- "github.com/sirupsen/logrus"-- "github.com/GoKillers/libsodium-go/cryptobox"- generichash "github.com/GoKillers/libsodium-go/cryptogenerichash"- cryptosecretbox "github.com/GoKillers/libsodium-go/cryptosecretbox""github.com/ente-io/museum/ente"- "github.com/ente-io/museum/pkg/utils/auth"- "github.com/ente-io/stacktrace")// Exported constants matching libsodium@@ -21,86 +13,21 @@ const ()func Encrypt(data string, encryptionKey []byte) (ente.EncryptionResult, error) {- if SecretBoxNonceBytes != cryptosecretbox.CryptoSecretBoxNonceBytes() {- return ente.EncryptionResult{}, stacktrace.NewError("SecretBoxNonceBytes constant does not match the actual nonce size")- }- nonce, err := auth.GenerateRandomBytes(SecretBoxNonceBytes)- if err != nil {- return ente.EncryptionResult{}, stacktrace.Propagate(err, "")- }- return encryptWithNonce(data, encryptionKey, nonce)+ return EncryptNative(data, encryptionKey)}func encryptWithNonce(data string, encryptionKey []byte, nonce []byte) (ente.EncryptionResult, error) {- encryptedEmailBytes, errCode := cryptosecretbox.CryptoSecretBoxEasy([]byte(data), nonce, encryptionKey)- if errCode != 0 {- return ente.EncryptionResult{}, stacktrace.NewError("encryption failed")- }- nativeEnc, err := encryptWithNonceNative(data, encryptionKey, nonce)- if err != nil {- logrus.WithField("op", "crypto_compare").WithError(err).Error("native encryption failed")- return ente.EncryptionResult{}, stacktrace.Propagate(err, "native encryption failed")- }- if nativeEnc.Cipher == nil {- return ente.EncryptionResult{}, stacktrace.NewError("native encryption returned nil cipher")- }- if base64.StdEncoding.EncodeToString(nativeEnc.Cipher) != base64.StdEncoding.EncodeToString(encryptedEmailBytes) ||- base64.StdEncoding.EncodeToString(nativeEnc.Nonce) != base64.StdEncoding.EncodeToString(nonce) {- logrus.WithField("op", "crypto_compare").Error("encryption mismatch between libsodium and native implementation")- return ente.EncryptionResult{}, stacktrace.NewError("encryption mismatch nonce or cipher not same")- }- return nativeEnc, nil+ return encryptWithNonceNative(data, encryptionKey, nonce)}func Decrypt(cipher []byte, key []byte, nonce []byte) (string, error) {- decryptedBytes, err := cryptosecretbox.CryptoSecretBoxOpenEasy(cipher, nonce, key)- if err != 0 {- return "", stacktrace.NewError("email decryption failed")- }- result := string(decryptedBytes)- nativeResult, nativeErr := DecryptNative(cipher, key, nonce)- if nativeErr != nil {- logrus.WithField("op", "crypto_compare").WithError(nativeErr).Error("native decryption failed")- return "", stacktrace.Propagate(nativeErr, "native decryption failed")- } else if nativeResult != result {- logrus.WithField("op", "crypto_compare").Error("decryption mismatch between libsodium and native implementation")- return "", stacktrace.NewError("decryption mismatch")- }- return nativeResult, nil+ return DecryptNative(cipher, key, nonce)}func GetHash(data string, hashKey []byte) (string, error) {- if GenericHashBytes != generichash.CryptoGenericHashBytes() {- return "", stacktrace.NewError("GenericHashBytes constant does not match the actual hash size")- }- dataHashBytes, err := generichash.CryptoGenericHash(GenericHashBytes, []byte(data), hashKey)- if err != 0 {- return "", stacktrace.NewError("email hash failed")- }- result := base64.StdEncoding.EncodeToString(dataHashBytes)- nativeResult, nativeErr := GetHashNative(data, hashKey)- if nativeErr != nil {- logrus.WithField("op", "crypto_compare").WithError(nativeErr).Error("native hash failed")- return "", stacktrace.Propagate(nativeErr, "native hash failed")- } else if nativeResult != result {- logrus.WithField("op", "crypto_compare").Error("hash mismatch between libsodium and native implementation")- return "", stacktrace.NewError("hash mismatch")- }- return nativeResult, nil+ return GetHashNative(data, hashKey)}func GetEncryptedToken(token string, publicKey string) (string, error) {- publicKeyBytes, err := base64.StdEncoding.DecodeString(publicKey)- if err != nil {- return "", stacktrace.Propagate(err, "")- }- tokenBytes, err := base64.URLEncoding.DecodeString(token)- if err != nil {- return "", stacktrace.Propagate(err, "")- }- encryptedTokenBytes, errCode := cryptobox.CryptoBoxSeal(tokenBytes, publicKeyBytes)- if errCode != 0 {- return "", stacktrace.NewError("token encryption failed")- }- return base64.StdEncoding.EncodeToString(encryptedTokenBytes), nil+ return GetEncryptedTokenNative(token, publicKey)}diff --git a/server/pkg/utils/crypto/crypto_bench_test.go b/server/pkg/utils/crypto/crypto_bench_test.goindex 90fbacca05..b50b1f5cc3 100644--- a/server/pkg/utils/crypto/crypto_bench_test.go+++ b/server/pkg/utils/crypto/crypto_bench_test.go@@ -7,11 +7,6 @@ import ("github.com/ente-io/museum/ente")-func init() {- // Initialize libsodium for benchmarks- InitSodiumForTest()-}-// Benchmark encryption operationsfunc BenchmarkEncryptLibsodium(b *testing.B) {@@ -38,10 +33,10 @@ func benchmarkEncrypt(b *testing.B, encryptFunc func(string, []byte) (ente.Encryb.Run(size.name, func(b *testing.B) {data := generateLargeText(size.size)key := generateTestKey()-+b.SetBytes(int64(size.size))b.ResetTimer()-+for i := 0; i < b.N; i++ {_, err := encryptFunc(data, key)if err != nil {@@ -62,10 +57,10 @@ func BenchmarkDecryptNative(b *testing.B) {benchmarkDecrypt(b, EncryptNative, DecryptNative)}-func benchmarkDecrypt(b *testing.B,+func benchmarkDecrypt(b *testing.B,encryptFunc func(string, []byte) (ente.EncryptionResult, error),decryptFunc func([]byte, []byte, []byte) (string, error)) {-+sizes := []struct {name stringsize int@@ -81,19 +76,19 @@ func benchmarkDecrypt(b *testing.B,b.Run(size.name, func(b *testing.B) {data := generateLargeText(size.size)key := generateTestKey()-+// Encrypt once for benchmarkencResult, err := encryptFunc(data, key)if err != nil {b.Fatal(err)}-+cipher := encResult.Ciphernonce := encResult.Nonce-+b.SetBytes(int64(size.size))b.ResetTimer()-+for i := 0; i < b.N; i++ {_, err := decryptFunc(cipher, key, nonce)if err != nil {@@ -129,10 +124,10 @@ func benchmarkHash(b *testing.B, hashFunc func(string, []byte) (string, error))for _, size := range sizes {b.Run(size.name, func(b *testing.B) {data := generateLargeText(size.size)-+b.SetBytes(int64(size.size))b.ResetTimer()-+for i := 0; i < b.N; i++ {_, err := hashFunc(data, nil)if err != nil {@@ -160,7 +155,7 @@ func benchmarkGetEncryptedToken(b *testing.B, tokenFunc func(string, string) (stpublicKey[i] = byte(i * 3)}publicKeyB64 := base64.StdEncoding.EncodeToString(publicKey)-+sizes := []struct {name stringsize int@@ -174,10 +169,10 @@ func benchmarkGetEncryptedToken(b *testing.B, tokenFunc func(string, string) (stb.Run(size.name, func(b *testing.B) {tokenData := generateLargeText(size.size)token := base64.URLEncoding.EncodeToString([]byte(tokenData))-+b.SetBytes(int64(size.size))b.ResetTimer()-+for i := 0; i < b.N; i++ {_, err := tokenFunc(token, publicKeyB64)if err != nil {@@ -201,7 +196,7 @@ func BenchmarkFullCycleNative(b *testing.B) {func benchmarkFullCycle(b *testing.B,encryptFunc func(string, []byte) (ente.EncryptionResult, error),decryptFunc func([]byte, []byte, []byte) (string, error)) {-+sizes := []struct {name stringsize int@@ -216,19 +211,19 @@ func benchmarkFullCycle(b *testing.B,b.Run(size.name, func(b *testing.B) {data := generateLargeText(size.size)key := generateTestKey()-+b.SetBytes(int64(size.size * 2)) // Count both encrypt and decryptb.ResetTimer()-+for i := 0; i < b.N; i++ {encResult, err := encryptFunc(data, key)if err != nil {b.Fatal(err)}-+cipher := encResult.Ciphernonce := encResult.Nonce-+_, err = decryptFunc(cipher, key, nonce)if err != nil {b.Fatal(err)@@ -244,7 +239,7 @@ func BenchmarkMemoryAllocLibsodium(b *testing.B) {b.ReportAllocs()data := generateLargeText(1024)key := generateTestKey()-+for i := 0; i < b.N; i++ {_, _ = Encrypt(data, key)}@@ -254,7 +249,7 @@ func BenchmarkMemoryAllocNative(b *testing.B) {b.ReportAllocs()data := generateLargeText(1024)key := generateTestKey()-+for i := 0; i < b.N; i++ {_, _ = EncryptNative(data, key)}@@ -265,7 +260,7 @@ func BenchmarkMemoryAllocNative(b *testing.B) {func BenchmarkParallelEncryptLibsodium(b *testing.B) {data := generateLargeText(1024)key := generateTestKey()-+b.RunParallel(func(pb *testing.PB) {for pb.Next() {_, _ = Encrypt(data, key)@@ -276,11 +271,10 @@ func BenchmarkParallelEncryptLibsodium(b *testing.B) {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_test.go b/server/pkg/utils/crypto/crypto_test.goindex 71a8f0aa3a..43ce3b19f1 100644--- a/server/pkg/utils/crypto/crypto_test.go+++ b/server/pkg/utils/crypto/crypto_test.go@@ -10,11 +10,6 @@ import ("golang.org/x/crypto/nacl/box")-func init() {- // Initialize libsodium- InitSodiumForTest()-}-func TestEncryptWithSameNonce(t *testing.T) {// Test that both implementations produce identical output with the same noncedata := "Hello, World!"diff --git a/server/pkg/utils/crypto/sealed_box_deep_test.go b/server/pkg/utils/crypto/sealed_box_deep_test.goindex 1d03a2ff85..7ba730183b 100644--- a/server/pkg/utils/crypto/sealed_box_deep_test.go+++ b/server/pkg/utils/crypto/sealed_box_deep_test.go@@ -3,107 +3,74 @@ package cryptoimport ("crypto/rand""encoding/base64"- "encoding/hex""testing"- "github.com/GoKillers/libsodium-go/cryptobox"- generichash "github.com/GoKillers/libsodium-go/cryptogenerichash""github.com/stretchr/testify/require""golang.org/x/crypto/blake2b""golang.org/x/crypto/nacl/box")-func TestNonceDerivationInDetail(t *testing.T) {- // Initialize libsodium- InitSodiumForTest()+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+}- // Generate a test keypair+func TestNonceDerivationInDetail(t *testing.T) {recipientPublicKey, _, err := box.GenerateKey(rand.Reader)require.NoError(t, err)- // Generate ephemeral keypairephemeralPublicKey, _, err := box.GenerateKey(rand.Reader)require.NoError(t, err)- t.Run("test_libsodium_nonce_derivation", func(t *testing.T) {- // According to libsodium source, crypto_box_seal derives nonce as:- // crypto_generichash(nonce, 24, ephemeral_pk || recipient_pk, 64, NULL, 0)- // This is an UNKEYED hash of the concatenated public keys-- // Method 1: What our native code currently does (unkeyed hash)- nonceInput := make([]byte, 64)- copy(nonceInput[:32], ephemeralPublicKey[:])- copy(nonceInput[32:], recipientPublicKey[:])-- hash1, err := blake2b.New(24, nil) // unkeyed+ t.Run("unkeyed_blake2b_derivation_is_deterministic", func(t *testing.T) {+ nonce1, err := deriveSealedBoxNonce(ephemeralPublicKey, recipientPublicKey)require.NoError(t, err)- hash1.Write(nonceInput)- nonce1 := hash1.Sum(nil)- // Method 2: What the comment suggests (keyed hash - INCORRECT)- // crypto_generichash(nonce, 24, recipient_pk, 32, ephemeral_pk, 32)- // This would be recipient_pk as message, ephemeral_pk as key- hash2, err := blake2b.New(24, ephemeralPublicKey[:])+ nonce2, err := deriveSealedBoxNonce(ephemeralPublicKey, recipientPublicKey)require.NoError(t, err)- hash2.Write(recipientPublicKey[:])- nonce2 := hash2.Sum(nil)-- // Method 3: Using libsodium's generic hash to verify- // This should match Method 1 if our understanding is correct- nonce3, errCode := generichash.CryptoGenericHash(24, nonceInput, nil)- require.Equal(t, 0, errCode)- t.Logf("Method 1 (native - unkeyed): %s", hex.EncodeToString(nonce1))- t.Logf("Method 2 (keyed - wrong): %s", hex.EncodeToString(nonce2))- t.Logf("Method 3 (libsodium): %s", hex.EncodeToString(nonce3))-- // The correct implementation should match libsodium- require.Equal(t, nonce3, nonce1, "Native implementation should match libsodium's nonce derivation")- require.NotEqual(t, nonce2, nonce3, "Keyed hash should NOT match (proving the comment is incorrect)")+ require.Equal(t, nonce1, nonce2, "nonce derivation must be deterministic for same inputs")})- t.Run("actual_interop_test", func(t *testing.T) {- // Let's do a real interop test with fixed keys to be absolutely sure- // Generate a fixed recipient keypair for reproducible testing- var fixedRecipientPubKey [32]byte- var fixedRecipientPrivKey [32]byte- for i := range fixedRecipientPubKey {- fixedRecipientPubKey[i] = byte(i)- fixedRecipientPrivKey[i] = byte(255 - i)- }-- // Actually generate a valid keypair- realPubKey, realPrivKey, err := box.GenerateKey(rand.Reader)+ t.Run("keyed_blake2b_derivation_is_different", func(t *testing.T) {+ expectedNonce, err := deriveSealedBoxNonce(ephemeralPublicKey, recipientPublicKey)require.NoError(t, err)- message := []byte("test message for sealed box")+ keyedHash, err := blake2b.New(SecretBoxNonceBytes, ephemeralPublicKey[:])+ require.NoError(t, err)+ keyedHash.Write(recipientPublicKey[:])- // Encrypt with libsodium- sealed, errCode := cryptobox.CryptoBoxSeal(message, realPubKey[:])- require.Equal(t, 0, errCode, "libsodium seal should work")+ keyedNonce := keyedHash.Sum(nil)+ require.NotEqual(t, expectedNonce[:], keyedNonce, "keyed derivation must not match sealed-box nonce")+ })+}- // Decrypt with libsodium to verify it works- unsealed, errCode := cryptobox.CryptoBoxSealOpen(sealed, realPubKey[:], realPrivKey[:])- require.Equal(t, 0, errCode, "libsodium unseal should work")- require.Equal(t, message, unsealed, "round trip should work")+func TestNativeSealedBoxRoundTrip(t *testing.T) {+ recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err)- // Now test with our functions- token := base64.URLEncoding.EncodeToString(message)- pubKeyB64 := base64.StdEncoding.EncodeToString(realPubKey[:])+ message := []byte("test message for sealed box")+ token := base64.URLEncoding.EncodeToString(message)+ publicKey := base64.StdEncoding.EncodeToString(recipientPublicKey[:])- encrypted, err := GetEncryptedTokenNative(token, pubKeyB64)- require.NoError(t, err)+ encrypted, err := GetEncryptedTokenNative(token, publicKey)+ require.NoError(t, err)- encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)- require.NoError(t, err)+ encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)+ require.NoError(t, err)- // Try to decrypt with libsodium- decrypted, errCode := cryptobox.CryptoBoxSealOpen(encryptedBytes, realPubKey[:], realPrivKey[:])- if errCode != 0 {- t.Errorf("FAILED: libsodium cannot decrypt native sealed box")- } else {- require.Equal(t, message, decrypted, "Decryption should produce original message")- t.Log("SUCCESS: Native sealed box is compatible with libsodium")- }- })-}\ No newline at end of file+ 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.goindex 6c647d2828..3d20040ce4 100644--- a/server/pkg/utils/crypto/sealed_box_test.go+++ b/server/pkg/utils/crypto/sealed_box_test.go@@ -3,72 +3,78 @@ package cryptoimport ("crypto/rand""encoding/base64"+ "errors""testing"- "github.com/GoKillers/libsodium-go/cryptobox""github.com/stretchr/testify/require"+ "golang.org/x/crypto/blake2b""golang.org/x/crypto/nacl/box")-func TestSealedBoxCompatibility(t *testing.T) {- // Initialize libsodium- InitSodiumForTest()+func openSealedBox(sealed []byte, recipientPublicKey *[BoxPublicKeyBytes]byte, recipientPrivateKey *[BoxPublicKeyBytes]byte) ([]byte, error) {+ if len(sealed) < BoxPublicKeyBytes+16 {+ return nil, errors.New("invalid sealed box length")+ }- // Generate a test keypair for the recipient- recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)- require.NoError(t, err, "should generate keypair")+ var ephemeralPublicKey [BoxPublicKeyBytes]byte+ copy(ephemeralPublicKey[:], sealed[:BoxPublicKeyBytes])- // Prepare test data- originalToken := "test-token-12345"- tokenBytes := []byte(originalToken)- publicKeyBase64 := base64.StdEncoding.EncodeToString(recipientPublicKey[:])- tokenBase64 := base64.URLEncoding.EncodeToString(tokenBytes)+ nonceInput := make([]byte, BoxPublicKeyBytes*2)+ copy(nonceInput[:BoxPublicKeyBytes], ephemeralPublicKey[:])+ copy(nonceInput[BoxPublicKeyBytes:], recipientPublicKey[:])- t.Run("libsodium sealed box can be opened", func(t *testing.T) {- // Encrypt with libsodium's crypto_box_seal- encryptedLibsodium, errCode := cryptobox.CryptoBoxSeal(tokenBytes, recipientPublicKey[:])- require.Equal(t, 0, errCode, "libsodium encryption should succeed")+ hash, err := blake2b.New(SecretBoxNonceBytes, nil)+ if err != nil {+ return nil, err+ }+ hash.Write(nonceInput)- // Try to open with libsodium's crypto_box_seal_open- decrypted, errCode := cryptobox.CryptoBoxSealOpen(encryptedLibsodium, recipientPublicKey[:], recipientPrivateKey[:])- require.Equal(t, 0, errCode, "libsodium should decrypt its own sealed box")- require.Equal(t, tokenBytes, decrypted, "decrypted should match original")- })+ var nonce [SecretBoxNonceBytes]byte+ copy(nonce[:], hash.Sum(nil))- t.Run("compare GetEncryptedToken with GetEncryptedTokenNative", func(t *testing.T) {- // Encrypt with both implementations- encryptedLibsodium, err := GetEncryptedToken(tokenBase64, publicKeyBase64)- require.NoError(t, err, "libsodium GetEncryptedToken should succeed")+ decrypted, ok := box.Open(nil, sealed[BoxPublicKeyBytes:], &nonce, &ephemeralPublicKey, recipientPrivateKey)+ if !ok {+ return nil, errors.New("failed to open sealed box")+ }+ return decrypted, nil+}- encryptedNative, err := GetEncryptedTokenNative(tokenBase64, publicKeyBase64)- require.NoError(t, err, "native GetEncryptedTokenNative should succeed")+func TestSealedBoxCompatibility(t *testing.T) {+ recipientPublicKey, recipientPrivateKey, err := box.GenerateKey(rand.Reader)+ require.NoError(t, err, "should generate keypair")- // Decode the encrypted data- encryptedLibsodiumBytes, err := base64.StdEncoding.DecodeString(encryptedLibsodium)- require.NoError(t, err)+ tokenBytes := []byte("test-token-12345")+ publicKeyBase64 := base64.StdEncoding.EncodeToString(recipientPublicKey[:])+ tokenBase64 := base64.URLEncoding.EncodeToString(tokenBytes)- encryptedNativeBytes, err := base64.StdEncoding.DecodeString(encryptedNative)- require.NoError(t, err)+ tests := []struct {+ name string+ encryptFn func(token, publicKey string) (string, error)+ }{+ {+ name: "compat_wrapper",+ encryptFn: GetEncryptedToken,+ },+ {+ name: "native",+ encryptFn: GetEncryptedTokenNative,+ },+ }- // Both should be 48 bytes + len(tokenBytes) (32 bytes ephemeral pubkey + 16 bytes auth tag + message)- expectedLen := 32 + 16 + len(tokenBytes)- require.Equal(t, expectedLen, len(encryptedLibsodiumBytes), "libsodium sealed box should have correct length")- require.Equal(t, expectedLen, len(encryptedNativeBytes), "native sealed box should have correct length")+ 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")- // Try to decrypt libsodium's output with libsodium- decryptedLib, errCode := cryptobox.CryptoBoxSealOpen(encryptedLibsodiumBytes, recipientPublicKey[:], recipientPrivateKey[:])- require.Equal(t, 0, errCode, "libsodium should decrypt its own output")- require.Equal(t, tokenBytes, decryptedLib, "libsodium decrypted should match original")+ encryptedBytes, err := base64.StdEncoding.DecodeString(encrypted)+ require.NoError(t, err)- // CRITICAL TEST: Try to decrypt native's output with libsodium- decryptedNative, errCode := cryptobox.CryptoBoxSealOpen(encryptedNativeBytes, recipientPublicKey[:], recipientPrivateKey[:])- if errCode != 0 {- t.Errorf("COMPATIBILITY ISSUE: libsodium cannot decrypt native sealed box (error code: %d)", errCode)- t.Log("This confirms the nonce derivation is incompatible")- } else {- require.Equal(t, tokenBytes, decryptedNative, "cross-decryption should work if compatible")- t.Log("SUCCESS: Native implementation is compatible with libsodium")- }- })+ 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")+ })+ }}diff --git a/server/pkg/utils/crypto/test_init.go b/server/pkg/utils/crypto/test_init.godeleted file mode 100644index 6fe649b3dc..0000000000--- a/server/pkg/utils/crypto/test_init.go+++ /dev/null@@ -1,14 +0,0 @@-package crypto--import (- sodium "github.com/GoKillers/libsodium-go/sodium"- "sync"-)--var initOnce sync.Once--func InitSodiumForTest() {- initOnce.Do(func() {- sodium.Init()- })-}\ No newline at end of file