fix: Bump golangci-lint version and fix some linter's problems

Signed-off-by: m.nabokikh <maksim.nabokikh@flant.com>
This commit is contained in:
m.nabokikh 2020-10-18 01:02:29 +04:00
parent 28b2350cd2
commit 4d63e9cd68
12 changed files with 97 additions and 79 deletions

View File

@ -8,27 +8,38 @@ linters-settings:
local-prefixes: github.com/dexidp/dex local-prefixes: github.com/dexidp/dex
linters: linters:
enable-all: true disable-all: true
disable: enable:
- funlen - bodyclose
- maligned - deadcode
- wsl - depguard
- dogsled
# TODO: fix me
- unparam
- golint
- goconst
- staticcheck
- nakedret
- errcheck
- gosec
- gochecknoinits - gochecknoinits
- gochecknoglobals - gofmt
- prealloc - goimports
- scopelint - golint
- lll - gosimple
- dupl - govet
- gocritic - ineffassign
- gocyclo - interfacer
- gocognit - misspell
- godox - nakedret
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unused
- varcheck
- whitespace
# TODO: fix linter errors before enabling
# - unparam
# - scopelint
# - gosec
# - gocyclo
# - lll
# - goconst
# - gocritic
# - errcheck
# - dupl

View File

@ -18,7 +18,7 @@ export GOBIN=$(PWD)/bin
LD_FLAGS="-w -X $(REPO_PATH)/version.Version=$(VERSION)" LD_FLAGS="-w -X $(REPO_PATH)/version.Version=$(VERSION)"
# Dependency versions # Dependency versions
GOLANGCI_VERSION = 1.21.0 GOLANGCI_VERSION = 1.31.0
build: bin/dex build: bin/dex

View File

@ -111,7 +111,7 @@ func (c *crowdConnector) Login(ctx context.Context, s connector.Scopes, username
// We want to return a different error if the user's password is incorrect vs // We want to return a different error if the user's password is incorrect vs
// if there was an error. // if there was an error.
incorrectPass := false var incorrectPass bool
var user crowdUser var user crowdUser
client := c.crowdAPIClient() client := c.crowdAPIClient()

View File

@ -13,6 +13,7 @@ import (
"golang.org/x/oauth2" "golang.org/x/oauth2"
"golang.org/x/oauth2/google" "golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1" admin "google.golang.org/api/admin/directory/v1"
"google.golang.org/api/option"
"github.com/dexidp/dex/connector" "github.com/dexidp/dex/connector"
pkg_groups "github.com/dexidp/dex/pkg/groups" pkg_groups "github.com/dexidp/dex/pkg/groups"
@ -289,7 +290,7 @@ func createDirectoryService(serviceAccountFilePath string, email string) (*admin
ctx := context.Background() ctx := context.Background()
client := config.Client(ctx) client := config.Client(ctx)
srv, err := admin.New(client) srv, err := admin.NewService(ctx, option.WithHTTPClient(client))
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to create directory service %v", err) return nil, fmt.Errorf("unable to create directory service %v", err)
} }

View File

@ -56,6 +56,7 @@ import (
// nameAttr: name // nameAttr: name
// //
// UserMatcher holds information about user and group matching.
type UserMatcher struct { type UserMatcher struct {
UserAttr string `json:"userAttr"` UserAttr string `json:"userAttr"`
GroupAttr string `json:"groupAttr"` GroupAttr string `json:"groupAttr"`
@ -303,7 +304,7 @@ var (
// do initializes a connection to the LDAP directory and passes it to the // do initializes a connection to the LDAP directory and passes it to the
// provided function. It then performs appropriate teardown or reuse before // provided function. It then performs appropriate teardown or reuse before
// returning. // returning.
func (c *ldapConnector) do(ctx context.Context, f func(c *ldap.Conn) error) error { func (c *ldapConnector) do(_ context.Context, f func(c *ldap.Conn) error) error {
// TODO(ericchiang): support context here // TODO(ericchiang): support context here
var ( var (
conn *ldap.Conn conn *ldap.Conn

View File

@ -11,6 +11,7 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"strings" "strings"
"sync"
"time" "time"
"github.com/beevik/etree" "github.com/beevik/etree"
@ -60,20 +61,9 @@ var (
nameIDformatTransient, nameIDformatTransient,
} }
nameIDFormatLookup = make(map[string]string) nameIDFormatLookup = make(map[string]string)
)
func init() { lookupOnce sync.Once
suffix := func(s, sep string) string { )
if i := strings.LastIndex(s, sep); i > 0 {
return s[i+1:]
}
return s
}
for _, format := range nameIDFormats {
nameIDFormatLookup[suffix(format, ":")] = format
nameIDFormatLookup[format] = format
}
}
// Config represents configuration options for the SAML provider. // Config represents configuration options for the SAML provider.
type Config struct { type Config struct {
@ -176,6 +166,19 @@ func (c *Config) openConnector(logger log.Logger) (*provider, error) {
if p.nameIDPolicyFormat == "" { if p.nameIDPolicyFormat == "" {
p.nameIDPolicyFormat = nameIDFormatPersistent p.nameIDPolicyFormat = nameIDFormatPersistent
} else { } else {
lookupOnce.Do(func() {
suffix := func(s, sep string) string {
if i := strings.LastIndex(s, sep); i > 0 {
return s[i+1:]
}
return s
}
for _, format := range nameIDFormats {
nameIDFormatLookup[suffix(format, ":")] = format
nameIDFormatLookup[format] = format
}
})
if format, ok := nameIDFormatLookup[p.nameIDPolicyFormat]; ok { if format, ok := nameIDFormatLookup[p.nameIDPolicyFormat]; ok {
p.nameIDPolicyFormat = format p.nameIDPolicyFormat = format
} else { } else {
@ -364,7 +367,7 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str
switch { switch {
case subject.NameID != nil: case subject.NameID != nil:
if ident.UserID = subject.NameID.Value; ident.UserID == "" { if ident.UserID = subject.NameID.Value; ident.UserID == "" {
return ident, fmt.Errorf("NameID element does not contain a value") return ident, fmt.Errorf("element NameID does not contain a value")
} }
default: default:
return ident, fmt.Errorf("subject does not contain an NameID element") return ident, fmt.Errorf("subject does not contain an NameID element")
@ -488,7 +491,7 @@ func (p *provider) validateSubject(subject *subject, inResponseTo string) error
data := c.SubjectConfirmationData data := c.SubjectConfirmationData
if data == nil { if data == nil {
return fmt.Errorf("SubjectConfirmation contained no SubjectConfirmationData") return fmt.Errorf("no SubjectConfirmationData field found in SubjectConfirmation")
} }
if data.InResponseTo != inResponseTo { if data.InResponseTo != inResponseTo {
return fmt.Errorf("expected SubjectConfirmationData InResponseTo value %q, got %q", inResponseTo, data.InResponseTo) return fmt.Errorf("expected SubjectConfirmationData InResponseTo value %q, got %q", inResponseTo, data.InResponseTo)

View File

@ -546,7 +546,7 @@ func TestDeviceTokenResponse(t *testing.T) {
t.Errorf("Could read token response %v", err) t.Errorf("Could read token response %v", err)
} }
if tc.expectedResponseCode == http.StatusBadRequest || tc.expectedResponseCode == http.StatusUnauthorized { if tc.expectedResponseCode == http.StatusBadRequest || tc.expectedResponseCode == http.StatusUnauthorized {
expectJsonErrorResponse(tc.testName, body, tc.expectedServerResponse, t) expectJSONErrorResponse(tc.testName, body, tc.expectedServerResponse, t)
} else if string(body) != tc.expectedServerResponse { } else if string(body) != tc.expectedServerResponse {
t.Errorf("Unexpected Server Response. Expected %v got %v", tc.expectedServerResponse, string(body)) t.Errorf("Unexpected Server Response. Expected %v got %v", tc.expectedServerResponse, string(body))
} }
@ -554,7 +554,7 @@ func TestDeviceTokenResponse(t *testing.T) {
} }
} }
func expectJsonErrorResponse(testCase string, body []byte, expectedError string, t *testing.T) { func expectJSONErrorResponse(testCase string, body []byte, expectedError string, t *testing.T) {
jsonMap := make(map[string]interface{}) jsonMap := make(map[string]interface{})
err := json.Unmarshal(body, &jsonMap) err := json.Unmarshal(body, &jsonMap)
if err != nil { if err != nil {

View File

@ -274,7 +274,7 @@ func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) {
} }
} }
if err := s.templates.login(r, w, connectorInfos, r.URL.Path); err != nil { if err := s.templates.login(r, w, connectorInfos); err != nil {
s.logger.Errorf("Server template error: %v", err) s.logger.Errorf("Server template error: %v", err)
} }
} }
@ -335,7 +335,7 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
} }
http.Redirect(w, r, callbackURL, http.StatusFound) http.Redirect(w, r, callbackURL, http.StatusFound)
case connector.PasswordConnector: case connector.PasswordConnector:
if err := s.templates.password(r, w, r.URL.String(), "", usernamePrompt(conn), false, showBacklink, r.URL.Path); err != nil { if err := s.templates.password(r, w, r.URL.String(), "", usernamePrompt(conn), false, showBacklink); err != nil {
s.logger.Errorf("Server template error: %v", err) s.logger.Errorf("Server template error: %v", err)
} }
case connector.SAMLConnector: case connector.SAMLConnector:
@ -383,7 +383,7 @@ func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
return return
} }
if !ok { if !ok {
if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink, r.URL.Path); err != nil { if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink); err != nil {
s.logger.Errorf("Server template error: %v", err) s.logger.Errorf("Server template error: %v", err)
} }
return return
@ -577,7 +577,7 @@ func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) {
s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve client.") s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve client.")
return return
} }
if err := s.templates.approval(r, w, authReq.ID, authReq.Claims.Username, client.Name, authReq.Scopes, r.URL.Path); err != nil { if err := s.templates.approval(r, w, authReq.ID, authReq.Claims.Username, client.Name, authReq.Scopes); err != nil {
s.logger.Errorf("Server template error: %v", err) s.logger.Errorf("Server template error: %v", err)
} }
case http.MethodPost: case http.MethodPost:
@ -650,7 +650,7 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe
// Implicit and hybrid flows that try to use the OOB redirect URI are // Implicit and hybrid flows that try to use the OOB redirect URI are
// rejected earlier. If we got here we're using the code flow. // rejected earlier. If we got here we're using the code flow.
if authReq.RedirectURI == redirectURIOOB { if authReq.RedirectURI == redirectURIOOB {
if err := s.templates.oob(r, w, code.ID, r.URL.Path); err != nil { if err := s.templates.oob(r, w, code.ID); err != nil {
s.logger.Errorf("Server template error: %v", err) s.logger.Errorf("Server template error: %v", err)
} }
return return

View File

@ -78,7 +78,7 @@ func dirExists(dir string) error {
// | |- (theme name) // | |- (theme name)
// |- templates // |- templates
// //
func loadWebConfig(c webConfig) (static, theme http.Handler, templates *templates, err error) { func loadWebConfig(c webConfig) (http.Handler, http.Handler, *templates, error) {
if c.theme == "" { if c.theme == "" {
c.theme = "coreos" c.theme = "coreos"
} }
@ -106,11 +106,11 @@ func loadWebConfig(c webConfig) (static, theme http.Handler, templates *template
} }
} }
static = http.FileServer(http.Dir(staticDir)) static := http.FileServer(http.Dir(staticDir))
theme = http.FileServer(http.Dir(themeDir)) theme := http.FileServer(http.Dir(themeDir))
templates, err = loadTemplates(c, templatesDir) templates, err := loadTemplates(c, templatesDir)
return return static, theme, templates, err
} }
// loadTemplates parses the expected templates from the provided directory. // loadTemplates parses the expected templates from the provided directory.
@ -219,8 +219,7 @@ func relativeURL(serverPath, reqPath, assetPath string) string {
server, req, asset := splitPath(serverPath), splitPath(reqPath), splitPath(assetPath) server, req, asset := splitPath(serverPath), splitPath(reqPath), splitPath(assetPath)
// Remove common prefix of request path with server path // Remove common prefix of request path with server path
// nolint: ineffassign _, req = stripCommonParts(server, req)
server, req = stripCommonParts(server, req)
// Remove common prefix of request path with asset path // Remove common prefix of request path with asset path
asset, req = stripCommonParts(asset, req) asset, req = stripCommonParts(asset, req)
@ -276,7 +275,7 @@ func (t *templates) deviceSuccess(r *http.Request, w http.ResponseWriter, client
return renderTemplate(w, t.deviceSuccessTmpl, data) return renderTemplate(w, t.deviceSuccessTmpl, data)
} }
func (t *templates) login(r *http.Request, w http.ResponseWriter, connectors []connectorInfo, reqPath string) error { func (t *templates) login(r *http.Request, w http.ResponseWriter, connectors []connectorInfo) error {
sort.Sort(byName(connectors)) sort.Sort(byName(connectors))
data := struct { data := struct {
Connectors []connectorInfo Connectors []connectorInfo
@ -285,7 +284,7 @@ func (t *templates) login(r *http.Request, w http.ResponseWriter, connectors []c
return renderTemplate(w, t.loginTmpl, data) return renderTemplate(w, t.loginTmpl, data)
} }
func (t *templates) password(r *http.Request, w http.ResponseWriter, postURL, lastUsername, usernamePrompt string, lastWasInvalid, showBacklink bool, reqPath string) error { func (t *templates) password(r *http.Request, w http.ResponseWriter, postURL, lastUsername, usernamePrompt string, lastWasInvalid, showBacklink bool) error {
data := struct { data := struct {
PostURL string PostURL string
BackLink bool BackLink bool
@ -297,7 +296,7 @@ func (t *templates) password(r *http.Request, w http.ResponseWriter, postURL, la
return renderTemplate(w, t.passwordTmpl, data) return renderTemplate(w, t.passwordTmpl, data)
} }
func (t *templates) approval(r *http.Request, w http.ResponseWriter, authReqID, username, clientName string, scopes []string, reqPath string) error { func (t *templates) approval(r *http.Request, w http.ResponseWriter, authReqID, username, clientName string, scopes []string) error {
accesses := []string{} accesses := []string{}
for _, scope := range scopes { for _, scope := range scopes {
access, ok := scopeDescriptions[scope] access, ok := scopeDescriptions[scope]
@ -316,7 +315,7 @@ func (t *templates) approval(r *http.Request, w http.ResponseWriter, authReqID,
return renderTemplate(w, t.approvalTmpl, data) return renderTemplate(w, t.approvalTmpl, data)
} }
func (t *templates) oob(r *http.Request, w http.ResponseWriter, code string, reqPath string) error { func (t *templates) oob(r *http.Request, w http.ResponseWriter, code string) error {
data := struct { data := struct {
Code string Code string
ReqPath string ReqPath string
@ -332,7 +331,7 @@ func (t *templates) err(r *http.Request, w http.ResponseWriter, errCode int, err
ReqPath string ReqPath string
}{http.StatusText(errCode), errMsg, r.URL.Path} }{http.StatusText(errCode), errMsg, r.URL.Path}
if err := t.errorTmpl.Execute(w, data); err != nil { if err := t.errorTmpl.Execute(w, data); err != nil {
return fmt.Errorf("Error rendering template %s: %s", t.errorTmpl.Name(), err) return fmt.Errorf("rendering template %s failed: %s", t.errorTmpl.Name(), err)
} }
return nil return nil
} }
@ -355,7 +354,7 @@ func renderTemplate(w http.ResponseWriter, tmpl *template.Template, data interfa
// TODO(ericchiang): replace with better internal server error. // TODO(ericchiang): replace with better internal server error.
http.Error(w, "Internal server error", http.StatusInternalServerError) http.Error(w, "Internal server error", http.StatusInternalServerError)
} }
return fmt.Errorf("Error rendering template %s: %s", tmpl.Name(), err) return fmt.Errorf("rendering template %s failed: %s", tmpl.Name(), err)
} }
return nil return nil
} }

View File

@ -679,7 +679,7 @@ type DeviceRequest struct {
Expiry time.Time `json:"expiry"` Expiry time.Time `json:"expiry"`
} }
// AuthRequestList is a list of AuthRequests. // DeviceRequestList is a list of DeviceRequests.
type DeviceRequestList struct { type DeviceRequestList struct {
k8sapi.TypeMeta `json:",inline"` k8sapi.TypeMeta `json:",inline"`
k8sapi.ListMeta `json:"metadata,omitempty"` k8sapi.ListMeta `json:"metadata,omitempty"`

View File

@ -84,7 +84,9 @@ type scanner interface {
Scan(dest ...interface{}) error Scan(dest ...interface{}) error
} }
func (c *conn) GarbageCollect(now time.Time) (result storage.GCResult, err error) { func (c *conn) GarbageCollect(now time.Time) (storage.GCResult, error) {
result := storage.GCResult{}
r, err := c.Exec(`delete from auth_request where expiry < $1`, now) r, err := c.Exec(`delete from auth_request where expiry < $1`, now)
if err != nil { if err != nil {
return result, fmt.Errorf("gc auth_request: %v", err) return result, fmt.Errorf("gc auth_request: %v", err)
@ -117,7 +119,7 @@ func (c *conn) GarbageCollect(now time.Time) (result storage.GCResult, err error
result.DeviceTokens = n result.DeviceTokens = n
} }
return return result, err
} }
func (c *conn) CreateAuthRequest(a storage.AuthRequest) error { func (c *conn) CreateAuthRequest(a storage.AuthRequest) error {

View File

@ -384,23 +384,24 @@ func randomString(n int) (string, error) {
return string(bytes), nil return string(bytes), nil
} }
//DeviceRequest represents an OIDC device authorization request. It holds the state of a device request until the user // DeviceRequest represents an OIDC device authorization request. It holds the state of a device request until the user
//authenticates using their user code or the expiry time passes. // authenticates using their user code or the expiry time passes.
type DeviceRequest struct { type DeviceRequest struct {
//The code the user will enter in a browser // The code the user will enter in a browser
UserCode string UserCode string
//The unique device code for device authentication // The unique device code for device authentication
DeviceCode string DeviceCode string
//The client ID the code is for // The client ID the code is for
ClientID string ClientID string
//The Client Secret // The Client Secret
ClientSecret string ClientSecret string
//The scopes the device requests // The scopes the device requests
Scopes []string Scopes []string
//The expire time // The expire time
Expiry time.Time Expiry time.Time
} }
// DeviceToken is a structure which represents the actual token of an authorized device and its rotation parameters
type DeviceToken struct { type DeviceToken struct {
DeviceCode string DeviceCode string
Status string Status string