From 84054cd9dc9acc218e0fd5012e71557c6709d19a Mon Sep 17 00:00:00 2001 From: Binbin Li Date: Tue, 13 Sep 2022 02:25:09 +0000 Subject: [PATCH] refactor: address comments Signed-off-by: Binbin Li --- signature/algorithm.go | 9 ++-- signature/envelope.go | 34 +++++++------- signature/envelope_test.go | 41 ++++++++-------- signature/errors.go | 42 ++++++++--------- signature/errors_test.go | 40 ++++++++-------- signature/internal/base/envelope.go | 59 ++++++++++++++---------- signature/internal/base/envelope_test.go | 47 ++++++++++++------- signature/jws.go | 30 ++++++------ signature/jws_test.go | 24 +++++----- signature/jwt.go | 2 +- signature/signer.go | 26 ++--------- signature/types.go | 6 --- signature/utils.go | 2 +- 13 files changed, 185 insertions(+), 177 deletions(-) diff --git a/signature/algorithm.go b/signature/algorithm.go index 32ee7c17..4f106208 100644 --- a/signature/algorithm.go +++ b/signature/algorithm.go @@ -33,7 +33,10 @@ const ( // KeySpec defines a key type and size. type KeySpec struct { + // KeyType is the type of the key. Type KeyType + + // KeySize is the size of the key in bits. Size int } @@ -62,7 +65,7 @@ func ExtractKeySpec(signingCert *x509.Certificate) (KeySpec, error) { }, nil default: return KeySpec{}, &UnsupportedSigningKeyError{ - Msg: fmt.Sprintf("rsa key size %d is not supported", bitSize), + Msg: fmt.Sprintf("rsa key size %d bits is not supported", bitSize), } } case *ecdsa.PublicKey: @@ -74,12 +77,12 @@ func ExtractKeySpec(signingCert *x509.Certificate) (KeySpec, error) { }, nil default: return KeySpec{}, &UnsupportedSigningKeyError{ - Msg: fmt.Sprintf("ecdsa key size %d is not supported", bitSize), + Msg: fmt.Sprintf("ecdsa key size %d bits is not supported", bitSize), } } } return KeySpec{}, &UnsupportedSigningKeyError{ - Msg: "invalid public key type", + Msg: "unsupported public key type", } } diff --git a/signature/envelope.go b/signature/envelope.go index eb8ad2e7..89b58921 100644 --- a/signature/envelope.go +++ b/signature/envelope.go @@ -10,9 +10,12 @@ // local crypto library or the external signing plugin. package signature -import "fmt" +import ( + "fmt" + "sync" +) -// Envelope provides functions to basic functions to manipulate signatures. +// Envelope provides basic functions to manipulate signatures. type Envelope interface { // Sign generates and sign the envelope according to the sign request. Sign(req *SignRequest) ([]byte, error) @@ -41,7 +44,7 @@ type envelopeFunc struct { // envelopeFuncs maps envelope media type to corresponding constructors and // parsers. -var envelopeFuncs map[string]envelopeFunc +var envelopeFuncs sync.Map // RegisterEnvelopeType registers newFunc and parseFunc for the given mediaType. // Those functions are intended to be called when creating a new envelope. @@ -50,14 +53,10 @@ func RegisterEnvelopeType(mediaType string, newFunc NewEnvelopeFunc, parseFunc P if newFunc == nil || parseFunc == nil { return fmt.Errorf("required functions not provided") } - if envelopeFuncs == nil { - envelopeFuncs = make(map[string]envelopeFunc) - } - - envelopeFuncs[mediaType] = envelopeFunc{ + envelopeFuncs.Store(mediaType, envelopeFunc{ newFunc: newFunc, parseFunc: parseFunc, - } + }) return nil } @@ -65,28 +64,29 @@ func RegisterEnvelopeType(mediaType string, newFunc NewEnvelopeFunc, parseFunc P func RegisteredEnvelopeTypes() []string { var types []string - for envelopeType := range envelopeFuncs { - types = append(types, envelopeType) - } + envelopeFuncs.Range(func(k, v interface{}) bool { + types = append(types, k.(string)) + return true + }) return types } // NewEnvelope generates an envelope of given media type. func NewEnvelope(mediaType string) (Envelope, error) { - envelopeFunc, ok := envelopeFuncs[mediaType] + val, ok := envelopeFuncs.Load(mediaType) if !ok { return nil, &UnsupportedSignatureFormatError{MediaType: mediaType} } - return envelopeFunc.newFunc(), nil + return val.(envelopeFunc).newFunc(), nil } -// ParseEnvelope generates an envelope by given envelope bytes with specified +// ParseEnvelope generates an envelope for given envelope bytes with specified // media type. func ParseEnvelope(mediaType string, envelopeBytes []byte) (Envelope, error) { - envelopeFunc, ok := envelopeFuncs[mediaType] + val, ok := envelopeFuncs.Load(mediaType) if !ok { return nil, &UnsupportedSignatureFormatError{MediaType: mediaType} } - return envelopeFunc.parseFunc(envelopeBytes) + return val.(envelopeFunc).parseFunc(envelopeBytes) } diff --git a/signature/envelope_test.go b/signature/envelope_test.go index 8a6ef628..56ab5135 100644 --- a/signature/envelope_test.go +++ b/signature/envelope_test.go @@ -2,9 +2,22 @@ package signature import ( "reflect" + "sync" "testing" ) +var ( + emptyFuncs sync.Map + validFuncs sync.Map +) + +func init() { + validFuncs.Store(testMediaType, envelopeFunc{ + newFunc: testNewFunc, + parseFunc: testParseFunc, + }) +} + // mock an envelope that implements signature.Envelope. type testEnvelope struct { } @@ -78,19 +91,17 @@ func TestRegisterEnvelopeType(t *testing.T) { func TestRegisteredEnvelopeTypes(t *testing.T) { tests := []struct { name string - envelopeFuncs map[string]envelopeFunc + envelopeFuncs sync.Map expect []string }{ { name: "empty map", - envelopeFuncs: make(map[string]envelopeFunc), + envelopeFuncs: emptyFuncs, expect: nil, }, { name: "nonempty map", - envelopeFuncs: map[string]envelopeFunc{ - testMediaType: {}, - }, + envelopeFuncs: validFuncs, expect: []string{testMediaType}, }, } @@ -111,25 +122,21 @@ func TestNewEnvelope(t *testing.T) { tests := []struct { name string mediaType string - envelopeFuncs map[string]envelopeFunc + envelopeFuncs sync.Map expect Envelope expectErr bool }{ { name: "unsupported media type", mediaType: testMediaType, - envelopeFuncs: make(map[string]envelopeFunc), + envelopeFuncs: emptyFuncs, expect: nil, expectErr: true, }, { name: "valid media type", mediaType: testMediaType, - envelopeFuncs: map[string]envelopeFunc{ - testMediaType: { - newFunc: testNewFunc, - }, - }, + envelopeFuncs: validFuncs, expect: testEnvelope{}, expectErr: false, }, @@ -154,25 +161,21 @@ func TestParseEnvelope(t *testing.T) { tests := []struct { name string mediaType string - envelopeFuncs map[string]envelopeFunc + envelopeFuncs sync.Map expect Envelope expectErr bool }{ { name: "unsupported media type", mediaType: testMediaType, - envelopeFuncs: make(map[string]envelopeFunc), + envelopeFuncs: emptyFuncs, expect: nil, expectErr: true, }, { name: "valid media type", mediaType: testMediaType, - envelopeFuncs: map[string]envelopeFunc{ - testMediaType: { - parseFunc: testParseFunc, - }, - }, + envelopeFuncs: validFuncs, expect: testEnvelope{}, expectErr: false, }, diff --git a/signature/errors.go b/signature/errors.go index 2016c654..49d98dd4 100644 --- a/signature/errors.go +++ b/signature/errors.go @@ -18,17 +18,17 @@ func (e *SignatureIntegrityError) Unwrap() error { return e.Err } -// MalformedSignatureError is used when Signature envelope is malformed. -type MalformedSignatureError struct { +// InvalidSignatureError is used when Signature envelope is invalid. +type InvalidSignatureError struct { Msg string } // Error returns the error message or the default message if not provided. -func (e MalformedSignatureError) Error() string { +func (e InvalidSignatureError) Error() string { if e.Msg != "" { return e.Msg } - return "signature envelope format is malformed" + return "signature envelope format is invalid" } @@ -71,45 +71,45 @@ func (e UnsupportedSigningKeyError) Error() string { return "signing key is not supported" } -// MalformedArgumentError is used when an argument to a function is malformed. -type MalformedArgumentError struct { +// InvalidArgumentError is used when an argument to a function is invalid. +type InvalidArgumentError struct { Param string Err error } // Error returns the error message. -func (e *MalformedArgumentError) Error() string { +func (e *InvalidArgumentError) Error() string { if e.Err != nil { - return fmt.Sprintf("%q param is malformed. Error: %s", e.Param, e.Err.Error()) + return fmt.Sprintf("%q param is invalid. Error: %s", e.Param, e.Err.Error()) } - return fmt.Sprintf("%q param is malformed", e.Param) + return fmt.Sprintf("%q param is invalid", e.Param) } // Unwrap returns the unwrapped error -func (e *MalformedArgumentError) Unwrap() error { +func (e *InvalidArgumentError) Unwrap() error { return e.Err } -// MalformedSignRequestError is used when SignRequest is malformed. -type MalformedSignRequestError struct { +// InvalidSignRequestError is used when SignRequest is invalid. +type InvalidSignRequestError struct { Msg string } // Error returns the error message or the default message if not provided. -func (e *MalformedSignRequestError) Error() string { +func (e *InvalidSignRequestError) Error() string { if e.Msg != "" { return e.Msg } - return "SignRequest is malformed" + return "SignRequest is invalid" } -// SignatureAlgoNotSupportedError is used when signing algo is not supported. -type SignatureAlgoNotSupportedError struct { +// UnsupportedSignatureAlgoError is used when signing algo is not supported. +type UnsupportedSignatureAlgoError struct { Alg string } // Error returns the formatted error message. -func (e *SignatureAlgoNotSupportedError) Error() string { +func (e *UnsupportedSignatureAlgoError) Error() string { return fmt.Sprintf("signature algorithm %q is not supported", e.Alg) } @@ -121,12 +121,12 @@ func (e *SignatureEnvelopeNotFoundError) Error() string { return "signature envelope is not present" } -// EnvelopeKeyRepeatedError is used when repeated key name found in the envelope. -type EnvelopeKeyRepeatedError struct { +// DuplicateKeyError is used when repeated key name found. +type DuplicateKeyError struct { Key string } // Error returns the formatted error message. -func (e *EnvelopeKeyRepeatedError) Error() string { - return fmt.Sprintf("repeated key: %q exists in the envelope.", e.Key) +func (e *DuplicateKeyError) Error() string { + return fmt.Sprintf("repeated key: %q exists.", e.Key) } diff --git a/signature/errors_test.go b/signature/errors_test.go index b4a55b3c..84cb20c1 100644 --- a/signature/errors_test.go +++ b/signature/errors_test.go @@ -28,21 +28,21 @@ func TestSignatureIntegrityError(t *testing.T) { } } -func TestMalformedSignatureError(t *testing.T) { +func TestInvalidSignatureError(t *testing.T) { tests := []struct { name string - err *MalformedSignatureError + err *InvalidSignatureError expect string }{ { name: "err msg set", - err: &MalformedSignatureError{Msg: errMsg}, + err: &InvalidSignatureError{Msg: errMsg}, expect: errMsg, }, { name: "err msg not set", - err: &MalformedSignatureError{}, - expect: "signature envelope format is malformed", + err: &InvalidSignatureError{}, + expect: "signature envelope format is invalid", }, } @@ -93,16 +93,16 @@ func TestUnsupportedSigningKeyError(t *testing.T) { } } -func TestMalformedArgumentError(t *testing.T) { - expectedMsg := "\"hola\" param is malformed" - validateErrorMsg(&MalformedArgumentError{Param: "hola"}, expectedMsg, t) +func TestInvalidArgumentError(t *testing.T) { + expectedMsg := "\"hola\" param is invalid" + validateErrorMsg(&InvalidArgumentError{Param: "hola"}, expectedMsg, t) - expectedMsg = "\"hola\" param is malformed. Error: se produjo un error" - validateErrorMsg(&MalformedArgumentError{Param: "hola", Err: fmt.Errorf("se produjo un error")}, expectedMsg, t) + expectedMsg = "\"hola\" param is invalid. Error: se produjo un error" + validateErrorMsg(&InvalidArgumentError{Param: "hola", Err: fmt.Errorf("se produjo un error")}, expectedMsg, t) } -func TestSignatureAlgoNotSupportedError(t *testing.T) { - err := &SignatureAlgoNotSupportedError{ +func TestUnsupportedSignatureAlgoError(t *testing.T) { + err := &UnsupportedSignatureAlgoError{ Alg: testAlg, } @@ -112,12 +112,12 @@ func TestSignatureAlgoNotSupportedError(t *testing.T) { } } -func TestMalformedSignRequestError(t *testing.T) { - expectedMsg := "SignRequest is malformed" - validateErrorMsg(&MalformedSignRequestError{}, expectedMsg, t) +func TestInvalidSignRequestError(t *testing.T) { + expectedMsg := "SignRequest is invalid" + validateErrorMsg(&InvalidSignRequestError{}, expectedMsg, t) expectedMsg = "Se produjo un error" - validateErrorMsg(&MalformedSignRequestError{Msg: expectedMsg}, expectedMsg, t) + validateErrorMsg(&InvalidSignRequestError{Msg: expectedMsg}, expectedMsg, t) } func validateErrorMsg(err error, expectedMsg string, t *testing.T) { @@ -127,8 +127,8 @@ func validateErrorMsg(err error, expectedMsg string, t *testing.T) { } } -func TestMalformedArgumentError_Unwrap(t *testing.T) { - err := &MalformedArgumentError{ +func TestInvalidArgumentError_Unwrap(t *testing.T) { + err := &InvalidArgumentError{ Param: testParam, Err: errors.New(errMsg), } @@ -157,8 +157,8 @@ func TestSignatureAuthenticityError(t *testing.T) { } func TestEnvelopeKeyRepeatedError(t *testing.T) { - err := &EnvelopeKeyRepeatedError{Key: errMsg} - expectMsg := fmt.Sprintf("repeated key: %q exists in the envelope.", errMsg) + err := &DuplicateKeyError{Key: errMsg} + expectMsg := fmt.Sprintf("repeated key: %q exists.", errMsg) if err.Error() != expectMsg { t.Errorf("Expected %v but got %v", expectMsg, err.Error()) diff --git a/signature/internal/base/envelope.go b/signature/internal/base/envelope.go index b035568e..29459290 100644 --- a/signature/internal/base/envelope.go +++ b/signature/internal/base/envelope.go @@ -62,7 +62,7 @@ func (e *Envelope) Sign(req *signature.SignRequest) ([]byte, error) { func (e *Envelope) Verify() (*signature.EnvelopeContent, error) { // validation before the core verify process. if len(e.Raw) == 0 { - return nil, &signature.MalformedSignatureError{} + return nil, &signature.SignatureNotFoundError{} } // core verify process. @@ -82,7 +82,7 @@ func (e *Envelope) Verify() (*signature.EnvelopeContent, error) { // Content returns the validated signature information and payload. func (e *Envelope) Content() (*signature.EnvelopeContent, error) { if len(e.Raw) == 0 { - return nil, &signature.MalformedSignatureError{Msg: "raw signature is empty"} + return nil, &signature.SignatureNotFoundError{} } content, err := e.Envelope.Content() @@ -103,18 +103,30 @@ func validateSignRequest(req *signature.SignRequest) error { return err } - if err := validateSigningTime(req.SigningTime, req.Expiry); err != nil { + if err := validateSigningAndExpiryTime(req.SigningTime, req.Expiry); err != nil { return err } if req.Signer == nil { - return &signature.MalformedSignatureError{Msg: "signer is nil"} + return &signature.InvalidSignRequestError{Msg: "signer is nil"} + } + + if err := validateSigningSchema(req.SigningScheme); err != nil { + return err } _, err := req.Signer.KeySpec() return err } +// validateSigningSchema validates the schema. +func validateSigningSchema(schema signature.SigningScheme) error { + if schema == "" { + return &signature.InvalidSignRequestError{Msg: "SigningScheme not present"} + } + return nil +} + // validateEnvelopeContent validates the content which includes signerInfo and // payload. func validateEnvelopeContent(content *signature.EnvelopeContent) error { @@ -127,15 +139,19 @@ func validateEnvelopeContent(content *signature.EnvelopeContent) error { // validateSignerInfo performs basic set of validations on SignerInfo struct. func validateSignerInfo(info *signature.SignerInfo) error { if len(info.Signature) == 0 { - return &signature.MalformedSignatureError{Msg: "signature not present or is empty"} + return &signature.InvalidSignatureError{Msg: "signature not present or is empty"} } if info.SignatureAlgorithm == 0 { - return &signature.MalformedSignatureError{Msg: "SignatureAlgorithm is not present"} + return &signature.InvalidSignatureError{Msg: "SignatureAlgorithm is not present"} } signingTime := info.SignedAttributes.SigningTime - if err := validateSigningTime(signingTime, info.SignedAttributes.Expiry); err != nil { + if err := validateSigningAndExpiryTime(signingTime, info.SignedAttributes.Expiry); err != nil { + return err + } + + if err := validateSigningSchema(info.SignedAttributes.SigningScheme); err != nil { return err } @@ -146,30 +162,23 @@ func validateSignerInfo(info *signature.SignerInfo) error { ) } -// validateSigningTime checks that signing time is within the valid range of -// time duration. -func validateSigningTime(signingTime, expireTime time.Time) error { +// validateSigningAndExpiryTime checks that signing time is within the valid +// range of time duration and expire time is valid. +func validateSigningAndExpiryTime(signingTime, expireTime time.Time) error { if signingTime.IsZero() { - return &signature.MalformedSignatureError{Msg: "signing-time not present"} + return &signature.InvalidSignatureError{Msg: "signing-time not present"} } if !expireTime.IsZero() && (expireTime.Before(signingTime) || expireTime.Equal(signingTime)) { - return &signature.MalformedSignatureError{Msg: "expiry cannot be equal or before the signing time"} + return &signature.InvalidSignatureError{Msg: "expiry cannot be equal or before the signing time"} } return nil } // validatePayload performs validation of the payload. func validatePayload(payload *signature.Payload) error { - switch payload.ContentType { - case signature.MediaTypePayloadV1: - if len(payload.Content) == 0 { - return &signature.MalformedSignatureError{Msg: "content not present"} - } - default: - return &signature.MalformedSignatureError{ - Msg: fmt.Sprintf("payload content type: {%s} not supported", payload.ContentType), - } + if len(payload.Content) == 0 { + return &signature.InvalidSignatureError{Msg: "content not present"} } return nil @@ -178,22 +187,22 @@ func validatePayload(payload *signature.Payload) error { // validateCertificateChain performs the validation of the certificate chain. func validateCertificateChain(certChain []*x509.Certificate, signTime time.Time, expectedAlg signature.Algorithm) error { if len(certChain) == 0 { - return &signature.MalformedSignatureError{Msg: "certificate-chain not present or is empty"} + return &signature.InvalidSignatureError{Msg: "certificate-chain not present or is empty"} } err := nx509.ValidateCodeSigningCertChain(certChain, signTime) if err != nil { - return &signature.MalformedSignatureError{ + return &signature.InvalidSignatureError{ Msg: fmt.Sprintf("certificate-chain is invalid, %s", err), } } signingAlg, err := getSignatureAlgorithm(certChain[0]) if err != nil { - return &signature.MalformedSignatureError{Msg: err.Error()} + return &signature.InvalidSignatureError{Msg: err.Error()} } if signingAlg != expectedAlg { - return &signature.MalformedSignatureError{ + return &signature.InvalidSignatureError{ Msg: fmt.Sprintf("mismatch between signature algorithm derived from signing certificate (%v) and signing algorithm specified (%vs)", signingAlg, expectedAlg), } } diff --git a/signature/internal/base/envelope_test.go b/signature/internal/base/envelope_test.go index 54395750..e6f2d06b 100644 --- a/signature/internal/base/envelope_test.go +++ b/signature/internal/base/envelope_test.go @@ -22,12 +22,14 @@ var ( time08_02 time.Time time08_03 time.Time timeLayout = "2006-01-02" + signiningSchema = signature.SigningScheme("notary.x509") validSignerInfo = &signature.SignerInfo{ Signature: validBytes, SignatureAlgorithm: signature.AlgorithmPS384, SignedAttributes: signature.SignedAttributes{ SigningTime: testhelper.GetRSALeafCertificate().Cert.NotBefore, Expiry: testhelper.GetECLeafCertificate().Cert.NotAfter, + SigningScheme: signiningSchema, }, CertificateChain: []*x509.Certificate{ testhelper.GetRSALeafCertificate().Cert, @@ -40,7 +42,7 @@ var ( } validEnvelopeContent = &signature.EnvelopeContent{ SignerInfo: *validSignerInfo, - Payload: *validPayload, + Payload: *validPayload, } validReq = &signature.SignRequest{ Payload: signature.Payload{ @@ -49,6 +51,7 @@ var ( }, SigningTime: testhelper.GetRSALeafCertificate().Cert.NotBefore, Expiry: testhelper.GetRSALeafCertificate().Cert.NotAfter, + SigningScheme: signiningSchema, Signer: &mockSigner{ keySpec: signature.KeySpec{ Type: signature.KeyTypeRSA, @@ -68,6 +71,7 @@ var ( }, SigningTime: testhelper.GetRSALeafCertificate().Cert.NotBefore, Expiry: testhelper.GetRSALeafCertificate().Cert.NotAfter, + SigningScheme: signiningSchema, Signer: &mockSigner{ keySpec: signature.KeySpec{ Type: signature.KeyTypeRSA, @@ -89,10 +93,10 @@ func init() { // Mock an internal envelope that implements signature.Envelope. type mockEnvelope struct { - payload *signature.Payload - signerInfo *signature.SignerInfo - content *signature.EnvelopeContent - failVerify bool + payload *signature.Payload + signerInfo *signature.SignerInfo + content *signature.EnvelopeContent + failVerify bool } // Sign implements Sign of signature.Envelope. @@ -279,7 +283,7 @@ func TestVerify(t *testing.T) { Raw: validBytes, Envelope: &mockEnvelope{ content: &signature.EnvelopeContent{ - Payload: *validPayload, + Payload: *validPayload, SignerInfo: signature.SignerInfo{}, }, }, @@ -293,7 +297,7 @@ func TestVerify(t *testing.T) { Raw: validBytes, Envelope: &mockEnvelope{ content: &signature.EnvelopeContent{ - Payload: *validPayload, + Payload: *validPayload, SignerInfo: *validSignerInfo, }, }, @@ -348,13 +352,11 @@ func TestContent(t *testing.T) { Raw: validBytes, Envelope: &mockEnvelope{ content: &signature.EnvelopeContent{ - Payload: signature.Payload{ - ContentType: invalidContentType, - }, + Payload: signature.Payload{}, }, }, }, - expect: nil, + expect: nil, expectErr: true, }, { @@ -368,7 +370,7 @@ func TestContent(t *testing.T) { signerInfo: &signature.SignerInfo{}, }, }, - expect: nil, + expect: nil, expectErr: true, }, { @@ -377,12 +379,12 @@ func TestContent(t *testing.T) { Raw: validBytes, Envelope: &mockEnvelope{ content: &signature.EnvelopeContent{ - Payload: *validPayload, + Payload: *validPayload, SignerInfo: *validSignerInfo, }, }, }, - expect: validEnvelopeContent, + expect: validEnvelopeContent, expectErr: false, }, } @@ -435,7 +437,7 @@ func TestValidateSignRequest(t *testing.T) { expectErr: true, }, { - name: "empty certificates", + name: "invalid signing schema", req: &signature.SignRequest{ Payload: signature.Payload{ ContentType: validContentType, @@ -456,6 +458,7 @@ func TestValidateSignRequest(t *testing.T) { }, SigningTime: time08_02, Expiry: time08_03, + SigningScheme: signiningSchema, Signer: &mockSigner{ certs: []*x509.Certificate{ testhelper.GetRSALeafCertificate().Cert, @@ -510,6 +513,18 @@ func TestValidateSignerInfo(t *testing.T) { }, expectErr: true, }, + { + name: "invalid signing schema", + info: &signature.SignerInfo{ + Signature: validBytes, + SignatureAlgorithm: signature.AlgorithmPS384, + SignedAttributes: signature.SignedAttributes{ + SigningTime: testhelper.GetRSALeafCertificate().Cert.NotBefore, + Expiry: testhelper.GetECLeafCertificate().Cert.NotAfter, + }, + }, + expectErr: true, + }, { name: "valid signerInfo", info: validSignerInfo, @@ -557,7 +572,7 @@ func TestValidateSigningTime(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := validateSigningTime(tt.signingTime, tt.expireTime) + err := validateSigningAndExpiryTime(tt.signingTime, tt.expireTime) if (err != nil) != tt.expectErr { t.Errorf("error = %v, expectErr = %v", err, tt.expectErr) diff --git a/signature/jws.go b/signature/jws.go index 9e105090..86763867 100644 --- a/signature/jws.go +++ b/signature/jws.go @@ -57,12 +57,12 @@ func (jws *jwsEnvelope) validateIntegrity() error { } if len(jws.internalEnv.Header.CertChain) == 0 { - return MalformedSignatureError{Msg: "malformed leaf certificate"} + return InvalidSignatureError{Msg: "malformed leaf certificate"} } cert, err := x509.ParseCertificate(jws.internalEnv.Header.CertChain[0]) if err != nil { - return MalformedSignatureError{Msg: "malformed leaf certificate"} + return InvalidSignatureError{Msg: "malformed leaf certificate"} } // verify JWT @@ -72,7 +72,7 @@ func (jws *jwsEnvelope) validateIntegrity() error { func (jws *jwsEnvelope) signPayload(req SignRequest) ([]byte, error) { errorFunc := func(s string) error { - return MalformedSignRequestError{msg: s} + return InvalidSignRequestError{msg: s} } ks, err := req.SignatureProvider.KeySpec() @@ -157,7 +157,7 @@ func (jws *jwsEnvelope) getSignerInfo() (*EnvelopeContent, error) { func parseProtectedHeaders(encoded string) (*jwsProtectedHeader, error) { rawProtected, err := base64.RawURLEncoding.DecodeString(encoded) if err != nil { - return nil, MalformedSignatureError{Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())} + return nil, InvalidSignatureError{Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())} } // To Unmarshal JSON with some known(jwsProtectedHeader), and some unknown(jwsProtectedHeader.ExtendedAttributes) field names. @@ -165,10 +165,10 @@ func parseProtectedHeaders(encoded string) (*jwsProtectedHeader, error) { // and removing the keys are already been defined in jwsProtectedHeader. var protected jwsProtectedHeader if err = json.Unmarshal(rawProtected, &protected); err != nil { - return nil, MalformedSignatureError{Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())} + return nil, InvalidSignatureError{Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())} } if err = json.Unmarshal(rawProtected, &protected.ExtendedAttributes); err != nil { - return nil, MalformedSignatureError{Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())} + return nil, InvalidSignatureError{Msg: fmt.Sprintf("jws envelope protected header can't be decoded: %s", err.Error())} } // delete attributes that are already defined in jwsProtectedHeader. @@ -233,14 +233,14 @@ func validateProtectedHeaders(protectedHdr *jwsProtectedHeader) error { switch protectedHdr.SigningScheme { case SigningSchemeX509: if protectedHdr.AuthenticSigningTime != nil { - return MalformedSignatureError{Msg: fmt.Sprintf("%q header must not be present for %s signing scheme", headerKeyAuthenticSigningTime, SigningSchemeX509)} + return InvalidSignatureError{Msg: fmt.Sprintf("%q header must not be present for %s signing scheme", headerKeyAuthenticSigningTime, SigningSchemeX509)} } case SigningSchemeX509SigningAuthority: if protectedHdr.SigningTime != nil { - return MalformedSignatureError{Msg: fmt.Sprintf("%q header must not be present for %s signing scheme", headerKeySigningTime, SigningSchemeX509SigningAuthority)} + return InvalidSignatureError{Msg: fmt.Sprintf("%q header must not be present for %s signing scheme", headerKeySigningTime, SigningSchemeX509SigningAuthority)} } if protectedHdr.AuthenticSigningTime == nil { - return MalformedSignatureError{Msg: fmt.Sprintf("%q header must be present for %s signing scheme", headerKeyAuthenticSigningTime, SigningSchemeX509)} + return InvalidSignatureError{Msg: fmt.Sprintf("%q header must be present for %s signing scheme", headerKeyAuthenticSigningTime, SigningSchemeX509)} } } @@ -250,7 +250,7 @@ func validateProtectedHeaders(protectedHdr *jwsProtectedHeader) error { // validateCriticalHeaders validates headers that should be present or marked critical as per singing scheme func validateCriticalHeaders(protectedHdr *jwsProtectedHeader) error { if len(protectedHdr.Critical) == 0 { - return MalformedSignatureError{"missing `crit` header"} + return InvalidSignatureError{"missing `crit` header"} } mustMarkedCrit := map[string]bool{headerKeySigningScheme: true} @@ -275,7 +275,7 @@ func validateCriticalHeaders(protectedHdr *jwsProtectedHeader) error { delete(mustMarkedCrit, val) } else { if _, ok := protectedHdr.ExtendedAttributes[val]; !ok { - return MalformedSignatureError{Msg: fmt.Sprintf("%q header is marked critical but not present", val)} + return InvalidSignatureError{Msg: fmt.Sprintf("%q header is marked critical but not present", val)} } } } @@ -287,7 +287,7 @@ func validateCriticalHeaders(protectedHdr *jwsProtectedHeader) error { for k := range mustMarkedCrit { keys = append(keys, k) } - return MalformedSignatureError{fmt.Sprintf("these required headers are not marked as critical: %v", keys)} + return InvalidSignatureError{fmt.Sprintf("these required headers are not marked as critical: %v", keys)} } return nil @@ -339,7 +339,7 @@ func getSignedAttrs(req SignRequest, sigAlg SignatureAlgorithm) (map[string]inte jwsProtectedHdr.Critical = crit m, err := convertToMap(jwsProtectedHdr) if err != nil { - return nil, MalformedSignRequestError{msg: fmt.Sprintf("unexpected error occured while creating protected headers, Error: %s", err.Error())} + return nil, InvalidSignRequestError{msg: fmt.Sprintf("unexpected error occured while creating protected headers, Error: %s", err.Error())} } return mergeMaps(m, extAttrs), nil @@ -462,7 +462,7 @@ func sign(payload []byte, headers map[string]interface{}, sigPro Signer) (string func getSignatureAlgo(alg string) (SignatureAlgorithm, error) { signatureAlg, ok := jwsAlgSignatureAlgMap[alg] if !ok { - return "", SignatureAlgoNotSupportedError{alg: alg} + return "", UnsupportedSignatureAlgoError{alg: alg} } return signatureAlg, nil @@ -471,7 +471,7 @@ func getSignatureAlgo(alg string) (SignatureAlgorithm, error) { func getJWSAlgo(alg SignatureAlgorithm) (string, error) { jwsAlg, ok := signatureAlgJWSAlgMap[alg] if !ok { - return "", SignatureAlgoNotSupportedError{alg: string(alg)} + return "", UnsupportedSignatureAlgoError{alg: string(alg)} } return jwsAlg, nil diff --git a/signature/jws_test.go b/signature/jws_test.go index 2369f1d0..f6c554a0 100644 --- a/signature/jws_test.go +++ b/signature/jws_test.go @@ -50,14 +50,14 @@ func TestValidateIntegrity(t *testing.T) { t.Run("with invalid base64 bytes sig envelope returns error", func(t *testing.T) { env, _ := newJWSEnvelopeFromBytes([]byte("{\"Payload\":\"Hi!\",\"Protected\":\"Hi\",\"Header\":{},\"Signature\":\"Hi!\"}")) err := env.validateIntegrity() - if !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) t.Run("with incomplete sig envelope returns error", func(t *testing.T) { env, _ := newJWSEnvelopeFromBytes([]byte("{\"Payload\":\"eyJhbGciOiJIUzI1NiJ9\",\"Protected\":\"eyJhbGciOiJQUzI1NiIsImNyaXQiOlsiaW8uY25jZi5ub3Rhcnkuc2lnbmluZ1RpbWUiXSwiaW8uY25jZi5ub3Rhcnkuc2luaW5nVGltZSI6IjIwMDYtMDEtMDJUMTU6MDQ6MDVaIn0\",\"Header\":{},\"Signature\":\"YjGj\"}")) - if err := env.validateIntegrity(); !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if err := env.validateIntegrity(); !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) @@ -84,7 +84,7 @@ func TestValidateIntegrity(t *testing.T) { malformedSig := "{\"payload\":\"eyJ0YXJnZXRBcnRpZmFjdCI6eyJtZWRpYVR5cGUiOiJhcHBsaWNhdGlvbi92bmQub2NpLmltYWdlLm1hbmlmZXN0LnYxK2pzb24iLCJkaWdlc3QiOiJzaGEyNTY6NzNjODAzOTMwZWEzYmExZTU0YmMyNWMyYmRjNTNlZGQwMjg0YzYyZWQ2NTFmZTdiMDAzNjlkYTUxOWEzYzMzMyIsInNpemUiOjE2NzI0LCJhbm5vdGF0aW9ucyI6eyJpby53YWJiaXQtbmV0d29ya3MuYnVpbGRJZCI6IjEyMyJ9fX0\",\"protected\":\"eyJhbGciOiJQUzM4NCIsImNyaXQiOlsiaW8uY25jZi5ub3Rhcnkuc2lnbmluZ1NjaGV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mNf9kU04YFwkTJn8HECFseGRmZAvG8x0W5PcQik5\"}" env, _ := newJWSEnvelopeFromBytes([]byte(malformedSig)) - if err := env.validateIntegrity(); !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if err := env.validateIntegrity(); !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("validateIntegrity(). Expected SignatureIntegrityError but found %q", reflect.TypeOf(err)) } }) @@ -99,7 +99,7 @@ func TestValidateIntegrity(t *testing.T) { t.Errorf("validateIntegrity(). Error = %s", err) } - if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("getSignerInfo. Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } } @@ -143,7 +143,7 @@ func TestGetSignerInfo(t *testing.T) { t.Run("with invalid singing time returns error", func(t *testing.T) { env, _ := newJWSEnvelopeFromBytes([]byte("{\"Payload\":\"eyJhbGciOiJIUzI1NiJ9\",\"Protected\":\"eyJhbGciOiJQUzI1NiIsImNyaXQiOlsiaW8uY25jZi5ub3Rhcnkuc2lnbmluZ1RpbWUiXSwiaW8uY25jZi5ub3Rhcnkuc2lnbmluZ1RpbWUiOiIyMDA2LS0wMlQxNTowNDowNVoifQ\"" + ",\"Header\":{},\"Signature\":\"YjGj\"}")) - if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) @@ -161,7 +161,7 @@ func TestGetSignerInfo(t *testing.T) { t.Errorf("validateIntegrity(). Error: %s", err.Error()) } - if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) @@ -169,7 +169,7 @@ func TestGetSignerInfo(t *testing.T) { t.Run("with malformed alg header returns error", func(t *testing.T) { env, _ := newJWSEnvelopeFromBytes([]byte("{\"Payload\":\"eyJhbGciOiJIUzI1NiJ9\",\"Protected\":\"eyJhbGciOjEzLCJjcml0IjpbImlvLmNuY2Yubm90YXJ5LnNpZ25pbmdUaW1lIl0sImlvLmNuY2Yubm90YXJ5LnNpbmluZ1RpbWUiOiIyMDA2LTAxLTAyVDE1OjA0OjA1WiJ9\"" + ",\"Header\":{},\"Signature\":\"YjGj\"}")) - if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) @@ -177,7 +177,7 @@ func TestGetSignerInfo(t *testing.T) { t.Run("with malformed cty header returns error", func(t *testing.T) { env, _ := newJWSEnvelopeFromBytes([]byte("{\"Payload\":\"eyJhbGciOiJIUzI1NiJ9\",\"Protected\":\"eyJhbGciOiJQUzUxMiIsImN0eSI6MTIzLCJjcml0IjpbImlvLmNuY2Yubm90YXJ5LnNpZ25pbmdUaW1lIl0sImlvLmNuY2Yubm90YXJ5LnNpbmluZ1RpbWUiOiIyMDA2LTAxLTAyVDE1OjA0OjA1WiJ9\"" + ",\"Header\":{},\"Signature\":\"YjGj\"}")) - if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(MalformedSignatureError))) { + if _, err := env.getSignerInfo(); !(err != nil && errors.As(err, new(InvalidSignatureError))) { t.Errorf("Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) @@ -210,28 +210,28 @@ func TestSignPayloadError(t *testing.T) { req := getSignRequest() t.Run("when SignatureProvider'KeySpec returns error", func(t *testing.T) { req.SignatureProvider = ErrorSignatureProvider{KeySpecError: true} - if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(MalformedSignRequestError))) { + if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(InvalidSignRequestError))) { t.Errorf("signPayload(). Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) t.Run("when SignatureProvider'SignError returns error", func(t *testing.T) { req.SignatureProvider = ErrorSignatureProvider{SignError: true} - if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(MalformedSignRequestError))) { + if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(InvalidSignRequestError))) { t.Errorf("signPayload(). Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) t.Run("when SignatureProvider'Sign returns invalid certificate chain", func(t *testing.T) { req.SignatureProvider = ErrorSignatureProvider{InvalidCertChain: true} - if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(MalformedSignRequestError))) { + if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(InvalidSignRequestError))) { t.Errorf("signPayload(). Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) t.Run("when SignatureProvider'KeySpec returns invalid value", func(t *testing.T) { req.SignatureProvider = ErrorSignatureProvider{InvalidKeySpec: true} - if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(SignatureAlgoNotSupportedError))) { + if _, err := env.signPayload(req); !(err != nil && errors.As(err, new(UnsupportedSignatureAlgoError))) { t.Errorf("signPayload(). Expected MalformedSignatureError but found %q", reflect.TypeOf(err)) } }) diff --git a/signature/jwt.go b/signature/jwt.go index 9036eaba..394c1dec 100644 --- a/signature/jwt.go +++ b/signature/jwt.go @@ -25,7 +25,7 @@ func verifyJWT(tokenString string, key crypto.PublicKey) error { if _, err := parser.Parse(tokenString, func(t *jwt.Token) (interface{}, error) { if t.Method.Alg() != signingMethod.Alg() { - return nil, MalformedSignatureError{Msg: fmt.Sprintf("unexpected signing method: %v: require %v", t.Method.Alg(), signingMethod.Alg())} + return nil, InvalidSignatureError{Msg: fmt.Sprintf("unexpected signing method: %v: require %v", t.Method.Alg(), signingMethod.Alg())} } // override default signing method with key-specific method diff --git a/signature/signer.go b/signature/signer.go index e9faa8d9..6364de6c 100644 --- a/signature/signer.go +++ b/signature/signer.go @@ -18,7 +18,7 @@ type Signer interface { KeySpec() (KeySpec, error) } -// LocalSigner is used by built-in signers to sign only. +// LocalSigner is only used by built-in signers to sign. type LocalSigner interface { Signer @@ -40,26 +40,10 @@ type localSigner struct { certs []*x509.Certificate } -// SignatureEnvelope provides functions to generate signature and verify signature. -type SignatureEnvelope struct { - rawSignatureEnvelope []byte - internalEnvelope internalSignatureEnvelope -} - -// Contains a set of common methods that every Signature envelope format must implement. -type internalSignatureEnvelope interface { - // validateIntegrity validates the integrity of given Signature envelope. - validateIntegrity() error - // getSignerInfo returns the information stored in the Signature envelope and doesn't perform integrity verification. - getSignerInfo() (*EnvelopeContent, error) - // signPayload created Signature envelope. - signPayload(SignRequest) ([]byte, error) -} - // NewLocalSigner returns a new signer with given certificates and private key. func NewLocalSigner(certs []*x509.Certificate, key crypto.PrivateKey) (LocalSigner, error) { if len(certs) == 0 { - return nil, &MalformedArgumentError{ + return nil, &InvalidArgumentError{ Param: "certs", Err: errors.New("empty certs"), } @@ -71,7 +55,7 @@ func NewLocalSigner(certs []*x509.Certificate, key crypto.PrivateKey) (LocalSign } if !isKeyPair(key, certs[0].PublicKey, keySpec) { - return nil, &MalformedArgumentError{ + return nil, &InvalidArgumentError{ Param: "key and certs", Err: errors.New("key not matches certificate"), } @@ -132,11 +116,11 @@ func (s *localSigner) PrivateKey() crypto.PrivateKey { // Reference: https://github.com/notaryproject/notaryproject/blob/main/trust-store-trust-policy-specification.md#steps func VerifyAuthenticity(signerInfo *SignerInfo, trustedCerts []*x509.Certificate) (*x509.Certificate, error) { if len(trustedCerts) == 0 { - return nil, &MalformedArgumentError{Param: "trustedCerts"} + return nil, &InvalidArgumentError{Param: "trustedCerts"} } if signerInfo == nil { - return nil, &MalformedArgumentError{Param: "signerInfo"} + return nil, &InvalidArgumentError{Param: "signerInfo"} } for _, trust := range trustedCerts { diff --git a/signature/types.go b/signature/types.go index 49cecae9..30a0d02d 100644 --- a/signature/types.go +++ b/signature/types.go @@ -23,9 +23,6 @@ const ( SigningSchemeX509SigningAuthority SigningScheme = "notary.x509.signingAuthority" ) -// MediaTypePayloadV1 is the supported content type for signature's payload. -const MediaTypePayloadV1 = "application/vnd.cncf.notary.payload.v1+json" - // SignedAttributes represents signed metadata in the signature envelope. // Reference: https://github.com/notaryproject/notaryproject/blob/main/signature-specification.md#signed-attributes type SignedAttributes struct { @@ -123,9 +120,6 @@ type SignerInfo struct { // Signature is the bytes generated from the signature. Signature []byte - - // Payload represents payload in bytes and its content type. - Payload Payload } // Payload represents payload in bytes and its content type. diff --git a/signature/utils.go b/signature/utils.go index 705ec860..c07847f3 100644 --- a/signature/utils.go +++ b/signature/utils.go @@ -11,7 +11,7 @@ import ( // NewLocalSignatureProvider returns the LocalSignatureProvider created using given certificates and private key. func NewLocalSignatureProvider(certs []*x509.Certificate, pk crypto.PrivateKey) (*LocalSignatureProvider, error) { if len(certs) == 0 { - return nil, &MalformedArgumentError{Param: "certs"} + return nil, &InvalidArgumentError{Param: "certs"} } ks, err := ExtractKeySpec(certs[0])