This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.go
249 lines (220 loc) · 7.58 KB
/
main.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package main
import (
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
"github.com/crewjam/saml/samlsp"
log "github.com/sirupsen/logrus"
"github.com/vulcand/oxy/buffer"
"github.com/vulcand/oxy/cbreaker"
"github.com/vulcand/oxy/forward"
"github.com/vulcand/oxy/ratelimit"
"github.com/vulcand/oxy/roundrobin"
"github.com/vulcand/oxy/trace"
"github.com/vulcand/oxy/utils"
"github.com/labstack/echo"
)
// Config for reverse proxy settings and RBAC users and groups
type Config struct {
ListenInterface string `yaml:"listen_interface"`
ListenPort int `yaml:"listen_port"`
Targets []string `yaml:"targets"`
IdpMetadataURL string `yaml:"idp_metadata_url"`
AllowIDPInitiated bool `yaml:"allow_idp_initiated"`
ServiceRootURL string `yaml:"service_root_url"`
CertPath string `yaml:"cert_path"`
KeyPath string `yaml:"key_path"`
RateLimitAvgSecond int64 `yaml:"rate_limit_avg_second"`
RateLimitBurstSecond int64 `yaml:"rate_limit_burst_second"`
TraceRequestHeaders []string `yaml:"trace_request_headers"`
AddAttributesAsHeaders []string `yaml:"add_attributes_as_headers"`
CookieMaxAge time.Duration `yaml:"cookie_max_age"`
LogLevel string `yaml:"log_level"`
}
type server struct {
config Config
}
func (C *Config) getConf(configPath string) {
yamlFile, err := ioutil.ReadFile(configPath)
if err != nil {
log.WithFields(log.Fields{
"config_path": configPath,
"error": err.Error()}).Fatal("could not read config")
}
err = yaml.Unmarshal(yamlFile, C)
if err != nil {
log.WithFields(log.Fields{
"config_path": configPath,
"error": err.Error()}).Fatal("could not parse config")
}
}
func newServer() *server {
var configPath string
flag.StringVar(&configPath, "c", "config.yaml", "path to the config file")
flag.Parse()
var C Config
absPath, err := filepath.Abs(configPath)
if err != nil {
log.WithFields(log.Fields{
"config_path": configPath,
"error": err.Error()}).Fatal("could not determine absolute path for config")
}
C.getConf(absPath)
log.Print("config loaded")
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
logLevel, err := log.ParseLevel(C.LogLevel)
if err != nil {
log.WithFields(log.Fields{
"log_level": C.LogLevel,
"error": err.Error()}).Fatal("could not parse log level")
}
log.SetLevel(logLevel)
s := server{config: C}
return &s
}
func (s *server) addSamlHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attributes := samlsp.Token(r.Context()).Attributes
for _, attr := range s.config.AddAttributesAsHeaders {
if val, ok := attributes[attr]; ok {
r.Header.Add("X-Saml-"+attr, strings.Join(val, " "))
} else {
log.WithFields(log.Fields{"attrs_available": attributes,
"attr": attr}).Warn("given attr not in attributes")
}
}
next.ServeHTTP(w, r)
})
}
func (s *server) getMiddleware() http.Handler {
// reverse proxy layer
fwd, err := forward.New()
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatal("could not initialize reverse proxy middleware")
}
// rate-limiting layers
var extractorSource = "client.ip"
extractor, err := utils.NewExtractor(extractorSource)
if err != nil {
log.WithFields(log.Fields{"extractor": extractorSource,
"error": err.Error()}).Fatal("could not use given rate limiting extractor")
}
rates := ratelimit.NewRateSet()
err = rates.Add(time.Second, s.config.RateLimitAvgSecond, s.config.RateLimitBurstSecond)
if err != nil {
log.WithFields(log.Fields{
"error": err.Error()}).Fatal("could not set rate limiting rates")
}
rm, err := ratelimit.New(fwd, extractor, rates)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatal("could not initialize rate limiter middleware")
}
// circuit-breaker layer
const triggerNetRatio = `NetworkErrorRatio() > 0.5`
cb, err := cbreaker.New(rm, triggerNetRatio)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatal("could not initialize circuit breaker middleware")
}
// load balancing layer
lb, err := roundrobin.New(cb)
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatal("could not initialize load balancing middleware")
}
var targetURL *url.URL
for _, target := range s.config.Targets {
targetURL, err = url.Parse(target)
if err != nil {
log.WithFields(log.Fields{
"target": target,
"error": err.Error()}).Fatal("could not parse target")
}
// add target to the load balancer
err = lb.UpsertServer(targetURL)
if err != nil {
log.WithFields(log.Fields{
"target": target,
"error": err.Error()}).Fatal("could not add target to load balancer")
}
}
// trace layer
trace, err := trace.New(lb, io.Writer(os.Stdout),
trace.Option(trace.RequestHeaders(s.config.TraceRequestHeaders...)))
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatal("could not initialize request tracing middleware")
}
// buffer will read the request body and will replay the request again in case if forward returned status
// corresponding to nework error (e.g. Gateway Timeout)
buffer, err := buffer.New(trace, buffer.Retry(`IsNetworkError() && Attempts() < 3`))
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatal("could not initialize buffering middleware")
}
return buffer
}
func main() {
s := newServer()
keyPair, err := tls.LoadX509KeyPair(s.config.CertPath, s.config.KeyPath)
if err != nil {
log.WithFields(log.Fields{
"cert_path": s.config.CertPath,
"key_path": s.config.KeyPath,
"error": err.Error()}).Fatal("could not load keypair")
}
keyPair.Leaf, err = x509.ParseCertificate(keyPair.Certificate[0])
if err != nil {
log.WithFields(log.Fields{
"cert_path": s.config.CertPath,
"error": err.Error()}).Fatal("could not parse certificate")
}
idpMetadataURL, err := url.Parse(s.config.IdpMetadataURL)
if err != nil {
log.WithFields(log.Fields{
"idp_metadata_url": s.config.IdpMetadataURL,
"error": err.Error()}).Fatal("could not parse metadata URL")
}
rootURL, err := url.Parse(s.config.ServiceRootURL)
if err != nil {
log.WithFields(log.Fields{
"service_root_url": s.config.IdpMetadataURL,
"error": err.Error()}).Fatal("could not parse service root URL")
}
// initialize SAML middleware
samlSP, err := samlsp.New(samlsp.Options{
URL: *rootURL,
Key: keyPair.PrivateKey.(*rsa.PrivateKey),
Certificate: keyPair.Leaf,
IDPMetadataURL: idpMetadataURL,
AllowIDPInitiated: s.config.AllowIDPInitiated,
CookieMaxAge: s.config.CookieMaxAge,
})
if err != nil {
log.WithFields(log.Fields{"error": err.Error()}).Fatal("could not initialize SAML middleware")
}
// Use mux for explicit paths and so no other routes are accidently exposed
router := echo.New()
// This endpoint handles SAML auth flow
router.Any("/saml/*", echo.WrapHandler(samlSP))
// These endpoints require valid session cookie
router.Any("/*", echo.WrapHandler(samlSP.RequireAccount(s.addSamlHeaders(s.getMiddleware()))))
srv := &http.Server{
Addr: fmt.Sprintf("%s:%d", s.config.ListenInterface, s.config.ListenPort),
Handler: router,
// This breaks streaming requests
ReadTimeout: 45 * time.Second,
// This breaks long downloads
WriteTimeout: 45 * time.Second,
IdleTimeout: 120 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}