-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathmain.go
More file actions
529 lines (460 loc) · 14.9 KB
/
main.go
File metadata and controls
529 lines (460 loc) · 14.9 KB
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
package badger
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
"github.com/fosrl/badger/ips"
"github.com/fosrl/badger/version"
)
type Config struct {
APIBaseUrl string `json:"apiBaseUrl,omitempty"`
UserSessionCookieName string `json:"userSessionCookieName,omitempty"`
ResourceSessionRequestParam string `json:"resourceSessionRequestParam,omitempty"`
AccessTokenQueryParam string `json:"accessTokenQueryParam,omitempty"`
AccessTokenIDHeader string `json:"accessTokenIdHeader,omitempty"`
AccessTokenHeader string `json:"accessTokenHeader,omitempty"`
DisableForwardAuth bool `json:"disableForwardAuth,omitempty"`
TrustIP []string `json:"trustip,omitempty"`
DisableDefaultCFIPs bool `json:"disableDefaultCFIPs,omitempty"`
CustomIPHeader string `json:"customIPHeader,omitempty"`
}
const (
xRealIP = "X-Real-Ip"
xForwardFor = "X-Forwarded-For"
xForwardProto = "X-Forwarded-Proto"
cfConnectingIP = "CF-Connecting-IP"
cfVisitor = "CF-Visitor"
)
type Badger struct {
next http.Handler
name string
apiBaseUrl string
userSessionCookieName string
resourceSessionRequestParam string
accessTokenQueryParam string
accessTokenIDHeader string
accessTokenHeader string
disableForwardAuth bool
trustIP []*net.IPNet
customIPHeader string
}
type VerifyBody struct {
Sessions map[string]string `json:"sessions"`
OriginalRequestURL string `json:"originalRequestURL"`
RequestScheme *string `json:"scheme"`
RequestHost *string `json:"host"`
RequestPath *string `json:"path"`
RequestMethod *string `json:"method"`
TLS bool `json:"tls"`
RequestIP *string `json:"requestIp,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Query map[string]string `json:"query,omitempty"`
BadgerVersion string `json:"badgerVersion,omitempty"`
}
type VerifyResponse struct {
Data struct {
HeaderAuthChallenged bool `json:"headerAuthChallenged"`
Valid bool `json:"valid"`
RedirectURL *string `json:"redirectUrl"`
Username *string `json:"username,omitempty"`
Email *string `json:"email,omitempty"`
Name *string `json:"name,omitempty"`
Role *string `json:"role,omitempty"`
ResponseHeaders map[string]string `json:"responseHeaders,omitempty"`
PangolinVersion *string `json:"pangolinVersion,omitempty"`
} `json:"data"`
}
type ExchangeSessionBody struct {
RequestToken *string `json:"requestToken"`
RequestHost *string `json:"host"`
RequestIP *string `json:"requestIp,omitempty"`
}
type ExchangeSessionResponse struct {
Data struct {
Valid bool `json:"valid"`
Cookie *string `json:"cookie"`
ResponseHeaders map[string]string `json:"responseHeaders,omitempty"`
} `json:"data"`
}
func CreateConfig() *Config {
return &Config{}
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
badger := &Badger{
next: next,
name: name,
apiBaseUrl: config.APIBaseUrl,
userSessionCookieName: config.UserSessionCookieName,
resourceSessionRequestParam: config.ResourceSessionRequestParam,
accessTokenQueryParam: config.AccessTokenQueryParam,
accessTokenIDHeader: config.AccessTokenIDHeader,
accessTokenHeader: config.AccessTokenHeader,
disableForwardAuth: config.DisableForwardAuth,
customIPHeader: config.CustomIPHeader,
}
// Validate required fields only if forward auth is enabled
if !config.DisableForwardAuth {
if config.APIBaseUrl == "" {
return nil, fmt.Errorf("apiBaseUrl is required when forward auth is enabled")
}
if config.UserSessionCookieName == "" {
return nil, fmt.Errorf("userSessionCookieName is required when forward auth is enabled")
}
if config.ResourceSessionRequestParam == "" {
return nil, fmt.Errorf("resourceSessionRequestParam is required when forward auth is enabled")
}
}
if config.TrustIP != nil {
for _, v := range config.TrustIP {
_, trustip, err := net.ParseCIDR(v)
if err != nil {
return nil, err
}
badger.trustIP = append(badger.trustIP, trustip)
}
}
if !config.DisableDefaultCFIPs {
for _, v := range ips.CFIPs() {
_, trustip, err := net.ParseCIDR(v)
if err != nil {
return nil, err
}
badger.trustIP = append(badger.trustIP, trustip)
}
}
return badger, nil
}
func (p *Badger) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
realIP := p.getRealIP(req)
p.setIPHeaders(req, realIP)
if p.disableForwardAuth {
p.next.ServeHTTP(rw, req)
return
}
cookies := p.extractCookies(req)
queryValues := req.URL.Query()
if sessionRequestValue := queryValues.Get(p.resourceSessionRequestParam); sessionRequestValue != "" {
body := ExchangeSessionBody{
RequestToken: &sessionRequestValue,
RequestHost: &req.Host,
RequestIP: &realIP,
}
jsonData, err := json.Marshal(body)
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
verifyURL := fmt.Sprintf("%s/badger/exchange-session", p.apiBaseUrl)
resp, err := http.Post(verifyURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
var result ExchangeSessionResponse
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
if result.Data.Cookie != nil && *result.Data.Cookie != "" {
rw.Header().Add("Set-Cookie", *result.Data.Cookie)
queryValues.Del(p.resourceSessionRequestParam)
cleanedQuery := queryValues.Encode()
originalRequestURL := fmt.Sprintf("%s://%s%s", p.getScheme(req), req.Host, req.URL.Path)
if cleanedQuery != "" {
originalRequestURL = fmt.Sprintf("%s?%s", originalRequestURL, cleanedQuery)
}
if result.Data.ResponseHeaders != nil {
for key, value := range result.Data.ResponseHeaders {
rw.Header().Add(key, value)
}
}
fmt.Println("Got exchange token, redirecting to", originalRequestURL)
http.Redirect(rw, req, originalRequestURL, http.StatusFound)
return
}
}
cleanedQuery := queryValues.Encode()
originalRequestURL := fmt.Sprintf("%s://%s%s", p.getScheme(req), req.Host, req.URL.Path)
if cleanedQuery != "" {
originalRequestURL = fmt.Sprintf("%s?%s", originalRequestURL, cleanedQuery)
}
verifyURL := fmt.Sprintf("%s/badger/verify-session", p.apiBaseUrl)
headers := make(map[string]string)
for name, values := range req.Header {
if len(values) > 0 {
headers[name] = values[0] // Send only the first value for simplicity
}
}
queryParams := make(map[string]string)
for key, values := range queryValues {
if len(values) > 0 {
queryParams[key] = values[0]
}
}
cookieData := VerifyBody{
Sessions: cookies,
OriginalRequestURL: originalRequestURL,
RequestScheme: &req.URL.Scheme,
RequestHost: &req.Host,
RequestPath: &req.URL.Path,
RequestMethod: &req.Method,
TLS: req.TLS != nil,
RequestIP: &realIP,
Headers: headers,
Query: queryParams,
BadgerVersion: version.Version,
}
jsonData, err := json.Marshal(cookieData)
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError) // TODO: redirect to error page
return
}
resp, err := http.Post(verifyURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
for _, setCookie := range resp.Header["Set-Cookie"] {
rw.Header().Add("Set-Cookie", setCookie)
}
if resp.StatusCode != http.StatusOK {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
var result VerifyResponse
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
http.Error(rw, "Internal Server Error", http.StatusInternalServerError)
return
}
req.Header.Del("Remote-User")
req.Header.Del("Remote-Email")
req.Header.Del("Remote-Name")
req.Header.Del("Remote-Role")
if result.Data.ResponseHeaders != nil {
for key, value := range result.Data.ResponseHeaders {
rw.Header().Add(key, value)
}
}
if result.Data.HeaderAuthChallenged {
fmt.Println("Badger: challenging client for header authentication")
rw.Header().Add("WWW-Authenticate", "Basic realm=\"pangolin\"")
if result.Data.RedirectURL != nil && *result.Data.RedirectURL != "" {
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
rw.WriteHeader(http.StatusUnauthorized)
rw.Write([]byte(p.renderRedirectPage(*result.Data.RedirectURL)))
} else {
http.Error(rw, "Unauthorized", http.StatusUnauthorized)
}
return
}
if result.Data.RedirectURL != nil && *result.Data.RedirectURL != "" {
fmt.Println("Badger: Redirecting to", *result.Data.RedirectURL)
http.Redirect(rw, req, *result.Data.RedirectURL, http.StatusFound)
return
}
if result.Data.Valid {
if result.Data.Username != nil {
req.Header.Add("Remote-User", *result.Data.Username)
}
if result.Data.Email != nil {
req.Header.Add("Remote-Email", *result.Data.Email)
}
if result.Data.Name != nil {
req.Header.Add("Remote-Name", *result.Data.Name)
}
if result.Data.Role != nil {
req.Header.Add("Remote-Role", *result.Data.Role)
}
p.stripSessionCookies(req)
p.stripSessionParam(req)
p.stripAccessTokenHeaders(req)
fmt.Println("Badger: Valid session")
p.next.ServeHTTP(rw, req)
return
}
http.Error(rw, "Unauthorized", http.StatusUnauthorized)
}
func (p *Badger) extractCookies(req *http.Request) map[string]string {
cookies := make(map[string]string)
isSecureRequest := req.TLS != nil
for _, cookie := range req.Cookies() {
if strings.HasPrefix(cookie.Name, p.userSessionCookieName) {
if cookie.Secure && !isSecureRequest {
continue
}
cookies[cookie.Name] = cookie.Value
}
}
return cookies
}
func (p *Badger) getScheme(req *http.Request) string {
if req.TLS != nil {
return "https"
}
return "http"
}
func (p *Badger) renderRedirectPage(redirectURL string) string {
return fmt.Sprintf(`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Redirecting...</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f5f5f5;
}
.container {
text-align: center;
padding: 2rem;
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
a {
color: #0066cc;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<p>Redirecting...</p>
<p>If you are not redirected automatically, <a href="%s">click here</a>.</p>
</div>
<script>
window.location.href = "%s";
</script>
</body>
</html>`, redirectURL, redirectURL)
}
func (p *Badger) getRealIP(req *http.Request) string {
// Check if request comes from a trusted source
isTrusted := p.isTrustedIP(req.RemoteAddr)
// If custom IP header is configured, use it
if p.customIPHeader != "" {
if customIP := req.Header.Get(p.customIPHeader); customIP != "" && isTrusted {
return customIP
}
}
// Default: use CF-Connecting-IP if from trusted source
if isTrusted {
if cfIP := req.Header.Get(cfConnectingIP); cfIP != "" {
return cfIP
}
}
// Fallback: extract IP from RemoteAddr
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
// If parsing fails, return RemoteAddr as-is (might be just IP without port)
return req.RemoteAddr
}
return ip
}
func (p *Badger) stripSessionParam(req *http.Request) {
query := req.URL.Query()
modified := false
if query.Has(p.resourceSessionRequestParam) {
query.Del(p.resourceSessionRequestParam)
modified = true
}
if p.accessTokenQueryParam != "" && query.Has(p.accessTokenQueryParam) {
query.Del(p.accessTokenQueryParam)
modified = true
}
if modified {
req.URL.RawQuery = query.Encode()
req.RequestURI = req.URL.RequestURI()
}
}
func (p *Badger) stripAccessTokenHeaders(req *http.Request) {
if p.accessTokenIDHeader != "" {
req.Header.Del(p.accessTokenIDHeader)
}
if p.accessTokenHeader != "" {
req.Header.Del(p.accessTokenHeader)
}
}
// stripSessionCookies removes session cookies from the request before forwarding to the backend.
// It processes raw Cookie header pairs so non-target cookies are preserved as-is.
func (p *Badger) stripSessionCookies(req *http.Request) {
cookieHeaders := req.Header.Values("Cookie")
if len(cookieHeaders) == 0 {
return
}
var remainingPairs []string
for _, headerValue := range cookieHeaders {
for _, part := range strings.Split(headerValue, ";") {
part = strings.TrimSpace(part)
if part == "" {
continue
}
name, _, _ := strings.Cut(part, "=")
name = strings.TrimSpace(name)
if !strings.HasPrefix(name, p.userSessionCookieName) {
remainingPairs = append(remainingPairs, part)
}
}
}
if len(remainingPairs) == 0 {
req.Header.Del("Cookie")
return
}
// Keep a single canonical Cookie header while preserving surviving name=value pairs.
req.Header.Set("Cookie", strings.Join(remainingPairs, "; "))
}
func (p *Badger) isTrustedIP(remoteAddr string) bool {
ipStr, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
return false
}
ip := net.ParseIP(ipStr)
if ip == nil {
return false
}
for _, network := range p.trustIP {
if network.Contains(ip) {
return true
}
}
return false
}
func (p *Badger) setIPHeaders(req *http.Request, realIP string) {
isTrusted := p.isTrustedIP(req.RemoteAddr)
if isTrusted {
// Handle CF-Visitor header for scheme
if req.Header.Get(cfVisitor) != "" {
var cfVisitorValue struct {
Scheme string `json:"scheme"`
}
if err := json.Unmarshal([]byte(req.Header.Get(cfVisitor)), &cfVisitorValue); err == nil {
req.Header.Set(xForwardProto, cfVisitorValue.Scheme)
}
}
// Set headers with the real IP (already extracted from CF-Connecting-IP or custom header)
req.Header.Set(xForwardFor, realIP)
req.Header.Set(xRealIP, realIP)
} else {
// Not from trusted source, use direct IP
req.Header.Set(xRealIP, realIP)
// Remove CF headers if present
req.Header.Del(cfVisitor)
req.Header.Del(cfConnectingIP)
}
}