Skip to content

Commit e77adb6

Browse files
sozercanaramase
andauthored
chore: update linters (#217)
* chore: update linters Signed-off-by: Sertac Ozercan <sozercan@gmail.com> * Apply suggestions from code review Co-authored-by: Anish Ramasekar <anish.ramasekar@gmail.com> Signed-off-by: Sertaç Özercan <852750+sozercan@users.noreply.github.com> * Update .golangci.yml Co-authored-by: Anish Ramasekar <anish.ramasekar@gmail.com> Signed-off-by: Sertaç Özercan <852750+sozercan@users.noreply.github.com> * fix formatting Signed-off-by: Sertac Ozercan <sozercan@gmail.com> --------- Signed-off-by: Sertac Ozercan <sozercan@gmail.com> Signed-off-by: Sertaç Özercan <852750+sozercan@users.noreply.github.com> Co-authored-by: Anish Ramasekar <anish.ramasekar@gmail.com>
1 parent e4f695b commit e77adb6

17 files changed

+76
-45
lines changed

.golangci.yml

+19
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,29 @@
11
run:
22
timeout: 5m
33

4+
linters-settings:
5+
gocritic:
6+
enabled-tags:
7+
- performance
8+
lll:
9+
line-length: 200
10+
misspell:
11+
locale: US
12+
staticcheck:
13+
go: "1.20"
14+
415
linters:
516
disable-all: true
617
enable:
18+
- errcheck
19+
- exportloopref
20+
- forcetypeassert
721
- goconst
22+
- gocritic
823
- gocyclo
24+
- godot
925
- gofmt
26+
- gofumpt
1027
- goimports
1128
- gosec
1229
- gosimple
@@ -17,4 +34,6 @@ linters:
1734
- prealloc
1835
- revive
1936
- staticcheck
37+
- typecheck
2038
- unused
39+
- whitespace

cmd/server/main.go

+10-2
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,10 @@ func main() {
6262
}
6363

6464
if *versionInfo {
65-
version.PrintVersion()
65+
if err := version.PrintVersion(); err != nil {
66+
klog.ErrorS(err, "failed to print version")
67+
os.Exit(1)
68+
}
6669
os.Exit(0)
6770
}
6871

@@ -117,7 +120,12 @@ func main() {
117120
pb.RegisterKeyManagementServiceServer(s, kmsServer)
118121

119122
klog.InfoS("Listening for connections", "addr", listener.Addr().String())
120-
go s.Serve(listener)
123+
go func() {
124+
if err := s.Serve(listener); err != nil {
125+
klog.ErrorS(err, "failed to serve")
126+
os.Exit(1)
127+
}
128+
}()
121129

122130
healthz := &plugin.HealthZ{
123131
KMSServer: kmsServer,

pkg/auth/auth.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import (
2323
"k8s.io/klog/v2"
2424
)
2525

26-
// GetKeyvaultToken() returns token for Keyvault endpoint
26+
// GetKeyvaultToken() returns token for Keyvault endpoint.
2727
func GetKeyvaultToken(config *config.AzureConfig, env *azure.Environment, resource string, proxyMode bool) (authorizer autorest.Authorizer, err error) {
2828
servicePrincipalToken, err := GetServicePrincipalToken(config, env.ActiveDirectoryEndpoint, resource, proxyMode)
2929
if err != nil {
@@ -33,7 +33,7 @@ func GetKeyvaultToken(config *config.AzureConfig, env *azure.Environment, resour
3333
return authorizer, nil
3434
}
3535

36-
// GetServicePrincipalToken creates a new service principal token based on the configuration
36+
// GetServicePrincipalToken creates a new service principal token based on the configuration.
3737
func GetServicePrincipalToken(config *config.AzureConfig, aadEndpoint, resource string, proxyMode bool) (adal.OAuthTokenProvider, error) {
3838
oauthConfig, err := adal.NewOAuthConfig(aadEndpoint, config.TenantID)
3939
if err != nil {
@@ -106,7 +106,7 @@ func GetServicePrincipalToken(config *config.AzureConfig, aadEndpoint, resource
106106
return nil, fmt.Errorf("no credentials provided for accessing keyvault")
107107
}
108108

109-
// ParseAzureEnvironment returns azure environment by name
109+
// ParseAzureEnvironment returns azure environment by name.
110110
func ParseAzureEnvironment(cloudName string) (*azure.Environment, error) {
111111
var env azure.Environment
112112
var err error
@@ -119,7 +119,7 @@ func ParseAzureEnvironment(cloudName string) (*azure.Environment, error) {
119119
}
120120

121121
// decodePkcs12 decodes a PKCS#12 client certificate by extracting the public certificate and
122-
// the private RSA key
122+
// the private RSA key.
123123
func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) {
124124
privateKey, certificate, err := pkcs12.Decode(pkcs, password)
125125
if err != nil {
@@ -133,13 +133,13 @@ func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.Private
133133
return certificate, rsaPrivateKey, nil
134134
}
135135

136-
// redactClientCredentials applies regex to a sensitive string and return the redacted value
136+
// redactClientCredentials applies regex to a sensitive string and return the redacted value.
137137
func redactClientCredentials(sensitiveString string) string {
138-
r, _ := regexp.Compile(`^(\S{4})(\S|\s)*(\S{4})$`)
138+
r := regexp.MustCompile(`^(\S{4})(\S|\s)*(\S{4})$`)
139139
return r.ReplaceAllString(sensitiveString, "$1##### REDACTED #####$3")
140140
}
141141

142-
// addTargetTypeHeader adds the target header if proxy mode is enabled
142+
// addTargetTypeHeader adds the target header if proxy mode is enabled.
143143
func addTargetTypeHeader(spt *adal.ServicePrincipalToken) *adal.ServicePrincipalToken {
144144
spt.SetSender(autorest.CreateSender(
145145
(func() autorest.SendDecorator {

pkg/config/azure_config.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"k8s.io/klog/v2"
99
)
1010

11-
// AzureConfig is representing /etc/kubernetes/azure.json
11+
// AzureConfig is representing /etc/kubernetes/azure.json.
1212
type AzureConfig struct {
1313
Cloud string `json:"cloud" yaml:"cloud"`
1414
TenantID string `json:"tenantId" yaml:"tenantId"`
@@ -20,7 +20,7 @@ type AzureConfig struct {
2020
AADClientCertPassword string `json:"aadClientCertPassword" yaml:"aadClientCertPassword"`
2121
}
2222

23-
// GetAzureConfig returns configs in the azure.json cloud provider file
23+
// GetAzureConfig returns configs in the azure.json cloud provider file.
2424
func GetAzureConfig(configFile string) (config *AzureConfig, err error) {
2525
cfg := AzureConfig{}
2626

pkg/metrics/exporter.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const (
1111
prometheusExporter = "prometheus"
1212
)
1313

14-
// InitMetricsExporter initializes new exporter
14+
// InitMetricsExporter initializes new exporter.
1515
func InitMetricsExporter(metricsBackend, metricsAddress string) error {
1616
exporter := strings.ToLower(metricsBackend)
1717
klog.InfoS("metrics backend", "exporter", exporter)

pkg/metrics/prometheus_exporter.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ func initPrometheusExporter(metricsAddress string) error {
1818
exporter, err := prometheus.InstallNewPipeline(prometheus.Config{
1919
DefaultHistogramBoundaries: []float64{
2020
0.1, 0.2, 0.3, 0.4, 0.5, 1, 1.5, 2, 2.5, 3.0, 5.0, 10.0, 15.0, 30.0,
21-
}},
21+
},
22+
},
2223
)
2324
if err != nil {
2425
return fmt.Errorf("failed to register prometheus exporter: %v", err)

pkg/metrics/stats_reporter.go

+8-10
Original file line numberDiff line numberDiff line change
@@ -14,32 +14,30 @@ const (
1414
statusTypeKey = "status"
1515
operationTypeKey = "operation"
1616
kmsRequestMetricName = "kms_request"
17-
// ErrorStatusTypeValue sets status tag to "error"
17+
// ErrorStatusTypeValue sets status tag to "error".
1818
ErrorStatusTypeValue = "error"
19-
// SuccessStatusTypeValue sets status tag to "success"
19+
// SuccessStatusTypeValue sets status tag to "success".
2020
SuccessStatusTypeValue = "success"
21-
// EncryptOperationTypeValue sets operation tag to "encrypt"
21+
// EncryptOperationTypeValue sets operation tag to "encrypt".
2222
EncryptOperationTypeValue = "encrypt"
23-
// DecryptOperationTypeValue sets operation tag to "decrypt"
23+
// DecryptOperationTypeValue sets operation tag to "decrypt".
2424
DecryptOperationTypeValue = "decrypt"
25-
// GrpcOperationTypeValue sets operation tag to "grpc"
25+
// GrpcOperationTypeValue sets operation tag to "grpc".
2626
GrpcOperationTypeValue = "grpc"
2727
)
2828

29-
var (
30-
kmsRequest metric.Float64ValueRecorder
31-
)
29+
var kmsRequest metric.Float64ValueRecorder
3230

3331
type reporter struct {
3432
meter metric.Meter
3533
}
3634

37-
// StatsReporter reports metrics
35+
// StatsReporter reports metrics.
3836
type StatsReporter interface {
3937
ReportRequest(ctx context.Context, operationType, status string, duration float64, errors ...string)
4038
}
4139

42-
// NewStatsReporter instantiates otel reporter
40+
// NewStatsReporter instantiates otel reporter.
4341
func NewStatsReporter() StatsReporter {
4442
meter := global.Meter(instrumentationName)
4543

pkg/plugin/healthz.go

+5-2
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ type HealthZ struct {
3333
RPCTimeout time.Duration
3434
}
3535

36-
// Serve creates the http handler for serving health requests
36+
// Serve creates the http handler for serving health requests.
3737
func (h *HealthZ) Serve() {
3838
serveMux := http.NewServeMux()
3939
serveMux.HandleFunc(h.HealthCheckURL.EscapedPath(), h.ServeHTTP)
@@ -85,7 +85,10 @@ func (h *HealthZ) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
8585
return
8686
}
8787
w.WriteHeader(http.StatusOK)
88-
w.Write([]byte("ok"))
88+
if _, err = w.Write([]byte("ok")); err != nil {
89+
http.Error(w, err.Error(), http.StatusInternalServerError)
90+
return
91+
}
8992
klog.V(5).Info("Completed health check")
9093
}
9194

pkg/plugin/healthz_test.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,9 @@ func setupFakeKMSServer(socketPath string) (*KeyManagementServiceServer, *mockke
144144
}
145145
s := grpc.NewServer()
146146
pb.RegisterKeyManagementServiceServer(s, fakeKMSServer)
147-
go s.Serve(listener)
147+
go func() {
148+
_ = s.Serve(listener)
149+
}()
148150

149151
return fakeKMSServer, kvClient, nil
150152
}

pkg/plugin/keyvault.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import (
2424
"k8s.io/klog/v2"
2525
)
2626

27-
// Client interface for interacting with Keyvault
27+
// Client interface for interacting with Keyvault.
2828
type Client interface {
2929
Encrypt(ctx context.Context, cipher []byte) ([]byte, error)
3030
Decrypt(ctx context.Context, plain []byte) ([]byte, error)
@@ -40,14 +40,15 @@ type keyVaultClient struct {
4040
azureEnvironment *azure.Environment
4141
}
4242

43-
// NewKeyVaultClient returns a new key vault client to use for kms operations
43+
// NewKeyVaultClient returns a new key vault client to use for kms operations.
4444
func newKeyVaultClient(
4545
config *config.AzureConfig,
4646
vaultName, keyName, keyVersion string,
4747
proxyMode bool,
4848
proxyAddress string,
4949
proxyPort int,
50-
managedHSM bool) (*keyVaultClient, error) {
50+
managedHSM bool,
51+
) (*keyVaultClient, error) {
5152
// Sanitize vaultName, keyName, keyVersion. (https://github.com/Azure/kubernetes-kms/issues/85)
5253
vaultName = utils.SanitizeString(vaultName)
5354
keyName = utils.SanitizeString(keyName)

pkg/plugin/server.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ func New(pc *Config) (*KeyManagementServiceServer, error) {
5050
}, nil
5151
}
5252

53-
// Version of kms
53+
// Version of kms.
5454
func (s *KeyManagementServiceServer) Version(_ context.Context, _ *k8spb.VersionRequest) (*k8spb.VersionResponse, error) {
5555
return &k8spb.VersionResponse{
5656
Version: version.APIVersion,
@@ -59,7 +59,7 @@ func (s *KeyManagementServiceServer) Version(_ context.Context, _ *k8spb.Version
5959
}, nil
6060
}
6161

62-
// Encrypt message
62+
// Encrypt message.
6363
func (s *KeyManagementServiceServer) Encrypt(ctx context.Context, request *k8spb.EncryptRequest) (*k8spb.EncryptResponse, error) {
6464
start := time.Now()
6565

@@ -84,7 +84,7 @@ func (s *KeyManagementServiceServer) Encrypt(ctx context.Context, request *k8spb
8484
return &k8spb.EncryptResponse{Cipher: cipher}, nil
8585
}
8686

87-
// Decrypt message
87+
// Decrypt message.
8888
func (s *KeyManagementServiceServer) Decrypt(ctx context.Context, request *k8spb.DecryptRequest) (*k8spb.DecryptResponse, error) {
8989
start := time.Now()
9090

pkg/plugin/server_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
package plugin
77

88
import (
9+
"bytes"
910
"context"
1011
"fmt"
1112
"testing"
@@ -54,7 +55,7 @@ func TestEncrypt(t *testing.T) {
5455
if err != test.err {
5556
t.Fatalf("expected err: %v, got: %v", test.err, err)
5657
}
57-
if string(out.GetCipher()) != string(test.output) {
58+
if !bytes.Equal(out.GetCipher(), test.output) {
5859
t.Fatalf("expected out: %v, got: %v", test.output, out)
5960
}
6061
})
@@ -98,7 +99,7 @@ func TestDecrypt(t *testing.T) {
9899
if err != test.err {
99100
t.Fatalf("expected err: %v, got: %v", test.err, err)
100101
}
101-
if string(out.GetPlain()) != string(test.output) {
102+
if !bytes.Equal(out.GetPlain(), test.output) {
102103
t.Fatalf("expected out: %v, got: %v", test.output, out)
103104
}
104105
})

pkg/utils/grpc.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
"k8s.io/klog/v2"
1313
)
1414

15-
// ParseEndpoint returns unix socket's protocol and address
15+
// ParseEndpoint returns unix socket's protocol and address.
1616
func ParseEndpoint(ep string) (string, string, error) {
1717
if strings.HasPrefix(strings.ToLower(ep), "unix://") {
1818
s := strings.SplitN(ep, "://", 2)

pkg/utils/sanitize.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package utils
22

33
import "strings"
44

5-
// SanitizeString returns a string that does not have white spaces and double quotes
5+
// SanitizeString returns a string that does not have white spaces and double quotes.
66
func SanitizeString(s string) string {
77
return strings.TrimSpace(strings.Trim(strings.TrimSpace(s), "\""))
88
}

pkg/version/version.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,17 @@ import (
77
)
88

99
var (
10-
// BuildDate is the date when the binary was built
10+
// BuildDate is the date when the binary was built.
1111
BuildDate string
12-
// GitCommit is the commit hash when the binary was built
12+
// GitCommit is the commit hash when the binary was built.
1313
GitCommit string
14-
// BuildVersion is the version of the KMS binary
14+
// BuildVersion is the version of the KMS binary.
1515
BuildVersion string
1616
APIVersion = "v1beta1"
1717
Runtime = "Microsoft AzureKMS"
1818
)
1919

20-
// PrintVersion prints the current KMS plugin version
20+
// PrintVersion prints the current KMS plugin version.
2121
func PrintVersion() (err error) {
2222
pv := struct {
2323
BuildVersion string

pkg/version/version_test.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func TestPrintVersion(t *testing.T) {
2525
// copy the output in a separate goroutine so printing can't block indefinitely
2626
go func() {
2727
var buf bytes.Buffer
28-
io.Copy(&buf, r)
28+
_, _ = io.Copy(&buf, r)
2929
outC <- strings.TrimSpace(buf.String())
3030
}()
3131

@@ -52,6 +52,5 @@ func TestGetUserAgent(t *testing.T) {
5252
expectedUserAgent := fmt.Sprintf("k8s-kms-keyvault/version (%s/%s) hash/Now", runtime.GOOS, runtime.GOARCH)
5353
if !strings.EqualFold(userAgent, expectedUserAgent) {
5454
t.Fatalf("string doesn't match, expected %s, got %s", expectedUserAgent, userAgent)
55-
5655
}
5756
}

tests/client/client_test.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package test
22

33
import (
4+
"bytes"
45
"fmt"
56
"net"
67
"testing"
@@ -53,7 +54,6 @@ func TestEncryptDecrypt(t *testing.T) {
5354

5455
for _, tc := range cases {
5556
t.Run(tc.name, func(t *testing.T) {
56-
5757
encryptRequest := k8spb.EncryptRequest{Version: version, Plain: tc.want}
5858
encryptResponse, err := client.Encrypt(context.Background(), &encryptRequest)
5959
if err != nil {
@@ -62,7 +62,7 @@ func TestEncryptDecrypt(t *testing.T) {
6262

6363
decryptRequest := k8spb.DecryptRequest{Version: version, Cipher: encryptResponse.Cipher}
6464
decryptResponse, err := client.Decrypt(context.Background(), &decryptRequest)
65-
if string(decryptResponse.Plain) != string(tc.want) {
65+
if !bytes.Equal(decryptResponse.Plain, tc.want) {
6666
t.Fatalf("Expected secret, but got %s - %v", string(decryptResponse.Plain), err)
6767
}
6868
})
@@ -85,7 +85,6 @@ func TestVersion(t *testing.T) {
8585

8686
for _, tc := range cases {
8787
t.Run(tc.name, func(t *testing.T) {
88-
8988
request := &k8spb.VersionRequest{Version: tc.want}
9089
response, err := client.Version(context.Background(), request)
9190
if err != nil {

0 commit comments

Comments
 (0)