Compare commits

...

15 Commits

8 changed files with 1138 additions and 15 deletions

101
basic_auth.go Normal file
View File

@ -0,0 +1,101 @@
package middleware
import (
"encoding/base64"
"strconv"
"strings"
http "github.com/valyala/fasthttp"
)
type (
BasicAuthConfig struct {
Skipper Skipper
Validator BasicAuthValidator
Realm string
}
BasicAuthValidator func(ctx *http.RequestCtx, login, password string) (bool, error)
)
const DefaultRealm string = "Restricted"
const basic string = "basic"
//nolint: gochecknoglobals
var DefaultBasicAuthConfig = BasicAuthConfig{
Skipper: DefaultSkipper,
Realm: DefaultRealm,
}
func BasicAuth(validator BasicAuthValidator) Interceptor {
cfg := DefaultBasicAuthConfig
cfg.Validator = validator
return BasicAuthWithConfig(cfg)
}
func BasicAuthWithConfig(config BasicAuthConfig) Interceptor {
// Defaults
if config.Validator == nil {
panic("middleware: basic-auth middleware requires a validator function")
}
if config.Skipper == nil {
config.Skipper = DefaultBasicAuthConfig.Skipper
}
if config.Realm == "" {
config.Realm = DefaultRealm
}
return func(ctx *http.RequestCtx, next http.RequestHandler) {
if config.Skipper(ctx) {
next(ctx)
return
}
auth := ctx.Request.Header.Peek(http.HeaderAuthorization)
l := len(basic)
if len(auth) > l+1 && strings.EqualFold(string(auth[:l]), basic) {
b, err := base64.StdEncoding.DecodeString(string(auth[l+1:]))
if err != nil {
ctx.Error(err.Error(), http.StatusBadRequest)
return
}
cred := string(b)
for i := 0; i < len(cred); i++ {
if cred[i] == ':' {
// NOTE(toby3d): verify credentials.
valid, err := config.Validator(ctx, cred[:i], cred[i+1:])
if err != nil {
ctx.Error(err.Error(), http.StatusBadRequest)
return
}
if valid {
next(ctx)
return
}
break
}
}
}
realm := DefaultRealm
if config.Realm != DefaultRealm {
realm = strconv.Quote(config.Realm)
}
// NOTE(toby3d): require 401 status for login pop-up.
ctx.SetStatusCode(http.StatusUnauthorized)
ctx.Response.Header.Set(http.HeaderWWWAuthenticate, basic+" realm="+realm)
}
}

239
csrf.go Normal file
View File

@ -0,0 +1,239 @@
package middleware
import (
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"time"
http "github.com/valyala/fasthttp"
)
// CSRFConfig defines the config for CSRF middleware.
type CSRFConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Indicates SameSite mode of the CSRF cookie.
//
// Optional. Default value SameSiteDefaultMode.
CookieSameSite http.CookieSameSite
// Context key to store generated CSRF token into context.
//
// Optional. Default value "csrf".
ContextKey string
// Domain of the CSRF cookie.
//
// Optional. Default value none.
CookieDomain string
// Name of the CSRF cookie. This cookie will store CSRF token.
//
// Optional. Default value "csrf".
CookieName string
// Path of the CSRF cookie.
//
// Optional. Default value none.
CookiePath string
// TokenLookup is a string in the form of "<source>:<key>" that is used
// to extract token from the request.
// Possible values:
// - "header:<name>"
// - "form:<name>"
// - "query:<name>"
//
// Optional. Default value "header:X-CSRF-Token".
TokenLookup string
// Max age (in seconds) of the CSRF cookie.
//
// Optional. Default value 86400 (24hr).
CookieMaxAge int
// TokenLength is the length of the generated token.
//
// Optional. Default value 32.
TokenLength int
// Indicates if CSRF cookie is secure.
//
// Optional. Default value false.
CookieSecure bool
// Indicates if CSRF cookie is HTTP only.
//
// Optional. Default value false.
CookieHTTPOnly bool
}
const (
ExtractorLimit int = 20
// HeaderXCSRFToken describes the name of the header with the CSRF token.
HeaderXCSRFToken string = "X-CSRF-Token"
)
var (
ErrCSRFInvalid = errors.New("invalid csrf token")
// DefaultCSRFConfig contains the default CSRF middleware configuration.
//nolint: gochecknoglobals, gomnd
DefaultCSRFConfig = CSRFConfig{
Skipper: DefaultSkipper,
CookieMaxAge: 86400,
CookieSameSite: http.CookieSameSiteDefaultMode,
ContextKey: "csrf",
CookieDomain: "",
CookieName: "_csrf",
CookiePath: "",
TokenLookup: "header:" + HeaderXCSRFToken,
TokenLength: 32,
CookieSecure: true,
CookieHTTPOnly: false,
}
)
// CSRF returns a Cross-Site Request Forgery (CSRF) middleware.
func CSRF() Interceptor {
config := DefaultCSRFConfig
return CSRFWithConfig(config)
}
// CSRFWithConfig returns a CSRF middleware with config.
//nolint: funlen, cyclop
func CSRFWithConfig(config CSRFConfig) Interceptor {
if config.Skipper == nil {
config.Skipper = DefaultCSRFConfig.Skipper
}
if config.TokenLength == 0 {
config.TokenLength = DefaultCSRFConfig.TokenLength
}
if config.TokenLookup == "" {
config.TokenLookup = DefaultCSRFConfig.TokenLookup
}
if config.ContextKey == "" {
config.ContextKey = DefaultCSRFConfig.ContextKey
}
if config.CookieName == "" {
config.CookieName = DefaultCSRFConfig.CookieName
}
if config.CookieMaxAge == 0 {
config.CookieMaxAge = DefaultCSRFConfig.CookieMaxAge
}
if config.CookieSameSite == http.CookieSameSiteNoneMode {
config.CookieSecure = DefaultCSRFConfig.CookieSecure
}
extractors, err := createExtractors(config.TokenLookup, "")
if err != nil {
panic("middleware: csrf: " + err.Error())
}
return func(ctx *http.RequestCtx, next http.RequestHandler) {
if config.Skipper(ctx) {
next(ctx)
return
}
var token []byte
if k := ctx.Request.Header.Cookie(config.CookieName); k != nil {
token = k
} else {
token = make([]byte, config.TokenLength)
if _, err := rand.Read(token); err != nil {
ctx.Error(err.Error(), http.StatusInternalServerError)
return
}
token = []byte(base64.RawURLEncoding.EncodeToString(token))
}
switch {
case ctx.IsGet(), ctx.IsHead(), ctx.IsOptions(), ctx.IsTrace():
default:
var lastExtractorErr, lastTokenErr error
outer:
for _, extractor := range extractors {
clientTokens, err := extractor(ctx)
if err != nil {
lastExtractorErr = err
continue
}
for _, clientToken := range clientTokens {
if !validateCSRFToken(token, clientToken) {
lastTokenErr = ErrCSRFInvalid
continue
}
lastTokenErr, lastExtractorErr = nil, nil
break outer
}
}
if lastTokenErr != nil {
ctx.Error(lastTokenErr.Error(), http.StatusInternalServerError)
return
} else if lastExtractorErr != nil {
ctx.Error(lastExtractorErr.Error(), http.StatusBadRequest)
return
}
}
// NOTE(toby3d): set CSRF cookie
cookie := http.AcquireCookie()
defer http.ReleaseCookie(cookie)
cookie.SetKey(config.CookieName)
cookie.SetValueBytes(token)
if config.CookiePath != "" {
cookie.SetPath(config.CookiePath)
}
if config.CookieDomain != "" {
cookie.SetDomain(config.CookieDomain)
}
if config.CookieSameSite != http.CookieSameSiteDefaultMode {
cookie.SetSameSite(config.CookieSameSite)
}
cookie.SetExpire(time.Now().Add(time.Duration(config.CookieMaxAge) * time.Second))
cookie.SetSecure(config.CookieSecure)
cookie.SetHTTPOnly(config.CookieHTTPOnly)
ctx.Response.Header.SetCookie(cookie)
// NOTE(toby3d): store token in the context
ctx.SetUserValue(config.ContextKey, token)
// NOTE(toby3d): protect clients from caching the response
ctx.Response.Header.Add(http.HeaderVary, http.HeaderCookie)
next(ctx)
}
}
func validateCSRFToken(token, clientToken []byte) bool {
return subtle.ConstantTimeCompare(token, clientToken) == 1
}

177
extractor.go Normal file
View File

@ -0,0 +1,177 @@
package middleware
import (
"bytes"
"errors"
"fmt"
"net/textproto"
"strings"
http "github.com/valyala/fasthttp"
)
// ValuesExtractor defines a function for extracting values (keys/tokens) from
// the given context.
type ValuesExtractor func(ctx *http.RequestCtx) ([][]byte, error)
const (
// extractorLimit is arbitrary number to limit values extractor can
// return. this limits possible resource exhaustion attack vector.
extractorLimit = 20
)
var (
errHeaderExtractorValueMissing = errors.New("missing value in request header")
errHeaderExtractorValueInvalid = errors.New("invalid value in request header")
errQueryExtractorValueMissing = errors.New("missing value in the query string")
errParamExtractorValueMissing = errors.New("missing value in path params")
errCookieExtractorValueMissing = errors.New("missing value in cookies")
errFormExtractorValueMissing = errors.New("missing value in the form")
)
func createExtractors(lookups, authScheme string) ([]ValuesExtractor, error) {
if lookups == "" {
return nil, nil
}
sources := strings.Split(lookups, ",")
extractors := make([]ValuesExtractor, 0)
for _, source := range sources {
parts := strings.Split(source, ":")
if len(parts) < 2 {
return nil, fmt.Errorf("extractor source for lookup could not be split into needed parts: %s",
source)
}
switch parts[0] {
case "query":
extractors = append(extractors, valuesFromQuery(parts[1]))
case "param":
extractors = append(extractors, valuesFromParam(parts[1]))
case "cookie":
extractors = append(extractors, valuesFromCookie(parts[1]))
case "form":
extractors = append(extractors, valuesFromForm(parts[1]))
case "header":
prefix := ""
if len(parts) > 2 {
prefix = parts[2]
} else if authScheme != "" && parts[1] == http.HeaderAuthorization {
// backwards compatibility for JWT and KeyAuth:
// * we only apply this fix to Authorization as header we use and uses prefixes like "Bearer <token-value>" etc
// * previously header extractor assumed that auth-scheme/prefix had a space as suffix we need to retain that
// behaviour for default values and Authorization header.
prefix = authScheme
if !strings.HasSuffix(prefix, " ") {
prefix += " "
}
}
extractors = append(extractors, valuesFromHeader(parts[1], prefix))
}
}
return extractors, nil
}
// valuesFromHeader returns a functions that extracts values from the request header.
// valuePrefix is parameter to remove first part (prefix) of the extracted value. This is useful if header value has static
// prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we want to remove is `<auth-scheme> `
// note the space at the end. In case of basic authentication `Authorization: Basic <credentials>` prefix we want to remove
// is `Basic `. In case of JWT tokens `Authorization: Bearer <token>` prefix is `Bearer `.
// If prefix is left empty the whole value is returned.
func valuesFromHeader(header, valuePrefix string) ValuesExtractor {
prefixLen := len(valuePrefix)
// standard library parses http.Request header keys in canonical form but we may provide something else so fix this
header = textproto.CanonicalMIMEHeaderKey(header)
return func(ctx *http.RequestCtx) ([][]byte, error) {
value := ctx.Request.Header.Peek(header)
if len(value) == 0 {
return nil, errHeaderExtractorValueMissing
}
if prefixLen == 0 {
return append([][]byte{}, value), nil
}
if len(value) > prefixLen && bytes.EqualFold(value[:prefixLen], []byte(valuePrefix)) {
return append([][]byte{}, value[prefixLen:]), nil
}
return nil, errHeaderExtractorValueInvalid
}
}
// valuesFromQuery returns a function that extracts values from the query string.
func valuesFromQuery(param string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
if !ctx.QueryArgs().Has(param) {
return nil, errQueryExtractorValueMissing
}
result := ctx.QueryArgs().PeekMulti(param)
if len(result) > extractorLimit-1 {
result = result[:extractorLimit]
}
return result, nil
}
}
// valuesFromParam returns a function that extracts values from the url param string.
func valuesFromParam(param string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
if !ctx.PostArgs().Has(param) {
return nil, errParamExtractorValueMissing
}
result := ctx.PostArgs().PeekMulti(param)
if len(result) > extractorLimit-1 {
result = result[:extractorLimit]
}
return result, nil
}
}
// valuesFromCookie returns a function that extracts values from the named cookie.
func valuesFromCookie(name string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
if value := ctx.Request.Header.Cookie(name); len(value) != 0 {
return append([][]byte{}, value), nil
}
return nil, errCookieExtractorValueMissing
}
}
// valuesFromForm returns a function that extracts values from the form field.
func valuesFromForm(name string) ValuesExtractor {
return func(ctx *http.RequestCtx) ([][]byte, error) {
form, err := ctx.MultipartForm()
if err != nil {
return nil, fmt.Errorf("valuesFromForm parse form failed: %w", err)
}
values := form.Value[name]
switch {
case len(values) == 0:
return nil, errFormExtractorValueMissing
case len(values) > extractorLimit-1:
values = values[:extractorLimit]
}
result := make([][]byte, 0)
for i := range values {
result = append(result, []byte(values[i]))
}
return result, nil
}
}

21
go.mod
View File

@ -2,10 +2,27 @@ module source.toby3d.me/toby3d/middleware
go 1.17
require github.com/valyala/fasthttp v1.31.0
require (
github.com/fasthttp/session/v2 v2.4.11
github.com/go-logfmt/logfmt v0.5.1
github.com/lestrrat-go/jwx/v2 v2.0.2
github.com/valyala/fasthttp v1.37.0
)
require (
github.com/andybalholm/brotli v1.0.4 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
github.com/goccy/go-json v0.9.7 // indirect
github.com/klauspost/compress v1.15.6 // indirect
github.com/lestrrat-go/blackmagic v1.0.1 // indirect
github.com/lestrrat-go/httpcc v1.0.1 // indirect
github.com/lestrrat-go/httprc v1.0.1 // indirect
github.com/lestrrat-go/iter v1.0.2 // indirect
github.com/lestrrat-go/option v1.0.0 // indirect
github.com/philhofer/fwd v1.1.1 // indirect
github.com/savsgio/dictpool v0.0.0-20220406081701-03de5edb2e6d // indirect
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d // indirect
github.com/tinylib/msgp v1.1.6 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e // indirect
)

159
go.sum
View File

@ -1,24 +1,157 @@
github.com/andybalholm/brotli v1.0.2 h1:JKnhI/XQ75uFBTiuzXpzFrUriDPiZjlOSzh6wXogP0E=
github.com/andybalholm/brotli v1.0.2/go.mod h1:loMXtMfwqflxFJPmdbJO0a3KNoPuLBgiu3qAvBg8x/Y=
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/klauspost/compress v1.13.4 h1:0zhec2I8zGnjWcKyLl6i3gPqKANCCn5e9xmviEEeX6s=
github.com/klauspost/compress v1.13.4/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg=
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc=
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fasthttp/session/v2 v2.4.11 h1:ZPiKk0pkBl7umMVq1nOdvRgjn9Kfc5RzusPjnYckP84=
github.com/fasthttp/session/v2 v2.4.11/go.mod h1:mHFWv73p5vYJaTZQDPokykT4GVOxfOoHGag/DlX8FzU=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/go-logfmt/logfmt v0.5.1 h1:otpy5pqBCBZ1ng9RQ0dPu4PN7ba75Y/aA+UpowDyNVA=
github.com/go-logfmt/logfmt v0.5.1/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/goccy/go-json v0.9.7 h1:IcB+Aqpx/iMHu5Yooh7jEzJk1JZ7Pjtmys2ukPr7EeM=
github.com/goccy/go-json v0.9.7/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/klauspost/compress v1.15.6 h1:6D9PcO8QWu0JyaQ2zUMmu16T1T+zjjEpP91guRsvDfY=
github.com/klauspost/compress v1.15.6/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU=
github.com/lestrrat-go/blackmagic v1.0.1 h1:lS5Zts+5HIC/8og6cGHb0uCcNCa3OUt1ygh3Qz2Fe80=
github.com/lestrrat-go/blackmagic v1.0.1/go.mod h1:UrEqBzIR2U6CnzVyUtfM6oZNMt/7O7Vohk2J0OGSAtU=
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
github.com/lestrrat-go/httprc v1.0.1 h1:Cnc4NxIySph38pQPzKbjg5OkKsGR/Cf5xcWt5OlSUDI=
github.com/lestrrat-go/httprc v1.0.1/go.mod h1:5Ml+nB++j6IC0e6LzefJnrpMQDKgDwDCaIQQzhbqhJM=
github.com/lestrrat-go/iter v1.0.2 h1:gMXo1q4c2pHmC3dn8LzRhJfP1ceCbgSiT9lUydIzltI=
github.com/lestrrat-go/iter v1.0.2/go.mod h1:Momfcq3AnRlRjI5b5O8/G5/BvpzrhoFTZcn06fEOPt4=
github.com/lestrrat-go/jwx/v2 v2.0.2 h1:wkq9jwCkF3xrykISzn0Eksd7NEMOZ9yvCdnEpovIJX8=
github.com/lestrrat-go/jwx/v2 v2.0.2/go.mod h1:xV8+xRcrKbmnScV8adOzUuuTrL8aAZJoY4q2JAqIYU8=
github.com/lestrrat-go/option v1.0.0 h1:WqAWL8kh8VcSoD6xjSH34/1m8yxluXQbDeKNfvFeEO4=
github.com/lestrrat-go/option v1.0.0/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
github.com/lib/pq v1.10.6/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.13/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/ginkgo/v2 v2.0.0/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
github.com/philhofer/fwd v1.1.1 h1:GdGcTjf5RNAxwS4QLsiMzJYj5KEvPJD3Abr261yRQXQ=
github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/savsgio/dictpool v0.0.0-20220406081701-03de5edb2e6d h1:ICMDEgNgR5xFW6ZDeMKTtmh07YiLr7GkDw897I2DwKg=
github.com/savsgio/dictpool v0.0.0-20220406081701-03de5edb2e6d/go.mod h1:jrsy/bTK2n5uybo7bAvtLGzmuzAbxp+nKS8bzgrZURE=
github.com/savsgio/gotils v0.0.0-20220401102855-e56b59f40436/go.mod h1:Gy+0tqhJvgGlqnTF8CVGP0AaGRjwBtXs/a5PA0Y3+A4=
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d h1:Q+gqLBOPkFGHyCJxXMRqtUgUbTjI8/Ze8vu8GGyNFwo=
github.com/savsgio/gotils v0.0.0-20220530130905-52f3993e8d6d/go.mod h1:Gy+0tqhJvgGlqnTF8CVGP0AaGRjwBtXs/a5PA0Y3+A4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/tinylib/msgp v1.1.6 h1:i+SbKraHhnrf9M5MYmvQhFnbLhAXSDWF8WWsuyRdocw=
github.com/tinylib/msgp v1.1.6/go.mod h1:75BAfg2hauQhs3qedfdDZmWAPcFMAvJE5b9rGOMufyw=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.31.0 h1:lrauRLII19afgCs2fnWRJ4M5IkV0lo2FqA61uGkNBfE=
github.com/valyala/fasthttp v1.31.0/go.mod h1:2rsYD01CKFrjjsvFxx75KlEUNpWNBY9JWD3K/7o2Cus=
github.com/valyala/fasthttp v1.37.0 h1:7WHCyI7EAkQMVmrfBhWTCOaeROb1aCBiTopx63LkMbE=
github.com/valyala/fasthttp v1.37.0/go.mod h1:t/G+3rLek+CyY9bnIE+YlMRddxVAAGjhxndDB4i4C0I=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220427172511-eb4f295cb31f/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM=
golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

301
jwt.go Normal file
View File

@ -0,0 +1,301 @@
package middleware
import (
"errors"
"fmt"
"github.com/lestrrat-go/jwx/v2/jwa"
"github.com/lestrrat-go/jwx/v2/jwt"
http "github.com/valyala/fasthttp"
)
type (
// JWTConfig defines the config for JWT middleware.
JWTConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// BeforeFunc defines a function which is executed just before
// the middleware.
BeforeFunc BeforeFunc
// SuccessHandler defines a function which is executed for a
// valid token.
SuccessHandler JWTSuccessHandler
// ErrorHandler defines a function which is executed for an
// invalid token. It may be used to define a custom JWT error.
ErrorHandler JWTErrorHandler
// ErrorHandlerWithContext is almost identical to ErrorHandler,
// but it's passed the current context.
ErrorHandlerWithContext JWTErrorHandlerWithContext
// Signing key to validate token.
// This is one of the three options to provide a token
// validation key. The order of precedence is a user-defined
// KeyFunc, SigningKeys and SigningKey.
//
// Required if neither user-defined KeyFunc nor SigningKeys is
// provided.
SigningKey interface{}
// Map of signing keys to validate token with kid field usage.
// This is one of the three options to provide a token
// validation key. The order of precedence is a user-defined
// KeyFunc, SigningKeys and SigningKey.
//
// Required if neither user-defined KeyFunc nor SigningKey is
// provided.
SigningKeys map[string]interface{}
// Signing method used to check the token's signing algorithm.
//
// Optional. Default value HS256.
SigningMethod jwa.SignatureAlgorithm
// Context key to store user information from the token into
// context.
//
// Optional. Default value "user".
ContextKey string
// Claims are extendable claims data defining token content.
// Used by default ParseTokenFunc implementation. Not used if
// custom ParseTokenFunc is set.
//
// Optional. Default value []jwt.ClaimPair
Claims []jwt.ClaimPair
// TokenLookup is a string in the form of "<source>:<name>" or
// "<source>:<name>,<source>:<name>" that is used to extract
// token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "param:<name>"
// - "cookie:<name>"
// - "form:<name>"
// Multiply sources example:
// - "header: Authorization,cookie: myowncookie"
TokenLookup string
// TokenLookupFuncs defines a list of user-defined functions
// that extract JWT token from the given context.
// This is one of the two options to provide a token extractor.
// The order of precedence is user-defined TokenLookupFuncs, and
// TokenLookup.
// You can also provide both if you want.
TokenLookupFuncs []ValuesExtractor
// AuthScheme to be used in the Authorization header.
//
// Optional. Default value "Bearer".
AuthScheme string
// KeyFunc defines a user-defined function that supplies the
// public key for a token validation. The function shall take
// care of verifying the signing algorithm and selecting the
// proper key. A user-defined KeyFunc can be useful if tokens
// are issued by an external party. Used by default
// ParseTokenFunc implementation.
//
// When a user-defined KeyFunc is provided, SigningKey,
// SigningKeys, and SigningMethod are ignored. This is one of
// the three options to provide a token validation key. The
// order of precedence is a user-defined KeyFunc, SigningKeys
// and SigningKey. Required if neither SigningKeys nor
// SigningKey is provided. Not used if custom ParseTokenFunc is
// set. Default to an internal implementation verifying the
// signing algorithm and selecting the proper key.
// KeyFunc jwt.Keyfunc
// ParseTokenFunc defines a user-defined function that parses
// token from given auth. Returns an error when token parsing
// fails or parsed token is invalid. Defaults to implementation
// using `github.com/golang-jwt/jwt` as JWT implementation library
ParseTokenFunc func(auth []byte, ctx *http.RequestCtx) (interface{}, error)
// ContinueOnIgnoredError allows the next middleware/handler to
// be called when ErrorHandlerWithContext decides to ignore the
// error (by returning `nil`). This is useful when parts of your
// site/api allow public access and some authorized routes
// provide extra functionality. In that case you can use
// ErrorHandlerWithContext to set a default public JWT token
// value in the request context and continue. Some logic down
// the remaining execution chain needs to check that (public)
// token value then.
ContinueOnIgnoredError bool
}
// JWTSuccessHandler defines a function which is executed for a valid
// token.
JWTSuccessHandler func(ctx *http.RequestCtx)
// JWTErrorHandler defines a function which is executed for an invalid
// token.
JWTErrorHandler func(err error)
// JWTErrorHandlerWithContext is almost identical to JWTErrorHandler,
// but it's passed the current context.
JWTErrorHandlerWithContext func(err error, ctx *http.RequestCtx) error
jwtExtractor func(ctx *http.RequestCtx) ([]byte, error)
)
// DefaultJWTConfig is the default JWT auth middleware config.
//nolint: gochecknoglobals
var DefaultJWTConfig = JWTConfig{
Skipper: DefaultSkipper,
SigningMethod: "HS256",
ContextKey: "user",
TokenLookup: "header:" + http.HeaderAuthorization,
AuthScheme: "Bearer",
Claims: []jwt.ClaimPair{},
}
// Possible token errors.
var (
ErrJWTMissing = errors.New("jwt: missing or malformed jwt")
ErrJWTInvalid = errors.New("jwt: invalid or expired jwt")
)
// JWT returns a JSON Web Token (JWT) auth middleware.
//
// * For valid token, it sets the user in context and calls next handler.
// * For invalid token, it returns "401 - Unauthorized" error.
// * For missing token, it returns "400 - Bad Request" error.
func JWT(key interface{}) Interceptor {
config := DefaultJWTConfig
config.SigningKey = key
return JWTWithConfig(config)
}
// JWTWithConfig returns a JWT auth middleware with config.
//nolint: funlen, gocognit
func JWTWithConfig(config JWTConfig) Interceptor {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultJWTConfig.Skipper
}
if config.SigningKey == nil && len(config.SigningKeys) == 0 && config.ParseTokenFunc == nil {
panic("jwt: middleware requires signing key")
}
if config.SigningMethod == "" {
config.SigningMethod = DefaultJWTConfig.SigningMethod
}
if config.ContextKey == "" {
config.ContextKey = DefaultJWTConfig.ContextKey
}
if config.Claims == nil {
config.Claims = DefaultJWTConfig.Claims
}
if config.TokenLookup == "" {
config.TokenLookup = DefaultJWTConfig.TokenLookup
}
if config.AuthScheme == "" {
config.AuthScheme = DefaultJWTConfig.AuthScheme
}
if config.ParseTokenFunc == nil {
config.ParseTokenFunc = config.defaultParseToken
}
extractors, err := createExtractors(config.TokenLookup, config.AuthScheme)
if err != nil {
panic("middleware: jwt: " + err.Error())
}
if len(config.TokenLookupFuncs) > 0 {
extractors = append(config.TokenLookupFuncs, extractors...)
}
return func(ctx *http.RequestCtx, next http.RequestHandler) {
if config.Skipper(ctx) {
next(ctx)
return
}
if config.BeforeFunc != nil {
config.BeforeFunc(ctx)
}
var lastExtractorErr, lastTokenErr error
for _, extractor := range extractors {
auths, err := extractor(ctx)
if err != nil {
lastExtractorErr = ErrJWTMissing
continue
}
for _, auth := range auths {
token, err := config.ParseTokenFunc(auth, ctx)
if err != nil {
lastTokenErr = err
continue
}
ctx.SetUserValue(config.ContextKey, token)
if config.SuccessHandler != nil {
config.SuccessHandler(ctx)
}
next(ctx)
return
}
}
err := lastTokenErr
if err == nil {
err = lastExtractorErr
}
if config.ErrorHandler != nil {
config.ErrorHandler(err)
return
}
if config.ErrorHandlerWithContext != nil {
tmpErr := config.ErrorHandlerWithContext(err, ctx)
if config.ContinueOnIgnoredError && tmpErr == nil {
next(ctx)
} else {
ctx.Error(tmpErr.Error(), http.StatusUnauthorized)
}
return
}
if lastTokenErr != nil {
ctx.Error(lastTokenErr.Error(), http.StatusUnauthorized)
return
}
ctx.Error(err.Error(), http.StatusInternalServerError)
}
}
func (config *JWTConfig) defaultParseToken(auth []byte, ctx *http.RequestCtx) (interface{}, error) {
token, err := jwt.Parse(auth, jwt.WithKey(config.SigningMethod, config.SigningKey), jwt.WithVerify(true))
if err != nil {
return nil, fmt.Errorf("cannot parse JWT token: %w", err)
}
return token, nil
}

85
logfmt.go Normal file
View File

@ -0,0 +1,85 @@
package middleware
import (
"io"
"os"
"strings"
"time"
"github.com/go-logfmt/logfmt"
http "github.com/valyala/fasthttp"
)
type LogFmtConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// TODO(toby3d): allow select some tags
// Output is a writer where logs in JSON format are written.
// Optional. Default value os.Stdout.
Output io.Writer
}
var DefaultLogFmtConfig = LogFmtConfig{
Skipper: DefaultSkipper,
Output: os.Stdout,
}
func LogFmt() Interceptor {
c := DefaultLogFmtConfig
return LogFmtWithConfig(c)
}
func LogFmtWithConfig(config LogFmtConfig) Interceptor {
if config.Skipper == nil {
config.Skipper = DefaultLogFmtConfig.Skipper
}
if config.Output == nil {
config.Output = DefaultLogFmtConfig.Output
}
encoder := logfmt.NewEncoder(config.Output)
return func(ctx *http.RequestCtx, next http.RequestHandler) {
next(ctx)
encoder.EncodeKeyvals(
"bytes_in", len(ctx.Request.Body()),
"bytes_out", len(ctx.Response.Body()),
"error", ctx.Err(),
"host", ctx.Host(),
"id", ctx.ID(),
"latency", ctx.Time().Sub(ctx.ConnTime()).Nanoseconds(),
"latency_human", ctx.Time().Sub(ctx.ConnTime()).String(),
"method", ctx.Method(),
"path", ctx.Path(),
"protocol", ctx.Request.Header.Protocol(),
"referer", ctx.Referer(),
"remote_ip", ctx.RemoteIP(),
"status", ctx.Response.StatusCode(),
"time_rfc3339", ctx.Time().Format(time.RFC3339),
"time_rfc3339_nano", ctx.Time().Format(time.RFC3339Nano),
"time_unix", ctx.Time().Unix(),
"time_unix_nano", ctx.Time().UnixNano(),
"uri", ctx.URI(),
"user_agent", ctx.UserAgent(),
)
ctx.Request.Header.VisitAllInOrder(func(key, value []byte) {
encoder.EncodeKeyval(strings.ReplaceAll(strings.ToLower("header_"+string(key)), "-", "_"), value)
})
ctx.QueryArgs().VisitAll(func(key, value []byte) {
encoder.EncodeKeyval(strings.ReplaceAll(strings.ToLower("query_"+string(key)), "-", "_"), value)
})
if form, err := ctx.MultipartForm(); err == nil {
for k, v := range form.Value {
encoder.EncodeKeyval(strings.ReplaceAll(strings.ToLower("form_"+k), "-", "_"), v)
}
}
encoder.EndRecord()
}
}

70
session.go Normal file
View File

@ -0,0 +1,70 @@
package middleware
import (
"fmt"
"github.com/fasthttp/session/v2"
http "github.com/valyala/fasthttp"
)
type SessionConfig struct {
Skipper Skipper
Session *session.Session
}
// DefaultSessionConfig is the default Session middleware config.
var DefaultSessionConfig = SessionConfig{
Skipper: DefaultSkipper,
}
var key string = "_session_store"
func Session(s *session.Session) Interceptor {
c := DefaultSessionConfig
c.Session = s
return SessionWithConfig(c)
}
func SessionWithConfig(config SessionConfig) Interceptor {
if config.Skipper == nil {
config.Skipper = DefaultSessionConfig.Skipper
}
if config.Session == nil {
panic("session: session middleware requires session")
}
return func(ctx *http.RequestCtx, next http.RequestHandler) {
if config.Skipper(ctx) {
next(ctx)
return
}
store, err := config.Session.Get(ctx)
if err != nil {
ctx.Error(err.Error(), http.StatusInternalServerError)
return
}
defer func(s *session.Session, ctx *http.RequestCtx, store *session.Store) {
if err := s.Save(ctx, store); err != nil {
ctx.Error(err.Error(), http.StatusInternalServerError)
}
}(config.Session, ctx, store)
ctx.SetUserValue(key, store)
next(ctx)
}
}
// SessionGet returns a named session.
func SessionGet(ctx *http.RequestCtx) (*session.Store, error) {
store, ok := ctx.UserValue(key).(*session.Store)
if !ok {
return nil, fmt.Errorf("%s session store not found", key)
}
return store, nil
}