github.com/jasoet/gopki@v1.15.0/encryption/encryption_test.go (about)

     1  package encryption
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/jasoet/gopki/keypair/algo"
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestDefaultEncryptOptions(t *testing.T) {
    12  	opts := DefaultEncryptOptions()
    13  
    14  	// Test default values using assert
    15  	assert.Equal(t, AlgorithmEnvelope, opts.Algorithm, "Expected default algorithm to be AlgorithmEnvelope")
    16  	assert.Equal(t, FormatCMS, opts.Format, "Expected default format to be FormatCMS")
    17  	assert.False(t, opts.IncludeCertificate, "Expected default IncludeCertificate to be false")
    18  	assert.Nil(t, opts.CertificateRecipients, "Expected default CertificateRecipients to be nil")
    19  	assert.Nil(t, opts.KDF, "Expected default KDF to be nil")
    20  	assert.NotNil(t, opts.Metadata, "Expected default Metadata to be initialized")
    21  	assert.Empty(t, opts.Metadata, "Expected default Metadata to be empty")
    22  }
    23  
    24  func TestDefaultDecryptOptions(t *testing.T) {
    25  	opts := DefaultDecryptOptions()
    26  
    27  	// Test default values using assert
    28  	assert.Empty(t, opts.ExpectedAlgorithm, "Expected default ExpectedAlgorithm to be empty")
    29  	assert.False(t, opts.VerifyTimestamp, "Expected default VerifyTimestamp to be false")
    30  	assert.Equal(t, 24*time.Hour, opts.MaxAge, "Expected default MaxAge to be 24 hours")
    31  	assert.True(t, opts.VerifyTime.IsZero(), "Expected default VerifyTime to be zero time")
    32  	assert.False(t, opts.SkipExpirationCheck, "Expected default SkipExpirationCheck to be false")
    33  	assert.NotNil(t, opts.ValidationOptions, "Expected default ValidationOptions to be initialized")
    34  	assert.Empty(t, opts.ValidationOptions, "Expected default ValidationOptions to be empty")
    35  }
    36  
    37  func TestGetAlgorithmForKeyType(t *testing.T) {
    38  	testCases := []struct {
    39  		keyType     string
    40  		expectedAlg Algorithm
    41  	}{
    42  		{"RSA", AlgorithmRSAOAEP},
    43  		{"ECDSA", AlgorithmECDH},
    44  		{"Ed25519", AlgorithmX25519},
    45  		{"Unknown", AlgorithmEnvelope},
    46  		{"", AlgorithmEnvelope},
    47  		{"lowercase-rsa", AlgorithmEnvelope},
    48  		{"random", AlgorithmEnvelope},
    49  	}
    50  
    51  	for _, tc := range testCases {
    52  		t.Run(tc.keyType, func(t *testing.T) {
    53  			result := GetAlgorithmForKeyType(tc.keyType)
    54  			assert.Equal(t, tc.expectedAlg, result, "For key type %s", tc.keyType)
    55  		})
    56  	}
    57  }
    58  
    59  func TestValidateEncryptOptions(t *testing.T) {
    60  	t.Run("ValidOptions", func(t *testing.T) {
    61  		validAlgorithms := []Algorithm{
    62  			AlgorithmRSAOAEP,
    63  			AlgorithmECDH,
    64  			AlgorithmX25519,
    65  			AlgorithmAESGCM,
    66  			AlgorithmEnvelope,
    67  		}
    68  
    69  		for _, alg := range validAlgorithms {
    70  			opts := EncryptOptions{
    71  				Algorithm: alg,
    72  				Format:    FormatCMS,
    73  			}
    74  
    75  			err := ValidateEncryptOptions(opts)
    76  			assert.NoError(t, err, "Valid options for algorithm %s should pass validation", alg)
    77  		}
    78  	})
    79  
    80  	t.Run("InvalidAlgorithm", func(t *testing.T) {
    81  		opts := EncryptOptions{
    82  			Algorithm: Algorithm("INVALID"),
    83  			Format:    FormatCMS,
    84  		}
    85  
    86  		err := ValidateEncryptOptions(opts)
    87  		assert.ErrorIs(t, err, ErrUnsupportedAlgorithm, "Should return ErrUnsupportedAlgorithm for invalid algorithm")
    88  	})
    89  
    90  	t.Run("InvalidFormat", func(t *testing.T) {
    91  		opts := EncryptOptions{
    92  			Algorithm: AlgorithmRSAOAEP,
    93  			Format:    Format("INVALID"),
    94  		}
    95  
    96  		err := ValidateEncryptOptions(opts)
    97  		assert.ErrorIs(t, err, ErrUnsupportedFormat, "Should return ErrUnsupportedFormat for invalid format")
    98  	})
    99  
   100  	t.Run("EmptyAlgorithm", func(t *testing.T) {
   101  		opts := EncryptOptions{
   102  			Algorithm: "",
   103  			Format:    FormatCMS,
   104  		}
   105  
   106  		err := ValidateEncryptOptions(opts)
   107  		if err != ErrUnsupportedAlgorithm {
   108  			t.Errorf("Expected ErrUnsupportedAlgorithm for empty algorithm, got: %v", err)
   109  		}
   110  	})
   111  
   112  	t.Run("EmptyFormat", func(t *testing.T) {
   113  		opts := EncryptOptions{
   114  			Algorithm: AlgorithmRSAOAEP,
   115  			Format:    "",
   116  		}
   117  
   118  		err := ValidateEncryptOptions(opts)
   119  		if err != ErrUnsupportedFormat {
   120  			t.Errorf("Expected ErrUnsupportedFormat for empty format, got: %v", err)
   121  		}
   122  	})
   123  }
   124  
   125  func TestValidateDecryptOptions(t *testing.T) {
   126  	t.Run("ValidOptions", func(t *testing.T) {
   127  		validOptions := []DecryptOptions{
   128  			{MaxAge: 0},
   129  			{MaxAge: time.Hour},
   130  			{MaxAge: 24 * time.Hour},
   131  			{MaxAge: 365 * 24 * time.Hour},
   132  		}
   133  
   134  		for i, opts := range validOptions {
   135  			err := ValidateDecryptOptions(opts)
   136  			if err != nil {
   137  				t.Errorf("Valid options case %d should pass validation, got error: %v", i, err)
   138  			}
   139  		}
   140  	})
   141  
   142  	t.Run("NegativeMaxAge", func(t *testing.T) {
   143  		opts := DecryptOptions{
   144  			MaxAge: -time.Hour,
   145  		}
   146  
   147  		err := ValidateDecryptOptions(opts)
   148  		if err != ErrInvalidParameters {
   149  			t.Errorf("Expected ErrInvalidParameters for negative MaxAge, got: %v", err)
   150  		}
   151  	})
   152  
   153  	t.Run("VeryNegativeMaxAge", func(t *testing.T) {
   154  		opts := DecryptOptions{
   155  			MaxAge: -365 * 24 * time.Hour,
   156  		}
   157  
   158  		err := ValidateDecryptOptions(opts)
   159  		if err != ErrInvalidParameters {
   160  			t.Errorf("Expected ErrInvalidParameters for very negative MaxAge, got: %v", err)
   161  		}
   162  	})
   163  }
   164  
   165  func TestEncodeData(t *testing.T) {
   166  	t.Run("NilData", func(t *testing.T) {
   167  		result, err := EncodeData(nil)
   168  		if err == nil {
   169  			t.Error("Expected error for nil data, got nil")
   170  		}
   171  		if result != nil {
   172  			t.Error("Expected nil result for nil data")
   173  		}
   174  		expectedMsg := "encrypted data is nil"
   175  		if err.Error() != expectedMsg {
   176  			t.Errorf("Expected error message '%s', got '%s'", expectedMsg, err.Error())
   177  		}
   178  	})
   179  
   180  	t.Run("ValidDataWithoutRecipients", func(t *testing.T) {
   181  		// This will test the path where EncodeToCMS is called but fails due to no recipients
   182  		encData := &EncryptedData{
   183  			Algorithm:  AlgorithmEnvelope,
   184  			Format:     FormatCMS,
   185  			Data:       []byte("test data"),
   186  			Recipients: nil, // No recipients - will cause EncodeToCMS to fail
   187  			Timestamp:  time.Now(),
   188  			Metadata:   make(map[string]any),
   189  		}
   190  
   191  		_, err := EncodeData(encData)
   192  		if err == nil {
   193  			t.Error("Expected error for data without recipients, got nil")
   194  		}
   195  		// The exact error message comes from EncodeToCMS
   196  		if err.Error() != "no recipients available for CMS envelope encryption" {
   197  			t.Errorf("Expected specific error message, got: %s", err.Error())
   198  		}
   199  	})
   200  }
   201  
   202  func TestDecodeDataWithKey(t *testing.T) {
   203  	t.Run("EmptyData", func(t *testing.T) {
   204  		// Generate a test key and certificate
   205  		rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   206  		if err != nil {
   207  			t.Fatalf("Failed to generate RSA key pair: %v", err)
   208  		}
   209  
   210  		cert := createTestCertificate(t, rsaKeys.PublicKey, rsaKeys.PrivateKey)
   211  
   212  		result, err := DecodeDataWithKey([]byte{}, cert, rsaKeys.PrivateKey)
   213  		if err == nil {
   214  			t.Error("Expected error for empty data, got nil")
   215  		}
   216  		if result != nil {
   217  			t.Error("Expected nil result for empty data")
   218  		}
   219  		expectedMsg := "data is empty"
   220  		if err.Error() != expectedMsg {
   221  			t.Errorf("Expected error message '%s', got '%s'", expectedMsg, err.Error())
   222  		}
   223  	})
   224  
   225  	t.Run("InvalidCMSData", func(t *testing.T) {
   226  		// Generate a test key and certificate
   227  		rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   228  		if err != nil {
   229  			t.Fatalf("Failed to generate RSA key pair: %v", err)
   230  		}
   231  
   232  		cert := createTestCertificate(t, rsaKeys.PublicKey, rsaKeys.PrivateKey)
   233  
   234  		// Pass invalid CMS data
   235  		invalidData := []byte("invalid cms data")
   236  		result, err := DecodeDataWithKey(invalidData, cert, rsaKeys.PrivateKey)
   237  		if err == nil {
   238  			t.Error("Expected error for invalid CMS data, got nil")
   239  		}
   240  		if result != nil {
   241  			t.Error("Expected nil result for invalid CMS data")
   242  		}
   243  		// The error should come from DecodeFromCMS (PKCS7 parsing)
   244  	})
   245  
   246  	t.Run("TypeSafety", func(t *testing.T) {
   247  		// This test ensures the generic constraint works at compile time
   248  		rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   249  		if err != nil {
   250  			t.Fatalf("Failed to generate RSA key pair: %v", err)
   251  		}
   252  
   253  		ecdsaKeys, err := algo.GenerateECDSAKeyPair(algo.P256)
   254  		if err != nil {
   255  			t.Fatalf("Failed to generate ECDSA key pair: %v", err)
   256  		}
   257  
   258  		cert := createTestCertificate(t, rsaKeys.PublicKey, rsaKeys.PrivateKey)
   259  		dummyData := []byte("dummy")
   260  
   261  		// These should compile with different private key types
   262  		_, _ = DecodeDataWithKey(dummyData, cert, rsaKeys.PrivateKey)   // *rsa.PrivateKey
   263  		_, _ = DecodeDataWithKey(dummyData, cert, ecdsaKeys.PrivateKey) // *ecdsa.PrivateKey
   264  
   265  		t.Log("Generic function accepts multiple private key types at compile time")
   266  	})
   267  }
   268  
   269  func TestValidateEncodedData(t *testing.T) {
   270  	t.Run("EmptyData", func(t *testing.T) {
   271  		err := ValidateEncodedData([]byte{})
   272  		if err == nil {
   273  			t.Error("Expected error for empty data, got nil")
   274  		}
   275  		// Error comes from ValidateCMS
   276  		expectedMsg := "CMS data is empty"
   277  		if err.Error() != expectedMsg {
   278  			t.Errorf("Expected error message '%s', got '%s'", expectedMsg, err.Error())
   279  		}
   280  	})
   281  
   282  	t.Run("InvalidData", func(t *testing.T) {
   283  		invalidData := []byte("invalid cms data")
   284  		err := ValidateEncodedData(invalidData)
   285  		if err == nil {
   286  			t.Error("Expected error for invalid data, got nil")
   287  		}
   288  		// Error comes from ValidateCMS which uses pkcs7.Parse
   289  	})
   290  }
   291  
   292  func TestEncryptionAlgorithmConstants(t *testing.T) {
   293  	// Test that algorithm constants have expected values
   294  	expectedAlgorithms := map[Algorithm]string{
   295  		AlgorithmRSAOAEP:  "RSA-OAEP",
   296  		AlgorithmECDH:     "ECDH",
   297  		AlgorithmX25519:   "X25519",
   298  		AlgorithmAESGCM:   "AES-GCM",
   299  		AlgorithmEnvelope: "Envelope",
   300  	}
   301  
   302  	for alg, expectedValue := range expectedAlgorithms {
   303  		if string(alg) != expectedValue {
   304  			t.Errorf("Algorithm constant %s has unexpected value: expected %s, got %s",
   305  				expectedValue, expectedValue, string(alg))
   306  		}
   307  	}
   308  }
   309  
   310  func TestEncryptionFormatConstants(t *testing.T) {
   311  	// Test that format constants have expected values
   312  	if string(FormatCMS) != "cms" {
   313  		t.Errorf("FormatCMS constant has unexpected value: expected 'cms', got '%s'", string(FormatCMS))
   314  	}
   315  }
   316  
   317  func TestErrorConstants(t *testing.T) {
   318  	// Test that error constants are properly defined
   319  	errors := []error{
   320  		ErrUnsupportedAlgorithm,
   321  		ErrUnsupportedFormat,
   322  		ErrInvalidKey,
   323  		ErrDecryptionFailed,
   324  		ErrDataTooLarge,
   325  		ErrInvalidRecipient,
   326  		ErrExpiredData,
   327  		ErrInvalidFormat,
   328  		ErrInvalidParameters,
   329  	}
   330  
   331  	for _, err := range errors {
   332  		if err == nil {
   333  			t.Error("Error constant should not be nil")
   334  		}
   335  		if err.Error() == "" {
   336  			t.Error("Error constant should have a non-empty message")
   337  		}
   338  	}
   339  }
   340  
   341  func TestEncryptedDataStructure(t *testing.T) {
   342  	// Test that EncryptedData struct can be created and used
   343  	now := time.Now()
   344  	metadata := make(map[string]any)
   345  	metadata["test"] = "value"
   346  
   347  	encData := &EncryptedData{
   348  		Algorithm:    AlgorithmRSAOAEP,
   349  		Format:       FormatCMS,
   350  		Data:         []byte("test data"),
   351  		EncryptedKey: []byte("encrypted key"),
   352  		IV:           []byte("initialization vector"),
   353  		Tag:          []byte("auth tag"),
   354  		KDF:          nil,
   355  		Recipients:   []*RecipientInfo{},
   356  		Timestamp:    now,
   357  		Metadata:     metadata,
   358  	}
   359  
   360  	// Verify all fields are accessible
   361  	if encData.Algorithm != AlgorithmRSAOAEP {
   362  		t.Error("Algorithm field not properly set")
   363  	}
   364  	if encData.Format != FormatCMS {
   365  		t.Error("Format field not properly set")
   366  	}
   367  	if string(encData.Data) != "test data" {
   368  		t.Error("Data field not properly set")
   369  	}
   370  	if !encData.Timestamp.Equal(now) {
   371  		t.Error("Timestamp field not properly set")
   372  	}
   373  	if encData.Metadata["test"] != "value" {
   374  		t.Error("Metadata field not properly set")
   375  	}
   376  }
   377  
   378  func TestRecipientInfoStructure(t *testing.T) {
   379  	// Test that RecipientInfo struct can be created and used
   380  	rsaKeys, err := algo.GenerateRSAKeyPair(algo.KeySize2048)
   381  	if err != nil {
   382  		t.Fatalf("Failed to generate RSA key pair: %v", err)
   383  	}
   384  
   385  	cert := createTestCertificate(t, rsaKeys.PublicKey, rsaKeys.PrivateKey)
   386  
   387  	recipInfo := &RecipientInfo{
   388  		Certificate:            cert,
   389  		KeyID:                  []byte("key-id"),
   390  		EncryptedKey:           []byte("encrypted key"),
   391  		KeyEncryptionAlgorithm: AlgorithmRSAOAEP,
   392  		EphemeralKey:           []byte("ephemeral key"),
   393  		KeyIV:                  []byte("key iv"),
   394  		KeyTag:                 []byte("key tag"),
   395  	}
   396  
   397  	// Verify all fields are accessible
   398  	if recipInfo.Certificate != cert {
   399  		t.Error("Certificate field not properly set")
   400  	}
   401  	if string(recipInfo.KeyID) != "key-id" {
   402  		t.Error("KeyID field not properly set")
   403  	}
   404  	if recipInfo.KeyEncryptionAlgorithm != AlgorithmRSAOAEP {
   405  		t.Error("KeyEncryptionAlgorithm field not properly set")
   406  	}
   407  }
   408  
   409  func TestKDFParamsStructure(t *testing.T) {
   410  	// Test that KDFParams struct can be created and used
   411  	params := make(map[string]any)
   412  	params["test"] = "value"
   413  
   414  	kdfParams := &KDFParams{
   415  		Algorithm:  "PBKDF2",
   416  		Salt:       []byte("salt"),
   417  		Iterations: 10000,
   418  		KeyLength:  32,
   419  		Params:     params,
   420  	}
   421  
   422  	// Verify all fields are accessible
   423  	if kdfParams.Algorithm != "PBKDF2" {
   424  		t.Error("Algorithm field not properly set")
   425  	}
   426  	if string(kdfParams.Salt) != "salt" {
   427  		t.Error("Salt field not properly set")
   428  	}
   429  	if kdfParams.Iterations != 10000 {
   430  		t.Error("Iterations field not properly set")
   431  	}
   432  	if kdfParams.KeyLength != 32 {
   433  		t.Error("KeyLength field not properly set")
   434  	}
   435  	if kdfParams.Params["test"] != "value" {
   436  		t.Error("Params field not properly set")
   437  	}
   438  }
   439  
   440  // Note: createTestCertificate function is defined in cms_generic_test.go