github.com/hashicorp/vault/sdk@v0.11.0/helper/roottoken/encode_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package roottoken
     5  
     6  import (
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  func TestTokenEncodingDecodingWithOTP(t *testing.T) {
    13  	otpTestCases := []struct {
    14  		token               string
    15  		name                string
    16  		otpLength           int
    17  		expectedEncodingErr string
    18  		expectedDecodingErr string
    19  	}{
    20  		{
    21  			token:               "someToken",
    22  			name:                "test token encoding with base64",
    23  			otpLength:           0,
    24  			expectedEncodingErr: "xor of root token failed: length of byte slices is not equivalent: 24 != 9",
    25  			expectedDecodingErr: "",
    26  		},
    27  		{
    28  			token:               "someToken",
    29  			name:                "test token encoding with base62",
    30  			otpLength:           len("someToken"),
    31  			expectedEncodingErr: "",
    32  			expectedDecodingErr: "",
    33  		},
    34  		{
    35  			token:               "someToken",
    36  			name:                "test token encoding with base62 - wrong otp length",
    37  			otpLength:           len("someToken") + 1,
    38  			expectedEncodingErr: "xor of root token failed: length of byte slices is not equivalent: 10 != 9",
    39  			expectedDecodingErr: "",
    40  		},
    41  		{
    42  			token:               "",
    43  			name:                "test no token to encode",
    44  			otpLength:           0,
    45  			expectedEncodingErr: "no token provided",
    46  			expectedDecodingErr: "",
    47  		},
    48  	}
    49  	for _, otpTestCase := range otpTestCases {
    50  		t.Run(otpTestCase.name, func(t *testing.T) {
    51  			otp, err := GenerateOTP(otpTestCase.otpLength)
    52  			if err != nil {
    53  				t.Fatal(err.Error())
    54  			}
    55  			encodedToken, err := EncodeToken(otpTestCase.token, otp)
    56  			if err != nil || otpTestCase.expectedDecodingErr != "" {
    57  				assert.EqualError(t, err, otpTestCase.expectedEncodingErr)
    58  				return
    59  			}
    60  			assert.NotEqual(t, otp, encodedToken)
    61  			assert.NotEqual(t, encodedToken, otpTestCase.token)
    62  			decodedToken, err := DecodeToken(encodedToken, otp, len(otp))
    63  			if err != nil || otpTestCase.expectedDecodingErr != "" {
    64  				assert.EqualError(t, err, otpTestCase.expectedDecodingErr)
    65  				return
    66  			}
    67  			assert.Equal(t, otpTestCase.token, decodedToken)
    68  		})
    69  	}
    70  }
    71  
    72  func TestTokenEncodingDecodingWithNoOTPorPGPKey(t *testing.T) {
    73  	_, err := EncodeToken("", "")
    74  	assert.EqualError(t, err, "no token provided")
    75  }