Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 51 additions & 15 deletions internal/web/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ func (s *Server) Mux() *http.ServeMux {
if s.GraphQLEnabled && s.GraphQLUpstream != "" {
if target, err := parseProxyUpstream(s.GraphQLUpstream); err == nil {
proxy := httputil.NewSingleHostReverseProxy(target)
proxy.Transport = newUpstreamTransport()
mux.Handle("/graphql", proxy)
mux.Handle("/graphql/", proxy)
mux.Handle("/graphiql", proxy)
Expand All @@ -114,11 +115,17 @@ func (s *Server) Mux() *http.ServeMux {

// parseProxyUpstream parses and validates the GraphQL reverse-proxy
// upstream URL. Reject anything that isn't http/https and anything that
// resolves outside loopback or RFC1918/ULA private space — without this
// points outside loopback or RFC1918/ULA private space — without this
// the indexer becomes a SSRF proxy: a misconfigured GRAPHQL_UPSTREAM
// could be aimed at the AWS metadata service or an arbitrary attacker
// host, and any unauthenticated client of the indexer's web port could
// proxy through it.
//
// A literal IP is checked here. A hostname is not resolved here: at boot
// the graphql container often starts after the indexer, so its name does
// not resolve yet, and failing here would leave /graphql unregistered
// until the indexer restarts. privateDialContext checks every address a
// hostname resolves to on each connection instead.
func parseProxyUpstream(raw string) (*url.URL, error) {
u, err := url.Parse(raw)
if err != nil {
Expand All @@ -131,23 +138,52 @@ func parseProxyUpstream(raw string) (*url.URL, error) {
return nil, fmt.Errorf("missing host")
}
host := u.Hostname()
// Resolve the host. ResolveIPAddr returns a single IP — fine for the
// validation gate; we're checking that no public IP is reachable, so
// any single resolved address tells us whether the host points at a
// safe range. For multi-A-record hostnames Go uses LookupIP elsewhere
// in the stack, but the proxy only needs to know if the *target* is
// allowed to be reached.
ips, err := net.LookupIP(host)
if err != nil {
return nil, fmt.Errorf("resolve %q: %w", host, err)
if ip := net.ParseIP(host); ip != nil && !isPrivateOrLoopback(ip) {
return nil, fmt.Errorf("upstream host %q is a public IP — refusing to proxy", host)
}
for _, ip := range ips {
if !isPrivateOrLoopback(ip) {
return nil, fmt.Errorf("upstream host %q resolves to public IP %s — refusing to proxy",
host, ip)
return u, nil
}

// newUpstreamTransport is the GraphQL proxy's transport. It never goes
// through HTTP(S)_PROXY and dials only addresses privateDialContext allows.
func newUpstreamTransport() *http.Transport {
t := http.DefaultTransport.(*http.Transport).Clone()
t.Proxy = nil
t.DialContext = privateDialContext(&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second})
return t
}

// privateDialContext resolves the upstream host on every connection,
// refuses it if any address is outside loopback or RFC1918/ULA space, and
// then dials a vetted IP itself, so the DNS answer cannot change between
// the check and the connect. An upstream that does not resolve yet fails
// only that request (the proxy answers 502) and works once it resolves.
func privateDialContext(dialer *net.Dialer) func(ctx context.Context, network, addr string) (net.Conn, error) {
return func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
if err != nil {
return nil, fmt.Errorf("resolve %q: %w", host, err)
}
for _, ip := range ips {
if !isPrivateOrLoopback(ip) {
return nil, fmt.Errorf("upstream host %q resolves to public IP %s — refusing to proxy",
host, ip)
}
}
var lastErr error
for _, ip := range ips {
conn, err := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
if err == nil {
return conn, nil
}
lastErr = err
}
return nil, lastErr
}
return u, nil
}

func isPrivateOrLoopback(ip net.IP) bool {
Expand Down
100 changes: 100 additions & 0 deletions internal/web/server_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package web

import (
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)

func TestParseProxyUpstream(t *testing.T) {
cases := []struct {
raw string
wantErr bool
}{
// A hostname is accepted without resolving it: at boot the graphql
// container may not exist yet. .invalid never resolves (RFC 2606).
{"http://graphql.invalid:5000", false},
{"http://127.0.0.1:5000", false},
{"http://10.0.0.5:5000/graphql", false},
{"ftp://graphql:5000", true},
{"http://", true},
{"http://8.8.8.8:5000", true},
{"http://169.254.169.254/latest/meta-data", true},
}
for _, c := range cases {
_, err := parseProxyUpstream(c.raw)
if (err != nil) != c.wantErr {
t.Errorf("parseProxyUpstream(%q) error = %v, want error %v", c.raw, err, c.wantErr)
}
}
}

func TestPrivateDialContextRefusesPublicAddresses(t *testing.T) {
dial := privateDialContext(&net.Dialer{Timeout: time.Second})
for _, addr := range []string{"8.8.8.8:80", "169.254.169.254:80"} {
conn, err := dial(context.Background(), "tcp", addr)
if err == nil {
conn.Close()
t.Fatalf("dial %s succeeded, want refusal", addr)
}
if !strings.Contains(err.Error(), "refusing to proxy") {
t.Errorf("dial %s error = %v, want a refusal", addr, err)
}
}
}

func graphqlStatus(t *testing.T, mux http.Handler) (int, string) {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/graphql", strings.NewReader(`{"query":"{ __typename }"}`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
body, _ := io.ReadAll(rec.Body)
return rec.Code, string(body)
}

func TestGraphQLProxyRegisteredWhenUpstreamDoesNotResolve(t *testing.T) {
s := &Server{GraphQLEnabled: true, GraphQLUpstream: "http://graphql.invalid:5000"}
code, _ := graphqlStatus(t, s.Mux())
if code != http.StatusBadGateway {
t.Fatalf("/graphql status = %d, want %d (proxy registered, upstream not up yet)", code, http.StatusBadGateway)
}
}

func TestGraphQLProxyRecoversWhenUpstreamStarts(t *testing.T) {
// Reserve a loopback port, then free it so the upstream is down at first.
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
ln.Close()

s := &Server{GraphQLEnabled: true, GraphQLUpstream: "http://" + addr}
mux := s.Mux()

if code, _ := graphqlStatus(t, mux); code != http.StatusBadGateway {
t.Fatalf("before upstream starts: /graphql status = %d, want %d", code, http.StatusBadGateway)
}

ln, err = net.Listen("tcp", addr)
if err != nil {
t.Skipf("could not re-listen on %s: %v", addr, err)
}
upstream := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"data":{"__typename":"Query"}}`)
})}
go func() { _ = upstream.Serve(ln) }()
defer upstream.Close()

code, body := graphqlStatus(t, mux)
if code != http.StatusOK || !strings.Contains(body, `"__typename":"Query"`) {
t.Fatalf("after upstream starts: /graphql = %d %q, want 200 from the upstream", code, body)
}
}
Loading