-
Notifications
You must be signed in to change notification settings - Fork 1
/
fifteen.go
162 lines (145 loc) · 4.36 KB
/
fifteen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package traefik_plugins
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"github.com/golang-jwt/jwt/v5"
)
type FallbackType string
const (
FallbackError FallbackType = "error"
FallbackPass FallbackType = "pass"
FallbackIp FallbackType = "ip"
FallbackHeader FallbackType = "header"
)
type Fallback struct {
Type FallbackType `yaml:"type,omitempty"`
Value string `yaml:"value,omitempty"`
KeepIfEmpty bool `yaml:"keepIfEmpty,omitempty"`
}
// Config the plugin configuration.
type Config struct {
JwtHeaderName string `yaml:"jwtHeaderName,omitempty"`
JwtField string `yaml:"jwtField,omitempty"`
ValueHeaderName string `yaml:"valueHeaderName,omitempty"`
Fallbacks []Fallback `yaml:"fallbacks,omitempty"`
Debug bool `yaml:"debug,omitempty"`
}
// CreateConfig creates the default plugin configuration.
func CreateConfig() *Config {
return &Config{}
}
// Fifteen a Fifteen plugin.
type Fifteen struct {
next http.Handler
cfg *Config
name string
}
// New created a new Fifteen plugin.
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
return &Fifteen{
cfg: config,
next: next,
name: name,
}, nil
}
func (a *Fifteen) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if req.Header.Get(a.cfg.JwtHeaderName) == "" {
a.logDebug("Empty jwt, falling back")
a.ServeFallback(rw, req)
return
}
rawHeader := req.Header.Get(a.cfg.JwtHeaderName)
rawToken := ""
if strings.HasPrefix(rawHeader, "Bearer ") {
rawToken = rawHeader[len("Bearer "):]
}
parsedToken, _, err := jwt.NewParser().ParseUnverified(rawToken, jwt.MapClaims{})
if err != nil {
a.logDebug("Could not parse non-empty jwt token, falling back: %s", err.Error())
a.ServeFallback(rw, req)
return
}
mapClaims := parsedToken.Claims.(jwt.MapClaims)
if newHeaderValue, hasValue := mapClaims[a.cfg.JwtField]; hasValue {
a.logDebug("JWT value on field %s was %v (of type %T)", a.cfg.JwtField, newHeaderValue, newHeaderValue)
switch val := newHeaderValue.(type) {
case string:
req.Header.Set(a.cfg.ValueHeaderName, val)
case []string:
if len(val) > 0 {
req.Header.Set(a.cfg.ValueHeaderName, val[0])
} else {
a.logDebug("JWT field value was an empty array, falling back")
a.ServeFallback(rw, req)
return
}
default:
a.logDebug("JWT field value has an unexpected type, falling back")
a.ServeFallback(rw, req)
return
}
} else {
a.logDebug("JWT field value does not hold field %s, falling back", a.cfg.JwtField)
a.ServeFallback(rw, req)
return
}
a.end(rw, req)
}
func (a *Fifteen) ServeFallback(rw http.ResponseWriter, req *http.Request) {
if len(a.cfg.Fallbacks) == 0 {
a.logDebug("Fallbacked because JWT was not set, invalid or has unexpected value on field. No fallback strategies, ignoring...")
} else {
a.logDebug("Fallbacked because JWT was not set, invalid or has unexpected value on field. Finding right fallback strategy")
for i, fallback := range a.cfg.Fallbacks {
a.logDebug("Strategy %d: %+v", i, fallback)
var success bool
switch fallback.Type {
case FallbackError:
rw.Header().Set("Content-Type", "text/plain")
rw.WriteHeader(http.StatusBadRequest)
rw.Write([]byte("Bad request"))
return
case FallbackPass:
a.logDebug("Passing through")
success = true
case FallbackIp:
req.Header.Set(a.cfg.ValueHeaderName, ipWithNoPort(req.RemoteAddr))
success = true
case FallbackHeader:
headerValue := req.Header.Get(fallback.Value)
if headerValue == "" && !fallback.KeepIfEmpty {
a.logDebug("Header %s was empty, skipping...", fallback.Value)
continue
}
req.Header.Set(a.cfg.ValueHeaderName, headerValue)
success = true
default:
a.logDebug("Unknown fallback type, skipping...")
}
if success {
a.logDebug("Fallback strategy %d was successful", i)
break
}
}
}
a.end(rw, req)
}
func (a *Fifteen) logDebug(format string, args ...any) {
if !a.cfg.Debug {
return
}
os.Stderr.WriteString("[Fifteen middleware]: " + fmt.Sprintf(format, args...) + "\n")
}
func (a *Fifteen) end(rw http.ResponseWriter, req *http.Request) {
a.logDebug("ending with request headers: %+v", req.Header)
a.next.ServeHTTP(rw, req)
}
func ipWithNoPort(addr string) string {
if colon := strings.LastIndex(addr, ":"); colon != -1 {
return addr[:colon]
}
return addr
}