Skip to content
This repository has been archived by the owner on Dec 7, 2020. It is now read-only.

Commit

Permalink
Linting Errors (#209)
Browse files Browse the repository at this point in the history
- fixing up a number of warming found by the linters
  • Loading branch information
gambol99 committed May 19, 2017
1 parent f262a99 commit 330f96c
Show file tree
Hide file tree
Showing 14 changed files with 44 additions and 103 deletions.
33 changes: 15 additions & 18 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ NAME=keycloak-proxy
AUTHOR=gambol99
AUTHOR_EMAIL[email protected]
REGISTRY=quay.io
GOVERSION ?= 1.8.0
SUDO=
GOVERSION ?= 1.8.1
ROOT_DIR=${PWD}
HARDWARE=$(shell uname -m)
GIT_SHA=$(shell git --no-pager describe --always --dirty)
Expand All @@ -27,39 +26,32 @@ version:

build:
@echo "--> Compiling the project"
mkdir -p bin
@mkdir -p bin
godep go build -ldflags "${LFLAGS}" -o bin/${NAME}

static: golang deps
@echo "--> Compiling the static binary"
mkdir -p bin
@mkdir -p bin
CGO_ENABLED=0 GOOS=linux godep go build -a -tags netgo -ldflags "-w ${LFLAGS}" -o bin/${NAME}

docker-build:
@echo "--> Compiling the project"
${SUDO} docker run --rm -v ${ROOT_DIR}:/go/src/github.com/gambol99/keycloak-proxy \
-w /go/src/github.com/gambol99/keycloak-proxy -e GOOS=linux golang:${GOVERSION} make static
docker run --rm \
-v ${ROOT_DIR}:/go/src/github.com/gambol99/keycloak-proxy \
-w /go/src/github.com/gambol99/keycloak-proxy \
-e GOOS=linux golang:${GOVERSION} \
make static

docker-test:
@echo "--> Running the docker test"
${SUDO} docker run --rm -ti -p 3000:3000 \
docker run --rm -ti -p 3000:3000 \
-v ${ROOT_DIR}/config.yml:/etc/keycloak/config.yml:ro \
-v ${ROOT_DIR}/tests:/opt/tests:ro \
${REGISTRY}/${AUTHOR}/${NAME}:${VERSION} --config /etc/keycloak/config.yml

docker:
@echo "--> Building the docker image"
${SUDO} docker build -t ${REGISTRY}/${AUTHOR}/${NAME}:${VERSION} .

docker-release:
@echo "--> Building a release image"
@make static
@make docker
@docker push ${REGISTRY}/${AUTHOR}/${NAME}:${VERSION}

docker-push:
@echo "--> Pushing the docker images to the registry"
${SUDO} docker push ${REGISTRY}/${AUTHOR}/${NAME}:${VERSION}
docker build -t ${REGISTRY}/${AUTHOR}/${NAME}:${VERSION} .

certs:
@echo "--> Generating the root CA"
Expand Down Expand Up @@ -112,6 +104,10 @@ gofmt:
exit 1; \
fi

verify:
@echo "--> Linting the code"
@gometalinter --disable=errcheck --disable=gocyclo --disable=gas --disable=aligncheck

format:
@echo "--> Running go fmt"
@gofmt -s -w *.go
Expand All @@ -132,6 +128,7 @@ cover:
test: deps
@echo "--> Running the tests"
@godep go test -v
@$(MAKE) golang
@$(MAKE) gofmt
@$(MAKE) vet
@$(MAKE) cover
Expand Down
18 changes: 5 additions & 13 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ import (
func newDefaultConfig() *Config {
return &Config{
AccessTokenDuration: time.Duration(720) * time.Hour,
Tags: make(map[string]string, 0),
MatchClaims: make(map[string]string, 0),
Headers: make(map[string]string, 0),
Tags: make(map[string]string),
MatchClaims: make(map[string]string),
Headers: make(map[string]string),
UpstreamTimeout: time.Duration(10) * time.Second,
UpstreamKeepaliveTimeout: time.Duration(10) * time.Second,
EnableAuthorizationHeader: true,
Expand Down Expand Up @@ -154,18 +154,10 @@ func (r *Config) isValid() error {

// hasCustomSignInPage checks if there is a custom sign in page
func (r *Config) hasCustomSignInPage() bool {
if r.SignInPage != "" {
return true
}

return false
return r.SignInPage != ""
}

// hasForbiddenPage checks if there is a custom forbidden page
func (r *Config) hasCustomForbiddenPage() bool {
if r.ForbiddenPage != "" {
return true
}

return false
return r.ForbiddenPage != ""
}
4 changes: 2 additions & 2 deletions cookies.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ func (r *oauthProxy) clearAllCookies(req *http.Request, w http.ResponseWriter) {

// clearRefreshSessionCookie clears the session cookie
func (r *oauthProxy) clearRefreshTokenCookie(req *http.Request, w http.ResponseWriter) {
r.dropCookie(w, req.Host, r.config.CookieRefreshName, "", time.Duration(-10*time.Hour))
r.dropCookie(w, req.Host, r.config.CookieRefreshName, "", -10*time.Hour)
}

// clearAccessTokenCookie clears the session cookie
func (r *oauthProxy) clearAccessTokenCookie(req *http.Request, w http.ResponseWriter) {
r.dropCookie(w, req.Host, r.config.CookieAccessName, "", time.Duration(-10*time.Hour))
r.dropCookie(w, req.Host, r.config.CookieAccessName, "", -10*time.Hour)
}
10 changes: 5 additions & 5 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (r *oauthProxy) oauthAuthorizationHandler(cx echo.Context) error {

// step: if we have a custom sign in page, lets display that
if r.config.hasCustomSignInPage() {
model := make(map[string]string, 0)
model := make(map[string]string)
model["redirect"] = authURL

return cx.Render(http.StatusOK, path.Base(r.config.SignInPage), mergeMaps(model, r.config.Tags))
Expand Down Expand Up @@ -190,7 +190,7 @@ func (r *oauthProxy) oauthCallbackHandler(cx echo.Context) error {
log.WithFields(log.Fields{
"email": identity.Email,
"expires": identity.ExpiresAt.Format(time.RFC3339),
"duration": identity.ExpiresAt.Sub(time.Now()).String(),
"duration": time.Until(identity.ExpiresAt).String(),
}).Infof("issuing access token for user, email: %s", identity.Email)

// step: does the response has a refresh token and we are NOT ignore refresh tokens?
Expand Down Expand Up @@ -218,11 +218,11 @@ func (r *oauthProxy) oauthCallbackHandler(cx echo.Context) error {
if _, ident, err := parseToken(resp.RefreshToken); err != nil {
r.dropRefreshTokenCookie(cx.Request(), cx.Response().Writer, encrypted, time.Duration(240)*time.Hour)
} else {
r.dropRefreshTokenCookie(cx.Request(), cx.Response().Writer, encrypted, ident.ExpiresAt.Sub(time.Now()))
r.dropRefreshTokenCookie(cx.Request(), cx.Response().Writer, encrypted, time.Until(ident.ExpiresAt))
}
}
} else {
r.dropAccessTokenCookie(cx.Request(), cx.Response().Writer, token.Encode(), identity.ExpiresAt.Sub(time.Now()))
r.dropAccessTokenCookie(cx.Request(), cx.Response().Writer, token.Encode(), time.Until(identity.ExpiresAt))
}

// step: decode the state variable
Expand Down Expand Up @@ -277,7 +277,7 @@ func (r *oauthProxy) loginHandler(cx echo.Context) error {
return "unable to decode the access token", http.StatusNotImplemented, err
}

r.dropAccessTokenCookie(cx.Request(), cx.Response().Writer, token.AccessToken, identity.ExpiresAt.Sub(time.Now()))
r.dropAccessTokenCookie(cx.Request(), cx.Response().Writer, token.AccessToken, time.Until(identity.ExpiresAt))

cx.JSON(http.StatusOK, tokenResponse{
IDToken: token.IDToken,
Expand Down
6 changes: 3 additions & 3 deletions middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func (r *oauthProxy) loggingMiddleware() echo.MiddlewareFunc {
return func(cx echo.Context) error {
start := time.Now()
next(cx)
latency := time.Now().Sub(start)
latency := time.Since(start)
addr := cx.RealIP()
log.WithFields(log.Fields{
"client_ip": addr,
Expand Down Expand Up @@ -236,7 +236,7 @@ func (r *oauthProxy) authenticationMiddleware(resource *Resource) echo.Middlewar

// admissionMiddleware is responsible checking the access token against the protected resource
func (r *oauthProxy) admissionMiddleware(resource *Resource) echo.MiddlewareFunc {
claimMatches := make(map[string]*regexp.Regexp, 0)
claimMatches := make(map[string]*regexp.Regexp)
for k, v := range r.config.MatchClaims {
claimMatches[k] = regexp.MustCompile(v)
}
Expand Down Expand Up @@ -318,7 +318,7 @@ func (r *oauthProxy) admissionMiddleware(resource *Resource) echo.MiddlewareFunc
log.WithFields(log.Fields{
"access": "permitted",
"email": user.email,
"expires": user.expiresAt.Sub(time.Now()).String(),
"expires": time.Until(user.expiresAt).String(),
"resource": resource.URL,
}).Debugf("access permitted to resource")

Expand Down
2 changes: 1 addition & 1 deletion middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func newFakeProxy(c *Config) *fakeProxy {
panic("failed to recreate the openid client, error: " + err.Error())
}

return &fakeProxy{c, auth, proxy, service, make(map[string]*http.Cookie, 0)}
return &fakeProxy{c, auth, proxy, service, make(map[string]*http.Cookie)}
}

// RunTests performs a series of requests against a fake proxy service
Expand Down
2 changes: 1 addition & 1 deletion misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func (r *oauthProxy) getAccessCookieExpiration(token jose.JWT, refresh string) t
// refresh token
duration := r.config.AccessTokenDuration
if _, ident, err := parseToken(refresh); err == nil {
duration = ident.ExpiresAt.Sub(time.Now())
duration = time.Until(ident.ExpiresAt)
}

return duration
Expand Down
2 changes: 1 addition & 1 deletion oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func getUserinfo(client *oauth2.Client, endpoint string, token string) (jose.Cla
return nil, err
}
var claims jose.Claims
if err := json.Unmarshal([]byte(content), &claims); err != nil {
if err := json.Unmarshal(content, &claims); err != nil {
return nil, newAPIError("unable to decode response", resp.StatusCode)
}

Expand Down
4 changes: 2 additions & 2 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ func (r *oauthProxy) createForwardingProxy() error {
// @NOTES, somewhat annoying but goproxy hands back a nil response on proxy client errors
if resp != nil && r.config.EnableLogging {
start := ctx.UserData.(time.Time)
latency := time.Now().Sub(start)
latency := time.Since(start)

log.WithFields(log.Fields{
"method": resp.Request.Method,
Expand Down Expand Up @@ -306,7 +306,7 @@ func (r *oauthProxy) Run() error {
}
httpsvc := &http.Server{
Addr: r.config.ListenHTTP,
Handler: http.Handler(r.router),
Handler: r.router,
}
go func() {
if err := httpsvc.Serve(httpListener); err != nil {
Expand Down
4 changes: 2 additions & 2 deletions server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ func newTestProxyService(config *Config) (*oauthProxy, *fakeAuthServer, string)
func newFakeHTTPRequest(method, path string) *http.Request {
return &http.Request{
Method: method,
Header: make(map[string][]string, 0),
Header: make(map[string][]string),
Host: "127.0.0.1",
URL: &url.URL{
Scheme: "http",
Expand Down Expand Up @@ -319,7 +319,7 @@ type fakeToken struct {
}

func newTestToken(issuer string) *fakeToken {
claims := make(jose.Claims, 0)
claims := make(jose.Claims)
for k, v := range defaultTestTokenClaims {
claims[k] = v
}
Expand Down
2 changes: 1 addition & 1 deletion store_boltdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func newBoltDBStore(location *url.URL) (storage, error) {

log.Infof("creating the bolddb store, file: %s", path)
db, err := bolt.Open(path, 0600, &bolt.Options{
Timeout: time.Duration(10 * time.Second),
Timeout: 10 * time.Second,
})
if err != nil {
return nil, err
Expand Down
6 changes: 1 addition & 5 deletions user_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,7 @@ func extractIdentity(token jose.JWT) (*userContext, error) {

// isAudience checks the audience
func (r *userContext) isAudience(aud string) bool {
if r.audience == aud {
return true
}

return false
return r.audience == aud
}

// getRoles returns a list of roles
Expand Down
48 changes: 5 additions & 43 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ var (
)

var (
httpMethodRegex = regexp.MustCompile("^(ANY|GET|POST|DELETE|PATCH|HEAD|PUT|TRACE)$")
symbolsFilter = regexp.MustCompilePOSIX("[_$><\\[\\].,\\+-/'%^&*()!\\\\]+")
symbolsFilter = regexp.MustCompilePOSIX("[_$><\\[\\].,\\+-/'%^&*()!\\\\]+")
)

// readConfigFile reads and parses the configuration file
Expand Down Expand Up @@ -218,7 +217,7 @@ func newOpenIDClient(cfg *Config) (*oidc.Client, oidc.ProviderConfig, *http.Clie

// decodeKeyPairs converts a list of strings (key=pair) to a map
func decodeKeyPairs(list []string) (map[string]string, error) {
kp := make(map[string]string, 0)
kp := make(map[string]string)

for _, x := range list {
items := strings.Split(x, "=")
Expand Down Expand Up @@ -251,34 +250,6 @@ func defaultTo(v, d string) string {
return d
}

// cloneTLSConfig clones the tls configuration
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return &tls.Config{
Rand: cfg.Rand,
Time: cfg.Time,
Certificates: cfg.Certificates,
NameToCertificate: cfg.NameToCertificate,
GetCertificate: cfg.GetCertificate,
RootCAs: cfg.RootCAs,
NextProtos: cfg.NextProtos,
ServerName: cfg.ServerName,
ClientAuth: cfg.ClientAuth,
ClientCAs: cfg.ClientCAs,
InsecureSkipVerify: cfg.InsecureSkipVerify,
CipherSuites: cfg.CipherSuites,
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
SessionTicketsDisabled: cfg.SessionTicketsDisabled,
SessionTicketKey: cfg.SessionTicketKey,
ClientSessionCache: cfg.ClientSessionCache,
MinVersion: cfg.MinVersion,
MaxVersion: cfg.MaxVersion,
CurvePreferences: cfg.CurvePreferences,
}
}

// fileExists check if a file exists
func fileExists(filename string) bool {
if _, err := os.Stat(filename); err != nil {
Expand Down Expand Up @@ -338,22 +309,13 @@ func tryDialEndpoint(location *url.URL) (net.Conn, error) {

// isUpgradedConnection checks to see if the request is requesting
func isUpgradedConnection(req *http.Request) bool {
if req.Header.Get(headerUpgrade) != "" {
return true
}

return false
return req.Header.Get(headerUpgrade) != ""
}

// transferBytes transfers bytes between the sink and source
func transferBytes(src io.Reader, dest io.Writer, wg *sync.WaitGroup) (int64, error) {
defer wg.Done()
copied, err := io.Copy(dest, src)
if err != nil {
return copied, err
}

return copied, nil
return io.Copy(dest, src)
}

// tryUpdateConnection attempt to upgrade the connection to a http pdy stream
Expand Down Expand Up @@ -473,7 +435,7 @@ func getWithin(expires time.Time, within float64) time.Duration {
if left <= 0 {
return time.Duration(0)
}
seconds := int(float64(left * within))
seconds := int(left * within)

return time.Duration(seconds) * time.Second
}
Expand Down
6 changes: 0 additions & 6 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package main

import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
Expand Down Expand Up @@ -247,11 +246,6 @@ func BenchmarkContainsSubString(t *testing.B) {
}
}

func TestCloneTLSConfig(t *testing.T) {
assert.NotNil(t, cloneTLSConfig(nil))
assert.NotNil(t, cloneTLSConfig(&tls.Config{}))
}

func TestDialAddress(t *testing.T) {
assert.Equal(t, dialAddress(getFakeURL("http://127.0.0.1")), "127.0.0.1:80")
assert.Equal(t, dialAddress(getFakeURL("https://127.0.0.1")), "127.0.0.1:443")
Expand Down

0 comments on commit 330f96c

Please sign in to comment.