Skip to content

Commit 7f7e6be

Browse files
holimanfjl
authored andcommittedOct 3, 2022
cmd/geth, cmd/utils: geth attach with custom headers (ethereum#25829)
This PR makes it possible to set custom headers, in particular for two scenarios: - geth attach - geth commands which can use --remotedb, e..g geth db inspect The ability to use custom headers is typically useful for connecting to cloud-apis, e.g. providing an infura- or alchemy key, or for that matter access-keys for environments behind cloudflare. Co-authored-by: Felix Lange <fjl@twurst.com>
1 parent adf5aa6 commit 7f7e6be

File tree

4 files changed

+128
-42
lines changed

4 files changed

+128
-42
lines changed
 

‎cmd/geth/attach_test.go

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// Copyright 2022 The go-ethereum Authors
2+
// This file is part of the go-ethereum library.
3+
//
4+
// The go-ethereum library is free software: you can redistribute it and/or modify
5+
// it under the terms of the GNU Lesser General Public License as published by
6+
// the Free Software Foundation, either version 3 of the License, or
7+
// (at your option) any later version.
8+
//
9+
// The go-ethereum library is distributed in the hope that it will be useful,
10+
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
// GNU Lesser General Public License for more details.
13+
//
14+
// You should have received a copy of the GNU Lesser General Public License
15+
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16+
17+
package main
18+
19+
import (
20+
"fmt"
21+
"net"
22+
"net/http"
23+
"sync/atomic"
24+
"testing"
25+
)
26+
27+
type testHandler struct {
28+
body func(http.ResponseWriter, *http.Request)
29+
}
30+
31+
func (t *testHandler) ServeHTTP(out http.ResponseWriter, in *http.Request) {
32+
t.body(out, in)
33+
}
34+
35+
// TestAttachWithHeaders tests that 'geth attach' with custom headers works, i.e
36+
// that custom headers are forwarded to the target.
37+
func TestAttachWithHeaders(t *testing.T) {
38+
t.Parallel()
39+
ln, err := net.Listen("tcp", "localhost:0")
40+
if err != nil {
41+
t.Fatal(err)
42+
}
43+
port := ln.Addr().(*net.TCPAddr).Port
44+
testReceiveHeaders(t, ln, "attach", "-H", "first: one", "-H", "second: two", fmt.Sprintf("http://localhost:%d", port))
45+
// This way to do it fails due to flag ordering:
46+
//
47+
// testReceiveHeaders(t, ln, "-H", "first: one", "-H", "second: two", "attach", fmt.Sprintf("http://localhost:%d", port))
48+
// This is fixed in a follow-up PR.
49+
}
50+
51+
// TestAttachWithHeaders tests that 'geth db --remotedb' with custom headers works, i.e
52+
// that custom headers are forwarded to the target.
53+
func TestRemoteDbWithHeaders(t *testing.T) {
54+
t.Parallel()
55+
ln, err := net.Listen("tcp", "localhost:0")
56+
if err != nil {
57+
t.Fatal(err)
58+
}
59+
port := ln.Addr().(*net.TCPAddr).Port
60+
testReceiveHeaders(t, ln, "db", "metadata", "--remotedb", fmt.Sprintf("http://localhost:%d", port), "-H", "first: one", "-H", "second: two")
61+
}
62+
63+
func testReceiveHeaders(t *testing.T, ln net.Listener, gethArgs ...string) {
64+
var ok uint32
65+
server := &http.Server{
66+
Addr: "localhost:0",
67+
Handler: &testHandler{func(w http.ResponseWriter, r *http.Request) {
68+
// We expect two headers
69+
if have, want := r.Header.Get("first"), "one"; have != want {
70+
t.Fatalf("missing header, have %v want %v", have, want)
71+
}
72+
if have, want := r.Header.Get("second"), "two"; have != want {
73+
t.Fatalf("missing header, have %v want %v", have, want)
74+
}
75+
atomic.StoreUint32(&ok, 1)
76+
}}}
77+
go server.Serve(ln)
78+
defer server.Close()
79+
runGeth(t, gethArgs...).WaitExit()
80+
if atomic.LoadUint32(&ok) != 1 {
81+
t.Fatal("Test fail, expected invocation to succeed")
82+
}
83+
}

‎cmd/geth/consolecmd.go

+2-19
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ import (
2323
"github.com/ethereum/go-ethereum/cmd/utils"
2424
"github.com/ethereum/go-ethereum/console"
2525
"github.com/ethereum/go-ethereum/internal/flags"
26-
"github.com/ethereum/go-ethereum/node"
27-
"github.com/ethereum/go-ethereum/rpc"
2826
"github.com/urfave/cli/v2"
2927
)
3028

@@ -47,7 +45,7 @@ See https://geth.ethereum.org/docs/interface/javascript-console.`,
4745
Name: "attach",
4846
Usage: "Start an interactive JavaScript environment (connect to node)",
4947
ArgsUsage: "[endpoint]",
50-
Flags: flags.Merge([]cli.Flag{utils.DataDirFlag}, consoleFlags),
48+
Flags: flags.Merge([]cli.Flag{utils.DataDirFlag, utils.HttpHeaderFlag}, consoleFlags),
5149
Description: `
5250
The Geth console is an interactive shell for the JavaScript runtime environment
5351
which exposes a node admin interface as well as the Ðapp JavaScript API.
@@ -118,14 +116,13 @@ func remoteConsole(ctx *cli.Context) error {
118116
if ctx.Args().Len() > 1 {
119117
utils.Fatalf("invalid command-line: too many arguments")
120118
}
121-
122119
endpoint := ctx.Args().First()
123120
if endpoint == "" {
124121
cfg := defaultNodeConfig()
125122
utils.SetDataDir(ctx, &cfg)
126123
endpoint = cfg.IPCEndpoint()
127124
}
128-
client, err := dialRPC(endpoint)
125+
client, err := utils.DialRPCWithHeaders(endpoint, ctx.StringSlice(utils.HttpHeaderFlag.Name))
129126
if err != nil {
130127
utils.Fatalf("Unable to attach to remote geth: %v", err)
131128
}
@@ -164,17 +161,3 @@ func ephemeralConsole(ctx *cli.Context) error {
164161
geth --exec "%s" console`, b.String())
165162
return nil
166163
}
167-
168-
// dialRPC returns a RPC client which connects to the given endpoint.
169-
// The check for empty endpoint implements the defaulting logic
170-
// for "geth attach" with no argument.
171-
func dialRPC(endpoint string) (*rpc.Client, error) {
172-
if endpoint == "" {
173-
endpoint = node.DefaultIPCEndpoint(clientIdentifier)
174-
} else if strings.HasPrefix(endpoint, "rpc:") || strings.HasPrefix(endpoint, "ipc:") {
175-
// Backwards compatibility with geth < 1.5 which required
176-
// these prefixes.
177-
endpoint = endpoint[4:]
178-
}
179-
return rpc.Dial(endpoint)
180-
}

‎cmd/utils/flags.go

+41-2
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,13 @@
1818
package utils
1919

2020
import (
21+
"context"
2122
"crypto/ecdsa"
23+
"errors"
2224
"fmt"
2325
"math"
2426
"math/big"
27+
"net/http"
2528
"os"
2629
"path/filepath"
2730
godebug "runtime/debug"
@@ -976,6 +979,13 @@ var (
976979
Value: metrics.DefaultConfig.InfluxDBOrganization,
977980
Category: flags.MetricsCategory,
978981
}
982+
983+
HttpHeaderFlag = &cli.StringSliceFlag{
984+
Name: "header",
985+
Aliases: []string{"H"},
986+
Usage: "Pass custom headers to the RPC server wheng using --" + RemoteDBFlag.Name + " or the geth attach console.",
987+
Category: flags.NetworkingCategory,
988+
}
979989
)
980990

981991
var (
@@ -995,6 +1005,7 @@ var (
9951005
DataDirFlag,
9961006
AncientFlag,
9971007
RemoteDBFlag,
1008+
HttpHeaderFlag,
9981009
}
9991010
)
10001011

@@ -2125,8 +2136,12 @@ func MakeChainDatabase(ctx *cli.Context, stack *node.Node, readonly bool) ethdb.
21252136
)
21262137
switch {
21272138
case ctx.IsSet(RemoteDBFlag.Name):
2128-
log.Info("Using remote db", "url", ctx.String(RemoteDBFlag.Name))
2129-
chainDb, err = remotedb.New(ctx.String(RemoteDBFlag.Name))
2139+
log.Info("Using remote db", "url", ctx.String(RemoteDBFlag.Name), "headers", len(ctx.StringSlice(HttpHeaderFlag.Name)))
2140+
client, err := DialRPCWithHeaders(ctx.String(RemoteDBFlag.Name), ctx.StringSlice(HttpHeaderFlag.Name))
2141+
if err != nil {
2142+
break
2143+
}
2144+
chainDb = remotedb.New(client)
21302145
case ctx.String(SyncModeFlag.Name) == "light":
21312146
chainDb, err = stack.OpenDatabase("lightchaindata", cache, handles, "", readonly)
21322147
default:
@@ -2148,6 +2163,30 @@ func IsNetworkPreset(ctx *cli.Context) bool {
21482163
return false
21492164
}
21502165

2166+
func DialRPCWithHeaders(endpoint string, headers []string) (*rpc.Client, error) {
2167+
if endpoint == "" {
2168+
return nil, errors.New("endpoint must be specified")
2169+
}
2170+
if strings.HasPrefix(endpoint, "rpc:") || strings.HasPrefix(endpoint, "ipc:") {
2171+
// Backwards compatibility with geth < 1.5 which required
2172+
// these prefixes.
2173+
endpoint = endpoint[4:]
2174+
}
2175+
var opts []rpc.ClientOption
2176+
if len(headers) > 0 {
2177+
var customHeaders = make(http.Header)
2178+
for _, h := range headers {
2179+
kv := strings.Split(h, ":")
2180+
if len(kv) != 2 {
2181+
return nil, fmt.Errorf("invalid http header directive: %q", h)
2182+
}
2183+
customHeaders.Add(kv[0], kv[1])
2184+
}
2185+
opts = append(opts, rpc.WithHeaders(customHeaders))
2186+
}
2187+
return rpc.DialOptions(context.Background(), endpoint, opts...)
2188+
}
2189+
21512190
func MakeGenesis(ctx *cli.Context) *core.Genesis {
21522191
var genesis *core.Genesis
21532192
switch {

‎ethdb/remotedb/remotedb.go

+2-21
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,6 @@
2222
package remotedb
2323

2424
import (
25-
"errors"
26-
"strings"
27-
2825
"github.com/ethereum/go-ethereum/common/hexutil"
2926
"github.com/ethereum/go-ethereum/ethdb"
3027
"github.com/ethereum/go-ethereum/rpc"
@@ -150,24 +147,8 @@ func (db *Database) Close() error {
150147
return nil
151148
}
152149

153-
func dialRPC(endpoint string) (*rpc.Client, error) {
154-
if endpoint == "" {
155-
return nil, errors.New("endpoint must be specified")
156-
}
157-
if strings.HasPrefix(endpoint, "rpc:") || strings.HasPrefix(endpoint, "ipc:") {
158-
// Backwards compatibility with geth < 1.5 which required
159-
// these prefixes.
160-
endpoint = endpoint[4:]
161-
}
162-
return rpc.Dial(endpoint)
163-
}
164-
165-
func New(endpoint string) (ethdb.Database, error) {
166-
client, err := dialRPC(endpoint)
167-
if err != nil {
168-
return nil, err
169-
}
150+
func New(client *rpc.Client) ethdb.Database {
170151
return &Database{
171152
remote: client,
172-
}, nil
153+
}
173154
}

0 commit comments

Comments
 (0)
Please sign in to comment.