diff --git a/.golangci.yml b/.golangci.yml deleted file mode 100644 index af723230..00000000 --- a/.golangci.yml +++ /dev/null @@ -1,74 +0,0 @@ -linters-settings: - govet: - check-shadowing: true - settings: - printf: - funcs: - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf - revive: - min-confidence: 0 - gocyclo: - min-complexity: 10 - maligned: - suggest-new: true - dupl: - threshold: 100 - goconst: - min-len: 2 - min-occurrences: 2 - depguard: - list-type: blacklist - packages: - # logging is allowed only by logutils.Log, logrus - # is allowed to use only in logutils package - - github.com/sirupsen/logrus - misspell: - locale: US - lll: - line-length: 140 - goimports: - local-prefixes: github.com/golangci/golangci-lint - gocritic: - enabled-tags: - - performance - - style - - experimental - - diagnostic - disabled-checks: - - commentFormatting - - commentedOutCode - - evalOrder - - hugeParam - - octalLiteral - - rangeValCopy - - tooManyResultsChecker - - unnamedResult - -linters: - disable-all: true - enable: - - gocritic - - gofmt - - gosimple - - govet - - ineffassign - - misspell - - revive - - staticcheck - - unused - -run: - skip-dirs: - - pkg - -issues: - exclude: - - can't lint - - declaration of "err" shadows declaration at line - - should have a package comment, unless it's in another file for this package - - error strings should not be capitalized or end with punctuation or a newline - - Wrapf call needs 1 arg but has 2 args - - cs.NegotiatedProtocolIsMutual is deprecated diff --git a/Makefile b/Makefile index 906569f1..e4bece1d 100644 --- a/Makefile +++ b/Makefile @@ -29,7 +29,7 @@ ci: testcgo build bootstra%: # Using a released version of golangci-lint to take into account custom replacements in their go.mod - $Q curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.42.0 + $Q curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(shell go env GOPATH)/bin v1.48.0 .PHONY: bootstra% @@ -151,7 +151,7 @@ integration: bin/$(BINNAME) ######################################### fmt: - $Q gofmt -l -s -w $(SRC) + $Q goimports -local github.com/golangci/golangci-lint -l -w $(SRC) lint: $Q golangci-lint run --timeout=30m diff --git a/acme/account.go b/acme/account.go index 2dd412db..fa4b1167 100644 --- a/acme/account.go +++ b/acme/account.go @@ -33,7 +33,7 @@ func (a *Account) ToLog() (interface{}, error) { // IsValid returns true if the Account is valid. func (a *Account) IsValid() bool { - return Status(a.Status) == StatusValid + return a.Status == StatusValid } // KeyToID converts a JWK to a thumbprint. diff --git a/acme/account_test.go b/acme/account_test.go index edd1f5b0..88718a9a 100644 --- a/acme/account_test.go +++ b/acme/account_test.go @@ -46,14 +46,14 @@ func TestKeyToID(t *testing.T) { tc := run(t) if id, err := KeyToID(tc.jwk); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -131,12 +131,13 @@ func TestExternalAccountKey_BindTo(t *testing.T) { } if wantErr { assert.NotNil(t, err) - assert.Type(t, &Error{}, err) - ae, _ := err.(*Error) - assert.Equals(t, ae.Type, tt.err.Type) - assert.Equals(t, ae.Detail, tt.err.Detail) - assert.Equals(t, ae.Identifier, tt.err.Identifier) - assert.Equals(t, ae.Subproblems, tt.err.Subproblems) + var ae *Error + if assert.True(t, errors.As(err, &ae)) { + assert.Equals(t, ae.Type, tt.err.Type) + assert.Equals(t, ae.Detail, tt.err.Detail) + assert.Equals(t, ae.Identifier, tt.err.Identifier) + assert.Equals(t, ae.Subproblems, tt.err.Subproblems) + } } else { assert.Equals(t, eak.AccountID, acct.ID) assert.Equals(t, eak.HmacKey, []byte{}) diff --git a/acme/api/account.go b/acme/api/account.go index 710747ca..954cb9de 100644 --- a/acme/api/account.go +++ b/acme/api/account.go @@ -2,6 +2,7 @@ package api import ( "encoding/json" + "errors" "net/http" "github.com/go-chi/chi" @@ -97,8 +98,8 @@ func NewAccount(w http.ResponseWriter, r *http.Request) { httpStatus := http.StatusCreated acc, err := accountFromContext(ctx) if err != nil { - acmeErr, ok := err.(*acme.Error) - if !ok || acmeErr.Status != http.StatusBadRequest { + var acmeErr *acme.Error + if !errors.As(err, &acmeErr) || acmeErr.Status != http.StatusBadRequest { // Something went wrong ... render.Error(w, err) return diff --git a/acme/api/account_test.go b/acme/api/account_test.go index d74b5433..3f8641b8 100644 --- a/acme/api/account_test.go +++ b/acme/api/account_test.go @@ -197,11 +197,12 @@ func TestNewAccountRequest_Validate(t *testing.T) { t.Run(name, func(t *testing.T) { if err := tc.nar.Validate(); err != nil { if assert.NotNil(t, err) { - ae, ok := err.(*acme.Error) - assert.True(t, ok) - assert.HasPrefix(t, ae.Error(), tc.err.Error()) - assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) - assert.Equals(t, ae.Type, tc.err.Type) + var ae *acme.Error + if assert.True(t, errors.As(err, &ae)) { + assert.HasPrefix(t, ae.Error(), tc.err.Error()) + assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) + assert.Equals(t, ae.Type, tc.err.Type) + } } } else { assert.Nil(t, tc.err) @@ -268,11 +269,12 @@ func TestUpdateAccountRequest_Validate(t *testing.T) { t.Run(name, func(t *testing.T) { if err := tc.uar.Validate(); err != nil { if assert.NotNil(t, err) { - ae, ok := err.(*acme.Error) - assert.True(t, ok) - assert.HasPrefix(t, ae.Error(), tc.err.Error()) - assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) - assert.Equals(t, ae.Type, tc.err.Type) + var ae *acme.Error + if assert.True(t, errors.As(err, &ae)) { + assert.HasPrefix(t, ae.Error(), tc.err.Error()) + assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) + assert.Equals(t, ae.Type, tc.err.Type) + } } } else { assert.Nil(t, tc.err) diff --git a/acme/api/eab.go b/acme/api/eab.go index 4c4fff04..26854595 100644 --- a/acme/api/eab.go +++ b/acme/api/eab.go @@ -3,6 +3,7 @@ package api import ( "context" "encoding/json" + "errors" "go.step.sm/crypto/jose" @@ -24,6 +25,7 @@ func validateExternalAccountBinding(ctx context.Context, nar *NewAccountRequest) } if !acmeProv.RequireEAB { + //nolint:nilnil // legacy return nil, nil } @@ -51,7 +53,8 @@ func validateExternalAccountBinding(ctx context.Context, nar *NewAccountRequest) db := acme.MustDatabaseFromContext(ctx) externalAccountKey, err := db.GetExternalAccountKey(ctx, acmeProv.ID, keyID) if err != nil { - if _, ok := err.(*acme.Error); ok { + var ae *acme.Error + if errors.As(err, &ae) { return nil, acme.WrapError(acme.ErrorUnauthorizedType, err, "the field 'kid' references an unknown key") } return nil, acme.WrapErrorISE(err, "error retrieving external account key") diff --git a/acme/api/eab_test.go b/acme/api/eab_test.go index d2e596f9..c923a2f6 100644 --- a/acme/api/eab_test.go +++ b/acme/api/eab_test.go @@ -860,13 +860,15 @@ func TestHandler_validateExternalAccountBinding(t *testing.T) { if wantErr { assert.NotNil(t, err) assert.Type(t, &acme.Error{}, err) - ae, _ := err.(*acme.Error) - assert.Equals(t, ae.Type, tc.err.Type) - assert.Equals(t, ae.Status, tc.err.Status) - assert.HasPrefix(t, ae.Err.Error(), tc.err.Err.Error()) - assert.Equals(t, ae.Detail, tc.err.Detail) - assert.Equals(t, ae.Identifier, tc.err.Identifier) - assert.Equals(t, ae.Subproblems, tc.err.Subproblems) + var ae *acme.Error + if assert.True(t, errors.As(err, &ae)) { + assert.Equals(t, ae.Type, tc.err.Type) + assert.Equals(t, ae.Status, tc.err.Status) + assert.HasPrefix(t, ae.Err.Error(), tc.err.Err.Error()) + assert.Equals(t, ae.Detail, tc.err.Detail) + assert.Equals(t, ae.Identifier, tc.err.Identifier) + assert.Equals(t, ae.Subproblems, tc.err.Subproblems) + } } else { if got == nil { assert.Nil(t, tc.eak) diff --git a/acme/api/middleware_test.go b/acme/api/middleware_test.go index e43f6f99..faff0616 100644 --- a/acme/api/middleware_test.go +++ b/acme/api/middleware_test.go @@ -518,9 +518,6 @@ func TestHandler_verifyAndExtractJWSPayload(t *testing.T) { } }, "ok/empty-algorithm-in-jwk": func(t *testing.T) test { - _pub := *pub - clone := &_pub - clone.Algorithm = "" ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS) ctx = context.WithValue(ctx, jwkContextKey, pub) return test{ diff --git a/acme/api/order_test.go b/acme/api/order_test.go index b83dfc7c..e3f2f605 100644 --- a/acme/api/order_test.go +++ b/acme/api/order_test.go @@ -179,11 +179,12 @@ func TestNewOrderRequest_Validate(t *testing.T) { t.Run(name, func(t *testing.T) { if err := tc.nor.Validate(); err != nil { if assert.NotNil(t, err) { - ae, ok := err.(*acme.Error) - assert.True(t, ok) - assert.HasPrefix(t, ae.Error(), tc.err.Error()) - assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) - assert.Equals(t, ae.Type, tc.err.Type) + var ae *acme.Error + if assert.True(t, errors.As(err, &ae)) { + assert.HasPrefix(t, ae.Error(), tc.err.Error()) + assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) + assert.Equals(t, ae.Type, tc.err.Type) + } } } else { if assert.Nil(t, tc.err) { @@ -253,11 +254,12 @@ func TestFinalizeRequestValidate(t *testing.T) { t.Run(name, func(t *testing.T) { if err := tc.fr.Validate(); err != nil { if assert.NotNil(t, err) { - ae, ok := err.(*acme.Error) - assert.True(t, ok) - assert.HasPrefix(t, ae.Error(), tc.err.Error()) - assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) - assert.Equals(t, ae.Type, tc.err.Type) + var ae *acme.Error + if assert.True(t, errors.As(err, &ae)) { + assert.HasPrefix(t, ae.Error(), tc.err.Error()) + assert.Equals(t, ae.StatusCode(), tc.err.StatusCode()) + assert.Equals(t, ae.Type, tc.err.Type) + } } } else { if assert.Nil(t, tc.err) { @@ -761,14 +763,14 @@ func TestHandler_newAuthorization(t *testing.T) { ctx = acme.NewProvisionerContext(ctx, tc.prov) if err := newAuthorization(ctx, tc.az); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *acme.Error: + var k *acme.Error + if assert.True(t, errors.As(err, &k)) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } diff --git a/acme/authorization_test.go b/acme/authorization_test.go index 00b35b99..28aefe9f 100644 --- a/acme/authorization_test.go +++ b/acme/authorization_test.go @@ -130,14 +130,14 @@ func TestAuthorization_UpdateStatus(t *testing.T) { tc := run(t) if err := tc.az.UpdateStatus(context.Background(), tc.db); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } diff --git a/acme/challenge.go b/acme/challenge.go index 47c46490..84b3f83a 100644 --- a/acme/challenge.go +++ b/acme/challenge.go @@ -162,7 +162,7 @@ func tlsalpn01Validate(ctx context.Context, ch *Challenge, db DB, jwk *jose.JSON // [RFC5246] or higher when connecting to clients for validation. MinVersion: tls.VersionTLS12, ServerName: serverName(ch), - InsecureSkipVerify: true, // nolint:gosec // we expect a self-signed challenge certificate + InsecureSkipVerify: true, //nolint:gosec // we expect a self-signed challenge certificate } hostPort := net.JoinHostPort(ch.Value, "443") diff --git a/acme/challenge_test.go b/acme/challenge_test.go index 90aafa97..e452b175 100644 --- a/acme/challenge_test.go +++ b/acme/challenge_test.go @@ -188,14 +188,14 @@ func Test_storeError(t *testing.T) { tc := run(t) if err := storeError(context.Background(), tc.db, tc.ch, tc.markInvalid, err); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -243,14 +243,14 @@ func TestKeyAuthorization(t *testing.T) { tc := run(t) if ka, err := KeyAuthorization(tc.token, tc.jwk); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -533,14 +533,14 @@ func TestChallenge_Validate(t *testing.T) { ctx := NewClientContext(context.Background(), tc.vc) if err := tc.ch.Validate(ctx, tc.db, tc.jwk, nil); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -928,14 +928,14 @@ func TestHTTP01Validate(t *testing.T) { ctx := NewClientContext(context.Background(), tc.vc) if err := http01Validate(ctx, tc.ch, tc.db, tc.jwk); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -1228,14 +1228,14 @@ func TestDNS01Validate(t *testing.T) { ctx := NewClientContext(context.Background(), tc.vc) if err := dns01Validate(ctx, tc.ch, tc.db, tc.jwk); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -2298,14 +2298,14 @@ func TestTLSALPN01Validate(t *testing.T) { ctx := NewClientContext(context.Background(), tc.vc) if err := tlsalpn01Validate(ctx, tc.ch, tc.db, tc.jwk); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } diff --git a/acme/client.go b/acme/client.go index cf5f8c09..51560cb8 100644 --- a/acme/client.go +++ b/acme/client.go @@ -56,7 +56,7 @@ func NewClient() Client { Timeout: 30 * time.Second, Transport: &http.Transport{ TLSClientConfig: &tls.Config{ - // nolint:gosec // used on tls-alpn-01 challenge + //nolint:gosec // used on tls-alpn-01 challenge InsecureSkipVerify: true, // lgtm[go/disabled-certificate-check] }, }, diff --git a/acme/db/nosql/account_test.go b/acme/db/nosql/account_test.go index 83a23476..6097cc5a 100644 --- a/acme/db/nosql/account_test.go +++ b/acme/db/nosql/account_test.go @@ -95,16 +95,16 @@ func TestDB_getDBAccount(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if dbacc, err := d.getDBAccount(context.Background(), accID); err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -174,16 +174,16 @@ func TestDB_getAccountIDByKeyID(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if retAccID, err := d.getAccountIDByKeyID(context.Background(), kid); err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -248,16 +248,16 @@ func TestDB_GetAccount(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if acc, err := d.GetAccount(context.Background(), accID); err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -354,16 +354,16 @@ func TestDB_GetAccountByKeyID(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if acc, err := d.GetAccountByKeyID(context.Background(), kid); err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/acme/db/nosql/authz_test.go b/acme/db/nosql/authz_test.go index c41fabb5..c7d47eda 100644 --- a/acme/db/nosql/authz_test.go +++ b/acme/db/nosql/authz_test.go @@ -101,16 +101,16 @@ func TestDB_getDBAuthz(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if dbaz, err := d.getDBAuthz(context.Background(), azID); err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -295,16 +295,16 @@ func TestDB_GetAuthorization(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if az, err := d.GetAuthorization(context.Background(), azID); err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -745,16 +745,16 @@ func TestDB_GetAuthorizationsByAccountID(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if azs, err := d.GetAuthorizationsByAccountID(context.Background(), accountID); err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/acme/db/nosql/certificate.go b/acme/db/nosql/certificate.go index ee37c570..8f271ba5 100644 --- a/acme/db/nosql/certificate.go +++ b/acme/db/nosql/certificate.go @@ -138,5 +138,4 @@ func parseBundle(b []byte) ([]*x509.Certificate, error) { return nil, errors.New("error decoding PEM: unexpected data") } return bundle, nil - } diff --git a/acme/db/nosql/certificate_test.go b/acme/db/nosql/certificate_test.go index d64b3015..ba16a175 100644 --- a/acme/db/nosql/certificate_test.go +++ b/acme/db/nosql/certificate_test.go @@ -250,16 +250,16 @@ func TestDB_GetCertificate(t *testing.T) { d := DB{db: tc.db} cert, err := d.GetCertificate(context.Background(), certID) if err != nil { - switch k := err.(type) { - case *acme.Error: + var acmeErr *acme.Error + if errors.As(err, &acmeErr) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Type, tc.acmeErr.Type) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) + assert.Equals(t, acmeErr.Status, tc.acmeErr.Status) + assert.Equals(t, acmeErr.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, acmeErr.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -444,16 +444,16 @@ func TestDB_GetCertificateBySerial(t *testing.T) { d := DB{db: tc.db} cert, err := d.GetCertificateBySerial(context.Background(), serial) if err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/acme/db/nosql/challenge_test.go b/acme/db/nosql/challenge_test.go index 08c5a608..4eb815f5 100644 --- a/acme/db/nosql/challenge_test.go +++ b/acme/db/nosql/challenge_test.go @@ -94,16 +94,16 @@ func TestDB_getDBChallenge(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if ch, err := d.getDBChallenge(context.Background(), chID); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -286,16 +286,16 @@ func TestDB_GetChallenge(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if ch, err := d.GetChallenge(context.Background(), chID, azID); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/acme/db/nosql/eab.go b/acme/db/nosql/eab.go index e87aa9bc..e3651151 100644 --- a/acme/db/nosql/eab.go +++ b/acme/db/nosql/eab.go @@ -54,7 +54,6 @@ func (db *DB) getDBExternalAccountKey(ctx context.Context, id string) (*dbExtern // CreateExternalAccountKey creates a new External Account Binding key with a name func (db *DB) CreateExternalAccountKey(ctx context.Context, provisionerID, reference string) (*acme.ExternalAccountKey, error) { - externalAccountKeyMutex.Lock() defer externalAccountKeyMutex.Unlock() @@ -210,6 +209,7 @@ func (db *DB) GetExternalAccountKeyByReference(ctx context.Context, provisionerI defer externalAccountKeyMutex.RUnlock() if reference == "" { + //nolint:nilnil // legacy return nil, nil } @@ -228,6 +228,7 @@ func (db *DB) GetExternalAccountKeyByReference(ctx context.Context, provisionerI } func (db *DB) GetExternalAccountKeyByAccountID(ctx context.Context, provisionerID, accountID string) (*acme.ExternalAccountKey, error) { + //nolint:nilnil // legacy return nil, nil } @@ -371,7 +372,6 @@ func sliceIndex(slice []string, item string) int { // removeElement deletes the item if it exists in the // slice. It returns a new slice, keeping the old one intact. func removeElement(slice []string, item string) []string { - newSlice := make([]string, 0) index := sliceIndex(slice, item) if index < 0 { diff --git a/acme/db/nosql/eab_test.go b/acme/db/nosql/eab_test.go index 525afa72..51097911 100644 --- a/acme/db/nosql/eab_test.go +++ b/acme/db/nosql/eab_test.go @@ -93,16 +93,16 @@ func TestDB_getDBExternalAccountKey(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if dbeak, err := d.getDBExternalAccountKey(context.Background(), keyID); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -210,16 +210,16 @@ func TestDB_GetExternalAccountKey(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if eak, err := d.GetExternalAccountKey(context.Background(), provID, keyID); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -374,16 +374,16 @@ func TestDB_GetExternalAccountKeyByReference(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if eak, err := d.GetExternalAccountKeyByReference(context.Background(), provID, tc.ref); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -580,16 +580,16 @@ func TestDB_GetExternalAccountKeys(t *testing.T) { cursor, limit := "", 0 if eaks, nextCursor, err := d.GetExternalAccountKeys(context.Background(), provID, cursor, limit); err != nil { assert.Equals(t, "", nextCursor) - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.Equals(t, tc.err.Error(), err.Error()) } @@ -672,7 +672,7 @@ func TestDB_DeleteExternalAccountKey(t *testing.T) { return errors.New("force default") } }, - MCmpAndSwap: func(bucket, key, old, new []byte) ([]byte, bool, error) { + MCmpAndSwap: func(bucket, key, old, nu []byte) ([]byte, bool, error) { fmt.Println(string(bucket)) switch string(bucket) { case string(externalAccountKeyIDsByReferenceTable): @@ -882,16 +882,16 @@ func TestDB_DeleteExternalAccountKey(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if err := d.DeleteExternalAccountKey(context.Background(), provID, keyID); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.Equals(t, err.Error(), tc.err.Error()) } diff --git a/acme/db/nosql/nonce_test.go b/acme/db/nosql/nonce_test.go index 7dc5cc91..253731bf 100644 --- a/acme/db/nosql/nonce_test.go +++ b/acme/db/nosql/nonce_test.go @@ -146,16 +146,16 @@ func TestDB_DeleteNonce(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if err := d.DeleteNonce(context.Background(), acme.Nonce(nonceID)); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/acme/db/nosql/order_test.go b/acme/db/nosql/order_test.go index ff9396bd..cf22f094 100644 --- a/acme/db/nosql/order_test.go +++ b/acme/db/nosql/order_test.go @@ -102,16 +102,16 @@ func TestDB_getDBOrder(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if dbo, err := d.getDBOrder(context.Background(), orderID); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -206,16 +206,16 @@ func TestDB_GetOrder(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if o, err := d.GetOrder(context.Background(), orderID); err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -1003,16 +1003,16 @@ func TestDB_updateAddOrderIDs(t *testing.T) { } if err != nil { - switch k := err.(type) { - case *acme.Error: + var ae *acme.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.acmeErr) { - assert.Equals(t, k.Type, tc.acmeErr.Type) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) - assert.Equals(t, k.Status, tc.acmeErr.Status) - assert.Equals(t, k.Err.Error(), tc.acmeErr.Err.Error()) - assert.Equals(t, k.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Type, tc.acmeErr.Type) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) + assert.Equals(t, ae.Status, tc.acmeErr.Status) + assert.Equals(t, ae.Err.Error(), tc.acmeErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.acmeErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/acme/errors.go b/acme/errors.go index 34421500..c7c6c2cf 100644 --- a/acme/errors.go +++ b/acme/errors.go @@ -310,10 +310,11 @@ func NewErrorISE(msg string, args ...interface{}) *Error { // WrapError attempts to wrap the internal error. func WrapError(typ ProblemType, err error, msg string, args ...interface{}) *Error { - switch e := err.(type) { - case nil: + var e *Error + switch { + case err == nil: return nil - case *Error: + case errors.As(err, &e): if e.Err == nil { e.Err = errors.Errorf(msg+"; "+e.Detail, args...) } else { diff --git a/acme/order.go b/acme/order.go index 2eddad53..96c925f1 100644 --- a/acme/order.go +++ b/acme/order.go @@ -324,7 +324,6 @@ func numberOfIdentifierType(typ IdentifierType, ids []Identifier) int { // addresses or DNS names slice, depending on whether it can be parsed as an IP // or not. This might result in an additional SAN in the final certificate. func canonicalize(csr *x509.CertificateRequest) (canonicalized *x509.CertificateRequest) { - // for clarity only; we're operating on the same object by pointer canonicalized = csr diff --git a/acme/order_test.go b/acme/order_test.go index f1f28e40..606e9f71 100644 --- a/acme/order_test.go +++ b/acme/order_test.go @@ -247,14 +247,14 @@ func TestOrder_UpdateStatus(t *testing.T) { tc := run(t) if err := tc.o.UpdateStatus(context.Background(), tc.db); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -812,14 +812,14 @@ func TestOrder_Finalize(t *testing.T) { tc := run(t) if err := tc.o.Finalize(context.Background(), tc.db, tc.csr, tc.ca, tc.prov); err != nil { if assert.NotNil(t, tc.err) { - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tc.err.Type) assert.Equals(t, k.Detail, tc.err.Detail) assert.Equals(t, k.Status, tc.err.Status) assert.Equals(t, k.Err.Error(), tc.err.Err.Error()) assert.Equals(t, k.Detail, tc.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } } @@ -1474,14 +1474,14 @@ func TestOrder_sans(t *testing.T) { t.Errorf("Order.sans() = %v, want error; got none", got) return } - switch k := err.(type) { - case *Error: + var k *Error + if errors.As(err, &k) { assert.Equals(t, k.Type, tt.err.Type) assert.Equals(t, k.Detail, tt.err.Detail) assert.Equals(t, k.Status, tt.err.Status) assert.Equals(t, k.Err.Error(), tt.err.Err.Error()) assert.Equals(t, k.Detail, tt.err.Detail) - default: + } else { assert.FatalError(t, errors.New("unexpected error type")) } return diff --git a/api/api.go b/api/api.go index 75d26237..8bf7b209 100644 --- a/api/api.go +++ b/api/api.go @@ -3,7 +3,7 @@ package api import ( "context" "crypto" - "crypto/dsa" //nolint + "crypto/dsa" //nolint:staticcheck // support legacy algorithms "crypto/ecdsa" "crypto/ed25519" "crypto/rsa" diff --git a/api/log/log.go b/api/log/log.go index e5c8c45a..85891f82 100644 --- a/api/log/log.go +++ b/api/log/log.go @@ -21,6 +21,16 @@ type StackTracedError interface { StackTrace() errors.StackTrace } +// AsStackTracedError attempts to return the input error cast to a +// StackTracedError interface. +func AsStackTracedError(err error) (StackTracedError, bool) { + //nolint:errorlint // ignore type assertion warning. casting to interface is hard. + if st, ok := err.(StackTracedError); ok { + return st, ok + } + return nil, false +} + // Error adds to the response writer the given error if it implements // logging.ResponseLogger. If it does not implement it, then writes the error // using the log package. @@ -38,8 +48,9 @@ func Error(rw http.ResponseWriter, err error) { return } - e, ok := err.(StackTracedError) + e, ok := AsStackTracedError(err) if !ok { + //nolint:errorlint // ignore type assertion warning. casting to interface is hard. e, ok = errors.Cause(err).(StackTracedError) } diff --git a/api/read/read_test.go b/api/read/read_test.go index 72100584..e46e7f61 100644 --- a/api/read/read_test.go +++ b/api/read/read_test.go @@ -41,8 +41,8 @@ func TestJSON(t *testing.T) { } if tt.wantErr { - e, ok := err.(*errs.Error) - if ok { + var e *errs.Error + if errors.As(err, &e) { if code := e.StatusCode(); code != 400 { t.Errorf("error.StatusCode() = %v, wants 400", code) } @@ -102,14 +102,15 @@ func TestProtoJSON(t *testing.T) { } if tt.wantErr { - switch err.(type) { - case badProtoJSONError: + var ( + ee *errs.Error + bpe badProtoJSONError + ) + switch { + case errors.As(err, &bpe): assert.Contains(t, err.Error(), "syntax error") - case *errs.Error: - var ee *errs.Error - if errors.As(err, &ee) { - assert.Equal(t, http.StatusBadRequest, ee.Status) - } + case errors.As(err, &ee): + assert.Equal(t, http.StatusBadRequest, ee.Status) } return } diff --git a/api/render/render.go b/api/render/render.go index 9df4c791..33fabaeb 100644 --- a/api/render/render.go +++ b/api/render/render.go @@ -72,12 +72,22 @@ type RenderableError interface { Render(http.ResponseWriter) } +// AsRenderableError attempts to return an error type that implements the +// RenderableError interface. +func AsRenderableError(err error) (RenderableError, bool) { + //nolint:errorlint // ignore type assertion warning. casting to interface is hard. + if r, ok := err.(RenderableError); ok { + return r, true + } + return nil, false +} + // Error marshals the JSON representation of err to w. In case err implements // RenderableError its own Render method will be called instead. func Error(w http.ResponseWriter, err error) { log.Error(w, err) - if e, ok := err.(RenderableError); ok { + if e, ok := AsRenderableError(err); ok { e.Render(w) return @@ -97,6 +107,16 @@ type StatusCodedError interface { StatusCode() int } +// AsStatusCodedError attempts to return an error type that implements the +// StatusCodedError interface. +func AsStatusCodedError(err error) (StatusCodedError, bool) { + //nolint:errorlint // ignore type assertion warning. casting to interface is hard. + if sc, ok := err.(StatusCodedError); ok { + return sc, true + } + return nil, false +} + func statusCodeFromError(err error) (code int) { code = http.StatusInternalServerError @@ -105,12 +125,13 @@ func statusCodeFromError(err error) (code int) { } for err != nil { - if sc, ok := err.(StatusCodedError); ok { + if sc, ok := AsStatusCodedError(err); ok { code = sc.StatusCode() break } + //nolint:errorlint // ignore type assertion warning. casting to interface is hard. cause, ok := err.(causer) if !ok { break diff --git a/api/revoke_test.go b/api/revoke_test.go index 0955244e..763986b0 100644 --- a/api/revoke_test.go +++ b/api/revoke_test.go @@ -62,12 +62,12 @@ func TestRevokeRequestValidate(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { if err := tc.rr.Validate(); err != nil { - switch v := err.(type) { - case *errs.Error: - assert.HasPrefix(t, v.Error(), tc.err.Error()) - assert.Equals(t, v.StatusCode(), tc.err.Status) - default: - t.Errorf("unexpected error type: %T", v) + var ee *errs.Error + if errors.As(err, &ee) { + assert.HasPrefix(t, ee.Error(), tc.err.Error()) + assert.Equals(t, ee.StatusCode(), tc.err.Status) + } else { + t.Errorf("unexpected error type: %T", err) } } else { assert.Nil(t, tc.err) diff --git a/authority/admin/api/acme.go b/authority/admin/api/acme.go index db393e9a..0ce8d4d7 100644 --- a/authority/admin/api/acme.go +++ b/authority/admin/api/acme.go @@ -84,7 +84,6 @@ func (h *acmeAdminResponder) DeleteExternalAccountKey(w http.ResponseWriter, r * } func eakToLinked(k *acme.ExternalAccountKey) *linkedca.EABKey { - if k == nil { return nil } diff --git a/authority/admin/api/admin_test.go b/authority/admin/api/admin_test.go index ecb95244..3d4cdd9c 100644 --- a/authority/admin/api/admin_test.go +++ b/authority/admin/api/admin_test.go @@ -229,11 +229,13 @@ func TestCreateAdminRequest_Validate(t *testing.T) { if err != nil { assert.Type(t, &admin.Error{}, err) - adminErr, _ := err.(*admin.Error) - assert.Equals(t, tt.err.Type, adminErr.Type) - assert.Equals(t, tt.err.Detail, adminErr.Detail) - assert.Equals(t, tt.err.Status, adminErr.Status) - assert.Equals(t, tt.err.Message, adminErr.Message) + var adminErr *admin.Error + if assert.True(t, errors.As(err, &adminErr)) { + assert.Equals(t, tt.err.Type, adminErr.Type) + assert.Equals(t, tt.err.Detail, adminErr.Detail) + assert.Equals(t, tt.err.Status, adminErr.Status) + assert.Equals(t, tt.err.Message, adminErr.Message) + } } }) } @@ -278,11 +280,13 @@ func TestUpdateAdminRequest_Validate(t *testing.T) { if err != nil { assert.Type(t, &admin.Error{}, err) - adminErr, _ := err.(*admin.Error) - assert.Equals(t, tt.err.Type, adminErr.Type) - assert.Equals(t, tt.err.Detail, adminErr.Detail) - assert.Equals(t, tt.err.Status, adminErr.Status) - assert.Equals(t, tt.err.Message, adminErr.Message) + var ae *admin.Error + if assert.True(t, errors.As(err, &ae)) { + assert.Equals(t, tt.err.Type, ae.Type) + assert.Equals(t, tt.err.Detail, ae.Detail) + assert.Equals(t, tt.err.Status, ae.Status) + assert.Equals(t, tt.err.Message, ae.Message) + } } }) } diff --git a/authority/admin/api/middleware.go b/authority/admin/api/middleware.go index 780cfb65..3c1b040a 100644 --- a/authority/admin/api/middleware.go +++ b/authority/admin/api/middleware.go @@ -30,7 +30,6 @@ func requireAPIEnabled(next http.HandlerFunc) http.HandlerFunc { // extractAuthorizeTokenAdmin is a middleware that extracts and caches the bearer token. func extractAuthorizeTokenAdmin(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - tok := r.Header.Get("Authorization") if tok == "" { render.Error(w, admin.NewError(admin.ErrorUnauthorizedType, diff --git a/authority/admin/api/policy.go b/authority/admin/api/policy.go index a478c83c..89744893 100644 --- a/authority/admin/api/policy.go +++ b/authority/admin/api/policy.go @@ -50,7 +50,8 @@ func (par *policyAdminResponder) GetAuthorityPolicy(w http.ResponseWriter, r *ht auth := mustAuthority(ctx) authorityPolicy, err := auth.GetAuthorityPolicy(r.Context()) - if ae, ok := err.(*admin.Error); ok && !ae.IsType(admin.ErrorNotFoundType) { + var ae *admin.Error + if errors.As(err, &ae) && !ae.IsType(admin.ErrorNotFoundType) { render.Error(w, admin.WrapErrorISE(ae, "error retrieving authority policy")) return } @@ -74,7 +75,8 @@ func (par *policyAdminResponder) CreateAuthorityPolicy(w http.ResponseWriter, r auth := mustAuthority(ctx) authorityPolicy, err := auth.GetAuthorityPolicy(ctx) - if ae, ok := err.(*admin.Error); ok && !ae.IsType(admin.ErrorNotFoundType) { + var ae *admin.Error + if errors.As(err, &ae) && !ae.IsType(admin.ErrorNotFoundType) { render.Error(w, admin.WrapErrorISE(err, "error retrieving authority policy")) return } @@ -125,7 +127,8 @@ func (par *policyAdminResponder) UpdateAuthorityPolicy(w http.ResponseWriter, r auth := mustAuthority(ctx) authorityPolicy, err := auth.GetAuthorityPolicy(ctx) - if ae, ok := err.(*admin.Error); ok && !ae.IsType(admin.ErrorNotFoundType) { + var ae *admin.Error + if errors.As(err, &ae) && !ae.IsType(admin.ErrorNotFoundType) { render.Error(w, admin.WrapErrorISE(err, "error retrieving authority policy")) return } @@ -175,7 +178,8 @@ func (par *policyAdminResponder) DeleteAuthorityPolicy(w http.ResponseWriter, r auth := mustAuthority(ctx) authorityPolicy, err := auth.GetAuthorityPolicy(ctx) - if ae, ok := err.(*admin.Error); ok && !ae.IsType(admin.ErrorNotFoundType) { + var ae *admin.Error + if errors.As(err, &ae) && !ae.IsType(admin.ErrorNotFoundType) { render.Error(w, admin.WrapErrorISE(ae, "error retrieving authority policy")) return } @@ -468,7 +472,6 @@ func isBadRequest(err error) bool { } func validatePolicy(p *linkedca.Policy) error { - // convert the policy; return early if nil options := policy.LinkedToCertificates(p) if options == nil { diff --git a/authority/admin/db/nosql/admin.go b/authority/admin/db/nosql/admin.go index 6bb6bdd1..c0f90c2f 100644 --- a/authority/admin/db/nosql/admin.go +++ b/authority/admin/db/nosql/admin.go @@ -111,14 +111,14 @@ func (db *DB) GetAdmins(ctx context.Context) ([]*linkedca.Admin, error) { for _, entry := range dbEntries { adm, err := db.unmarshalAdmin(entry.Value, string(entry.Key)) if err != nil { - switch k := err.(type) { - case *admin.Error: - if k.IsType(admin.ErrorDeletedType) || k.IsType(admin.ErrorAuthorityMismatchType) { + var ae *admin.Error + if errors.As(err, &ae) { + if ae.IsType(admin.ErrorDeletedType) || ae.IsType(admin.ErrorAuthorityMismatchType) { continue } else { return nil, err } - default: + } else { return nil, err } } diff --git a/authority/admin/db/nosql/admin_test.go b/authority/admin/db/nosql/admin_test.go index 2631b68c..9961d7f5 100644 --- a/authority/admin/db/nosql/admin_test.go +++ b/authority/admin/db/nosql/admin_test.go @@ -68,16 +68,16 @@ func TestDB_getDBAdminBytes(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if b, err := d.getDBAdminBytes(context.Background(), adminID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -192,16 +192,16 @@ func TestDB_getDBAdmin(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if dba, err := d.getDBAdmin(context.Background(), adminID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -280,16 +280,16 @@ func TestDB_unmarshalDBAdmin(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{authorityID: admin.DefaultAuthorityID} if dba, err := d.unmarshalDBAdmin(tc.in, adminID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -355,16 +355,16 @@ func TestDB_unmarshalAdmin(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{authorityID: admin.DefaultAuthorityID} if adm, err := d.unmarshalAdmin(tc.in, adminID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -509,16 +509,16 @@ func TestDB_GetAdmin(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if adm, err := d.GetAdmin(context.Background(), adminID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -661,16 +661,16 @@ func TestDB_DeleteAdmin(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if err := d.DeleteAdmin(context.Background(), adminID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -812,16 +812,16 @@ func TestDB_UpdateAdmin(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if err := d.UpdateAdmin(context.Background(), tc.adm); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -910,16 +910,16 @@ func TestDB_CreateAdmin(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if err := d.CreateAdmin(context.Background(), tc.adm); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -1086,16 +1086,16 @@ func TestDB_GetAdmins(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if admins, err := d.GetAdmins(context.Background()); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/authority/admin/db/nosql/policy.go b/authority/admin/db/nosql/policy.go index d4f2e9f9..3023a3f6 100644 --- a/authority/admin/db/nosql/policy.go +++ b/authority/admin/db/nosql/policy.go @@ -83,6 +83,7 @@ func (db *DB) getDBAuthorityPolicyBytes(ctx context.Context, authorityID string) func (db *DB) unmarshalDBAuthorityPolicy(data []byte) (*dbAuthorityPolicy, error) { if len(data) == 0 { + //nolint:nilnil // legacy return nil, nil } var dba = new(dbAuthorityPolicy) @@ -102,6 +103,7 @@ func (db *DB) getDBAuthorityPolicy(ctx context.Context, authorityID string) (*db return nil, err } if dbap == nil { + //nolint:nilnil // legacy return nil, nil } if dbap.AuthorityID != authorityID { @@ -112,7 +114,6 @@ func (db *DB) getDBAuthorityPolicy(ctx context.Context, authorityID string) (*db } func (db *DB) CreateAuthorityPolicy(ctx context.Context, policy *linkedca.Policy) error { - dbap := &dbAuthorityPolicy{ ID: db.authorityID, AuthorityID: db.authorityID, @@ -228,7 +229,6 @@ func dbToLinked(p *dbPolicy) *linkedca.Policy { } func linkedToDB(p *linkedca.Policy) *dbPolicy { - if p == nil { return nil } diff --git a/authority/admin/db/nosql/policy_test.go b/authority/admin/db/nosql/policy_test.go index 3ffded6b..84f02a1d 100644 --- a/authority/admin/db/nosql/policy_test.go +++ b/authority/admin/db/nosql/policy_test.go @@ -72,16 +72,16 @@ func TestDB_getDBAuthorityPolicyBytes(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if b, err := d.getDBAuthorityPolicyBytes(tc.ctx, tc.authorityID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -208,16 +208,16 @@ func TestDB_getDBAuthorityPolicy(t *testing.T) { dbp, err := d.getDBAuthorityPolicy(tc.ctx, tc.authorityID) switch { case err != nil: - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -309,16 +309,16 @@ func TestDB_CreateAuthorityPolicy(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: tc.authorityID} if err := d.CreateAuthorityPolicy(tc.ctx, tc.policy); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -406,16 +406,16 @@ func TestDB_GetAuthorityPolicy(t *testing.T) { d := DB{db: tc.db, authorityID: tc.authorityID} got, err := d.GetAuthorityPolicy(tc.ctx) if err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -578,16 +578,16 @@ func TestDB_UpdateAuthorityPolicy(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: tc.authorityID} if err := d.UpdateAuthorityPolicy(tc.ctx, tc.policy); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -718,16 +718,16 @@ func TestDB_DeleteAuthorityPolicy(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: tc.authorityID} if err := d.DeleteAuthorityPolicy(tc.ctx); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/authority/admin/db/nosql/provisioner.go b/authority/admin/db/nosql/provisioner.go index 71d9c8d6..c82d4afe 100644 --- a/authority/admin/db/nosql/provisioner.go +++ b/authority/admin/db/nosql/provisioner.go @@ -122,14 +122,14 @@ func (db *DB) GetProvisioners(ctx context.Context) ([]*linkedca.Provisioner, err for _, entry := range dbEntries { prov, err := db.unmarshalProvisioner(entry.Value, string(entry.Key)) if err != nil { - switch k := err.(type) { - case *admin.Error: - if k.IsType(admin.ErrorDeletedType) || k.IsType(admin.ErrorAuthorityMismatchType) { + var ae *admin.Error + if errors.As(err, &ae) { + if ae.IsType(admin.ErrorDeletedType) || ae.IsType(admin.ErrorAuthorityMismatchType) { continue } else { return nil, err } - default: + } else { return nil, err } } diff --git a/authority/admin/db/nosql/provisioner_test.go b/authority/admin/db/nosql/provisioner_test.go index a399558a..c5caf696 100644 --- a/authority/admin/db/nosql/provisioner_test.go +++ b/authority/admin/db/nosql/provisioner_test.go @@ -67,16 +67,16 @@ func TestDB_getDBProvisionerBytes(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db} if b, err := d.getDBProvisionerBytes(context.Background(), provID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -189,16 +189,16 @@ func TestDB_getDBProvisioner(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if dbp, err := d.getDBProvisioner(context.Background(), provID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -275,16 +275,16 @@ func TestDB_unmarshalDBProvisioner(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{authorityID: admin.DefaultAuthorityID} if dbp, err := d.unmarshalDBProvisioner(tc.in, provID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -397,16 +397,16 @@ func TestDB_unmarshalProvisioner(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{authorityID: admin.DefaultAuthorityID} if prov, err := d.unmarshalProvisioner(tc.in, provID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -535,16 +535,16 @@ func TestDB_GetProvisioner(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if prov, err := d.GetProvisioner(context.Background(), provID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -683,16 +683,16 @@ func TestDB_DeleteProvisioner(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if err := d.DeleteProvisioner(context.Background(), provID); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -844,16 +844,16 @@ func TestDB_GetProvisioners(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if provs, err := d.GetProvisioners(context.Background()); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -952,16 +952,16 @@ func TestDB_CreateProvisioner(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if err := d.CreateProvisioner(context.Background(), tc.prov); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } @@ -1188,16 +1188,16 @@ func TestDB_UpdateProvisioner(t *testing.T) { t.Run(name, func(t *testing.T) { d := DB{db: tc.db, authorityID: admin.DefaultAuthorityID} if err := d.UpdateProvisioner(context.Background(), tc.prov); err != nil { - switch k := err.(type) { - case *admin.Error: + var ae *admin.Error + if errors.As(err, &ae) { if assert.NotNil(t, tc.adminErr) { - assert.Equals(t, k.Type, tc.adminErr.Type) - assert.Equals(t, k.Detail, tc.adminErr.Detail) - assert.Equals(t, k.Status, tc.adminErr.Status) - assert.Equals(t, k.Err.Error(), tc.adminErr.Err.Error()) - assert.Equals(t, k.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Type, tc.adminErr.Type) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) + assert.Equals(t, ae.Status, tc.adminErr.Status) + assert.Equals(t, ae.Err.Error(), tc.adminErr.Err.Error()) + assert.Equals(t, ae.Detail, tc.adminErr.Detail) } - default: + } else { if assert.NotNil(t, tc.err) { assert.HasPrefix(t, err.Error(), tc.err.Error()) } diff --git a/authority/admin/errors.go b/authority/admin/errors.go index 2cf0c0e5..c729c8b2 100644 --- a/authority/admin/errors.go +++ b/authority/admin/errors.go @@ -156,16 +156,17 @@ func NewErrorISE(msg string, args ...interface{}) *Error { // WrapError attempts to wrap the internal error. func WrapError(typ ProblemType, err error, msg string, args ...interface{}) *Error { - switch e := err.(type) { - case nil: + var ee *Error + switch { + case err == nil: return nil - case *Error: - if e.Err == nil { - e.Err = errors.Errorf(msg+"; "+e.Detail, args...) + case errors.As(err, &ee): + if ee.Err == nil { + ee.Err = errors.Errorf(msg+"; "+ee.Detail, args...) } else { - e.Err = errors.Wrapf(e.Err, msg, args...) + ee.Err = errors.Wrapf(ee.Err, msg, args...) } - return e + return ee default: return newError(typ, errors.Wrapf(err, msg, args...)) } diff --git a/authority/authority.go b/authority/authority.go index 73aa9cca..295c6413 100644 --- a/authority/authority.go +++ b/authority/authority.go @@ -368,7 +368,7 @@ func (a *Authority) init() error { } options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{ SigningKey: a.config.IntermediateKey, - Password: []byte(a.password), + Password: a.password, }) if err != nil { return err @@ -434,7 +434,7 @@ func (a *Authority) init() error { if a.config.SSH.HostKey != "" { signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{ SigningKey: a.config.SSH.HostKey, - Password: []byte(a.sshHostPassword), + Password: a.sshHostPassword, }) if err != nil { return err @@ -460,7 +460,7 @@ func (a *Authority) init() error { if a.config.SSH.UserKey != "" { signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{ SigningKey: a.config.SSH.UserKey, - Password: []byte(a.sshUserPassword), + Password: a.sshUserPassword, }) if err != nil { return err @@ -545,7 +545,7 @@ func (a *Authority) init() error { options.CertificateChain = append(options.CertificateChain, a.rootX509Certs...) options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{ SigningKey: a.config.IntermediateKey, - Password: []byte(a.password), + Password: a.password, }) if err != nil { return err @@ -554,7 +554,7 @@ func (a *Authority) init() error { if km, ok := a.keyManager.(kmsapi.Decrypter); ok { options.Decrypter, err = km.CreateDecrypter(&kmsapi.CreateDecrypterRequest{ DecryptionKey: a.config.IntermediateKey, - Password: []byte(a.password), + Password: a.password, }) if err != nil { return err diff --git a/authority/authorize.go b/authority/authorize.go index 8f916e1d..44956cbd 100644 --- a/authority/authorize.go +++ b/authority/authorize.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/pkg/errors" "github.com/smallstep/certificates/authority/admin" "github.com/smallstep/certificates/authority/provisioner" "github.com/smallstep/certificates/errs" @@ -416,16 +417,16 @@ func (a *Authority) AuthorizeRenewToken(ctx context.Context, ott string) (*x509. Subject: leaf.Subject.CommonName, Time: time.Now().UTC(), }, time.Minute); err != nil { - switch err { - case jose.ErrInvalidIssuer: + switch { + case errors.Is(err, jose.ErrInvalidIssuer): return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid issuer claim (iss)")) - case jose.ErrInvalidSubject: + case errors.Is(err, jose.ErrInvalidSubject): return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: invalid subject claim (sub)")) - case jose.ErrNotValidYet: + case errors.Is(err, jose.ErrNotValidYet): return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token not valid yet (nbf)")) - case jose.ErrExpired: + case errors.Is(err, jose.ErrExpired): return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token is expired (exp)")) - case jose.ErrIssuedInTheFuture: + case errors.Is(err, jose.ErrIssuedInTheFuture): return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token: token issued in the future (iat)")) default: return nil, errs.UnauthorizedErr(err, errs.WithMessage("error validating renew token")) diff --git a/authority/authorize_test.go b/authority/authorize_test.go index af80d3d3..c5ca4a77 100644 --- a/authority/authorize_test.go +++ b/authority/authorize_test.go @@ -313,7 +313,7 @@ func TestAuthority_authorizeToken(t *testing.T) { p, err := tc.auth.authorizeToken(context.Background(), tc.token) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -399,7 +399,7 @@ func TestAuthority_authorizeRevoke(t *testing.T) { if err := tc.auth.authorizeRevoke(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -484,7 +484,7 @@ func TestAuthority_authorizeSign(t *testing.T) { got, err := tc.auth.authorizeSign(context.Background(), tc.token) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -743,13 +743,13 @@ func TestAuthority_Authorize(t *testing.T) { if err != nil { if assert.NotNil(t, tc.err, fmt.Sprintf("unexpected error: %s", err)) { assert.Nil(t, got) - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) - ctxErr, ok := err.(*errs.Error) - assert.Fatal(t, ok, "error is not of type *errs.Error") + var ctxErr *errs.Error + assert.Fatal(t, errors.As(err, &ctxErr), "error is not of type *errs.Error") assert.Equals(t, ctxErr.Details["token"], tc.token) } } else { @@ -879,13 +879,13 @@ func TestAuthority_authorizeRenew(t *testing.T) { err := tc.auth.authorizeRenew(tc.cert) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCoder interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) - ctxErr, ok := err.(*errs.Error) - assert.Fatal(t, ok, "error is not of type *errs.Error") + var ctxErr *errs.Error + assert.Fatal(t, errors.As(err, &ctxErr), "error is not of type *errs.Error") assert.Equals(t, ctxErr.Details["serialNumber"], tc.cert.SerialNumber.String()) } } else { @@ -1027,7 +1027,7 @@ func TestAuthority_authorizeSSHSign(t *testing.T) { got, err := tc.auth.authorizeSSHSign(context.Background(), tc.token) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -1144,7 +1144,7 @@ func TestAuthority_authorizeSSHRenew(t *testing.T) { got, err := tc.auth.authorizeSSHRenew(context.Background(), tc.token) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -1244,7 +1244,7 @@ func TestAuthority_authorizeSSHRevoke(t *testing.T) { if err := tc.auth.authorizeSSHRevoke(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -1337,7 +1337,7 @@ func TestAuthority_authorizeSSHRekey(t *testing.T) { cert, signOpts, err := tc.auth.authorizeSSHRekey(context.Background(), tc.token) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/config/tls_options.go b/authority/config/tls_options.go index 01ab3d0a..5ef6c894 100644 --- a/authority/config/tls_options.go +++ b/authority/config/tls_options.go @@ -169,7 +169,7 @@ func (t *TLSOptions) TLSConfig() *tls.Config { rs = tls.RenegotiateNever } - // nolint:gosec // default MinVersion 1.2, if defined but empty 1.3 is used + //nolint:gosec // default MinVersion 1.2, if defined but empty 1.3 is used return &tls.Config{ CipherSuites: t.CipherSuites.Value(), MinVersion: t.MinVersion.Value(), diff --git a/authority/linkedca.go b/authority/linkedca.go index 133ae616..7179b1d7 100644 --- a/authority/linkedca.go +++ b/authority/linkedca.go @@ -461,7 +461,7 @@ func getRootCertificate(endpoint, fingerprint string) (*x509.Certificate, error) defer cancel() conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{ - // nolint:gosec // used in bootstrap protocol + //nolint:gosec // used in bootstrap protocol InsecureSkipVerify: true, // lgtm[go/disabled-certificate-check] }))) if err != nil { diff --git a/authority/policy.go b/authority/policy.go index 258873af..d3078e10 100644 --- a/authority/policy.go +++ b/authority/policy.go @@ -119,7 +119,6 @@ func (a *Authority) RemoveAuthorityPolicy(ctx context.Context) error { } func (a *Authority) checkAuthorityPolicy(ctx context.Context, currentAdmin *linkedca.Admin, p *linkedca.Policy) error { - // no policy and thus nothing to evaluate; return early if p == nil { return nil @@ -138,7 +137,6 @@ func (a *Authority) checkAuthorityPolicy(ctx context.Context, currentAdmin *link } func (a *Authority) checkProvisionerPolicy(ctx context.Context, provName string, p *linkedca.Policy) error { - // no policy and thus nothing to evaluate; return early if p == nil { return nil @@ -157,7 +155,6 @@ func (a *Authority) checkProvisionerPolicy(ctx context.Context, provName string, // checkPolicy checks if a new or updated policy configuration results in the user // locking themselves or other admins out of the CA. func (a *Authority) checkPolicy(ctx context.Context, currentAdmin *linkedca.Admin, otherAdmins []*linkedca.Admin, p *linkedca.Policy) error { - // convert the policy; return early if nil policyOptions := authPolicy.LinkedToCertificates(p) if policyOptions == nil { @@ -216,7 +213,6 @@ func (a *Authority) reloadPolicyEngines(ctx context.Context) error { ) if a.config.AuthorityConfig.EnableAdmin { - // temporarily disable policy loading when LinkedCA is in use if _, ok := a.adminDB.(*linkedCaClient); ok { return nil diff --git a/authority/policy/engine.go b/authority/policy/engine.go index 4b21f66b..d3881d9b 100644 --- a/authority/policy/engine.go +++ b/authority/policy/engine.go @@ -17,9 +17,9 @@ type Engine struct { // New returns a new Engine using Options. func New(options *Options) (*Engine, error) { - // if no options provided, return early if options == nil { + //nolint:nilnil // legacy return nil, nil } @@ -56,7 +56,6 @@ func New(options *Options) (*Engine, error) { // the X.509 policy (if available) and returns an error if one of the // names in the certificate is not allowed. func (e *Engine) IsX509CertificateAllowed(cert *x509.Certificate) error { - // return early if there's no policy to evaluate if e == nil || e.x509Policy == nil { return nil @@ -69,7 +68,6 @@ func (e *Engine) IsX509CertificateAllowed(cert *x509.Certificate) error { // AreSANsAllowed evaluates the slice of SANs against the X.509 policy // (if available) and returns an error if one of the SANs is not allowed. func (e *Engine) AreSANsAllowed(sans []string) error { - // return early if there's no policy to evaluate if e == nil || e.x509Policy == nil { return nil @@ -83,7 +81,6 @@ func (e *Engine) AreSANsAllowed(sans []string) error { // user or host policy (if configured) and returns an error if one of the // principals in the certificate is not allowed. func (e *Engine) IsSSHCertificateAllowed(cert *ssh.Certificate) error { - // return early if there's no policy to evaluate if e == nil || (e.sshHostPolicy == nil && e.sshUserPolicy == nil) { return nil diff --git a/authority/policy/policy.go b/authority/policy/policy.go index 3c53b704..96c7d7ea 100644 --- a/authority/policy/policy.go +++ b/authority/policy/policy.go @@ -19,7 +19,6 @@ type HostPolicy policy.SSHNamePolicyEngine // NewX509PolicyEngine creates a new x509 name policy engine func NewX509PolicyEngine(policyOptions X509PolicyOptionsInterface) (X509Policy, error) { - // return early if no policy engine options to configure if policyOptions == nil { return nil, nil @@ -92,7 +91,6 @@ func NewSSHHostPolicyEngine(policyOptions SSHPolicyOptionsInterface) (HostPolicy // newSSHPolicyEngine creates a new SSH name policy engine func newSSHPolicyEngine(policyOptions SSHPolicyOptionsInterface, typ sshPolicyEngineType) (policy.SSHNamePolicyEngine, error) { - // return early if no policy engine options to configure if policyOptions == nil { return nil, nil @@ -143,7 +141,6 @@ func newSSHPolicyEngine(policyOptions SSHPolicyOptionsInterface, typ sshPolicyEn } func LinkedToCertificates(p *linkedca.Policy) *Options { - // return early if p == nil { return nil diff --git a/authority/policy_test.go b/authority/policy_test.go index 1dccf0d1..8e2e0df4 100644 --- a/authority/policy_test.go +++ b/authority/policy_test.go @@ -185,11 +185,11 @@ func TestAuthority_checkPolicy(t *testing.T) { } else { assert.IsType(t, &PolicyError{}, err) - pe, ok := err.(*PolicyError) - assert.True(t, ok) - - assert.Equal(t, tc.err.Typ, pe.Typ) - assert.Equal(t, tc.err.Error(), pe.Error()) + var pe *PolicyError + if assert.True(t, errors.As(err, &pe)) { + assert.Equal(t, tc.err.Typ, pe.Typ) + assert.Equal(t, tc.err.Error(), pe.Error()) + } } }) } @@ -1179,10 +1179,11 @@ func TestAuthority_RemoveAuthorityPolicy(t *testing.T) { } err := a.RemoveAuthorityPolicy(tt.args.ctx) if err != nil { - pe, ok := err.(*PolicyError) - assert.True(t, ok) - assert.Equal(t, tt.wantErr.Typ, pe.Typ) - assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + var pe *PolicyError + if assert.True(t, errors.As(err, &pe)) { + assert.Equal(t, tt.wantErr.Typ, pe.Typ) + assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + } return } }) @@ -1250,10 +1251,11 @@ func TestAuthority_GetAuthorityPolicy(t *testing.T) { } got, err := a.GetAuthorityPolicy(tt.args.ctx) if err != nil { - pe, ok := err.(*PolicyError) - assert.True(t, ok) - assert.Equal(t, tt.wantErr.Typ, pe.Typ) - assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + var pe *PolicyError + if assert.True(t, errors.As(err, &pe)) { + assert.Equal(t, tt.wantErr.Typ, pe.Typ) + assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + } return } if !reflect.DeepEqual(got, tt.want) { @@ -1429,10 +1431,11 @@ func TestAuthority_CreateAuthorityPolicy(t *testing.T) { } got, err := a.CreateAuthorityPolicy(tt.args.ctx, tt.args.adm, tt.args.p) if err != nil { - pe, ok := err.(*PolicyError) - assert.True(t, ok) - assert.Equal(t, tt.wantErr.Typ, pe.Typ) - assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + var pe *PolicyError + if assert.True(t, errors.As(err, &pe)) { + assert.Equal(t, tt.wantErr.Typ, pe.Typ) + assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + } return } if !reflect.DeepEqual(got, tt.want) { @@ -1611,10 +1614,11 @@ func TestAuthority_UpdateAuthorityPolicy(t *testing.T) { } got, err := a.UpdateAuthorityPolicy(tt.args.ctx, tt.args.adm, tt.args.p) if err != nil { - pe, ok := err.(*PolicyError) - assert.True(t, ok) - assert.Equal(t, tt.wantErr.Typ, pe.Typ) - assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + var pe *PolicyError + if assert.True(t, errors.As(err, &pe)) { + assert.Equal(t, tt.wantErr.Typ, pe.Typ) + assert.Equal(t, tt.wantErr.Err.Error(), pe.Err.Error()) + } return } if !reflect.DeepEqual(got, tt.want) { diff --git a/authority/provisioner/acme.go b/authority/provisioner/acme.go index 5955ac6a..a8741a05 100644 --- a/authority/provisioner/acme.go +++ b/authority/provisioner/acme.go @@ -217,7 +217,6 @@ type ACMEIdentifier struct { // AuthorizeOrderIdentifier verifies the provisioner is allowed to issue a // certificate for an ACME Order Identifier. func (p *ACME) AuthorizeOrderIdentifier(ctx context.Context, identifier ACMEIdentifier) error { - x509Policy := p.ctl.getPolicy().getX509() // identifier is allowed if no policy is configured diff --git a/authority/provisioner/acme_test.go b/authority/provisioner/acme_test.go index bfd85303..551a6d62 100644 --- a/authority/provisioner/acme_test.go +++ b/authority/provisioner/acme_test.go @@ -224,7 +224,7 @@ func TestACME_AuthorizeRenew(t *testing.T) { t.Run(name, func(t *testing.T) { tc := tt(t) if err := tc.p.AuthorizeRenew(context.Background(), tc.cert); err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) if assert.NotNil(t, tc.err) { @@ -259,7 +259,7 @@ func TestACME_AuthorizeSign(t *testing.T) { tc := tt(t) if opts, err := tc.p.AuthorizeSign(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/provisioner/aws.go b/authority/provisioner/aws.go index 463a4aee..b124dfdb 100644 --- a/authority/provisioner/aws.go +++ b/authority/provisioner/aws.go @@ -35,7 +35,7 @@ const awsIdentityURL = "http://169.254.169.254/latest/dynamic/instance-identity/ const awsSignatureURL = "http://169.254.169.254/latest/dynamic/instance-identity/signature" // awsAPITokenURL is the url used to get the IMDSv2 API token -// nolint:gosec // no credentials here +//nolint:gosec,goimports // no credentials here const awsAPITokenURL = "http://169.254.169.254/latest/api/token" // awsAPITokenTTL is the default TTL to use when requesting IMDSv2 API tokens @@ -43,11 +43,11 @@ const awsAPITokenURL = "http://169.254.169.254/latest/api/token" const awsAPITokenTTL = "30" // awsMetadataTokenHeader is the header that must be passed with every IMDSv2 request -// nolint:gosec // no credentials here +//nolint:gosec,goimports // no credentials here const awsMetadataTokenHeader = "X-aws-ec2-metadata-token" // awsMetadataTokenTTLHeader is the header used to indicate the token TTL requested -// nolint:gosec // no credentials here +//nolint:gosec,goimports // no credentials here const awsMetadataTokenTTLHeader = "X-aws-ec2-metadata-token-ttl-seconds" // awsCertificate is the certificate used to validate the instance identity diff --git a/authority/provisioner/aws_test.go b/authority/provisioner/aws_test.go index 0660c3f0..42cf60a8 100644 --- a/authority/provisioner/aws_test.go +++ b/authority/provisioner/aws_test.go @@ -522,7 +522,7 @@ func TestAWS_authorizeToken(t *testing.T) { tc := tt(t) if claims, err := tc.p.authorizeToken(tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -669,7 +669,7 @@ func TestAWS_AuthorizeSign(t *testing.T) { t.Errorf("AWS.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr) return case err != nil: - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) default: @@ -748,7 +748,7 @@ func TestAWS_AuthorizeSSHSign(t *testing.T) { pub := key.Public().Key rsa2048, err := rsa.GenerateKey(rand.Reader, 2048) assert.FatalError(t, err) - // nolint:gosec // tests minimum size of the key + //nolint:gosec // tests minimum size of the key rsa1024, err := rsa.GenerateKey(rand.Reader, 1024) assert.FatalError(t, err) @@ -807,7 +807,7 @@ func TestAWS_AuthorizeSSHSign(t *testing.T) { return } if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.Nil(t, got) @@ -864,7 +864,7 @@ func TestAWS_AuthorizeRenew(t *testing.T) { if err := tt.aws.AuthorizeRenew(context.Background(), tt.args.cert); (err != nil) != tt.wantErr { t.Errorf("AWS.AuthorizeRenew() error = %v, wantErr %v", err, tt.wantErr) } else if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) } diff --git a/authority/provisioner/azure.go b/authority/provisioner/azure.go index 3f714a3e..d6f71a89 100644 --- a/authority/provisioner/azure.go +++ b/authority/provisioner/azure.go @@ -24,8 +24,7 @@ import ( // azureOIDCBaseURL is the base discovery url for Microsoft Azure tokens. const azureOIDCBaseURL = "https://login.microsoftonline.com" -// azureIdentityTokenURL is the URL to get the identity token for an instance. -// nolint:gosec // no credentials here +//nolint:gosec // azureIdentityTokenURL is the URL to get the identity token for an instance. const azureIdentityTokenURL = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F" // azureDefaultAudience is the default audience used. diff --git a/authority/provisioner/azure_test.go b/authority/provisioner/azure_test.go index 7f8b70d0..626c7bc1 100644 --- a/authority/provisioner/azure_test.go +++ b/authority/provisioner/azure_test.go @@ -336,7 +336,7 @@ func TestAzure_authorizeToken(t *testing.T) { tc := tt(t) if claims, name, group, subscriptionID, objectID, err := tc.p.authorizeToken(tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -498,7 +498,7 @@ func TestAzure_AuthorizeSign(t *testing.T) { t.Errorf("Azure.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr) return case err != nil: - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) default: @@ -576,7 +576,7 @@ func TestAzure_AuthorizeRenew(t *testing.T) { if err := tt.azure.AuthorizeRenew(context.Background(), tt.args.cert); (err != nil) != tt.wantErr { t.Errorf("Azure.AuthorizeRenew() error = %v, wantErr %v", err, tt.wantErr) } else if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) } @@ -624,7 +624,7 @@ func TestAzure_AuthorizeSSHSign(t *testing.T) { pub := key.Public().Key rsa2048, err := rsa.GenerateKey(rand.Reader, 2048) assert.FatalError(t, err) - // nolint:gosec // tests minimum size of the key + //nolint:gosec // tests minimum size of the key rsa1024, err := rsa.GenerateKey(rand.Reader, 1024) assert.FatalError(t, err) @@ -673,7 +673,7 @@ func TestAzure_AuthorizeSSHSign(t *testing.T) { return } if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.Nil(t, got) diff --git a/authority/provisioner/claims.go b/authority/provisioner/claims.go index 96f19b37..b6a5a81e 100644 --- a/authority/provisioner/claims.go +++ b/authority/provisioner/claims.go @@ -38,7 +38,8 @@ type Claimer struct { // NewClaimer initializes a new claimer with the given claims. func NewClaimer(claims *Claims, global Claims) (*Claimer, error) { c := &Claimer{global: global, claims: claims} - return c, c.Validate() + err := c.Validate() + return c, err } // Claims returns the merge of the inner and global claims. diff --git a/authority/provisioner/collection.go b/authority/provisioner/collection.go index 85b489c1..c483a50d 100644 --- a/authority/provisioner/collection.go +++ b/authority/provisioner/collection.go @@ -1,7 +1,7 @@ package provisioner import ( - "crypto/sha1" // nolint:gosec // not used for cryptographic security + "crypto/sha1" //nolint:gosec // not used for cryptographic security "crypto/x509" "encoding/asn1" "encoding/binary" @@ -319,7 +319,7 @@ func loadProvisioner(m *sync.Map, key string) (Interface, bool) { // provisionerSum returns the SHA1 of the provisioners ID. From this we will // create the unique and sorted id. func provisionerSum(p Interface) []byte { - // nolint:gosec // not used for cryptographic security + //nolint:gosec // not used for cryptographic security sum := sha1.Sum([]byte(p.GetID())) return sum[:] } diff --git a/authority/provisioner/gcp.go b/authority/provisioner/gcp.go index a116312d..19b731fa 100644 --- a/authority/provisioner/gcp.go +++ b/authority/provisioner/gcp.go @@ -102,7 +102,6 @@ func (p *GCP) GetID() string { return p.ID } return p.GetIDForToken() - } // GetIDForToken returns an identifier that will be used to load the provisioner diff --git a/authority/provisioner/gcp_test.go b/authority/provisioner/gcp_test.go index 3d6b5d75..983add79 100644 --- a/authority/provisioner/gcp_test.go +++ b/authority/provisioner/gcp_test.go @@ -391,7 +391,7 @@ func TestGCP_authorizeToken(t *testing.T) { tc := tt(t) if claims, err := tc.p.authorizeToken(tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -541,7 +541,7 @@ func TestGCP_AuthorizeSign(t *testing.T) { t.Errorf("GCP.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr) return case err != nil: - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) default: @@ -623,7 +623,7 @@ func TestGCP_AuthorizeSSHSign(t *testing.T) { pub := key.Public().Key rsa2048, err := rsa.GenerateKey(rand.Reader, 2048) assert.FatalError(t, err) - // nolint:gosec // tests minimum size of the key + //nolint:gosec // tests minimum size of the key rsa1024, err := rsa.GenerateKey(rand.Reader, 1024) assert.FatalError(t, err) @@ -682,7 +682,7 @@ func TestGCP_AuthorizeSSHSign(t *testing.T) { return } if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.Nil(t, got) @@ -739,7 +739,7 @@ func TestGCP_AuthorizeRenew(t *testing.T) { if err := tt.prov.AuthorizeRenew(context.Background(), tt.args.cert); (err != nil) != tt.wantErr { t.Errorf("GCP.AuthorizeRenew() error = %v, wantErr %v", err, tt.wantErr) } else if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCoder interface") assert.Equals(t, sc.StatusCode(), tt.code) } diff --git a/authority/provisioner/jwk_test.go b/authority/provisioner/jwk_test.go index 723ccf56..5f9937fa 100644 --- a/authority/provisioner/jwk_test.go +++ b/authority/provisioner/jwk_test.go @@ -185,7 +185,7 @@ func TestJWK_authorizeToken(t *testing.T) { t.Run(tt.name, func(t *testing.T) { if got, err := tt.prov.authorizeToken(tt.args.token, testAudiences.Sign); err != nil { if assert.NotNil(t, tt.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.HasPrefix(t, err.Error(), tt.err.Error()) @@ -225,7 +225,7 @@ func TestJWK_AuthorizeRevoke(t *testing.T) { t.Run(tt.name, func(t *testing.T) { if err := tt.prov.AuthorizeRevoke(context.Background(), tt.args.token); err != nil { if assert.NotNil(t, tt.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.HasPrefix(t, err.Error(), tt.err.Error()) @@ -290,7 +290,7 @@ func TestJWK_AuthorizeSign(t *testing.T) { ctx := NewContextWithMethod(context.Background(), SignMethod) if got, err := tt.prov.AuthorizeSign(ctx, tt.args.token); err != nil { if assert.NotNil(t, tt.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.HasPrefix(t, err.Error(), tt.err.Error()) @@ -366,7 +366,7 @@ func TestJWK_AuthorizeRenew(t *testing.T) { if err := tt.prov.AuthorizeRenew(context.Background(), tt.args.cert); (err != nil) != tt.wantErr { t.Errorf("JWK.AuthorizeRenew() error = %v, wantErr %v", err, tt.wantErr) } else if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) } @@ -411,7 +411,7 @@ func TestJWK_AuthorizeSSHSign(t *testing.T) { pub := key.Public().Key rsa2048, err := rsa.GenerateKey(rand.Reader, 2048) assert.FatalError(t, err) - // nolint:gosec // tests minimum size of the key + //nolint:gosec // tests minimum size of the key rsa1024, err := rsa.GenerateKey(rand.Reader, 1024) assert.FatalError(t, err) @@ -461,7 +461,7 @@ func TestJWK_AuthorizeSSHSign(t *testing.T) { return } if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.Nil(t, got) @@ -626,7 +626,7 @@ func TestJWK_AuthorizeSSHRevoke(t *testing.T) { tc := tt(t) if err := tc.p.AuthorizeSSHRevoke(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/provisioner/k8sSA.go b/authority/provisioner/k8sSA.go index 28be0d5c..3d79933a 100644 --- a/authority/provisioner/k8sSA.go +++ b/authority/provisioner/k8sSA.go @@ -93,7 +93,6 @@ func (p *K8sSA) GetEncryptedKey() (string, string, bool) { // Init initializes and validates the fields of a K8sSA type. func (p *K8sSA) Init(config Config) (err error) { - switch { case p.Type == "": return errors.New("provisioner type cannot be empty") diff --git a/authority/provisioner/k8sSA_test.go b/authority/provisioner/k8sSA_test.go index 2458babb..4d5a230d 100644 --- a/authority/provisioner/k8sSA_test.go +++ b/authority/provisioner/k8sSA_test.go @@ -118,7 +118,7 @@ func TestK8sSA_authorizeToken(t *testing.T) { tc := tt(t) if claims, err := tc.p.authorizeToken(tc.token, testAudiences.Sign); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -167,7 +167,7 @@ func TestK8sSA_AuthorizeRevoke(t *testing.T) { t.Run(name, func(t *testing.T) { tc := tt(t) if err := tc.p.AuthorizeRevoke(context.Background(), tc.token); err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) if assert.NotNil(t, tc.err) { @@ -223,7 +223,7 @@ func TestK8sSA_AuthorizeRenew(t *testing.T) { t.Run(name, func(t *testing.T) { tc := tt(t) if err := tc.p.AuthorizeRenew(context.Background(), tc.cert); err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) if assert.NotNil(t, tc.err) { @@ -272,7 +272,7 @@ func TestK8sSA_AuthorizeSign(t *testing.T) { tc := tt(t) if opts, err := tc.p.AuthorizeSign(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -360,7 +360,7 @@ func TestK8sSA_AuthorizeSSHSign(t *testing.T) { tc := tt(t) if opts, err := tc.p.AuthorizeSSHSign(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/provisioner/keystore.go b/authority/provisioner/keystore.go index 8b276a75..e74a6b8a 100644 --- a/authority/provisioner/keystore.go +++ b/authority/provisioner/keystore.go @@ -85,14 +85,14 @@ func (ks *keyStore) reload() { // 0 it will randomly rotate between 0-12 hours, but every time we call to Get // it will automatically rotate. func (ks *keyStore) nextReloadDuration(age time.Duration) time.Duration { - n := rand.Int63n(int64(ks.jitter)) // nolint:gosec // not used for cryptographic security + n := rand.Int63n(int64(ks.jitter)) //nolint:gosec // not used for cryptographic security age -= time.Duration(n) return abs(age) } func getKeysFromJWKsURI(uri string) (jose.JSONWebKeySet, time.Duration, error) { var keys jose.JSONWebKeySet - resp, err := http.Get(uri) // nolint:gosec // openid-configuration jwks_uri + resp, err := http.Get(uri) //nolint:gosec // openid-configuration jwks_uri if err != nil { return keys, 0, errors.Wrapf(err, "failed to connect to %s", uri) } diff --git a/authority/provisioner/noop.go b/authority/provisioner/noop.go index 9ccd0c8c..bba64eb8 100644 --- a/authority/provisioner/noop.go +++ b/authority/provisioner/noop.go @@ -54,6 +54,7 @@ func (p *noop) AuthorizeSSHSign(ctx context.Context, token string) ([]SignOption } func (p *noop) AuthorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) { + //nolint:nilnil // fine for noop return nil, nil } diff --git a/authority/provisioner/oidc.go b/authority/provisioner/oidc.go index bb3745b7..5463f20c 100644 --- a/authority/provisioner/oidc.go +++ b/authority/provisioner/oidc.go @@ -479,7 +479,7 @@ func (o *OIDC) AuthorizeSSHRevoke(ctx context.Context, token string) error { } func getAndDecode(uri string, v interface{}) error { - resp, err := http.Get(uri) // nolint:gosec // openid-configuration uri + resp, err := http.Get(uri) //nolint:gosec // openid-configuration uri if err != nil { return errors.Wrapf(err, "failed to connect to %s", uri) } diff --git a/authority/provisioner/oidc_test.go b/authority/provisioner/oidc_test.go index 7f80315f..70aa1684 100644 --- a/authority/provisioner/oidc_test.go +++ b/authority/provisioner/oidc_test.go @@ -247,7 +247,7 @@ func TestOIDC_authorizeToken(t *testing.T) { return } if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.Nil(t, got) @@ -318,7 +318,7 @@ func TestOIDC_AuthorizeSign(t *testing.T) { return } if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.Nil(t, got) @@ -406,7 +406,7 @@ func TestOIDC_AuthorizeRevoke(t *testing.T) { t.Errorf("OIDC.Authorize() error = %v, wantErr %v", err, tt.wantErr) return } else if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) } @@ -452,7 +452,7 @@ func TestOIDC_AuthorizeRenew(t *testing.T) { if (err != nil) != tt.wantErr { t.Errorf("OIDC.AuthorizeRenew() error = %v, wantErr %v", err, tt.wantErr) } else if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) } @@ -540,7 +540,7 @@ func TestOIDC_AuthorizeSSHSign(t *testing.T) { pub := key.Public().Key rsa2048, err := rsa.GenerateKey(rand.Reader, 2048) assert.FatalError(t, err) - // nolint:gosec // tests minimum size of the key + //nolint:gosec // tests minimum size of the key rsa1024, err := rsa.GenerateKey(rand.Reader, 1024) assert.FatalError(t, err) @@ -614,7 +614,7 @@ func TestOIDC_AuthorizeSSHSign(t *testing.T) { return } if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) assert.Nil(t, got) @@ -682,7 +682,7 @@ func TestOIDC_AuthorizeSSHRevoke(t *testing.T) { if (err != nil) != tt.wantErr { t.Errorf("OIDC.AuthorizeSSHRevoke() error = %v, wantErr %v", err, tt.wantErr) } else if err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.code) } diff --git a/authority/provisioner/options_test.go b/authority/provisioner/options_test.go index 652fff73..aaf4b36c 100644 --- a/authority/provisioner/options_test.go +++ b/authority/provisioner/options_test.go @@ -254,7 +254,7 @@ func TestCustomTemplateOptions(t *testing.T) { } func Test_unsafeParseSigned(t *testing.T) { - // nolint:gosec // no credentials here + //nolint:gosec // no credentials here okToken := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJqYW5lQGRvZS5jb20iLCJpc3MiOiJodHRwczovL2RvZS5jb20iLCJqdGkiOiI4ZmYzMjQ4MS1mZDVmLTRlMmUtOTZkZi05MDhjMTI3Yzg1ZjciLCJpYXQiOjE1OTUzNjAwMjgsImV4cCI6MTU5NTM2MzYyOH0.aid8UuhFucJOFHXaob9zpNtVvhul9ulTGsA52mU6XIw" type args struct { s string diff --git a/authority/provisioner/policy.go b/authority/provisioner/policy.go index 95ef4163..caf8c782 100644 --- a/authority/provisioner/policy.go +++ b/authority/provisioner/policy.go @@ -9,8 +9,8 @@ type policyEngine struct { } func newPolicyEngine(options *Options) (*policyEngine, error) { - if options == nil { + //nolint:nilnil // legacy return nil, nil } diff --git a/authority/provisioner/provisioner_test.go b/authority/provisioner/provisioner_test.go index 9678a20b..82beffc3 100644 --- a/authority/provisioner/provisioner_test.go +++ b/authority/provisioner/provisioner_test.go @@ -241,7 +241,7 @@ func TestUnimplementedMethods(t *testing.T) { default: t.Errorf("unexpected method %s", tt.method) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), http.StatusUnauthorized) assert.Equals(t, err.Error(), msg) diff --git a/authority/provisioner/sign_options.go b/authority/provisioner/sign_options.go index 8a0363a6..bc0d88ff 100644 --- a/authority/provisioner/sign_options.go +++ b/authority/provisioner/sign_options.go @@ -310,7 +310,6 @@ func (v profileDefaultDuration) Modify(cert *x509.Certificate, so SignOptions) e if notBefore.IsZero() { notBefore = now() backdate = -1 * so.Backdate - } notAfter := so.NotAfter.RelativeTime(notBefore) if notAfter.IsZero() { diff --git a/authority/provisioner/sign_ssh_options_test.go b/authority/provisioner/sign_ssh_options_test.go index 28a35639..1993295b 100644 --- a/authority/provisioner/sign_ssh_options_test.go +++ b/authority/provisioner/sign_ssh_options_test.go @@ -287,7 +287,7 @@ func Test_sshCertTypeModifier_Modify(t *testing.T) { t.Run(name, func(t *testing.T) { tc := run() if assert.Nil(t, tc.modifier.Modify(tc.cert, SignSSHOptions{})) { - assert.Equals(t, tc.cert.CertType, uint32(tc.expected)) + assert.Equals(t, tc.cert.CertType, tc.expected) } }) } diff --git a/authority/provisioner/ssh_test.go b/authority/provisioner/ssh_test.go index b86945a3..3fd97f9d 100644 --- a/authority/provisioner/ssh_test.go +++ b/authority/provisioner/ssh_test.go @@ -2,6 +2,7 @@ package provisioner import ( "crypto" + "errors" "fmt" "net/http" "reflect" @@ -84,9 +85,10 @@ func signSSHCertificate(key crypto.PublicKey, opts SignSSHOptions, signOpts []Si // Create certificate from template. certificate, err := sshutil.NewCertificate(cr, certOptions...) if err != nil { - if _, ok := err.(*sshutil.TemplateError); ok { - return nil, errs.NewErr(http.StatusBadRequest, err, - errs.WithMessage(err.Error()), + var templErr *sshutil.TemplateError + if errors.As(err, &templErr) { + return nil, errs.NewErr(http.StatusBadRequest, templErr, + errs.WithMessage(templErr.Error()), errs.WithKeyVal("signOptions", signOpts), ) } diff --git a/authority/provisioner/sshpop_test.go b/authority/provisioner/sshpop_test.go index 1e026883..857ad824 100644 --- a/authority/provisioner/sshpop_test.go +++ b/authority/provisioner/sshpop_test.go @@ -218,7 +218,7 @@ func TestSSHPOP_authorizeToken(t *testing.T) { t.Run(name, func(t *testing.T) { tc := tt(t) if claims, err := tc.p.authorizeToken(tc.token, testAudiences.Sign, true); err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) if assert.NotNil(t, tc.err) { @@ -289,7 +289,7 @@ func TestSSHPOP_AuthorizeSSHRevoke(t *testing.T) { t.Run(name, func(t *testing.T) { tc := tt(t) if err := tc.p.AuthorizeSSHRevoke(context.Background(), tc.token); err != nil { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) if assert.NotNil(t, tc.err) { @@ -370,7 +370,7 @@ func TestSSHPOP_AuthorizeSSHRenew(t *testing.T) { tc := tt(t) if cert, err := tc.p.AuthorizeSSHRenew(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -452,7 +452,7 @@ func TestSSHPOP_AuthorizeSSHRekey(t *testing.T) { tc := tt(t) if cert, opts, err := tc.p.AuthorizeSSHRekey(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/provisioner/utils_test.go b/authority/provisioner/utils_test.go index 265c7b08..f0e6949f 100644 --- a/authority/provisioner/utils_test.go +++ b/authority/provisioner/utils_test.go @@ -100,7 +100,7 @@ func generateJSONWebKey() (*jose.JSONWebKey, error) { if err != nil { return nil, err } - jwk.KeyID = string(hex.EncodeToString(fp)) + jwk.KeyID = hex.EncodeToString(fp) return jwk, nil } @@ -449,7 +449,7 @@ func generateAWSWithServer() (*AWS, *httptest.Server, error) { if err != nil { return nil, nil, errors.Wrap(err, "error signing document") } - // nolint:gosec // tests minimum size of the key + //nolint:gosec // tests minimum size of the key token := "AQAEAEEO9-7Z88ewKFpboZuDlFYWz9A3AN-wMOVzjEhfAyXW31BvVw==" srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { diff --git a/authority/provisioner/x5c_test.go b/authority/provisioner/x5c_test.go index 3bcf30d1..0920ac1a 100644 --- a/authority/provisioner/x5c_test.go +++ b/authority/provisioner/x5c_test.go @@ -120,7 +120,7 @@ M46l92gdOozT return ProvisionerValidateTest{ p: p, extraValid: func(p *X5C) error { - // nolint:staticcheck // We don't have a different way to + //nolint:staticcheck // We don't have a different way to // check the number of certificates in the pool. numCerts := len(p.rootPool.Subjects()) if numCerts != 2 { @@ -389,7 +389,7 @@ lgsqsR63is+0YQ== tc := tt(t) if claims, err := tc.p.authorizeToken(tc.token, testAudiences.Sign); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -460,7 +460,7 @@ func TestX5C_AuthorizeSign(t *testing.T) { tc := tt(t) if opts, err := tc.p.AuthorizeSign(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCoder interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -545,7 +545,7 @@ func TestX5C_AuthorizeRevoke(t *testing.T) { tc := tt(t) if err := tc.p.AuthorizeRevoke(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -595,7 +595,7 @@ func TestX5C_AuthorizeRenew(t *testing.T) { NotAfter: now.Add(time.Hour), }); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -756,7 +756,7 @@ func TestX5C_AuthorizeSSHSign(t *testing.T) { tc := tt(t) if opts, err := tc.p.AuthorizeSSHSign(context.Background(), tc.token); err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCoder interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/provisioners.go b/authority/provisioners.go index dcf8de36..60382b21 100644 --- a/authority/provisioners.go +++ b/authority/provisioners.go @@ -145,7 +145,6 @@ func (a *Authority) generateProvisionerConfig(ctx context.Context) (provisioner. AuthorizeRenewFunc: a.authorizeRenewFunc, AuthorizeSSHRenewFunc: a.authorizeSSHRenewFunc, }, nil - } // StoreProvisioner stores a provisioner to the authority. @@ -530,6 +529,7 @@ func durationsToLinkedca(d *provisioner.Duration) string { // certifictes claims type. func claimsToCertificates(c *linkedca.Claims) (*provisioner.Claims, error) { if c == nil { + //nolint:nilnil // legacy return nil, nil } diff --git a/authority/provisioners_test.go b/authority/provisioners_test.go index 56cd16b1..f3aeb5fd 100644 --- a/authority/provisioners_test.go +++ b/authority/provisioners_test.go @@ -57,7 +57,7 @@ func TestGetEncryptedKey(t *testing.T) { ek, err := tc.a.GetEncryptedKey(tc.kid) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -107,7 +107,7 @@ func TestGetProvisioners(t *testing.T) { ps, next, err := tc.a.GetProvisioners("", 0) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/root_test.go b/authority/root_test.go index a1b08fac..68f7952f 100644 --- a/authority/root_test.go +++ b/authority/root_test.go @@ -32,7 +32,7 @@ func TestRoot(t *testing.T) { crt, err := a.Root(tc.sum) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCoder interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/ssh.go b/authority/ssh.go index d8d5375c..dda8a876 100644 --- a/authority/ssh.go +++ b/authority/ssh.go @@ -140,6 +140,7 @@ func (a *Authority) GetSSHBastion(ctx context.Context, user, hostname string) (* return a.config.SSH.Bastion, nil } } + //nolint:nilnil // legacy return nil, nil } return nil, errs.NotFound("authority.GetSSHBastion; ssh is not configured") @@ -202,9 +203,10 @@ func (a *Authority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisi // Create certificate from template. certificate, err := sshutil.NewCertificate(cr, certOptions...) if err != nil { - if _, ok := err.(*sshutil.TemplateError); ok { + var templErr *sshutil.TemplateError + if errors.As(err, &templErr) { return nil, errs.ApplyOptions( - errs.BadRequestErr(err, err.Error()), + errs.BadRequestErr(templErr, templErr.Error()), errs.WithKeyVal("signOptions", signOpts), ) } @@ -281,7 +283,7 @@ func (a *Authority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisi } } - if err = a.storeSSHCertificate(prov, cert); err != nil && err != db.ErrNotImplemented { + if err = a.storeSSHCertificate(prov, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) { return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error storing certificate in db") } @@ -351,7 +353,7 @@ func (a *Authority) RenewSSH(ctx context.Context, oldCert *ssh.Certificate) (*ss return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate") } - if err = a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && err != db.ErrNotImplemented { + if err = a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) { return nil, errs.Wrap(http.StatusInternalServerError, err, "renewSSH: error storing certificate in db") } @@ -434,7 +436,7 @@ func (a *Authority) RekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub } } - if err = a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && err != db.ErrNotImplemented { + if err = a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) { return nil, errs.Wrap(http.StatusInternalServerError, err, "rekeySSH; error storing certificate in db") } @@ -570,7 +572,7 @@ func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subje } cert.Signature = sig - if err = a.storeRenewedSSHCertificate(prov, subject, cert); err != nil && err != db.ErrNotImplemented { + if err = a.storeRenewedSSHCertificate(prov, subject, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) { return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error storing certificate in db") } @@ -589,7 +591,7 @@ func (a *Authority) CheckSSHHost(ctx context.Context, principal, token string) ( } exists, err := a.db.IsSSHHost(principal) if err != nil { - if err == db.ErrNotImplemented { + if errors.Is(err, db.ErrNotImplemented) { return false, errs.Wrap(http.StatusNotImplemented, err, "checkSSHHost: isSSHHost is not implemented") } diff --git a/authority/ssh_test.go b/authority/ssh_test.go index 4fd7eaa0..f5ab0d59 100644 --- a/authority/ssh_test.go +++ b/authority/ssh_test.go @@ -760,7 +760,7 @@ func TestAuthority_GetSSHBastion(t *testing.T) { t.Errorf("Authority.GetSSHBastion() error = %v, wantErr %v", err, tt.wantErr) return } else if err != nil { - _, ok := err.(render.StatusCodedError) + _, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") } if !reflect.DeepEqual(got, tt.want) { @@ -850,7 +850,7 @@ func TestAuthority_GetSSHHosts(t *testing.T) { hosts, err := auth.GetSSHHosts(context.Background(), tc.cert) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) @@ -1077,7 +1077,7 @@ func TestAuthority_RekeySSH(t *testing.T) { cert, err := auth.RekeySSH(context.Background(), tc.cert, tc.key, tc.signOpts...) if err != nil { if assert.NotNil(t, tc.err) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) diff --git a/authority/tls.go b/authority/tls.go index 632ac238..c52e6753 100644 --- a/authority/tls.go +++ b/authority/tls.go @@ -142,7 +142,8 @@ func (a *Authority) Sign(csr *x509.CertificateRequest, signOpts provisioner.Sign cert, err := x509util.NewCertificate(csr, certOptions...) if err != nil { - if _, ok := err.(*x509util.TemplateError); ok { + var te *x509util.TemplateError + if errors.As(err, &te) { return nil, errs.ApplyOptions( errs.BadRequestErr(err, err.Error()), errs.WithKeyVal("csr", csr), @@ -244,7 +245,7 @@ func (a *Authority) Sign(csr *x509.CertificateRequest, signOpts provisioner.Sign fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...) if err = a.storeCertificate(prov, fullchain); err != nil { - if err != db.ErrNotImplemented { + if !errors.Is(err, db.ErrNotImplemented) { return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Sign; error storing certificate in db", opts...) } @@ -362,7 +363,7 @@ func (a *Authority) Rekey(oldCert *x509.Certificate, pk crypto.PublicKey) ([]*x5 fullchain := append([]*x509.Certificate{resp.Certificate}, resp.CertificateChain...) if err = a.storeRenewedCertificate(oldCert, fullchain); err != nil { - if err != db.ErrNotImplemented { + if !errors.Is(err, db.ErrNotImplemented) { return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.Rekey; error storing certificate in db", opts...) } } @@ -542,12 +543,12 @@ func (a *Authority) Revoke(ctx context.Context, revokeOpts *RevokeOptions) error // Save as revoked in the Db. err = a.revoke(revokedCert, rci) } - switch err { - case nil: + switch { + case err == nil: return nil - case db.ErrNotImplemented: + case errors.Is(err, db.ErrNotImplemented): return errs.NotImplemented("authority.Revoke; no persistence layer configured", opts...) - case db.ErrAlreadyExists: + case errors.Is(err, db.ErrAlreadyExists): return errs.ApplyOptions( errs.BadRequest("certificate with serial number '%s' is already revoked", rci.Serial), opts..., @@ -667,7 +668,7 @@ func templatingError(err error) error { ) if errors.As(err, &syntaxError) { // offset is arguably not super clear to the user, but it's the best we can do here - cause = fmt.Errorf("%s at offset %d", cause.Error(), syntaxError.Offset) + cause = fmt.Errorf("%w at offset %d", cause, syntaxError.Offset) } else if errors.As(err, &typeError) { // slightly rewriting the default error message to include the offset cause = fmt.Errorf("cannot unmarshal %s at offset %d into Go value of type %s", typeError.Value, typeError.Offset, typeError.Type) diff --git a/authority/tls_test.go b/authority/tls_test.go index a8521b51..75ffb8ce 100644 --- a/authority/tls_test.go +++ b/authority/tls_test.go @@ -6,7 +6,7 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" - "crypto/sha1" // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 "crypto/x509" "crypto/x509/pkix" "encoding/asn1" @@ -199,7 +199,7 @@ func generateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) { if _, err = asn1.Unmarshal(b, &info); err != nil { return nil, fmt.Errorf("error unmarshaling public key: %w", err) } - // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 hash := sha1.Sum(info.SubjectPublicKey.Bytes) return hash[:], nil } @@ -577,7 +577,7 @@ ZYtQ9Ot36qc= {Id: stepOIDProvisioner, Value: []byte("foo")}, {Id: []int{1, 1, 1}, Value: []byte("bar")}})) now := time.Now().UTC() - // nolint:gocritic + //nolint:gocritic enforcedExtraOptions := append(extraOpts, &certificateDurationEnforcer{ NotBefore: now, NotAfter: now.Add(365 * 24 * time.Hour), @@ -730,13 +730,13 @@ ZYtQ9Ot36qc= if err != nil { if assert.NotNil(t, tc.err, fmt.Sprintf("unexpected error: %s", err)) { assert.Nil(t, certChain) - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) - ctxErr, ok := err.(*errs.Error) - assert.Fatal(t, ok, "error is not of type *errs.Error") + var ctxErr *errs.Error + assert.Fatal(t, errors.As(err, &ctxErr), "error is not of type *errs.Error") assert.Equals(t, ctxErr.Details["csr"], tc.csr) assert.Equals(t, ctxErr.Details["signOptions"], tc.signOpts) } @@ -929,13 +929,13 @@ func TestAuthority_Renew(t *testing.T) { if err != nil { if assert.NotNil(t, tc.err, fmt.Sprintf("unexpected error: %s", err)) { assert.Nil(t, certChain) - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) - ctxErr, ok := err.(*errs.Error) - assert.Fatal(t, ok, "error is not of type *errs.Error") + var ctxErr *errs.Error + assert.Fatal(t, errors.As(err, &ctxErr), "error is not of type *errs.Error") assert.Equals(t, ctxErr.Details["serialNumber"], tc.cert.SerialNumber.String()) } } else { @@ -1136,13 +1136,13 @@ func TestAuthority_Rekey(t *testing.T) { if err != nil { if assert.NotNil(t, tc.err, fmt.Sprintf("unexpected error: %s", err)) { assert.Nil(t, certChain) - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) - ctxErr, ok := err.(*errs.Error) - assert.Fatal(t, ok, "error is not of type *errs.Error") + var ctxErr *errs.Error + assert.Fatal(t, errors.As(err, &ctxErr), "error is not of type *errs.Error") assert.Equals(t, ctxErr.Details["serialNumber"], tc.cert.SerialNumber.String()) } } else { @@ -1566,13 +1566,13 @@ func TestAuthority_Revoke(t *testing.T) { t.Run(name, func(t *testing.T) { if err := tc.auth.Revoke(tc.ctx, tc.opts); err != nil { if assert.NotNil(t, tc.err, fmt.Sprintf("unexpected error: %s", err)) { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tc.code) assert.HasPrefix(t, err.Error(), tc.err.Error()) - ctxErr, ok := err.(*errs.Error) - assert.Fatal(t, ok, "error is not of type *errs.Error") + var ctxErr *errs.Error + assert.Fatal(t, errors.As(err, &ctxErr), "error is not of type *errs.Error") assert.Equals(t, ctxErr.Details["serialNumber"], tc.opts.Serial) assert.Equals(t, ctxErr.Details["reasonCode"], tc.opts.ReasonCode) assert.Equals(t, ctxErr.Details["reason"], tc.opts.Reason) diff --git a/ca/acmeClient.go b/ca/acmeClient.go index 2bbb0d6a..039b10a3 100644 --- a/ca/acmeClient.go +++ b/ca/acmeClient.go @@ -52,6 +52,7 @@ func NewACMEClient(endpoint string, contact []string, opts ...ClientOption) (*AC if err != nil { return nil, errors.Wrapf(err, "client GET %s failed", endpoint) } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, readACMEError(resp.Body) } @@ -80,6 +81,7 @@ func NewACMEClient(endpoint string, contact []string, opts ...ClientOption) (*AC if err != nil { return nil, err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, readACMEError(resp.Body) } @@ -111,6 +113,7 @@ func (c *ACMEClient) GetNonce() (string, error) { if err != nil { return "", errors.Wrapf(err, "client GET %s failed", c.dir.NewNonce) } + defer resp.Body.Close() if resp.StatusCode >= 400 { return "", readACMEError(resp.Body) } @@ -198,6 +201,7 @@ func (c *ACMEClient) NewOrder(payload []byte) (*acme.Order, error) { if err != nil { return nil, err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, readACMEError(resp.Body) } @@ -218,6 +222,7 @@ func (c *ACMEClient) GetChallenge(url string) (*acme.Challenge, error) { if err != nil { return nil, err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, readACMEError(resp.Body) } @@ -237,6 +242,7 @@ func (c *ACMEClient) ValidateChallenge(url string) error { if err != nil { return err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return readACMEError(resp.Body) } @@ -262,6 +268,7 @@ func (c *ACMEClient) GetAuthz(url string) (*acme.Authorization, error) { if err != nil { return nil, err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, readACMEError(resp.Body) } @@ -279,6 +286,7 @@ func (c *ACMEClient) GetOrder(url string) (*acme.Order, error) { if err != nil { return nil, err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, readACMEError(resp.Body) } @@ -302,6 +310,7 @@ func (c *ACMEClient) FinalizeOrder(url string, csr *x509.CertificateRequest) err if err != nil { return err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return readACMEError(resp.Body) } @@ -314,6 +323,7 @@ func (c *ACMEClient) GetCertificate(url string) (*x509.Certificate, []*x509.Cert if err != nil { return nil, nil, err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, nil, readACMEError(resp.Body) } @@ -350,6 +360,7 @@ func (c *ACMEClient) GetAccountOrders() ([]string, error) { if err != nil { return nil, err } + defer resp.Body.Close() if resp.StatusCode >= 400 { return nil, readACMEError(resp.Body) } diff --git a/ca/acmeClient_test.go b/ca/acmeClient_test.go index 034af0f6..77d380f9 100644 --- a/ca/acmeClient_test.go +++ b/ca/acmeClient_test.go @@ -1359,7 +1359,7 @@ func TestACMEClient_GetCertificate(t *testing.T) { Type: "Certificate", Bytes: leaf.Raw, }) - // nolint:gocritic + //nolint:gocritic certBytes := append(leafb, leafb...) certBytes = append(certBytes, leafb...) ac := &ACMEClient{ diff --git a/ca/adminClient.go b/ca/adminClient.go index 6532b000..84a0d413 100644 --- a/ca/adminClient.go +++ b/ca/adminClient.go @@ -116,7 +116,6 @@ func (c *AdminClient) generateAdminToken(aud *url.URL) (string, error) { } return tok.SignedString(c.x5cJWK.Algorithm, c.x5cJWK.Key) - } func (c *AdminClient) retryOnError(r *http.Response) bool { diff --git a/ca/bootstrap_test.go b/ca/bootstrap_test.go index 2a837a3d..974ba1f1 100644 --- a/ca/bootstrap_test.go +++ b/ca/bootstrap_test.go @@ -200,7 +200,7 @@ func TestBootstrap(t *testing.T) { } } -// nolint:gosec // insecure test servers +//nolint:gosec // insecure test servers func TestBootstrapServerWithoutMTLS(t *testing.T) { srv := startCABootstrapServer() defer srv.Close() @@ -246,6 +246,7 @@ func TestBootstrapServerWithoutMTLS(t *testing.T) { expected := &http.Server{ TLSConfig: got.TLSConfig, } + //nolint:govet // not comparing errors if !reflect.DeepEqual(got, expected) { t.Errorf("BootstrapServer() = %v, want %v", got, expected) } @@ -257,7 +258,7 @@ func TestBootstrapServerWithoutMTLS(t *testing.T) { } } -// nolint:gosec // insecure test servers +//nolint:gosec // insecure test servers func TestBootstrapServerWithMTLS(t *testing.T) { srv := startCABootstrapServer() defer srv.Close() @@ -303,6 +304,7 @@ func TestBootstrapServerWithMTLS(t *testing.T) { expected := &http.Server{ TLSConfig: got.TLSConfig, } + //nolint:govet // not comparing errors if !reflect.DeepEqual(got, expected) { t.Errorf("BootstrapServer() = %v, want %v", got, expected) } @@ -407,7 +409,7 @@ func TestBootstrapClientServerRotation(t *testing.T) { // Create bootstrap server token := generateBootstrapToken(caURL, "127.0.0.1", "ef742f95dc0d8aa82d3cca4017af6dac3fce84290344159891952d18c53eefe7") - // nolint:gosec // insecure test server + //nolint:gosec // insecure test server server, err := BootstrapServer(context.Background(), token, &http.Server{ Addr: ":0", Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { @@ -526,7 +528,7 @@ func TestBootstrapClientServerFederation(t *testing.T) { // Create bootstrap server token := generateBootstrapToken(caURL1, "127.0.0.1", "ef742f95dc0d8aa82d3cca4017af6dac3fce84290344159891952d18c53eefe7") - // nolint:gosec // insecure test server + //nolint:gosec // insecure test server server, err := BootstrapServer(context.Background(), token, &http.Server{ Addr: ":0", Handler: http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { diff --git a/ca/ca.go b/ca/ca.go index bddcab79..a7999edf 100644 --- a/ca/ca.go +++ b/ca/ca.go @@ -529,9 +529,9 @@ func (ca *CA) shouldServeSCEPEndpoints() bool { return ca.auth.GetSCEPService() != nil } -// nolint // ignore linters to allow keeping this function around for debugging +//nolint:unused,deadcode // useful for debugging func dumpRoutes(mux chi.Routes) { - // helpful routine for logging all routes // + // helpful routine for logging all routes walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error { fmt.Printf("%s %s\n", method, route) return nil diff --git a/ca/ca_test.go b/ca/ca_test.go index e76ca8ff..7ad25cc6 100644 --- a/ca/ca_test.go +++ b/ca/ca_test.go @@ -5,7 +5,7 @@ import ( "context" "crypto" "crypto/rand" - "crypto/sha1" // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 "crypto/tls" "crypto/x509" "crypto/x509/pkix" @@ -66,7 +66,7 @@ func generateSubjectKeyID(pub crypto.PublicKey) ([]byte, error) { return nil, errors.Wrap(err, "error unmarshaling public key") } - // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 hash := sha1.Sum(info.SubjectPublicKey.Bytes) return hash[:], nil } diff --git a/ca/client.go b/ca/client.go index 19fcd0bd..355471aa 100644 --- a/ca/client.go +++ b/ca/client.go @@ -56,7 +56,7 @@ func newClient(transport http.RoundTripper) *uaClient { } } -// nolint:gosec // used in bootstrap protocol +//nolint:gosec // used in bootstrap protocol func newInsecureClient() *uaClient { return &uaClient{ Client: &http.Client{ @@ -120,9 +120,7 @@ type clientOptions struct { } func (o *clientOptions) apply(opts []ClientOption) (err error) { - if err = o.applyDefaultIdentity(); err != nil { - return - } + o.applyDefaultIdentity() for _, fn := range opts { if err = fn(o); err != nil { return @@ -133,26 +131,25 @@ func (o *clientOptions) apply(opts []ClientOption) (err error) { // applyDefaultIdentity sets the options for the default identity if the // identity file is present. The identity is enabled by default. -func (o *clientOptions) applyDefaultIdentity() error { +func (o *clientOptions) applyDefaultIdentity() { if DisableIdentity { - return nil + return } // Do not load an identity if something fails i, err := identity.LoadDefaultIdentity() if err != nil { - return nil + return } if err := i.Validate(); err != nil { - return nil + return } crt, err := i.TLSCertificate() if err != nil { - return nil + return } o.certificate = crt o.getClientCertificate = i.GetClientCertificateFunc() - return nil } // checkTransport checks if other ways to set up a transport have been provided. @@ -241,13 +238,13 @@ func WithTransport(tr http.RoundTripper) ClientOption { } // WithInsecure adds a insecure transport that bypasses TLS verification. -// nolint:gosec // insecure option func WithInsecure() ClientOption { return func(o *clientOptions) error { o.transport = &http.Transport{ Proxy: http.ProxyFromEnvironment, TLSClientConfig: &tls.Config{ - MinVersion: tls.VersionTLS12, + MinVersion: tls.VersionTLS12, + //nolint:gosec // insecure option InsecureSkipVerify: true, }, } @@ -1138,8 +1135,7 @@ retry: } var check api.SSHCheckPrincipalResponse if err := readJSON(resp.Body, &check); err != nil { - return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response", - []interface{}{u, errs.WithMessage("Failed to parse response from /ssh/check-host endpoint")}) + return nil, errs.Wrapf(http.StatusInternalServerError, err, "error reading %s response", u) } return &check, nil } @@ -1203,6 +1199,7 @@ func (c *Client) RootFingerprint() (string, error) { if err != nil { return "", errors.Wrapf(err, "client GET %s failed", u) } + defer resp.Body.Close() if resp.TLS == nil || len(resp.TLS.VerifiedChains) == 0 { return "", errors.New("missing verified chains") } diff --git a/ca/client_test.go b/ca/client_test.go index 48aa1488..ce4ca310 100644 --- a/ca/client_test.go +++ b/ca/client_test.go @@ -519,7 +519,7 @@ func TestClient_Renew(t *testing.T) { t.Errorf("Client.Renew() = %v, want nil", got) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, err.Error(), tt.err.Error()) @@ -587,7 +587,7 @@ func TestClient_RenewWithToken(t *testing.T) { t.Errorf("Client.RenewWithToken() = %v, want nil", got) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, err.Error(), tt.err.Error()) @@ -656,7 +656,7 @@ func TestClient_Rekey(t *testing.T) { t.Errorf("Client.Renew() = %v, want nil", got) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, err.Error(), tt.err.Error()) @@ -777,7 +777,7 @@ func TestClient_ProvisionerKey(t *testing.T) { t.Errorf("Client.ProvisionerKey() = %v, want nil", got) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, tt.err.Error(), err.Error()) @@ -836,7 +836,7 @@ func TestClient_Roots(t *testing.T) { if got != nil { t.Errorf("Client.Roots() = %v, want nil", got) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, err.Error(), tt.err.Error()) @@ -894,7 +894,7 @@ func TestClient_Federation(t *testing.T) { if got != nil { t.Errorf("Client.Federation() = %v, want nil", got) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, tt.err.Error(), err.Error()) @@ -956,7 +956,7 @@ func TestClient_SSHRoots(t *testing.T) { if got != nil { t.Errorf("Client.SSHKeys() = %v, want nil", got) } - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, tt.err.Error(), err.Error()) @@ -1118,7 +1118,7 @@ func TestClient_SSHBastion(t *testing.T) { t.Errorf("Client.SSHBastion() = %v, want nil", got) } if tt.responseCode != 200 { - sc, ok := err.(render.StatusCodedError) + sc, ok := render.AsStatusCodedError(err) assert.Fatal(t, ok, "error does not implement StatusCodedError interface") assert.Equals(t, sc.StatusCode(), tt.responseCode) assert.HasPrefix(t, err.Error(), tt.err.Error()) diff --git a/ca/identity/client.go b/ca/identity/client.go index 4b0aee82..f6c8c213 100644 --- a/ca/identity/client.go +++ b/ca/identity/client.go @@ -82,7 +82,6 @@ func LoadClient() (*Client, error) { Transport: tr, }, }, nil - } type defaultsConfig struct { diff --git a/ca/identity/client_test.go b/ca/identity/client_test.go index 14e6da6c..2ebeb15d 100644 --- a/ca/identity/client_test.go +++ b/ca/identity/client_test.go @@ -242,7 +242,7 @@ func Test_defaultsConfig_Validate(t *testing.T) { } } -// nolint:staticcheck,gocritic +//nolint:staticcheck,gocritic func equalPools(a, b *x509.CertPool) bool { if reflect.DeepEqual(a, b) { return true diff --git a/ca/identity/identity.go b/ca/identity/identity.go index 2a6b4c39..755d270a 100644 --- a/ca/identity/identity.go +++ b/ca/identity/identity.go @@ -261,6 +261,7 @@ func (i *Identity) GetClientCertificateFunc() func(*tls.CertificateRequestInfo) // GetCertPool returns a x509.CertPool if the identity defines a custom root. func (i *Identity) GetCertPool() (*x509.CertPool, error) { if i.Root == "" { + //nolint:nilnil // legacy return nil, nil } b, err := os.ReadFile(i.Root) diff --git a/ca/identity/identity_test.go b/ca/identity/identity_test.go index eb32328a..9a2422b3 100644 --- a/ca/identity/identity_test.go +++ b/ca/identity/identity_test.go @@ -345,7 +345,7 @@ func TestIdentity_GetCertPool(t *testing.T) { return } if got != nil { - // nolint:staticcheck // we don't have a different way to check + //nolint:staticcheck // we don't have a different way to check // the certificates in the pool. subjects := got.Subjects() if !reflect.DeepEqual(subjects, tt.wantSubjects) { diff --git a/ca/provisioner.go b/ca/provisioner.go index c1879c86..d5b23f38 100644 --- a/ca/provisioner.go +++ b/ca/provisioner.go @@ -182,19 +182,17 @@ func loadProvisionerJWKByKid(client *Client, kid string, password []byte) (*jose // loadProvisionerJWKByName retrieves the list of provisioners and encrypted key then // returns the key of the first provisioner with a matching name that can be successfully // decrypted with the specified password. -func loadProvisionerJWKByName(client *Client, name string, password []byte) (key *jose.JSONWebKey, err error) { +func loadProvisionerJWKByName(client *Client, name string, password []byte) (*jose.JSONWebKey, error) { provisioners, err := getProvisioners(client) if err != nil { - err = errors.Wrap(err, "error getting the provisioners") - return + return nil, errors.Wrap(err, "error getting the provisioners") } for _, provisioner := range provisioners { if provisioner.GetName() == name { if _, encryptedKey, ok := provisioner.GetEncryptedKey(); ok { - key, err = decryptProvisionerJWK(encryptedKey, password) - if err == nil { - return + if key, err := decryptProvisionerJWK(encryptedKey, password); err == nil { + return key, nil } } } diff --git a/ca/renew.go b/ca/renew.go index a913e59c..ea4c5764 100644 --- a/ca/renew.go +++ b/ca/renew.go @@ -193,7 +193,7 @@ func (r *TLSRenewer) nextRenewDuration(notAfter time.Time) time.Duration { return d } -// nolint:gosec // not used for cryptographic security +//nolint:gosec // not used for cryptographic security func mathRandInt63n(n int64) int64 { return rand.Int63n(n) } diff --git a/ca/tls.go b/ca/tls.go index b4d54952..282f9778 100644 --- a/ca/tls.go +++ b/ca/tls.go @@ -105,8 +105,8 @@ func (c *Client) getClientTLSConfig(ctx context.Context, sign *api.SignResponse, } tr := getDefaultTransport(tlsConfig) - // Use mutable tls.Config on renew - tr.DialTLS = c.buildDialTLS(tlsCtx) // nolint:staticcheck,gocritic + //nolint:staticcheck // Use mutable tls.Config on renew + tr.DialTLS = c.buildDialTLS(tlsCtx) // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx) renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk) @@ -153,8 +153,8 @@ func (c *Client) GetServerTLSConfig(ctx context.Context, sign *api.SignResponse, // Update renew function with transport tr := getDefaultTransport(tlsConfig) - // Use mutable tls.Config on renew - tr.DialTLS = c.buildDialTLS(tlsCtx) // nolint:staticcheck,gocritic + //nolint:staticcheck // Use mutable tls.Config on renew + tr.DialTLS = c.buildDialTLS(tlsCtx) // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx) renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk) @@ -194,8 +194,7 @@ func (c *Client) buildDialTLS(ctx *TLSOptionCtx) func(network, addr string) (net } } -// buildDialTLSContext returns an implementation of DialTLSContext callback in http.Transport. -// nolint:unused,gocritic +//nolint:unused // buildDialTLSContext returns an implementation of DialTLSContext callback in http.Transport. func (c *Client) buildDialTLSContext(tlsCtx *TLSOptionCtx) func(ctx context.Context, network, addr string) (net.Conn, error) { return func(ctx context.Context, network, addr string) (net.Conn, error) { d := getDefaultDialer() @@ -253,8 +252,7 @@ func TLSCertificate(sign *api.SignResponse, pk crypto.PrivateKey) (*tls.Certific return nil, err } - // nolint:gocritic - // using a new variable for clarity + //nolint:gocritic // using a new variable for clarity chain := append(certPEM, caPEM...) cert, err := tls.X509KeyPair(chain, keyPEM) if err != nil { diff --git a/ca/tls_options_test.go b/ca/tls_options_test.go index 65086315..7dea3dc8 100644 --- a/ca/tls_options_test.go +++ b/ca/tls_options_test.go @@ -13,7 +13,7 @@ import ( "github.com/smallstep/certificates/api" ) -// nolint:gosec // test tls config +//nolint:gosec // test tls config func Test_newTLSOptionCtx(t *testing.T) { client, err := NewClient("https://ca.smallstep.com", WithTransport(http.DefaultTransport)) if err != nil { @@ -41,7 +41,7 @@ func Test_newTLSOptionCtx(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestTLSOptionCtx_apply(t *testing.T) { fail := func() TLSOption { return func(ctx *TLSOptionCtx) error { @@ -78,7 +78,7 @@ func TestTLSOptionCtx_apply(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestRequireAndVerifyClientCert(t *testing.T) { tests := []struct { name string @@ -103,7 +103,7 @@ func TestRequireAndVerifyClientCert(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestVerifyClientCertIfGiven(t *testing.T) { tests := []struct { name string @@ -128,7 +128,7 @@ func TestVerifyClientCertIfGiven(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddRootCA(t *testing.T) { cert := parseCertificate(rootPEM) pool := x509.NewCertPool() @@ -161,7 +161,7 @@ func TestAddRootCA(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddClientCA(t *testing.T) { cert := parseCertificate(rootPEM) pool := x509.NewCertPool() @@ -194,7 +194,7 @@ func TestAddClientCA(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddRootsToRootCAs(t *testing.T) { ca := startCATestServer() defer ca.Close() @@ -249,7 +249,7 @@ func TestAddRootsToRootCAs(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddRootsToClientCAs(t *testing.T) { ca := startCATestServer() defer ca.Close() @@ -304,7 +304,7 @@ func TestAddRootsToClientCAs(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddFederationToRootCAs(t *testing.T) { ca := startCATestServer() defer ca.Close() @@ -369,7 +369,7 @@ func TestAddFederationToRootCAs(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddFederationToClientCAs(t *testing.T) { ca := startCATestServer() defer ca.Close() @@ -434,7 +434,7 @@ func TestAddFederationToClientCAs(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddRootsToCAs(t *testing.T) { ca := startCATestServer() defer ca.Close() @@ -489,7 +489,7 @@ func TestAddRootsToCAs(t *testing.T) { } } -// nolint:gosec // test tls config +//nolint:gosec // test tls config func TestAddFederationToCAs(t *testing.T) { ca := startCATestServer() defer ca.Close() @@ -554,7 +554,7 @@ func TestAddFederationToCAs(t *testing.T) { } } -// nolint:staticcheck,gocritic +//nolint:staticcheck,gocritic func equalPools(a, b *x509.CertPool) bool { if reflect.DeepEqual(a, b) { return true diff --git a/cas/apiv1/services.go b/cas/apiv1/services.go index c8a8b0e9..767d4994 100644 --- a/cas/apiv1/services.go +++ b/cas/apiv1/services.go @@ -59,9 +59,9 @@ func (t Type) String() string { return strings.ToLower(string(t)) } -// ErrNotImplemented is the type of error returned if an operation is not -// implemented. -type ErrNotImplemented struct { +// ErrNotImplemented is the type of error returned if an operation is not implemented. +type ErrNotImplemented struct { //nolint:errname // ignore error name warning + Message string } diff --git a/cas/cloudcas/cloudcas_test.go b/cas/cloudcas/cloudcas_test.go index e5fbf58e..48582462 100644 --- a/cas/cloudcas/cloudcas_test.go +++ b/cas/cloudcas/cloudcas_test.go @@ -104,7 +104,7 @@ MHcCAQEEIN51Rgg6YcQVLeCRzumdw4pjM3VWqFIdCbnsV3Up1e/goAoGCCqGSM49 AwEHoUQDQgAEjJIcDhvvxi7gu4aFkiW/8+E3BfPhmhXU5RlDQusre+MHXc7XYMtk Lm6PXPeTF1DNdS21Ju1G/j1yUykGJOmxkg== -----END EC PRIVATE KEY-----` - // nolint:unused,deadcode,gocritic + //nolint:unused,deadcode,gocritic,varcheck testIntermediateKey = `-----BEGIN EC PRIVATE KEY----- MHcCAQEEIMMX/XkXGnRDD4fYu7Z4rHACdJn/iyOy2UTwsv+oZ0C+oAoGCCqGSM49 AwEHoUQDQgAE8u6rGAFj5CZpdzzMogLwUyCMnp0X9wtv4OKDRcpzkYf9PU5GuGA6 @@ -399,7 +399,7 @@ func TestNew_real(t *testing.T) { if v, ok := os.LookupEnv("GOOGLE_APPLICATION_CREDENTIALS"); ok { os.Unsetenv("GOOGLE_APPLICATION_CREDENTIALS") t.Cleanup(func() { - os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", v) + t.Setenv("GOOGLE_APPLICATION_CREDENTIALS", v) }) } @@ -881,12 +881,12 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { fake.LROClient = client // Configure mocks - any := gomock.Any() + anee := gomock.Any() // ok root - m.EXPECT().GetCaPool(any, any).Return(nil, status.Error(codes.NotFound, "not found")) - m.EXPECT().CreateCaPool(any, any).Return(fake.CreateCaPoolOperation("CreateCaPool"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(nil, status.Error(codes.NotFound, "not found")) + m.EXPECT().CreateCaPool(anee, anee).Return(fake.CreateCaPoolOperation("CreateCaPool"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCaPool", Done: true, Result: &longrunningpb.Operation_Response{ @@ -895,8 +895,8 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -906,8 +906,8 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "EnableCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -919,9 +919,9 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { }, nil) // ok intermediate - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -930,15 +930,15 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) - m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{ + m.EXPECT().CreateCertificate(anee, anee).Return(&pb.Certificate{ PemCertificate: testIntermediateCertificate, PemCertificateChain: []string{testRootCertificate}, }, nil) - m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().ActivateCertificateAuthority(anee, anee).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "ActivateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -948,8 +948,8 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "EnableCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -961,9 +961,9 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { }, nil) // ok intermediate local signer - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -972,11 +972,11 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) - m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().ActivateCertificateAuthority(anee, anee).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "ActivateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -986,8 +986,8 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "EnableCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -999,9 +999,9 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { }, nil) // ok create key - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1011,8 +1011,8 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "EnableCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1024,30 +1024,30 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { }, nil) // fail GetCaPool - m.EXPECT().GetCaPool(any, any).Return(nil, errTest) + m.EXPECT().GetCaPool(anee, anee).Return(nil, errTest) // fail CreateCaPool - m.EXPECT().GetCaPool(any, any).Return(nil, status.Error(codes.NotFound, "not found")) - m.EXPECT().CreateCaPool(any, any).Return(nil, errTest) + m.EXPECT().GetCaPool(anee, anee).Return(nil, status.Error(codes.NotFound, "not found")) + m.EXPECT().CreateCaPool(anee, anee).Return(nil, errTest) // fail CreateCaPool.Wait - m.EXPECT().GetCaPool(any, any).Return(nil, status.Error(codes.NotFound, "not found")) - m.EXPECT().CreateCaPool(any, any).Return(fake.CreateCaPoolOperation("CreateCaPool"), nil) - mos.EXPECT().GetOperation(any, any).Return(nil, errTest) + m.EXPECT().GetCaPool(anee, anee).Return(nil, status.Error(codes.NotFound, "not found")) + m.EXPECT().CreateCaPool(anee, anee).Return(fake.CreateCaPoolOperation("CreateCaPool"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(nil, errTest) // fail CreateCertificateAuthority - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(nil, errTest) + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(nil, errTest) // fail CreateCertificateAuthority.Wait - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(nil, errTest) + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(nil, errTest) // fail EnableCertificateAuthority - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1057,12 +1057,12 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(nil, errTest) + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(nil, errTest) // fail EnableCertificateAuthority.Wait - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1072,13 +1072,13 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) - mos.EXPECT().GetOperation(any, any).Return(nil, errTest) + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(nil, errTest) // fail EnableCertificateAuthority intermediate - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1087,15 +1087,15 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) - m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{ + m.EXPECT().CreateCertificate(anee, anee).Return(&pb.Certificate{ PemCertificate: testIntermediateCertificate, PemCertificateChain: []string{testRootCertificate}, }, nil) - m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().ActivateCertificateAuthority(anee, anee).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "ActivateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1105,12 +1105,12 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(nil, errTest) + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(nil, errTest) // fail EnableCertificateAuthority.Wait intermediate - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1119,15 +1119,15 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) - m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{ + m.EXPECT().CreateCertificate(anee, anee).Return(&pb.Certificate{ PemCertificate: testIntermediateCertificate, PemCertificateChain: []string{testRootCertificate}, }, nil) - m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().ActivateCertificateAuthority(anee, anee).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "ActivateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1137,13 +1137,13 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().EnableCertificateAuthority(any, any).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) - mos.EXPECT().GetOperation(any, any).Return(nil, errTest) + m.EXPECT().EnableCertificateAuthority(anee, anee).Return(fake.EnableCertificateAuthorityOperation("EnableCertificateAuthorityOperation"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(nil, errTest) // fail FetchCertificateAuthorityCsr - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1152,12 +1152,12 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(nil, errTest) + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(nil, errTest) // fail CreateCertificate - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1166,15 +1166,15 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) - m.EXPECT().CreateCertificate(any, any).Return(nil, errTest) + m.EXPECT().CreateCertificate(anee, anee).Return(nil, errTest) // fail ActivateCertificateAuthority - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1183,19 +1183,19 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) - m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{ + m.EXPECT().CreateCertificate(anee, anee).Return(&pb.Certificate{ PemCertificate: testIntermediateCertificate, PemCertificateChain: []string{testRootCertificate}, }, nil) - m.EXPECT().ActivateCertificateAuthority(any, any).Return(nil, errTest) + m.EXPECT().ActivateCertificateAuthority(anee, anee).Return(nil, errTest) // fail ActivateCertificateAuthority.Wait - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1204,20 +1204,20 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) - m.EXPECT().CreateCertificate(any, any).Return(&pb.Certificate{ + m.EXPECT().CreateCertificate(anee, anee).Return(&pb.Certificate{ PemCertificate: testIntermediateCertificate, PemCertificateChain: []string{testRootCertificate}, }, nil) - m.EXPECT().ActivateCertificateAuthority(any, any).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(nil, errTest) + m.EXPECT().ActivateCertificateAuthority(anee, anee).Return(fake.ActivateCertificateAuthorityOperation("ActivateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(nil, errTest) // fail x509util.CreateCertificate - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1226,14 +1226,14 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: testIntermediateCsr, }, nil) // fail parseCertificateRequest - m.EXPECT().GetCaPool(any, any).Return(&pb.CaPool{Name: testCaPoolName}, nil) - m.EXPECT().CreateCertificateAuthority(any, any).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) - mos.EXPECT().GetOperation(any, any).Return(&longrunningpb.Operation{ + m.EXPECT().GetCaPool(anee, anee).Return(&pb.CaPool{Name: testCaPoolName}, nil) + m.EXPECT().CreateCertificateAuthority(anee, anee).Return(fake.CreateCertificateAuthorityOperation("CreateCertificateAuthority"), nil) + mos.EXPECT().GetOperation(anee, anee).Return(&longrunningpb.Operation{ Name: "CreateCertificateAuthority", Done: true, Result: &longrunningpb.Operation_Response{ @@ -1242,7 +1242,7 @@ func TestCloudCAS_CreateCertificateAuthority(t *testing.T) { })).(*anypb.Any), }, }, nil) - m.EXPECT().FetchCertificateAuthorityCsr(any, any).Return(&pb.FetchCertificateAuthorityCsrResponse{ + m.EXPECT().FetchCertificateAuthorityCsr(anee, anee).Return(&pb.FetchCertificateAuthorityCsrResponse{ PemCsr: "Not a CSR", }, nil) diff --git a/cas/softcas/softcas.go b/cas/softcas/softcas.go index dc6343f6..e00a36de 100644 --- a/cas/softcas/softcas.go +++ b/cas/softcas/softcas.go @@ -215,7 +215,6 @@ func (c *SoftCAS) getCertSigner() ([]*x509.Certificate, crypto.Signer, error) { return c.CertificateSigner() } return c.CertificateChain, c.Signer, nil - } // createKey uses the configured kms to create a key. diff --git a/cas/softcas/softcas_test.go b/cas/softcas/softcas_test.go index 8867b9b4..5c8a2f1f 100644 --- a/cas/softcas/softcas_test.go +++ b/cas/softcas/softcas_test.go @@ -261,9 +261,6 @@ func TestSoftCAS_CreateCertificate(t *testing.T) { tmplNotBefore := *testTemplate tmplNotBefore.NotBefore = testNow - tmplNotAfter := *testTemplate - tmplNotAfter.NotAfter = testNow.Add(24 * time.Hour) - tmplWithLifetime := *testTemplate tmplWithLifetime.NotBefore = testNow tmplWithLifetime.NotAfter = testNow.Add(24 * time.Hour) diff --git a/cmd/step-awskms-init/main.go b/cmd/step-awskms-init/main.go index ee46ba94..81a91067 100644 --- a/cmd/step-awskms-init/main.go +++ b/cmd/step-awskms-init/main.go @@ -4,7 +4,7 @@ import ( "context" "crypto" "crypto/rand" - "crypto/sha1" // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 "crypto/x509" "crypto/x509/pkix" "encoding/pem" @@ -242,7 +242,7 @@ func mustSubjectKeyID(key crypto.PublicKey) []byte { if err != nil { panic(err) } - // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 hash := sha1.Sum(b) return hash[:] } diff --git a/cmd/step-ca/main.go b/cmd/step-ca/main.go index d070b6cf..2c952cdd 100644 --- a/cmd/step-ca/main.go +++ b/cmd/step-ca/main.go @@ -14,7 +14,7 @@ import ( "time" // Server profiler - // nolint:gosec // profile server, if enabled runs on a different port + //nolint:gosec // profile server, if enabled runs on a different port _ "net/http/pprof" "github.com/smallstep/certificates/authority" diff --git a/cmd/step-cloudkms-init/main.go b/cmd/step-cloudkms-init/main.go index 98d81ac0..6cc36adf 100644 --- a/cmd/step-cloudkms-init/main.go +++ b/cmd/step-cloudkms-init/main.go @@ -4,7 +4,7 @@ import ( "context" "crypto" "crypto/rand" - "crypto/sha1" // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 "crypto/x509" "crypto/x509/pkix" "encoding/pem" @@ -280,7 +280,7 @@ func mustSubjectKeyID(key crypto.PublicKey) []byte { if err != nil { panic(err) } - // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 hash := sha1.Sum(b) return hash[:] } diff --git a/cmd/step-pkcs11-init/main.go b/cmd/step-pkcs11-init/main.go index 7595000c..30258cdd 100644 --- a/cmd/step-pkcs11-init/main.go +++ b/cmd/step-pkcs11-init/main.go @@ -6,7 +6,7 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" - "crypto/sha1" // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 "crypto/x509" "crypto/x509/pkix" "encoding/pem" @@ -547,7 +547,7 @@ func mustSubjectKeyID(key crypto.PublicKey) []byte { if err != nil { panic(err) } - // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 hash := sha1.Sum(b) return hash[:] } diff --git a/cmd/step-yubikey-init/main.go b/cmd/step-yubikey-init/main.go index a06afe04..cd6018cf 100644 --- a/cmd/step-yubikey-init/main.go +++ b/cmd/step-yubikey-init/main.go @@ -6,7 +6,7 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" - "crypto/sha1" // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + "crypto/sha1" //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 "crypto/x509" "crypto/x509/pkix" "encoding/hex" @@ -349,7 +349,7 @@ func mustSubjectKeyID(key crypto.PublicKey) []byte { if err != nil { panic(err) } - // nolint:gosec // used to create the Subject Key Identifier by RFC 5280 + //nolint:gosec // used to create the Subject Key Identifier by RFC 5280 hash := sha1.Sum(b) return hash[:] } diff --git a/commands/app.go b/commands/app.go index 7545f1df..7a0b2637 100644 --- a/commands/app.go +++ b/commands/app.go @@ -196,7 +196,7 @@ To get a linked authority token: } go ca.StopReloaderHandler(srv) - if err = srv.Run(); err != nil && err != http.ErrServerClosed { + if err = srv.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) { fatal(err) } return nil diff --git a/commands/onboard.go b/commands/onboard.go index bb704fd4..ef3b7854 100644 --- a/commands/onboard.go +++ b/commands/onboard.go @@ -92,11 +92,12 @@ func onboardAction(ctx *cli.Context) error { token := ctx.Args().Get(0) onboardingURL := u.ResolveReference(&url.URL{Path: token}).String() - // nolint:gosec // onboarding url + //nolint:gosec // onboarding url res, err := http.Get(onboardingURL) if err != nil { return errors.Wrap(err, "error connecting onboarding guide") } + defer res.Body.Close() if res.StatusCode >= 400 { var msg onboardingError if err := readJSON(res.Body, &msg); err != nil { @@ -133,7 +134,7 @@ func onboardAction(ctx *cli.Context) error { return errors.Wrap(err, "error marshaling payload") } - // nolint:gosec // onboarding url + //nolint:gosec // onboarding url resp, err := http.Post(onboardingURL, "application/json", bytes.NewBuffer(payload)) if err != nil { return errors.Wrap(err, "error connecting onboarding guide") @@ -158,7 +159,7 @@ func onboardAction(ctx *cli.Context) error { } go ca.StopReloaderHandler(srv) - if err := srv.Run(); err != nil && err != http.ErrServerClosed { + if err := srv.Run(); err != nil && !errors.Is(err, http.ErrServerClosed) { fatal(err) } diff --git a/errs/error.go b/errs/error.go index c42e342d..c8edd249 100644 --- a/errs/error.go +++ b/errs/error.go @@ -92,7 +92,8 @@ func Wrap(status int, e error, m string, args ...interface{}) error { return nil } _, opts := splitOptionArgs(args) - if err, ok := e.(*Error); ok { + var err *Error + if ok := errors.As(e, &err); ok { err.Err = errors.Wrap(err.Err, m) e = err } else { @@ -108,7 +109,8 @@ func Wrapf(status int, e error, format string, args ...interface{}) error { return nil } as, opts := splitOptionArgs(args) - if err, ok := e.(*Error); ok { + var err *Error + if ok := errors.As(e, &err); ok { err.Err = errors.Wrapf(err.Err, format, args...) e = err } else { @@ -141,6 +143,7 @@ func (e *Error) UnmarshalJSON(data []byte) error { // Format implements the fmt.Formatter interface. func (e *Error) Format(f fmt.State, c rune) { + //nolint:errorlint // ignore type assertion warning. casting to interface is hard. if err, ok := e.Err.(fmt.Formatter); ok { err.Format(f, c) return @@ -246,11 +249,12 @@ func New(status int, format string, args ...interface{}) error { // NewError creates a new http error with the given error and message. func NewError(status int, err error, format string, args ...interface{}) error { - if _, ok := err.(*Error); ok { + var e *Error + if errors.As(err, &e) { return err } msg := fmt.Sprintf(format, args...) - if _, ok := err.(log.StackTracedError); !ok { + if _, ok := log.AsStackTracedError(err); !ok { err = errors.Wrap(err, msg) } return &Error{ @@ -263,16 +267,13 @@ func NewError(status int, err error, format string, args ...interface{}) error { // NewErr returns a new Error. If the given error implements the StatusCoder // interface we will ignore the given status. func NewErr(status int, err error, opts ...Option) error { - var ( - e *Error - ok bool - ) - if e, ok = err.(*Error); !ok { - if sc, ok := err.(render.StatusCodedError); ok { + var e *Error + if !errors.As(err, &e) { + if sc, ok := render.AsStatusCodedError(err); ok { e = &Error{Status: sc.StatusCode(), Err: err} } else { cause := errors.Cause(err) - if sc, ok := cause.(render.StatusCodedError); ok { + if sc, ok := render.AsStatusCodedError(cause); ok { e = &Error{Status: sc.StatusCode(), Err: err} } else { e = &Error{Status: status, Err: err} @@ -299,7 +300,8 @@ func Errorf(code int, format string, args ...interface{}) error { // ApplyOptions applies the given options to the error if is the type *Error. // TODO(mariano): try to get rid of this. func ApplyOptions(err error, opts ...interface{}) error { - if e, ok := err.(*Error); ok { + var e *Error + if ok := errors.As(err, &e); ok { _, o := splitOptionArgs(opts) for _, fn := range o { fn(e) diff --git a/errs/errors_test.go b/errs/errors_test.go index a2accebb..7b83c8d9 100644 --- a/errs/errors_test.go +++ b/errs/errors_test.go @@ -57,6 +57,7 @@ func TestError_UnmarshalJSON(t *testing.T) { if err := e.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr { t.Errorf("Error.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) } + //nolint:govet // best option if !reflect.DeepEqual(tt.expected, e) { t.Errorf("Error.UnmarshalJSON() wants = %+v, got %+v", tt.expected, e) } diff --git a/pki/pki.go b/pki/pki.go index 4f3b2127..c05eadbd 100644 --- a/pki/pki.go +++ b/pki/pki.go @@ -389,7 +389,7 @@ func New(o apiv1.Options, opts ...Option) (*PKI, error) { if port == "443" || p.options.isHelm { p.Defaults.CaUrl = fmt.Sprintf("https://%s", p.Defaults.CaUrl) } else { - p.Defaults.CaUrl = fmt.Sprintf("https://%s:%s", p.Defaults.CaUrl, port) + p.Defaults.CaUrl = fmt.Sprintf("https://%s", net.JoinHostPort(p.Defaults.CaUrl, port)) } } diff --git a/policy/engine.go b/policy/engine.go index d1fb4928..4a0baa8f 100755 --- a/policy/engine.go +++ b/policy/engine.go @@ -73,7 +73,6 @@ func (e *NamePolicyError) Detail() string { // TODO(hs): implement matching URI schemes, paths, etc; not just the domain part of URI domains type NamePolicyEngine struct { - // verifySubjectCommonName is set when Subject Common Name must be verified verifySubjectCommonName bool // allowLiteralWildcardNames allows literal wildcard DNS domains @@ -107,7 +106,6 @@ type NamePolicyEngine struct { // NewNamePolicyEngine creates a new NamePolicyEngine with NamePolicyOptions func New(opts ...NamePolicyOption) (*NamePolicyEngine, error) { - e := &NamePolicyEngine{} for _, option := range opts { if err := option(e); err != nil { @@ -153,7 +151,6 @@ func New(opts ...NamePolicyOption) (*NamePolicyEngine, error) { // duplicate values removed. It retains the order of elements // in the source slice. func removeDuplicates(items []string) (ret []string) { - // no need to remove dupes; return original if len(items) <= 1 { return items @@ -179,7 +176,6 @@ func removeDuplicates(items []string) (ret []string) { // the source slice. An IPNet is considered duplicate if its CIDR // notation exists multiple times in the slice. func removeDuplicateIPNets(items []*net.IPNet) (ret []*net.IPNet) { - // no need to remove dupes; return original if len(items) <= 1 { return items diff --git a/policy/validate.go b/policy/validate.go index ee6f7e9c..f7cf6e70 100644 --- a/policy/validate.go +++ b/policy/validate.go @@ -8,6 +8,7 @@ package policy import ( "bytes" + "errors" "fmt" "net" "net/url" @@ -21,7 +22,6 @@ import ( // validateNames verifies that all names are allowed. func (e *NamePolicyEngine) validateNames(dnsNames []string, ips []net.IP, emailAddresses []string, uris []*url.URL, principals []string) error { - // nothing to compare against; return early if e.totalNumberOfConstraints == 0 { return nil @@ -182,7 +182,6 @@ func (e *NamePolicyEngine) validateNames(dnsNames []string, ips []net.IP, emailA // validateCommonName verifies that the Subject Common Name is allowed func (e *NamePolicyEngine) validateCommonName(commonName string) error { - // nothing to compare against; return early if e.totalNumberOfConstraints == 0 { return nil @@ -212,7 +211,8 @@ func (e *NamePolicyEngine) validateCommonName(commonName string) error { err := e.validateNames(dnsNames, ips, emails, uris, []string{}) - if pe, ok := err.(*NamePolicyError); ok { + var pe *NamePolicyError + if errors.As(err, &pe) { // override the name type with CN pe.NameType = CNNameType } @@ -229,7 +229,6 @@ func checkNameConstraints( parsedName interface{}, match func(parsedName, constraint interface{}) (match bool, err error), permitted, excluded interface{}) error { - excludedValue := reflect.ValueOf(excluded) for i := 0; i < excludedValue.Len(); i++ { @@ -552,7 +551,6 @@ func (e *NamePolicyEngine) matchDomainConstraint(domain, constraint string) (boo // SOURCE: https://cs.opensource.google/go/go/+/refs/tags/go1.17.5:src/crypto/x509/verify.go func matchIPConstraint(ip net.IP, constraint *net.IPNet) (bool, error) { - // TODO(hs): this is code from Go library, but I got some unexpected result: // with permitted net 127.0.0.0/24, 127.0.0.1 is NOT allowed. When parsing 127.0.0.1 as net.IP // which is in the IPAddresses slice, the underlying length is 16. The contraint.IP has a length diff --git a/scep/api/api.go b/scep/api/api.go index b738a933..346b9c75 100644 --- a/scep/api/api.go +++ b/scep/api/api.go @@ -350,7 +350,6 @@ func formatCapabilities(caps []string) []byte { // writeResponse writes a SCEP response back to the SCEP client. func writeResponse(w http.ResponseWriter, res Response) { - if res.Error != nil { log.Error(w, res.Error) } diff --git a/scep/authority.go b/scep/authority.go index 7dbbb8c5..bdba1d5f 100644 --- a/scep/authority.go +++ b/scep/authority.go @@ -71,7 +71,6 @@ type SignAuthority interface { // New returns a new Authority that implements the SCEP interface. func New(signAuth SignAuthority, ops AuthorityOptions) (*Authority, error) { - authority := &Authority{ prefix: ops.Prefix, dns: ops.DNS, @@ -145,7 +144,6 @@ func (a *Authority) getLinkExplicit(provisionerName string, abs bool, baseURL *u // GetCACertificates returns the certificate (chain) for the CA func (a *Authority) GetCACertificates(ctx context.Context) ([]*x509.Certificate, error) { - // TODO: this should return: the "SCEP Server (RA)" certificate, the issuing CA up to and excl. the root // Some clients do need the root certificate however; also see: https://github.com/openxpki/openxpki/issues/73 // @@ -385,7 +383,6 @@ func (a *Authority) SignCSR(ctx context.Context, csr *x509.CertificateRequest, m // CreateFailureResponse creates an appropriately signed reply for PKI operations func (a *Authority) CreateFailureResponse(ctx context.Context, csr *x509.CertificateRequest, msg *PKIMessage, info FailInfoName, infoText string) (*PKIMessage, error) { - config := pkcs7.SignerInfoConfig{ ExtraSignedAttributes: []pkcs7.Attribute{ { @@ -471,7 +468,6 @@ func (a *Authority) MatchChallengePassword(ctx context.Context, password string) // GetCACaps returns the CA capabilities func (a *Authority) GetCACaps(ctx context.Context) []string { - p, err := provisionerFromContext(ctx) if err != nil { return defaultCapabilities diff --git a/scep/options.go b/scep/options.go index 752b309a..201f1beb 100644 --- a/scep/options.go +++ b/scep/options.go @@ -20,7 +20,6 @@ type Options struct { // Validate checks the fields in Options. func (o *Options) Validate() error { - if o.CertificateChain == nil { return errors.New("certificate chain not configured correctly") } diff --git a/scep/service.go b/scep/service.go index 508bcf77..a4efe27e 100644 --- a/scep/service.go +++ b/scep/service.go @@ -14,7 +14,6 @@ type Service struct { } func NewService(ctx context.Context, opts Options) (*Service, error) { - if err := opts.Validate(); err != nil { return nil, err }