Skip to content

Commit

Permalink
fix: rewrite Host header in dex reverse proxy (#6183)
Browse files Browse the repository at this point in the history
* fix: rewrite Host header in dex reverse proxy

Signed-off-by: Alexey Khalyavka <[email protected]>

* lint

Signed-off-by: Alexey Khalyavka <[email protected]>
  • Loading branch information
okhaliavka authored May 12, 2021
1 parent 5934094 commit 9bf83b4
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
9 changes: 9 additions & 0 deletions util/dex/dex.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ import (

var messageRe = regexp.MustCompile(`<p>(.*)([\s\S]*?)<\/p>`)

func decorateDirector(director func(req *http.Request), target *url.URL) func(req *http.Request) {
return func(req *http.Request) {
director(req)
req.Host = target.Host
}
}

// NewDexHTTPReverseProxy returns a reverse proxy to the Dex server. Dex is assumed to be configured
// with the external issuer URL muxed to the same path configured in server.go. In other words, if
// Argo CD API server wants to proxy requests at /api/dex, then the dex config yaml issuer URL should
Expand All @@ -25,6 +32,7 @@ func NewDexHTTPReverseProxy(serverAddr string, baseHRef string) func(writer http
target, err := url.Parse(serverAddr)
errors.CheckError(err)
target.Path = baseHRef

proxy := httputil.NewSingleHostReverseProxy(target)
proxy.ModifyResponse = func(resp *http.Response) error {
if resp.StatusCode == 500 {
Expand Down Expand Up @@ -52,6 +60,7 @@ func NewDexHTTPReverseProxy(serverAddr string, baseHRef string) func(writer http
}
return nil
}
proxy.Director = decorateDirector(proxy.Director, target)
return func(w http.ResponseWriter, r *http.Request) {
proxy.ServeHTTP(w, r)
}
Expand Down
5 changes: 5 additions & 0 deletions util/dex/dex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

Expand Down Expand Up @@ -270,18 +271,22 @@ func Test_GenerateDexConfig(t *testing.T) {

func Test_DexReverseProxy(t *testing.T) {
t.Run("Good case", func(t *testing.T) {
var host string
fakeDex := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
host = req.Host
rw.WriteHeader(http.StatusOK)
}))
defer fakeDex.Close()
fmt.Printf("Fake Dex listening on %s\n", fakeDex.URL)
server := httptest.NewServer(http.HandlerFunc(NewDexHTTPReverseProxy(fakeDex.URL, "/")))
fmt.Printf("Fake API Server listening on %s\n", server.URL)
defer server.Close()
target, _ := url.Parse(fakeDex.URL)
resp, err := http.Get(server.URL)
assert.NotNil(t, resp)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, host, target.Host)
fmt.Printf("%s\n", resp.Status)
})

Expand Down

0 comments on commit 9bf83b4

Please sign in to comment.