Skip to content

Commit

Permalink
updated per code review
Browse files Browse the repository at this point in the history
Signed-off-by: Patrick Zheng <[email protected]>
  • Loading branch information
Two-Hearts committed Oct 29, 2024
1 parent 3fa2921 commit 3ebd9c3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
7 changes: 2 additions & 5 deletions request.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,6 @@ import (
"github.com/notaryproject/tspclient-go/internal/oid"
)

// nonceGenerator generates nonce. Used for unit test
var nonceGenerator func() (*big.Int, error) = generateNonce

// MessageImprint contains the hash of the datum to be time-stamped.
//
// MessageImprint ::= SEQUENCE {
Expand Down Expand Up @@ -124,7 +121,7 @@ func NewRequest(opts RequestOptions) (*Request, error) {
if tspclientasn1.EqualRawValue(hashAlgParameter, asn1.RawValue{}) || tspclientasn1.EqualRawValue(hashAlgParameter, asn1.NullRawValue) {
hashAlgParameter = asn1NullRawValue
}
nonce, err := nonceGenerator()
nonce, err := generateNonce()
if err != nil {
return nil, &MalformedRequestError{Msg: err.Error()}
}
Expand Down Expand Up @@ -189,7 +186,7 @@ func generateNonce() (*big.Int, error) {
// Pick a random number from 0 to 2^159
nonce, err := rand.Int(rand.Reader, (&big.Int{}).Lsh(big.NewInt(1), 159))
if err != nil {
return nil, errors.New("error generating nonce")
return nil, errors.New("failed to generate nonce")
}
return nonce, nil
}
16 changes: 10 additions & 6 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ package tspclient

import (
"crypto"
"crypto/rand"
"crypto/x509/pkix"
"encoding/asn1"
"errors"
"fmt"
"math/big"
"reflect"
"testing"

Expand Down Expand Up @@ -73,9 +73,8 @@ func TestNewRequest(t *testing.T) {
t.Fatalf("expected %v, but got %v", asn1NullRawValue, req.MessageImprint.HashAlgorithm.Parameters)
}

nonceGenerator = func() (*big.Int, error) {
return nil, errors.New("failed to generate nonce")
}
defaultRandReader := rand.Reader
rand.Reader = &dummyRandReader{}
opts = RequestOptions{
Content: message,
HashAlgorithm: crypto.SHA256,
Expand All @@ -85,8 +84,7 @@ func TestNewRequest(t *testing.T) {
if err == nil || !errors.As(err, &malformedRequest) || err.Error() != expectedErrMsg {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, err)
}
// clean up
nonceGenerator = generateNonce
rand.Reader = defaultRandReader
}

func TestRequestMarshalBinary(t *testing.T) {
Expand Down Expand Up @@ -171,3 +169,9 @@ func TestValidateRequest(t *testing.T) {
t.Fatalf("expected error %s, but got %v", expectedErrMsg, err)
}
}

type dummyRandReader struct{}

func (r *dummyRandReader) Read(b []byte) (int, error) {
return 0, errors.New("failed to read")
}

0 comments on commit 3ebd9c3

Please sign in to comment.