Skip to content

Commit 8d99068

Browse files
authored
refactor: allow for multiple auth modules if they match (#1169)
1 parent d6c80a8 commit 8d99068

2 files changed

Lines changed: 112 additions & 46 deletions

File tree

‎internal/controller/proxy_controller.go‎

Lines changed: 56 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"net/url"
99
"path"
1010
"regexp"
11+
"slices"
1112
"strings"
1213

1314
"github.com/tinyauthapp/tinyauth/internal/model"
@@ -39,6 +40,8 @@ const (
3940

4041
var BrowserUserAgentRegex = regexp.MustCompile("Chrome|Gecko|AppleWebKit|Opera|Edge")
4142

43+
var envoyAuthPath = "/api/auth/envoy?path="
44+
4245
type Proxy struct {
4346
Proxy string `uri:"proxy" binding:"required"`
4447
}
@@ -421,19 +424,19 @@ func (controller *ProxyController) getAuthRequestContext(c *gin.Context) (ProxyC
421424
return ProxyContext{}, errors.New("x-original-url not found")
422425
}
423426

424-
url, err := url.Parse(xOriginalUrl)
427+
u, err := url.Parse(xOriginalUrl)
425428

426429
if err != nil {
427430
return ProxyContext{}, err
428431
}
429432

430-
host := url.Host
433+
host := u.Host
431434

432435
if strings.TrimSpace(host) == "" {
433436
return ProxyContext{}, errors.New("host not found")
434437
}
435438

436-
proto := url.Scheme
439+
proto := u.Scheme
437440

438441
if strings.TrimSpace(proto) == "" {
439442
return ProxyContext{}, errors.New("proto not found")
@@ -444,7 +447,7 @@ func (controller *ProxyController) getAuthRequestContext(c *gin.Context) (ProxyC
444447
return ProxyContext{
445448
Host: host,
446449
Proto: proto,
447-
PathRaw: url.RequestURI(),
450+
PathRaw: u.RequestURI(),
448451
Method: method,
449452
Type: AuthRequest,
450453
}, nil
@@ -466,19 +469,23 @@ func (controller *ProxyController) getExtAuthzContext(c *gin.Context) (ProxyCont
466469
}
467470

468471
// The path is attached to the end of the /api/auth/envoy?path= string so we just strip it out
469-
path := strings.TrimPrefix(c.Request.RequestURI, "/api/auth/envoy?path=")
472+
if !strings.HasPrefix(c.Request.RequestURI, envoyAuthPath) {
473+
return ProxyContext{}, errors.New("path not found")
474+
}
475+
476+
p := strings.TrimPrefix(c.Request.RequestURI, envoyAuthPath)
470477

471-
if strings.TrimSpace(path) == "" {
478+
if strings.TrimSpace(p) == "" {
472479
return ProxyContext{}, errors.New("path not found")
473480
}
474481

475-
// For envoy we need to support every method
482+
// For ext_authz we need to support every method
476483
method := c.Request.Method
477484

478485
return ProxyContext{
479486
Host: host,
480487
Proto: proto,
481-
PathRaw: path,
488+
PathRaw: p,
482489
Method: method,
483490
Type: ExtAuthz,
484491
}, nil
@@ -529,37 +536,34 @@ func (controller *ProxyController) getContextFromAuthModule(c *gin.Context, modu
529536
return ProxyContext{}, fmt.Errorf("unsupported auth module: %v", module)
530537
}
531538

532-
func (controller *ProxyController) authModuleIdentifiersPresent(c *gin.Context, module AuthModuleType) bool {
533-
switch module {
534-
case ForwardAuth:
535-
_, host := controller.getHeader(c, "x-forwarded-host")
536-
_, uri := controller.getHeader(c, "x-forwarded-uri")
537-
return host || uri
538-
case AuthRequest:
539-
_, ok := controller.getHeader(c, "x-original-url")
540-
return ok
541-
case ExtAuthz:
542-
return strings.TrimSpace(c.Query("path")) != ""
543-
default:
544-
return false
545-
}
539+
func (controller *ProxyController) compareProxyContext(ctx1, ctx2 ProxyContext) bool {
540+
return ctx1.Host == ctx2.Host && ctx1.Proto == ctx2.Proto && ctx1.PathRaw == ctx2.PathRaw && ctx1.Method == ctx2.Method
546541
}
547542

548-
func (controller *ProxyController) ensureNoMultipleAuthModules(c *gin.Context, authModules []AuthModuleType) error {
549-
present := 0
543+
func (controller *ProxyController) includedAuthModules(c *gin.Context, discoveredModules []AuthModuleType) []AuthModuleType {
544+
var modules []AuthModuleType
550545

551-
for _, module := range authModules {
552-
if controller.authModuleIdentifiersPresent(c, module) {
553-
present++
554-
}
546+
if strings.HasPrefix(c.Request.RequestURI, envoyAuthPath) &&
547+
strings.TrimPrefix(c.Request.RequestURI, envoyAuthPath) != "" {
548+
modules = append(modules, ExtAuthz)
555549
}
556550

557-
if present > 1 {
558-
controller.log.App.Warn().Msg("Request carries headers for multiple auth modules, possible spoofing attempt, denying")
559-
return fmt.Errorf("conflicting auth module headers")
551+
hasURI := c.GetHeader("x-forwarded-uri") != ""
552+
hasHost := c.GetHeader("x-forwarded-host") != ""
553+
554+
if hasURI && hasHost {
555+
modules = append(modules, ForwardAuth)
560556
}
561557

562-
return nil
558+
hasXOriginalUrl := c.GetHeader("x-original-url") != ""
559+
560+
if hasXOriginalUrl {
561+
modules = append(modules, AuthRequest)
562+
}
563+
564+
return utils.Filter(modules, func(module AuthModuleType) bool {
565+
return slices.Contains(discoveredModules, module)
566+
})
563567
}
564568

565569
func (controller *ProxyController) getProxyContext(c *gin.Context) (ProxyContext, error) {
@@ -584,13 +588,7 @@ func (controller *ProxyController) getProxyContext(c *gin.Context) (ProxyContext
584588
return ProxyContext{}, fmt.Errorf("no auth modules supported for proxy: %v", req.Proxy)
585589
}
586590

587-
err = controller.ensureNoMultipleAuthModules(c, controller.determineAuthModules(proxy, true))
588-
589-
if err != nil {
590-
return ProxyContext{}, err
591-
}
592-
593-
var ctx *ProxyContext
591+
var extracted []ProxyContext
594592

595593
for _, module := range authModules {
596594
controller.log.App.Debug().Msgf("Trying to get context from auth module %v", module)
@@ -600,14 +598,29 @@ func (controller *ProxyController) getProxyContext(c *gin.Context) (ProxyContext
600598
continue
601599
}
602600
controller.log.App.Debug().Msgf("Successfully got context from auth module %v", module)
603-
ctx = &authModuleCtx
604-
break
601+
extracted = append(extracted, authModuleCtx)
605602
}
606603

607-
if ctx == nil {
604+
if len(extracted) == 0 {
608605
return ProxyContext{}, fmt.Errorf("failed to get context from any auth module")
609606
}
610607

608+
includedAuthModules := controller.includedAuthModules(c, authModules)
609+
610+
if len(extracted) != len(includedAuthModules) {
611+
controller.log.App.Warn().
612+
Msg("Request carries context for multiple auth modules but some failed to extract, cannot determine correct auth modules")
613+
return ProxyContext{}, fmt.Errorf("cannot determine correct auth module")
614+
}
615+
616+
if s := slices.CompactFunc(extracted, controller.compareProxyContext); len(s) > 1 {
617+
controller.log.App.Warn().
618+
Msg("Request carries context for multiple auth modules but they don't match, cannot determine correct auth modules")
619+
return ProxyContext{}, fmt.Errorf("cannot determine correct auth module")
620+
}
621+
622+
ctx := extracted[0]
623+
611624
// Parse the raw path to populate the cleaned path used for ACLs
612625
upath, err := url.Parse(ctx.PathRaw)
613626

@@ -633,5 +646,5 @@ func (controller *ProxyController) getProxyContext(c *gin.Context) (ProxyContext
633646

634647
ctx.IsBrowser = isBrowser
635648
ctx.ProxyType = proxy
636-
return *ctx, nil
649+
return ctx, nil
637650
}

‎internal/controller/proxy_controller_test.go‎

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -867,10 +867,10 @@ func TestProxyController(t *testing.T) {
867867
},
868868
},
869869
{
870-
description: "Forward auth and auth request headers should fail for nginx",
870+
description: "Forward auth and different auth request headers should fail for nginx",
871871
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
872872
req := httptest.NewRequest("GET", "/api/auth/nginx", nil)
873-
req.Header.Set("x-forwarded-host", "foo.example.com")
873+
req.Header.Set("x-forwarded-host", "foobar.example.com")
874874
req.Header.Set("x-forwarded-proto", "https")
875875
req.Header.Set("x-forwarded-uri", "/foo?bar=foo")
876876
req.Header.Set("x-original-url", "https://foo.example.com/foo?bar=foo")
@@ -880,13 +880,54 @@ func TestProxyController(t *testing.T) {
880880
},
881881
},
882882
{
883-
description: "Forward auth and ext authz headers should fail for envoy",
883+
description: "Forward auth and different ext authz headers should fail for envoy",
884884
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
885885
req := httptest.NewRequest("HEAD", "/api/auth/envoy?path=/hello", nil)
886886
req.Host = "foo.example.com"
887+
req.Header.Set("x-forwarded-host", "foobar.example.com")
888+
req.Header.Set("x-forwarded-proto", "https")
889+
req.Header.Set("x-forwarded-uri", "/foo?bar=foo")
890+
router.ServeHTTP(recorder, req)
891+
892+
assert.Equal(t, http.StatusBadRequest, recorder.Code)
893+
},
894+
},
895+
{
896+
description: "Forward auth and same auth request headers should succeed for nginx",
897+
middlewares: []gin.HandlerFunc{
898+
simpleCtx,
899+
},
900+
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
901+
req := httptest.NewRequest("GET", "/api/auth/nginx", nil)
887902
req.Header.Set("x-forwarded-host", "foo.example.com")
888903
req.Header.Set("x-forwarded-proto", "https")
889904
req.Header.Set("x-forwarded-uri", "/foo?bar=foo")
905+
req.Header.Set("x-original-url", "https://foo.example.com/foo?bar=foo")
906+
router.ServeHTTP(recorder, req)
907+
908+
assert.Equal(t, http.StatusOK, recorder.Code)
909+
},
910+
},
911+
{
912+
description: "Forward auth and ext authz headers should succeed for envoy of they match",
913+
middlewares: []gin.HandlerFunc{
914+
simpleCtx,
915+
},
916+
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
917+
req := httptest.NewRequest("HEAD", "/api/auth/envoy?path=/foo?bar=foo", nil)
918+
req.Host = "foo.example.com"
919+
req.Header.Set("x-forwarded-host", "foo.example.com")
920+
req.Header.Set("x-forwarded-proto", "https")
921+
req.Header.Set("x-forwarded-uri", "/foo?bar=foo")
922+
router.ServeHTTP(recorder, req)
923+
924+
assert.Equal(t, http.StatusOK, recorder.Code)
925+
},
926+
},
927+
{
928+
description: "Proxy without any modules matching should fail",
929+
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
930+
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
890931
router.ServeHTTP(recorder, req)
891932

892933
assert.Equal(t, http.StatusBadRequest, recorder.Code)
@@ -902,6 +943,18 @@ func TestProxyController(t *testing.T) {
902943
assert.Equal(t, http.StatusUnauthorized, recorder.Code)
903944
},
904945
},
946+
{
947+
description: "Unrelated auth modules for proxy don't fail request",
948+
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
949+
req := httptest.NewRequest("GET", "/api/auth/traefik", nil)
950+
req.Header.Set("x-forwarded-host", "path-allow.example.com")
951+
req.Header.Set("x-forwarded-proto", "https")
952+
req.Header.Set("x-forwarded-uri", "/allowed")
953+
req.Header.Set("x-original-url", "https://foobar.example.com/foo")
954+
router.ServeHTTP(recorder, req)
955+
assert.Equal(t, http.StatusOK, recorder.Code)
956+
},
957+
},
905958
}
906959

907960
store := memory.New()

0 commit comments

Comments
 (0)