Fix nits found by staticcheck (#4726)

Part of #4700
This commit is contained in:
Jacob Hoffman-Andrews 2020-03-30 10:20:20 -07:00 committed by GitHub
parent 81bb4047d5
commit bef02e782a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 49 additions and 183 deletions

View File

@ -375,7 +375,7 @@ func GeneratePurgeURLs(der []byte, issuer *x509.Certificate) ([]string, error) {
ocspServer += "/"
}
// Generate GET url
urls = append(generateOCSPCacheKeys(req, ocspServer))
urls = generateOCSPCacheKeys(req, ocspServer)
}
return urls, nil
}

View File

@ -169,7 +169,6 @@ func mockDNSQuery(w dns.ResponseWriter, r *dns.Msg) {
if err != nil {
panic(err) // running tests, so panic is OK
}
return
}
func serveLoopResolver(stopChan chan bool) {

View File

@ -349,14 +349,11 @@ func NewCertificateAuthorityImpl(
// noteSignError is called after operations that may cause a CFSSL
// or PKCS11 signing error.
func (ca *CertificateAuthorityImpl) noteSignError(err error) {
if err != nil {
if _, ok := err.(*pkcs11.Error); ok {
ca.signErrorCounter.WithLabelValues("HSM").Inc()
} else if cfErr, ok := err.(*cferr.Error); ok {
ca.signErrorCounter.WithLabelValues(fmt.Sprintf("CFSSL %d", cfErr.ErrorCode)).Inc()
}
if _, ok := err.(*pkcs11.Error); ok {
ca.signErrorCounter.WithLabelValues("HSM").Inc()
} else if cfErr, ok := err.(*cferr.Error); ok {
ca.signErrorCounter.WithLabelValues(fmt.Sprintf("CFSSL %d", cfErr.ErrorCode)).Inc()
}
return
}
// Extract supported extensions from a CSR. The following extensions are

View File

@ -413,7 +413,6 @@ func issueCertificateSubTestIssuePrecertificate(t *testing.T, i *TestCertificate
if len(cert.DNSNames) == 1 {
if cert.DNSNames[0] != "not-example.com" {
t.Errorf("Improper list of domain names %v", cert.DNSNames)
} else {
}
t.Errorf("Improper list of domain names %v", cert.DNSNames)
}
@ -550,7 +549,7 @@ func TestOCSP(t *testing.T) {
// ocspResp2 is a second OCSP response for `cert` (issued by caCert), and
// should be signed by caCert.
ocspResp2, err := ca.GenerateOCSP(ctx, &caPB.GenerateOCSPRequest{
CertDER: append(cert.DER),
CertDER: append([]byte(nil), cert.DER...),
Status: &status,
})
test.AssertNotError(t, err, "Failed to sign second OCSP response")
@ -736,14 +735,10 @@ func issueCertificateSubTestAllowNoCN(t *testing.T, i *TestCertificateIssuance)
}
expected := []string{}
for _, name := range i.req.DNSNames {
expected = append(expected, name)
}
expected = append(expected, i.req.DNSNames...)
sort.Strings(expected)
actual := []string{}
for _, name := range cert.DNSNames {
actual = append(actual, name)
}
actual = append(actual, cert.DNSNames...)
sort.Strings(actual)
test.AssertDeepEquals(t, actual, expected)
}

View File

@ -103,6 +103,9 @@ func revokeBySerial(ctx context.Context, serial string, reasonCode revocation.Re
}
u, err := user.Current()
if err != nil {
return
}
err = rac.AdministrativelyRevokeCertificate(ctx, *cert, reasonCode, u.Username)
if err != nil {
return
@ -173,7 +176,7 @@ func (rc revocationCodes) Swap(i, j int) { rc[i], rc[j] = rc[j], rc[i] }
func main() {
usage := func() {
fmt.Fprintf(os.Stderr, usageString)
fmt.Fprint(os.Stderr, usageString)
os.Exit(1)
}
if len(os.Args) <= 2 {

View File

@ -134,7 +134,7 @@ func main() {
}
if c.CA.MaxNames == 0 {
cmd.Fail(fmt.Sprintf("Error in CA config: MaxNames must not be 0"))
cmd.Fail("Error in CA config: MaxNames must not be 0")
}
scope, logger := cmd.StatsAndLogging(c.Syslog, c.CA.DebugAddr)

View File

@ -55,9 +55,7 @@ func (m mockDB) Select(result interface{}, query string, args ...interface{}) ([
if idResults, ok := result.(*[]workUnit); !ok {
m.t.Fatalf("Select()'s result target pointer was %T not []int64", result)
} else {
for _, wu := range m.selectResult {
*idResults = append(*idResults, wu)
}
*idResults = append(*idResults, m.selectResult...)
}
return nil, m.errResult

View File

@ -208,7 +208,7 @@ func main() {
cmd.FailOnError(err, "Unable to create key policy")
if c.RA.MaxNames == 0 {
cmd.Fail(fmt.Sprintf("Error in RA config: MaxNames must not be 0"))
cmd.Fail("Error in RA config: MaxNames must not be 0")
}
rai := ra.NewRegistrationAuthorityImpl(

View File

@ -251,7 +251,6 @@ func (m *mailer) processCerts(allCerts []core.Certificate) {
}
}
}
return
}
func (m *mailer) findExpiringCertificates() error {
@ -517,7 +516,7 @@ func main() {
}
// Load subject template
subjTmpl, err := template.New("expiry-email-subject").Parse(c.Mailer.Subject)
cmd.FailOnError(err, fmt.Sprintf("Could not parse email subject template"))
cmd.FailOnError(err, "Could not parse email subject template")
fromAddress, err := netmail.ParseAddress(c.Mailer.From)
cmd.FailOnError(err, fmt.Sprintf("Could not parse from address: %s", c.Mailer.From))

View File

@ -94,7 +94,7 @@ func (m *mailer) printStatus(to string, cur, total int, start time.Time) {
func sortAddresses(input emailToRecipientMap) []string {
var addresses []string
for k, _ := range input {
for k := range input {
addresses = append(addresses, k)
}
sort.Strings(addresses)

View File

@ -145,6 +145,7 @@ func TestMailIntervals(t *testing.T) {
// Run the mailer. It should produce an error about the interval start
mc.Clear()
err := m.run()
test.AssertError(t, err, "expected error")
test.AssertEquals(t, len(mc.Messages), 0)
// Create a mailer with a negative sleep interval

View File

@ -277,7 +277,7 @@ func setup(configFile string) (blog.Logger, core.StorageAuthority, capb.OCSPGene
func main() {
if len(os.Args) <= 2 {
fmt.Fprintf(os.Stderr, usageString)
fmt.Fprint(os.Stderr, usageString)
os.Exit(1)
}

View File

@ -239,7 +239,7 @@ func newStatsRegistry(addr string, logger blog.Logger) prometheus.Registerer {
func Fail(msg string) {
logger := blog.Get()
logger.AuditErr(msg)
fmt.Fprintf(os.Stderr, msg)
fmt.Fprint(os.Stderr, msg)
os.Exit(1)
}

View File

@ -69,7 +69,7 @@ func NewToken() string {
return RandomString(32)
}
var tokenFormat = regexp.MustCompile("^[\\w-]{43}$")
var tokenFormat = regexp.MustCompile(`^[\w-]{43}$`)
// LooksLikeAToken checks whether a string represents a 32-octet value in
// the URL-safe base64 alphabet.
@ -167,10 +167,7 @@ func ValidSerial(serial string) bool {
return false
}
_, err := hex.DecodeString(serial)
if err != nil {
return false
}
return true
return err == nil
}
// GetBuildID identifies what build is running.

View File

@ -32,7 +32,6 @@ func TestNewToken(t *testing.T) {
test.Assert(t, !collider[token], "Token collision!")
collider[token] = true
}
return
}
func TestLooksLikeAToken(t *testing.T) {
@ -129,7 +128,7 @@ func TestValidSerial(t *testing.T) {
func TestRetryBackoff(t *testing.T) {
assertBetween := func(a, b, c float64) {
t.Helper()
if a < b || a > a {
if a < b || a > c {
t.Fatalf("%f is not between %f and %f", a, b, c)
}
}

View File

@ -19,10 +19,11 @@ func TestRollback(t *testing.T) {
// Since the tx.Rollback will fail we expect the result to be a wrapped error
test.AssertNotEquals(t, result, innerErr)
if rbErr, ok := result.(*RollbackError); !ok {
t.Fatal("Result was not a RollbackError")
if rbErr, ok := result.(*RollbackError); ok {
test.AssertEquals(t, rbErr.Err, innerErr)
test.AssertNotNil(t, rbErr.RollbackErr, "RollbackErr was nil")
} else {
t.Fatalf("Result was not a RollbackError: %#v", result)
}
// Create a new transaction and don't commit it this time. The rollback should

View File

@ -1,47 +0,0 @@
package grpc
import (
"google.golang.org/grpc/naming"
)
// staticResolver implements both the naming.Resolver and naming.Watcher
// interfaces. It always returns a single static list then blocks forever
type staticResolver struct {
addresses []*naming.Update
}
func newStaticResolver(addresses []string) *staticResolver {
sr := &staticResolver{}
for _, a := range addresses {
sr.addresses = append(sr.addresses, &naming.Update{
Op: naming.Add,
Addr: a,
})
}
return sr
}
// Resolve just returns the staticResolver it was called from as it satisfies
// both the naming.Resolver and naming.Watcher interfaces
func (sr *staticResolver) Resolve(target string) (naming.Watcher, error) {
return sr, nil
}
// Next is called in a loop by grpc.RoundRobin expecting updates to which addresses are
// appropriate. Since we just want to return a static list once return a list on the first
// call then block forever on the second instead of sitting in a tight loop
func (sr *staticResolver) Next() ([]*naming.Update, error) {
if sr.addresses != nil {
addrs := sr.addresses
sr.addresses = nil
return addrs, nil
}
// Since staticResolver.Next is called in a tight loop block forever
// after returning the initial set of addresses
forever := make(chan struct{})
<-forever
return nil, nil
}
// Close does nothing
func (sr *staticResolver) Close() {}

View File

@ -1,39 +0,0 @@
package grpc
import (
"testing"
"time"
"google.golang.org/grpc/naming"
"github.com/letsencrypt/boulder/test"
)
func TestStaticResolver(t *testing.T) {
names := []string{"test:443"}
sr := newStaticResolver(names)
watcher, err := sr.Resolve("")
test.AssertNotError(t, err, "staticResolver.Resolve failed")
// Make sure doing this doesn't break anything (since it does nothing)
watcher.Close()
updates, err := watcher.Next()
test.AssertNotError(t, err, "staticwatcher.Next failed")
test.AssertEquals(t, len(names), len(updates))
test.AssertEquals(t, updates[0].Addr, "test:443")
test.AssertEquals(t, updates[0].Op, naming.Add)
test.AssertEquals(t, updates[0].Metadata, nil)
returned := make(chan struct{}, 1)
go func() {
_, err = watcher.Next()
test.AssertNotError(t, err, "watcher.Next failed")
returned <- struct{}{}
}()
select {
case <-returned:
t.Fatal("staticWatcher.Next returned something after the first call")
case <-time.After(time.Millisecond * 500):
}
}

View File

@ -177,9 +177,7 @@ func (tc *serverTransportCredentials) validateClient(peerState tls.ConnectionSta
// Combine both the DNS and IP address subjectAlternativeNames into a single
// list for checking.
var receivedSANs []string
for _, dnsName := range leaf.DNSNames {
receivedSANs = append(receivedSANs, dnsName)
}
receivedSANs = append(receivedSANs, leaf.DNSNames...)
for _, ip := range leaf.IPAddresses {
receivedSANs = append(receivedSANs, ip.String())
}
@ -193,7 +191,7 @@ func (tc *serverTransportCredentials) validateClient(peerState tls.ConnectionSta
// If none of the DNS or IP SANs on the leaf certificate matched the
// acceptable list, the client isn't valid and we error
var acceptableSANs []string
for k, _ := range tc.acceptedSANs {
for k := range tc.acceptedSANs {
acceptableSANs = append(acceptableSANs, k)
}
return SANNotAcceptedErr{receivedSANs, acceptableSANs}

View File

@ -50,7 +50,7 @@ func TestErrorWrapping(t *testing.T) {
test.Assert(t, err != nil, fmt.Sprintf("nil error returned, expected: %s", err))
test.AssertDeepEquals(t, err, es.err)
test.AssertEquals(t, wrapError(nil, nil), nil)
test.AssertEquals(t, wrapError(context.Background(), nil), nil)
test.AssertEquals(t, unwrapError(nil, nil), nil)
}

View File

@ -67,7 +67,7 @@ func (si *serverInterceptor) intercept(ctx context.Context, req interface{}, inf
deadline = time.Now().Add(100 * time.Second)
}
deadline = deadline.Add(-returnOverhead)
remaining := deadline.Sub(time.Now())
remaining := time.Until(deadline)
if remaining < meaningfulWorkOverhead {
return nil, grpc.Errorf(codes.DeadlineExceeded, "not enough time left on clock: %s", remaining)
}

View File

@ -85,7 +85,7 @@ func TestFailFastFalse(t *testing.T) {
}
conn, err := grpc.Dial("localhost:19876", // random, probably unused port
grpc.WithInsecure(),
grpc.WithBalancer(grpc.RoundRobin(newStaticResolver([]string{"localhost:19000"}))),
grpc.WithBalancerName("round_robin"),
grpc.WithUnaryInterceptor(ci.intercept))
if err != nil {
t.Fatalf("did not connect: %v", err)

View File

@ -42,20 +42,6 @@ func pbToAuthzMeta(in *vapb.AuthzMeta) (core.Authorization, error) {
}, nil
}
func jwkToString(jwk *jose.JSONWebKey) (string, error) {
bytes, err := jwk.MarshalJSON()
return string(bytes), err
}
func stringToJWK(in string) (*jose.JSONWebKey, error) {
var jwk = new(jose.JSONWebKey)
err := jwk.UnmarshalJSON([]byte(in))
if err != nil {
return nil, err
}
return jwk, nil
}
func ProblemDetailsToPB(prob *probs.ProblemDetails) (*corepb.ProblemDetails, error) {
if prob == nil {
// nil problemDetails is valid

View File

@ -49,20 +49,6 @@ func TestAuthzMeta(t *testing.T) {
const JWK1JSON = `{"kty":"RSA","n":"vuc785P8lBj3fUxyZchF_uZw6WtbxcorqgTyq-qapF5lrO1U82Tp93rpXlmctj6fyFHBVVB5aXnUHJ7LZeVPod7Wnfl8p5OyhlHQHC8BnzdzCqCMKmWZNX5DtETDId0qzU7dPzh0LP0idt5buU7L9QNaabChw3nnaL47iu_1Di5Wp264p2TwACeedv2hfRDjDlJmaQXuS8Rtv9GnRWyC9JBu7XmGvGDziumnJH7Hyzh3VNu-kSPQD3vuAFgMZS6uUzOztCkT0fpOalZI6hqxtWLvXUMj-crXrn-Maavz8qRhpAyp5kcYk3jiHGgQIi7QSK2JIdRJ8APyX9HlmTN5AQ","e":"AQAB"}`
func TestJWK(t *testing.T) {
var jwk jose.JSONWebKey
err := json.Unmarshal([]byte(JWK1JSON), &jwk)
test.AssertNotError(t, err, "Failed to unmarshal test key")
str, err := jwkToString(&jwk)
test.AssertNotError(t, err, "jwkToString failed")
test.AssertEquals(t, str, JWK1JSON)
recon, err := stringToJWK(str)
test.AssertNotError(t, err, "stringToJWK failed")
test.AssertDeepEquals(t, recon.Key, jwk.Key)
}
func TestProblemDetails(t *testing.T) {
pb, err := ProblemDetailsToPB(nil)
test.AssertNotEquals(t, err, "problemDetailToPB failed")

View File

@ -106,7 +106,7 @@ func NewMemorySourceFromFile(responseFile string, logger blog.Logger) (Source, e
return nil, err
}
responsesB64 := regexp.MustCompile("\\s").Split(string(fileContents), -1)
responsesB64 := regexp.MustCompile(`\s`).Split(string(fileContents), -1)
responses := make(map[string][]byte, len(responsesB64))
for _, b64 := range responsesB64 {
// if the line/space is empty just skip

View File

@ -311,12 +311,12 @@ func (pub *Impl) singleLogSubmit(
}).Observe(took)
timestamp := time.Unix(int64(sct.Timestamp)/1000, 0)
if timestamp.Sub(time.Now()) > time.Minute {
if time.Until(timestamp) > time.Minute {
return nil, fmt.Errorf("SCT Timestamp was too far in the future (%s)", timestamp)
}
// For regular certificates, we could get an old SCT, but that shouldn't
// happen for precertificates.
if isPrecert && timestamp.Sub(time.Now()) < -10*time.Minute {
if isPrecert && time.Until(timestamp) < -10*time.Minute {
return nil, fmt.Errorf("SCT Timestamp was too far in the past (%s)", timestamp)
}

View File

@ -61,7 +61,7 @@ func UserAllowedReasonsMessage() string {
// and make the message unpredictable and cumbersome for unit testing.
// We use []ints instead of []Reason to use `sort.Ints` without fuss.
var allowed []int
for reason, _ := range UserAllowedReasons {
for reason := range UserAllowedReasons {
allowed = append(allowed, int(reason))
}
sort.Ints(allowed)

View File

@ -85,7 +85,7 @@ if [[ "$RUN" =~ "lints" ]] ; then
# words should be all lowercase).
run_and_expect_silence codespell \
--ignore-words=.codespell.ignore.txt \
--skip=.git,.gocache,go.sum,go.mod,vendor,bin,*.pyc,*.pem,*.der,*.resp,*.req,*.csr,.codespell.ignore.txt
--skip=.git,.gocache,go.sum,go.mod,vendor,bin,*.pyc,*.pem,*.der,*.resp,*.req,*.csr,.codespell.ignore.txt,.*.swp
fi
#

View File

@ -32,7 +32,6 @@ func main() {
return
}
w.Write(body)
return
})
http.HandleFunc("/debug/reset-purges", func(w http.ResponseWriter, r *http.Request) {
@ -40,7 +39,6 @@ func main() {
defer mu.Unlock()
v3Purges = [][]string{}
w.WriteHeader(http.StatusOK)
return
})
http.HandleFunc("/ccu/", func(w http.ResponseWriter, r *http.Request) {

View File

@ -43,8 +43,8 @@ func expectLine(buf *bufio.Reader, expected string) error {
return nil
}
var mailFromRegex = regexp.MustCompile("^MAIL FROM:<(.*)>\\s*BODY=8BITMIME\\s*$")
var rcptToRegex = regexp.MustCompile("^RCPT TO:<(.*)>\\s*$")
var mailFromRegex = regexp.MustCompile(`^MAIL FROM:<(.*)>\s*BODY=8BITMIME\s*$`)
var rcptToRegex = regexp.MustCompile(`^RCPT TO:<(.*)>\s*$`)
var smtpErr501 = []byte("501 syntax error in parameters or arguments \r\n")
var smtpOk250 = []byte("250 OK \r\n")
@ -84,6 +84,7 @@ func (srv *mailSrv) handleConn(conn net.Conn) {
}
reader := bufio.NewScanner(readBuf)
scan:
for reader.Scan() {
line := reader.Text()
cmdSplit := strings.SplitN(line, " ", 2)
@ -91,7 +92,7 @@ func (srv *mailSrv) handleConn(conn net.Conn) {
switch cmd {
case "QUIT":
conn.Write([]byte("221 Bye \r\n"))
break
break scan
case "RSET":
clearState()
conn.Write(smtpOk250)

View File

@ -2,10 +2,9 @@ package test
import "github.com/golang/mock/mockgen/model"
// This assignment exists solely for the purpose of convincing godep
// to vendor github.com/golang/mock/mockgen/model as gomock will fail
// to generate code if it doesn't exist in the users GOPATH but isn't
// actually imported by any boulder or gomock code. The variable name
// is chosen so that it is unlikely to clash with anything else in this
// package.
var _ignore = model.Package{}
// This assignment exists solely for the purpose of convincing
// go mod vendor to vendor github.com/golang/mock/mockgen/model as
// gomock will fail to generate code if it doesn't exist in the
// users GOPATH, but it isn't actually imported by any boulder or
// gomock code.
var _ = model.Package{}

View File

@ -109,7 +109,7 @@ func ReqDER(der []byte, expectStatus int) (*ocsp.Response, error) {
return nil, nil
} else {
return nil, fmt.Errorf("certificate expired %s ago: %s",
time.Now().Sub(cert.NotAfter), cert.NotAfter)
time.Since(cert.NotAfter), cert.NotAfter)
}
}

View File

@ -54,7 +54,6 @@ func dnsHandler(w dns.ResponseWriter, r *dns.Msg) {
})
w.WriteMsg(m)
return
}
func main() {

View File

@ -100,7 +100,7 @@ func (th *TopHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Method: r.Method,
UserAgent: r.Header.Get("User-Agent"),
Origin: r.Header.Get("Origin"),
Extra: make(map[string]interface{}, 0),
Extra: make(map[string]interface{}),
}
if features.Enabled(features.StripDefaultSchemePort) {

View File

@ -1447,7 +1447,6 @@ func (wfe *WebFrontEndImpl) Certificate(ctx context.Context, logEvent *web.Reque
if _, err = response.Write(cert.DER); err != nil {
wfe.log.Warningf("Could not write response: %s", err)
}
return
}
// Terms is used by the client to obtain the current Terms of Service /

View File

@ -1883,10 +1883,8 @@ func TestAuthorization(t *testing.T) {
func TestAuthorizationV2(t *testing.T) {
wfe, _ := setupWFE(t)
responseWriter := httptest.NewRecorder()
// Test retrieving a v2 style authorization
responseWriter = httptest.NewRecorder()
responseWriter := httptest.NewRecorder()
wfe.AuthorizationV2(ctx, newRequestEvent(), responseWriter, &http.Request{
URL: mustParseURL("1"),
Method: "GET",

View File

@ -1684,7 +1684,6 @@ func (wfe *WebFrontEndImpl) Certificate(ctx context.Context, logEvent *web.Reque
if _, err = response.Write(responsePEM); err != nil {
wfe.log.Warningf("Could not write response: %s", err)
}
return
}
// Issuer obtains the issuer certificate used by this instance of Boulder.