Merge pull request #1604 from dexidp/fix-linters

Fix linters
This commit is contained in:
Nándor István Krácser 2019-12-20 07:10:22 +01:00 committed by GitHub
commit a901e2f204
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 86 additions and 113 deletions

View file

@ -16,21 +16,11 @@ linters:
- wsl - wsl
# TODO: fix me # TODO: fix me
- unused
- structcheck
- stylecheck
- deadcode
- misspell
- unparam - unparam
- goimports
- golint - golint
- whitespace
- goconst - goconst
- unconvert
- bodyclose
- staticcheck - staticcheck
- nakedret - nakedret
- ineffassign
- errcheck - errcheck
- gosec - gosec
- gochecknoinits - gochecknoinits

View file

@ -1,7 +1,6 @@
package main package main
import ( import (
"github.com/dexidp/dex/server"
"testing" "testing"
"github.com/ghodss/yaml" "github.com/ghodss/yaml"
@ -9,6 +8,7 @@ import (
"github.com/dexidp/dex/connector/mock" "github.com/dexidp/dex/connector/mock"
"github.com/dexidp/dex/connector/oidc" "github.com/dexidp/dex/connector/oidc"
"github.com/dexidp/dex/server"
"github.com/dexidp/dex/storage" "github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/sql" "github.com/dexidp/dex/storage/sql"
) )
@ -211,5 +211,4 @@ logger:
if diff := pretty.Compare(c, want); diff != "" { if diff := pretty.Compare(c, want); diff != "" {
t.Errorf("got!=want: %s", diff) t.Errorf("got!=want: %s", diff)
} }
} }

View file

@ -182,7 +182,6 @@ func serve(cmd *cobra.Command, args []string) error {
return fmt.Errorf("failed to initialize storage connectors: %v", err) return fmt.Errorf("failed to initialize storage connectors: %v", err)
} }
storageConnectors[i] = conn storageConnectors[i] = conn
} }
if c.EnablePasswordDB { if c.EnablePasswordDB {

View file

@ -143,7 +143,7 @@ func cmd() *cobra.Command {
ctx := oidc.ClientContext(context.Background(), a.client) ctx := oidc.ClientContext(context.Background(), a.client)
provider, err := oidc.NewProvider(ctx, issuerURL) provider, err := oidc.NewProvider(ctx, issuerURL)
if err != nil { if err != nil {
return fmt.Errorf("Failed to query provider %q: %v", issuerURL, err) return fmt.Errorf("failed to query provider %q: %v", issuerURL, err)
} }
var s struct { var s struct {
@ -153,7 +153,7 @@ func cmd() *cobra.Command {
ScopesSupported []string `json:"scopes_supported"` ScopesSupported []string `json:"scopes_supported"`
} }
if err := provider.Claims(&s); err != nil { if err := provider.Claims(&s); err != nil {
return fmt.Errorf("Failed to parse provider scopes_supported: %v", err) return fmt.Errorf("failed to parse provider scopes_supported: %v", err)
} }
if len(s.ScopesSupported) == 0 { if len(s.ScopesSupported) == 0 {

View file

@ -41,7 +41,6 @@ type Config struct {
// Open returns a strategy for logging in through Bitbucket. // Open returns a strategy for logging in through Bitbucket.
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) {
b := bitbucketConnector{ b := bitbucketConnector{
redirectURI: c.RedirectURI, redirectURI: c.RedirectURI,
teams: c.Teams, teams: c.Teams,
@ -373,7 +372,6 @@ type userTeamsResponse struct {
} }
func (b *bitbucketConnector) userTeams(ctx context.Context, client *http.Client) ([]string, error) { func (b *bitbucketConnector) userTeams(ctx context.Context, client *http.Client) ([]string, error) {
var teams []string var teams []string
apiURL := b.apiURL + "/teams?role=member" apiURL := b.apiURL + "/teams?role=member"

View file

@ -14,7 +14,6 @@ import (
) )
func TestUserGroups(t *testing.T) { func TestUserGroups(t *testing.T) {
teamsResponse := userTeamsResponse{ teamsResponse := userTeamsResponse{
pagedResponse: pagedResponse{ pagedResponse: pagedResponse{
Size: 3, Size: 3,
@ -46,7 +45,6 @@ func TestUserGroups(t *testing.T) {
} }
func TestUserWithoutTeams(t *testing.T) { func TestUserWithoutTeams(t *testing.T) {
s := newTestServer(map[string]interface{}{ s := newTestServer(map[string]interface{}{
"/teams?role=member": userTeamsResponse{}, "/teams?role=member": userTeamsResponse{},
}) })
@ -61,7 +59,6 @@ func TestUserWithoutTeams(t *testing.T) {
} }
func TestUsernameIncludedInFederatedIdentity(t *testing.T) { func TestUsernameIncludedInFederatedIdentity(t *testing.T) {
s := newTestServer(map[string]interface{}{ s := newTestServer(map[string]interface{}{
"/user": user{Username: "some-login"}, "/user": user{Username: "some-login"},
"/user/emails": userEmailResponse{ "/user/emails": userEmailResponse{

View file

@ -67,7 +67,6 @@ type Org struct {
// Open returns a strategy for logging in through GitHub. // Open returns a strategy for logging in through GitHub.
func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) { func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error) {
if c.Org != "" { if c.Org != "" {
// Return error if both 'org' and 'orgs' fields are used. // Return error if both 'org' and 'orgs' fields are used.
if len(c.Orgs) > 0 { if len(c.Orgs) > 0 {
@ -107,7 +106,6 @@ func (c *Config) Open(id string, logger log.Logger) (connector.Connector, error)
if g.httpClient, err = newHTTPClient(g.rootCA); err != nil { if g.httpClient, err = newHTTPClient(g.rootCA); err != nil {
return nil, fmt.Errorf("failed to create HTTP client: %v", err) return nil, fmt.Errorf("failed to create HTTP client: %v", err)
} }
} }
g.loadAllGroups = c.LoadAllGroups g.loadAllGroups = c.LoadAllGroups
@ -144,7 +142,7 @@ type githubConnector struct {
hostName string hostName string
// Used to support untrusted/self-signed CA certs. // Used to support untrusted/self-signed CA certs.
rootCA string rootCA string
// HTTP Client that trusts the custom delcared rootCA cert. // HTTP Client that trusts the custom declared rootCA cert.
httpClient *http.Client httpClient *http.Client
// optional choice between 'name' (default) or 'slug' // optional choice between 'name' (default) or 'slug'
teamNameField string teamNameField string
@ -206,7 +204,7 @@ func (e *oauth2Error) Error() string {
return e.error + ": " + e.errorDescription return e.error + ": " + e.errorDescription
} }
// newHTTPClient returns a new HTTP client that trusts the custom delcared rootCA cert. // newHTTPClient returns a new HTTP client that trusts the custom declared rootCA cert.
func newHTTPClient(rootCA string) (*http.Client, error) { func newHTTPClient(rootCA string) (*http.Client, error) {
tlsConfig := tls.Config{RootCAs: x509.NewCertPool()} tlsConfig := tls.Config{RootCAs: x509.NewCertPool()}
rootCABytes, err := ioutil.ReadFile(rootCA) rootCABytes, err := ioutil.ReadFile(rootCA)

View file

@ -126,7 +126,6 @@ func TestUserGroupsWithTeamNameAndSlugFieldConfig(t *testing.T) {
// tests that the users login is used as their username when they have no username set // tests that the users login is used as their username when they have no username set
func TestUsernameIncludedInFederatedIdentity(t *testing.T) { func TestUsernameIncludedInFederatedIdentity(t *testing.T) {
s := newTestServer(map[string]testResponse{ s := newTestServer(map[string]testResponse{
"/user": {data: user{Login: "some-login", ID: 12345678}}, "/user": {data: user{Login: "some-login", ID: 12345678}},
"/user/emails": {data: []userEmail{{ "/user/emails": {data: []userEmail{{
@ -168,7 +167,6 @@ func TestUsernameIncludedInFederatedIdentity(t *testing.T) {
} }
func TestLoginUsedAsIDWhenConfigured(t *testing.T) { func TestLoginUsedAsIDWhenConfigured(t *testing.T) {
s := newTestServer(map[string]testResponse{ s := newTestServer(map[string]testResponse{
"/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}}, "/user": {data: user{Login: "some-login", ID: 12345678, Name: "Joe Bloggs"}},
"/user/emails": {data: []userEmail{{ "/user/emails": {data: []userEmail{{

View file

@ -65,7 +65,6 @@ func TestUserGroupsWithoutOrgs(t *testing.T) {
// tests that the email is used as their username when they have no username set // tests that the email is used as their username when they have no username set
func TestUsernameIncludedInFederatedIdentity(t *testing.T) { func TestUsernameIncludedInFederatedIdentity(t *testing.T) {
s := newTestServer(map[string]interface{}{ s := newTestServer(map[string]interface{}{
"/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678}, "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678},
"/oauth/token": map[string]interface{}{ "/oauth/token": map[string]interface{}{
@ -102,7 +101,6 @@ func TestUsernameIncludedInFederatedIdentity(t *testing.T) {
} }
func TestLoginUsedAsIDWhenConfigured(t *testing.T) { func TestLoginUsedAsIDWhenConfigured(t *testing.T) {
s := newTestServer(map[string]interface{}{ s := newTestServer(map[string]interface{}{
"/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs", Username: "joebloggs"}, "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs", Username: "joebloggs"},
"/oauth/token": map[string]interface{}{ "/oauth/token": map[string]interface{}{
@ -130,7 +128,6 @@ func TestLoginUsedAsIDWhenConfigured(t *testing.T) {
} }
func TestLoginWithTeamWhitelisted(t *testing.T) { func TestLoginWithTeamWhitelisted(t *testing.T) {
s := newTestServer(map[string]interface{}{ s := newTestServer(map[string]interface{}{
"/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs"}, "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs"},
"/oauth/token": map[string]interface{}{ "/oauth/token": map[string]interface{}{
@ -158,7 +155,6 @@ func TestLoginWithTeamWhitelisted(t *testing.T) {
} }
func TestLoginWithTeamNonWhitelisted(t *testing.T) { func TestLoginWithTeamNonWhitelisted(t *testing.T) {
s := newTestServer(map[string]interface{}{ s := newTestServer(map[string]interface{}{
"/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs", Username: "joebloggs"}, "/api/v4/user": gitlabUser{Email: "some@email.com", ID: 12345678, Name: "Joe Bloggs", Username: "joebloggs"},
"/oauth/token": map[string]interface{}{ "/oauth/token": map[string]interface{}{

View file

@ -11,12 +11,12 @@ import (
"github.com/coreos/go-oidc" "github.com/coreos/go-oidc"
"golang.org/x/oauth2" "golang.org/x/oauth2"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
"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"
"github.com/dexidp/dex/pkg/log" "github.com/dexidp/dex/pkg/log"
"golang.org/x/oauth2/google"
admin "google.golang.org/api/admin/directory/v1"
) )
const ( const (
@ -105,7 +105,6 @@ type googleConnector struct {
redirectURI string redirectURI string
oauth2Config *oauth2.Config oauth2Config *oauth2.Config
verifier *oidc.IDTokenVerifier verifier *oidc.IDTokenVerifier
ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
logger log.Logger logger log.Logger
hostedDomains []string hostedDomains []string

View file

@ -150,7 +150,6 @@ func (p *conn) Prompt() string { return "username" }
func (p *conn) Refresh( func (p *conn) Refresh(
ctx context.Context, scopes connector.Scopes, identity connector.Identity) (connector.Identity, error) { ctx context.Context, scopes connector.Scopes, identity connector.Identity) (connector.Identity, error) {
token, err := p.getAdminToken(ctx) token, err := p.getAdminToken(ctx)
if err != nil { if err != nil {
return identity, fmt.Errorf("keystone: failed to obtain admin token: %v", err) return identity, fmt.Errorf("keystone: failed to obtain admin token: %v", err)
@ -210,6 +209,8 @@ func (p *conn) getAdminToken(ctx context.Context) (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
defer resp.Body.Close()
token := resp.Header.Get("X-Subject-Token") token := resp.Header.Get("X-Subject-Token")
return token, nil return token, nil
} }
@ -229,6 +230,7 @@ func (p *conn) checkIfUserExists(ctx context.Context, userID string, token strin
if err != nil { if err != nil {
return false, err return false, err
} }
defer resp.Body.Close()
if resp.StatusCode == 200 { if resp.StatusCode == 200 {
return true, nil return true, nil

View file

@ -154,7 +154,12 @@ func delete(t *testing.T, token, id, uri string) {
t.Fatalf("error: %v", err) t.Fatalf("error: %v", err)
} }
req.Header.Set("X-Auth-Token", token) req.Header.Set("X-Auth-Token", token)
client.Do(req)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("error: %v", err)
}
defer resp.Body.Close()
} }
func createGroup(t *testing.T, token, description, name string) string { func createGroup(t *testing.T, token, description, name string) string {
@ -208,7 +213,13 @@ func addUserToGroup(t *testing.T, token, groupID, userID string) error {
return err return err
} }
req.Header.Set("X-Auth-Token", token) req.Header.Set("X-Auth-Token", token)
client.Do(req)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("error: %v", err)
}
defer resp.Body.Close()
return nil return nil
} }
@ -274,7 +285,7 @@ func TestUseRefreshToken(t *testing.T) {
delete(t, token, groupID, groupsURL) delete(t, token, groupID, groupsURL)
expectEquals(t, 1, len(identityRefresh.Groups)) expectEquals(t, 1, len(identityRefresh.Groups))
expectEquals(t, testGroup, string(identityRefresh.Groups[0])) expectEquals(t, testGroup, identityRefresh.Groups[0])
} }
func TestUseRefreshTokenUserDeleted(t *testing.T) { func TestUseRefreshTokenUserDeleted(t *testing.T) {

View file

@ -189,7 +189,6 @@ func (c *Config) OpenConnector(logger log.Logger) (interface {
} }
func (c *Config) openConnector(logger log.Logger) (*ldapConnector, error) { func (c *Config) openConnector(logger log.Logger) (*ldapConnector, error) {
requiredFields := []struct { requiredFields := []struct {
name string name string
val string val string
@ -365,7 +364,6 @@ func (c *ldapConnector) identityFromEntry(user ldap.Entry) (ident connector.Iden
} }
func (c *ldapConnector) userEntry(conn *ldap.Conn, username string) (user ldap.Entry, found bool, err error) { func (c *ldapConnector) userEntry(conn *ldap.Conn, username string) (user ldap.Entry, found bool, err error) {
filter := fmt.Sprintf("(%s=%s)", c.UserSearch.Username, ldap.EscapeFilter(username)) filter := fmt.Sprintf("(%s=%s)", c.UserSearch.Username, ldap.EscapeFilter(username))
if c.UserSearch.Filter != "" { if c.UserSearch.Filter != "" {
filter = fmt.Sprintf("(&%s%s)", c.UserSearch.Filter, filter) filter = fmt.Sprintf("(&%s%s)", c.UserSearch.Filter, filter)

View file

@ -16,9 +16,10 @@ import (
"testing" "testing"
"time" "time"
"github.com/dexidp/dex/connector"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"gopkg.in/square/go-jose.v2" "gopkg.in/square/go-jose.v2"
"github.com/dexidp/dex/connector"
) )
func TestKnownBrokenAuthHeaderProvider(t *testing.T) { func TestKnownBrokenAuthHeaderProvider(t *testing.T) {

View file

@ -14,11 +14,12 @@ import (
"time" "time"
"github.com/beevik/etree" "github.com/beevik/etree"
dsig "github.com/russellhaering/goxmldsig"
"github.com/russellhaering/goxmldsig/etreeutils"
"github.com/dexidp/dex/connector" "github.com/dexidp/dex/connector"
"github.com/dexidp/dex/pkg/groups" "github.com/dexidp/dex/pkg/groups"
"github.com/dexidp/dex/pkg/log" "github.com/dexidp/dex/pkg/log"
dsig "github.com/russellhaering/goxmldsig"
"github.com/russellhaering/goxmldsig/etreeutils"
) )
// nolint // nolint
@ -248,7 +249,6 @@ type provider struct {
} }
func (p *provider) POSTData(s connector.Scopes, id string) (action, value string, err error) { func (p *provider) POSTData(s connector.Scopes, id string) (action, value string, err error) {
r := &authnRequest{ r := &authnRequest{
ProtocolBinding: bindingPOST, ProtocolBinding: bindingPOST,
ID: id, ID: id,
@ -325,7 +325,7 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str
// Status is a required element. // Status is a required element.
if resp.Status == nil { if resp.Status == nil {
return ident, fmt.Errorf("Response did not contain a Status element") return ident, fmt.Errorf("response did not contain a Status element")
} }
if err = p.validateStatus(resp.Status); err != nil { if err = p.validateStatus(resp.Status); err != nil {
@ -398,7 +398,7 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str
if len(p.allowedGroups) > 0 && (!s.Groups || p.groupsAttr == "") { if len(p.allowedGroups) > 0 && (!s.Groups || p.groupsAttr == "") {
// allowedGroups set but no groups or groupsAttr. Disallowing. // allowedGroups set but no groups or groupsAttr. Disallowing.
return ident, fmt.Errorf("User not a member of allowed groups") return ident, fmt.Errorf("user not a member of allowed groups")
} }
// Grab the groups. // Grab the groups.
@ -427,7 +427,7 @@ func (p *provider) HandlePOST(s connector.Scopes, samlResponse, inResponseTo str
if len(groupMatches) == 0 { if len(groupMatches) == 0 {
// No group membership matches found, disallowing // No group membership matches found, disallowing
return ident, fmt.Errorf("User not a member of allowed groups") return ident, fmt.Errorf("user not a member of allowed groups")
} }
// Otherwise, we're good // Otherwise, we're good
@ -468,7 +468,7 @@ func (p *provider) validateStatus(status *status) error {
func (p *provider) validateSubject(subject *subject, inResponseTo string) error { func (p *provider) validateSubject(subject *subject, inResponseTo string) error {
// Optional according to the spec, but again, we're going to be strict here. // Optional according to the spec, but again, we're going to be strict here.
if len(subject.SubjectConfirmations) == 0 { if len(subject.SubjectConfirmations) == 0 {
return fmt.Errorf("Subject contained no SubjectConfirmations") return fmt.Errorf("subject contained no SubjectConfirmations")
} }
var errs []error var errs []error

View file

@ -218,7 +218,6 @@ func (d dexAPI) DeletePassword(ctx context.Context, req *api.DeletePasswordReq)
return nil, fmt.Errorf("delete password: %v", err) return nil, fmt.Errorf("delete password: %v", err)
} }
return &api.DeletePasswordResp{}, nil return &api.DeletePasswordResp{}, nil
} }
func (d dexAPI) GetVersion(ctx context.Context, req *api.VersionReq) (*api.VersionResp, error) { func (d dexAPI) GetVersion(ctx context.Context, req *api.VersionReq) (*api.VersionResp, error) {
@ -248,7 +247,6 @@ func (d dexAPI) ListPasswords(ctx context.Context, req *api.ListPasswordReq) (*a
return &api.ListPasswordResp{ return &api.ListPasswordResp{
Passwords: passwords, Passwords: passwords,
}, nil }, nil
} }
func (d dexAPI) VerifyPassword(ctx context.Context, req *api.VerifyPasswordReq) (*api.VerifyPasswordResp, error) { func (d dexAPI) VerifyPassword(ctx context.Context, req *api.VerifyPasswordReq) (*api.VerifyPasswordResp, error) {

View file

@ -167,7 +167,6 @@ func TestPassword(t *testing.T) {
if _, err := client.DeletePassword(ctx, &deleteReq); err != nil { if _, err := client.DeletePassword(ctx, &deleteReq); err != nil {
t.Fatalf("Unable to delete password: %v", err) t.Fatalf("Unable to delete password: %v", err)
} }
} }
// Ensures checkCost returns expected values // Ensures checkCost returns expected values
@ -495,7 +494,6 @@ func TestUpdateClient(t *testing.T) {
if tc.cleanup != nil { if tc.cleanup != nil {
tc.cleanup(t, tc.req.Id) tc.cleanup(t, tc.req.Id)
} }
}) })
} }
} }

View file

@ -45,8 +45,8 @@ func (s *Server) newHealthChecker(ctx context.Context) http.Handler {
return h return h
} }
// healthChecker periodically performs health checks on server dependenices. // healthChecker periodically performs health checks on server dependencies.
// Currently, it only checks that the storage layer is avialable. // Currently, it only checks that the storage layer is available.
type healthChecker struct { type healthChecker struct {
s *Server s *Server
@ -922,7 +922,6 @@ func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client s
deleteToken = true deleteToken = true
return return
} }
} }
} }
s.writeAccessToken(w, idToken, accessToken, refreshToken, expiry) s.writeAccessToken(w, idToken, accessToken, refreshToken, expiry)

View file

@ -24,7 +24,6 @@ func TestHandleHealth(t *testing.T) {
if rr.Code != http.StatusOK { if rr.Code != http.StatusOK {
t.Errorf("expected 200 got %d", rr.Code) t.Errorf("expected 200 got %d", rr.Code)
} }
} }
type badStorage struct { type badStorage struct {

View file

@ -14,6 +14,10 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/felixge/httpsnoop"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"github.com/dexidp/dex/connector" "github.com/dexidp/dex/connector"
@ -31,10 +35,6 @@ import (
"github.com/dexidp/dex/connector/saml" "github.com/dexidp/dex/connector/saml"
"github.com/dexidp/dex/pkg/log" "github.com/dexidp/dex/pkg/log"
"github.com/dexidp/dex/storage" "github.com/dexidp/dex/storage"
"github.com/felixge/httpsnoop"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
) )
// LocalConnector is the local passwordDB connector which is an internal // LocalConnector is the local passwordDB connector which is an internal

View file

@ -590,6 +590,8 @@ func TestOAuth2CodeFlow(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("get failed: %v", err) t.Fatalf("get failed: %v", err)
} }
defer resp.Body.Close()
if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -726,6 +728,8 @@ func TestOAuth2ImplicitFlow(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("get failed: %v", err) t.Fatalf("get failed: %v", err)
} }
defer resp.Body.Close()
if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -799,7 +803,6 @@ func TestCrossClientScopes(t *testing.T) {
if !reflect.DeepEqual(idToken.Audience, expAudience) { if !reflect.DeepEqual(idToken.Audience, expAudience) {
t.Errorf("expected audience %q, got %q", expAudience, idToken.Audience) t.Errorf("expected audience %q, got %q", expAudience, idToken.Audience)
} }
} }
if gotState := q.Get("state"); gotState != state { if gotState := q.Get("state"); gotState != state {
t.Errorf("state did not match, want=%q got=%q", state, gotState) t.Errorf("state did not match, want=%q got=%q", state, gotState)
@ -848,6 +851,8 @@ func TestCrossClientScopes(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("get failed: %v", err) t.Fatalf("get failed: %v", err)
} }
defer resp.Body.Close()
if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -921,7 +926,6 @@ func TestCrossClientScopesWithAzpInAudienceByDefault(t *testing.T) {
if !reflect.DeepEqual(idToken.Audience, expAudience) { if !reflect.DeepEqual(idToken.Audience, expAudience) {
t.Errorf("expected audience %q, got %q", expAudience, idToken.Audience) t.Errorf("expected audience %q, got %q", expAudience, idToken.Audience)
} }
} }
if gotState := q.Get("state"); gotState != state { if gotState := q.Get("state"); gotState != state {
t.Errorf("state did not match, want=%q got=%q", state, gotState) t.Errorf("state did not match, want=%q got=%q", state, gotState)
@ -969,6 +973,8 @@ func TestCrossClientScopesWithAzpInAudienceByDefault(t *testing.T) {
if err != nil { if err != nil {
t.Fatalf("get failed: %v", err) t.Fatalf("get failed: %v", err)
} }
defer resp.Body.Close()
if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil { if reqDump, err = httputil.DumpRequest(resp.Request, false); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -1058,7 +1064,6 @@ func TestPasswordDB(t *testing.T) {
t.Errorf("%s: %s", tc.name, diff) t.Errorf("%s: %s", tc.name, diff)
} }
} }
} }
func TestPasswordDBUsernamePrompt(t *testing.T) { func TestPasswordDBUsernamePrompt(t *testing.T) {
@ -1225,9 +1230,11 @@ func TestRefreshTokenFlow(t *testing.T) {
RedirectURL: redirectURL, RedirectURL: redirectURL,
} }
if _, err = http.Get(oauth2Client.server.URL + "/login"); err != nil { resp, err := http.Get(oauth2Client.server.URL + "/login")
if err != nil {
t.Fatalf("get failed: %v", err) t.Fatalf("get failed: %v", err)
} }
defer resp.Body.Close()
tok := &oauth2.Token{ tok := &oauth2.Token{
RefreshToken: oauth2Client.token.RefreshToken, RefreshToken: oauth2Client.token.RefreshToken,
@ -1235,9 +1242,11 @@ func TestRefreshTokenFlow(t *testing.T) {
} }
// Login in again to receive a new token. // Login in again to receive a new token.
if _, err = http.Get(oauth2Client.server.URL + "/login"); err != nil { resp, err = http.Get(oauth2Client.server.URL + "/login")
if err != nil {
t.Fatalf("get failed: %v", err) t.Fatalf("get failed: %v", err)
} }
defer resp.Body.Close()
// try to refresh expired token with old refresh token. // try to refresh expired token with old refresh token.
if _, err := oauth2Client.config.TokenSource(ctx, tok).Token(); err == nil { if _, err := oauth2Client.config.TokenSource(ctx, tok).Token(); err == nil {

View file

@ -47,19 +47,6 @@ type webConfig struct {
extra map[string]string extra map[string]string
} }
func join(base, path string) string {
b := strings.HasSuffix(base, "/")
p := strings.HasPrefix(path, "/")
switch {
case b && p:
return base + path[1:]
case b || p:
return base + path
default:
return base + "/" + path
}
}
func dirExists(dir string) error { func dirExists(dir string) error {
stat, err := os.Stat(dir) stat, err := os.Stat(dir)
if err != nil { if err != nil {
@ -189,7 +176,6 @@ func loadTemplates(c webConfig, templatesDir string) (*templates, error) {
//assetPath is static/main.css //assetPath is static/main.css
//relativeURL("/dex", "/dex/auth", "static/main.css") = "../static/main.css" //relativeURL("/dex", "/dex/auth", "static/main.css") = "../static/main.css"
func relativeURL(serverPath, reqPath, assetPath string) string { func relativeURL(serverPath, reqPath, assetPath string) string {
splitPath := func(p string) []string { splitPath := func(p string) []string {
res := []string{} res := []string{}
parts := strings.Split(path.Clean(p), "/") parts := strings.Split(path.Clean(p), "/")
@ -220,6 +206,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
server, 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

View file

@ -160,7 +160,6 @@ func testAuthRequestCRUD(t *testing.T, s storage.Storage) {
if err := s.DeleteAuthRequest(a2.ID); err != nil { if err := s.DeleteAuthRequest(a2.ID); err != nil {
t.Fatalf("failed to delete auth request: %v", err) t.Fatalf("failed to delete auth request: %v", err)
} }
} }
func testAuthCodeCRUD(t *testing.T, s storage.Storage) { func testAuthCodeCRUD(t *testing.T, s storage.Storage) {
@ -509,7 +508,6 @@ func testPasswordCRUD(t *testing.T, s storage.Storage) {
_, err = s.GetPassword(password1.Email) _, err = s.GetPassword(password1.Email)
mustBeErrNotFound(t, "password", err) mustBeErrNotFound(t, "password", err)
} }
func testOfflineSessionCRUD(t *testing.T, s storage.Storage) { func testOfflineSessionCRUD(t *testing.T, s storage.Storage) {

View file

@ -156,7 +156,7 @@ func (c *conn) UpdateRefreshToken(id string, updater func(old storage.RefreshTok
return c.txnUpdate(ctx, keyID(refreshTokenPrefix, id), func(currentValue []byte) ([]byte, error) { return c.txnUpdate(ctx, keyID(refreshTokenPrefix, id), func(currentValue []byte) ([]byte, error) {
var current RefreshToken var current RefreshToken
if len(currentValue) > 0 { if len(currentValue) > 0 {
if err := json.Unmarshal([]byte(currentValue), &current); err != nil { if err := json.Unmarshal(currentValue, &current); err != nil {
return nil, err return nil, err
} }
} }

View file

@ -55,14 +55,14 @@ type client struct {
} }
// idToName maps an arbitrary ID, such as an email or client ID to a Kubernetes object name. // idToName maps an arbitrary ID, such as an email or client ID to a Kubernetes object name.
func (c *client) idToName(s string) string { func (cli *client) idToName(s string) string {
return idToName(s, c.hash) return idToName(s, cli.hash)
} }
// offlineTokenName maps two arbitrary IDs, to a single Kubernetes object name. // offlineTokenName maps two arbitrary IDs, to a single Kubernetes object name.
// This is used when more than one field is used to uniquely identify the object. // This is used when more than one field is used to uniquely identify the object.
func (c *client) offlineTokenName(userID string, connID string) string { func (cli *client) offlineTokenName(userID string, connID string) string {
return offlineTokenName(userID, connID, c.hash) return offlineTokenName(userID, connID, cli.hash)
} }
// Kubernetes names must match the regexp '[a-z0-9]([-a-z0-9]*[a-z0-9])?'. // Kubernetes names must match the regexp '[a-z0-9]([-a-z0-9]*[a-z0-9])?'.
@ -79,7 +79,7 @@ func offlineTokenName(userID string, connID string, h func() hash.Hash) string {
return strings.TrimRight(encoding.EncodeToString(hash.Sum(nil)), "=") return strings.TrimRight(encoding.EncodeToString(hash.Sum(nil)), "=")
} }
func (c *client) urlFor(apiVersion, namespace, resource, name string) string { func (cli *client) urlFor(apiVersion, namespace, resource, name string) string {
basePath := "apis/" basePath := "apis/"
if apiVersion == "v1" { if apiVersion == "v1" {
basePath = "api/" basePath = "api/"
@ -91,10 +91,10 @@ func (c *client) urlFor(apiVersion, namespace, resource, name string) string {
} else { } else {
p = path.Join(basePath, apiVersion, resource, name) p = path.Join(basePath, apiVersion, resource, name)
} }
if strings.HasSuffix(c.baseURL, "/") { if strings.HasSuffix(cli.baseURL, "/") {
return c.baseURL + p return cli.baseURL + p
} }
return c.baseURL + "/" + p return cli.baseURL + "/" + p
} }
// Define an error interface so we can get at the underlying status code if it's // Define an error interface so we can get at the underlying status code if it's
@ -156,13 +156,13 @@ func closeResp(r *http.Response) {
r.Body.Close() r.Body.Close()
} }
func (c *client) get(resource, name string, v interface{}) error { func (cli *client) get(resource, name string, v interface{}) error {
return c.getResource(c.apiVersion, c.namespace, resource, name, v) return cli.getResource(cli.apiVersion, cli.namespace, resource, name, v)
} }
func (c *client) getResource(apiVersion, namespace, resource, name string, v interface{}) error { func (cli *client) getResource(apiVersion, namespace, resource, name string, v interface{}) error {
url := c.urlFor(apiVersion, namespace, resource, name) url := cli.urlFor(apiVersion, namespace, resource, name)
resp, err := c.client.Get(url) resp, err := cli.client.Get(url)
if err != nil { if err != nil {
return err return err
} }
@ -173,22 +173,22 @@ func (c *client) getResource(apiVersion, namespace, resource, name string, v int
return json.NewDecoder(resp.Body).Decode(v) return json.NewDecoder(resp.Body).Decode(v)
} }
func (c *client) list(resource string, v interface{}) error { func (cli *client) list(resource string, v interface{}) error {
return c.get(resource, "", v) return cli.get(resource, "", v)
} }
func (c *client) post(resource string, v interface{}) error { func (cli *client) post(resource string, v interface{}) error {
return c.postResource(c.apiVersion, c.namespace, resource, v) return cli.postResource(cli.apiVersion, cli.namespace, resource, v)
} }
func (c *client) postResource(apiVersion, namespace, resource string, v interface{}) error { func (cli *client) postResource(apiVersion, namespace, resource string, v interface{}) error {
body, err := json.Marshal(v) body, err := json.Marshal(v)
if err != nil { if err != nil {
return fmt.Errorf("marshal object: %v", err) return fmt.Errorf("marshal object: %v", err)
} }
url := c.urlFor(apiVersion, namespace, resource, "") url := cli.urlFor(apiVersion, namespace, resource, "")
resp, err := c.client.Post(url, "application/json", bytes.NewReader(body)) resp, err := cli.client.Post(url, "application/json", bytes.NewReader(body))
if err != nil { if err != nil {
return err return err
} }
@ -196,13 +196,13 @@ func (c *client) postResource(apiVersion, namespace, resource string, v interfac
return checkHTTPErr(resp, http.StatusCreated) return checkHTTPErr(resp, http.StatusCreated)
} }
func (c *client) delete(resource, name string) error { func (cli *client) delete(resource, name string) error {
url := c.urlFor(c.apiVersion, c.namespace, resource, name) url := cli.urlFor(cli.apiVersion, cli.namespace, resource, name)
req, err := http.NewRequest("DELETE", url, nil) req, err := http.NewRequest("DELETE", url, nil)
if err != nil { if err != nil {
return fmt.Errorf("create delete request: %v", err) return fmt.Errorf("create delete request: %v", err)
} }
resp, err := c.client.Do(req) resp, err := cli.client.Do(req)
if err != nil { if err != nil {
return fmt.Errorf("delete request: %v", err) return fmt.Errorf("delete request: %v", err)
} }
@ -210,7 +210,7 @@ func (c *client) delete(resource, name string) error {
return checkHTTPErr(resp, http.StatusOK) return checkHTTPErr(resp, http.StatusOK)
} }
func (c *client) deleteAll(resource string) error { func (cli *client) deleteAll(resource string) error {
var list struct { var list struct {
k8sapi.TypeMeta `json:",inline"` k8sapi.TypeMeta `json:",inline"`
k8sapi.ListMeta `json:"metadata,omitempty"` k8sapi.ListMeta `json:"metadata,omitempty"`
@ -219,24 +219,24 @@ func (c *client) deleteAll(resource string) error {
k8sapi.ObjectMeta `json:"metadata,omitempty"` k8sapi.ObjectMeta `json:"metadata,omitempty"`
} `json:"items"` } `json:"items"`
} }
if err := c.list(resource, &list); err != nil { if err := cli.list(resource, &list); err != nil {
return err return err
} }
for _, item := range list.Items { for _, item := range list.Items {
if err := c.delete(resource, item.Name); err != nil { if err := cli.delete(resource, item.Name); err != nil {
return err return err
} }
} }
return nil return nil
} }
func (c *client) put(resource, name string, v interface{}) error { func (cli *client) put(resource, name string, v interface{}) error {
body, err := json.Marshal(v) body, err := json.Marshal(v)
if err != nil { if err != nil {
return fmt.Errorf("marshal object: %v", err) return fmt.Errorf("marshal object: %v", err)
} }
url := c.urlFor(c.apiVersion, c.namespace, resource, name) url := cli.urlFor(cli.apiVersion, cli.namespace, resource, name)
req, err := http.NewRequest("PUT", url, bytes.NewReader(body)) req, err := http.NewRequest("PUT", url, bytes.NewReader(body))
if err != nil { if err != nil {
return fmt.Errorf("create patch request: %v", err) return fmt.Errorf("create patch request: %v", err)
@ -244,7 +244,7 @@ func (c *client) put(resource, name string, v interface{}) error {
req.Header.Set("Content-Length", strconv.Itoa(len(body))) req.Header.Set("Content-Length", strconv.Itoa(len(body)))
resp, err := c.client.Do(req) resp, err := cli.client.Do(req)
if err != nil { if err != nil {
return fmt.Errorf("patch request: %v", err) return fmt.Errorf("patch request: %v", err)
} }

View file

@ -43,7 +43,7 @@ type CustomResourceDefinitionNames struct {
ListKind string `json:"listKind,omitempty" protobuf:"bytes,5,opt,name=listKind"` ListKind string `json:"listKind,omitempty" protobuf:"bytes,5,opt,name=listKind"`
} }
// ResourceScope is an enum defining the different scopes availabe to a custom resource // ResourceScope is an enum defining the different scopes available to a custom resource
type ResourceScope string type ResourceScope string
const ( const (

View file

@ -311,7 +311,7 @@ func (s *MySQL) open(logger log.Logger) (*conn, error) {
err = db.Ping() err = db.Ping()
if err != nil { if err != nil {
if mysqlErr, ok := err.(*mysql.MySQLError); ok && mysqlErr.Number == mysqlErrUnknownSysVar { if mysqlErr, ok := err.(*mysql.MySQLError); ok && mysqlErr.Number == mysqlErrUnknownSysVar {
logger.Info("reconnecting with MySQL pre-5.7.20 compatibilty mode") logger.Info("reconnecting with MySQL pre-5.7.20 compatibility mode")
// MySQL 5.7.20 introduced transaction_isolation and deprecated tx_isolation. // MySQL 5.7.20 introduced transaction_isolation and deprecated tx_isolation.
// MySQL 8.0 doesn't have tx_isolation at all. // MySQL 8.0 doesn't have tx_isolation at all.

View file

@ -169,7 +169,6 @@ func (c *conn) UpdateAuthRequest(id string, updater func(a storage.AuthRequest)
} }
return nil return nil
}) })
} }
func (c *conn) GetAuthRequest(id string) (storage.AuthRequest, error) { func (c *conn) GetAuthRequest(id string) (storage.AuthRequest, error) {