MCPcopy Index your code
hub / github.com/coder/coder / EnsureXForwardedForHeader

Function EnsureXForwardedForHeader

coderd/httpmw/realip.go:150–186  ·  view source on GitHub ↗

EnsureXForwardedForHeader ensures that the request has an X-Forwarded-For header. It uses the following logic: 1. If we have a direct connection (remoteAddr == proxyAddr), then set it to remoteAddr 2. If we have a proxied connection (remoteAddr != proxyAddr) and X-Forwarded-For doesn't begin with r

(req *http.Request)

Source from the content-addressed store, hash-verified

148// 4. If X-Forwarded-Proto is not set, then it will be set to "https"
149// if req.TLS != nil, otherwise it will be set to "http"
150func EnsureXForwardedForHeader(req *http.Request) error {
151 state := RealIP(req.Context())
152 if state == nil {
153 return xerrors.New("request does not contain realip.State; was it processed by httpmw.ExtractRealIP?")
154 }
155
156 remoteAddr := getRemoteAddress(req.RemoteAddr)
157 if remoteAddr == nil {
158 return xerrors.Errorf("failed to parse remote address: %s", remoteAddr)
159 }
160
161 proxyAddr := getRemoteAddress(state.OriginalRemoteAddr)
162 if proxyAddr == nil {
163 return xerrors.Errorf("failed to parse original address: %s", proxyAddr)
164 }
165
166 if remoteAddr.Equal(proxyAddr) {
167 req.Header.Set(headerXForwardedFor, remoteAddr.String())
168 } else {
169 forwarded := req.Header.Get(headerXForwardedFor)
170 if forwarded == "" || !remoteAddr.Equal(getRemoteAddress(forwarded)) {
171 req.Header.Set(headerXForwardedFor, remoteAddr.String()+","+proxyAddr.String())
172 } else {
173 req.Header.Set(headerXForwardedFor, forwarded+","+proxyAddr.String())
174 }
175 }
176
177 if req.Header.Get(headerXForwardedProto) == "" {
178 if req.TLS != nil {
179 req.Header.Set(headerXForwardedProto, "https")
180 } else {
181 req.Header.Set(headerXForwardedProto, "http")
182 }
183 }
184
185 return nil
186}
187
188// getRemoteAddress extracts the IP address from the given string. If
189// the string contains commas, it assumes that the first part is the

Callers 2

TestApplicationProxyFunction · 0.92
proxyWorkspaceAppMethod · 0.92

Calls 9

RealIPFunction · 0.85
getRemoteAddressFunction · 0.85
ContextMethod · 0.65
NewMethod · 0.65
SetMethod · 0.65
GetMethod · 0.65
ErrorfMethod · 0.45
EqualMethod · 0.45
StringMethod · 0.45

Tested by 1

TestApplicationProxyFunction · 0.74