Skip to content

Commit

Permalink
Fix nits found by staticcheck (#4726)
Browse files Browse the repository at this point in the history
Part of #4700
  • Loading branch information
jsha committed Mar 30, 2020
1 parent 81bb404 commit bef02e7
Show file tree
Hide file tree
Showing 37 changed files with 49 additions and 183 deletions.
2 changes: 1 addition & 1 deletion akamai/cache-client.go
Expand Up @@ -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
}
1 change: 0 additions & 1 deletion bdns/dns_test.go
Expand Up @@ -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) {
Expand Down
11 changes: 4 additions & 7 deletions ca/ca.go
Expand Up @@ -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
Expand Down
11 changes: 3 additions & 8 deletions ca/ca_test.go
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
}
Expand Down
5 changes: 4 additions & 1 deletion cmd/admin-revoker/main.go
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion cmd/boulder-ca/main.go
Expand Up @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions cmd/boulder-janitor/job_test.go
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cmd/boulder-ra/main.go
Expand Up @@ -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(
Expand Down
3 changes: 1 addition & 2 deletions cmd/expiration-mailer/main.go
Expand Up @@ -251,7 +251,6 @@ func (m *mailer) processCerts(allCerts []core.Certificate) {
}
}
}
return
}

func (m *mailer) findExpiringCertificates() error {
Expand Down Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion cmd/notify-mailer/main.go
Expand Up @@ -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)
Expand Down
1 change: 1 addition & 0 deletions cmd/notify-mailer/main_test.go
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion cmd/orphan-finder/main.go
Expand Up @@ -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)
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/shell.go
Expand Up @@ -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)
}

Expand Down
7 changes: 2 additions & 5 deletions core/util.go
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
3 changes: 1 addition & 2 deletions core/util_test.go
Expand Up @@ -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) {
Expand Down Expand Up @@ -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)
}
}
Expand Down
5 changes: 3 additions & 2 deletions db/rollback_test.go
Expand Up @@ -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
Expand Down
47 changes: 0 additions & 47 deletions grpc/balancer.go

This file was deleted.

39 changes: 0 additions & 39 deletions grpc/balancer_test.go

This file was deleted.

6 changes: 2 additions & 4 deletions grpc/creds/creds.go
Expand Up @@ -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())
}
Expand All @@ -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}
Expand Down
2 changes: 1 addition & 1 deletion grpc/errors_test.go
Expand Up @@ -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)
}

Expand Down
2 changes: 1 addition & 1 deletion grpc/interceptors.go
Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion grpc/interceptors_test.go
Expand Up @@ -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)
Expand Down
14 changes: 0 additions & 14 deletions grpc/pb-marshalling.go
Expand Up @@ -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
Expand Down
14 changes: 0 additions & 14 deletions grpc/pb-marshalling_test.go
Expand Up @@ -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")
Expand Down

0 comments on commit bef02e7

Please sign in to comment.