Skip to content
This repository has been archived by the owner on Jul 30, 2024. It is now read-only.

Commit

Permalink
Merge pull request #73 from YannikBramkamp/task/update-deps
Browse files Browse the repository at this point in the history
update deps; use cache implementation
  • Loading branch information
Lucaber authored Jan 11, 2024
2 parents f51992e + 160b676 commit 451ee3c
Show file tree
Hide file tree
Showing 29 changed files with 367 additions and 204 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
go-version: 1.21

- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
go-version: 1.21

- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
Expand All @@ -40,4 +40,4 @@ jobs:
chartYaml: './deploy/helm-chart/servicegateway/Chart.yaml'
env:
GITHUB_TOKEN: "${{ secrets.RELEASE_USER_TOKEN }}"
HELM_REPO_PASSWORD: "${{ secrets.HELM_REPO_PASSWORD }}"
HELM_REPO_PASSWORD: "${{ secrets.HELM_REPO_PASSWORD }}"
18 changes: 14 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
GO_VERSION=1.15
GO_VERSION=1.21.4
PKG_LIST := $(shell go list ./... | grep -v /vendor/)
GOLANGCI_VERSION := "0.0.33"

all: dep build-static

lint:
golangci-lint run
docker run --rm -t \
-v $(shell go env GOPATH):/go \
-v ${CURDIR}:/app \
-v $(HOME)/.cache:/home/mittwald-golangci/.cache \
-w /app \
-e GOFLAGS="-buildvcs=false" \
quay.io/mittwald/golangci-lint:$(GOLANGCI_VERSION) \
golangci-lint run -v --fix ./...

dep:
go get && go mod vendor -v
go mod download
go mod tidy


build-static:
CGO_ENABLED=0 GOOS=linux go build -o servicegateway
Expand All @@ -20,4 +30,4 @@ docker:
docker build -t mittwald/servicegateway .

fmt:
go fmt ${PKG_LIST}
go fmt ${PKG_LIST}
27 changes: 14 additions & 13 deletions admin/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package admin
import (
"encoding/json"
"fmt"
"github.com/go-zoo/bone"
"github.com/mittwald/servicegateway/auth"
"github.com/op/go-logging"
"io/ioutil"
"net/http"
"net/url"
"time"

"github.com/go-zoo/bone"
"github.com/mittwald/servicegateway/auth"
"github.com/op/go-logging"
)

func writeError(res http.ResponseWriter, msg string) {
Expand Down Expand Up @@ -62,7 +63,7 @@ func NewAdminServer(

if req.Header.Get("Content-Type") != "application/jwt" {
res.WriteHeader(415)
_ , _ = res.Write([]byte(`{"msg":"only 'application/jwt' is allowed as content-type"}`))
_, _ = res.Write([]byte(`{"msg":"only 'application/jwt' is allowed as content-type"}`))
return
}

Expand All @@ -78,7 +79,7 @@ func NewAdminServer(
valid, _, _, err := tokenVerifier.VerifyToken(jwt)
if err != nil || !valid {
res.WriteHeader(400)
_ , _ = res.Write([]byte(fmt.Sprintf(`{"msg":"invalid token","reason":"%s"}`, err)))
_, _ = res.Write([]byte(fmt.Sprintf(`{"msg":"invalid token","reason":"%s"}`, err)))
return
}

Expand All @@ -88,16 +89,16 @@ func NewAdminServer(
if err != nil {
logger.Errorf("error while storing token: %s", err)
res.WriteHeader(500)
_ , _ = res.Write([]byte(`{"msg":"could not store token"}`))
_, _ = res.Write([]byte(`{"msg":"could not store token"}`))
return
}

res.WriteHeader(200)

if exp != 0 {
_ , _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s","expires":"%s"}`, tokenString, time.Unix(exp, 0).Format(time.RFC3339))))
_, _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s","expires":"%s"}`, tokenString, time.Unix(exp, 0).Format(time.RFC3339))))
} else {
_ , _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s"}`, tokenString)))
_, _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s"}`, tokenString)))
}
}))

Expand All @@ -106,7 +107,7 @@ func NewAdminServer(

if req.Header.Get("Content-Type") != "application/jwt" {
res.WriteHeader(415)
_ , _ = res.Write([]byte(`{"msg":"only 'application/jwt' is allowed as content-type"}`))
_, _ = res.Write([]byte(`{"msg":"only 'application/jwt' is allowed as content-type"}`))
return
}

Expand All @@ -122,23 +123,23 @@ func NewAdminServer(
valid, _, _, err := tokenVerifier.VerifyToken(jwt)
if err != nil || !valid {
res.WriteHeader(400)
_ , _ = res.Write([]byte(fmt.Sprintf(`{"msg":"invalid token","reason":"%s"}`, err)))
_, _ = res.Write([]byte(fmt.Sprintf(`{"msg":"invalid token","reason":"%s"}`, err)))
return
}

tokenString, exp, err := tokenStore.AddToken(&auth.JWTResponse{JWT: jwt})
if err != nil {
logger.Errorf("error while storing token: %s", err)
res.WriteHeader(500)
_ , _ = res.Write([]byte(`{"msg":"could not store token"}`))
_, _ = res.Write([]byte(`{"msg":"could not store token"}`))
return
}

res.WriteHeader(200)
if exp != 0 {
_ , _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s","expires":"%s"}`, tokenString, time.Unix(exp, 0).Format(time.RFC3339))))
_, _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s","expires":"%s"}`, tokenString, time.Unix(exp, 0).Format(time.RFC3339))))
} else {
_ , _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s"}`, tokenString)))
_, _ = res.Write([]byte(fmt.Sprintf(`{"token":"%s"}`, tokenString)))
}
}))

Expand Down
2 changes: 1 addition & 1 deletion auth/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
"net/http"
"reflect"

"github.com/garyburd/redigo/redis"
"github.com/gomodule/redigo/redis"
"github.com/julienschmidt/httprouter"
"github.com/mittwald/servicegateway/config"
"github.com/op/go-logging"
Expand Down
36 changes: 12 additions & 24 deletions auth/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ import (
"io"
"net/http"
"strings"
"sync"
"time"

"github.com/dgrijalva/jwt-go"
"github.com/garyburd/redigo/redis"
"github.com/gomodule/redigo/redis"
"github.com/mittwald/servicegateway/config"
"github.com/op/go-logging"
cache "github.com/patrickmn/go-cache"
"github.com/robertkrimen/otto"
)

Expand All @@ -46,8 +46,7 @@ type AuthenticationHandler struct {

hookPreAuth *otto.Script

expCache map[string]int64
expLock sync.RWMutex
expCache *cache.Cache

jsVM *otto.Otto
}
Expand All @@ -71,8 +70,7 @@ func NewAuthenticationHandler(
httpClient: &http.Client{},
logger: logger,
verifier: verifier,
expCache: make(map[string]int64),
expLock: sync.RWMutex{},
expCache: cache.New(cache.NoExpiration, 5*time.Minute),
}

if cfg.ProviderConfig.PreAuthenticationHook != "" {
Expand Down Expand Up @@ -258,34 +256,24 @@ func (h *AuthenticationHandler) IsAuthenticated(req *http.Request) (bool, *JWTRe
return false, nil, err
}

h.expLock.RLock()
exp, ok := h.expCache[token.JWT]
h.expLock.RUnlock()
exp, ok := h.expCache.Get(token.JWT)
var expiry int64
if ok {
expiry = exp.(int64)
}

if ok && (exp == 0 || exp > time.Now().Unix()) {
if ok && (exp == 0 || expiry > time.Now().Unix()) {
return true, token, nil
} else if !ok {
valid, stdClaims, _, err := h.verifier.VerifyToken(token.JWT)
if err == nil && valid {
if stdClaims.ExpiresAt == 0 {
h.expLock.Lock()
h.expCache[token.JWT] = 0
h.expLock.Unlock()
h.expCache.Set(token.JWT, 0, cache.NoExpiration)
return true, token, nil
}

if stdClaims.ExpiresAt > time.Now().Unix() {
h.expLock.Lock()
h.expCache[token.JWT] = stdClaims.ExpiresAt
h.expLock.Unlock()

c := time.After(time.Duration(stdClaims.ExpiresAt-time.Now().Unix()) * time.Second)
go func() {
<-c
h.expLock.Lock()
delete(h.expCache, token.JWT)
h.expLock.Unlock()
}()
h.expCache.Set(token.JWT, stdClaims.ExpiresAt, time.Duration(stdClaims.ExpiresAt-time.Now().Unix())*time.Second)

return true, token, nil
}
Expand Down
1 change: 1 addition & 0 deletions auth/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package auth

import (
"fmt"

"github.com/dgrijalva/jwt-go"
"github.com/mittwald/servicegateway/config"

Expand Down
6 changes: 1 addition & 5 deletions auth/rest.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ func rewriteBodyAccessTokens(resp *httptest.ResponseRecorder, req *http.Request,
return err
}

contentLength, err := resp.Write([]byte(token))
contentLength, err := resp.WriteString(token)
if err != nil {
return err
}
Expand All @@ -316,7 +316,6 @@ func rewriteBodyAccessTokens(resp *httptest.ResponseRecorder, req *http.Request,
// rewrite body tokens
bodyTokenKey := resp.Header().Get("X-Gateway-BodyToken")
if bodyTokenKey != "" {

var response map[string]interface{}
jsonBlob, err := io.ReadAll(resp.Body)
if err != nil {
Expand Down Expand Up @@ -359,10 +358,8 @@ func rewriteBodyAccessTokens(resp *httptest.ResponseRecorder, req *http.Request,
}

func rewriteHeaderAccessTokens(resp *httptest.ResponseRecorder, req *http.Request, a *RestAuthDecorator) error {

headerTokenKey := resp.Header().Get("X-Gateway-HeaderToken")
if headerTokenKey != "" {

header := resp.Header().Get(headerTokenKey)

jwtResponse := JWTResponse{}
Expand All @@ -382,7 +379,6 @@ func rewriteHeaderAccessTokens(resp *httptest.ResponseRecorder, req *http.Reques
func rewriteCookieAccessTokens(resp *httptest.ResponseRecorder, req *http.Request, a *RestAuthDecorator) error {
cookieTokenKey := resp.Header().Get("X-Gateway-CookieToken")
if cookieTokenKey != "" {

cookie := parseCookie(resp, cookieTokenKey)

if cookie == nil {
Expand Down
5 changes: 3 additions & 2 deletions auth/tokenstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@ import (
"crypto/rand"
"encoding/base32"
"fmt"
"github.com/garyburd/redigo/redis"
"github.com/hashicorp/golang-lru"
"strings"

"github.com/gomodule/redigo/redis"
lru "github.com/hashicorp/golang-lru"
)

type MappedToken struct {
Expand Down
1 change: 1 addition & 0 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ package cache
import (
"bytes"
"fmt"

"github.com/bluele/gcache"
"github.com/julienschmidt/httprouter"

Expand Down
3 changes: 2 additions & 1 deletion config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ package config

import (
"fmt"
"github.com/garyburd/redigo/redis"

"github.com/gomodule/redigo/redis"
"github.com/hashicorp/consul/api"
)

Expand Down
6 changes: 3 additions & 3 deletions dispatcher/behaviours.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type ratelimitBehaviour struct {
rlim ratelimit.RateLimitingMiddleware
}

func NewCachingBehaviour(c cache.CacheMiddleware) Behaviour {
func NewCachingBehaviour(c cache.CacheMiddleware) Behavior {
return &cachingBehaviour{c}
}

Expand All @@ -54,7 +54,7 @@ func (c *cachingBehaviour) Apply(safe httprouter.Handle, unsafe httprouter.Handl
return safe, unsafe, nil
}

func NewAuthenticationBehaviour(a auth.AuthDecorator) Behaviour {
func NewAuthenticationBehaviour(a auth.AuthDecorator) Behavior {
return &authBehaviour{a}
}

Expand All @@ -70,7 +70,7 @@ func (a *authBehaviour) AddRoutes(mux *httprouter.Router) error {
return a.auth.RegisterRoutes(mux)
}

func NewRatelimitBehaviour(rlim ratelimit.RateLimitingMiddleware) Behaviour {
func NewRatelimitBehaviour(rlim ratelimit.RateLimitingMiddleware) Behavior {
return &ratelimitBehaviour{rlim}
}

Expand Down
13 changes: 7 additions & 6 deletions dispatcher/consul_dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package dispatcher
import (
"encoding/json"
"fmt"
"github.com/garyburd/redigo/redis"

"github.com/gomodule/redigo/redis"
"github.com/hashicorp/consul/api"
"github.com/julienschmidt/httprouter"
"github.com/mittwald/servicegateway/admin"
Expand Down Expand Up @@ -97,8 +98,8 @@ func BuildConsulDispatcher(

cch := cache.NewCache(4096)

// Order is important here! Behaviours will be called in LIFO order;
// behaviours that are added last will be called first!
// Order is important here! Behaviors will be called in LIFO order;
// behaviors that are added last will be called first!
disp.AddBehaviour(NewCachingBehaviour(cch))
disp.AddBehaviour(NewAuthenticationBehaviour(authDecorator))
disp.AddBehaviour(NewRatelimitBehaviour(rlim))
Expand Down Expand Up @@ -165,7 +166,7 @@ func buildConsulPathDispatcher(
dispatcher.mux = httprouter.New()
dispatcher.log = log
dispatcher.prx = prx
dispatcher.behaviours = make([]Behaviour, 0, 8)
dispatcher.behaviors = make([]Behavior, 0, 8)

return dispatcher, nil
}
Expand Down Expand Up @@ -229,9 +230,9 @@ func (c *consulPathDispatcher) RegisterApplication(name string, appCfg config.Ap
safeHandler := handler
unsafeHandler := handler

for _, behaviour := range c.behaviours {
for _, behavior := range c.behaviors {
var err error
safeHandler, unsafeHandler, err = behaviour.Apply(safeHandler, unsafeHandler, c, name, &appCfg, config)
safeHandler, unsafeHandler, err = behavior.Apply(safeHandler, unsafeHandler, c, name, &appCfg, config)
if err != nil {
return err
}
Expand Down
Loading

0 comments on commit 451ee3c

Please sign in to comment.