Migrate proxy logic to the API package (#4216)

This allows arbitrary programs to have an easy mechanism to make
connections through Boundary using Go. Internal cluster tests and test
helpers have been migrated to use this package, as well as the `connect`
command.

---------

Co-authored-by: Johan Brandhorst-Satzkorn <johan.brandhorst@gmail.com>
This commit is contained in:
Jeff MitchellandJohan Brandhorst-Satzkorn authored and GitHub committed 2024-01-21 22:34:33 -05:00
1 parent 422bd6c224
commit fff5f9506f
27 files changed
+1593 -546

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package proxy
import (
"context"
"net"
"net/netip"
"sync"
"testing"
"time"
"github.com/hashicorp/boundary/api/proxy"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/internal/cmd/config"
"github.com/hashicorp/boundary/internal/daemon/controller"
"github.com/hashicorp/boundary/internal/daemon/worker"
"github.com/hashicorp/boundary/internal/tests/helper"
"github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/require"
_ "github.com/hashicorp/boundary/internal/daemon/controller/handlers/targets/tcp"
)
// TestConnectionsLeft tests general proxy functionality, as well as the
// mechanism to notify the caller of the number of connections left on the
// caller's channel and in the ConnectionsLeft function.
func TestConnectionsLeft(t *testing.T) {
require := require.New(t)
logger := hclog.New(&hclog.LoggerOptions{
Name: t.Name(),
Level: hclog.Trace,
})
// Create controller and worker
conf, err := config.DevController()
require.NoError(err)
c1 := controller.NewTestController(t, &controller.TestControllerOpts{
Config: conf,
InitialResourcesSuffix: "1234567890",
Logger: logger.Named("c1"),
WorkerStatusGracePeriodDuration: helper.DefaultWorkerStatusGracePeriod,
})
defer c1.Shutdown()
helper.ExpectWorkers(t, c1)
w1 := worker.NewTestWorker(t, &worker.TestWorkerOpts{
WorkerAuthKms: c1.Config().WorkerAuthKms,
InitialUpstreams: c1.ClusterAddrs(),
Logger: logger.Named("w1"),
SuccessfulStatusGracePeriodDuration: helper.DefaultWorkerStatusGracePeriod,
})
defer w1.Shutdown()
err = w1.Worker().WaitForNextSuccessfulStatusUpdate()
require.NoError(err)
err = c1.WaitForNextWorkerStatusUpdate(w1.Name())
require.NoError(err)
helper.ExpectWorkers(t, c1, w1)
// Connect target
client := c1.Client()
client.SetToken(c1.Token().Token)
tcl := targets.NewClient(client)
tgt, err := tcl.Read(c1.Context(), "ttcp_1234567890")
require.NoError(err)
require.NotNil(tgt)
// Create test server, update default port on target
ts := helper.NewTestTcpServer(t)
require.NotNil(t, ts)
defer ts.Close()
var sessionConnsLimit int32 = 4
tgt, err = tcl.Update(c1.Context(), tgt.Item.Id, tgt.Item.Version, targets.WithTcpTargetDefaultPort(ts.Port()), targets.WithSessionConnectionLimit(sessionConnsLimit))
require.NoError(err)
require.NotNil(tgt)
// Authorize session to get authorization data
sess, err := tcl.AuthorizeSession(c1.Context(), tgt.Item.Id)
require.NoError(err)
sessAuthz, err := sess.GetSessionAuthorization()
require.NoError(err)
// Create a context we can cancel to stop the proxy, a channel for conns
// left, and a waitgroup to ensure cleanup
pxyCtx, pxyCancel := context.WithCancel(c1.Context())
defer pxyCancel()
connsLeftCh := make(chan int32)
wg := new(sync.WaitGroup)
pxy, err := proxy.New(pxyCtx, sessAuthz.AuthorizationToken, proxy.WithConnectionsLeftCh(connsLeftCh))
require.NoError(err)
wg.Add(1)
go func() {
defer wg.Done()
require.NoError(pxy.Start())
// Ensure that starting it again does not actually result in it starting
// again
require.ErrorContains(pxy.Start(), "already started")
}()
addr := pxy.ListenerAddress(context.Background())
require.NotEmpty(addr)
addrPort, err := netip.ParseAddrPort(addr)
require.NoError(err)
echo := []byte("echo")
readBuf := make([]byte, len(echo))
// While we have sessions left, expect no error and to read and write
// through the proxy, and to read the conns left from the channel. Once we
// have hit the connection limit, we expect an error on dial.
for i := sessionConnsLimit; i >= 0; i-- {
// Give time for the listener to be closed. The information about conns
// left comes from upstream responses and we can circle around too fast
// to have the listener be closed, leading to indeterminate results.
time.Sleep(time.Second)
conn, err := net.DialTCP("tcp", nil, net.TCPAddrFromAddrPort(addrPort))
if i == 0 {
require.Error(err)
break
}
require.NoError(err)
written, err := conn.Write(echo)
require.NoError(err)
require.Equal(written, len(echo))
read, err := conn.Read(readBuf)
require.NoError(err)
require.Equal(read, len(echo))
connsLeft := <-connsLeftCh
require.Equal(i-1, connsLeft)
require.Equal(i-1, pxy.ConnectionsLeft())
}
pxyCancel()
// Wait to ensure cleanup and that the second-start logic works
wg.Wait()
}
+11 -5
View File
@@ -106,7 +106,9 @@ func testWorkerSessionCleanupSingle(burdenCase timeoutBurdenType) func(t *testin
dawdle.WithWbufSize(256),
)
require.NoError(err)
defer proxy.Close()
t.Cleanup(func() {
proxy.Close()
})
require.NotEmpty(t, proxy.ListenerAddr())
w1 := worker.NewTestWorker(t, &worker.TestWorkerOpts{
@@ -138,7 +140,7 @@ func testWorkerSessionCleanupSingle(burdenCase timeoutBurdenType) func(t *testin
// Create test server, update default port on target
ts := helper.NewTestTcpServer(t)
require.NotNil(t, ts)
defer ts.Close()
t.Cleanup(ts.Close)
tgt, err = tcl.Update(ctx, tgt.Item.Id, tgt.Item.Version, targets.WithTcpTargetDefaultPort(ts.Port()), targets.WithSessionConnectionLimit(-1))
require.NoError(err)
require.NotNil(tgt)
@@ -248,7 +250,9 @@ func testWorkerSessionCleanupMulti(burdenCase timeoutBurdenType) func(t *testing
dawdle.WithWbufSize(256),
)
require.NoError(err)
defer p1.Close()
t.Cleanup(func() {
p1.Close()
})
require.NotEmpty(t, p1.ListenerAddr())
// *************
@@ -261,7 +265,9 @@ func testWorkerSessionCleanupMulti(burdenCase timeoutBurdenType) func(t *testing
dawdle.WithWbufSize(256),
)
require.NoError(err)
defer p2.Close()
t.Cleanup(func() {
p2.Close()
})
require.NotEmpty(t, p2.ListenerAddr())
// ************
@@ -303,7 +309,7 @@ func testWorkerSessionCleanupMulti(burdenCase timeoutBurdenType) func(t *testing
// Create test server, update default port on target
ts := helper.NewTestTcpServer(t)
require.NotNil(ts)
defer ts.Close()
t.Cleanup(ts.Close)
tgt, err = tcl.Update(ctx, tgt.Item.Id, tgt.Item.Version, targets.WithTcpTargetDefaultPort(ts.Port()), targets.WithSessionConnectionLimit(-1))
require.NoError(err)
require.NotNil(tgt)
+8 -4
View File
@@ -44,7 +44,7 @@ func TestWorkerSessionProxyMultipleConnections(t *testing.T) {
PublicClusterAddr: pl.Addr().String(),
WorkerStatusGracePeriodDuration: helper.DefaultWorkerStatusGracePeriod,
})
defer c1.Shutdown()
t.Cleanup(c1.Shutdown)
helper.ExpectWorkers(t, c1)
@@ -56,7 +56,9 @@ func TestWorkerSessionProxyMultipleConnections(t *testing.T) {
dawdle.WithWbufSize(256),
)
require.NoError(err)
defer proxy.Close()
t.Cleanup(func() {
proxy.Close()
})
require.NotEmpty(t, proxy.ListenerAddr())
w1 := worker.NewTestWorker(t, &worker.TestWorkerOpts{
@@ -65,7 +67,7 @@ func TestWorkerSessionProxyMultipleConnections(t *testing.T) {
Logger: logger.Named("w1"),
SuccessfulStatusGracePeriodDuration: helper.DefaultWorkerStatusGracePeriod,
})
defer w1.Shutdown()
t.Cleanup(w1.Shutdown)
err = w1.Worker().WaitForNextSuccessfulStatusUpdate()
require.NoError(err)
@@ -89,7 +91,9 @@ func TestWorkerSessionProxyMultipleConnections(t *testing.T) {
// Create test server, update default port on target
ts := helper.NewTestTcpServer(t)
require.NotNil(t, ts)
defer ts.Close()
t.Cleanup(ts.Close)
t.Logf("test server listening on port %d", ts.Port())
tgt, err = tcl.Update(ctx, tgt.Item.Id, tgt.Item.Version, targets.WithTcpTargetDefaultPort(ts.Port()), targets.WithSessionConnectionLimit(-1))
require.NoError(err)
require.NotNil(tgt)
@@ -10,11 +10,13 @@ import (
"crypto/x509"
"errors"
"fmt"
"net"
"net/http"
"sync"
"testing"
"time"
apiproxy "github.com/hashicorp/boundary/api/proxy"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/cmd/config"
@@ -23,6 +25,7 @@ import (
"github.com/hashicorp/boundary/internal/daemon/worker"
"github.com/hashicorp/boundary/internal/event"
"github.com/hashicorp/boundary/internal/tests/helper"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-hclog"
"github.com/stretchr/testify/require"
"nhooyr.io/websocket"
@@ -64,6 +67,7 @@ func TestCustomX509Verification_Client(t *testing.T) {
err = w1.Worker().WaitForNextSuccessfulStatusUpdate()
req.NoError(err)
helper.ExpectWorkers(t, c1, w1)
// Connect target
client := c1.Client()
@@ -104,17 +108,26 @@ func TestCustomX509Verification_Client(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
require := require.New(t)
sess := helper.NewTestSession(ctx, t, tcl, "ttcp_1234567890")
sar, err := tcl.AuthorizeSession(ctx, "ttcp_1234567890")
require.NoError(err)
require.NotNil(sar)
sessAuth, err := sar.GetSessionAuthorization()
require.NoError(err)
sessAuthzData, err := sessAuth.GetSessionAuthorizationData()
require.NoError(err)
require.LessOrEqual(1, len(sessAuthzData.WorkerInfo))
tlsConf := apiproxy.TestClientTlsConfig(t, sessAuth.AuthorizationToken, apiproxy.WithWorkerHost(sessAuth.SessionId))
certPool := tc.certPool
if certPool == nil {
parsedCert, err := x509.ParseCertificate(sess.SessionAuthzData.Certificate)
parsedCert, err := x509.ParseCertificate(sessAuthzData.Certificate)
require.NoError(err)
certPool = x509.NewCertPool()
certPool.AddCert(parsedCert)
}
dnsName := sess.SessionId
dnsName := sessAuth.SessionId
if tc.dnsName != nil {
dnsName = tc.dnsName.String()
}
@@ -127,7 +140,7 @@ func TestCustomX509Verification_Client(t *testing.T) {
x509.ExtKeyUsageServerAuth,
},
}
sess.Transport.TLSClientConfig.VerifyConnection = func(cs tls.ConnectionState) error {
tlsConf.VerifyConnection = func(cs tls.ConnectionState) error {
// Go will not run this without at least one peer certificate, but
// doesn't hurt to check
if len(cs.PeerCertificates) == 0 {
@@ -136,12 +149,24 @@ func TestCustomX509Verification_Client(t *testing.T) {
_, err := cs.PeerCertificates[0].Verify(verifyOpts)
return err
}
transport := cleanhttp.DefaultTransport()
transport.DisableKeepAlives = false
// This isn't/shouldn't used anyways really because the connection is
// hijacked, just setting for completeness
transport.IdleConnTimeout = 0
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// time.Sleep(1000 * time.Second)
dialer := &tls.Dialer{Config: tlsConf}
return dialer.DialContext(ctx, network, addr)
}
conn, _, err := websocket.Dial(
ctx,
fmt.Sprintf("wss://%s/v1/proxy", sess.WorkerAddr),
fmt.Sprintf("ws://%s/v1/proxy", sessAuthzData.WorkerInfo[0].Address),
&websocket.DialOptions{
HTTPClient: &http.Client{
Transport: sess.Transport,
Transport: transport,
},
Subprotocols: []string{globals.TcpProxyV1},
},
@@ -220,14 +245,33 @@ func testCustomX509Verification_Server(ec event.TestConfig, certPool *x509.CertP
req.NoError(err)
req.NotNil(tgt)
sess := helper.NewTestSession(ctx, t, tcl, "ttcp_1234567890")
sar, err := tcl.AuthorizeSession(ctx, "ttcp_1234567890")
req.NoError(err)
req.NotNil(sar)
sessAuth, err := sar.GetSessionAuthorization()
req.NoError(err)
sessAuthzData, err := sessAuth.GetSessionAuthorizationData()
req.NoError(err)
req.LessOrEqual(1, len(sessAuthzData.WorkerInfo))
tlsConf := apiproxy.TestClientTlsConfig(t, sessAuth.AuthorizationToken, apiproxy.WithWorkerHost(sessAuth.SessionId))
transport := cleanhttp.DefaultTransport()
transport.DisableKeepAlives = false
// This isn't/shouldn't used anyways really because the connection is
// hijacked, just setting for completeness
transport.IdleConnTimeout = 0
transport.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
// time.Sleep(1000 * time.Second)
dialer := &tls.Dialer{Config: tlsConf}
return dialer.DialContext(ctx, network, addr)
}
conn, _, err := websocket.Dial(
ctx,
fmt.Sprintf("wss://%s/v1/proxy", sess.WorkerAddr),
fmt.Sprintf("wss://%s/v1/proxy", sessAuthzData.WorkerInfo[0].Address),
&websocket.DialOptions{
HTTPClient: &http.Client{
Transport: sess.Transport,
Transport: transport,
},
Subprotocols: []string{globals.TcpProxyV1},
},
+45
View File
@@ -0,0 +1,45 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package helper
// getOpts iterates the inbound Options and returns a struct and any errors
func getOpts(opt ...Option) (*Options, error) {
opts := getDefaultOptions()
for _, o := range opt {
if o == nil {
continue
}
if err := o(opts); err != nil {
return nil, err
}
}
return opts, nil
}
// Options contains various options. The values are exported since the options
// are parsed in various other packages.
type Options struct {
WithSkipSessionTeardown bool
}
// Option is a function that takes in an options struct and sets values or
// returns an error
type Option func(*Options) error
func getDefaultOptions() *Options {
return &Options{}
}
// WithSkipSessionTeardown can be used to override the normal behavior of the
// session sending a teardown request to the worker on completion. This is
// useful if you know that this will result in an error (for instance, if the
// worker is going to be offline) and want to avoid the attempted connection or
// avoid the error rather than ignore it.
func WithSkipSessionTeardown(with bool) Option {
return func(o *Options) error {
o.WithSkipSessionTeardown = with
return nil
}
}
+43 -111
View File
@@ -7,32 +7,21 @@ import (
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"net/http"
"reflect"
"strconv"
"testing"
"time"
"github.com/cenkalti/backoff/v4"
apiproxy "github.com/hashicorp/boundary/api/proxy"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/cmd/commands/connect"
"github.com/hashicorp/boundary/internal/daemon/controller"
"github.com/hashicorp/boundary/internal/daemon/controller/common"
"github.com/hashicorp/boundary/internal/daemon/worker"
"github.com/hashicorp/boundary/internal/session"
targetspb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/targets"
"github.com/hashicorp/boundary/sdk/pbs/proxy"
"github.com/hashicorp/boundary/sdk/wspb"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-secure-stdlib/base62"
"github.com/mr-tron/base58"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"nhooyr.io/websocket"
)
@@ -58,124 +47,67 @@ const (
// TestSession represents an authorized session.
type TestSession struct {
SessionId string
WorkerAddr string
Transport *http.Transport
tofuToken string
connectionsLeft int32
SessionAuthzData *targetspb.SessionAuthorizationData
proxy *apiproxy.ClientProxy
SessionId string
}
// NewTestSession authorizes a session and creates all of the data
// necessary to initialize.
// NewTestSession authorizes a session and starts a client proxy. Connections
// through the proxy can be established via the `connect` function.
func NewTestSession(
ctx context.Context,
t *testing.T,
tcl *targets.Client,
targetId string,
opt ...Option,
) *TestSession {
t.Helper()
require := require.New(t)
ctx, cancel := context.WithCancel(ctx)
require, assert := require.New(t), assert.New(t)
opts, err := getOpts(opt...)
require.NoError(err)
sar, err := tcl.AuthorizeSession(ctx, targetId)
require.NoError(err)
require.NotNil(sar)
s := &TestSession{
SessionId: sar.Item.SessionId,
}
authzString := sar.GetItem().(*targets.SessionAuthorization).AuthorizationToken
marshaled, err := base58.FastBase58Decoding(authzString)
require.NoError(err)
require.NotZero(marshaled)
s.SessionAuthzData = new(targetspb.SessionAuthorizationData)
err = proto.Unmarshal(marshaled, s.SessionAuthzData)
require.NoError(err)
require.NotZero(s.SessionAuthzData.GetWorkerInfo())
s.WorkerAddr = s.SessionAuthzData.GetWorkerInfo()[0].GetAddress()
tlsConf, err := connect.ClientTlsConfig(s.SessionAuthzData, "")
sessAuth, err := sar.GetSessionAuthorization()
require.NoError(err)
s.Transport = cleanhttp.DefaultTransport()
s.Transport.DisableKeepAlives = false
s.Transport.TLSClientConfig = tlsConf
s.Transport.IdleConnTimeout = 0
return s
}
// connect returns a connected websocket for the stored session,
// connecting to the stored workerAddr with the configured transport.
//
// The returned (wrapped) net.Conn should be ready for communication.
func (s *TestSession) connect(ctx context.Context, t *testing.T) net.Conn {
t.Helper()
require := require.New(t)
var conn *websocket.Conn
var resp *http.Response
var handshakeResult proxy.HandshakeResult
// A retry was added here to mitigate some flakiness.
// Occasionally, `wspb.Read` would throw an error due to "received header with unexpected
// rsv bits set: false:false:true". It was unclear what the cause of this was, so we
// resorted to retrying the connection.
err := backoff.RetryNotify(
func() error {
var err error
conn, resp, err = websocket.Dial(
ctx,
fmt.Sprintf("wss://%s/v1/proxy", s.WorkerAddr),
&websocket.DialOptions{
HTTPClient: &http.Client{
Transport: s.Transport,
},
Subprotocols: []string{globals.TcpProxyV1},
},
)
if err != nil {
return backoff.Permanent(err)
}
if resp.Header.Get("Sec-WebSocket-Protocol") != globals.TcpProxyV1 {
return backoff.Permanent(errors.New(
fmt.Sprintf("Unexpected header. Expected: %s, Actual: %s",
globals.TcpProxyV1,
resp.Header.Get("Sec-WebSocket-Protocol"),
)))
}
// Send and receive/check the handshake.
if s.tofuToken == "" {
s.tofuToken, err = base62.Random(20)
if err != nil {
return backoff.Permanent(errors.New("Error creating token"))
}
}
handshake := proxy.ClientHandshake{TofuToken: s.tofuToken}
t.Logf("Using token: %s", s.tofuToken)
err = wspb.Write(ctx, conn, &handshake)
if err != nil {
return backoff.Permanent(err)
}
return wspb.Read(ctx, conn, &handshakeResult)
},
backoff.WithMaxRetries(backoff.NewConstantBackOff(time.Second), 1),
func(err error, td time.Duration) {
t.Logf("Issue with reading websocket: %s. Retrying...", err)
},
proxy, err := apiproxy.New(
ctx,
sessAuth.AuthorizationToken,
apiproxy.WithWorkerHost(sessAuth.SessionId),
apiproxy.WithSkipSessionTeardown(opts.WithSkipSessionTeardown),
)
require.NoError(err)
// This is just a cursory check to make sure that the handshake is
// populated. We could check connections remaining too, but that
// could legitimately be a trivial (zero) value.
require.NotNil(handshakeResult.GetExpiration())
s.connectionsLeft = handshakeResult.GetConnectionsLeft()
cleanupDone := make(chan struct{}, 1)
go func() {
proxyErr := proxy.Start()
assert.NoError(proxyErr)
close(cleanupDone)
}()
t.Cleanup(func() {
cancel()
<-cleanupDone
})
return websocket.NetConn(ctx, conn, websocket.MessageBinary)
return &TestSession{
proxy: proxy,
SessionId: sessAuth.SessionId,
}
}
// connect returns a connected dialed through the client proxy. The returned
// net.Conn should be ready for communications.
func (s *TestSession) connect(ctx context.Context, t *testing.T) net.Conn {
t.Helper()
conn, err := net.Dial("tcp", s.proxy.ListenerAddress(ctx))
require.NoError(t, err)
return conn
}
// ExpectConnectionStateOnController waits until all connections in a