From b683251f716a1fd99ffc5d056516d7a80478d3d5 Mon Sep 17 00:00:00 2001 From: Ben Norcombe Date: Wed, 21 Jan 2026 12:24:21 +0000 Subject: [PATCH] Replace errors.New with fmt.Errorf --- bdns/dns.go | 2 +- bdns/dns_test.go | 15 +++--- bdns/mocks.go | 10 ++-- bdns/problem_test.go | 6 +-- bdns/servers.go | 11 ++--- ca/ca.go | 14 +++--- ca/ca_test.go | 6 +-- ca/crl.go | 11 ++--- cmd/admin/admin.go | 3 +- cmd/admin/cert.go | 12 ++--- cmd/admin/cert_test.go | 6 +-- cmd/admin/key.go | 2 +- cmd/admin/overrides_add.go | 5 +- cmd/admin/overrides_dump.go | 3 +- cmd/admin/overrides_import.go | 5 +- cmd/admin/overrides_toggle.go | 3 +- cmd/admin/pause_identifier.go | 4 +- cmd/admin/pause_identifier_test.go | 4 +- cmd/admin/unpause_account.go | 5 +- cmd/admin/unpause_account_test.go | 4 +- cmd/ceremony/cert.go | 41 ++++++++-------- cmd/ceremony/cert_test.go | 3 +- cmd/ceremony/crl.go | 9 ++-- cmd/ceremony/ecdsa.go | 3 +- cmd/ceremony/ecdsa_test.go | 10 ++-- cmd/ceremony/main.go | 47 +++++++++---------- cmd/ceremony/rsa.go | 6 +-- cmd/ceremony/rsa_test.go | 8 ++-- cmd/cert-checker/main_test.go | 4 +- cmd/config.go | 10 ++-- cmd/shell.go | 9 ++-- config/duration.go | 3 +- core/util.go | 2 +- core/util_test.go | 3 +- crl/idp/idp.go | 3 +- crl/storer/storer.go | 8 ++-- crl/storer/storer_test.go | 8 ++-- crl/updater/batch.go | 4 +- crl/updater/batch_test.go | 4 +- crl/updater/updater_test.go | 6 +-- csr/csr_test.go | 6 +-- ctpolicy/ctpolicy_test.go | 16 +++---- ctpolicy/loglist/loglist.go | 3 +- db/interfaces.go | 30 ++++++------ db/map_test.go | 5 +- email/exporter.go | 3 +- goodkey/good_key.go | 3 +- grpc/client.go | 2 +- grpc/creds/creds.go | 11 ++--- grpc/interceptors_test.go | 7 ++- .../resolver/dns/dns_resolver_test.go | 3 +- grpc/noncebalancer/noncebalancer.go | 10 ++-- grpc/server.go | 4 +- grpc/server_test.go | 6 +-- issuance/cert.go | 27 +++++------ issuance/crl_test.go | 6 +-- issuance/issuer.go | 23 +++++---- .../rfc/lint_crl_has_valid_timestamps.go | 13 +++-- log/log.go | 5 +- log/validator/validator.go | 4 +- mocks/sa.go | 10 ++-- nonce/nonce.go | 5 +- observer/mon_conf.go | 4 +- observer/obs_conf.go | 3 +- observer/obs_conf_test.go | 4 +- observer/probers/mock/mock_conf.go | 4 +- observer/probers/tls/tls.go | 3 +- pkcs11helpers/helpers.go | 19 ++++---- pkcs11helpers/helpers_test.go | 20 ++++---- policy/pa.go | 4 +- precert/corr.go | 5 +- privatekey/privatekey.go | 5 +- publisher/publisher.go | 2 +- ra/ra.go | 18 +++---- ra/ra_test.go | 5 +- ratelimits/limit.go | 3 +- ratelimits/limit_test.go | 3 +- ratelimits/source_redis.go | 3 +- ratelimits/transaction_test.go | 5 +- redis/lookup.go | 2 +- sa/database_test.go | 4 +- sa/model.go | 6 +-- sa/sa.go | 14 +++--- sa/type-converter.go | 5 +- sfe/overrides.go | 4 +- sfe/sfe.go | 2 +- test/certs/webpki.go | 3 +- test/chall-test-srv/history.go | 3 +- test/chall-test-srv/http.go | 4 +- test/load-generator/acme/challenge.go | 5 +- test/load-generator/acme/directory.go | 13 +++-- test/load-generator/boulder-calls.go | 9 ++-- test/load-generator/state.go | 5 +- test/zendeskfake/zendeskfake.go | 5 +- unpause/unpause.go | 12 ++--- va/caa.go | 3 +- va/caa_test.go | 7 ++- va/http_test.go | 15 +++--- va/tlsalpn.go | 11 ++--- va/va.go | 6 +-- va/va_test.go | 3 +- web/send_error_test.go | 6 +-- wfe2/cache_test.go | 4 +- wfe2/verify.go | 2 +- wfe2/wfe.go | 14 +++--- wfe2/wfe_test.go | 11 ++--- 106 files changed, 382 insertions(+), 430 deletions(-) diff --git a/bdns/dns.go b/bdns/dns.go index ea91a5c4349..1b19cb97883 100644 --- a/bdns/dns.go +++ b/bdns/dns.go @@ -266,7 +266,7 @@ func (c *impl) exchangeOne(ctx context.Context, hostname string, qtype uint16) ( // It's impossible to get past the bottom of the loop: on the last attempt // (when tries == c.maxTries), all paths lead to a return from inside the loop. - return nil, "", errors.New("unexpected loop escape in exchangeOne") + return nil, "", fmt.Errorf("unexpected loop escape in exchangeOne") } // LookupA sends a DNS query to find all A records associated with the provided diff --git a/bdns/dns_test.go b/bdns/dns_test.go index be964aea14f..d85f25b3427 100644 --- a/bdns/dns_test.go +++ b/bdns/dns_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/tls" "crypto/x509" - "errors" "fmt" "io" "log" @@ -606,7 +605,7 @@ type testExchanger struct { errs []error } -var errTooManyRequests = errors.New("too many requests") +var errTooManyRequests = fmt.Errorf("too many requests") func (te *testExchanger) ExchangeContext(ctx context.Context, m *dns.Msg, a string) (*dns.Msg, time.Duration, error) { if ctx.Err() != nil { @@ -630,8 +629,8 @@ func (te *testExchanger) ExchangeContext(ctx context.Context, m *dns.Msg, a stri func TestRetry(t *testing.T) { isTimeoutErr := &url.Error{Op: "read", Err: testTimeoutError(true)} nonTimeoutErr := &url.Error{Op: "read", Err: testTimeoutError(false)} - servFailError := errors.New("DNS problem: server failure at resolver looking up TXT for example.com") - timeoutFailError := errors.New("DNS problem: query timed out looking up TXT for example.com") + servFailError := fmt.Errorf("DNS problem: server failure at resolver looking up TXT for example.com") + timeoutFailError := fmt.Errorf("DNS problem: query timed out looking up TXT for example.com") type testCase struct { name string maxTries int @@ -656,7 +655,7 @@ func TestRetry(t *testing.T) { name: "non-operror", maxTries: 3, te: &testExchanger{ - errs: []error{errors.New("nope")}, + errs: []error{fmt.Errorf("nope")}, }, expected: servFailError, expectedCount: 1, @@ -666,7 +665,7 @@ func TestRetry(t *testing.T) { name: "err-then-non-operror", maxTries: 3, te: &testExchanger{ - errs: []error{isTimeoutErr, errors.New("nope")}, + errs: []error{isTimeoutErr, fmt.Errorf("nope")}, }, expected: servFailError, expectedCount: 2, @@ -798,7 +797,7 @@ func TestRetryMetrics(t *testing.T) { // checks for cancellation before doing any work. testClient := New(time.Second*10, staticProvider, metrics.NoopRegisterer, clock.NewFake(), 3, "", blog.UseMock(), tlsConfig) dr := testClient.(*impl) - dr.exchanger = &testExchanger{errs: []error{errors.New("oops")}} + dr.exchanger = &testExchanger{errs: []error{fmt.Errorf("oops")}} ctx, cancel := context.WithCancel(t.Context()) cancel() _, _, err = dr.LookupTXT(ctx, "example.com") @@ -817,7 +816,7 @@ func TestRetryMetrics(t *testing.T) { // let the go runtime cancel it as a result of a deadline in the past. testClient = New(time.Second*10, staticProvider, metrics.NoopRegisterer, clock.NewFake(), 3, "", blog.UseMock(), tlsConfig) dr = testClient.(*impl) - dr.exchanger = &testExchanger{errs: []error{errors.New("oops")}} + dr.exchanger = &testExchanger{errs: []error{fmt.Errorf("oops")}} ctx, cancel = context.WithTimeout(t.Context(), -10*time.Hour) defer cancel() _, _, err = dr.LookupTXT(ctx, "example.com") diff --git a/bdns/mocks.go b/bdns/mocks.go index d9c3b15ef0e..0c8aaf89903 100644 --- a/bdns/mocks.go +++ b/bdns/mocks.go @@ -2,7 +2,7 @@ package bdns import ( "context" - "errors" + "fmt" "github.com/miekg/dns" ) @@ -12,20 +12,20 @@ type MockClient struct{} // LookupTXT is a mock func (mock *MockClient) LookupTXT(_ context.Context, hostname string) (*Result[*dns.TXT], string, error) { - return nil, "MockClient", errors.New("unexpected LookupTXT call on test fake") + return nil, "MockClient", fmt.Errorf("unexpected LookupTXT call on test fake") } // LookupA is a fake func (mock *MockClient) LookupA(_ context.Context, hostname string) (*Result[*dns.A], string, error) { - return nil, "MockClient", errors.New("unexpected LookupA call on test fake") + return nil, "MockClient", fmt.Errorf("unexpected LookupA call on test fake") } // LookupAAAA is a fake func (mock *MockClient) LookupAAAA(_ context.Context, hostname string) (*Result[*dns.AAAA], string, error) { - return nil, "MockClient", errors.New("unexpected LookupAAAA call on test fake") + return nil, "MockClient", fmt.Errorf("unexpected LookupAAAA call on test fake") } // LookupCAA is a fake func (mock *MockClient) LookupCAA(_ context.Context, domain string) (*Result[*dns.CAA], string, error) { - return nil, "MockClient", errors.New("unexpected LookupCAA call on test fake") + return nil, "MockClient", fmt.Errorf("unexpected LookupCAA call on test fake") } diff --git a/bdns/problem_test.go b/bdns/problem_test.go index bdf7040b019..b0fee4d622c 100644 --- a/bdns/problem_test.go +++ b/bdns/problem_test.go @@ -2,7 +2,7 @@ package bdns import ( "context" - "errors" + "fmt" "net" "net/url" "testing" @@ -18,7 +18,7 @@ func TestError(t *testing.T) { expected string }{ { - &Error{dns.TypeMX, "hostname", &net.OpError{Err: errors.New("some net error")}, -1, nil}, + &Error{dns.TypeMX, "hostname", &net.OpError{Err: fmt.Errorf("some net error")}, -1, nil}, "DNS problem: networking error looking up MX for hostname", }, { &Error{dns.TypeTXT, "hostname", nil, dns.RcodeNameError, nil}, @@ -85,6 +85,6 @@ func TestWrapErr(t *testing.T) { err = wrapErr(dns.TypeA, "hostname", &dns.Msg{ MsgHdr: dns.MsgHdr{Rcode: dns.RcodeSuccess}, - }, errors.New("oh no")) + }, fmt.Errorf("oh no")) test.AssertError(t, err, "expected error") } diff --git a/bdns/servers.go b/bdns/servers.go index 19abc1e2fff..0a26f638bb7 100644 --- a/bdns/servers.go +++ b/bdns/servers.go @@ -2,7 +2,6 @@ package bdns import ( "context" - "errors" "fmt" "math/rand/v2" "net" @@ -49,7 +48,7 @@ func validateServerAddress(address string) error { // Ensure `address` contains both a `host` and `port` portion. if host == "" || port == "" { - return errors.New("port cannot be missing") + return fmt.Errorf("port cannot be missing") } // Ensure the `port` portion of `address` is a valid port. @@ -58,14 +57,14 @@ func validateServerAddress(address string) error { return fmt.Errorf("parsing port number: %s", err) } if portNum <= 0 || portNum > 65535 { - return errors.New("port must be an integer between 0 - 65535") + return fmt.Errorf("port must be an integer between 0 - 65535") } // Ensure the `host` portion of `address` is a valid FQDN or IP address. _, err = netip.ParseAddr(host) FQDN := dns.IsFqdn(dns.Fqdn(host)) if err != nil && !FQDN { - return errors.New("host is not an FQDN or IP address") + return fmt.Errorf("host is not an FQDN or IP address") } return nil } @@ -140,7 +139,7 @@ type dynamicProvider struct { // It has been minimally modified to fit our code style. func ParseTarget(target, defaultPort string) (host, port string, err error) { if target == "" { - return "", "", errors.New("missing address") + return "", "", fmt.Errorf("missing address") } ip := net.ParseIP(target) if ip != nil { @@ -152,7 +151,7 @@ func ParseTarget(target, defaultPort string) (host, port string, err error) { if port == "" { // If the port field is empty (target ends with colon), e.g. // "[::1]:", this is an error. - return "", "", errors.New("missing port after port-separator colon") + return "", "", fmt.Errorf("missing port after port-separator colon") } // target has port, i.e ipv4-host:port, [ipv6-host]:port, host-name:port if host == "" { diff --git a/ca/ca.go b/ca/ca.go index 656aaf49b23..f2a6a330b38 100644 --- a/ca/ca.go +++ b/ca/ca.go @@ -147,15 +147,15 @@ func NewCertificateAuthorityImpl( clk clock.Clock, ) (*certificateAuthorityImpl, error) { if serialPrefix < 0x01 || serialPrefix > 0x7f { - return nil, errors.New("serial prefix must be between 0x01 (1) and 0x7f (127)") + return nil, fmt.Errorf("serial prefix must be between 0x01 (1) and 0x7f (127)") } if len(issuers) == 0 { - return nil, errors.New("must have at least one issuer") + return nil, fmt.Errorf("must have at least one issuer") } if len(profiles) == 0 { - return nil, errors.New("must have at least one certificate profile") + return nil, fmt.Errorf("must have at least one certificate profile") } issuableKeys := make(map[x509.PublicKeyAlgorithm]bool) @@ -224,7 +224,7 @@ func (ca *certificateAuthorityImpl) IssueCertificate(ctx context.Context, req *c } if ca.sctClient == nil { - return nil, errors.New("IssueCertificate called with a nil SCT service") + return nil, fmt.Errorf("IssueCertificate called with a nil SCT service") } profile, ok := ca.profiles[req.CertProfileName] @@ -553,17 +553,17 @@ func tbsCertIsDeterministic(lintCertBytes []byte, leafCertBytes []byte) error { // Extract the Certificate bytes if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) { - return nil, errors.New("malformed certificate") + return nil, fmt.Errorf("malformed certificate") } var tbs cryptobyte.String // Extract the TBSCertificate bytes from the Certificate bytes if !input.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) { - return nil, errors.New("malformed tbs certificate") + return nil, fmt.Errorf("malformed tbs certificate") } if tbs.Empty() { - return nil, errors.New("parsed RawTBSCertificate field was empty") + return nil, fmt.Errorf("parsed RawTBSCertificate field was empty") } return tbs, nil diff --git a/ca/ca_test.go b/ca/ca_test.go index 042056d33a9..63b3719ed1a 100644 --- a/ca/ca_test.go +++ b/ca/ca_test.go @@ -389,7 +389,7 @@ func deserializeSCTList(sctListExtensionValue []byte) ([]ct.SignedCertificateTim return nil, err } if len(rest) != 0 { - return nil, errors.New("serialized SCT list contained trailing garbage") + return nil, fmt.Errorf("serialized SCT list contained trailing garbage") } list := make([]ct.SignedCertificateTimestamp, len(sctList.SCTList)) for i, serializedSCT := range sctList.SCTList { @@ -399,7 +399,7 @@ func deserializeSCTList(sctListExtensionValue []byte) ([]ct.SignedCertificateTim return nil, err } if len(rest) != 0 { - return nil, errors.New("serialized SCT contained trailing garbage") + return nil, fmt.Errorf("serialized SCT contained trailing garbage") } list[i] = sct } @@ -928,7 +928,7 @@ func TestNoteSignError(t *testing.T) { testCtx := newCAArgs(t) metrics := testCtx.metrics - err := fmt.Errorf("wrapped non-signing error: %w", errors.New("oops")) + err := fmt.Errorf("wrapped non-signing error: %w", fmt.Errorf("oops")) metrics.noteSignError(err) test.AssertMetricWithLabelsEquals(t, metrics.signErrorCount, prometheus.Labels{"type": "HSM"}, 0) diff --git a/ca/crl.go b/ca/crl.go index 513b9deaee0..e919b3b6104 100644 --- a/ca/crl.go +++ b/ca/crl.go @@ -3,7 +3,6 @@ package ca import ( "crypto/sha256" "crypto/x509" - "errors" "fmt" "io" "strings" @@ -83,7 +82,7 @@ func (ci *crlImpl) GenerateCRL(stream grpc.BidiStreamingServer[capb.GenerateCRLR switch payload := in.Payload.(type) { case *capb.GenerateCRLRequest_Metadata: if req != nil { - return errors.New("got more than one metadata message") + return fmt.Errorf("got more than one metadata message") } req, err = ci.metadataToRequest(payload.Metadata) @@ -106,12 +105,12 @@ func (ci *crlImpl) GenerateCRL(stream grpc.BidiStreamingServer[capb.GenerateCRLR rcs = append(rcs, *rc) default: - return errors.New("got empty or malformed message in input stream") + return fmt.Errorf("got empty or malformed message in input stream") } } if req == nil { - return errors.New("no crl metadata received") + return fmt.Errorf("no crl metadata received") } // Compute a unique ID for this issuer-number-shard combo, to tie together all @@ -174,7 +173,7 @@ func (ci *crlImpl) GenerateCRL(stream grpc.BidiStreamingServer[capb.GenerateCRLR func (ci *crlImpl) metadataToRequest(meta *capb.CRLMetadata) (*issuance.CRLRequest, error) { if core.IsAnyNilOrZero(meta.IssuerNameID, meta.ThisUpdate, meta.ShardIdx) { - return nil, errors.New("got incomplete metadata message") + return nil, fmt.Errorf("got incomplete metadata message") } thisUpdate := meta.ThisUpdate.AsTime() number := bcrl.Number(thisUpdate) @@ -193,7 +192,7 @@ func (ci *crlImpl) entryToRevokedCertificate(entry *corepb.CRLEntry) (*x509.Revo } if core.IsAnyNilOrZero(entry.RevokedAt) { - return nil, errors.New("got empty or zero revocation timestamp") + return nil, fmt.Errorf("got empty or zero revocation timestamp") } revokedAt := entry.RevokedAt.AsTime() diff --git a/cmd/admin/admin.go b/cmd/admin/admin.go index 0f738d6153d..76ba31e0b34 100644 --- a/cmd/admin/admin.go +++ b/cmd/admin/admin.go @@ -2,7 +2,6 @@ package main import ( "context" - "errors" "fmt" "github.com/jmhodges/clock" @@ -91,7 +90,7 @@ func findActiveInputMethodFlag(setInputs map[string]bool) (string, error) { } if len(activeFlags) == 0 { - return "", errors.New("at least one input method flag must be specified") + return "", fmt.Errorf("at least one input method flag must be specified") } else if len(activeFlags) > 1 { return "", fmt.Errorf("more than one input method flag specified: %v", activeFlags) } diff --git a/cmd/admin/cert.go b/cmd/admin/cert.go index aee1a6c66e0..be4286ee081 100644 --- a/cmd/admin/cert.go +++ b/cmd/admin/cert.go @@ -82,13 +82,13 @@ func (s *subcommandRevokeCert) Run(ctx context.Context, a *admin) error { if s.skipBlock && reasonCode == revocation.KeyCompromise { // We would only add the SPKI hash of the pubkey to the blockedKeys table if // the revocation reason is keyCompromise. - return errors.New("-skip-block-key only makes sense with -reason=1") + return fmt.Errorf("-skip-block-key only makes sense with -reason=1") } if s.malformed && reasonCode == revocation.KeyCompromise { // This is because we can't extract and block the pubkey if we can't // parse the certificate. - return errors.New("cannot revoke malformed certs for reason keyCompromise") + return fmt.Errorf("cannot revoke malformed certs for reason keyCompromise") } // This is a map of all input-selection flags to whether or not they were set @@ -122,7 +122,7 @@ func (s *subcommandRevokeCert) Run(ctx context.Context, a *admin) error { case "-cert-file": serials, err = a.serialsFromCertPEM(ctx, s.certFile) default: - return errors.New("no recognized input method flag set (this shouldn't happen)") + return fmt.Errorf("no recognized input method flag set (this shouldn't happen)") } if err != nil { return fmt.Errorf("collecting serials to revoke: %w", err) @@ -134,7 +134,7 @@ func (s *subcommandRevokeCert) Run(ctx context.Context, a *admin) error { } if len(serials) == 0 { - return errors.New("no serials to revoke found") + return fmt.Errorf("no serials to revoke found") } a.log.Infof("Found %d certificates to revoke", len(serials)) @@ -157,10 +157,10 @@ func (s *subcommandRevokeCert) revokeMalformed(ctx context.Context, a *admin, se return fmt.Errorf("getting admin username: %w", err) } if s.crlShard == 0 { - return errors.New("when revoking malformed certificates, a nonzero CRL shard must be specified") + return fmt.Errorf("when revoking malformed certificates, a nonzero CRL shard must be specified") } if len(serials) > 1 { - return errors.New("when revoking malformed certificates, only one cert at a time is allowed") + return fmt.Errorf("when revoking malformed certificates, only one cert at a time is allowed") } _, err = a.rac.AdministrativelyRevokeCertificate( ctx, diff --git a/cmd/admin/cert_test.go b/cmd/admin/cert_test.go index cbf0bd5eb66..3b7162c83df 100644 --- a/cmd/admin/cert_test.go +++ b/cmd/admin/cert_test.go @@ -7,7 +7,7 @@ import ( "crypto/rand" "crypto/x509" "encoding/pem" - "errors" + "fmt" "os" "path" "reflect" @@ -136,7 +136,7 @@ type mockSAWithAccount struct { func (msa *mockSAWithAccount) GetRegistration(_ context.Context, req *sapb.RegistrationID, _ ...grpc.CallOption) (*corepb.Registration, error) { if req.Id != msa.regID { - return nil, errors.New("no such reg") + return nil, fmt.Errorf("no such reg") } return &corepb.Registration{}, nil } @@ -182,7 +182,7 @@ func (mra *mockRARecordingRevocations) AdministrativelyRevokeCertificate(_ conte defer mra.Unlock() mra.revocationRequests = append(mra.revocationRequests, req) if slices.Contains(mra.doomedToFail, req.Serial) { - return nil, errors.New("oops") + return nil, fmt.Errorf("oops") } if slices.Contains(mra.alreadyRevoked, req.Serial) { return nil, berrors.AlreadyRevokedError("too slow") diff --git a/cmd/admin/key.go b/cmd/admin/key.go index 63b0621bde9..a7bc38b2506 100644 --- a/cmd/admin/key.go +++ b/cmd/admin/key.go @@ -86,7 +86,7 @@ func (s *subcommandBlockKey) Run(ctx context.Context, a *admin) error { case "-csr-file": spkiHashes, err = a.spkiHashFromCSRPEM(s.csrFile, s.checkSignature, s.csrFileExpectedCN) default: - return errors.New("no recognized input method flag set (this shouldn't happen)") + return fmt.Errorf("no recognized input method flag set (this shouldn't happen)") } if err != nil { return fmt.Errorf("collecting spki hashes to block: %w", err) diff --git a/cmd/admin/overrides_add.go b/cmd/admin/overrides_add.go index 6c217b0a13f..fc14b9704c1 100644 --- a/cmd/admin/overrides_add.go +++ b/cmd/admin/overrides_add.go @@ -2,7 +2,6 @@ package main import ( "context" - "errors" "flag" "fmt" "net/netip" @@ -67,10 +66,10 @@ func validateIdentifiers(idents ...identifier.ACMEIdentifier) error { func (c *subcommandAddOverride) Run(ctx context.Context, a *admin) error { if c.limit == "" { - return errors.New("--limit is required") + return fmt.Errorf("--limit is required") } if c.count == 0 || c.burst == 0 || c.period == "" || c.comment == "" { - return errors.New("all of --count, --burst, --period, and --comment are required") + return fmt.Errorf("all of --count, --burst, --period, and --comment are required") } name, ok := rl.StringToName[c.limit] diff --git a/cmd/admin/overrides_dump.go b/cmd/admin/overrides_dump.go index 810def1ae05..b7b6f28af61 100644 --- a/cmd/admin/overrides_dump.go +++ b/cmd/admin/overrides_dump.go @@ -2,7 +2,6 @@ package main import ( "context" - "errors" "flag" "fmt" "io" @@ -26,7 +25,7 @@ func (c *subcommandDumpEnabledOverrides) Flags(f *flag.FlagSet) { func (c *subcommandDumpEnabledOverrides) Run(ctx context.Context, a *admin) error { if c.file == "" { - return errors.New("--file is required") + return fmt.Errorf("--file is required") } stream, err := a.sac.GetEnabledRateLimitOverrides(ctx, &emptypb.Empty{}) diff --git a/cmd/admin/overrides_import.go b/cmd/admin/overrides_import.go index a061f0a3757..3e56c0e5435 100644 --- a/cmd/admin/overrides_import.go +++ b/cmd/admin/overrides_import.go @@ -2,7 +2,6 @@ package main import ( "context" - "errors" "flag" "fmt" "sync" @@ -26,10 +25,10 @@ func (c *subcommandImportOverrides) Flags(f *flag.FlagSet) { func (c *subcommandImportOverrides) Run(ctx context.Context, a *admin) error { if c.file == "" { - return errors.New("--file is required") + return fmt.Errorf("--file is required") } if c.parallelism <= 0 { - return errors.New("--parallelism must be greater than 0") + return fmt.Errorf("--parallelism must be greater than 0") } overrides, err := ratelimits.LoadOverridesByBucketKey(c.file) if err != nil { diff --git a/cmd/admin/overrides_toggle.go b/cmd/admin/overrides_toggle.go index 99e713b2907..f5b3f572212 100644 --- a/cmd/admin/overrides_toggle.go +++ b/cmd/admin/overrides_toggle.go @@ -2,7 +2,6 @@ package main import ( "context" - "errors" "flag" "fmt" "net/netip" @@ -38,7 +37,7 @@ func (c *subcommandToggleOverride) Flags(f *flag.FlagSet) { func (c *subcommandToggleOverride) Run(ctx context.Context, a *admin) error { if c.limit == "" { - return errors.New("--limit is required") + return fmt.Errorf("--limit is required") } name, ok := rl.StringToName[c.limit] if !ok { diff --git a/cmd/admin/pause_identifier.go b/cmd/admin/pause_identifier.go index da268d7245b..b9fabfef843 100644 --- a/cmd/admin/pause_identifier.go +++ b/cmd/admin/pause_identifier.go @@ -36,7 +36,7 @@ func (p *subcommandPauseIdentifier) Flags(flag *flag.FlagSet) { func (p *subcommandPauseIdentifier) Run(ctx context.Context, a *admin) error { if p.batchFile == "" { - return errors.New("the -batch-file flag is required") + return fmt.Errorf("the -batch-file flag is required") } idents, err := a.readPausedAccountFile(p.batchFile) @@ -57,7 +57,7 @@ func (p *subcommandPauseIdentifier) Run(ctx context.Context, a *admin) error { // errors. func (a *admin) pauseIdentifiers(ctx context.Context, entries []pauseCSVData, parallelism uint) ([]*sapb.PauseIdentifiersResponse, error) { if len(entries) <= 0 { - return nil, errors.New("cannot pause identifiers because no pauseData was sent") + return nil, fmt.Errorf("cannot pause identifiers because no pauseData was sent") } accountToIdents := make(map[int64][]*corepb.Identifier) diff --git a/cmd/admin/pause_identifier_test.go b/cmd/admin/pause_identifier_test.go index 937cf179107..32bac860b1d 100644 --- a/cmd/admin/pause_identifier_test.go +++ b/cmd/admin/pause_identifier_test.go @@ -2,7 +2,7 @@ package main import ( "context" - "errors" + "fmt" "os" "path" "strings" @@ -96,7 +96,7 @@ type mockSAPausedBroken struct { } func (msa *mockSAPausedBroken) PauseIdentifiers(ctx context.Context, in *sapb.PauseRequest, _ ...grpc.CallOption) (*sapb.PauseIdentifiersResponse, error) { - return nil, errors.New("its all jacked up") + return nil, fmt.Errorf("its all jacked up") } func TestPauseIdentifiers(t *testing.T) { diff --git a/cmd/admin/unpause_account.go b/cmd/admin/unpause_account.go index 7f38c20b02e..bed016f5c51 100644 --- a/cmd/admin/unpause_account.go +++ b/cmd/admin/unpause_account.go @@ -3,7 +3,6 @@ package main import ( "bufio" "context" - "errors" "flag" "fmt" "os" @@ -55,7 +54,7 @@ func (u *subcommandUnpauseAccount) Run(ctx context.Context, a *admin) error { case "-batch-file": regIDs, err = a.readUnpauseAccountFile(u.batchFile) default: - return errors.New("no recognized input method flag set (this shouldn't happen)") + return fmt.Errorf("no recognized input method flag set (this shouldn't happen)") } if err != nil { return fmt.Errorf("collecting serials to revoke: %w", err) @@ -79,7 +78,7 @@ type unpauseCount struct { // unpaused for each account and any accumulated errors. func (a *admin) unpauseAccounts(ctx context.Context, accountIDs []int64, parallelism uint) ([]unpauseCount, error) { if len(accountIDs) <= 0 { - return nil, errors.New("no account IDs provided for unpausing") + return nil, fmt.Errorf("no account IDs provided for unpausing") } slices.Sort(accountIDs) accountIDs = slices.Compact(accountIDs) diff --git a/cmd/admin/unpause_account_test.go b/cmd/admin/unpause_account_test.go index f39b168fcbf..5e409c78792 100644 --- a/cmd/admin/unpause_account_test.go +++ b/cmd/admin/unpause_account_test.go @@ -2,7 +2,7 @@ package main import ( "context" - "errors" + "fmt" "os" "path" "strings" @@ -74,7 +74,7 @@ type mockSAUnpauseBroken struct { } func (msa *mockSAUnpauseBroken) UnpauseAccount(ctx context.Context, in *sapb.RegistrationID, _ ...grpc.CallOption) (*sapb.Count, error) { - return nil, errors.New("oh dear") + return nil, fmt.Errorf("oh dear") } func TestUnpauseAccounts(t *testing.T) { diff --git a/cmd/ceremony/cert.go b/cmd/ceremony/cert.go index f2dfd734f3a..d42df64d44a 100644 --- a/cmd/ceremony/cert.go +++ b/cmd/ceremony/cert.go @@ -6,7 +6,6 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/asn1" - "errors" "fmt" "io" "math/big" @@ -89,65 +88,65 @@ func (profile *certProfile) Subject() pkix.Name { func (profile *certProfile) verifyProfile(ct certType) error { if ct == requestCert { if profile.NotBefore != "" { - return errors.New("not-before cannot be set for a CSR") + return fmt.Errorf("not-before cannot be set for a CSR") } if profile.NotAfter != "" { - return errors.New("not-after cannot be set for a CSR") + return fmt.Errorf("not-after cannot be set for a CSR") } if profile.SignatureAlgorithm != "" { - return errors.New("signature-algorithm cannot be set for a CSR") + return fmt.Errorf("signature-algorithm cannot be set for a CSR") } if profile.CRLURL != "" { - return errors.New("crl-url cannot be set for a CSR") + return fmt.Errorf("crl-url cannot be set for a CSR") } if profile.IssuerURL != "" { - return errors.New("issuer-url cannot be set for a CSR") + return fmt.Errorf("issuer-url cannot be set for a CSR") } if profile.Policies != nil { - return errors.New("policies cannot be set for a CSR") + return fmt.Errorf("policies cannot be set for a CSR") } if profile.KeyUsages != nil { - return errors.New("key-usages cannot be set for a CSR") + return fmt.Errorf("key-usages cannot be set for a CSR") } } else { if profile.NotBefore == "" { - return errors.New("not-before is required") + return fmt.Errorf("not-before is required") } if profile.NotAfter == "" { - return errors.New("not-after is required") + return fmt.Errorf("not-after is required") } if profile.SignatureAlgorithm == "" { - return errors.New("signature-algorithm is required") + return fmt.Errorf("signature-algorithm is required") } } if profile.CommonName == "" { - return errors.New("common-name is required") + return fmt.Errorf("common-name is required") } if profile.Organization == "" { - return errors.New("organization is required") + return fmt.Errorf("organization is required") } if profile.Country == "" { - return errors.New("country is required") + return fmt.Errorf("country is required") } if ct == rootCert { if len(profile.Policies) != 0 { - return errors.New("policies should not be set on root certs") + return fmt.Errorf("policies should not be set on root certs") } } if ct == intermediateCert || ct == crossCert { if profile.CRLURL == "" { - return errors.New("crl-url is required for subordinate CAs") + return fmt.Errorf("crl-url is required for subordinate CAs") } if profile.IssuerURL == "" { - return errors.New("issuer-url is required for subordinate CAs") + return fmt.Errorf("issuer-url is required for subordinate CAs") } // BR 7.1.2.10.5 CA Certificate Certificate Policies // OID 2.23.140.1.2.1 is CABF BRs Domain Validated if len(profile.Policies) != 1 || profile.Policies[0].OID != "2.23.140.1.2.1" { - return errors.New("policy should be exactly BRs domain-validated for subordinate CAs") + return fmt.Errorf("policy should be exactly BRs domain-validated for subordinate CAs") } } @@ -162,7 +161,7 @@ func parseOID(oidStr string) (asn1.ObjectIdentifier, error) { return nil, err } if i <= 0 { - return nil, errors.New("OID components must be >= 1") + return nil, fmt.Errorf("OID components must be >= 1") } oid = append(oid, i) } @@ -228,7 +227,7 @@ func makeTemplate(randReader io.Reader, profile *certProfile, pubKey []byte, tbc ku |= kuBit } if ku == 0 { - return nil, errors.New("at least one key usage must be set") + return nil, fmt.Errorf("at least one key usage must be set") } cert := &x509.Certificate{ @@ -311,7 +310,7 @@ func makeTemplate(randReader io.Reader, profile *certProfile, pubKey []byte, tbc type failReader struct{} func (fr *failReader) Read([]byte) (int, error) { - return 0, errors.New("empty reader used by x509.CreateCertificate") + return 0, fmt.Errorf("empty reader used by x509.CreateCertificate") } func generateCSR(profile *certProfile, signer crypto.Signer) ([]byte, error) { diff --git a/cmd/ceremony/cert_test.go b/cmd/ceremony/cert_test.go index 2cdf78f8c67..ea8bc3c1121 100644 --- a/cmd/ceremony/cert_test.go +++ b/cmd/ceremony/cert_test.go @@ -8,7 +8,6 @@ import ( "crypto/x509/pkix" "encoding/asn1" "encoding/hex" - "errors" "fmt" "io/fs" "math/big" @@ -86,7 +85,7 @@ func TestMakeTemplateRoot(t *testing.T) { profile.SignatureAlgorithm = "SHA256WithRSA" ctx.GenerateRandomFunc = func(pkcs11.SessionHandle, int) ([]byte, error) { - return nil, errors.New("bad") + return nil, fmt.Errorf("bad") } _, err = makeTemplate(randReader, profile, pubKey, nil, rootCert) test.AssertError(t, err, "makeTemplate didn't fail when GenerateRandom failed") diff --git a/cmd/ceremony/crl.go b/cmd/ceremony/crl.go index cde31023dbb..0d3ee7b2d1e 100644 --- a/cmd/ceremony/crl.go +++ b/cmd/ceremony/crl.go @@ -4,7 +4,6 @@ import ( "crypto" "crypto/x509" "encoding/pem" - "errors" "fmt" "math/big" "time" @@ -22,18 +21,18 @@ func generateCRL(signer crypto.Signer, issuer *x509.Certificate, thisUpdate, nex } if nextUpdate.Before(thisUpdate) { - return nil, errors.New("thisUpdate must be before nextUpdate") + return nil, fmt.Errorf("thisUpdate must be before nextUpdate") } if thisUpdate.Before(issuer.NotBefore) { - return nil, errors.New("thisUpdate is before issuing certificate's notBefore") + return nil, fmt.Errorf("thisUpdate is before issuing certificate's notBefore") } else if nextUpdate.After(issuer.NotAfter) { - return nil, errors.New("nextUpdate is after issuing certificate's notAfter") + return nil, fmt.Errorf("nextUpdate is after issuing certificate's notAfter") } // Verify that the CRL is not valid for more than 12 months as specified in // CABF BRs Section 4.9.7 if nextUpdate.Sub(thisUpdate) > time.Hour*24*365 { - return nil, errors.New("nextUpdate must be less than 12 months after thisUpdate") + return nil, fmt.Errorf("nextUpdate must be less than 12 months after thisUpdate") } // Add the Issuing Distribution Point extension. idp, err := idp.MakeCACertsExt() diff --git a/cmd/ceremony/ecdsa.go b/cmd/ceremony/ecdsa.go index e6d8700940e..7ba25f65536 100644 --- a/cmd/ceremony/ecdsa.go +++ b/cmd/ceremony/ecdsa.go @@ -3,7 +3,6 @@ package main import ( "crypto/ecdsa" "crypto/elliptic" - "errors" "fmt" "log" @@ -69,7 +68,7 @@ func ecPub( return nil, err } if pubKey.Curve != expectedCurve { - return nil, errors.New("returned EC parameters doesn't match expected curve") + return nil, fmt.Errorf("returned EC parameters doesn't match expected curve") } log.Printf("\tX: %X\n", pubKey.X.Bytes()) log.Printf("\tY: %X\n", pubKey.Y.Bytes()) diff --git a/cmd/ceremony/ecdsa_test.go b/cmd/ceremony/ecdsa_test.go index 8bd34867581..6a6b4674aa8 100644 --- a/cmd/ceremony/ecdsa_test.go +++ b/cmd/ceremony/ecdsa_test.go @@ -4,7 +4,7 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" - "errors" + "fmt" "testing" "github.com/letsencrypt/boulder/pkcs11helpers" @@ -17,7 +17,7 @@ func TestECPub(t *testing.T) { // test we fail when pkcs11helpers.GetECDSAPublicKey fails ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { - return nil, errors.New("bad!") + return nil, fmt.Errorf("bad!") } _, err := ecPub(s, 0, elliptic.P256()) test.AssertError(t, err, "ecPub didn't fail with non-matching curve") @@ -49,7 +49,7 @@ func TestECGenerate(t *testing.T) { // Test ecGenerate fails when GenerateKeyPair fails ctx.GenerateKeyPairFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) { - return 0, 0, errors.New("bad") + return 0, 0, fmt.Errorf("bad") } _, _, err = ecGenerate(s, "", "P-256") test.AssertError(t, err, "ecGenerate didn't fail on GenerateKeyPair error") @@ -59,7 +59,7 @@ func TestECGenerate(t *testing.T) { return 0, 0, nil } ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { - return nil, errors.New("bad") + return nil, fmt.Errorf("bad") } _, _, err = ecGenerate(s, "", "P-256") test.AssertError(t, err, "ecGenerate didn't fail on ecPub error") @@ -72,7 +72,7 @@ func TestECGenerate(t *testing.T) { }, nil } ctx.GenerateRandomFunc = func(pkcs11.SessionHandle, int) ([]byte, error) { - return nil, errors.New("yup") + return nil, fmt.Errorf("yup") } _, _, err = ecGenerate(s, "", "P-256") test.AssertError(t, err, "ecGenerate didn't fail on ecVerify error") diff --git a/cmd/ceremony/main.go b/cmd/ceremony/main.go index 97c94eb1d30..a0415fee2ea 100644 --- a/cmd/ceremony/main.go +++ b/cmd/ceremony/main.go @@ -10,7 +10,6 @@ import ( "crypto/x509/pkix" "encoding/asn1" "encoding/pem" - "errors" "flag" "fmt" "log" @@ -108,22 +107,22 @@ var allowedCurves = map[string]bool{ func (kgc keyGenConfig) validate() error { if kgc.Type == "" { - return errors.New("key.type is required") + return fmt.Errorf("key.type is required") } if kgc.Type != "rsa" && kgc.Type != "ecdsa" { - return errors.New("key.type can only be 'rsa' or 'ecdsa'") + return fmt.Errorf("key.type can only be 'rsa' or 'ecdsa'") } if kgc.Type == "rsa" && (kgc.RSAModLength != 2048 && kgc.RSAModLength != 4096) { - return errors.New("key.rsa-mod-length can only be 2048 or 4096") + return fmt.Errorf("key.rsa-mod-length can only be 2048 or 4096") } if kgc.Type == "rsa" && kgc.ECDSACurve != "" { - return errors.New("if key.type = 'rsa' then key.ecdsa-curve is not used") + return fmt.Errorf("if key.type = 'rsa' then key.ecdsa-curve is not used") } if kgc.Type == "ecdsa" && !allowedCurves[kgc.ECDSACurve] { - return errors.New("key.ecdsa-curve can only be 'P-256', 'P-384', or 'P-521'") + return fmt.Errorf("key.ecdsa-curve can only be 'P-256', 'P-384', or 'P-521'") } if kgc.Type == "ecdsa" && kgc.RSAModLength != 0 { - return errors.New("if key.type = 'ecdsa' then key.rsa-mod-length is not used") + return fmt.Errorf("if key.type = 'ecdsa' then key.rsa-mod-length is not used") } return nil @@ -138,10 +137,10 @@ type PKCS11KeyGenConfig struct { func (pkgc PKCS11KeyGenConfig) validate() error { if pkgc.Module == "" { - return errors.New("pkcs11.module is required") + return fmt.Errorf("pkcs11.module is required") } if pkgc.StoreLabel == "" { - return errors.New("pkcs11.store-key-with-label is required") + return fmt.Errorf("pkcs11.store-key-with-label is required") } // key-slot is allowed to be 0 (which is a valid slot). // PIN is allowed to be "", which will commonly happen when @@ -215,10 +214,10 @@ type PKCS11SigningConfig struct { func (psc PKCS11SigningConfig) validate() error { if psc.Module == "" { - return errors.New("pkcs11.module is required") + return fmt.Errorf("pkcs11.module is required") } if psc.SigningLabel == "" { - return errors.New("pkcs11.signing-key-label is required") + return fmt.Errorf("pkcs11.signing-key-label is required") } // key-slot is allowed to be 0 (which is a valid slot). return nil @@ -246,10 +245,10 @@ func (ic intermediateConfig) validate() error { // Input fields if ic.Inputs.PublicKeyPath == "" { - return errors.New("inputs.public-key-path is required") + return fmt.Errorf("inputs.public-key-path is required") } if ic.Inputs.IssuerCertificatePath == "" { - return errors.New("inputs.issuer-certificate is required") + return fmt.Errorf("inputs.issuer-certificate is required") } // Output fields @@ -288,13 +287,13 @@ func (csc crossCertConfig) validate() error { return err } if csc.Inputs.PublicKeyPath == "" { - return errors.New("inputs.public-key-path is required") + return fmt.Errorf("inputs.public-key-path is required") } if csc.Inputs.IssuerCertificatePath == "" { - return errors.New("inputs.issuer-certificate is required") + return fmt.Errorf("inputs.issuer-certificate is required") } if csc.Inputs.CertificateToCrossSignPath == "" { - return errors.New("inputs.certificate-to-cross-sign-path is required") + return fmt.Errorf("inputs.certificate-to-cross-sign-path is required") } err = checkOutputFile(csc.Outputs.CertificatePath, "certificate-path") if err != nil { @@ -328,7 +327,7 @@ func (cc csrConfig) validate() error { // Input fields if cc.Inputs.PublicKeyPath == "" { - return errors.New("inputs.public-key-path is required") + return fmt.Errorf("inputs.public-key-path is required") } // Output fields @@ -407,7 +406,7 @@ func (cc crlConfig) validate() error { // Input fields if cc.Inputs.IssuerCertificatePath == "" { - return errors.New("inputs.issuer-certificate-path is required") + return fmt.Errorf("inputs.issuer-certificate-path is required") } // Output fields @@ -418,23 +417,23 @@ func (cc crlConfig) validate() error { // CRL profile fields if cc.CRLProfile.ThisUpdate == "" { - return errors.New("crl-profile.this-update is required") + return fmt.Errorf("crl-profile.this-update is required") } if cc.CRLProfile.NextUpdate == "" { - return errors.New("crl-profile.next-update is required") + return fmt.Errorf("crl-profile.next-update is required") } if cc.CRLProfile.Number == 0 { - return errors.New("crl-profile.number must be non-zero") + return fmt.Errorf("crl-profile.number must be non-zero") } for _, rc := range cc.CRLProfile.RevokedCertificates { if rc.CertificatePath == "" { - return errors.New("crl-profile.revoked-certificates.certificate-path is required") + return fmt.Errorf("crl-profile.revoked-certificates.certificate-path is required") } if rc.RevocationDate == "" { - return errors.New("crl-profile.revoked-certificates.revocation-date is required") + return fmt.Errorf("crl-profile.revoked-certificates.revocation-date is required") } if rc.RevocationReason == "" { - return errors.New("crl-profile.revoked-certificates.revocation-reason is required") + return fmt.Errorf("crl-profile.revoked-certificates.revocation-reason is required") } } diff --git a/cmd/ceremony/rsa.go b/cmd/ceremony/rsa.go index 7d0eb4b30c5..48adb379001 100644 --- a/cmd/ceremony/rsa.go +++ b/cmd/ceremony/rsa.go @@ -2,7 +2,7 @@ package main import ( "crypto/rsa" - "errors" + "fmt" "log" "math/big" @@ -62,10 +62,10 @@ func rsaPub(session *pkcs11helpers.Session, object pkcs11.ObjectHandle, modulusL return nil, err } if pubKey.E != rsaExp { - return nil, errors.New("returned CKA_PUBLIC_EXPONENT doesn't match expected exponent") + return nil, fmt.Errorf("returned CKA_PUBLIC_EXPONENT doesn't match expected exponent") } if pubKey.N.BitLen() != modulusLen { - return nil, errors.New("returned CKA_MODULUS isn't of the expected bit length") + return nil, fmt.Errorf("returned CKA_MODULUS isn't of the expected bit length") } log.Printf("\tPublic exponent: %d\n", pubKey.E) log.Printf("\tModulus: (%d bits) %X\n", pubKey.N.BitLen(), pubKey.N.Bytes()) diff --git a/cmd/ceremony/rsa_test.go b/cmd/ceremony/rsa_test.go index 40eb9d5df90..c8c658241f1 100644 --- a/cmd/ceremony/rsa_test.go +++ b/cmd/ceremony/rsa_test.go @@ -4,7 +4,7 @@ import ( "crypto" "crypto/rand" "crypto/rsa" - "errors" + "fmt" "math/big" "testing" @@ -49,7 +49,7 @@ func TestRSAGenerate(t *testing.T) { // Test rsaGenerate fails when GenerateKeyPair fails ctx.GenerateKeyPairFunc = func(pkcs11.SessionHandle, []*pkcs11.Mechanism, []*pkcs11.Attribute, []*pkcs11.Attribute) (pkcs11.ObjectHandle, pkcs11.ObjectHandle, error) { - return 0, 0, errors.New("bad") + return 0, 0, fmt.Errorf("bad") } _, _, err = rsaGenerate(s, "", 1024) test.AssertError(t, err, "rsaGenerate didn't fail on GenerateKeyPair error") @@ -59,7 +59,7 @@ func TestRSAGenerate(t *testing.T) { return 0, 0, nil } ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { - return nil, errors.New("bad") + return nil, fmt.Errorf("bad") } _, _, err = rsaGenerate(s, "", 1024) test.AssertError(t, err, "rsaGenerate didn't fail on rsaPub error") @@ -72,7 +72,7 @@ func TestRSAGenerate(t *testing.T) { }, nil } ctx.GenerateRandomFunc = func(pkcs11.SessionHandle, int) ([]byte, error) { - return nil, errors.New("yup") + return nil, fmt.Errorf("yup") } _, _, err = rsaGenerate(s, "", 1024) test.AssertError(t, err, "rsaGenerate didn't fail on rsaVerify error") diff --git a/cmd/cert-checker/main_test.go b/cmd/cert-checker/main_test.go index 6d3504f7288..6e8a6631e25 100644 --- a/cmd/cert-checker/main_test.go +++ b/cmd/cert-checker/main_test.go @@ -12,7 +12,7 @@ import ( "database/sql" "encoding/asn1" "encoding/pem" - "errors" + "fmt" "log" "math/big" mrand "math/rand/v2" @@ -407,7 +407,7 @@ func (db mismatchedCountDB) Select(_ context.Context, output any, _ string, _ .. } func (db mismatchedCountDB) SelectOne(_ context.Context, _ any, _ string, _ ...any) error { - return errors.New("unimplemented") + return fmt.Errorf("unimplemented") } /* diff --git a/cmd/config.go b/cmd/config.go index d9b62fd32d3..952f4fdbb49 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -102,7 +102,7 @@ type PAConfig struct { // actually contains valid challenge names func (pc PAConfig) CheckChallenges() error { if len(pc.Challenges) == 0 { - return errors.New("empty challenges map in the Policy Authority config is not allowed") + return fmt.Errorf("empty challenges map in the Policy Authority config is not allowed") } for c := range pc.Challenges { if !c.IsValid() { @@ -355,7 +355,7 @@ func (c *GRPCClientConfig) MakeTargetAndHostOverride() (string, string, error) { var hostOverride string if c.ServerAddress != "" { if c.SRVLookup != nil { - return "", "", errors.New( + return "", "", fmt.Errorf( "both 'serverAddress' and 'SRVLookup' in gRPC client config. Only one should be provided", ) } @@ -373,7 +373,7 @@ func (c *GRPCClientConfig) MakeTargetAndHostOverride() (string, string, error) { } else if c.SRVLookup != nil { if c.DNSAuthority == "" { - return "", "", errors.New("field 'dnsAuthority' is required in gRPC client config with SRVLookup") + return "", "", fmt.Errorf("field 'dnsAuthority' is required in gRPC client config with SRVLookup") } scheme, err := c.makeSRVScheme() if err != nil { @@ -390,7 +390,7 @@ func (c *GRPCClientConfig) MakeTargetAndHostOverride() (string, string, error) { } else if c.SRVLookups != nil { if c.DNSAuthority == "" { - return "", "", errors.New("field 'dnsAuthority' is required in gRPC client config with SRVLookups") + return "", "", fmt.Errorf("field 'dnsAuthority' is required in gRPC client config with SRVLookups") } scheme, err := c.makeSRVScheme() if err != nil { @@ -407,7 +407,7 @@ func (c *GRPCClientConfig) MakeTargetAndHostOverride() (string, string, error) { return fmt.Sprintf("%s://%s/%s", scheme, c.DNSAuthority, strings.Join(targetHosts, ",")), hostOverride, nil } else { - return "", "", errors.New( + return "", "", fmt.Errorf( "at least one of 'serverAddress', 'SRVLookup', or 'SRVLookups' required in gRPC client config", ) } diff --git a/cmd/shell.go b/cmd/shell.go index 4e552c5edbe..8ec01a4286c 100644 --- a/cmd/shell.go +++ b/cmd/shell.go @@ -4,7 +4,6 @@ package cmd import ( "context" "encoding/json" - "errors" "expvar" "fmt" "io" @@ -444,7 +443,7 @@ func ReadConfigFile(filename string, out any) error { // use in SRE CI tooling. func ValidateJSONConfig(cv *ConfigValidator, in io.Reader) error { if cv == nil { - return errors.New("config validator cannot be nil") + return fmt.Errorf("config validator cannot be nil") } // Initialize the validator and load any custom tags. @@ -475,7 +474,7 @@ func ValidateJSONConfig(cv *ConfigValidator, in io.Reader) error { for _, e := range errs { allErrs = append(allErrs, e.Error()) } - return errors.New(strings.Join(allErrs, ", ")) + return fmt.Errorf("%s", strings.Join(allErrs, ", ")) } } return nil @@ -489,7 +488,7 @@ func ValidateJSONConfig(cv *ConfigValidator, in io.Reader) error { // use in SRE CI tooling. func ValidateYAMLConfig(cv *ConfigValidator, in io.Reader) error { if cv == nil { - return errors.New("config validator cannot be nil") + return fmt.Errorf("config validator cannot be nil") } // Initialize the validator and load any custom tags. @@ -524,7 +523,7 @@ func ValidateYAMLConfig(cv *ConfigValidator, in io.Reader) error { for _, e := range errs { allErrs = append(allErrs, e.Error()) } - return errors.New(strings.Join(allErrs, ", ")) + return fmt.Errorf("%s", strings.Join(allErrs, ", ")) } } return nil diff --git a/config/duration.go b/config/duration.go index 3e30c0283e4..351f279d392 100644 --- a/config/duration.go +++ b/config/duration.go @@ -3,6 +3,7 @@ package config import ( "encoding/json" "errors" + "fmt" "reflect" "time" ) @@ -26,7 +27,7 @@ func DurationCustomTypeFunc(field reflect.Value) any { // ErrDurationMustBeString is returned when a non-string value is // presented to be deserialized as a ConfigDuration -var ErrDurationMustBeString = errors.New("cannot JSON unmarshal something other than a string into a ConfigDuration") +var ErrDurationMustBeString = fmt.Errorf("cannot JSON unmarshal something other than a string into a ConfigDuration") // UnmarshalJSON parses a string into a ConfigDuration using // time.ParseDuration. If the input does not unmarshal as a diff --git a/core/util.go b/core/util.go index a85ff2817eb..85c2b70ad0a 100644 --- a/core/util.go +++ b/core/util.go @@ -104,7 +104,7 @@ func KeyDigest(key crypto.PublicKey) (Sha256Digest, error) { switch t := key.(type) { case *jose.JSONWebKey: if t == nil { - return Sha256Digest{}, errors.New("cannot compute digest of nil key") + return Sha256Digest{}, fmt.Errorf("cannot compute digest of nil key") } return KeyDigest(t.Key) case jose.JSONWebKey: diff --git a/core/util_test.go b/core/util_test.go index 8ccd459661d..09fb00a5870 100644 --- a/core/util_test.go +++ b/core/util_test.go @@ -3,7 +3,6 @@ package core import ( "context" "encoding/json" - "errors" "fmt" "math" "math/big" @@ -422,7 +421,7 @@ func TestIsCanceled(t *testing.T) { if !IsCanceled(status.Errorf(codes.Canceled, "hi")) { t.Errorf("Expected gRPC cancellation to be canceled, but wasn't.") } - if IsCanceled(errors.New("hi")) { + if IsCanceled(fmt.Errorf("hi")) { t.Errorf("Expected random error to not be canceled, but was.") } } diff --git a/crl/idp/idp.go b/crl/idp/idp.go index 2ed835dfd79..2f56ee5b923 100644 --- a/crl/idp/idp.go +++ b/crl/idp/idp.go @@ -3,7 +3,6 @@ package idp import ( "crypto/x509/pkix" "encoding/asn1" - "errors" "fmt" ) @@ -98,5 +97,5 @@ func GetIDPURIs(exts []pkix.Extension) ([]string, error) { return uris, nil } } - return nil, errors.New("no IssuingDistributionPoint extension found") + return nil, fmt.Errorf("no IssuingDistributionPoint extension found") } diff --git a/crl/storer/storer.go b/crl/storer/storer.go index e0a49a19cc1..b39dee65db0 100644 --- a/crl/storer/storer.go +++ b/crl/storer/storer.go @@ -119,10 +119,10 @@ func (cs *crlStorer) UploadCRL(stream grpc.ClientStreamingServer[cspb.UploadCRLR switch payload := in.Payload.(type) { case *cspb.UploadCRLRequest_Metadata: if crlNumber != nil || issuer != nil { - return errors.New("got more than one metadata message") + return fmt.Errorf("got more than one metadata message") } if payload.Metadata.IssuerNameID == 0 || payload.Metadata.Number == 0 { - return errors.New("got incomplete metadata message") + return fmt.Errorf("got incomplete metadata message") } cacheControl = payload.Metadata.CacheControl @@ -144,7 +144,7 @@ func (cs *crlStorer) UploadCRL(stream grpc.ClientStreamingServer[cspb.UploadCRLR // Do some basic sanity checks on the received metadata and CRL. if issuer == nil || crlNumber == nil { - return errors.New("got no metadata message") + return fmt.Errorf("got no metadata message") } crlId := crl.Id(issuer.NameID(), int(shardIdx), crlNumber) @@ -157,7 +157,7 @@ func (cs *crlStorer) UploadCRL(stream grpc.ClientStreamingServer[cspb.UploadCRLR } if crl.Number.Cmp(crlNumber) != 0 { - return errors.New("got mismatched CRL Number") + return fmt.Errorf("got mismatched CRL Number") } err = crl.CheckSignatureFrom(issuer.Certificate) diff --git a/crl/storer/storer_test.go b/crl/storer/storer_test.go index 22654b9ebcc..3eaaf08027f 100644 --- a/crl/storer/storer_test.go +++ b/crl/storer/storer_test.go @@ -8,7 +8,7 @@ import ( "crypto/rand" "crypto/x509" "crypto/x509/pkix" - "errors" + "fmt" "io" "math/big" "net/http" @@ -288,7 +288,7 @@ func (p *fakeSimpleS3) PutObject(ctx context.Context, params *s3.PutObjectInput, return nil, err } if !bytes.Equal(p.expectBytes, recvBytes) { - return nil, errors.New("received bytes did not match expectation") + return nil, fmt.Errorf("received bytes did not match expectation") } return &s3.PutObjectOutput{}, nil } @@ -477,11 +477,11 @@ func TestUploadCRLBackwardsNumber(t *testing.T) { type brokenSimpleS3 struct{} func (p *brokenSimpleS3) PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error) { - return nil, errors.New("sorry") + return nil, fmt.Errorf("sorry") } func (p *brokenSimpleS3) GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error) { - return nil, errors.New("oops") + return nil, fmt.Errorf("oops") } // Test that we get an error when S3 falls over. diff --git a/crl/updater/batch.go b/crl/updater/batch.go index 9b303faedf9..91d127f60b6 100644 --- a/crl/updater/batch.go +++ b/crl/updater/batch.go @@ -2,7 +2,7 @@ package updater import ( "context" - "errors" + "fmt" "sync" "github.com/letsencrypt/boulder/crl" @@ -67,7 +67,7 @@ func (cu *crlUpdater) RunOnce(ctx context.Context) error { wg.Wait() if anyErr { - return errors.New("one or more errors encountered, see logs") + return fmt.Errorf("one or more errors encountered, see logs") } return ctx.Err() } diff --git a/crl/updater/batch_test.go b/crl/updater/batch_test.go index b0cc0445ec8..28629c784b1 100644 --- a/crl/updater/batch_test.go +++ b/crl/updater/batch_test.go @@ -2,7 +2,7 @@ package updater import ( "context" - "errors" + "fmt" "testing" "time" @@ -29,7 +29,7 @@ func TestRunOnce(t *testing.T) { 6*time.Hour, time.Minute, 1, 1, "stale-if-error=60", 5*time.Minute, - &fakeSAC{revokedCerts: revokedCertsStream{err: errors.New("db no worky")}, maxNotAfter: clk.Now().Add(90 * 24 * time.Hour)}, + &fakeSAC{revokedCerts: revokedCertsStream{err: fmt.Errorf("db no worky")}, maxNotAfter: clk.Now().Add(90 * 24 * time.Hour)}, &fakeCA{gcc: generateCRLStream{}}, &fakeStorer{uploaderStream: &noopUploader{}}, metrics.NoopRegisterer, mockLog, clk, diff --git a/crl/updater/updater_test.go b/crl/updater/updater_test.go index 86c73c2ca94..75f5a6ae430 100644 --- a/crl/updater/updater_test.go +++ b/crl/updater/updater_test.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "encoding/json" - "errors" + "fmt" "io" "testing" "time" @@ -202,7 +202,7 @@ func TestUpdateShard(t *testing.T) { r3, err := issuance.LoadCertificate("../../test/hierarchy/int-r3.cert.pem") test.AssertNotError(t, err, "loading test issuer") - sentinelErr := errors.New("oops") + sentinelErr := fmt.Errorf("oops") ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() @@ -373,7 +373,7 @@ func TestUpdateShardWithRetry(t *testing.T) { r3, err := issuance.LoadCertificate("../../test/hierarchy/int-r3.cert.pem") test.AssertNotError(t, err, "loading test issuer") - sentinelErr := errors.New("oops") + sentinelErr := fmt.Errorf("oops") ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() diff --git a/csr/csr_test.go b/csr/csr_test.go index d3d3d1bc44f..fbc6df82d35 100644 --- a/csr/csr_test.go +++ b/csr/csr_test.go @@ -7,7 +7,7 @@ import ( "crypto/x509" "crypto/x509/pkix" "encoding/asn1" - "errors" + "fmt" "net" "net/netip" "net/url" @@ -31,7 +31,7 @@ func (pa *mockPA) ChallengeTypesFor(ident identifier.ACMEIdentifier) ([]core.Acm func (pa *mockPA) WillingToIssue(idents identifier.ACMEIdentifiers) error { for _, ident := range idents { if ident.Value == "bad-name.com" || ident.Value == "other-bad-name.com" { - return errors.New("policy forbids issuing for identifier") + return fmt.Errorf("policy forbids issuing for identifier") } } return nil @@ -130,7 +130,7 @@ func TestVerifyCSR(t *testing.T) { signedReqWithBadNames, 100, &mockPA{}, - errors.New("policy forbids issuing for identifier"), + fmt.Errorf("policy forbids issuing for identifier"), }, { signedReqWithEmailAddress, diff --git a/ctpolicy/ctpolicy_test.go b/ctpolicy/ctpolicy_test.go index 30e9b2840a7..0d63edc0ab7 100644 --- a/ctpolicy/ctpolicy_test.go +++ b/ctpolicy/ctpolicy_test.go @@ -3,7 +3,7 @@ package ctpolicy import ( "bytes" "context" - "errors" + "fmt" "strings" "testing" "time" @@ -30,14 +30,14 @@ func (mp *mockPub) SubmitToSingleCTWithResult(_ context.Context, _ *pubpb.Reques type mockFailPub struct{} func (mp *mockFailPub) SubmitToSingleCTWithResult(_ context.Context, _ *pubpb.Request, _ ...grpc.CallOption) (*pubpb.Result, error) { - return nil, errors.New("BAD") + return nil, fmt.Errorf("BAD") } type mockSlowPub struct{} func (mp *mockSlowPub) SubmitToSingleCTWithResult(ctx context.Context, _ *pubpb.Request, _ ...grpc.CallOption) (*pubpb.Result, error) { <-ctx.Done() - return nil, errors.New("timed out") + return nil, fmt.Errorf("timed out") } func TestGetSCTs(t *testing.T) { @@ -117,7 +117,7 @@ type mockFailOnePub struct { func (mp *mockFailOnePub) SubmitToSingleCTWithResult(_ context.Context, req *pubpb.Request, _ ...grpc.CallOption) (*pubpb.Result, error) { if req.LogURL == mp.badURL { - return nil, errors.New("BAD") + return nil, fmt.Errorf("BAD") } return &pubpb.Result{Sct: []byte{0}}, nil } @@ -203,7 +203,7 @@ func TestCompliantSet(t *testing.T) { name: "only one good result", results: []result{ {log: loglist.Log{Operator: "A", Tiled: false}, sct: []byte("sct1")}, - {log: loglist.Log{Operator: "B", Tiled: false}, err: errors.New("oops")}, + {log: loglist.Log{Operator: "B", Tiled: false}, err: fmt.Errorf("oops")}, }, want: nil, }, @@ -226,13 +226,13 @@ func TestCompliantSet(t *testing.T) { { name: "happy path", results: []result{ - {log: loglist.Log{Operator: "A", Tiled: false}, err: errors.New("oops")}, + {log: loglist.Log{Operator: "A", Tiled: false}, err: fmt.Errorf("oops")}, {log: loglist.Log{Operator: "A", Tiled: true}, sct: []byte("sct2")}, {log: loglist.Log{Operator: "A", Tiled: false}, sct: []byte("sct3")}, - {log: loglist.Log{Operator: "B", Tiled: false}, err: errors.New("oops")}, + {log: loglist.Log{Operator: "B", Tiled: false}, err: fmt.Errorf("oops")}, {log: loglist.Log{Operator: "B", Tiled: true}, sct: []byte("sct4")}, {log: loglist.Log{Operator: "B", Tiled: false}, sct: []byte("sct6")}, - {log: loglist.Log{Operator: "C", Tiled: false}, err: errors.New("oops")}, + {log: loglist.Log{Operator: "C", Tiled: false}, err: fmt.Errorf("oops")}, {log: loglist.Log{Operator: "C", Tiled: true}, sct: []byte("sct8")}, {log: loglist.Log{Operator: "C", Tiled: false}, sct: []byte("sct9")}, }, diff --git a/ctpolicy/loglist/loglist.go b/ctpolicy/loglist/loglist.go index be6f97bb49a..be388a79a0f 100644 --- a/ctpolicy/loglist/loglist.go +++ b/ctpolicy/loglist/loglist.go @@ -3,7 +3,6 @@ package loglist import ( _ "embed" "encoding/base64" - "errors" "fmt" "math/rand/v2" "os" @@ -206,7 +205,7 @@ func (ll List) forPurpose(p purpose, submitToTestLogs bool) (List, error) { } if len(operators) < 2 && p != Informational { - return nil, errors.New("log list does not have enough groups to satisfy Chrome policy") + return nil, fmt.Errorf("log list does not have enough groups to satisfy Chrome policy") } return res, nil diff --git a/db/interfaces.go b/db/interfaces.go index 60c6f3583cf..24c9930f1d3 100644 --- a/db/interfaces.go +++ b/db/interfaces.go @@ -3,7 +3,7 @@ package db import ( "context" "database/sql" - "errors" + "fmt" "reflect" "github.com/letsencrypt/borp" @@ -106,46 +106,46 @@ type Rows[T any] interface { type MockSqlExecutor struct{} func (mse MockSqlExecutor) Get(ctx context.Context, i any, keys ...any) (any, error) { - return nil, errors.New("unimplemented") + return nil, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) Insert(ctx context.Context, list ...any) error { - return errors.New("unimplemented") + return fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) Update(ctx context.Context, list ...any) (int64, error) { - return 0, errors.New("unimplemented") + return 0, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) Delete(ctx context.Context, list ...any) (int64, error) { - return 0, errors.New("unimplemented") + return 0, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { - return nil, errors.New("unimplemented") + return nil, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) Select(ctx context.Context, i any, query string, args ...any) ([]any, error) { - return nil, errors.New("unimplemented") + return nil, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) SelectInt(ctx context.Context, query string, args ...any) (int64, error) { - return 0, errors.New("unimplemented") + return 0, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) SelectNullInt(ctx context.Context, query string, args ...any) (sql.NullInt64, error) { - return sql.NullInt64{}, errors.New("unimplemented") + return sql.NullInt64{}, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) SelectFloat(ctx context.Context, query string, args ...any) (float64, error) { - return 0, errors.New("unimplemented") + return 0, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) SelectNullFloat(ctx context.Context, query string, args ...any) (sql.NullFloat64, error) { - return sql.NullFloat64{}, errors.New("unimplemented") + return sql.NullFloat64{}, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) SelectStr(ctx context.Context, query string, args ...any) (string, error) { - return "", errors.New("unimplemented") + return "", fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) SelectNullStr(ctx context.Context, query string, args ...any) (sql.NullString, error) { - return sql.NullString{}, errors.New("unimplemented") + return sql.NullString{}, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) SelectOne(ctx context.Context, holder any, query string, args ...any) error { - return errors.New("unimplemented") + return fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { - return nil, errors.New("unimplemented") + return nil, fmt.Errorf("unimplemented") } func (mse MockSqlExecutor) QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row { return nil diff --git a/db/map_test.go b/db/map_test.go index 8b6dc675613..069ff828519 100644 --- a/db/map_test.go +++ b/db/map_test.go @@ -3,7 +3,6 @@ package db import ( "context" "database/sql" - "errors" "fmt" "testing" @@ -17,7 +16,7 @@ import ( ) func TestErrDatabaseOpError(t *testing.T) { - testErr := errors.New("computers are cancelled") + testErr := fmt.Errorf("computers are cancelled") testCases := []struct { name string err error @@ -69,7 +68,7 @@ func TestIsNoRows(t *testing.T) { err: ErrDatabaseOp{ Op: "test", Table: "testTable", - Err: fmt.Errorf("some wrapper around %w", errors.New("lots of rows. too many rows.")), + Err: fmt.Errorf("some wrapper around %w", fmt.Errorf("lots of rows. too many rows.")), }, expectedNoRows: false, }, diff --git a/email/exporter.go b/email/exporter.go index 9cb020e8a5b..ef482a4cb05 100644 --- a/email/exporter.go +++ b/email/exporter.go @@ -3,6 +3,7 @@ package email import ( "context" "errors" + "fmt" "sync" "github.com/prometheus/client_golang/prometheus" @@ -21,7 +22,7 @@ import ( // is at most 320 bytes. Storing 100,000 emails requires ~34.4 MB of memory. const contactsQueueCap = 100000 -var ErrQueueFull = errors.New("email-exporter queue is full") +var ErrQueueFull = fmt.Errorf("email-exporter queue is full") // ExporterImpl implements the gRPC server and processes email exports. type ExporterImpl struct { diff --git a/goodkey/good_key.go b/goodkey/good_key.go index d8efd703ddc..958048bc06a 100644 --- a/goodkey/good_key.go +++ b/goodkey/good_key.go @@ -6,7 +6,6 @@ import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rsa" - "errors" "fmt" "math/big" "sync" @@ -87,7 +86,7 @@ func LetsEncryptCPS() AllowedKeys { // ways in which an ACME request can have an erroneous key (BadPublicKeyError, // BadCSRError) because this library is used to check both JWS signing keys and // keys in CSRs. -var ErrBadKey = errors.New("") +var ErrBadKey = fmt.Errorf("") func badKey(msg string, args ...any) error { return fmt.Errorf("%w%s", ErrBadKey, fmt.Errorf(msg, args...)) diff --git a/grpc/client.go b/grpc/client.go index 87ff82f7995..32d97437887 100644 --- a/grpc/client.go +++ b/grpc/client.go @@ -32,7 +32,7 @@ import ( // It dials the remote service and returns a grpc.ClientConn if successful. func ClientSetup(c *cmd.GRPCClientConfig, tlsConfig *tls.Config, statsRegistry prometheus.Registerer, clk clock.Clock) (*grpc.ClientConn, error) { if c == nil { - return nil, errors.New("nil gRPC client config provided: JSON config is probably missing a fooService section") + return nil, fmt.Errorf("nil gRPC client config provided: JSON config is probably missing a fooService section") } if tlsConfig == nil { return nil, errNilTLS diff --git a/grpc/creds/creds.go b/grpc/creds/creds.go index 31da6e234ba..919cad1a6ee 100644 --- a/grpc/creds/creds.go +++ b/grpc/creds/creds.go @@ -4,7 +4,6 @@ import ( "context" "crypto/tls" "crypto/x509" - "errors" "fmt" "net" @@ -12,17 +11,17 @@ import ( ) var ( - ErrClientHandshakeNop = errors.New( + ErrClientHandshakeNop = fmt.Errorf( "boulder/grpc/creds: Client-side handshakes are not implemented with " + "serverTransportCredentials") - ErrServerHandshakeNop = errors.New( + ErrServerHandshakeNop = fmt.Errorf( "boulder/grpc/creds: Server-side handshakes are not implemented with " + "clientTransportCredentials") - ErrOverrideServerNameNop = errors.New( + ErrOverrideServerNameNop = fmt.Errorf( "boulder/grpc/creds: OverrideServerName() is not implemented") - ErrNilServerConfig = errors.New( + ErrNilServerConfig = fmt.Errorf( "boulder/grpc/creds: `serverConfig` must not be nil") - ErrEmptyPeerCerts = errors.New( + ErrEmptyPeerCerts = fmt.Errorf( "boulder/grpc/creds: validateClient given state with empty PeerCertificates") ) diff --git a/grpc/interceptors_test.go b/grpc/interceptors_test.go index fa42c252d15..55cc344cf27 100644 --- a/grpc/interceptors_test.go +++ b/grpc/interceptors_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/tls" "crypto/x509" - "errors" "fmt" "log" "net" @@ -35,7 +34,7 @@ var fc = clock.NewFake() func testHandler(_ context.Context, i any) (any, error) { if i != nil { - return nil, errors.New("") + return nil, fmt.Errorf("") } fc.Sleep(time.Second) return nil, nil @@ -44,7 +43,7 @@ func testHandler(_ context.Context, i any) (any, error) { func testInvoker(_ context.Context, method string, _, _ any, _ *grpc.ClientConn, opts ...grpc.CallOption) error { switch method { case "-service-brokeTest": - return errors.New("") + return fmt.Errorf("") case "-service-requesterCanceledTest": return status.Error(1, context.Canceled.Error()) } @@ -171,7 +170,7 @@ func (s *testTimeoutServer) Chill(ctx context.Context, in *test_proto.Time) (*te spent := time.Since(start) / time.Nanosecond return &test_proto.Time{Duration: durationpb.New(spent)}, nil case <-ctx.Done(): - return nil, errors.New("unique error indicating that the server's shortened context timed itself out") + return nil, fmt.Errorf("unique error indicating that the server's shortened context timed itself out") } } diff --git a/grpc/internal/resolver/dns/dns_resolver_test.go b/grpc/internal/resolver/dns/dns_resolver_test.go index 51cb2ddffac..1379315ab61 100644 --- a/grpc/internal/resolver/dns/dns_resolver_test.go +++ b/grpc/internal/resolver/dns/dns_resolver_test.go @@ -20,7 +20,6 @@ package dns import ( "context" - "errors" "fmt" "net" "os" @@ -582,7 +581,7 @@ func TestCustomAuthority(t *testing.T) { errChan <- nil } return func(ctx context.Context, network, address string) (net.Conn, error) { - return nil, errors.New("no need to dial") + return nil, fmt.Errorf("no need to dial") } } diff --git a/grpc/noncebalancer/noncebalancer.go b/grpc/noncebalancer/noncebalancer.go index 4867e400dd5..f61e5393c6f 100644 --- a/grpc/noncebalancer/noncebalancer.go +++ b/grpc/noncebalancer/noncebalancer.go @@ -1,7 +1,7 @@ package noncebalancer import ( - "errors" + "fmt" "sync" "github.com/letsencrypt/boulder/nonce" @@ -35,10 +35,10 @@ const ( // detect that the status it receives is this exact status object, so don't // wrap this with fmt.Errorf when returning it. var ErrNoBackendsMatchPrefix = status.New(codes.Unavailable, "no backends match the nonce prefix") -var errMissingPrefixCtxKey = errors.New("nonce.PrefixCtxKey value required in RPC context") -var errMissingHMACKeyCtxKey = errors.New("nonce.HMACKeyCtxKey value required in RPC context") -var errInvalidPrefixCtxKeyType = errors.New("nonce.PrefixCtxKey value in RPC context must be a string") -var errInvalidHMACKeyCtxKeyType = errors.New("nonce.HMACKeyCtxKey value in RPC context must be a byte slice") +var errMissingPrefixCtxKey = fmt.Errorf("nonce.PrefixCtxKey value required in RPC context") +var errMissingHMACKeyCtxKey = fmt.Errorf("nonce.HMACKeyCtxKey value required in RPC context") +var errInvalidPrefixCtxKeyType = fmt.Errorf("nonce.PrefixCtxKey value in RPC context must be a string") +var errInvalidHMACKeyCtxKeyType = fmt.Errorf("nonce.HMACKeyCtxKey value in RPC context must be a byte slice") // pickerBuilder implements the base.PickerBuilder interface. It's used to // create new Picker instances. It should only be used by nonce-service clients. diff --git a/grpc/server.go b/grpc/server.go index 3c8b8b653e6..9d4ec8a11df 100644 --- a/grpc/server.go +++ b/grpc/server.go @@ -29,7 +29,7 @@ import ( // CodedError is a alias required to appease go vet var CodedError = status.Errorf -var errNilTLS = errors.New("boulder/grpc: received nil tls.Config") +var errNilTLS = fmt.Errorf("boulder/grpc: received nil tls.Config") // checker is an interface for checking the health of a grpc service // implementation. @@ -192,7 +192,7 @@ func (sb *serverBuilder) Build(tlsConfig *tls.Config, statsRegistry prometheus.R } if sb.cfg.Address == "" { - return nil, errors.New("GRPC listen address not configured") + return nil, fmt.Errorf("GRPC listen address not configured") } sb.logger.Infof("grpc listening on %s", sb.cfg.Address) diff --git a/grpc/server_test.go b/grpc/server_test.go index 16c2e86a4ec..b1ee631e394 100644 --- a/grpc/server_test.go +++ b/grpc/server_test.go @@ -2,7 +2,7 @@ package grpc import ( "context" - "errors" + "fmt" "testing" "time" @@ -27,7 +27,7 @@ func TestServerBuilderInitLongRunningCheck(t *testing.T) { failEveryThirdCheck := func(context.Context) error { count++ if count%3 == 0 { - return errors.New("oops") + return fmt.Errorf("oops") } return nil } @@ -53,7 +53,7 @@ func TestServerBuilderInitLongRunningCheck(t *testing.T) { failEveryOtherCheck := func(context.Context) error { count++ if count%2 == 0 { - return errors.New("oops") + return fmt.Errorf("oops") } return nil } diff --git a/issuance/cert.go b/issuance/cert.go index 8980c039814..b89e08e1bf4 100644 --- a/issuance/cert.go +++ b/issuance/cert.go @@ -10,7 +10,6 @@ import ( "crypto/x509/pkix" "encoding/asn1" "encoding/json" - "errors" "fmt" "math/big" "net" @@ -121,26 +120,26 @@ func (i *Issuer) requestValid(clk clock.Clock, prof *Profile, req *IssuanceReque switch req.PublicKey.PublicKey.(type) { case *rsa.PublicKey, *ecdsa.PublicKey: default: - return errors.New("unsupported public key type") + return fmt.Errorf("unsupported public key type") } if len(req.precertDER) == 0 && !i.active { - return errors.New("inactive issuer cannot issue precert") + return fmt.Errorf("inactive issuer cannot issue precert") } if len(req.SubjectKeyId) != 0 && len(req.SubjectKeyId) != 20 { - return errors.New("unexpected subject key ID length") + return fmt.Errorf("unexpected subject key ID length") } if req.IncludeCTPoison && req.sctList != nil { - return errors.New("cannot include both ct poison and sct list extensions") + return fmt.Errorf("cannot include both ct poison and sct list extensions") } // The validity period is calculated inclusive of the whole second represented // by the notAfter timestamp. validity := req.NotAfter.Add(time.Second).Sub(req.NotBefore) if validity <= 0 { - return errors.New("NotAfter must be after NotBefore") + return fmt.Errorf("NotAfter must be after NotBefore") } if validity > prof.maxValidity { return fmt.Errorf("validity period is more than the maximum allowed period (%s>%s)", validity, prof.maxValidity) @@ -150,14 +149,14 @@ func (i *Issuer) requestValid(clk clock.Clock, prof *Profile, req *IssuanceReque return fmt.Errorf("NotBefore is backdated more than the maximum allowed period (%s>%s)", backdatedBy, prof.maxBackdate) } if backdatedBy < 0 { - return errors.New("NotBefore is in the future") + return fmt.Errorf("NotBefore is in the future") } // We use 19 here because a 20-byte serial could produce >20 octets when // encoded in ASN.1. That happens when the first byte is >0x80. See // https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/#integer-encoding if len(req.Serial) > 19 || len(req.Serial) < 9 { - return errors.New("serial must be between 9 and 19 bytes") + return fmt.Errorf("serial must be between 9 and 19 bytes") } return nil @@ -336,7 +335,7 @@ func (i *Issuer) Prepare(prof *Profile, req *IssuanceRequest) ([]byte, *issuance template.ExtraExtensions = append(template.ExtraExtensions, ctPoisonExt) } else if len(req.sctList) > 0 { if len(req.precertDER) == 0 { - return nil, nil, errors.New("inconsistent request contains sctList but no precertDER") + return nil, nil, fmt.Errorf("inconsistent request contains sctList but no precertDER") } sctListExt, err := generateSCTListExt(req.sctList) if err != nil { @@ -344,7 +343,7 @@ func (i *Issuer) Prepare(prof *Profile, req *IssuanceRequest) ([]byte, *issuance } template.ExtraExtensions = append(template.ExtraExtensions, sctListExt) } else { - return nil, nil, errors.New("invalid request contains neither sctList nor precertDER") + return nil, nil, fmt.Errorf("invalid request contains neither sctList nor precertDER") } // Pick a CRL shard based on the serial number modulo the number of shards. @@ -377,18 +376,18 @@ func (i *Issuer) Prepare(prof *Profile, req *IssuanceRequest) ([]byte, *issuance // the first will receive an error. func (i *Issuer) Issue(token *issuanceToken) ([]byte, error) { if token == nil { - return nil, errors.New("nil issuanceToken") + return nil, fmt.Errorf("nil issuanceToken") } token.mu.Lock() defer token.mu.Unlock() if token.template == nil { - return nil, errors.New("issuance token already redeemed") + return nil, fmt.Errorf("issuance token already redeemed") } template := token.template token.template = nil if token.issuer != i { - return nil, errors.New("tried to redeem issuance token with the wrong issuer") + return nil, fmt.Errorf("tried to redeem issuance token with the wrong issuer") } return x509.CreateCertificate(rand.Reader, template, i.Cert.Certificate, token.pubKey.PublicKey, i.Signer) @@ -411,7 +410,7 @@ func containsCTPoison(extensions []pkix.Extension) bool { // contain the CT poison extension. func RequestFromPrecert(precert *x509.Certificate, scts []ct.SignedCertificateTimestamp) (*IssuanceRequest, error) { if !containsCTPoison(precert.Extensions) { - return nil, errors.New("provided certificate doesn't contain the CT poison extension") + return nil, fmt.Errorf("provided certificate doesn't contain the CT poison extension") } return &IssuanceRequest{ PublicKey: MarshalablePublicKey{precert.PublicKey}, diff --git a/issuance/crl_test.go b/issuance/crl_test.go index df30bd1af7c..6f02ea2e00a 100644 --- a/issuance/crl_test.go +++ b/issuance/crl_test.go @@ -2,7 +2,7 @@ package issuance import ( "crypto/x509" - "errors" + "fmt" "math/big" "testing" "time" @@ -201,13 +201,13 @@ func revokedCertificatesFieldExists(der []byte) (bool, error) { // Extract the CertificateList if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) { - return false, errors.New("malformed crl") + return false, fmt.Errorf("malformed crl") } var tbs cryptobyte.String // Extract the TBSCertList from the CertificateList if !input.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) { - return false, errors.New("malformed tbs crl") + return false, fmt.Errorf("malformed tbs crl") } // Skip optional version diff --git a/issuance/issuer.go b/issuance/issuer.go index 8479470ba69..68817457f45 100644 --- a/issuance/issuer.go +++ b/issuance/issuer.go @@ -7,7 +7,6 @@ import ( "crypto/rsa" "crypto/x509" "encoding/json" - "errors" "fmt" "math/big" "os" @@ -76,7 +75,7 @@ func (ic *Certificate) NameID() NameID { // attributes expected of an issuer certificate. func NewCertificate(ic *x509.Certificate) (*Certificate, error) { if !ic.IsCA { - return nil, errors.New("certificate is not a CA certificate") + return nil, fmt.Errorf("certificate is not a CA certificate") } res := Certificate{ic, 0} @@ -99,7 +98,7 @@ func LoadCertificate(path string) (*Certificate, error) { // not be included in the resulting chain. func LoadChain(certFiles []string) ([]*Certificate, error) { if len(certFiles) < 2 { - return nil, errors.New( + return nil, fmt.Errorf( "each chain must have at least two certificates: an intermediate and a root") } @@ -230,14 +229,14 @@ func newIssuer(config IssuerConfig, cert *Certificate, signer crypto.Signer, clk return nil, fmt.Errorf("unsupported ECDSA curve: %q", k.Curve.Params().Name) } default: - return nil, errors.New("unsupported issuer key type") + return nil, fmt.Errorf("unsupported issuer key type") } if config.IssuerURL == "" { - return nil, errors.New("issuer URL is required") + return nil, fmt.Errorf("issuer URL is required") } if config.CRLURLBase == "" { - return nil, errors.New("crlURLBase is required") + return nil, fmt.Errorf("crlURLBase is required") } if !strings.HasPrefix(config.CRLURLBase, "http://") { return nil, fmt.Errorf("crlURLBase must use HTTP scheme, got %q", config.CRLURLBase) @@ -246,24 +245,24 @@ func newIssuer(config IssuerConfig, cert *Certificate, signer crypto.Signer, clk return nil, fmt.Errorf("crlURLBase must end with exactly one forward slash, got %q", config.CRLURLBase) } if config.CRLShards <= 0 { - return nil, errors.New("number of CRL shards is required") + return nil, fmt.Errorf("number of CRL shards is required") } // We require that all of our issuers be capable of both issuing certs and // providing revocation information. if cert.KeyUsage&x509.KeyUsageCertSign == 0 { - return nil, errors.New("end-entity signing cert does not have keyUsage certSign") + return nil, fmt.Errorf("end-entity signing cert does not have keyUsage certSign") } if cert.KeyUsage&x509.KeyUsageCRLSign == 0 { - return nil, errors.New("end-entity signing cert does not have keyUsage crlSign") + return nil, fmt.Errorf("end-entity signing cert does not have keyUsage crlSign") } if cert.KeyUsage&x509.KeyUsageDigitalSignature == 0 { - return nil, errors.New("end-entity signing cert does not have keyUsage digitalSignature") + return nil, fmt.Errorf("end-entity signing cert does not have keyUsage digitalSignature") } // If the issuer is active, it must have at least one profile configured. if config.Active && len(config.Profiles) == 0 { - return nil, errors.New("active issuers must have at least one profile") + return nil, fmt.Errorf("active issuers must have at least one profile") } lintSigner, err := linter.New(cert.Certificate, signer) @@ -338,7 +337,7 @@ func LoadIssuer(config IssuerConfig, clk clock.Clock) (*Issuer, error) { func loadSigner(location IssuerLoc, pubkey crypto.PublicKey) (crypto.Signer, error) { if location.File == "" && location.ConfigFile == "" && location.PKCS11 == nil { - return nil, errors.New("must supply File, ConfigFile, or PKCS11") + return nil, fmt.Errorf("must supply File, ConfigFile, or PKCS11") } if location.File != "" { diff --git a/linter/lints/rfc/lint_crl_has_valid_timestamps.go b/linter/lints/rfc/lint_crl_has_valid_timestamps.go index 0546d62c5e7..68355b08bcd 100644 --- a/linter/lints/rfc/lint_crl_has_valid_timestamps.go +++ b/linter/lints/rfc/lint_crl_has_valid_timestamps.go @@ -1,7 +1,6 @@ package rfc import ( - "errors" "fmt" "time" @@ -181,7 +180,7 @@ func lintTimestamp(der *cryptobyte.String, tag cryptobyte_asn1.Tag) error { derBytes := *der var tsBytes cryptobyte.String if !derBytes.ReadASN1(&tsBytes, tag) { - return errors.New("failed to read timestamp") + return fmt.Errorf("failed to read timestamp") } tsLen := len(string(tsBytes)) @@ -194,13 +193,13 @@ func lintTimestamp(der *cryptobyte.String, tag cryptobyte_asn1.Tag) error { } if !der.ReadASN1UTCTime(&parsedTime) { - return errors.New("failed to read timestamp encoded using UTCTime") + return fmt.Errorf("failed to read timestamp encoded using UTCTime") } // Verify that the timestamp is prior to the year 2050. This should // really never happen. if parsedTime.Year() > 2049 { - return errors.New("ReadASN1UTCTime returned a UTCTime after 2049") + return fmt.Errorf("ReadASN1UTCTime returned a UTCTime after 2049") } case cryptobyte_asn1.GeneralizedTime: // Verify that the timestamp is properly formatted. @@ -216,15 +215,15 @@ func lintTimestamp(der *cryptobyte.String, tag cryptobyte_asn1.Tag) error { // Verify that the timestamp occurred after the year 2049. if parsedTime.Year() < 2050 { - return errors.New("timestamps prior to 2050 MUST be encoded using UTCTime") + return fmt.Errorf("timestamps prior to 2050 MUST be encoded using UTCTime") } default: - return errors.New("unsupported time format") + return fmt.Errorf("unsupported time format") } // Verify that the location is UTC. if parsedTime.Location() != time.UTC { - return errors.New("time must be in UTC") + return fmt.Errorf("time must be in UTC") } return nil } diff --git a/log/log.go b/log/log.go index 8052749f64b..7c0f43fb8ff 100644 --- a/log/log.go +++ b/log/log.go @@ -4,7 +4,6 @@ import ( "encoding/base64" "encoding/binary" "encoding/json" - "errors" "fmt" "hash/crc32" "io" @@ -60,7 +59,7 @@ const auditTag = "[AUDIT]" // and also writes to stdout/stderr. It is safe for concurrent use. func New(log *syslog.Writer, stdoutLogLevel int, syslogLogLevel int) (Logger, error) { if log == nil { - return nil, errors.New("Attempted to use a nil System Logger") + return nil, fmt.Errorf("Attempted to use a nil System Logger") } return &impl{ &bothWriter{ @@ -112,7 +111,7 @@ func initialize() { // first time. func Set(logger Logger) (err error) { if _Singleton.log != nil { - err = errors.New("You may not call Set after it has already been implicitly or explicitly set") + err = fmt.Errorf("You may not call Set after it has already been implicitly or explicitly set") _Singleton.log.Warning(err.Error()) } else { _Singleton.log = logger diff --git a/log/validator/validator.go b/log/validator/validator.go index 5f309e5ae16..86435ce1750 100644 --- a/log/validator/validator.go +++ b/log/validator/validator.go @@ -18,7 +18,7 @@ import ( "github.com/letsencrypt/boulder/log" ) -var errInvalidChecksum = errors.New("invalid checksum length") +var errInvalidChecksum = fmt.Errorf("invalid checksum length") type Validator struct { // mu guards patterns and tailers to prevent Shutdown racing monitor @@ -230,7 +230,7 @@ func ValidateFile(filename string) error { } if badFile { - return errors.New("file contained invalid lines") + return fmt.Errorf("file contained invalid lines") } return nil } diff --git a/mocks/sa.go b/mocks/sa.go index 04e989cfb86..f94d1565033 100644 --- a/mocks/sa.go +++ b/mocks/sa.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "crypto/x509" - "errors" + "fmt" "os" "time" @@ -48,7 +48,7 @@ const ( func (sa *StorageAuthorityReadOnly) GetRegistration(_ context.Context, req *sapb.RegistrationID, _ ...grpc.CallOption) (*corepb.Registration, error) { if req.Id == 100 { // Tag meaning "Missing" - return nil, errors.New("missing") + return nil, fmt.Errorf("missing") } if req.Id == 101 { // Tag meaning "Malformed" @@ -183,7 +183,7 @@ func (sa *StorageAuthorityReadOnly) GetSerialMetadata(ctx context.Context, req * // GetCertificate is a mock func (sa *StorageAuthorityReadOnly) GetCertificate(_ context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*corepb.Certificate, error) { if req.Serial == "000000000000000000000000000000626164" { - return nil, errors.New("bad") + return nil, fmt.Errorf("bad") } else { return nil, berrors.NotFoundError("No cert") } @@ -196,7 +196,7 @@ func (sa *StorageAuthorityReadOnly) GetLintPrecertificate(_ context.Context, req // GetCertificateStatus is a mock func (sa *StorageAuthorityReadOnly) GetCertificateStatus(_ context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*corepb.CertificateStatus, error) { - return nil, errors.New("no cert status") + return nil, fmt.Errorf("no cert status") } // GetRevocationStatus is a mock @@ -250,7 +250,7 @@ func (sa *StorageAuthorityReadOnly) GetOrder(_ context.Context, req *sapb.OrderR case 2: return nil, berrors.NotFoundError("bad") case 3: - return nil, errors.New("very bad") + return nil, fmt.Errorf("very bad") } now := sa.clk.Now() diff --git a/nonce/nonce.go b/nonce/nonce.go index 91f1eabc78c..1838e44eb89 100644 --- a/nonce/nonce.go +++ b/nonce/nonce.go @@ -22,7 +22,6 @@ import ( "crypto/rand" "crypto/sha256" "encoding/base64" - "errors" "fmt" "math/big" "sync" @@ -46,7 +45,7 @@ const ( defaultMaxUsed = 65536 ) -var errInvalidNonceLength = errors.New("invalid nonce length") +var errInvalidNonceLength = fmt.Errorf("invalid nonce length") // PrefixCtxKey is exported for use as a key in a context.Context. type PrefixCtxKey struct{} @@ -116,7 +115,7 @@ func NewNonceService(stats prometheus.Registerer, maxUsed int, prefix string) (* ) } if _, err := base64.RawURLEncoding.DecodeString(prefix); err != nil { - return nil, errors.New("nonce prefix must be valid base64url") + return nil, fmt.Errorf("nonce prefix must be valid base64url") } } diff --git a/observer/mon_conf.go b/observer/mon_conf.go index 44ecb1a5719..a281f0f146d 100644 --- a/observer/mon_conf.go +++ b/observer/mon_conf.go @@ -1,7 +1,7 @@ package observer import ( - "errors" + "fmt" "time" "github.com/prometheus/client_golang/prometheus" @@ -21,7 +21,7 @@ type MonConf struct { // validatePeriod ensures the received `Period` field is at least 1µs. func (c *MonConf) validatePeriod() error { if c.Period.Duration < 1*time.Microsecond { - return errors.New("period must be at least 1µs") + return fmt.Errorf("period must be at least 1µs") } return nil } diff --git a/observer/obs_conf.go b/observer/obs_conf.go index f7d66a1b51b..fc887e112c0 100644 --- a/observer/obs_conf.go +++ b/observer/obs_conf.go @@ -1,7 +1,6 @@ package observer import ( - "errors" "fmt" "strconv" @@ -80,7 +79,7 @@ func (c *ObsConf) makeMonitors(metrics prometheus.Registerer) ([]*monitor, []err } } if len(c.MonConfs) == len(errs) { - return nil, errs, errors.New("no valid monitors, cannot continue") + return nil, errs, fmt.Errorf("no valid monitors, cannot continue") } return monitors, errs, nil } diff --git a/observer/obs_conf_test.go b/observer/obs_conf_test.go index dc2269e2e57..87188f29de0 100644 --- a/observer/obs_conf_test.go +++ b/observer/obs_conf_test.go @@ -1,7 +1,7 @@ package observer import ( - "errors" + "fmt" "testing" "time" @@ -19,7 +19,7 @@ const ( ) func TestObsConf_makeMonitors(t *testing.T) { - var errDBZ = errors.New(errDBZMsg) + var errDBZ = fmt.Errorf("%s", errDBZMsg) var cfgSyslog = cmd.SyslogConfig{StdoutLevel: 6, SyslogLevel: 6} var cfgDur = config.Duration{Duration: time.Second * 5} var cfgBuckets = []float64{.001} diff --git a/observer/probers/mock/mock_conf.go b/observer/probers/mock/mock_conf.go index 3640cb7fcf5..2d1889b90a9 100644 --- a/observer/probers/mock/mock_conf.go +++ b/observer/probers/mock/mock_conf.go @@ -1,7 +1,7 @@ package probers import ( - "errors" + "fmt" "github.com/prometheus/client_golang/prometheus" @@ -35,7 +35,7 @@ func (c MockConfigurer) UnmarshalSettings(settings []byte) (probers.Configurer, func (c MockConfigurer) MakeProber(_ map[string]prometheus.Collector) (probers.Prober, error) { if !c.Valid { - return nil, errors.New("could not be validated") + return nil, fmt.Errorf("could not be validated") } return MockProber{c.PName, c.PKind, c.PTook, c.PSuccess}, nil } diff --git a/observer/probers/tls/tls.go b/observer/probers/tls/tls.go index 070eceadf10..3b460992a0a 100644 --- a/observer/probers/tls/tls.go +++ b/observer/probers/tls/tls.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "crypto/x509" "encoding/base64" - "errors" "fmt" "io" "net" @@ -99,7 +98,7 @@ func checkOCSP(ctx context.Context, cert, issuer *x509.Certificate, want int) (b func checkCRL(ctx context.Context, cert, issuer *x509.Certificate, want int) (bool, error) { if len(cert.CRLDistributionPoints) != 1 { - return false, errors.New("cert does not contain CRLDP URI") + return false, fmt.Errorf("cert does not contain CRLDP URI") } req, err := http.NewRequestWithContext(ctx, "GET", cert.CRLDistributionPoints[0], nil) diff --git a/pkcs11helpers/helpers.go b/pkcs11helpers/helpers.go index 4c02146d8d8..cc8b0a4b5e2 100644 --- a/pkcs11helpers/helpers.go +++ b/pkcs11helpers/helpers.go @@ -6,7 +6,6 @@ import ( "crypto/elliptic" "crypto/rsa" "encoding/asn1" - "errors" "fmt" "io" "math/big" @@ -35,7 +34,7 @@ type Session struct { func Initialize(module string, slot uint, pin string) (*Session, error) { ctx := pkcs11.New(module) if ctx == nil { - return nil, errors.New("failed to load module") + return nil, fmt.Errorf("failed to load module") } err := ctx.Initialize() if err != nil { @@ -161,7 +160,7 @@ func (s *Session) GetRSAPublicKey(object pkcs11.ObjectHandle) (*rsa.PublicKey, e } // Fail if we are missing either the public exponent or modulus if !gotExp || !gotMod { - return nil, errors.New("Couldn't retrieve modulus and exponent") + return nil, fmt.Errorf("Couldn't retrieve modulus and exponent") } return pubKey, nil } @@ -192,7 +191,7 @@ func (s *Session) GetECDSAPublicKey(object pkcs11.ObjectHandle) (*ecdsa.PublicKe case pkcs11.CKA_EC_PARAMS: rCurve, present := oidDERToCurve[fmt.Sprintf("%X", a.Value)] if !present { - return nil, errors.New("Unknown curve OID value returned") + return nil, fmt.Errorf("Unknown curve OID value returned") } pubKey.Curve = rCurve case pkcs11.CKA_EC_POINT: @@ -200,7 +199,7 @@ func (s *Session) GetECDSAPublicKey(object pkcs11.ObjectHandle) (*ecdsa.PublicKe } } if pointBytes == nil || pubKey.Curve == nil { - return nil, errors.New("Couldn't retrieve EC point and EC parameters") + return nil, fmt.Errorf("Couldn't retrieve EC point and EC parameters") } x, y := elliptic.Unmarshal(pubKey.Curve, pointBytes) @@ -214,11 +213,11 @@ func (s *Session) GetECDSAPublicKey(object pkcs11.ObjectHandle) (*ecdsa.PublicKe return nil, fmt.Errorf("Failed to unmarshal returned CKA_EC_POINT: %s", err) } if len(point.Bytes) == 0 { - return nil, errors.New("Invalid CKA_EC_POINT value returned, OCTET string is empty") + return nil, fmt.Errorf("Invalid CKA_EC_POINT value returned, OCTET string is empty") } x, y = elliptic.Unmarshal(pubKey.Curve, point.Bytes) if x == nil { - return nil, errors.New("Invalid CKA_EC_POINT value returned, point is malformed") + return nil, fmt.Errorf("Invalid CKA_EC_POINT value returned, point is malformed") } } pubKey.X, pubKey.Y = x, y @@ -243,7 +242,7 @@ var hashIdents = map[crypto.Hash][]byte{ func (s *Session) Sign(object pkcs11.ObjectHandle, keyType keyType, digest []byte, hash crypto.Hash) ([]byte, error) { if len(digest) != hash.Size() { - return nil, errors.New("digest length doesn't match hash length") + return nil, fmt.Errorf("digest length doesn't match hash length") } mech := make([]*pkcs11.Mechanism, 1) @@ -252,7 +251,7 @@ func (s *Session) Sign(object pkcs11.ObjectHandle, keyType keyType, digest []byt mech[0] = pkcs11.NewMechanism(pkcs11.CKM_RSA_PKCS, nil) prefix, ok := hashIdents[hash] if !ok { - return nil, errors.New("unsupported hash function") + return nil, fmt.Errorf("unsupported hash function") } digest = append(prefix, digest...) case ECDSAKey: @@ -271,7 +270,7 @@ func (s *Session) Sign(object pkcs11.ObjectHandle, keyType keyType, digest []byt return signature, nil } -var ErrNoObject = errors.New("no objects found matching provided template") +var ErrNoObject = fmt.Errorf("no objects found matching provided template") // FindObject looks up a PKCS#11 object handle based on the provided template. // In the case where zero or more than one objects are found to match the diff --git a/pkcs11helpers/helpers_test.go b/pkcs11helpers/helpers_test.go index f7089964523..0307e979f26 100644 --- a/pkcs11helpers/helpers_test.go +++ b/pkcs11helpers/helpers_test.go @@ -9,7 +9,7 @@ import ( "crypto/rsa" "crypto/sha256" "encoding/asn1" - "errors" + "fmt" "math/big" "strings" "testing" @@ -24,7 +24,7 @@ func TestGetECDSAPublicKey(t *testing.T) { // test attribute retrieval failing ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { - return nil, errors.New("yup") + return nil, fmt.Errorf("yup") } _, err := s.GetECDSAPublicKey(0) test.AssertError(t, err, "ecPub didn't fail on GetAttributeValue error") @@ -102,7 +102,7 @@ func TestRSAPublicKey(t *testing.T) { // test attribute retrieval failing ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { - return nil, errors.New("yup") + return nil, fmt.Errorf("yup") } _, err := s.GetRSAPublicKey(0) test.AssertError(t, err, "rsaPub didn't fail on GetAttributeValue error") @@ -159,7 +159,7 @@ func TestFindObjectFailsOnFailedInit(t *testing.T) { // test FindObject fails when FindObjectsInit fails ctx.FindObjectsInitFunc = func(pkcs11.SessionHandle, []*pkcs11.Attribute) error { - return errors.New("broken") + return fmt.Errorf("broken") } s := &Session{ctx, 0} _, err := s.FindObject(nil) @@ -173,7 +173,7 @@ func TestFindObjectFailsOnFailedFindObjects(t *testing.T) { // test FindObject fails when FindObjects fails ctx.FindObjectsFunc = func(pkcs11.SessionHandle, int) ([]pkcs11.ObjectHandle, bool, error) { - return nil, false, errors.New("broken") + return nil, false, fmt.Errorf("broken") } s := &Session{ctx, 0} _, err := s.FindObject(nil) @@ -218,7 +218,7 @@ func TestFindObjectFailsOnFinalizeFailure(t *testing.T) { return []pkcs11.ObjectHandle{1}, false, nil } ctx.FindObjectsFinalFunc = func(pkcs11.SessionHandle) error { - return errors.New("broken") + return fmt.Errorf("broken") } s := &Session{ctx, 0} _, err := s.FindObject(nil) @@ -325,7 +325,7 @@ func TestGetKeyWhenGetAttributeValueFails(t *testing.T) { // test newSigner fails when GetAttributeValue fails ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { - return nil, errors.New("broken") + return nil, fmt.Errorf("broken") } _, err := s.NewSigner("label", pubKey) test.AssertError(t, err, "newSigner didn't fail when GetAttributeValue for private key type failed") @@ -336,7 +336,7 @@ func TestGetKeyWhenGetAttributeValueReturnsNone(t *testing.T) { pubKey := &rsa.PublicKey{N: big.NewInt(1), E: 1} ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { - return nil, errors.New("broken") + return nil, fmt.Errorf("broken") } // test newSigner fails when GetAttributeValue returns no attributes ctx.GetAttributeValueFunc = func(pkcs11.SessionHandle, pkcs11.ObjectHandle, []*pkcs11.Attribute) ([]*pkcs11.Attribute, error) { @@ -356,7 +356,7 @@ func TestGetKeyWhenFindObjectForPublicKeyFails(t *testing.T) { } ctx.FindObjectsInitFunc = func(_ pkcs11.SessionHandle, tmpl []*pkcs11.Attribute) error { if bytes.Equal(tmpl[0].Value, []byte{2, 0, 0, 0, 0, 0, 0, 0}) { - return errors.New("broken") + return fmt.Errorf("broken") } return nil } @@ -410,7 +410,7 @@ func TestGetKeySucceeds(t *testing.T) { case pkcs11.CKA_ID: returns = append(returns, pkcs11.NewAttribute(pkcs11.CKA_ID, []byte{99})) default: - return nil, errors.New("GetAttributeValue got unexpected attribute type") + return nil, fmt.Errorf("GetAttributeValue got unexpected attribute type") } } return returns, nil diff --git a/policy/pa.go b/policy/pa.go index 99ac11ad564..017d75b0116 100644 --- a/policy/pa.go +++ b/policy/pa.go @@ -660,7 +660,7 @@ func (pa *AuthorityImpl) CheckAuthzChallenges(authz *core.Authorization) error { } if !pa.ChallengeTypeEnabled(chall) { - return errors.New("authorization fulfilled by disabled challenge type") + return fmt.Errorf("authorization fulfilled by disabled challenge type") } challTypes, err := pa.ChallengeTypesFor(authz.Identifier) @@ -669,7 +669,7 @@ func (pa *AuthorityImpl) CheckAuthzChallenges(authz *core.Authorization) error { } if !slices.Contains(challTypes, chall) { - return errors.New("authorization fulfilled by inapplicable challenge type") + return fmt.Errorf("authorization fulfilled by inapplicable challenge type") } return nil diff --git a/precert/corr.go b/precert/corr.go index a0708e28a21..05f0624dff7 100644 --- a/precert/corr.go +++ b/precert/corr.go @@ -3,7 +3,6 @@ package precert import ( "bytes" encoding_asn1 "encoding/asn1" - "errors" "fmt" "golang.org/x/crypto/cryptobyte" @@ -161,12 +160,12 @@ func (e *extensionParser) Next() (cryptobyte.String, error) { func unwrapExtensions(field cryptobyte.String) (cryptobyte.String, error) { var extensions cryptobyte.String if !field.ReadASN1(&extensions, asn1.Tag(3).Constructed().ContextSpecific()) { - return nil, errors.New("error reading extensions") + return nil, fmt.Errorf("error reading extensions") } var extensionsInner cryptobyte.String if !extensions.ReadASN1(&extensionsInner, asn1.SEQUENCE) { - return nil, errors.New("error reading extensions inner") + return nil, fmt.Errorf("error reading extensions inner") } return extensionsInner, nil diff --git a/privatekey/privatekey.go b/privatekey/privatekey.go index 912ce8f6a0d..8a4448eb01b 100644 --- a/privatekey/privatekey.go +++ b/privatekey/privatekey.go @@ -8,7 +8,6 @@ import ( "crypto/sha256" "crypto/x509" "encoding/pem" - "errors" "fmt" "hash" "os" @@ -52,7 +51,7 @@ func verifyECDSA(privKey *ecdsa.PrivateKey, pubKey *ecdsa.PublicKey, msgHash has verify := ecdsa.Verify(pubKey, msgHash.Sum(nil), r, s) if !verify { - return nil, nil, errors.New("the provided ECDSA private key failed signature verification") + return nil, nil, fmt.Errorf("the provided ECDSA private key failed signature verification") } return privKey, privKey.Public(), nil } @@ -76,7 +75,7 @@ func verify(privateKey crypto.Signer) (crypto.Signer, crypto.PublicKey, error) { default: // This should never happen. - return nil, nil, errors.New("the provided private key could not be asserted to ECDSA or RSA") + return nil, nil, fmt.Errorf("the provided private key could not be asserted to ECDSA or RSA") } } diff --git a/publisher/publisher.go b/publisher/publisher.go index bff7c7c23a3..a21392148c4 100644 --- a/publisher/publisher.go +++ b/publisher/publisher.go @@ -229,7 +229,7 @@ func New( // to the caller. func (pub *Impl) SubmitToSingleCTWithResult(ctx context.Context, req *pubpb.Request) (*pubpb.Result, error) { if core.IsAnyNilOrZero(req.Der, req.LogURL, req.LogPublicKey, req.Kind) { - return nil, errors.New("incomplete gRPC request message") + return nil, fmt.Errorf("incomplete gRPC request message") } cert, err := x509.ParseCertificate(req.Der) diff --git a/ra/ra.go b/ra/ra.go index 15d3dd6993a..11c232884be 100644 --- a/ra/ra.go +++ b/ra/ra.go @@ -56,8 +56,8 @@ import ( ) var ( - errIncompleteGRPCRequest = errors.New("incomplete gRPC request message") - errIncompleteGRPCResponse = errors.New("incomplete gRPC response message") + errIncompleteGRPCRequest = fmt.Errorf("incomplete gRPC request message") + errIncompleteGRPCResponse = fmt.Errorf("incomplete gRPC response message") // caaRecheckDuration is the amount of time after a CAA check that we will // recheck the CAA records for a domain. Per Baseline Requirements, we must @@ -114,7 +114,7 @@ func (ra *RegistrationAuthorityImpl) Health(ctx context.Context) error { if ra.txnBuilder.Ready() { return nil } - return errors.New("waiting for overrides") + return fmt.Errorf("waiting for overrides") } // NewRegistrationAuthorityImpl constructs a new RA object. @@ -312,7 +312,7 @@ type validationProfiles struct { // are within the bounds mandated by the Baseline Requirements. func NewValidationProfiles(defaultName string, configs map[string]*ValidationProfileConfig) (*validationProfiles, error) { if defaultName == "" { - return nil, errors.New("default profile name must be configured") + return nil, fmt.Errorf("default profile name must be configured") } profiles := make(map[string]*validationProfile, len(configs)) @@ -1826,10 +1826,10 @@ func (ra *RegistrationAuthorityImpl) RevokeCertByApplicant(ctx context.Context, // on this certificate comes from one of our issuers. func crlShard(cert *x509.Certificate) (int64, error) { if len(cert.CRLDistributionPoints) == 0 { - return 0, errors.New("no crlDistributionPoints in certificate") + return 0, fmt.Errorf("no crlDistributionPoints in certificate") } if len(cert.CRLDistributionPoints) > 1 { - return 0, errors.New("too many crlDistributionPoints in certificate") + return 0, fmt.Errorf("too many crlDistributionPoints in certificate") } url := strings.TrimSuffix(cert.CRLDistributionPoints[0], ".crl") @@ -1956,10 +1956,10 @@ func (ra *RegistrationAuthorityImpl) AdministrativelyRevokeCertificate(ctx conte return nil, errIncompleteGRPCRequest } if req.CrlShard != 0 && !req.Malformed { - return nil, errors.New("non-zero CRLShard is only allowed for malformed certificates (shard is automatic for well formed certificates)") + return nil, fmt.Errorf("non-zero CRLShard is only allowed for malformed certificates (shard is automatic for well formed certificates)") } if req.Malformed && req.CrlShard == 0 { - return nil, errors.New("CRLShard is required for malformed certificates") + return nil, fmt.Errorf("CRLShard is required for malformed certificates") } reasonCode := revocation.Reason(req.Code) @@ -2059,7 +2059,7 @@ func (ra *RegistrationAuthorityImpl) AdministrativelyRevokeCertificate(ctx conte if reasonCode == revocation.KeyCompromise && !req.SkipBlockKey { if cert == nil { - return nil, errors.New("revoking for key compromise requires providing the certificate's DER") + return nil, fmt.Errorf("revoking for key compromise requires providing the certificate's DER") } err = ra.addToBlockedKeys(ctx, cert.PublicKey, "admin-revoker", fmt.Sprintf("revoked by %s", req.AdminName)) if err != nil { diff --git a/ra/ra_test.go b/ra/ra_test.go index 8334f3ca1cd..5e8b3c5ad67 100644 --- a/ra/ra_test.go +++ b/ra/ra_test.go @@ -13,7 +13,6 @@ import ( "encoding/hex" "encoding/json" "encoding/pem" - "errors" "fmt" "math" "math/big" @@ -3673,10 +3672,10 @@ func (msar *mockSARevocation) RevokeCertificate(_ context.Context, req *sapb.Rev func (msar *mockSARevocation) UpdateRevokedCertificate(_ context.Context, req *sapb.RevokeCertificateRequest, _ ...grpc.CallOption) (*emptypb.Empty, error) { status, present := msar.revoked[req.Serial] if !present { - return nil, errors.New("not already revoked") + return nil, fmt.Errorf("not already revoked") } if revocation.Reason(req.Reason) != revocation.KeyCompromise { - return nil, errors.New("cannot re-revoke except for keyCompromise") + return nil, fmt.Errorf("cannot re-revoke except for keyCompromise") } if present && revocation.Reason(status.RevokedReason) == revocation.KeyCompromise { return nil, berrors.AlreadyRevokedError("already revoked for keyCompromise") diff --git a/ratelimits/limit.go b/ratelimits/limit.go index 7f093a5387b..c715a512c20 100644 --- a/ratelimits/limit.go +++ b/ratelimits/limit.go @@ -3,7 +3,6 @@ package ratelimits import ( "context" "encoding/csv" - "errors" "fmt" "net/netip" "os" @@ -23,7 +22,7 @@ import ( // errLimitDisabled indicates that the limit name specified is valid but is not // currently configured. -var errLimitDisabled = errors.New("limit disabled") +var errLimitDisabled = fmt.Errorf("limit disabled") // LimitConfig defines the exportable configuration for a rate limit or a rate // limit override, without a `limit`'s internal fields. diff --git a/ratelimits/limit_test.go b/ratelimits/limit_test.go index 933fbff1f55..34a70f2eefd 100644 --- a/ratelimits/limit_test.go +++ b/ratelimits/limit_test.go @@ -2,7 +2,6 @@ package ratelimits import ( "context" - "errors" "fmt" "net/netip" "os" @@ -292,7 +291,7 @@ func TestLoadOverrides(t *testing.T) { // overwrite existing overrides. mockLog.Clear() tb.limitRegistry.refreshOverrides = func(context.Context, prometheus.Gauge, blog.Logger) (Limits, error) { - return nil, errors.New("mock failure") + return nil, fmt.Errorf("mock failure") } err = tb.limitRegistry.loadOverrides(context.Background()) test.AssertError(t, err, "fail to load overrides") diff --git a/ratelimits/source_redis.go b/ratelimits/source_redis.go index 05562bb8869..88b7880aad8 100644 --- a/ratelimits/source_redis.go +++ b/ratelimits/source_redis.go @@ -3,6 +3,7 @@ package ratelimits import ( "context" "errors" + "fmt" "net" "time" @@ -39,7 +40,7 @@ func NewRedisSource(client *redis.Ring, clk clock.Clock, stats prometheus.Regist } } -var errMixedSuccess = errors.New("some keys not found") +var errMixedSuccess = fmt.Errorf("some keys not found") // resultForError returns a string representing the result of the operation // based on the provided error. diff --git a/ratelimits/transaction_test.go b/ratelimits/transaction_test.go index e45aa7dfa61..46c27b59e4d 100644 --- a/ratelimits/transaction_test.go +++ b/ratelimits/transaction_test.go @@ -2,7 +2,6 @@ package ratelimits import ( "context" - "errors" "fmt" "net/netip" "sort" @@ -260,7 +259,7 @@ func TestNewTransactionBuilderFromDatabase(t *testing.T) { { name: "error fetching enabled overrides", overrides: func(context.Context, *emptypb.Empty, ...grpc.CallOption) (grpc.ServerStreamingClient[sapb.RateLimitOverrideResponse], error) { - return nil, errors.New("lol no") + return nil, fmt.Errorf("lol no") }, expectError: "fetching enabled overrides: lol no", }, @@ -273,7 +272,7 @@ func TestNewTransactionBuilderFromDatabase(t *testing.T) { { name: "gRPC error", overrides: func(context.Context, *emptypb.Empty, ...grpc.CallOption) (grpc.ServerStreamingClient[sapb.RateLimitOverrideResponse], error) { - return &mocks.ServerStreamClient[sapb.RateLimitOverrideResponse]{Err: errors.New("i ate ur toast m8")}, nil + return &mocks.ServerStreamClient[sapb.RateLimitOverrideResponse]{Err: fmt.Errorf("i ate ur toast m8")}, nil }, expectError: "reading overrides stream: i ate ur toast m8", }, diff --git a/redis/lookup.go b/redis/lookup.go index f66ed7450a3..eba17f64c18 100644 --- a/redis/lookup.go +++ b/redis/lookup.go @@ -15,7 +15,7 @@ import ( "github.com/redis/go-redis/v9" ) -var ErrNoShardsResolved = errors.New("0 shards were resolved") +var ErrNoShardsResolved = fmt.Errorf("0 shards were resolved") // lookup wraps a Redis ring client by reference and keeps the Redis ring shards // up to date via periodic SRV lookups. diff --git a/sa/database_test.go b/sa/database_test.go index 95cfe07a977..9cb4b856941 100644 --- a/sa/database_test.go +++ b/sa/database_test.go @@ -3,7 +3,7 @@ package sa import ( "context" "database/sql" - "errors" + "fmt" "os" "path" "strings" @@ -38,7 +38,7 @@ func TestInvalidDSN(t *testing.T) { test.AssertError(t, err, "Integer enum declared, but should not have been quoted") } -var errExpected = errors.New("expected") +var errExpected = fmt.Errorf("expected") func TestDbSettings(t *testing.T) { // TODO(#5248): Add a full db.mockWrappedMap to sa/database tests diff --git a/sa/model.go b/sa/model.go index c748ce7b1fa..0d956a77e4e 100644 --- a/sa/model.go +++ b/sa/model.go @@ -247,7 +247,7 @@ func registrationPbToModel(reg *corepb.Registration) (*regModel, error) { func registrationModelToPb(reg *regModel) (*corepb.Registration, error) { if reg.ID == 0 || len(reg.Key) == 0 { - return nil, errors.New("incomplete Registration retrieved from DB") + return nil, fmt.Errorf("incomplete Registration retrieved from DB") } return &corepb.Registration{ @@ -649,7 +649,7 @@ func authzPBToModel(authz *corepb.Authorization) (*authzModel, error) { am.ID = int64(id) } if hasMultipleNonPendingChallenges(authz.Challenges) { - return nil, errors.New("multiple challenges are non-pending") + return nil, fmt.Errorf("multiple challenges are non-pending") } // In the v2 authorization style we don't store individual challenges with their own // token, validation errors/records, etc. Instead we store a single token/error/record @@ -1024,7 +1024,7 @@ func reverseFQDN(fqdn string) string { func addKeyHash(ctx context.Context, db db.Inserter, cert *x509.Certificate) error { if cert.RawSubjectPublicKeyInfo == nil { - return errors.New("certificate has a nil RawSubjectPublicKeyInfo") + return fmt.Errorf("certificate has a nil RawSubjectPublicKeyInfo") } h := sha256.Sum256(cert.RawSubjectPublicKeyInfo) khm := &keyHashModel{ diff --git a/sa/sa.go b/sa/sa.go index 46f43c831dc..a87009642c5 100644 --- a/sa/sa.go +++ b/sa/sa.go @@ -32,7 +32,7 @@ import ( ) var ( - errIncompleteRequest = errors.New("incomplete gRPC request message") + errIncompleteRequest = fmt.Errorf("incomplete gRPC request message") ) // SQLStorageAuthority defines a Storage Authority. @@ -469,7 +469,7 @@ func (ssa *SQLStorageAuthority) NewOrderAndAuthzs(ctx context.Context, req *sapb // This is a belt-and-suspenders check. These were just created by the RA, // so their RegIDs should match. But if they don't, the consequences would // be very bad, so we do an extra check here. - return nil, errors.New("new order and authzs must all be associated with same account") + return nil, fmt.Errorf("new order and authzs must all be associated with same account") } } @@ -808,7 +808,7 @@ func (ssa *SQLStorageAuthority) FinalizeAuthorization2(ctx context.Context, req // specifies a non-zero ShardIdx. func addRevokedCertificate(ctx context.Context, tx db.Executor, req *sapb.RevokeCertificateRequest, revokedDate time.Time) error { if req.ShardIdx == 0 { - return errors.New("cannot add revoked certificate with shard index 0") + return fmt.Errorf("cannot add revoked certificate with shard index 0") } var serial struct { @@ -979,7 +979,7 @@ func (ssa *SQLStorageAuthority) AddBlockedKey(ctx context.Context, req *sapb.Add } sourceInt, ok := stringToSourceInt[req.Source] if !ok { - return nil, errors.New("unknown source") + return nil, fmt.Errorf("unknown source") } cols, qs := blockedKeysColumns, "?, ?, ?, ?" vals := []any{ @@ -1127,7 +1127,7 @@ func (ssa *SQLStorageAuthority) leaseOldestCRLShard(ctx context.Context, req *sa return -1, fmt.Errorf("confirming update of selected shard: %w", err) } if rowsAffected != 1 { - return -1, errors.New("failed to lease shard") + return -1, fmt.Errorf("failed to lease shard") } } @@ -1204,7 +1204,7 @@ func (ssa *SQLStorageAuthority) leaseSpecificCRLShard(ctx context.Context, req * return -1, fmt.Errorf("confirming update of selected shard: %w", err) } if rowsAffected != 1 { - return -1, errors.New("failed to lease shard") + return -1, fmt.Errorf("failed to lease shard") } } @@ -1271,7 +1271,7 @@ func (ssa *SQLStorageAuthority) UpdateCRLShard(ctx context.Context, req *sapb.Up return nil, fmt.Errorf("unable to update shard %d for issuer %d; possibly because shard exists", req.ShardIdx, req.IssuerNameID) } if rowsAffected != 1 { - return nil, errors.New("update affected unexpected number of rows") + return nil, fmt.Errorf("update affected unexpected number of rows") } return nil, nil }) diff --git a/sa/type-converter.go b/sa/type-converter.go index 2ec4ad27a05..7018f7c0a39 100644 --- a/sa/type-converter.go +++ b/sa/type-converter.go @@ -2,7 +2,6 @@ package sa import ( "encoding/json" - "errors" "fmt" "time" @@ -60,7 +59,7 @@ func (tc BoulderTypeConverter) FromDb(target any) (borp.CustomScanner, bool) { binder := func(holder, target any) error { s, ok := holder.(*string) if !ok { - return errors.New("FromDb: Unable to convert *string") + return fmt.Errorf("FromDb: Unable to convert *string") } b := []byte(*s) err := json.Unmarshal(b, target) @@ -80,7 +79,7 @@ func (tc BoulderTypeConverter) FromDb(target any) (borp.CustomScanner, bool) { return fmt.Errorf("FromDb: Unable to convert %T to *string", holder) } if *s == "" { - return errors.New("FromDb: Empty JWK field.") + return fmt.Errorf("FromDb: Empty JWK field.") } b := []byte(*s) k, ok := target.(*jose.JSONWebKey) diff --git a/sfe/overrides.go b/sfe/overrides.go index a402c93b445..2b128630130 100644 --- a/sfe/overrides.go +++ b/sfe/overrides.go @@ -281,12 +281,12 @@ func createOverrideRequestZendeskTicket(client *zendesk.Client, rateLimit, reque limit, ok := rl.StringToName[limitStr] if !ok { // This should never happen, it indicates a bug in our validation. - return 0, errors.New("invalid rate limit prevented ticket creation") + return 0, fmt.Errorf("invalid rate limit prevented ticket creation") } if registeredDomain == "" && ipAddress == "" && accountURI == "" { // This should never happen, it indicates a bug in our validation. - return 0, errors.New("one of accountURI, registeredDomain, or ipAddress must be provided") + return 0, fmt.Errorf("one of accountURI, registeredDomain, or ipAddress must be provided") } return client.CreateTicket( diff --git a/sfe/sfe.go b/sfe/sfe.go index 99dc11d0a94..64072ef815d 100644 --- a/sfe/sfe.go +++ b/sfe/sfe.go @@ -357,7 +357,7 @@ func (sfe *SelfServiceFrontEndImpl) parseUnpauseJWT(incomingJWT string) (int64, if convErr != nil { // This should never happen as this was just validated by the call to // unpause.RedeemJWT(). - return 0, nil, errors.New("failed to parse account ID from JWT") + return 0, nil, fmt.Errorf("failed to parse account ID from JWT") } return account, strings.Split(claims.I, ","), nil diff --git a/test/certs/webpki.go b/test/certs/webpki.go index 465d69fb680..67bbe2abcc3 100644 --- a/test/certs/webpki.go +++ b/test/certs/webpki.go @@ -2,7 +2,6 @@ package main import ( - "errors" "fmt" "os" "os/exec" @@ -26,7 +25,7 @@ func createSlot(label string) (string, error) { re := regexp.MustCompile(`to slot (\d+)`) matches := re.FindSubmatch(output) if len(matches) != 2 { - return "", errors.New("unexpected number of slot matches") + return "", fmt.Errorf("unexpected number of slot matches") } return string(matches[1]), nil } diff --git a/test/chall-test-srv/history.go b/test/chall-test-srv/history.go index b03f9f524ec..c5f39aa5ac3 100644 --- a/test/chall-test-srv/history.go +++ b/test/chall-test-srv/history.go @@ -2,7 +2,6 @@ package main import ( "encoding/json" - "errors" "fmt" "net/http" @@ -95,7 +94,7 @@ func requestHost(r *http.Request) (string, error) { return "", err } if request.Host == "" { - return "", errors.New("host parameter of POST body must not be empty") + return "", fmt.Errorf("host parameter of POST body must not be empty") } return request.Host, nil } diff --git a/test/chall-test-srv/http.go b/test/chall-test-srv/http.go index 1c634cff04d..d424cbe3206 100644 --- a/test/chall-test-srv/http.go +++ b/test/chall-test-srv/http.go @@ -2,7 +2,7 @@ package main import ( "encoding/json" - "errors" + "fmt" "io" "net/http" ) @@ -17,7 +17,7 @@ func mustParsePOST(ob any, request *http.Request) error { } if string(jsonBody) == "" { - return errors.New("Expected JSON POST body, was empty") + return fmt.Errorf("Expected JSON POST body, was empty") } return json.Unmarshal(jsonBody, ob) diff --git a/test/load-generator/acme/challenge.go b/test/load-generator/acme/challenge.go index 12aeb9aa284..0621e106ea1 100644 --- a/test/load-generator/acme/challenge.go +++ b/test/load-generator/acme/challenge.go @@ -1,7 +1,6 @@ package acme import ( - "errors" "fmt" mrand "math/rand/v2" "strings" @@ -49,8 +48,8 @@ func NewChallengeStrategy(rawName string) (ChallengeStrategy, error) { } var ( - ErrPickChallengeNilAuthz = errors.New("PickChallenge: provided authorization can not be nil") - ErrPickChallengeAuthzMissingChallenges = errors.New("PickChallenge: provided authorization had no challenges") + ErrPickChallengeNilAuthz = fmt.Errorf("PickChallenge: provided authorization can not be nil") + ErrPickChallengeAuthzMissingChallenges = fmt.Errorf("PickChallenge: provided authorization had no challenges") ) // randomChallengeStrategy is a ChallengeStrategy implementation that always diff --git a/test/load-generator/acme/directory.go b/test/load-generator/acme/directory.go index 9be438b805a..2c8c05e5e0c 100644 --- a/test/load-generator/acme/directory.go +++ b/test/load-generator/acme/directory.go @@ -5,7 +5,6 @@ package acme import ( "crypto/tls" "encoding/json" - "errors" "fmt" "io" "net" @@ -29,22 +28,22 @@ const ( var ( // ErrEmptyDirectory is returned if NewDirectory is provided and empty directory URL. - ErrEmptyDirectory = errors.New("directoryURL must not be empty") + ErrEmptyDirectory = fmt.Errorf("directoryURL must not be empty") // ErrInvalidDirectoryURL is returned if NewDirectory is provided an invalid directory URL. - ErrInvalidDirectoryURL = errors.New("directoryURL is not a valid URL") + ErrInvalidDirectoryURL = fmt.Errorf("directoryURL is not a valid URL") // ErrInvalidDirectoryHTTPCode is returned if NewDirectory is provided a directory URL // that returns something other than HTTP Status OK to a GET request. - ErrInvalidDirectoryHTTPCode = errors.New("GET request to directoryURL did not result in HTTP Status 200") + ErrInvalidDirectoryHTTPCode = fmt.Errorf("GET request to directoryURL did not result in HTTP Status 200") // ErrInvalidDirectoryJSON is returned if NewDirectory is provided a directory URL // that returns invalid JSON. - ErrInvalidDirectoryJSON = errors.New("GET request to directoryURL returned invalid JSON") + ErrInvalidDirectoryJSON = fmt.Errorf("GET request to directoryURL returned invalid JSON") // ErrInvalidDirectoryMeta is returned if NewDirectory is provided a directory // URL that returns a directory resource with an invalid or missing "meta" key. - ErrInvalidDirectoryMeta = errors.New(`server's directory resource had invalid or missing "meta" key`) + ErrInvalidDirectoryMeta = fmt.Errorf(`server's directory resource had invalid or missing "meta" key`) // ErrInvalidTermsOfService is returned if NewDirectory is provided // a directory URL that returns a directory resource with an invalid or // missing "termsOfService" key in the "meta" map. - ErrInvalidTermsOfService = errors.New(`server's directory resource had invalid or missing "meta.termsOfService" key`) + ErrInvalidTermsOfService = fmt.Errorf(`server's directory resource had invalid or missing "meta.termsOfService" key`) // RequiredEndpoints is a slice of Endpoint keys that must be present in the // ACME server's directory. The load-generator uses each of these endpoints diff --git a/test/load-generator/boulder-calls.go b/test/load-generator/boulder-calls.go index 74db6d8e43c..0699202b34b 100644 --- a/test/load-generator/boulder-calls.go +++ b/test/load-generator/boulder-calls.go @@ -11,7 +11,6 @@ import ( "encoding/hex" "encoding/json" "encoding/pem" - "errors" "fmt" "io" mrand "math/rand/v2" @@ -66,7 +65,7 @@ func getAccount(s *State, c *acmeCache) error { // There must be an existing v2 account in the state if len(s.accts) == 0 { - return errors.New("no accounts to return") + return fmt.Errorf("no accounts to return") } // Select a random account from the state and put it into the context @@ -375,7 +374,7 @@ func pollAuthorization(authz *core.Authorization, s *State, c *acmeCache) error func fulfillOrder(s *State, c *acmeCache) error { // There must be at least one pending order in the context to fulfill if len(c.pendingOrders) == 0 { - return errors.New("no pending orders to fulfill") + return fmt.Errorf("no pending orders to fulfill") } // Get an order to fulfill from the context @@ -473,7 +472,7 @@ func popFulfilledOrder(c *acmeCache) string { func finalizeOrder(s *State, c *acmeCache) error { // There must be at least one fulfilled order in the context if len(c.fulfilledOrders) < 1 { - return errors.New("No fulfilled orders in the context ready to be finalized") + return fmt.Errorf("No fulfilled orders in the context ready to be finalized") } // Pop a fulfilled order to process, and then GET its contents @@ -596,7 +595,7 @@ func getCert(s *State, c *acmeCache, url string) ([]byte, error) { // key. func revokeCertificate(s *State, c *acmeCache) error { if len(c.certs) < 1 { - return errors.New("No certificates in the context that can be revoked") + return fmt.Errorf("No certificates in the context that can be revoked") } if r := mrand.Float32(); r > s.revokeChance { diff --git a/test/load-generator/state.go b/test/load-generator/state.go index 8c377965adf..4f97dc65806 100644 --- a/test/load-generator/state.go +++ b/test/load-generator/state.go @@ -9,7 +9,6 @@ import ( "crypto/tls" "crypto/x509" "encoding/json" - "errors" "fmt" "io" "log" @@ -294,7 +293,7 @@ func New( return nil, err } if revokeChance > 1 { - return nil, errors.New("revokeChance must be between 0.0 and 1.0") + return nil, fmt.Errorf("revokeChance must be between 0.0 and 1.0") } httpClient := &http.Client{ Transport: &http.Transport{ @@ -545,7 +544,7 @@ func (ns *nonceSource) getNonce() (string, error) { state = "good" return nonce, nil } - return "", errors.New("'Replay-Nonce' header not supplied") + return "", fmt.Errorf("'Replay-Nonce' header not supplied") } // Nonce satisfies the interface jose.NonceSource, should probably actually be per context but ¯\_(ツ)_/¯ for now diff --git a/test/zendeskfake/zendeskfake.go b/test/zendeskfake/zendeskfake.go index 974ff734c93..37a87b6a84f 100644 --- a/test/zendeskfake/zendeskfake.go +++ b/test/zendeskfake/zendeskfake.go @@ -3,7 +3,6 @@ package zendeskfake import ( "encoding/base64" "encoding/json" - "errors" "fmt" "log" "maps" @@ -117,7 +116,7 @@ func (s *Store) setStatus(id int64, status string) error { t, ok := s.byID[id] if !ok { - return errors.New("ticket not found") + return fmt.Errorf("ticket not found") } t.Status = status return nil @@ -129,7 +128,7 @@ func (s *Store) addComment(id int64, c comment) error { current, ok := s.byID[id] if !ok { - return errors.New("ticket not found") + return fmt.Errorf("ticket not found") } current.Comments = append(current.Comments, c) diff --git a/unpause/unpause.go b/unpause/unpause.go index 72cde8a15a7..3341e93b71b 100644 --- a/unpause/unpause.go +++ b/unpause/unpause.go @@ -94,7 +94,7 @@ func GenerateJWT(signer JWTSigner, regID int64, idents []string, lifetime time.D } // ErrMalformedJWT is returned when the JWT is malformed. -var ErrMalformedJWT = errors.New("malformed JWT") +var ErrMalformedJWT = fmt.Errorf("malformed JWT") // RedeemJWT deserializes an unpause JWT and returns the validated claims. The // key is used to validate the signature of the JWT. The version is the expected @@ -134,18 +134,18 @@ func RedeemJWT(token string, key []byte, version string, clk clock.Clock) (JWTCl } if len(claims.Subject) == 0 { - return JWTClaims{}, errors.New("no account ID specified in the JWT") + return JWTClaims{}, fmt.Errorf("no account ID specified in the JWT") } account, err := strconv.ParseInt(claims.Subject, 10, 64) if err != nil { - return JWTClaims{}, errors.New("invalid account ID specified in the JWT") + return JWTClaims{}, fmt.Errorf("invalid account ID specified in the JWT") } if account == 0 { - return JWTClaims{}, errors.New("no account ID specified in the JWT") + return JWTClaims{}, fmt.Errorf("no account ID specified in the JWT") } if claims.V == "" { - return JWTClaims{}, errors.New("no API version specified in the JWT") + return JWTClaims{}, fmt.Errorf("no API version specified in the JWT") } if claims.V != version { @@ -153,7 +153,7 @@ func RedeemJWT(token string, key []byte, version string, clk clock.Clock) (JWTCl } if claims.I == "" { - return JWTClaims{}, errors.New("no identifiers specified in the JWT") + return JWTClaims{}, fmt.Errorf("no identifiers specified in the JWT") } return claims, nil diff --git a/va/caa.go b/va/caa.go index 8bd2f186014..68f88d03caf 100644 --- a/va/caa.go +++ b/va/caa.go @@ -2,7 +2,6 @@ package va import ( "context" - "errors" "fmt" "net/url" "regexp" @@ -127,7 +126,7 @@ func (va *ValidationAuthorityImpl) checkCAA( ident identifier.ACMEIdentifier, params *caaParams) error { if core.IsAnyNilOrZero(params, params.validationMethod, params.accountURIID) { - return errors.New("expected validationMethod or accountURIID not provided to checkCAA") + return fmt.Errorf("expected validationMethod or accountURIID not provided to checkCAA") } foundAt, valid, response, err := va.checkCAARecords(ctx, ident, params) diff --git a/va/caa_test.go b/va/caa_test.go index 419c18ddfe0..ddf5344c39c 100644 --- a/va/caa_test.go +++ b/va/caa_test.go @@ -3,7 +3,6 @@ package va import ( "context" "encoding/json" - "errors" "fmt" "net/netip" "regexp" @@ -579,7 +578,7 @@ func TestDoCAAParams(t *testing.T) { test.AssertError(t, err, "calling IsCAAValid with a non-DNS identifier type") } -var errCAABrokenDNSClient = errors.New("dnsClient is broken") +var errCAABrokenDNSClient = fmt.Errorf("dnsClient is broken") // caaBrokenDNS implements the `dns.DNSClient` interface, but always returns // errors. @@ -1221,7 +1220,7 @@ func TestSelectCAA(t *testing.T) { // A slice of caaResults containing an error followed by a CAA // record should return the error r = []caaResult{ - {"foo.com", false, nil, nil, false, "", "", errors.New("oops")}, + {"foo.com", false, nil, nil, false, "", "", fmt.Errorf("oops")}, {"com", true, []*dns.CAA{&expected}, nil, false, "dig", "res", nil}, } s, err = selectCAA(r) @@ -1233,7 +1232,7 @@ func TestSelectCAA(t *testing.T) { // error, should return that good record, not the error r = []caaResult{ {"foo.com", true, []*dns.CAA{&expected}, nil, false, "dig", "res", nil}, - {"com", false, nil, nil, false, "", "", errors.New("")}, + {"com", false, nil, nil, false, "", "", fmt.Errorf("")}, } s, err = selectCAA(r) test.AssertEquals(t, len(s.issue), 1) diff --git a/va/http_test.go b/va/http_test.go index 605acbe03aa..7a22cd5757a 100644 --- a/va/http_test.go +++ b/va/http_test.go @@ -3,7 +3,6 @@ package va import ( "bytes" "context" - "errors" "fmt" mrand "math/rand/v2" "net" @@ -110,7 +109,7 @@ func (c *unroutableFakeDNS) LookupA(_ context.Context, hostname string) (*bdns.R } func (c *unroutableFakeDNS) LookupAAAA(_ context.Context, hostname string) (*bdns.Result[*dns.AAAA], string, error) { - return nil, "dnsFakeUnroutable", errors.New("SERVFAIL") + return nil, "dnsFakeUnroutable", fmt.Errorf("SERVFAIL") } // TestDialerTimeout tests that the preresolvedDialer's DialContext @@ -295,28 +294,28 @@ func TestExtractRequestTarget(t *testing.T) { Req: &http.Request{ URL: mustURL("https:///who/needs/a/hostname?not=me"), }, - ExpectedError: errors.New("Invalid empty host in redirect target"), + ExpectedError: fmt.Errorf("Invalid empty host in redirect target"), }, { Name: "invalid .well-known hostname", Req: &http.Request{ URL: mustURL("https://my.webserver.is.misconfigured.well-known/acme-challenge/xxx"), }, - ExpectedError: errors.New(`Invalid host in redirect target "my.webserver.is.misconfigured.well-known". Check webserver config for missing '/' in redirect target.`), + ExpectedError: fmt.Errorf(`Invalid host in redirect target "my.webserver.is.misconfigured.well-known". Check webserver config for missing '/' in redirect target.`), }, { Name: "invalid non-iana hostname", Req: &http.Request{ URL: mustURL("https://my.tld.is.cpu/pretty/cool/right?yeah=Ithoughtsotoo"), }, - ExpectedError: errors.New("Invalid host in redirect target, must end in IANA registered TLD"), + ExpectedError: fmt.Errorf("Invalid host in redirect target, must end in IANA registered TLD"), }, { Name: "malformed wildcard-ish IPv4 address", Req: &http.Request{ URL: mustURL("https://10.10.10.*"), }, - ExpectedError: errors.New("Invalid host in redirect target, must end in IANA registered TLD"), + ExpectedError: fmt.Errorf("Invalid host in redirect target, must end in IANA registered TLD"), }, { Name: "bare IPv4, implicit port", @@ -745,7 +744,7 @@ func (e *testNetErr) Timeout() bool { } func TestFallbackErr(t *testing.T) { - untypedErr := errors.New("the least interesting kind of error") + untypedErr := fmt.Errorf("the least interesting kind of error") berr := berrors.InternalServerError("code violet: class neptune") netOpErr := &net.OpError{ Op: "siphon", @@ -792,7 +791,7 @@ func TestFallbackErr(t *testing.T) { Err: &url.Error{ Op: "ivy", URL: "https://en.wikipedia.org/wiki/Operation_Ivy_(band)", - Err: errors.New("take warning"), + Err: fmt.Errorf("take warning"), }, }, { diff --git a/va/tlsalpn.go b/va/tlsalpn.go index 4671201e406..399ccf0cafe 100644 --- a/va/tlsalpn.go +++ b/va/tlsalpn.go @@ -9,7 +9,6 @@ import ( "crypto/x509/pkix" "encoding/asn1" "encoding/hex" - "errors" "fmt" "net" "net/netip" @@ -220,10 +219,10 @@ func checkExpectedSAN(cert *x509.Certificate, ident identifier.ACMEIdentifier) e switch ident.Type { case identifier.TypeDNS: if len(cert.DNSNames) != 1 || len(cert.IPAddresses) != 0 { - return errors.New("wrong number of identifiers") + return fmt.Errorf("wrong number of identifiers") } if !strings.EqualFold(cert.DNSNames[0], ident.Value) { - return errors.New("identifier does not match expected identifier") + return fmt.Errorf("identifier does not match expected identifier") } bytes, err := asn1.Marshal([]asn1.RawValue{ {Tag: 2, Class: 2, Bytes: []byte(ident.Value)}, @@ -234,10 +233,10 @@ func checkExpectedSAN(cert *x509.Certificate, ident identifier.ACMEIdentifier) e expectedSANBytes = bytes case identifier.TypeIP: if len(cert.IPAddresses) != 1 || len(cert.DNSNames) != 0 { - return errors.New("wrong number of identifiers") + return fmt.Errorf("wrong number of identifiers") } if !cert.IPAddresses[0].Equal(net.ParseIP(ident.Value)) { - return errors.New("identifier does not match expected identifier") + return fmt.Errorf("identifier does not match expected identifier") } netipAddr, err := netip.ParseAddr(ident.Value) if err != nil { @@ -263,7 +262,7 @@ func checkExpectedSAN(cert *x509.Certificate, ident identifier.ACMEIdentifier) e for _, ext := range cert.Extensions { if IdCeSubjectAltName.Equal(ext.Id) { if !bytes.Equal(ext.Value, expectedSANBytes) { - return errors.New("SAN extension does not match expected bytes") + return fmt.Errorf("SAN extension does not match expected bytes") } } } diff --git a/va/va.go b/va/va.go index 220ec67454a..71571b5d34d 100644 --- a/va/va.go +++ b/va/va.go @@ -230,7 +230,7 @@ func NewValidationAuthorityImpl( ) (*ValidationAuthorityImpl, error) { if len(accountURIPrefixes) == 0 { - return nil, errors.New("no account URI prefixes configured") + return nil, fmt.Errorf("no account URI prefixes configured") } for i, va1 := range remoteVAs { @@ -671,7 +671,7 @@ func (va *ValidationAuthorityImpl) DoDCV(ctx context.Context, req *vapb.PerformV chall, err := bgrpc.PBToChallenge(req.Challenge) if err != nil { - return nil, errors.New("challenge failed to deserialize") + return nil, fmt.Errorf("challenge failed to deserialize") } err = chall.CheckPending() @@ -743,7 +743,7 @@ func (va *ValidationAuthorityImpl) DoDCV(ctx context.Context, req *vapb.PerformV // Check for malformed ValidationRecords logEvent.Challenge.ValidationRecord = records if err == nil && !logEvent.Challenge.RecordsSane() { - err = errors.New("records from local validation failed sanity check") + err = fmt.Errorf("records from local validation failed sanity check") } if err != nil { diff --git a/va/va_test.go b/va/va_test.go index 273c563e289..d3d32b35019 100644 --- a/va/va_test.go +++ b/va/va_test.go @@ -4,7 +4,6 @@ import ( "context" "crypto/rsa" "encoding/base64" - "errors" "fmt" "math/big" "net" @@ -277,7 +276,7 @@ type brokenRemoteVA struct{} // errBrokenRemoteVA is the error returned by a brokenRemoteVA's // PerformValidation and IsSafeDomain functions. -var errBrokenRemoteVA = errors.New("brokenRemoteVA is broken") +var errBrokenRemoteVA = fmt.Errorf("brokenRemoteVA is broken") // DoDCV returns errBrokenRemoteVA unconditionally func (b brokenRemoteVA) DoDCV(_ context.Context, _ *vapb.PerformValidationRequest, _ ...grpc.CallOption) (*vapb.ValidationResult, error) { diff --git a/web/send_error_test.go b/web/send_error_test.go index 84b6eed9630..884526112b4 100644 --- a/web/send_error_test.go +++ b/web/send_error_test.go @@ -1,7 +1,7 @@ package web import ( - "errors" + "fmt" "net/http/httptest" "testing" @@ -36,7 +36,7 @@ func TestSendErrorSubProblemNamespace(t *testing.T) { }), "dfoop", ) - SendError(log.NewMock(), rw, &RequestEvent{}, prob, errors.New("it bad")) + SendError(log.NewMock(), rw, &RequestEvent{}, prob, fmt.Errorf("it bad")) body := rw.Body.String() test.AssertUnmarshaledEquals(t, body, `{ @@ -91,7 +91,7 @@ func TestSendErrorSubProbLogging(t *testing.T) { "dfoop", ) logEvent := RequestEvent{} - SendError(log.NewMock(), rw, &logEvent, prob, errors.New("it bad")) + SendError(log.NewMock(), rw, &logEvent, prob, fmt.Errorf("it bad")) test.AssertEquals(t, logEvent.Error, `400 :: malformed :: dfoop :: bad ["example.com :: malformed :: dfoop :: nop", "what about example.com :: malformed :: dfoop :: nah"]`) } diff --git a/wfe2/cache_test.go b/wfe2/cache_test.go index f4f0fafe1e4..51a7ecd57d0 100644 --- a/wfe2/cache_test.go +++ b/wfe2/cache_test.go @@ -2,7 +2,7 @@ package wfe2 import ( "context" - "errors" + "fmt" "testing" "time" @@ -133,7 +133,7 @@ func (eb errorBackend) GetRegistration(ctx context.Context, regID *sapb.RegistrationID, opts ...grpc.CallOption, ) (*corepb.Registration, error) { - return nil, errors.New("some error") + return nil, fmt.Errorf("some error") } func TestErrorPassthrough(t *testing.T) { diff --git a/wfe2/verify.go b/wfe2/verify.go index 70a655a1050..32ed71be046 100644 --- a/wfe2/verify.go +++ b/wfe2/verify.go @@ -417,7 +417,7 @@ func (wfe *WebFrontEndImpl) parseJWSRequest(request *http.Request) (*bJSONWebSig return nil, berrors.UnauthorizedError("request body too large") } wfe.stats.httpErrorCount.With(prometheus.Labels{"type": "UnableToReadReqBody"}).Inc() - return nil, errors.New("unable to read request body") + return nil, fmt.Errorf("unable to read request body") } jws, err := wfe.parseJWS(bodyBytes) diff --git a/wfe2/wfe.go b/wfe2/wfe.go index a51117e06ca..c5167193da6 100644 --- a/wfe2/wfe.go +++ b/wfe2/wfe.go @@ -82,7 +82,7 @@ const ( orderRetryAfter = 3 ) -var errIncompleteGRPCResponse = errors.New("incomplete gRPC response message") +var errIncompleteGRPCResponse = fmt.Errorf("incomplete gRPC response message") // WebFrontEndImpl provides all the logic for Boulder's web-facing interface, // i.e., ACME. Its members configure the paths for various ACME functions, @@ -195,19 +195,19 @@ func NewWebFrontEndImpl( unpauseURL string, ) (WebFrontEndImpl, error) { if len(issuerCertificates) == 0 { - return WebFrontEndImpl{}, errors.New("must provide at least one issuer certificate") + return WebFrontEndImpl{}, fmt.Errorf("must provide at least one issuer certificate") } if len(certificateChains) == 0 { - return WebFrontEndImpl{}, errors.New("must provide at least one certificate chain") + return WebFrontEndImpl{}, fmt.Errorf("must provide at least one certificate chain") } if gnc == nil { - return WebFrontEndImpl{}, errors.New("must provide a service for nonce issuance") + return WebFrontEndImpl{}, fmt.Errorf("must provide a service for nonce issuance") } if rnc == nil { - return WebFrontEndImpl{}, errors.New("must provide a service for nonce redemption") + return WebFrontEndImpl{}, fmt.Errorf("must provide a service for nonce redemption") } wfe := WebFrontEndImpl{ @@ -463,7 +463,7 @@ func (wfe *WebFrontEndImpl) Index(ctx context.Context, logEvent *web.RequestEven if request.Method != "GET" { response.Header().Set("Allow", "GET") - wfe.sendError(response, logEvent, probs.MethodNotAllowed(), errors.New("Bad method")) + wfe.sendError(response, logEvent, probs.MethodNotAllowed(), fmt.Errorf("Bad method")) return } @@ -2100,7 +2100,7 @@ func (wfe *WebFrontEndImpl) orderMatchesReplacement(ctx context.Context, acct *c if errors.Is(err, berrors.NotFound) { return berrors.NotFoundError("request included `replaces` field, but no current certificate with serial %q exists", serial) } - return errors.New("failed to retrieve existing certificate") + return fmt.Errorf("failed to retrieve existing certificate") } if oldCert.RegistrationID != acct.ID { diff --git a/wfe2/wfe_test.go b/wfe2/wfe_test.go index 4715d7f2262..e769f1d7ecd 100644 --- a/wfe2/wfe_test.go +++ b/wfe2/wfe_test.go @@ -13,7 +13,6 @@ import ( "encoding/base64" "encoding/json" "encoding/pem" - "errors" "fmt" "io" "math/big" @@ -1293,7 +1292,7 @@ type MockRAPerformValidationError struct { } func (ra *MockRAPerformValidationError) PerformValidation(context.Context, *rapb.PerformValidationRequest, ...grpc.CallOption) (*corepb.Authorization, error) { - return nil, errors.New("broken on purpose") + return nil, fmt.Errorf("broken on purpose") } // TestUpdateChallengeHandlerFinalizedAuthz tests that POSTing a challenge associated @@ -2571,7 +2570,7 @@ type mockSAWithError struct { } func (sa *mockSAWithError) GetCertificate(_ context.Context, req *sapb.Serial, _ ...grpc.CallOption) (*corepb.Certificate, error) { - return nil, errors.New("Oops") + return nil, fmt.Errorf("Oops") } func TestGetCertificateServerError(t *testing.T) { @@ -4086,7 +4085,7 @@ type mockRA struct { // NewOrder returns an error if the "" func (sa *mockRA) NewOrder(ctx context.Context, in *rapb.NewOrderRequest, opts ...grpc.CallOption) (*corepb.Order, error) { if in.CertificateProfileName != sa.expectProfileName { - return nil, errors.New("not expected profile name") + return nil, fmt.Errorf("not expected profile name") } now := time.Now().UTC() created := now.AddDate(-30, 0, 0) @@ -4164,7 +4163,7 @@ func TestNewOrderWithProfile(t *testing.T) { func makeARICertID(leaf *x509.Certificate) (string, error) { if leaf == nil { - return "", errors.New("leaf certificate is nil") + return "", fmt.Errorf("leaf certificate is nil") } // Marshal the Serial Number into DER. @@ -4176,7 +4175,7 @@ func makeARICertID(leaf *x509.Certificate) (string, error) { // Check if the DER encoded bytes are sufficient (at least 3 bytes: tag, // length, and value). if len(der) < 3 { - return "", errors.New("invalid DER encoding of serial number") + return "", fmt.Errorf("invalid DER encoding of serial number") } // Extract only the integer bytes from the DER encoded Serial Number