Skip to content

Commit

Permalink
test: add unit-tests for spiffe utils
Browse files Browse the repository at this point in the history
Signed-off-by: AhmedGrati <ahmedgrati1999@gmail.com>
  • Loading branch information
TessaIO committed Oct 31, 2023
1 parent b4317ec commit ef2093a
Showing 1 changed file with 105 additions and 0 deletions.
105 changes: 105 additions & 0 deletions pkg/utils/spiffe/spiffe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,108 @@ limitations under the License.
*/

package utils

import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
b64 "encoding/base64"
"testing"

"github.com/stretchr/testify/assert"
"sigs.k8s.io/node-feature-discovery/pkg/apis/nfd/v1alpha1"
)

func mockNFRSpec() v1alpha1.NodeFeatureSpec {
return v1alpha1.NodeFeatureSpec{
Features: v1alpha1.Features{
Flags: map[string]v1alpha1.FlagFeatureSet{
"test": {
Elements: map[string]v1alpha1.Nil{
"test2": {},
},
},
},
},
}
}

func mockWorkerECDSAPrivateKey() (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
privateKey, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
return privateKey, &privateKey.PublicKey
}

func mockWorkerRSAPrivateKey() (*rsa.PrivateKey, *rsa.PublicKey) {
privateKey, _ := rsa.GenerateKey(rand.Reader, 4096)
return privateKey, &privateKey.PublicKey
}

func TestVerify(t *testing.T) {
rsaPrivateKey, rsaPublicKey := mockWorkerRSAPrivateKey()
ecdsaPrivateKey, ecdsaPublicKey := mockWorkerECDSAPrivateKey()
spec := mockNFRSpec()

tc := []struct {
name string
privateKey crypto.Signer
publicKey crypto.PublicKey
wantErr bool
}{
{
name: "RSA Keys",
privateKey: rsaPrivateKey,
publicKey: rsaPublicKey,
wantErr: true,
},
{
name: "ECDSA Keys",
privateKey: ecdsaPrivateKey,
publicKey: ecdsaPublicKey,
wantErr: false,
},
}

for _, tt := range tc {
signedData, err := SignData(spec, tt.privateKey)
assert.NoError(t, err)

isVerified, err := VerifyDataSignature(spec, b64.StdEncoding.EncodeToString(signedData), tt.privateKey, tt.publicKey)
assert.NoError(t, err)
assert.True(t, isVerified)

signedData = append(signedData, "random"...)
isVerified, err = VerifyDataSignature(spec, b64.StdEncoding.EncodeToString(signedData), tt.privateKey, tt.publicKey)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.False(t, isVerified)
}
}
}

func TestSignData(t *testing.T) {
rsaPrivateKey, _ := mockWorkerRSAPrivateKey()
ecdsaPrivateKey, _ := mockWorkerECDSAPrivateKey()
spec := mockNFRSpec()

tc := []struct {
name string
privateKey crypto.Signer
}{
{
name: "RSA Keys",
privateKey: rsaPrivateKey,
},
{
name: "ECDSA Keys",
privateKey: ecdsaPrivateKey,
},
}

for _, tt := range tc {
_, err := SignData(spec, tt.privateKey)
assert.NoError(t, err)
}
}

0 comments on commit ef2093a

Please sign in to comment.