From ce55ec4bd6e48aa5d137a0ffe1924f0aca384596 Mon Sep 17 00:00:00 2001 From: Andrii Holovko Date: Fri, 15 Nov 2024 15:16:30 +0200 Subject: [PATCH] chore(sdk): update linters Signed-off-by: Andrii Holovko --- .golangci.yml | 33 ++++----- cmd/wallet-sdk-gomobile/api/activitylogger.go | 6 +- .../api/activitylogger_test.go | 2 +- cmd/wallet-sdk-gomobile/attestation/client.go | 1 + .../credential/inquirer.go | 3 +- .../credential/inquirer_test.go | 68 +++++++++---------- cmd/wallet-sdk-gomobile/did/resolver.go | 5 +- cmd/wallet-sdk-gomobile/did/wellknown_test.go | 7 +- cmd/wallet-sdk-gomobile/display/credential.go | 10 +-- .../display/displaydata.go | 11 ++- cmd/wallet-sdk-gomobile/display/resolve.go | 13 ++-- .../display/resolve_test.go | 37 +++++----- .../oauth2/clientmetadata.go | 2 +- .../oauth2/clientregistration_test.go | 8 +-- .../openid4ci/interaction.go | 6 +- .../issuerinitiatedinteraction_test.go | 9 +-- .../openid4vp/interaction.go | 7 +- .../openid4vp/interaction_test.go | 4 +- .../trustregistry/trust_registry_test.go | 6 +- .../verifiable/credential.go | 2 +- cmd/wallet-sdk-gomobile/wrapper/error_test.go | 4 +- .../wrapper/httpclient_test.go | 3 +- pkg/attestation/attestation_client.go | 2 +- pkg/common/jwt_signer_test.go | 8 +-- pkg/common/keyresolver_test.go | 2 +- pkg/credentialquery/errors.go | 5 +- pkg/credentialschema/credentialdisplay.go | 16 +++-- pkg/credentialschema/credentialschema_test.go | 11 +-- pkg/credentialschema/opts.go | 9 +-- pkg/did/resolver/resolver_test.go | 3 +- pkg/did/wellknown/wellknown.go | 1 + pkg/did/wellknown/wellknown_test.go | 7 +- pkg/internal/httprequest/httprequest.go | 5 +- pkg/internal/issuermetadata/issuermetadata.go | 2 +- pkg/ldproof/ldproof.go | 30 +++++--- pkg/localkms/ariescryptowrapper.go | 2 +- pkg/oauth2/clientregistration_test.go | 5 +- pkg/openid4ci/acknowledgment.go | 8 ++- pkg/openid4ci/interaction.go | 8 ++- pkg/openid4ci/issuerinitiatedinteraction.go | 12 ++-- .../issuerinitiatedinteraction_test.go | 46 +++++++++++-- pkg/openid4ci/model_test.go | 2 +- pkg/openid4ci/models.go | 4 +- pkg/openid4ci/walletinitiatedinteraction.go | 3 +- pkg/openid4vp/acknowledgment.go | 10 +-- pkg/openid4vp/openid4vp.go | 30 +++++--- pkg/openid4vp/openid4vp_test.go | 21 +++--- pkg/openid4vp/opts.go | 5 -- pkg/trustregistry/trust_registry_test.go | 4 +- 49 files changed, 302 insertions(+), 206 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index c473dbf4..6c22d023 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -6,14 +6,14 @@ run: concurrency: 4 - deadline: 3m + timeout: 3m issues-exit-code: 1 tests: true build-tags: [""] - skip-dirs: [""] output: - format: colored-line-number + formats: + - format: colored-line-number print-issued-lines: true print-linter-name: true @@ -21,19 +21,18 @@ linters-settings: errcheck: check-type-assertions: true check-blank: true - ignore: fmt:.*,io/ioutil:^Read.* + exclude-functions: + - fmt:.* + - io/ioutil:^Read.* govet: - check-shadowing: true - golint: - min-confidence: 0.6 + enable: + - shadow gofmt: simplify: true goimports: local-prefixes: github.com/trustbloc/agent-sdk gocyclo: min-complexity: 10 - maligned: - suggest-new: true dupl: threshold: 100 goconst: @@ -46,8 +45,6 @@ linters-settings: lll: line-length: 120 tab-width: 1 - unused: - check-exported: false unparam: check-exported: false nakedret: @@ -73,17 +70,11 @@ linters-settings: linters: enable-all: true disable: - - maligned - prealloc - - goerr113 # not good: https://github.com/Djarvur/go-err113/issues/10 + - err113 # not good: https://github.com/Djarvur/go-err113/issues/10 - paralleltest - - exhaustivestruct # - tparallel - - interfacer # deprecated by the author https://github.com/mvdan/interfacer#interfacer - - scopelint # deprecated by the author https://github.com/kyoh86/scopelint#obsoleted - - maligned # deprecated by the author https://github.com/mdempsky/maligned - cyclop # TODO consider replacing gocyclo with cyclop - - ifshort # TODO enable - wrapcheck # TODO enable - forbidigo # TODO enable - gci # giving spurious errors for imports of syscall/js @@ -92,6 +83,10 @@ linters: - tagliatelle # JSON tags using camel-case required by the specs we implement - varnamelen # This linter prevents us from using "i" as an index variable or "vc" for a variable name for a Verifiable Credential, both of which are very common in our code - depguard # TODO consider enabling in the future + - exportloopref + - revive + - perfsprint + - thelper issues: exclude-use-default: false @@ -101,6 +96,8 @@ issues: - dupl - funlen - maintidx + max-issues-per-linter: 0 + max-same-issues: 0 exclude: # Allow package logger variables (for now) diff --git a/cmd/wallet-sdk-gomobile/api/activitylogger.go b/cmd/wallet-sdk-gomobile/api/activitylogger.go index 62ab162d..440ec426 100644 --- a/cmd/wallet-sdk-gomobile/api/activitylogger.go +++ b/cmd/wallet-sdk-gomobile/api/activitylogger.go @@ -123,7 +123,7 @@ func (p *Params) GetString(key string) (string, error) { func (p *Params) GetStringArray(key string) (*StringArray, error) { value, exists := p.params[key] if !exists { - return nil, fmt.Errorf(noValueFoundErrMsg) + return nil, errors.New(noValueFoundErrMsg) } return interfaceAsStringArray(value) @@ -218,7 +218,7 @@ func getType(value interface{}) (string, error) { // This function checks to see if the []interface{} value is really a []string, and if so, // returns "[]string" (which matches what fmt.Sprintf("%T", value) returns for a []string). func getTypeOfInterfaceArray(typedValue []interface{}) (string, error) { - for i := 0; i < len(typedValue); i++ { + for i := range typedValue { _, ok := typedValue[i].(string) if !ok { return "", errors.New(unsupportedTypeErrMsg) @@ -237,7 +237,7 @@ func interfaceAsStringArray(value interface{}) (*StringArray, error) { } strings := make([]string, len(valueAsInterfaceArray)) - for i := 0; i < len(valueAsInterfaceArray); i++ { + for i := range valueAsInterfaceArray { strings[i], ok = valueAsInterfaceArray[i].(string) if !ok { return nil, errors.New(valueNotStringArrayErrMsg) diff --git a/cmd/wallet-sdk-gomobile/api/activitylogger_test.go b/cmd/wallet-sdk-gomobile/api/activitylogger_test.go index f5474fa2..d48f1bd4 100644 --- a/cmd/wallet-sdk-gomobile/api/activitylogger_test.go +++ b/cmd/wallet-sdk-gomobile/api/activitylogger_test.go @@ -154,7 +154,7 @@ func checkActivity(t *testing.T, activity *api.Activity) { require.Equal(t, 2, keyValuePairs.Length()) - for i := 0; i < keyValuePairs.Length(); i++ { + for i := range keyValuePairs.Length() { var stringCaseChecked, stringArrayCaseChecked bool keyValuePair := keyValuePairs.AtIndex(i) diff --git a/cmd/wallet-sdk-gomobile/attestation/client.go b/cmd/wallet-sdk-gomobile/attestation/client.go index 0561e7f0..c0b0b0be 100644 --- a/cmd/wallet-sdk-gomobile/attestation/client.go +++ b/cmd/wallet-sdk-gomobile/attestation/client.go @@ -202,6 +202,7 @@ func createGoAPIClientConfig(args *CreateClientArgs) (*attestationgoapi.ClientCo dlHTTPClient := wrapper.NewHTTPClient(args.httpTimeout, api.Headers{}, args.disableHTTPClientTLSVerification) var err error + goAPIClientConfig.DocumentLoader, err = common.CreateJSONLDDocumentLoader(dlHTTPClient, legacy.NewProvider()) if err != nil { return nil, err diff --git a/cmd/wallet-sdk-gomobile/credential/inquirer.go b/cmd/wallet-sdk-gomobile/credential/inquirer.go index 03b02167..e840da05 100644 --- a/cmd/wallet-sdk-gomobile/credential/inquirer.go +++ b/cmd/wallet-sdk-gomobile/credential/inquirer.go @@ -54,6 +54,7 @@ func NewInquirer(opts *InquirerOpts) (*Inquirer, error) { } var err error + goAPIDocumentLoader, err = common.CreateJSONLDDocumentLoader(httpClient, legacy.NewProvider()) if err != nil { return nil, wrapper.ToMobileError(err) @@ -112,7 +113,7 @@ func unwrapQuery(query []byte) (*presexch.PresentationDefinition, error) { func unwrapVCs(vcs *verifiable.CredentialsArray) []*afgoverifiable.Credential { var credentials []*afgoverifiable.Credential - for i := 0; i < vcs.Length(); i++ { + for i := range vcs.Length() { credentials = append(credentials, vcs.AtIndex(i).VC) } diff --git a/cmd/wallet-sdk-gomobile/credential/inquirer_test.go b/cmd/wallet-sdk-gomobile/credential/inquirer_test.go index 239ed5bd..5fff3d57 100644 --- a/cmd/wallet-sdk-gomobile/credential/inquirer_test.go +++ b/cmd/wallet-sdk-gomobile/credential/inquirer_test.go @@ -91,25 +91,25 @@ func TestInstance_GetSubmissionRequirements(t *testing.T) { requirements, err := query.GetSubmissionRequirements(multiInputPD, createCredJSONArray(t, contents)) require.NoError(t, err) - require.Equal(t, requirements.Len(), 1) + require.Equal(t, 1, requirements.Len()) req1 := requirements.AtIndex(0) - require.Equal(t, req1.DescriptorLen(), 3) - require.Equal(t, req1.Name(), "Information") - require.Equal(t, req1.Purpose(), "test purpose") - require.Equal(t, req1.Rule(), "pick") + require.Equal(t, 3, req1.DescriptorLen()) + require.Equal(t, "Information", req1.Name()) + require.Equal(t, "test purpose", req1.Purpose()) + require.Equal(t, "pick", req1.Rule()) require.Nil(t, requirements.AtIndex(1)) - require.Equal(t, req1.Count(), 1) - require.Equal(t, req1.Min(), 0) - require.Equal(t, req1.Max(), 0) - require.Equal(t, req1.NestedRequirementLength(), 0) + require.Equal(t, 1, req1.Count()) + require.Equal(t, 0, req1.Min()) + require.Equal(t, 0, req1.Max()) + require.Equal(t, 0, req1.NestedRequirementLength()) desc1 := req1.DescriptorAtIndex(0) - require.Equal(t, desc1.ID, "VerifiedEmployee") - require.Equal(t, desc1.Name, "Verified Employee") - require.Equal(t, desc1.Purpose, "test purpose") - require.Equal(t, desc1.MatchedVCs.Length(), 1) + require.Equal(t, "VerifiedEmployee", desc1.ID) + require.Equal(t, "Verified Employee", desc1.Name) + require.Equal(t, "test purpose", desc1.Purpose) + require.Equal(t, 1, desc1.MatchedVCs.Length()) require.Equal(t, 0, desc1.Schemas().Length()) require.Nil(t, desc1.Schemas().AtIndex(0)) require.Equal(t, "VerifiedEmployee", desc1.TypeConstraint()) @@ -124,26 +124,26 @@ func TestInstance_GetSubmissionRequirements(t *testing.T) { requirements, err := query.GetSubmissionRequirements(nestedRequirementsPD, createCredJSONArray(t, contents)) require.NoError(t, err) - require.Equal(t, requirements.Len(), 1) + require.Equal(t, 1, requirements.Len()) req1 := requirements.AtIndex(0) - require.Equal(t, req1.DescriptorLen(), 0) - require.Equal(t, req1.Name(), "Nested requirements") - require.Equal(t, req1.Rule(), "all") + require.Equal(t, 0, req1.DescriptorLen()) + require.Equal(t, "Nested requirements", req1.Name()) + require.Equal(t, "all", req1.Rule()) - require.Equal(t, req1.Count(), 2) - require.Equal(t, req1.Min(), 0) - require.Equal(t, req1.Max(), 0) - require.Equal(t, req1.NestedRequirementLength(), 2) + require.Equal(t, 2, req1.Count()) + require.Equal(t, 0, req1.Min()) + require.Equal(t, 0, req1.Max()) + require.Equal(t, 2, req1.NestedRequirementLength()) nestedReq1 := req1.NestedRequirementAtIndex(0) - require.Equal(t, nestedReq1.DescriptorLen(), 2) + require.Equal(t, 2, nestedReq1.DescriptorLen()) desc1 := nestedReq1.DescriptorAtIndex(0) - require.Equal(t, desc1.ID, "VerifiedEmployee") - require.Equal(t, desc1.Name, "Verified Employee") - require.Equal(t, desc1.MatchedVCs.Length(), 1) + require.Equal(t, "VerifiedEmployee", desc1.ID) + require.Equal(t, "Verified Employee", desc1.Name) + require.Equal(t, 1, desc1.MatchedVCs.Length()) require.Nil(t, req1.NestedRequirementAtIndex(2)) }) @@ -155,7 +155,7 @@ func TestInstance_GetSubmissionRequirements(t *testing.T) { requirements, err := query.GetSubmissionRequirements(schemaPD, createCredJSONArray(t, contents)) require.NoError(t, err) - require.Equal(t, requirements.Len(), 1) + require.Equal(t, 1, requirements.Len()) req1 := requirements.AtIndex(0) desc1 := req1.DescriptorAtIndex(0) @@ -178,7 +178,7 @@ func TestInstance_GetSubmissionRequirements(t *testing.T) { requirements, err := query.GetSubmissionRequirements(schemaPD, nil) require.NoError(t, err) - require.Equal(t, requirements.Len(), 1) + require.Equal(t, 1, requirements.Len()) req1 := requirements.AtIndex(0) desc1 := req1.DescriptorAtIndex(0) @@ -238,18 +238,18 @@ func TestInstance_GetSubmissionRequirementsCitizenship(t *testing.T) { requirements, err := query.GetSubmissionRequirements(citizenshipPD, createCredJSONArray(t, contents)) require.NoError(t, err) - require.Equal(t, requirements.Len(), 1) + require.Equal(t, 1, requirements.Len()) req1 := requirements.AtIndex(0) - require.Equal(t, req1.DescriptorLen(), 1) + require.Equal(t, 1, req1.DescriptorLen()) - require.Equal(t, req1.Count(), 1) - require.Equal(t, req1.Min(), 0) - require.Equal(t, req1.Max(), 0) - require.Equal(t, req1.NestedRequirementLength(), 0) + require.Equal(t, 1, req1.Count()) + require.Equal(t, 0, req1.Min()) + require.Equal(t, 0, req1.Max()) + require.Equal(t, 0, req1.NestedRequirementLength()) desc1 := req1.DescriptorAtIndex(0) - require.Equal(t, desc1.MatchedVCs.Length(), 1) + require.Equal(t, 1, desc1.MatchedVCs.Length()) }) } diff --git a/cmd/wallet-sdk-gomobile/did/resolver.go b/cmd/wallet-sdk-gomobile/did/resolver.go index 53589934..5b659287 100644 --- a/cmd/wallet-sdk-gomobile/did/resolver.go +++ b/cmd/wallet-sdk-gomobile/did/resolver.go @@ -9,11 +9,10 @@ SPDX-License-Identifier: Apache-2.0 package did import ( + "github.com/trustbloc/wallet-sdk/pkg/did/resolver" + "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/api" - // helps gomobile bind api.DIDResolver interface to Resolver implementation in ios-bindings. - _ "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/api" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/wrapper" - "github.com/trustbloc/wallet-sdk/pkg/did/resolver" ) // Resolver supports DID resolution. diff --git a/cmd/wallet-sdk-gomobile/did/wellknown_test.go b/cmd/wallet-sdk-gomobile/did/wellknown_test.go index c0189f19..d16b427e 100644 --- a/cmd/wallet-sdk-gomobile/did/wellknown_test.go +++ b/cmd/wallet-sdk-gomobile/did/wellknown_test.go @@ -14,6 +14,7 @@ import ( "net/http/httptest" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/did-go/doc/did" "github.com/trustbloc/did-go/method/httpbinding" @@ -121,11 +122,11 @@ func TestValidate(t *testing.T) { } testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { - require.Equal(t, "/"+testDID, req.URL.String()) + assert.Equal(t, "/"+testDID, req.URL.String()) res.Header().Add("Content-type", "application/did+ld+json") res.WriteHeader(http.StatusOK) _, err := res.Write([]byte(resolutionResponse)) - require.NoError(t, err) + assert.NoError(t, err) })) defer func() { testServer.Close() }() @@ -148,7 +149,7 @@ func TestValidate(t *testing.T) { t.Run("DID service validation failure", func(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, _ *http.Request) { _, err := res.Write([]byte(didCfg)) - require.NoError(t, err) + assert.NoError(t, err) })) defer func() { testServer.Close() }() diff --git a/cmd/wallet-sdk-gomobile/display/credential.go b/cmd/wallet-sdk-gomobile/display/credential.go index a32e31bd..2c2f7e2a 100644 --- a/cmd/wallet-sdk-gomobile/display/credential.go +++ b/cmd/wallet-sdk-gomobile/display/credential.go @@ -157,19 +157,19 @@ type Credential struct { } // LocalizedOverviewsLength returns the number of different locales supported for the credential displays. -func (d *Credential) LocalizedOverviewsLength() int { - return len(d.credentialDisplay.LocalizedOverview) +func (c *Credential) LocalizedOverviewsLength() int { + return len(c.credentialDisplay.LocalizedOverview) } // LocalizedOverviewAtIndex returns the number of different locales supported for the issuer displays. // If the index passed in is out of bounds, then nil is returned. -func (d *Credential) LocalizedOverviewAtIndex(index int) *Overview { - maxIndex := len(d.credentialDisplay.LocalizedOverview) - 1 +func (c *Credential) LocalizedOverviewAtIndex(index int) *Overview { + maxIndex := len(c.credentialDisplay.LocalizedOverview) - 1 if index > maxIndex || index < 0 { return nil } - return &Overview{overview: &d.credentialDisplay.LocalizedOverview[index]} + return &Overview{overview: &c.credentialDisplay.LocalizedOverview[index]} } // SubjectsLength returns the number of credential subject displays contained within this Credential object. diff --git a/cmd/wallet-sdk-gomobile/display/displaydata.go b/cmd/wallet-sdk-gomobile/display/displaydata.go index ee0ce2cd..57f554f4 100644 --- a/cmd/wallet-sdk-gomobile/display/displaydata.go +++ b/cmd/wallet-sdk-gomobile/display/displaydata.go @@ -306,9 +306,14 @@ func (c *Attachment) ID() string { } // Type returns the attachment Type. This could be "EmbeddedAttachment", "RemoteAttachment" or "AttachmentEvidence". -// For EmbeddedAttachment, the uri will be a data URI. Hash and HashAlg will provide the hash value of the data along with Hash algorithm used to generate the hash. -// For RemoteAttachment, the uri will be a remote HTTP URL. Hash and HashAlg will provide the hash value of the data along with Hash algorithm used to generate the hash. Consumer of this API need to validate the hash value against the hash of the data object retrieved from the remote url -// For AttachmentEvidence, the uri will be empty. But the hash and hashAlg will provide the hash value of the data along with Hash algorithm used to generate the hash. Consumer of this API need to validate the hash value against the hash of the data object retrieved from the out of band. +// For EmbeddedAttachment, the uri will be a data URI. Hash and HashAlg will provide the hash value of the data +// along with Hash algorithm used to generate the hash. +// For RemoteAttachment, the uri will be a remote HTTP URL. Hash and HashAlg will provide the hash value of the data +// along with Hash algorithm used to generate the hash. Consumer of this API need to validate the hash value against the +// hash of the data object retrieved from the remote url. +// For AttachmentEvidence, the uri will be empty. But the hash and hashAlg will provide the hash value of the data +// along with Hash algorithm used to generate the hash. Consumer of this API need to validate the hash value against the +// hash of the data object retrieved from the out of band. func (c *Attachment) Type() string { if len(c.attachment.Type) == 0 { return "" diff --git a/cmd/wallet-sdk-gomobile/display/resolve.go b/cmd/wallet-sdk-gomobile/display/resolve.go index daea8a97..d2fee43c 100644 --- a/cmd/wallet-sdk-gomobile/display/resolve.go +++ b/cmd/wallet-sdk-gomobile/display/resolve.go @@ -9,15 +9,16 @@ package display import ( "errors" + "github.com/trustbloc/vc-go/proof/defaults" afgoverifiable "github.com/trustbloc/vc-go/verifiable" + goapicredentialschema "github.com/trustbloc/wallet-sdk/pkg/credentialschema" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/api" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/openid4ci" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/verifiable" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/wrapper" "github.com/trustbloc/wallet-sdk/pkg/common" - goapicredentialschema "github.com/trustbloc/wallet-sdk/pkg/credentialschema" ) // Resolve resolves display information for issued credentials based on an issuer's metadata, which is fetched @@ -55,11 +56,15 @@ func ResolveCredential(credentialsArray *verifiable.CredentialsArray, issuerURI return &Resolved{resolvedDisplayData: resolvedDisplayData}, nil } -func ResolveCredentialV2(credentialsArray *verifiable.CredentialsArrayV2, issuerURI string, opts *Opts) (*Resolved, error) { +func ResolveCredentialV2( + credentialsArray *verifiable.CredentialsArrayV2, + issuerURI string, + opts *Opts, +) (*Resolved, error) { credentials := &verifiable.CredentialsArray{} opts.credentialConfigIDs = make([]string, credentialsArray.Length()) - for i := 0; i < credentialsArray.Length(); i++ { + for i := range credentialsArray.Length() { credentials.Add(credentialsArray.AtIndex(i)) opts.credentialConfigIDs[i] = credentialsArray.ConfigIDAtIndex(i) } @@ -150,7 +155,7 @@ func generateGoAPIOpts(vcs *verifiable.CredentialsArray, issuerURI string, func mobileVCsArrayToGoAPIVCsArray(vcs *verifiable.CredentialsArray) []*afgoverifiable.Credential { goAPIVCs := make([]*afgoverifiable.Credential, vcs.Length()) - for i := 0; i < vcs.Length(); i++ { + for i := range vcs.Length() { goAPIVCs[i] = vcs.AtIndex(i).VC } diff --git a/cmd/wallet-sdk-gomobile/display/resolve_test.go b/cmd/wallet-sdk-gomobile/display/resolve_test.go index a8ffe955..4e374ddd 100644 --- a/cmd/wallet-sdk-gomobile/display/resolve_test.go +++ b/cmd/wallet-sdk-gomobile/display/resolve_test.go @@ -15,6 +15,7 @@ import ( "strconv" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/api" @@ -49,12 +50,12 @@ func (m *mockIssuerServerHandler) ServeHTTP(writer http.ResponseWriter, request for _, headerToCheck := range m.headersToCheck.GetAll() { // Note: for these tests, we're assuming that there aren't multiple values under a single name/key. value := request.Header.Get(headerToCheck.Name) - require.Equal(m.t, headerToCheck.Value, value) + assert.Equal(m.t, headerToCheck.Value, value) } } _, err := writer.Write([]byte(m.issuerMetadata)) - require.NoError(m.t, err) + assert.NoError(m.t, err) } func TestResolve(t *testing.T) { @@ -85,7 +86,7 @@ func TestResolve(t *testing.T) { credentialDisplay := resolvedDisplayData.CredentialDisplayAtIndex(0) - for i := 0; i < credentialDisplay.ClaimsLength(); i++ { + for i := range credentialDisplay.ClaimsLength() { claim := credentialDisplay.ClaimAtIndex(i) if claim.Label() == sensitiveIDLabel { @@ -103,7 +104,7 @@ func TestResolve(t *testing.T) { credentialDisplay := resolvedDisplayData.CredentialDisplayAtIndex(0) - for i := 0; i < credentialDisplay.ClaimsLength(); i++ { + for i := range credentialDisplay.ClaimsLength() { claim := credentialDisplay.ClaimAtIndex(i) if claim.Label() == sensitiveIDLabel { @@ -121,7 +122,7 @@ func TestResolve(t *testing.T) { credentialDisplay := resolvedDisplayData.CredentialDisplayAtIndex(0) - for i := 0; i < credentialDisplay.ClaimsLength(); i++ { + for i := range credentialDisplay.ClaimsLength() { claim := credentialDisplay.ClaimAtIndex(i) if claim.Label() == sensitiveIDLabel { @@ -226,14 +227,14 @@ func TestResolveCredential(t *testing.T) { resolvedDisplayData, err := display.ResolveCredential(vcs, server.URL, opts) require.NoError(t, err) - require.Equal(t, resolvedDisplayData.LocalizedIssuersLength(), 2) - require.Equal(t, resolvedDisplayData.CredentialsLength(), 1) - require.Equal(t, resolvedDisplayData.CredentialAtIndex(0).LocalizedOverviewsLength(), 1) - require.Equal(t, resolvedDisplayData.CredentialAtIndex(0).SubjectsLength(), 6) + require.Equal(t, 2, resolvedDisplayData.LocalizedIssuersLength()) + require.Equal(t, 1, resolvedDisplayData.CredentialsLength()) + require.Equal(t, 1, resolvedDisplayData.CredentialAtIndex(0).LocalizedOverviewsLength()) + require.Equal(t, 6, resolvedDisplayData.CredentialAtIndex(0).SubjectsLength()) credentialDisplay := resolvedDisplayData.CredentialAtIndex(0) - for i := 0; i < credentialDisplay.SubjectsLength(); i++ { + for i := range credentialDisplay.SubjectsLength() { claim := credentialDisplay.SubjectAtIndex(i) if claim.LocalizedLabelAtIndex(0).Name() == sensitiveIDLabel { @@ -256,14 +257,14 @@ func TestResolveCredential(t *testing.T) { resolvedDisplayData, err := display.ResolveCredentialV2(vcs, server.URL, opts) require.NoError(t, err) - require.Equal(t, resolvedDisplayData.LocalizedIssuersLength(), 2) - require.Equal(t, resolvedDisplayData.CredentialsLength(), 1) - require.Equal(t, resolvedDisplayData.CredentialAtIndex(0).LocalizedOverviewsLength(), 1) - require.Equal(t, resolvedDisplayData.CredentialAtIndex(0).SubjectsLength(), 6) + require.Equal(t, 2, resolvedDisplayData.LocalizedIssuersLength()) + require.Equal(t, 1, resolvedDisplayData.CredentialsLength()) + require.Equal(t, 1, resolvedDisplayData.CredentialAtIndex(0).LocalizedOverviewsLength()) + require.Equal(t, 6, resolvedDisplayData.CredentialAtIndex(0).SubjectsLength()) credentialDisplay := resolvedDisplayData.CredentialAtIndex(0) - for i := 0; i < credentialDisplay.SubjectsLength(); i++ { + for i := range credentialDisplay.SubjectsLength() { claim := credentialDisplay.SubjectAtIndex(i) if claim.LocalizedLabelAtIndex(0).Name() == sensitiveIDLabel { @@ -421,10 +422,10 @@ func checkClaims(t *testing.T, credentialDisplay *display.CredentialDisplay) { / } expectedClaimsChecklist.Found = make([]bool, len(expectedClaimsChecklist.Claims)) - for i := 0; i < credentialDisplay.ClaimsLength(); i++ { + for i := range credentialDisplay.ClaimsLength() { claim := credentialDisplay.ClaimAtIndex(i) - for j := 0; j < len(expectedClaimsChecklist.Claims); j++ { + for j := range len(expectedClaimsChecklist.Claims) { expectedClaim := expectedClaimsChecklist.Claims[j] if claim.Label() == expectedClaim.Label && claim.ValueType() == expectedClaim.ValueType && @@ -458,7 +459,7 @@ func checkClaims(t *testing.T, credentialDisplay *display.CredentialDisplay) { / } } - for i := 0; i < len(expectedClaimsChecklist.Claims); i++ { + for i := range len(expectedClaimsChecklist.Claims) { if !expectedClaimsChecklist.Found[i] { expectedClaim := expectedClaimsChecklist.Claims[i] require.FailNow(t, "claim was expected but wasn't received", diff --git a/cmd/wallet-sdk-gomobile/oauth2/clientmetadata.go b/cmd/wallet-sdk-gomobile/oauth2/clientmetadata.go index a1105e7c..7f50d4ae 100644 --- a/cmd/wallet-sdk-gomobile/oauth2/clientmetadata.go +++ b/cmd/wallet-sdk-gomobile/oauth2/clientmetadata.go @@ -135,7 +135,7 @@ func (c *ClientMetadata) SetScopes(scopes *api.StringArray) { indexOfLastScope := numOfScopes - 1 - for i := 0; i < indexOfLastScope; i++ { + for i := range indexOfLastScope { sb.WriteString(scopes.AtIndex(i)) sb.WriteString(" ") } diff --git a/cmd/wallet-sdk-gomobile/oauth2/clientregistration_test.go b/cmd/wallet-sdk-gomobile/oauth2/clientregistration_test.go index 1f9f28c7..22d11983 100644 --- a/cmd/wallet-sdk-gomobile/oauth2/clientregistration_test.go +++ b/cmd/wallet-sdk-gomobile/oauth2/clientregistration_test.go @@ -13,12 +13,12 @@ import ( "testing" "time" - goapi "github.com/trustbloc/wallet-sdk/pkg/api" - + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/api" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/oauth2" + goapi "github.com/trustbloc/wallet-sdk/pkg/api" goapioauth2 "github.com/trustbloc/wallet-sdk/pkg/oauth2" ) @@ -61,12 +61,12 @@ func (m *mockIssuerServerHandler) ServeHTTP(w http.ResponseWriter, _ *http.Reque } responseBytes, err := json.Marshal(response) - require.NoError(m.t, err) + assert.NoError(m.t, err) w.WriteHeader(http.StatusCreated) _, err = w.Write(responseBytes) - require.NoError(m.t, err) + assert.NoError(m.t, err) } func TestRegisterClient(t *testing.T) { diff --git a/cmd/wallet-sdk-gomobile/openid4ci/interaction.go b/cmd/wallet-sdk-gomobile/openid4ci/interaction.go index 9fe02288..bf38e5ea 100644 --- a/cmd/wallet-sdk-gomobile/openid4ci/interaction.go +++ b/cmd/wallet-sdk-gomobile/openid4ci/interaction.go @@ -47,6 +47,7 @@ func createGoAPIClientConfig(didResolver api.DIDResolver, opts *InteractionOpts) dlHTTPClient := wrapper.NewHTTPClient(opts.httpTimeout, api.Headers{}, opts.disableHTTPClientTLSVerification) var err error + goAPIClientConfig.DocumentLoader, err = common.CreateJSONLDDocumentLoader(dlHTTPClient, legacy.NewProvider()) if err != nil { return nil, err @@ -110,7 +111,10 @@ func toGomobileCredentials(credentials []*afgoverifiable.Credential) *verifiable return gomobileCredentials } -func toGomobileCredentialsV2(credentials []*afgoverifiable.Credential, configIDs []string) *verifiable.CredentialsArrayV2 { +func toGomobileCredentialsV2( + credentials []*afgoverifiable.Credential, + configIDs []string, +) *verifiable.CredentialsArrayV2 { credentialArray := verifiable.NewCredentialsArrayV2() for i := range credentials { diff --git a/cmd/wallet-sdk-gomobile/openid4ci/issuerinitiatedinteraction_test.go b/cmd/wallet-sdk-gomobile/openid4ci/issuerinitiatedinteraction_test.go index bd070c6b..08cdba3a 100644 --- a/cmd/wallet-sdk-gomobile/openid4ci/issuerinitiatedinteraction_test.go +++ b/cmd/wallet-sdk-gomobile/openid4ci/issuerinitiatedinteraction_test.go @@ -19,6 +19,7 @@ import ( "time" "github.com/piprate/json-gold/ld" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/did-go/doc/did" arieskms "github.com/trustbloc/kms-go/spi/kms" @@ -150,7 +151,7 @@ func (m *mockIssuerServerHandler) ServeHTTP(writer http.ResponseWriter, //nolint for _, headerToCheck := range m.headersToCheck.GetAll() { // Note: for these tests, we're assuming that there aren't multiple values under a single name/key. value := request.Header.Get(headerToCheck.Name) - require.Equal(m.t, headerToCheck.Value, value) + assert.Equal(m.t, headerToCheck.Value, value) } } @@ -183,15 +184,15 @@ func (m *mockIssuerServerHandler) ServeHTTP(writer http.ResponseWriter, //nolint var payload map[string]interface{} err = json.NewDecoder(request.Body).Decode(&payload) - require.NoError(m.t, err) + assert.NoError(m.t, err) _, ok := payload["interaction_details"] - require.Equal(m.t, m.ackRequestExpectInteractionDetails, ok) + assert.Equal(m.t, m.ackRequestExpectInteractionDetails, ok) writer.WriteHeader(http.StatusNoContent) } - require.NoError(m.t, err) + assert.NoError(m.t, err) } func TestIssuerInitiatedInteraction_CreateAuthorizationURL(t *testing.T) { diff --git a/cmd/wallet-sdk-gomobile/openid4vp/interaction.go b/cmd/wallet-sdk-gomobile/openid4vp/interaction.go index 412ee460..6fef5e58 100644 --- a/cmd/wallet-sdk-gomobile/openid4vp/interaction.go +++ b/cmd/wallet-sdk-gomobile/openid4vp/interaction.go @@ -222,8 +222,8 @@ func (o *Interaction) PresentCredentialOpts( var presentOpts []openid4vp.PresentOpt - if opts != nil { - if len(opts.serializedInteractionDetails) > 0 { + if opts != nil { //nolint:nestif + if opts.serializedInteractionDetails != "" { var interactionDetails map[string]interface{} if err = json.Unmarshal([]byte(opts.serializedInteractionDetails), &interactionDetails); err != nil { return fmt.Errorf("decode vp interaction details: %w", err) @@ -267,6 +267,7 @@ func (o *Interaction) OTelTraceID() string { return traceID } +//nolint:unparam func toGoAPIOpts(opts *Opts) ([]openid4vp.Opt, error) { httpClient := wrapper.NewHTTPClient(opts.httpTimeout, opts.additionalHeaders, opts.disableHTTPClientTLSVerification) @@ -296,7 +297,7 @@ func unwrapVCs(vcs *verifiable.CredentialsArray) ([]*afgoverifiable.Credential, var credentials []*afgoverifiable.Credential - for i := 0; i < vcs.Length(); i++ { + for i := range vcs.Length() { vc := vcs.AtIndex(i) if vc == nil { return nil, fmt.Errorf("credential objects cannot be nil (credential at index %d is nil)", i) diff --git a/cmd/wallet-sdk-gomobile/openid4vp/interaction_test.go b/cmd/wallet-sdk-gomobile/openid4vp/interaction_test.go index 11d2f35d..0da9c5cc 100644 --- a/cmd/wallet-sdk-gomobile/openid4vp/interaction_test.go +++ b/cmd/wallet-sdk-gomobile/openid4vp/interaction_test.go @@ -414,7 +414,7 @@ func (c *mockCrypto) Sign(_ []byte, _ string) ([]byte, error) { return c.SignResult, c.SignErr } -func (c *mockCrypto) Verify(_ []byte, _ []byte, _ string) error { +func (c *mockCrypto) Verify(_, _ []byte, _ string) error { return c.VerifyErr } @@ -444,7 +444,7 @@ func (o *mockGoAPIInteraction) CustomScope() []string { func (o *mockGoAPIInteraction) PresentCredential( []*afgoverifiable.Credential, openid4vp.CustomClaims, -...openid4vp.PresentOpt, + ...openid4vp.PresentOpt, ) error { return o.PresentCredentialErr } diff --git a/cmd/wallet-sdk-gomobile/trustregistry/trust_registry_test.go b/cmd/wallet-sdk-gomobile/trustregistry/trust_registry_test.go index e4b11be7..6af812d1 100644 --- a/cmd/wallet-sdk-gomobile/trustregistry/trust_registry_test.go +++ b/cmd/wallet-sdk-gomobile/trustregistry/trust_registry_test.go @@ -54,8 +54,8 @@ func TestRegistry_EvaluateIssuance(t *testing.T) { require.NoError(t, err) require.NotNil(t, result) require.False(t, result.Allowed) - require.Equal(t, result.ErrorCode, "didForbidden") - require.Equal(t, result.DenyReason(), "unauthorized issuer, empty credentials") + require.Equal(t, "didForbidden", result.ErrorCode) + require.Equal(t, "unauthorized issuer, empty credentials", result.DenyReason()) }) t.Run("Invalid server URI", func(t *testing.T) { @@ -111,7 +111,7 @@ func TestRegistry_EvaluatePresentation(t *testing.T) { require.NoError(t, err) require.NotNil(t, result) require.False(t, result.Allowed) - require.Equal(t, result.ErrorCode, "didForbidden") + require.Equal(t, "didForbidden", result.ErrorCode) }) t.Run("Invalid server URI", func(t *testing.T) { diff --git a/cmd/wallet-sdk-gomobile/verifiable/credential.go b/cmd/wallet-sdk-gomobile/verifiable/credential.go index c35ad78c..3e2ddfa5 100644 --- a/cmd/wallet-sdk-gomobile/verifiable/credential.go +++ b/cmd/wallet-sdk-gomobile/verifiable/credential.go @@ -115,7 +115,7 @@ func rawTypesToStringArray(rawTypes interface{}) *api.StringArray { typesAsInterfaceArray, ok := rawTypes.([]interface{}) // This will be the type if the VC was parsed (unmarshalled) if ok { types := make([]string, len(typesAsInterfaceArray)) - for i := 0; i < len(typesAsInterfaceArray); i++ { + for i := range typesAsInterfaceArray { types[i], ok = typesAsInterfaceArray[i].(string) if !ok { return nil diff --git a/cmd/wallet-sdk-gomobile/wrapper/error_test.go b/cmd/wallet-sdk-gomobile/wrapper/error_test.go index 38f9fc7c..e4da823e 100644 --- a/cmd/wallet-sdk-gomobile/wrapper/error_test.go +++ b/cmd/wallet-sdk-gomobile/wrapper/error_test.go @@ -103,13 +103,13 @@ func TestToMobileError(t *testing.T) { require.Equal(t, "Code", parsedErr.Code) require.Equal(t, "Category", parsedErr.Category) require.Equal(t, "even-higher-level error: higher-level error: Details", parsedErr.Details) - }) + }, + ) t.Run("goapiwalleterror.Error wrapped by another goapiwalleterror.Error", func(t *testing.T) { // Note: We shouldn't actually do this anywhere in our code. If this happens, then the highest-level // goapiwalleterror.Error is the one that will be detected and converted properly to the Gomobile error type, // while the lower one will get "squashed" into the Details field. This test just confirms that this is the // expected behaviour in such a scenario. - lowerLevelWalletError := &goapiwalleterror.Error{ Code: "Lower-Level-Code", Category: "Lower-Level-Category", diff --git a/cmd/wallet-sdk-gomobile/wrapper/httpclient_test.go b/cmd/wallet-sdk-gomobile/wrapper/httpclient_test.go index 0590b893..f2aba00e 100644 --- a/cmd/wallet-sdk-gomobile/wrapper/httpclient_test.go +++ b/cmd/wallet-sdk-gomobile/wrapper/httpclient_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/wallet-sdk/cmd/wallet-sdk-gomobile/api" @@ -28,7 +29,7 @@ func (m *mockServer) ServeHTTP(_ http.ResponseWriter, request *http.Request) { for _, headerToCheck := range m.headersToCheck.GetAll() { // Note: for these tests, we're assuming that there aren't multiple values under a single name/key. value := request.Header.Get(headerToCheck.Name) - require.Equal(m.t, headerToCheck.Value, value) + assert.Equal(m.t, headerToCheck.Value, value) } } } diff --git a/pkg/attestation/attestation_client.go b/pkg/attestation/attestation_client.go index 9d02260e..c859ba1e 100644 --- a/pkg/attestation/attestation_client.go +++ b/pkg/attestation/attestation_client.go @@ -158,7 +158,7 @@ func (c *Client) attestationComplete( func getSignerDID(jwtSigner api.JWTSigner) (string, error) { kidParts := strings.Split(jwtSigner.GetKeyID(), "#") - if len(kidParts) < 2 { //nolint: gomnd + if len(kidParts) < 2 { //nolint: mnd return "", walleterror.NewExecutionError( ErrorModule, KeyIDMissingDIDPartCode, diff --git a/pkg/common/jwt_signer_test.go b/pkg/common/jwt_signer_test.go index 880896b5..f71dc530 100644 --- a/pkg/common/jwt_signer_test.go +++ b/pkg/common/jwt_signer_test.go @@ -167,13 +167,13 @@ func TestJWSSigner_Sign(t *testing.T) { require.NoError(t, err) require.Equal(t, sig, []byte("mock sig")) - require.Equal(t, signer.GetKeyID(), "testKeyID") - require.Equal(t, signer.Algorithm(), "EdDSA") + require.Equal(t, "testKeyID", signer.GetKeyID()) + require.Equal(t, "EdDSA", signer.Algorithm()) headers, err := signer.CreateJWTHeaders(jwt.SignParameters{}) require.NoError(t, err) - require.Equal(t, headers["kid"], "testKeyID") - require.Equal(t, headers["alg"], "EdDSA") + require.Equal(t, "testKeyID", headers["kid"]) + require.Equal(t, "EdDSA", headers["alg"]) }) t.Run("Failed", func(t *testing.T) { diff --git a/pkg/common/keyresolver_test.go b/pkg/common/keyresolver_test.go index c2be0a40..8030617a 100644 --- a/pkg/common/keyresolver_test.go +++ b/pkg/common/keyresolver_test.go @@ -35,7 +35,7 @@ func TestDIDKeyResolver_Resolve(t *testing.T) { req.Equal(publicKey.Value, pubKey.Value) req.Equal("Ed25519VerificationKey2018", pubKey.Type) req.NotNil(pubKey.JWK) - req.Equal(pubKey.JWK.Algorithm, "EdDSA") + req.Equal("EdDSA", pubKey.JWK.Algorithm) } type vdrResolverAdapter struct { diff --git a/pkg/credentialquery/errors.go b/pkg/credentialquery/errors.go index 4e15c39f..16ad02dc 100644 --- a/pkg/credentialquery/errors.go +++ b/pkg/credentialquery/errors.go @@ -6,11 +6,8 @@ SPDX-License-Identifier: Apache-2.0 package credentialquery -// Constants' names and reasons are obvious so they do not require additional comments. -// nolint:golint,nolintlint const ( module = "CRQ" FailToGetMatchRequirementsResultsError = "FAIL_TO_GET_MATCH_REQUIREMENTS_RESULTS" + FailToGetMatchRequirementsResultsCode = 4 ) - -const FailToGetMatchRequirementsResultsCode = 4 //nolint // Purpose is obvious from the name. diff --git a/pkg/credentialschema/credentialdisplay.go b/pkg/credentialschema/credentialdisplay.go index a0e2bfd8..23540783 100644 --- a/pkg/credentialschema/credentialdisplay.go +++ b/pkg/credentialschema/credentialdisplay.go @@ -56,6 +56,7 @@ func buildCredentialDisplays( var config *issuer.CredentialConfigurationSupported for _, c := range m.config { config = c + break } @@ -195,7 +196,7 @@ func resolveClaims( return resolvedClaims, nil } -func resolveClaim( +func resolveClaim( //nolint:funlen fieldName string, claim *issuer.Claim, vc *verifiable.Credential, @@ -301,8 +302,11 @@ func getLocalizedLabel(preferredLocale string, claim *issuer.Claim) (string, str } // Returns nil if no matching claim value could be found. -func getMatchingClaimValue(vc *verifiable.Credential, credentialSubject *verifiable.Subject, - fieldName string) interface{} { +func getMatchingClaimValue( + vc *verifiable.Credential, + credentialSubject *verifiable.Subject, + fieldName string, +) interface{} { if strings.EqualFold(fieldName, "ID") { if credentialSubject.ID == "" { return nil @@ -311,9 +315,10 @@ func getMatchingClaimValue(vc *verifiable.Credential, credentialSubject *verifia return credentialSubject.ID } - if strings.HasPrefix(fieldName, "$.credentialSubject.") { + if strings.HasPrefix(fieldName, "$.credentialSubject.") { //nolint:gocritic,nestif // work around for issue in vc.ToRawJSON() where the sd-jwt credentialSubject data is not included in the raw JSON fieldName = strings.ReplaceAll(fieldName, "$.credentialSubject.", "$.") + value := findMatchingClaimUsingJSONPath(credentialSubject.CustomFields, fieldName) if value != nil { return value @@ -431,6 +436,7 @@ func buildCredentialDisplaysAllLocale( var config *issuer.CredentialConfigurationSupported for _, c := range m.config { config = c + break } @@ -517,7 +523,7 @@ func resolveClaimsAllLocale( return resolvedClaims, nil } -func resolveClaimAllLocale( +func resolveClaimAllLocale( //nolint:funlen,gocyclo fieldName string, claim *issuer.Claim, vc *verifiable.Credential, diff --git a/pkg/credentialschema/credentialschema_test.go b/pkg/credentialschema/credentialschema_test.go index 3807d9ee..c372089e 100644 --- a/pkg/credentialschema/credentialschema_test.go +++ b/pkg/credentialschema/credentialschema_test.go @@ -62,7 +62,7 @@ func (m *mockIssuerServerHandler) ServeHTTP(writer http.ResponseWriter, _ *http. } } -func TestResolve(t *testing.T) { //nolint: gocognit // Test file +func TestResolve(t *testing.T) { //nolint:gocognit t.Run("Success", func(t *testing.T) { t.Run("Credentials supported object contains display info for the given VC", func(t *testing.T) { credential, err := verifiable.ParseCredential(credentialUniversityDegree, @@ -296,6 +296,7 @@ func TestResolve(t *testing.T) { //nolint: gocognit // Test file }) t.Run("VC does not have the subject fields specified by the claim display info", func(t *testing.T) { var rawCred verifiable.JSONObject + require.NoError(t, json.Unmarshal(credentialUniversityDegree, &rawCred)) // TODO: it not works in case of nil credentialSubject, but works with empty subject id. // Is empty subject id has sense at all? @@ -333,7 +334,7 @@ func TestResolve(t *testing.T) { //nolint: gocognit // Test file require.Equal(t, "#12107c", resolvedDisplayData.CredentialDisplays[0].Overview.BackgroundColor) require.Equal(t, "#FFFFFF", resolvedDisplayData.CredentialDisplays[0].Overview.TextColor) - require.Len(t, resolvedDisplayData.CredentialDisplays[0].Claims, 0) + require.Empty(t, resolvedDisplayData.CredentialDisplays[0].Claims) }) }) @@ -466,7 +467,7 @@ func TestResolveMetadataWithJsonPath(t *testing.T) { credentialschema.WithCredentials([]*verifiable.Credential{credential}), credentialschema.WithIssuerMetadata(&issuerMetadata)) require.NoError(t, errResolve) - require.Equal(t, len(resolvedDisplayData.CredentialDisplays[0].Claims), 7) + require.Len(t, resolvedDisplayData.CredentialDisplays[0].Claims, 7) }) } @@ -483,7 +484,7 @@ func TestResolveCredentialOffer(t *testing.T) { }) } -func TestResolveCredential(t *testing.T) { //nolint: gocognit // Test file +func TestResolveCredential(t *testing.T) { credential, err := verifiable.ParseCredential(credentialUniversityDegree, verifiable.WithCredDisableValidation(), verifiable.WithDisabledProofCheck()) @@ -499,7 +500,7 @@ func TestResolveCredential(t *testing.T) { //nolint: gocognit // Test file credentialschema.WithIssuerMetadata(&issuerMetadata)) require.NoError(t, errResolve) - require.Equal(t, len(resolvedDisplayData.Credential), 1) + require.Len(t, resolvedDisplayData.Credential, 1) } func checkSuccessCaseMatchedOverviewData(t *testing.T, resolvedDisplayData *credentialschema.ResolvedDisplayData) { diff --git a/pkg/credentialschema/opts.go b/pkg/credentialschema/opts.go index 047b5531..d7fb5624 100644 --- a/pkg/credentialschema/opts.go +++ b/pkg/credentialschema/opts.go @@ -46,7 +46,7 @@ type issuerMetadataSource struct { metadata *issuer.Metadata } -// credentialConfigMapping represents a mapping of Credential to its corresponding CredentialConfigurationSupported +// credentialConfigMapping represents a mapping of Credential to its corresponding CredentialConfigurationSupported. type credentialConfigMapping struct { credential *verifiable.Credential config map[string]*issuer.CredentialConfigurationSupported // config ID -> CredentialConfigurationSupported @@ -244,6 +244,7 @@ func validateIssuerMetadataOpts(issuerMetadataSource *issuerMetadataSource) erro return nil } +//nolint:gocyclo func processValidatedOpts(opts *resolveOpts) ([]*credentialConfigMapping, *issuer.Metadata, string, *string, error) { credentialConfigMappings, err := processVCOpts(&opts.credentialSource) if err != nil { @@ -275,8 +276,7 @@ func processValidatedOpts(opts *resolveOpts) ([]*credentialConfigMapping, *issue for configID := range m.config { config, ok := issuerMetadata.CredentialConfigurationsSupported[configID] if !ok { - return nil, nil, "", nil, errors.New(fmt.Sprintf("credential configuration with ID %s not found", - configID)) + return nil, nil, "", nil, fmt.Errorf("credential configuration with ID %s not found", configID) } m.config[configID] = config @@ -291,6 +291,7 @@ func processValidatedOpts(opts *resolveOpts) ([]*credentialConfigMapping, *issue } m.config[configID] = config + break } } @@ -305,7 +306,7 @@ func processVCOpts(credentialSource *credentialSource) ([]*credentialConfigMappi numVCs := len(credentialSource.vcs) numConfigIDs := len(credentialSource.credentialConfigIDs) - for i := 0; i < numVCs; i++ { + for i := range numVCs { m := &credentialConfigMapping{ credential: credentialSource.vcs[i], config: make(map[string]*issuer.CredentialConfigurationSupported), diff --git a/pkg/did/resolver/resolver_test.go b/pkg/did/resolver/resolver_test.go index d1a10ebf..8a9d1bcd 100644 --- a/pkg/did/resolver/resolver_test.go +++ b/pkg/did/resolver/resolver_test.go @@ -12,6 +12,7 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/wallet-sdk/pkg/did/resolver" @@ -66,7 +67,7 @@ func TestDIDResolver(t *testing.T) { res.WriteHeader(http.StatusOK) _, err := res.Write([]byte(doc)) - require.NoError(t, err) + assert.NoError(t, err) })) defer func() { testServer.Close() }() diff --git a/pkg/did/wellknown/wellknown.go b/pkg/did/wellknown/wellknown.go index aec83436..6d5d041f 100644 --- a/pkg/did/wellknown/wellknown.go +++ b/pkg/did/wellknown/wellknown.go @@ -104,6 +104,7 @@ func getLinkedDomainsService(didDoc *diddoc.Doc) (*diddoc.Service, error) { if strings.EqualFold(serviceType, linkedDomainsServiceType) { linkedDomainsService = &didDoc.Service[i] + break } } diff --git a/pkg/did/wellknown/wellknown_test.go b/pkg/did/wellknown/wellknown_test.go index c874ca99..b7a9b9af 100644 --- a/pkg/did/wellknown/wellknown_test.go +++ b/pkg/did/wellknown/wellknown_test.go @@ -15,6 +15,7 @@ import ( "net/http/httptest" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/did-go/doc/did" "github.com/trustbloc/did-go/method/httpbinding" @@ -126,11 +127,11 @@ func TestValidate(t *testing.T) { } testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) { - require.Equal(t, "/"+testDID, req.URL.String()) + assert.Equal(t, "/"+testDID, req.URL.String()) res.Header().Add("Content-type", "application/did+ld+json") res.WriteHeader(http.StatusOK) _, err := res.Write([]byte(resolutionResponse)) - require.NoError(t, err) + assert.NoError(t, err) })) defer func() { testServer.Close() }() @@ -209,7 +210,7 @@ func TestValidate(t *testing.T) { t.Run("DID service validation failure", func(t *testing.T) { testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, _ *http.Request) { _, err := res.Write([]byte(didCfg)) - require.NoError(t, err) + assert.NoError(t, err) })) defer func() { testServer.Close() }() diff --git a/pkg/internal/httprequest/httprequest.go b/pkg/internal/httprequest/httprequest.go index c2a098ec..159d156b 100644 --- a/pkg/internal/httprequest/httprequest.go +++ b/pkg/internal/httprequest/httprequest.go @@ -47,9 +47,12 @@ func (r *Request) Do(method, endpointURL, contentType string, body io.Reader, nil, body, event, parentEvent, nil, errorResponseHandler) } +//nolint:gochecknoglobals var defaultAcceptableStatuses = []int{http.StatusOK} // DoContext is the same as Do, but also accept context and headers. +// +//nolint:gocyclo func (r *Request) DoContext(ctx context.Context, method, endpointURL, contentType string, additionalHeaders http.Header, body io.Reader, event, parentEvent string, acceptableStatuses []int, errorResponseHandler func(statusCode int, responseBody []byte) error, @@ -88,7 +91,7 @@ func (r *Request) DoContext(ctx context.Context, method, endpointURL, contentTyp defer func() { errClose := resp.Body.Close() if errClose != nil { - println(fmt.Sprintf("failed to close response body: %s", errClose.Error())) + fmt.Printf("failed to close response body: %s\n", errClose.Error()) } }() diff --git a/pkg/internal/issuermetadata/issuermetadata.go b/pkg/internal/issuermetadata/issuermetadata.go index 50fe34f9..30c9aa3a 100644 --- a/pkg/internal/issuermetadata/issuermetadata.go +++ b/pkg/internal/issuermetadata/issuermetadata.go @@ -65,7 +65,7 @@ func responseBytesToIssuerMetadataObject(responseBytes []byte, return nil, fmt.Errorf("decode metadata: %w", err) } - if len(metadata.SignedMetadata) > 0 { + if metadata.SignedMetadata != "" { return issuerMetadataObjectFromJWT(metadata.SignedMetadata, signatureVerifier, err) } diff --git a/pkg/ldproof/ldproof.go b/pkg/ldproof/ldproof.go index 23b2fac3..7cd695a6 100644 --- a/pkg/ldproof/ldproof.go +++ b/pkg/ldproof/ldproof.go @@ -4,6 +4,7 @@ Copyright Gen Digital Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ +// Package ldproof contains a function for adding linked data proof to a verifiable presentation. package ldproof import ( @@ -36,6 +37,7 @@ const ( proofPurpose = "authentication" ) +//nolint:gochecknoglobals var supportedLDProofTypes = map[string]proof.LDProofDescriptor{ ecdsasecp256k1signature2019.ProofType: ecdsasecp256k1signature2019.New(), ed25519signature2018.ProofType: ed25519signature2018.New(), @@ -43,6 +45,7 @@ var supportedLDProofTypes = map[string]proof.LDProofDescriptor{ jsonwebsignature2020.ProofType: jsonwebsignature2020.New(), } +//nolint:gochecknoglobals var supportedDIKeyTypes = map[string][]kms.KeyType{ ecdsa2019.SuiteTypeNew: {kms.ECDSAP256TypeIEEEP1363, kms.ECDSAP384TypeIEEEP1363}, eddsa2022.SuiteType: {kms.ED25519Type}, @@ -130,20 +133,20 @@ func getKeyIDAndType(vm *did.VerificationMethod) (string, kms.KeyType, error) { return "", "", fmt.Errorf("unsupported verification method type: %s", vm.Type) } -func fullVMID(did, vmID string) string { +func fullVMID(id, vmID string) string { if vmID == "" { - return did + return id } if vmID[0] == '#' { - return did + vmID + return id + vmID } if strings.HasPrefix(vmID, "did:") { return vmID } - return did + "#" + vmID + return id + "#" + vmID } func isKeyTypeSupported(ldProof proof.LDProofDescriptor, keyType kms.KeyType) bool { @@ -156,7 +159,11 @@ func isKeyTypeSupported(ldProof proof.LDProofDescriptor, keyType kms.KeyType) bo return false } -func (p *LDProof) addDataIntegrityProof(vp *verifiable.Presentation, dataIntegritySuite string, keyID string, o *options) error { +func (p *LDProof) addDataIntegrityProof( + vp *verifiable.Presentation, + dataIntegritySuite, keyID string, + o *options, +) error { var initializer suite.SignerInitializer switch dataIntegritySuite { @@ -201,8 +208,13 @@ func (p *LDProof) addDataIntegrityProof(vp *verifiable.Presentation, dataIntegri return vp.AddDataIntegrityProof(proofContext, dataIntegritySigner) } -func (p *LDProof) addLinkedDataProof(vp *verifiable.Presentation, - proofDesc proof.LDProofDescriptor, keyID string, keyType kms.KeyType, o *options) error { +func (p *LDProof) addLinkedDataProof( + vp *verifiable.Presentation, + proofDesc proof.LDProofDescriptor, + keyID string, + keyType kms.KeyType, + o *options, +) error { proofContext := &verifiable.LinkedDataProofContext{ SignatureType: proofDesc.ProofType(), ProofCreator: creator.New(creator.WithLDProofType(proofDesc, p.createSigner(keyID))), @@ -247,6 +259,6 @@ type didResolverWrapper struct { didResolver api.DIDResolver } -func (d *didResolverWrapper) Resolve(did string, _ ...vdrapi.DIDMethodOption) (*did.DocResolution, error) { - return d.didResolver.Resolve(did) +func (d *didResolverWrapper) Resolve(id string, _ ...vdrapi.DIDMethodOption) (*did.DocResolution, error) { + return d.didResolver.Resolve(id) } diff --git a/pkg/localkms/ariescryptowrapper.go b/pkg/localkms/ariescryptowrapper.go index a8e0a859..92de35fa 100644 --- a/pkg/localkms/ariescryptowrapper.go +++ b/pkg/localkms/ariescryptowrapper.go @@ -28,7 +28,7 @@ func NewAriesCryptoWrapper(cryptoSuite api.Suite) *AriesCryptoWrapper { // Sign gets key from kms using keyID and use it to sign data. func (c *AriesCryptoWrapper) Sign(msg []byte, keyID string) ([]byte, error) { kidParts := strings.Split(keyID, "#") - if len(kidParts) == 2 { //nolint: gomnd + if len(kidParts) == 2 { //nolint: mnd keyID = kidParts[1] } diff --git a/pkg/oauth2/clientregistration_test.go b/pkg/oauth2/clientregistration_test.go index bf8d91e7..83ed4bd8 100644 --- a/pkg/oauth2/clientregistration_test.go +++ b/pkg/oauth2/clientregistration_test.go @@ -12,6 +12,7 @@ import ( "net/http/httptest" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/wallet-sdk/pkg/oauth2" @@ -42,10 +43,10 @@ func (m *mockIssuerServerHandler) ServeHTTP(w http.ResponseWriter, _ *http.Reque } responseBytes, err := json.Marshal(response) - require.NoError(m.t, err) + assert.NoError(m.t, err) _, err = w.Write(responseBytes) - require.NoError(m.t, err) + assert.NoError(m.t, err) } func TestRegisterClient(t *testing.T) { diff --git a/pkg/openid4ci/acknowledgment.go b/pkg/openid4ci/acknowledgment.go index 0be73622..50fb1b50 100644 --- a/pkg/openid4ci/acknowledgment.go +++ b/pkg/openid4ci/acknowledgment.go @@ -1,3 +1,9 @@ +/* +Copyright Gen Digital Inc. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + package openid4ci import ( @@ -85,7 +91,7 @@ func (a *Acknowledgment) sendAcknowledgeRequest( defer func() { errClose := resp.Body.Close() if errClose != nil { - println(fmt.Sprintf("failed to close response body: %s", errClose.Error())) + fmt.Printf("failed to close response body: %s\n", errClose.Error()) } }() diff --git a/pkg/openid4ci/interaction.go b/pkg/openid4ci/interaction.go index f34e7729..6c821cac 100644 --- a/pkg/openid4ci/interaction.go +++ b/pkg/openid4ci/interaction.go @@ -73,7 +73,7 @@ type interaction struct { } type requestedAcknowledgment struct { - //TODO: after update to the latest OIDC4CI this variable can be changed to string + // TODO: after update to the latest OIDC4CI this variable can be changed to string // since notification_id should be the same for given session. // spec: https://openid.github.io/OpenID4VCI/openid-4-verifiable-credential-issuance-wg-draft.html#section-8.3-14 ackIDs []string @@ -311,7 +311,8 @@ func (i *interaction) requestCredentialWithAuth(jwtSigner api.JWTSigner, credent ) ([]*verifiable.Credential, error) { timeStartRequestCredential := time.Now() - credentialResponses, err := i.getCredentialResponsesWithAuth(jwtSigner, credentialFormats, credentialTypes, credentialContexts) + credentialResponses, err := i.getCredentialResponsesWithAuth(jwtSigner, credentialFormats, credentialTypes, + credentialContexts) if err != nil { return nil, fmt.Errorf("failed to get credential response: %w", err) } @@ -355,6 +356,7 @@ func (i *interaction) getCredentialResponsesWithAuth(signer api.JWTSigner, crede credentialFormats, credentialTypes, credentialContexts, true) } +//nolint:nonamedreturns func (i *interaction) getCredentialResponse(signer api.JWTSigner, nonce any, credentialFormats []string, credentialTypes, credentialContexts [][]string, allowRetry bool, ) (credentialResponse []CredentialResponse, err error) { @@ -609,7 +611,7 @@ func (i *interaction) issuerFullTrustInfo( supportedCredentials := make([]SupportedCredential, len(credentialFormats)) - for j := 0; j < len(credentialFormats); j++ { + for j := range credentialFormats { supportedCredentials[j] = SupportedCredential{ Format: credentialFormats[j], Types: credentialTypes[j], diff --git a/pkg/openid4ci/issuerinitiatedinteraction.go b/pkg/openid4ci/issuerinitiatedinteraction.go index fd994585..d50b566d 100644 --- a/pkg/openid4ci/issuerinitiatedinteraction.go +++ b/pkg/openid4ci/issuerinitiatedinteraction.go @@ -74,6 +74,8 @@ type IssuerInitiatedInteraction struct { // NewIssuerInitiatedInteraction creates a new OpenID4CI IssuerInitiatedInteraction. // If no ActivityLogger is provided (via the ClientConfig object), then no activity logging will take place. +// +//nolint:funlen func NewIssuerInitiatedInteraction( initiateIssuanceURI string, config *ClientConfig, @@ -413,13 +415,15 @@ func (i *IssuerInitiatedInteraction) getCredentialResponsesWithPreAuth( return i.getCredentialResponse(tokenResponse, tokenResponse.CNonce, signer, true) } +//nolint:funlen,gocyclo,nonamedreturns func (i *IssuerInitiatedInteraction) getCredentialResponse( tokenResponse *preAuthTokenResponse, nonce any, signer api.JWTSigner, allowRetry bool) ( credentialResponse []CredentialResponse, - err error) { + err error, +) { proofJWT, err := i.interaction.createClaimsProof(nonce, signer) if err != nil { return nil, err @@ -761,7 +765,7 @@ func determineCredentialParameters( func validateSignerKeyID(jwtSigner api.JWTSigner) error { kidParts := strings.Split(jwtSigner.GetKeyID(), "#") - if len(kidParts) < 2 { //nolint: gomnd + if len(kidParts) < 2 { //nolint: mnd return walleterror.NewExecutionError( ErrorModule, KeyIDMissingDIDPartCode, @@ -775,10 +779,10 @@ func validateSignerKeyID(jwtSigner api.JWTSigner) error { func getSubjectIDs(vcs []*verifiable.Credential) []string { var subjectIDs []string - for i := 0; i < len(vcs); i++ { + for i := range vcs { subjects := vcs[i].Contents().Subject - for j := 0; j < len(subjects); j++ { + for j := range subjects { subjectIDs = append(subjectIDs, subjects[j].ID) } } diff --git a/pkg/openid4ci/issuerinitiatedinteraction_test.go b/pkg/openid4ci/issuerinitiatedinteraction_test.go index 1526529c..0d6e7505 100644 --- a/pkg/openid4ci/issuerinitiatedinteraction_test.go +++ b/pkg/openid4ci/issuerinitiatedinteraction_test.go @@ -20,6 +20,7 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/trustbloc/did-go/doc/did" "github.com/trustbloc/did-go/doc/did/endpoint" @@ -107,7 +108,7 @@ func (m *mockIssuerServerHandler) ServeHTTP(writer http.ResponseWriter, request var credentialOfferBytes []byte credentialOfferBytes, err = json.Marshal(m.credentialOffer) - require.NoError(m.t, err) + assert.NoError(m.t, err) _, err = writer.Write(credentialOfferBytes) } @@ -176,10 +177,10 @@ func (m *mockIssuerServerHandler) ServeHTTP(writer http.ResponseWriter, request var payload map[string]interface{} err = json.NewDecoder(request.Body).Decode(&payload) - require.NoError(m.t, err) + assert.NoError(m.t, err) _, ok := payload["interaction_details"] - require.Equal(m.t, m.ackRequestExpectInteractionDetails, ok) + assert.Equal(m.t, m.ackRequestExpectInteractionDetails, ok) if m.ackRequestErrorResponse != "" { _, err = writer.Write([]byte(m.ackRequestErrorResponse)) @@ -188,7 +189,7 @@ func (m *mockIssuerServerHandler) ServeHTTP(writer http.ResponseWriter, request writer.WriteHeader(statusCode) } - require.NoError(m.t, err) + assert.NoError(m.t, err) } type failingMetricsLogger struct { @@ -209,6 +210,7 @@ func (f *failingMetricsLogger) Log(metricsEvent *api.MetricsEvent) error { func TestNewIssuerInitiatedInteraction(t *testing.T) { t.Run("Success", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t, credentialResponse: sampleCredentialResponse} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -492,11 +494,13 @@ type mockResolver struct { func (m *mockResolver) Resolve(string) (*did.DocResolution, error) { var services []did.Service + if m.linkedDomainsNumber == nil { one := 1 m.linkedDomainsNumber = &one } - for i := 0; i < *m.linkedDomainsNumber; i++ { + + for range *m.linkedDomainsNumber { services = append(services, did.Service{ ID: "#LinkedDomains", Type: "LinkedDomains", @@ -757,6 +761,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { } else { err = requestedAcknowledgment.AcknowledgeIssuer(openid4ci.EventStatusCredentialFailure, &http.Client{}) } + require.NoError(t, err) } @@ -1048,6 +1053,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, tokenRequestShouldFail: true, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1087,9 +1093,11 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { credentials, err := interaction.RequestCredentialWithPreAuth(&jwtSignerMock{ keyID: mockKeyID, }, openid4ci.WithPIN("1234")) + require.NoError(t, err) require.Len(t, credentials, 1) require.NotEmpty(t, credentials[0]) + _, err = interaction.Acknowledgment() require.ErrorContains(t, err, "issuer not support credential acknowledgement") @@ -1130,6 +1138,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { tokenRequestShouldFail: true, tokenRequestErrorResponse: `{"error":"invalid_request"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1153,6 +1162,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { tokenRequestShouldFail: true, tokenRequestErrorResponse: `{"error":"invalid_grant"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1175,6 +1185,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { tokenRequestShouldFail: true, tokenRequestErrorResponse: `{"error":"invalid_client"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1198,6 +1209,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { tokenRequestShouldFail: true, tokenRequestErrorResponse: `{"error":"someOtherErrorCode"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1220,6 +1232,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, tokenRequestShouldGiveUnmarshallableResponse: true, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1239,6 +1252,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t.Run("Fail to get credential response: server response body is not an errorResponse "+ "object", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t, credentialRequestShouldFail: true} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1260,6 +1274,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, credentialRequestShouldFail: true, credentialRequestErrorResponse: `{"error":"invalid_request"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1279,6 +1294,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { }) t.Run("Fail to get credential response: invalid proof error ", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t, credentialRequestShouldGiveInvalidProofResponse: true} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1300,6 +1316,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, credentialRequestShouldFail: true, credentialRequestErrorResponse: `{"error":"invalid_token"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1322,6 +1339,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, credentialRequestShouldFail: true, credentialRequestErrorResponse: `{"error":"unsupported_credential_format"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1344,6 +1362,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, credentialRequestShouldFail: true, credentialRequestErrorResponse: `{"error":"unsupported_credential_type"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1366,6 +1385,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, credentialRequestShouldFail: true, credentialRequestErrorResponse: `{"error":"invalid_or_missing_proof"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1388,6 +1408,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { t: t, credentialRequestShouldFail: true, credentialRequestErrorResponse: `{"error":"someOtherErrorCode"}`, } + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1407,6 +1428,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { }) t.Run("Fail to get credential response: signature error", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t, credentialRequestShouldFail: true} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1425,6 +1447,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { }) t.Run("Fail to reach issuer's credential endpoint", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1441,11 +1464,13 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { credentials, err := interaction.RequestCredentialWithPreAuth(&jwtSignerMock{ keyID: mockKeyID, }, openid4ci.WithPIN("1234")) + require.Contains(t, err.Error(), `Post "http://BadURL/oidc/credential": dial tcp: lookup BadURL`) require.Nil(t, credentials) }) t.Run("Fail to get credential response: KID does not contain the DID part", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1458,11 +1483,13 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { credentials, err := interaction.RequestCredentialWithPreAuth(&jwtSignerMock{ keyID: "did:example:12345", }, openid4ci.WithPIN("1234")) + testutil.RequireErrorContains(t, err, "KEY_ID_MISSING_DID_PART") require.Nil(t, credentials) }) t.Run("Fail to unmarshal response from issuer credential endpoint", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t, credentialRequestShouldGiveUnmarshallableResponse: true} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1488,6 +1515,7 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { require.NoError(t, err) issuerServerHandler := &mockIssuerServerHandler{t: t, credentialResponse: credentialResponseBytes} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1500,12 +1528,14 @@ func TestIssuerInitiatedInteraction_RequestCredential(t *testing.T) { credentials, err := interaction.RequestCredentialWithPreAuth(&jwtSignerMock{ keyID: mockKeyID, }, openid4ci.WithPIN("1234")) + require.Contains(t, err.Error(), "CREDENTIAL_PARSE_FAILED(OCI1-0007):failed to parse credential from "+ "credential response at index 0: unmarshal cbor cred after hex failed\nunmarshal cbor credential: EOF") require.Nil(t, credentials) }) t.Run("Fail VC proof check - public key not found for issuer DID", func(t *testing.T) { issuerServerHandler := &mockIssuerServerHandler{t: t, credentialResponse: sampleCredentialResponse} + server := httptest.NewServer(issuerServerHandler) defer server.Close() @@ -1993,7 +2023,7 @@ func TestIssuerInitiatedInteraction_RequestCredential_NoProofFound(t *testing.T) ) require.ErrorContains(t, err, "proof not found") - require.Len(t, credentials, 0) + require.Empty(t, credentials) } func TestIssuerInitiatedInteraction_GrantTypes(t *testing.T) { @@ -2210,7 +2240,9 @@ func enableVCProofChecks() clientConfigOpt { } } -func newIssuerInitiatedInteraction(t *testing.T, requestURI string, opts ...clientConfigOpt) *openid4ci.IssuerInitiatedInteraction { +func newIssuerInitiatedInteraction(t *testing.T, requestURI string, + opts ...clientConfigOpt, +) *openid4ci.IssuerInitiatedInteraction { t.Helper() config := getTestClientConfig(t) diff --git a/pkg/openid4ci/model_test.go b/pkg/openid4ci/model_test.go index b97c367b..0c7e0896 100644 --- a/pkg/openid4ci/model_test.go +++ b/pkg/openid4ci/model_test.go @@ -34,7 +34,7 @@ func TestCredentialResponse_SerializeToCredentialsBytes(t *testing.T) { } res, err := credRes.SerializeToCredentialsBytes() require.NoError(t, err) - require.Equal(t, "{\"fld1\":\"val1\",\"fld2\":\"val2\",\"fld3\":\"val3\"}", string(res)) + require.JSONEq(t, "{\"fld1\":\"val1\",\"fld2\":\"val2\",\"fld3\":\"val3\"}", string(res)) }) t.Run("Unsupported type", func(t *testing.T) { diff --git a/pkg/openid4ci/models.go b/pkg/openid4ci/models.go index 129120bf..5cf5bc2d 100644 --- a/pkg/openid4ci/models.go +++ b/pkg/openid4ci/models.go @@ -76,7 +76,7 @@ type CredentialResponse struct { // OPTIONAL. Contains issued Credential. // It MUST be present when transaction_id is not returned. // It MAY be a string or an object, depending on the Credential format. - // Deprecated. Use Credentials instead. + // Deprecated: Use Credentials instead. Credential interface{} `json:"credential,omitempty"` // OPTIONAL. String identifying a Deferred Issuance transaction. // This claim is contained in the response if the Credential Issuer was unable to immediately issue the Credential. @@ -195,6 +195,8 @@ type acknowledgementRequest struct { // InvalidProofError -- special type of error to handle case described in specification // https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#section-7.3.2 +// +//nolint:recvcheck type InvalidProofError struct { ParentError *walleterror.Error CNonce string diff --git a/pkg/openid4ci/walletinitiatedinteraction.go b/pkg/openid4ci/walletinitiatedinteraction.go index 432d9420..0035a683 100644 --- a/pkg/openid4ci/walletinitiatedinteraction.go +++ b/pkg/openid4ci/walletinitiatedinteraction.go @@ -122,7 +122,8 @@ func (i *WalletInitiatedInteraction) RequestCredential(jwtSigner api.JWTSigner, return nil, err } - return i.interaction.requestCredentialWithAuth(jwtSigner, []string{i.credentialFormat}, [][]string{i.credentialTypes}, [][]string{i.credentialContext}) + return i.interaction.requestCredentialWithAuth(jwtSigner, []string{i.credentialFormat}, + [][]string{i.credentialTypes}, [][]string{i.credentialContext}) } // DynamicClientRegistrationSupported indicates whether the issuer supports dynamic client registration. diff --git a/pkg/openid4vp/acknowledgment.go b/pkg/openid4vp/acknowledgment.go index a5feaa7a..dcfad7b8 100644 --- a/pkg/openid4vp/acknowledgment.go +++ b/pkg/openid4vp/acknowledgment.go @@ -22,9 +22,11 @@ const ( // AccessDeniedErrorResponse is returned in "error" of Authorization Error Response when no consent is provided or // no credentials match found. AccessDeniedErrorResponse = "access_denied" - // NoConsentErrorDescription is returned in "error_description" of Authorization Error Response when no consent is provided. + // NoConsentErrorDescription is returned in "error_description" of Authorization Error Response when + // no consent is provided. NoConsentErrorDescription = "no_consent" - // NoMatchFoundErrorDescription is returned in "error_description" of Authorization Error Response when no credentials match found. + // NoMatchFoundErrorDescription is returned in "error_description" of Authorization Error Response when + // no credentials match found. NoMatchFoundErrorDescription = "no_match_found" ) @@ -36,10 +38,10 @@ type Acknowledgment struct { } // AcknowledgeVerifier sends acknowledgment to the verifier. -func (a *Acknowledgment) AcknowledgeVerifier(error, desc string, httpClient httpClient) error { +func (a *Acknowledgment) AcknowledgeVerifier(errStr, desc string, httpClient httpClient) error { // https://openid.github.io/OpenID4VP/openid-4-verifiable-presentations-wg-draft.html#section-6.2-16 v := url.Values{} - v.Set("error", error) + v.Set("error", errStr) v.Set("error_description", desc) v.Set("state", a.State) diff --git a/pkg/openid4vp/openid4vp.go b/pkg/openid4vp/openid4vp.go index 3946985b..8cbdcf67 100644 --- a/pkg/openid4vp/openid4vp.go +++ b/pkg/openid4vp/openid4vp.go @@ -275,7 +275,7 @@ func (o *Interaction) PresentCredentialUnsafe(credential *verifiable.Credential, } // PresentCredential presents credentials to redirect uri from request object. -func (o *Interaction) presentCredentials( +func (o *Interaction) presentCredentials( //nolint: funlen credentials []*verifiable.Credential, customClaims CustomClaims, opts *presentOpts, @@ -412,6 +412,7 @@ func fetchRequestObject(authorizationRequestURL *url.URL, client httpClient, return string(respBytes), nil } +//nolint:gocyclo func parseRequestObject( authorizationRequestClientID string, rawRequestObject string, @@ -428,9 +429,7 @@ func parseRequestObject( } switch reqObject.ClientIDScheme { - case "": //TODO: For backward compatibility, remove this case in the future - fallthrough - case didScheme: + case "", didScheme: if reqObject.Issuer == "" { return nil, errors.New("iss claim in request object is required") } @@ -451,6 +450,7 @@ func parseRequestObject( if reqObject.PresentationDefinition == nil && reqObject.Claims.VPToken.PresentationDefinition != nil { reqObject.PresentationDefinition = reqObject.Claims.VPToken.PresentationDefinition } + if reqObject.ClientMetadata.VPFormats == nil && reqObject.Registration.VPFormats != nil { reqObject.ClientMetadata.ClientName = reqObject.Registration.ClientName reqObject.ClientMetadata.ClientPurpose = reqObject.Registration.ClientPurpose @@ -458,6 +458,7 @@ func parseRequestObject( reqObject.ClientMetadata.VPFormats = reqObject.Registration.VPFormats reqObject.ClientMetadata.SubjectSyntaxTypesSupported = reqObject.Registration.SubjectSyntaxTypesSupported } + if reqObject.ResponseURI == "" && reqObject.RedirectURI != "" { reqObject.ResponseURI = reqObject.RedirectURI } @@ -567,17 +568,20 @@ func createAuthorizedResponseOneCred( //nolint:funlen,gocyclo // Unable to decom } presentationSubmission := presentation.CustomFields["presentation_submission"] + presentationSubmissionBytes, err := json.Marshal(presentationSubmission) if err != nil { return nil, fmt.Errorf("marshal presentation submission: %w", err) } presentation.CustomFields = nil - presentation.ID = "urn:uuid:" + presentation.ID //TODO: Resolve this properly in the vc-go + + // TODO: Resolve this properly in the vc-go + presentation.ID = "urn:uuid:" + presentation.ID var vpToken string - switch vpFormat { + switch vpFormat { //nolint:dupl case presexch.FormatJWTVP: claims := vpTokenClaims{ VP: presentation, @@ -630,7 +634,7 @@ func createAuthorizedResponseOneCred( //nolint:funlen,gocyclo // Unable to decom }, nil } -func createAuthorizedResponseMultiCred( //nolint:funlen,gocyclo // Unable to decompose without a major reworking +func createAuthorizedResponseMultiCred( //nolint:funlen,gocyclo,gocognit credentials []*verifiable.Credential, requestObject *requestObject, customClaims CustomClaims, @@ -650,9 +654,11 @@ func createAuthorizedResponseMultiCred( //nolint:funlen,gocyclo // Unable to dec if vpFormats := requestObject.ClientMetadata.VPFormats; vpFormats != nil { isJWTCredential := false + for _, credential := range credentials { if credential.IsJWT() { isJWTCredential = true + break } } @@ -700,7 +706,7 @@ func createAuthorizedResponseMultiCred( //nolint:funlen,gocyclo // Unable to dec var vpToken string - switch vpFormat { + switch vpFormat { //nolint:dupl case presexch.FormatJWTVP: // TODO: Fix this issue: the vpToken always uses the last presentation from the loop above claims := vpTokenClaims{ @@ -719,7 +725,8 @@ func createAuthorizedResponseMultiCred( //nolint:funlen,gocyclo // Unable to dec return nil, fmt.Errorf("sign vp token: %w", err) } case presexch.FormatLDPVP: - vpToken, err = createLdpVPToken(crypto, documentLoader, didResolver, holderDID, assertionVM, requestObject, presentation) + vpToken, err = createLdpVPToken(crypto, documentLoader, didResolver, holderDID, assertionVM, requestObject, + presentation) if err != nil { return nil, fmt.Errorf("create ldp vp token: %w", err) } @@ -737,6 +744,7 @@ func createAuthorizedResponseMultiCred( //nolint:funlen,gocyclo // Unable to dec var idTokenJWS string + //nolint:nestif if strings.Contains(requestObject.ResponseType, "id_token") { var idTokenSigningDID string @@ -1071,8 +1079,7 @@ func processUsingMSEntraErrorResponseFormat(respBytes []byte, detailedErr error) } } -type emptyObj struct { -} +type emptyObj struct{} func copyJSONKeysOnly(obj interface{}) interface{} { empty := &emptyObj{} @@ -1089,6 +1096,7 @@ func copyJSONKeysOnly(obj interface{}) interface{} { case verifiable.CustomFields: newMap := make(map[string]interface{}) populateClaimKeys(newMap, jsonObj) + return newMap case []interface{}: newSlice := make([]interface{}, len(jsonObj)) diff --git a/pkg/openid4vp/openid4vp_test.go b/pkg/openid4vp/openid4vp_test.go index 611eb754..b1c5ed0b 100644 --- a/pkg/openid4vp/openid4vp_test.go +++ b/pkg/openid4vp/openid4vp_test.go @@ -315,7 +315,7 @@ func TestOpenID4VP_PresentCredential(t *testing.T) { require.NotNil(t, query) displayData := interaction.VerifierDisplayData() - require.NoError(t, err) + require.Equal(t, verifierDID, displayData.DID) require.Equal(t, "v_myprofile_jwt", displayData.Name) require.Equal(t, "test verifier", displayData.Purpose) @@ -347,9 +347,11 @@ func TestOpenID4VP_PresentCredential(t *testing.T) { require.NotContains(t, data, "interaction_details") var presentationSubmission *presexch.PresentationSubmission + require.NoError(t, json.Unmarshal([]byte(data["presentation_submission"][0]), &presentationSubmission)) var vpTokenList []string + require.NoError(t, json.Unmarshal([]byte(data["vp_token"][0]), &vpTokenList)) var presentations []*verifiable.Presentation @@ -597,7 +599,7 @@ func TestOpenID4VP_PresentCredential(t *testing.T) { ) require.NoError(t, err) - require.Equal(t, response.State, "test34566") + require.Equal(t, "test34566", response.State) idToken, err := base64.RawURLEncoding.DecodeString(strings.Split(response.IDTokenJWS, ".")[1]) require.NoError(t, err) @@ -668,7 +670,7 @@ func TestOpenID4VP_PresentCredential(t *testing.T) { ) require.NoError(t, err) - require.Equal(t, response.State, "test34566") + require.Equal(t, "test34566", response.State) }) t.Run("no credentials provided", func(t *testing.T) { @@ -724,9 +726,11 @@ func TestOpenID4VP_PresentCredential(t *testing.T) { for _, testCase := range testCases { t.Run("", func(t *testing.T) { var vcs []*verifiable.Credential + for _, vcc := range testCase.vc { vc, err := verifiable.CreateCredential(vcc, nil) require.NoError(t, err) + vcs = append(vcs, vc) } @@ -921,7 +925,8 @@ func TestOpenID4VP_PresentCredential(t *testing.T) { require.Error(t, err) var walletError *walleterror.Error - require.True(t, errors.As(err, &walletError)) + + require.ErrorAs(t, err, &walletError) require.Equal(t, MSEntraBadOrMissingFieldsError, walletError.Category) require.Equal(t, "message", walletError.Message) }) @@ -1089,7 +1094,7 @@ func TestOpenID4VP_PresentedClaims(t *testing.T) { require.NoError(t, presErr) require.NotNil(t, presentation) - var credentials, singleCred []*verifiable.Credential + var credentials []*verifiable.Credential var rawCreds []json.RawMessage @@ -1106,8 +1111,6 @@ func TestOpenID4VP_PresentedClaims(t *testing.T) { credentials = append(credentials, cred) } - singleCred = append(singleCred, credentials[0]) - mockDoc := mockResolution(t, mockDID, false) t.Run("Success", func(t *testing.T) { @@ -1129,7 +1132,7 @@ func TestOpenID4VP_PresentedClaims(t *testing.T) { require.NotNil(t, query) displayData := interaction.VerifierDisplayData() - require.NoError(t, err) + require.Equal(t, verifierDID, displayData.DID) require.Equal(t, "v_myprofile_jwt", displayData.Name) require.Equal(t, "test verifier", displayData.Purpose) @@ -1318,7 +1321,7 @@ func (c *cryptoMock) Verify(_, _ []byte, _ string) error { return c.VerifyErr } -func mockResolution(t *testing.T, mockDID string, useJWK bool) *did.DocResolution { +func mockResolution(t *testing.T, mockDID string, useJWK bool) *did.DocResolution { //nolint:unparam t.Helper() edPub, _, err := ed25519.GenerateKey(rand.Reader) diff --git a/pkg/openid4vp/opts.go b/pkg/openid4vp/opts.go index 086b7ea0..c07a4d63 100644 --- a/pkg/openid4vp/opts.go +++ b/pkg/openid4vp/opts.go @@ -9,8 +9,6 @@ package openid4vp import ( "net/http" - wrapperapi "github.com/trustbloc/kms-go/wrapper/api" - noopactivitylogger "github.com/trustbloc/wallet-sdk/pkg/activitylogger/noop" "github.com/trustbloc/wallet-sdk/pkg/api" noopmetricslogger "github.com/trustbloc/wallet-sdk/pkg/metricslogger/noop" @@ -20,9 +18,6 @@ type opts struct { httpClient httpClient activityLogger api.ActivityLogger metricsLogger api.MetricsLogger - // If both of the below fields are set, then data integrity proofs will be added to - // presentations sent to the verifier. - signer wrapperapi.KMSCryptoSigner } // An Opt is a single option for an OpenID4VP instance. diff --git a/pkg/trustregistry/trust_registry_test.go b/pkg/trustregistry/trust_registry_test.go index bd26559e..673e4b5b 100644 --- a/pkg/trustregistry/trust_registry_test.go +++ b/pkg/trustregistry/trust_registry_test.go @@ -51,7 +51,7 @@ func TestRegistry_EvaluateIssuance(t *testing.T) { require.NoError(t, err) require.NotNil(t, result) require.False(t, result.Allowed) - require.Equal(t, result.ErrorCode, "didForbidden") + require.Equal(t, "didForbidden", result.ErrorCode) }) t.Run("Invalid server URI", func(t *testing.T) { @@ -103,7 +103,7 @@ func TestRegistry_EvaluatePresentation(t *testing.T) { require.NoError(t, err) require.NotNil(t, result) require.False(t, result.Allowed) - require.Equal(t, result.ErrorCode, "didForbidden") + require.Equal(t, "didForbidden", result.ErrorCode) }) t.Run("Invalid server URI", func(t *testing.T) {