-
Notifications
You must be signed in to change notification settings - Fork 5.4k
/
dex.go
82 lines (75 loc) · 2.55 KB
/
dex.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
package dex
import (
"bytes"
"fmt"
"html"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"path"
"regexp"
"strconv"
"github.com/argoproj/argo-cd/util/errors"
)
var messageRe = regexp.MustCompile(`<p>(.*)([\s\S]*?)<\/p>`)
// 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
// also be /api/dex (e.g. issuer: https://argocd.example.com/api/dex)
func NewDexHTTPReverseProxy(serverAddr string, baseHRef string) func(writer http.ResponseWriter, request *http.Request) {
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 {
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = resp.Body.Close()
if err != nil {
return err
}
var message string
matches := messageRe.FindSubmatch(b)
if len(matches) > 1 {
message = html.UnescapeString(string(matches[1]))
} else {
message = "Unknown error"
}
resp.ContentLength = 0
resp.Header.Set("Content-Length", strconv.Itoa(0))
resp.Header.Set("Location", fmt.Sprintf("%s?sso_error=%s", path.Join(baseHRef, "login"), url.QueryEscape(message)))
resp.StatusCode = http.StatusSeeOther
resp.Body = ioutil.NopCloser(bytes.NewReader(make([]byte, 0)))
return nil
}
return nil
}
return func(w http.ResponseWriter, r *http.Request) {
proxy.ServeHTTP(w, r)
}
}
// NewDexRewriteURLRoundTripper creates a new DexRewriteURLRoundTripper
func NewDexRewriteURLRoundTripper(dexServerAddr string, T http.RoundTripper) DexRewriteURLRoundTripper {
dexURL, _ := url.Parse(dexServerAddr)
return DexRewriteURLRoundTripper{
DexURL: dexURL,
T: T,
}
}
// DexRewriteURLRoundTripper is an HTTP RoundTripper to rewrite HTTP requests to the specified
// dex server address. This is used when reverse proxying Dex to avoid the API server from
// unnecessarily communicating to Argo CD through its externally facing load balancer, which is not
// always permitted in firewalled/air-gapped networks.
type DexRewriteURLRoundTripper struct {
DexURL *url.URL
T http.RoundTripper
}
func (s DexRewriteURLRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
r.URL.Host = s.DexURL.Host
r.URL.Scheme = s.DexURL.Scheme
return s.T.RoundTrip(r)
}