Skip to content

Commit f9e6716

Browse files
author
Michael Wilson
authored
Update golangci-lint version, linting fixes. (#511)
1 parent 8e92368 commit f9e6716

38 files changed

+316
-225
lines changed

.github/workflows/lint.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ jobs:
1515
- name: golangci-lint
1616
uses: golangci/golangci-lint-action@v2
1717
with:
18-
version: v1.46.2
18+
version: v1.52.2

.golangci.yml

+14-20
Original file line numberDiff line numberDiff line change
@@ -7,41 +7,35 @@
77

88
linters:
99
enable:
10-
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
11-
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports [fast: true, auto-fix: true]
12-
- gosec # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: true, auto-fix: false]
13-
- misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
14-
- deadcode # Finds unused code [fast: true, auto-fix: false]
15-
- revive # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes [fast: true, auto-fix: false]
16-
- unconvert # Remove unnecessary type conversions [fast: true, auto-fix: false]
17-
18-
disable:
19-
# TODO(ross): fix errors reported by these checkers and enable them
2010
- bodyclose # checks whether HTTP response body is closed successfully [fast: false, auto-fix: false]
2111
- depguard # Go linter that checks if package imports are in a list of acceptable packages [fast: true, auto-fix: false]
22-
- dupl # Tool for code clone detection [fast: true, auto-fix: false]
2312
- errcheck # Inspects source code for security problems [fast: true, auto-fix: false]
24-
- gochecknoglobals # Checks that no globals are present in Go code [fast: true, auto-fix: false]
25-
- gochecknoinits # Checks that no init functions are present in Go code [fast: true, auto-fix: false]
26-
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
2713
- gocritic # The most opinionated Go source code linter [fast: true, auto-fix: false]
2814
- gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false]
15+
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
16+
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports [fast: true, auto-fix: true]
17+
- gosec # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: true, auto-fix: false]
2918
- gosimple # Linter for Go source code that specializes in simplifying a code [fast: false, auto-fix: false]
3019
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: false, auto-fix: false]
3120
- ineffassign # Detects when assignments to existing variables are not used [fast: true, auto-fix: false]
32-
- interfacer # Linter that suggests narrower interface types [fast: false, auto-fix: false]
33-
- lll # Reports long lines [fast: true, auto-fix: false]
34-
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted [fast: true, auto-fix: false]
21+
- misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
3522
- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
3623
- prealloc # Finds slice declarations that could potentially be preallocated [fast: true, auto-fix: false]
37-
- scopelint # Scopelint checks for unpinned variables in go programs [fast: true, auto-fix: false]
24+
- revive # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes [fast: true, auto-fix: false]
3825
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: false, auto-fix: false]
39-
- structcheck # Finds unused struct fields [fast: true, auto-fix: false]
4026
- stylecheck # Stylecheck is a replacement for golint [fast: false, auto-fix: false]
4127
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code [fast: true, auto-fix: false]
28+
- unconvert # Remove unnecessary type conversions [fast: true, auto-fix: false]
4229
- unparam # Reports unused function parameters [fast: false, auto-fix: false]
4330
- unused # Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]
44-
- varcheck # Finds unused global variables and constants [fast: true, auto-fix: false]
31+
32+
disable:
33+
# TODO(ross): fix errors reported by these checkers and enable them
34+
- dupl # Tool for code clone detection [fast: true, auto-fix: false]
35+
- gochecknoglobals # Checks that no globals are present in Go code [fast: true, auto-fix: false]
36+
- gochecknoinits # Checks that no init functions are present in Go code [fast: true, auto-fix: false]
37+
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
38+
- lll # Reports long lines [fast: true, auto-fix: false]
4539
linters-settings:
4640
goimports:
4741
local-prefixes: github.com/crewjam/saml

example/idp/idp.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Package main contains an example identity provider implementation.
12
package main
23

34
import (

example/service.go

+15-7
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ type Link struct {
3232
}
3333

3434
// CreateLink handles requests to create links
35-
func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) {
35+
func CreateLink(_ web.C, w http.ResponseWriter, r *http.Request) {
3636
account := r.Header.Get("X-Remote-User")
3737
l := Link{
3838
ShortLink: uniuri.New(),
@@ -42,22 +42,20 @@ func CreateLink(c web.C, w http.ResponseWriter, r *http.Request) {
4242
links[l.ShortLink] = l
4343

4444
fmt.Fprintf(w, "%s\n", l.ShortLink)
45-
return
4645
}
4746

4847
// ServeLink handles requests to redirect to a link
49-
func ServeLink(c web.C, w http.ResponseWriter, r *http.Request) {
48+
func ServeLink(_ web.C, w http.ResponseWriter, r *http.Request) {
5049
l, ok := links[strings.TrimPrefix(r.URL.Path, "/")]
5150
if !ok {
5251
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
5352
return
5453
}
5554
http.Redirect(w, r, l.Target, http.StatusFound)
56-
return
5755
}
5856

5957
// ListLinks returns a list of the current user's links
60-
func ListLinks(c web.C, w http.ResponseWriter, r *http.Request) {
58+
func ListLinks(_ web.C, w http.ResponseWriter, r *http.Request) {
6159
account := r.Header.Get("X-Remote-User")
6260
for _, l := range links {
6361
if l.Owner == account {
@@ -145,14 +143,24 @@ func main() {
145143

146144
spURL := *idpMetadataURL
147145
spURL.Path = "/services/sp"
148-
http.Post(spURL.String(), "text/xml", bytes.NewReader(spMetadataBuf))
146+
resp, err := http.Post(spURL.String(), "text/xml", bytes.NewReader(spMetadataBuf))
147+
148+
if err != nil {
149+
panic(err)
150+
}
151+
152+
if err := resp.Body.Close(); err != nil {
153+
panic(err)
154+
}
149155

150156
goji.Handle("/saml/*", samlSP)
151157

152158
authMux := web.New()
153159
authMux.Use(samlSP.RequireAccount)
154160
authMux.Get("/whoami", func(w http.ResponseWriter, r *http.Request) {
155-
pretty.Fprintf(w, "%# v", r)
161+
if _, err := pretty.Fprintf(w, "%# v", r); err != nil {
162+
panic(err)
163+
}
156164
})
157165
authMux.Post("/", CreateLink)
158166
authMux.Get("/", ListLinks)

example/trivial/trivial.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Package main contains an example service provider implementation.
12
package main
23

34
import (
@@ -9,6 +10,7 @@ import (
910
"log"
1011
"net/http"
1112
"net/url"
13+
"time"
1214

1315
"github.com/crewjam/saml/samlsp"
1416
)
@@ -69,8 +71,14 @@ func main() {
6971
})
7072
app := http.HandlerFunc(hello)
7173
slo := http.HandlerFunc(logout)
74+
7275
http.Handle("/hello", samlMiddleware.RequireAccount(app))
7376
http.Handle("/saml/", samlMiddleware)
7477
http.Handle("/logout", slo)
75-
log.Fatal(http.ListenAndServe(":8000", nil))
78+
79+
server := &http.Server{
80+
Addr: ":8080",
81+
ReadHeaderTimeout: 5 * time.Second,
82+
}
83+
log.Fatal(server.ListenAndServe())
7684
}

identity_provider.go

+6-5
Original file line numberDiff line numberDiff line change
@@ -196,10 +196,13 @@ func (idp *IdentityProvider) Handler() http.Handler {
196196
}
197197

198198
// ServeMetadata is an http.HandlerFunc that serves the IDP metadata
199-
func (idp *IdentityProvider) ServeMetadata(w http.ResponseWriter, r *http.Request) {
199+
func (idp *IdentityProvider) ServeMetadata(w http.ResponseWriter, _ *http.Request) {
200200
buf, _ := xml.MarshalIndent(idp.Metadata(), "", " ")
201201
w.Header().Set("Content-Type", "application/samlmetadata+xml")
202-
w.Write(buf)
202+
if _, err := w.Write(buf); err != nil {
203+
idp.Logger.Printf("ERROR: %s", err)
204+
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
205+
}
203206
}
204207

205208
// ServeSSO handles SAML auth requests.
@@ -716,9 +719,7 @@ func (DefaultAssertionMaker) MakeAssertion(req *IdpAuthnRequest, session *Sessio
716719
})
717720
}
718721

719-
for _, ca := range session.CustomAttributes {
720-
attributes = append(attributes, ca)
721-
}
722+
attributes = append(attributes, session.CustomAttributes...)
722723

723724
if len(session.Groups) != 0 {
724725
groupMemberAttributeValues := []AttributeValue{}

identity_provider_go117_test.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,10 @@ func TestIDPHTTPCanHandleSSORequest(t *testing.T) {
4343
d := bytes.Replace(c, []byte("<AuthnRequest"), []byte("<AuthnRequest ::foo=\"bar\">]]"), 1)
4444
f := bytes.Buffer{}
4545
e, _ := flate.NewWriter(&f, flate.DefaultCompression)
46-
e.Write(d)
47-
e.Close()
46+
_, err := e.Write(d)
47+
assert.Check(t, err)
48+
err = e.Close()
49+
assert.Check(t, err)
4850
g := base64.StdEncoding.EncodeToString(f.Bytes())
4951
invalidRequest := url.QueryEscape(g)
5052

identity_provider_test.go

+8-8
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,8 @@ func TestIDPHTTPCanHandleMetadataRequest(t *testing.T) {
207207
test.IDP.Handler().ServeHTTP(w, r)
208208
assert.Check(t, is.Equal(http.StatusOK, w.Code))
209209
assert.Check(t, is.Equal("application/samlmetadata+xml", w.Header().Get("Content-type")))
210-
assert.Check(t, strings.HasPrefix(string(w.Body.Bytes()), "<EntityDescriptor"),
211-
string(w.Body.Bytes()))
210+
assert.Check(t, strings.HasPrefix(w.Body.String(), "<EntityDescriptor"),
211+
w.Body.String())
212212
}
213213

214214
func TestIDPCanHandleRequestWithNewSession(t *testing.T) {
@@ -760,7 +760,7 @@ func TestIDPIDPInitiatedNewSession(t *testing.T) {
760760
r, _ := http.NewRequest("GET", "https://idp.example.com/services/sp/whoami", nil)
761761
test.IDP.ServeIDPInitiated(w, r, test.SP.MetadataURL.String(), "ThisIsTheRelayState")
762762
assert.Check(t, is.Equal(200, w.Code))
763-
assert.Check(t, is.Equal("RelayState: ThisIsTheRelayState", string(w.Body.Bytes())))
763+
assert.Check(t, is.Equal("RelayState: ThisIsTheRelayState", w.Body.String()))
764764
}
765765

766766
func TestIDPIDPInitiatedExistingSession(t *testing.T) {
@@ -1026,18 +1026,18 @@ func TestIDPRejectDecompressionBomb(t *testing.T) {
10261026
},
10271027
}
10281028

1029-
//w := httptest.NewRecorder()
1030-
10311029
data := bytes.Repeat([]byte("a"), 768*1024*1024)
10321030
var compressed bytes.Buffer
10331031
w, _ := flate.NewWriter(&compressed, flate.BestCompression)
1034-
w.Write(data)
1035-
w.Close()
1032+
_, err := w.Write(data)
1033+
assert.Check(t, err)
1034+
err = w.Close()
1035+
assert.Check(t, err)
10361036
encoded := base64.StdEncoding.EncodeToString(compressed.Bytes())
10371037

10381038
r, _ := http.NewRequest("GET", "/dontcare?"+url.Values{
10391039
"SAMLRequest": {encoded},
10401040
}.Encode(), nil)
1041-
_, err := NewIdpAuthnRequest(&test.IDP, r)
1041+
_, err = NewIdpAuthnRequest(&test.IDP, r)
10421042
assert.Error(t, err, "cannot decompress request: flate: uncompress limit exceeded (10485760 bytes)")
10431043
}

logger/logger.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Package logger provides a logging interface.
12
package logger
23

34
import (

metadata.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ type EntityDescriptor struct {
6565
}
6666

6767
// MarshalXML implements xml.Marshaler
68-
func (m EntityDescriptor) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
68+
func (m EntityDescriptor) MarshalXML(e *xml.Encoder, _ xml.StartElement) error {
6969
type Alias EntityDescriptor
7070
aux := &struct {
7171
ValidUntil RelaxedTime `xml:"validUntil,attr,omitempty"`

samlidp/samlidp.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,9 +47,9 @@ type Server struct {
4747
// New returns a new Server
4848
func New(opts Options) (*Server, error) {
4949
metadataURL := opts.URL
50-
metadataURL.Path = metadataURL.Path + "/metadata"
50+
metadataURL.Path += "/metadata"
5151
ssoURL := opts.URL
52-
ssoURL.Path = ssoURL.Path + "/sso"
52+
ssoURL.Path += "/sso"
5353
logr := opts.Logger
5454
if logr == nil {
5555
logr = logger.DefaultLogger

samlidp/samlidp_test.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -124,8 +124,8 @@ func TestHTTPCanHandleMetadataRequest(t *testing.T) {
124124
test.Server.ServeHTTP(w, r)
125125
assert.Check(t, is.Equal(http.StatusOK, w.Code))
126126
assert.Check(t,
127-
strings.HasPrefix(string(w.Body.Bytes()), "<EntityDescriptor"),
128-
string(w.Body.Bytes()))
127+
strings.HasPrefix(w.Body.String(), "<EntityDescriptor"),
128+
w.Body.String())
129129
golden.Assert(t, w.Body.String(), "http_metadata_response.html")
130130
}
131131

@@ -139,7 +139,7 @@ func TestHTTPCanSSORequest(t *testing.T) {
139139
test.Server.ServeHTTP(w, r)
140140
assert.Check(t, is.Equal(http.StatusOK, w.Code))
141141
assert.Check(t,
142-
strings.HasPrefix(string(w.Body.Bytes()), "<html><p></p><form method=\"post\" action=\"https://idp.example.com/sso\">"),
143-
string(w.Body.Bytes()))
142+
strings.HasPrefix(w.Body.String(), "<html><p></p><form method=\"post\" action=\"https://idp.example.com/sso\">"),
143+
w.Body.String())
144144
golden.Assert(t, w.Body.String(), "http_sso_response.html")
145145
}

samlidp/service.go

+14-6
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ type Service struct {
2525
// service provider ID, which is typically the service provider's
2626
// metadata URL. If an appropriate service provider cannot be found then
2727
// the returned error must be os.ErrNotExist.
28-
func (s *Server) GetServiceProvider(r *http.Request, serviceProviderID string) (*saml.EntityDescriptor, error) {
28+
func (s *Server) GetServiceProvider(_ *http.Request, serviceProviderID string) (*saml.EntityDescriptor, error) {
2929
s.idpConfigMu.RLock()
3030
defer s.idpConfigMu.RUnlock()
3131
rv, ok := s.serviceProviders[serviceProviderID]
@@ -37,30 +37,38 @@ func (s *Server) GetServiceProvider(r *http.Request, serviceProviderID string) (
3737

3838
// HandleListServices handles the `GET /services/` request and responds with a JSON formatted list
3939
// of service names.
40-
func (s *Server) HandleListServices(c web.C, w http.ResponseWriter, r *http.Request) {
40+
func (s *Server) HandleListServices(_ web.C, w http.ResponseWriter, _ *http.Request) {
4141
services, err := s.Store.List("/services/")
4242
if err != nil {
4343
s.logger.Printf("ERROR: %s", err)
4444
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
4545
return
4646
}
4747

48-
json.NewEncoder(w).Encode(struct {
48+
err = json.NewEncoder(w).Encode(struct {
4949
Services []string `json:"services"`
5050
}{Services: services})
51+
if err != nil {
52+
s.logger.Printf("ERROR: %s", err)
53+
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
54+
}
5155
}
5256

5357
// HandleGetService handles the `GET /services/:id` request and responds with the service
5458
// metadata in XML format.
55-
func (s *Server) HandleGetService(c web.C, w http.ResponseWriter, r *http.Request) {
59+
func (s *Server) HandleGetService(c web.C, w http.ResponseWriter, _ *http.Request) {
5660
service := Service{}
5761
err := s.Store.Get(fmt.Sprintf("/services/%s", c.URLParams["id"]), &service)
5862
if err != nil {
5963
s.logger.Printf("ERROR: %s", err)
6064
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
6165
return
6266
}
63-
xml.NewEncoder(w).Encode(service.Metadata)
67+
err = xml.NewEncoder(w).Encode(service.Metadata)
68+
if err != nil {
69+
s.logger.Printf("ERROR: %s", err)
70+
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
71+
}
6472
}
6573

6674
// HandlePutService handles the `PUT /shortcuts/:id` request. It accepts the XML-formatted
@@ -92,7 +100,7 @@ func (s *Server) HandlePutService(c web.C, w http.ResponseWriter, r *http.Reques
92100
}
93101

94102
// HandleDeleteService handles the `DELETE /services/:id` request.
95-
func (s *Server) HandleDeleteService(c web.C, w http.ResponseWriter, r *http.Request) {
103+
func (s *Server) HandleDeleteService(c web.C, w http.ResponseWriter, _ *http.Request) {
96104
service := Service{}
97105
err := s.Store.Get(fmt.Sprintf("/services/%s", c.URLParams["id"]), &service)
98106
if err != nil {

samlidp/service_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ func TestServicesCrud(t *testing.T) {
1818
r, _ := http.NewRequest("GET", "https://idp.example.com/services/", nil)
1919
test.Server.ServeHTTP(w, r)
2020
assert.Check(t, is.Equal(http.StatusOK, w.Code))
21-
assert.Check(t, is.Equal("{\"services\":[]}\n", string(w.Body.Bytes())))
21+
assert.Check(t, is.Equal("{\"services\":[]}\n", w.Body.String()))
2222

2323
w = httptest.NewRecorder()
2424
r, _ = http.NewRequest("PUT", "https://idp.example.com/services/sp",
@@ -36,7 +36,7 @@ func TestServicesCrud(t *testing.T) {
3636
r, _ = http.NewRequest("GET", "https://idp.example.com/services/", nil)
3737
test.Server.ServeHTTP(w, r)
3838
assert.Check(t, is.Equal(http.StatusOK, w.Code))
39-
assert.Check(t, is.Equal("{\"services\":[\"sp\"]}\n", string(w.Body.Bytes())))
39+
assert.Check(t, is.Equal("{\"services\":[\"sp\"]}\n", w.Body.String()))
4040

4141
assert.Check(t, is.Len(test.Server.serviceProviders, 2))
4242

@@ -49,6 +49,6 @@ func TestServicesCrud(t *testing.T) {
4949
r, _ = http.NewRequest("GET", "https://idp.example.com/services/", nil)
5050
test.Server.ServeHTTP(w, r)
5151
assert.Check(t, is.Equal(http.StatusOK, w.Code))
52-
assert.Check(t, is.Equal("{\"services\":[]}\n", string(w.Body.Bytes())))
52+
assert.Check(t, is.Equal("{\"services\":[]}\n", w.Body.String()))
5353
assert.Check(t, is.Len(test.Server.serviceProviders, 1))
5454
}

0 commit comments

Comments
 (0)