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:
1 parent
422bd6c224
commit
fff5f9506f
27 files changed
+1593
-546
No files matched your search
@@ -5,38 +5,27 @@ package connect
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/hashicorp/boundary/api"
|
||||
apiproxy "github.com/hashicorp/boundary/api/proxy"
|
||||
"github.com/hashicorp/boundary/api/targets"
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/cmd/base"
|
||||
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/mitchellh/cli"
|
||||
"github.com/mr-tron/base58"
|
||||
"github.com/posener/complete"
|
||||
"go.uber.org/atomic"
|
||||
exec "golang.org/x/sys/execabs"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"nhooyr.io/websocket"
|
||||
)
|
||||
|
||||
const sessionCancelTimeout = 10 * time.Second
|
||||
@@ -48,6 +37,10 @@ type SessionInfo struct {
|
||||
Expiration time.Time `json:"expiration"`
|
||||
ConnectionLimit int32 `json:"connection_limit"`
|
||||
SessionId string `json:"session_id"`
|
||||
Endpoint string `json:"-"`
|
||||
Type string `json:"-"`
|
||||
TargetId string `json:"-"`
|
||||
HostId string `json:"-"`
|
||||
Credentials []*targets.SessionCredential `json:"credentials,omitempty"`
|
||||
}
|
||||
|
||||
@@ -94,16 +87,8 @@ type Command struct {
|
||||
|
||||
Func string
|
||||
|
||||
sessionAuthz *targets.SessionAuthorization
|
||||
sessionAuthzData *targetspb.SessionAuthorizationData
|
||||
sessInfo SessionInfo
|
||||
|
||||
connWg *sync.WaitGroup
|
||||
listenerCloseOnce sync.Once
|
||||
listener *net.TCPListener
|
||||
listenerAddr *net.TCPAddr
|
||||
connsLeftCh chan int32
|
||||
connectionsLeft *atomic.Int32
|
||||
expiration time.Time
|
||||
execCmdReturnValue *atomic.Int32
|
||||
proxyCtx context.Context
|
||||
proxyCancel context.CancelFunc
|
||||
@@ -277,6 +262,14 @@ func (c *Command) Run(args []string) (retCode int) {
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
if c.flagListenPort < 0 || c.flagListenPort > math.MaxUint16 {
|
||||
c.PrintCliError(errors.New("Invalid listen port supplied"))
|
||||
return base.CommandCliError
|
||||
}
|
||||
|
||||
c.proxyCtx, c.proxyCancel = context.WithCancel(c.Context)
|
||||
defer c.proxyCancel()
|
||||
|
||||
switch {
|
||||
case c.flagAuthzToken != "":
|
||||
switch {
|
||||
@@ -316,29 +309,11 @@ func (c *Command) Run(args []string) (retCode int) {
|
||||
}
|
||||
}
|
||||
|
||||
tofuToken, err := base62.Random(20)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Could not derive random bytes for tofu token: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
|
||||
c.connectionsLeft = atomic.NewInt32(0)
|
||||
c.connsLeftCh = make(chan int32)
|
||||
|
||||
if c.flagListenAddr == "" {
|
||||
c.flagListenAddr = "127.0.0.1"
|
||||
}
|
||||
listenAddr := net.ParseIP(c.flagListenAddr)
|
||||
if listenAddr == nil {
|
||||
c.PrintCliError(fmt.Errorf("Could not successfully parse listen address of %s", c.flagListenAddr))
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
authzString := c.flagAuthzToken
|
||||
switch {
|
||||
case authzString != "":
|
||||
if authzString == "-" {
|
||||
authBytes, err := ioutil.ReadAll(os.Stdin)
|
||||
authBytes, err := io.ReadAll(os.Stdin)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("No authorization string was provided and encountered the following error attempting to read it from stdin: %w", err))
|
||||
return base.CommandUserError
|
||||
@@ -358,12 +333,27 @@ func (c *Command) Run(args []string) (retCode int) {
|
||||
if authzString[0] == '{' {
|
||||
// Attempt to decode the JSON output of an authorize-session call
|
||||
// and pull the token out of there
|
||||
c.sessionAuthz = new(targets.SessionAuthorization)
|
||||
if err := json.Unmarshal([]byte(authzString), c.sessionAuthz); err == nil {
|
||||
authzString = c.sessionAuthz.AuthorizationToken
|
||||
sa := new(targets.SessionAuthorization)
|
||||
if err := json.Unmarshal([]byte(authzString), sa); err == nil {
|
||||
authzString = sa.AuthorizationToken
|
||||
}
|
||||
}
|
||||
|
||||
sad, err := targets.SessionAuthorization{AuthorizationToken: authzString}.GetSessionAuthorizationData()
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error decoding session authorization data: %w", err))
|
||||
return base.CommandUserError
|
||||
}
|
||||
c.sessInfo = SessionInfo{
|
||||
Protocol: sad.Type,
|
||||
ConnectionLimit: sad.ConnectionLimit,
|
||||
SessionId: sad.SessionId,
|
||||
Endpoint: sad.Endpoint,
|
||||
Type: sad.Type,
|
||||
TargetId: sad.TargetId,
|
||||
HostId: sad.HostId,
|
||||
}
|
||||
|
||||
default:
|
||||
client, err := c.Client()
|
||||
if c.WrapperCleanupFunc != nil {
|
||||
@@ -402,186 +392,66 @@ func (c *Command) Run(args []string) (retCode int) {
|
||||
c.PrintCliError(fmt.Errorf("Error trying to authorize a session against target: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
c.sessionAuthz = sar.GetItem().(*targets.SessionAuthorization)
|
||||
authzString = c.sessionAuthz.AuthorizationToken
|
||||
}
|
||||
|
||||
marshaled, err := base58.FastBase58Decoding(authzString)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Unable to base58-decode authorization data: %w", err))
|
||||
return base.CommandUserError
|
||||
}
|
||||
if len(marshaled) == 0 {
|
||||
c.PrintCliError(errors.New("Zero length authorization information after decoding"))
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
c.sessionAuthzData = new(targetspb.SessionAuthorizationData)
|
||||
if err := proto.Unmarshal(marshaled, c.sessionAuthzData); err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Unable to proto-decode authorization data: %w", err))
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
if len(c.sessionAuthzData.GetWorkerInfo()) == 0 {
|
||||
c.PrintCliError(errors.New("No workers found in authorization string"))
|
||||
return base.CommandUserError
|
||||
}
|
||||
|
||||
if c.flagListenPort == 0 {
|
||||
c.flagListenPort = int(c.sessionAuthzData.DefaultClientPort)
|
||||
}
|
||||
|
||||
c.connectionsLeft.Store(c.sessionAuthzData.ConnectionLimit)
|
||||
workerAddr := c.sessionAuthzData.GetWorkerInfo()[0].GetAddress()
|
||||
workerHost, _, err := net.SplitHostPort(workerAddr)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "missing port") {
|
||||
workerHost = workerAddr
|
||||
} else {
|
||||
c.PrintCliError(fmt.Errorf("Error splitting worker adddress host/port: %w", err))
|
||||
return base.CommandUserError
|
||||
sa := sar.GetItem().(*targets.SessionAuthorization)
|
||||
c.sessInfo = SessionInfo{
|
||||
Protocol: sa.Type,
|
||||
ConnectionLimit: sa.ConnectionLimit,
|
||||
SessionId: sa.SessionId,
|
||||
Endpoint: sa.Endpoint,
|
||||
Type: sa.Type,
|
||||
TargetId: sa.TargetId,
|
||||
HostId: sa.HostId,
|
||||
Credentials: sa.Credentials,
|
||||
}
|
||||
authzString = sa.AuthorizationToken
|
||||
}
|
||||
|
||||
tlsConf, err := ClientTlsConfig(c.sessionAuthzData, workerHost)
|
||||
var listenAddr netip.AddrPort
|
||||
var addr netip.Addr
|
||||
if c.flagListenAddr == "" {
|
||||
c.flagListenAddr = "127.0.0.1"
|
||||
}
|
||||
addr, err := netip.ParseAddr(c.flagListenAddr)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error creating TLS configuration: %w", err))
|
||||
c.PrintCliError(fmt.Errorf("Error parsing listen address: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
c.expiration = tlsConf.Certificates[0].Leaf.NotAfter
|
||||
listenAddr = netip.AddrPortFrom(addr, uint16(c.flagListenPort))
|
||||
|
||||
// We don't _rely_ on client-side timeout verification but this prevents us
|
||||
// seeming to be ready for a connection that will immediately fail when we
|
||||
// try to actually make it
|
||||
c.proxyCtx, c.proxyCancel = context.WithDeadline(c.Context, c.expiration)
|
||||
defer c.proxyCancel()
|
||||
|
||||
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) {
|
||||
dialer := &tls.Dialer{Config: tlsConf}
|
||||
return dialer.DialContext(ctx, network, addr)
|
||||
connsLeftCh := make(chan int32)
|
||||
apiProxyOpts := []apiproxy.Option{apiproxy.WithConnectionsLeftCh(connsLeftCh)}
|
||||
if listenAddr.IsValid() {
|
||||
apiProxyOpts = append(apiProxyOpts, apiproxy.WithListenAddrPort(listenAddr))
|
||||
}
|
||||
|
||||
c.listener, err = net.ListenTCP("tcp", &net.TCPAddr{
|
||||
IP: listenAddr,
|
||||
Port: c.flagListenPort,
|
||||
})
|
||||
clientProxy, err := apiproxy.New(
|
||||
c.proxyCtx,
|
||||
authzString,
|
||||
apiProxyOpts...,
|
||||
)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error starting listening port: %w", err))
|
||||
c.PrintCliError(fmt.Errorf("Could not create client proxy: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
c.sessInfo.Expiration = clientProxy.SessionExpiration()
|
||||
|
||||
listenerCloseFunc := func() {
|
||||
// Forces the for loop to exist instead of spinning on errors
|
||||
c.connectionsLeft.Store(0)
|
||||
if err := c.listener.Close(); err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error closing listener on shutdown: %w", err))
|
||||
retCode = 2
|
||||
}
|
||||
}
|
||||
clientProxyCloseCh := make(chan struct{})
|
||||
connCountCloseCh := make(chan struct{})
|
||||
|
||||
// Ensure it runs on any other return condition
|
||||
defer func() {
|
||||
c.listenerCloseOnce.Do(listenerCloseFunc)
|
||||
}()
|
||||
|
||||
c.listenerAddr = c.listener.Addr().(*net.TCPAddr)
|
||||
|
||||
if c.Func == "connect" {
|
||||
// "connect" indicates there is no subcommand to the connect function.
|
||||
// The only way a user will be able to connect to the session is by
|
||||
// connecting directly to the port and address we report to them here.
|
||||
|
||||
var creds []*targets.SessionCredential
|
||||
if c.sessionAuthz != nil && len(c.sessionAuthz.Credentials) > 0 {
|
||||
creds = c.sessionAuthz.Credentials
|
||||
}
|
||||
|
||||
sessInfo := SessionInfo{
|
||||
Protocol: c.sessionAuthzData.GetType(),
|
||||
Address: c.listenerAddr.IP.String(),
|
||||
Port: c.listenerAddr.Port,
|
||||
Expiration: c.expiration,
|
||||
ConnectionLimit: c.sessionAuthzData.GetConnectionLimit(),
|
||||
SessionId: c.sessionAuthzData.GetSessionId(),
|
||||
Credentials: creds,
|
||||
}
|
||||
switch base.Format(c.UI) {
|
||||
case "table":
|
||||
c.UI.Output(generateSessionInfoTableOutput(sessInfo))
|
||||
case "json":
|
||||
out, err := json.Marshal(&sessInfo)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("error marshaling session information: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
c.UI.Output(string(out))
|
||||
}
|
||||
}
|
||||
|
||||
c.connWg = new(sync.WaitGroup)
|
||||
|
||||
c.connWg.Add(1)
|
||||
proxyError := new(atomic.Error)
|
||||
go func() {
|
||||
defer c.connWg.Done()
|
||||
for {
|
||||
listeningConn, err := c.listener.AcceptTCP()
|
||||
if err != nil {
|
||||
select {
|
||||
case <-c.proxyCtx.Done():
|
||||
return
|
||||
case <-c.Context.Done():
|
||||
return
|
||||
default:
|
||||
// When this hits zero we trigger listener close so this
|
||||
// isn't actually an error condition
|
||||
if c.connectionsLeft.Load() == 0 {
|
||||
return
|
||||
}
|
||||
c.PrintCliError(fmt.Errorf("Error accepting connection: %w", err))
|
||||
continue
|
||||
}
|
||||
}
|
||||
c.connWg.Add(1)
|
||||
go func() {
|
||||
defer listeningConn.Close()
|
||||
defer c.connWg.Done()
|
||||
wsConn, err := c.getWsConn(
|
||||
c.proxyCtx,
|
||||
workerAddr,
|
||||
transport)
|
||||
if err != nil {
|
||||
c.PrintCliError(err)
|
||||
} else {
|
||||
if err := c.runTcpProxyV1(wsConn, listeningConn, tofuToken); err != nil {
|
||||
c.PrintCliError(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
defer close(clientProxyCloseCh)
|
||||
proxyError.Store(clientProxy.Start())
|
||||
}()
|
||||
|
||||
timer := time.NewTimer(time.Until(c.expiration))
|
||||
c.connWg.Add(1)
|
||||
go func() {
|
||||
defer c.connWg.Done()
|
||||
defer c.listenerCloseOnce.Do(listenerCloseFunc)
|
||||
|
||||
defer close(connCountCloseCh)
|
||||
for {
|
||||
select {
|
||||
case <-c.proxyCtx.Done():
|
||||
timer.Stop()
|
||||
// When the proxy exits it will cancel this even if we haven't
|
||||
// done it manually
|
||||
return
|
||||
case <-c.Context.Done():
|
||||
timer.Stop()
|
||||
return
|
||||
case <-timer.C:
|
||||
return
|
||||
case connsLeft := <-c.connsLeftCh:
|
||||
case connsLeft := <-connsLeftCh:
|
||||
c.updateConnsLeft(connsLeft)
|
||||
if connsLeft == 0 {
|
||||
return
|
||||
@@ -590,54 +460,73 @@ func (c *Command) Run(args []string) (retCode int) {
|
||||
}
|
||||
}()
|
||||
|
||||
if c.flagExec != "" {
|
||||
c.connWg.Add(1)
|
||||
c.execCmdReturnValue = atomic.NewInt32(0)
|
||||
go c.handleExec(passthroughArgs)
|
||||
if c.Func == "connect" {
|
||||
// "connect" indicates there is no subcommand to the connect function.
|
||||
// The only way a user will be able to connect to the session is by
|
||||
// connecting directly to the port and address we report to them here.
|
||||
|
||||
proxyAddr := clientProxy.ListenerAddress(context.Background())
|
||||
var clientProxyHost, clientProxyPort string
|
||||
clientProxyHost, clientProxyPort, err = net.SplitHostPort(proxyAddr)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "missing port") {
|
||||
clientProxyHost = proxyAddr
|
||||
} else {
|
||||
c.PrintCliError(fmt.Errorf("error splitting listener addr: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
}
|
||||
c.sessInfo.Address = clientProxyHost
|
||||
|
||||
if clientProxyPort != "" {
|
||||
c.sessInfo.Port, err = strconv.Atoi(clientProxyPort)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("error parsing listener port: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
}
|
||||
switch base.Format(c.UI) {
|
||||
case "table":
|
||||
c.UI.Output(generateSessionInfoTableOutput(c.sessInfo))
|
||||
case "json":
|
||||
out, err := json.Marshal(&c.sessInfo)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("error marshaling session information: %w", err))
|
||||
return base.CommandCliError
|
||||
}
|
||||
c.UI.Output(string(out))
|
||||
}
|
||||
}
|
||||
|
||||
c.connWg.Wait()
|
||||
if c.flagExec != "" {
|
||||
c.execCmdReturnValue = atomic.NewInt32(0)
|
||||
c.handleExec(clientProxy, passthroughArgs)
|
||||
}
|
||||
|
||||
<-connCountCloseCh
|
||||
<-clientProxyCloseCh
|
||||
|
||||
if c.execCmdReturnValue != nil {
|
||||
retCode = int(c.execCmdReturnValue.Load())
|
||||
}
|
||||
|
||||
termInfo := TerminationInfo{Reason: "Unknown"}
|
||||
sendSessionCancel := false
|
||||
select {
|
||||
case <-c.Context.Done():
|
||||
termInfo.Reason = "Received shutdown signal"
|
||||
sendSessionCancel = true
|
||||
default:
|
||||
if c.execCmdReturnValue != nil {
|
||||
// Don't print out in this case, so ensure we clear it
|
||||
termInfo.Reason = ""
|
||||
sendSessionCancel = true
|
||||
} else if !timer.Stop() {
|
||||
} else if time.Now().After(clientProxy.SessionExpiration()) {
|
||||
termInfo.Reason = "Session has expired"
|
||||
} else {
|
||||
if c.connectionsLeft.Load() == 0 {
|
||||
termInfo.Reason = "No connections left in session"
|
||||
}
|
||||
} else if clientProxy.ConnectionsLeft() == 0 {
|
||||
termInfo.Reason = "No connections left in session"
|
||||
} else if err := proxyError.Load(); err != nil {
|
||||
termInfo.Reason = "Error from proxy client: " + err.Error()
|
||||
}
|
||||
}
|
||||
|
||||
// Only send it if we should, and also if we're not after expiration, with a
|
||||
// bit of buffer in case clocks are not quite the same between worker and
|
||||
// this machine.
|
||||
if sendSessionCancel && time.Now().Before(c.expiration.Add(-5*time.Minute)) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), sessionCancelTimeout)
|
||||
wsConn, err := c.getWsConn(ctx, workerAddr, transport)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error fetching connection to send session teardown request to worker: %w", err))
|
||||
} else {
|
||||
if err := c.sendSessionTeardown(ctx, wsConn, tofuToken); err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error sending session teardown request to worker: %w", err))
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
|
||||
for _, f := range c.cleanupFuncs {
|
||||
if err := f(); err != nil {
|
||||
c.PrintCliError(err)
|
||||
@@ -682,121 +571,7 @@ func (c *Command) printCredentials(creds []*targets.SessionCredential) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Command) getWsConn(
|
||||
ctx context.Context,
|
||||
workerAddr string,
|
||||
transport *http.Transport,
|
||||
) (*websocket.Conn, error) {
|
||||
conn, resp, err := websocket.Dial(
|
||||
ctx,
|
||||
fmt.Sprintf("ws://%s/v1/proxy", workerAddr),
|
||||
&websocket.DialOptions{
|
||||
HTTPClient: &http.Client{
|
||||
Transport: transport,
|
||||
},
|
||||
Subprotocols: []string{globals.TcpProxyV1},
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
switch {
|
||||
case strings.Contains(err.Error(), "tls: internal error"):
|
||||
return nil, errors.New("Session credentials were not accepted, or session is unauthorized")
|
||||
case strings.Contains(err.Error(), "connect: connection refused"):
|
||||
return nil, fmt.Errorf("Unable to connect to worker at %s", workerAddr)
|
||||
default:
|
||||
return nil, fmt.Errorf("Error dialing the worker: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if resp == nil {
|
||||
return nil, errors.New("Response from worker is nil")
|
||||
}
|
||||
if resp.Header == nil {
|
||||
return nil, errors.New("Response header is nil")
|
||||
}
|
||||
negProto := resp.Header.Get("Sec-WebSocket-Protocol")
|
||||
if negProto != globals.TcpProxyV1 {
|
||||
return nil, fmt.Errorf("Unexpected negotiated protocol: %s", negProto)
|
||||
}
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
func (c *Command) sendSessionTeardown(
|
||||
ctx context.Context,
|
||||
wsConn *websocket.Conn,
|
||||
tofuToken string,
|
||||
) error {
|
||||
handshake := proxy.ClientHandshake{
|
||||
TofuToken: tofuToken,
|
||||
Command: proxy.HANDSHAKECOMMAND_HANDSHAKECOMMAND_SESSION_CANCEL,
|
||||
}
|
||||
if err := wspb.Write(ctx, wsConn, &handshake); err != nil {
|
||||
return fmt.Errorf("error sending teardown handshake to worker: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Command) runTcpProxyV1(
|
||||
wsConn *websocket.Conn,
|
||||
listeningConn *net.TCPConn,
|
||||
tofuToken string,
|
||||
) error {
|
||||
handshake := proxy.ClientHandshake{TofuToken: tofuToken}
|
||||
if err := wspb.Write(c.proxyCtx, wsConn, &handshake); err != nil {
|
||||
return fmt.Errorf("Error sending handshake to worker: %w", err)
|
||||
}
|
||||
var handshakeResult proxy.HandshakeResult
|
||||
if err := wspb.Read(c.proxyCtx, wsConn, &handshakeResult); err != nil {
|
||||
switch {
|
||||
case strings.Contains(err.Error(), "unable to authorize connection"):
|
||||
// There's no reason to think we'd be able to authorize any more
|
||||
// connections after the first has failed
|
||||
c.connsLeftCh <- 0
|
||||
return errors.New("Unable to authorize connection")
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(err.Error(), "tofu token not allowed"):
|
||||
// Nothing will be able to be done here, so cancel the context too
|
||||
c.proxyCancel()
|
||||
return errors.New("Session token has already been used")
|
||||
default:
|
||||
// If we can't handshake we can't do anything, so quit out
|
||||
c.proxyCancel()
|
||||
return fmt.Errorf("Error reading handshake result: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if handshakeResult.GetConnectionsLeft() != -1 {
|
||||
c.connsLeftCh <- handshakeResult.GetConnectionsLeft()
|
||||
}
|
||||
|
||||
// Get a wrapped net.Conn so we can use io.Copy
|
||||
netConn := websocket.NetConn(c.proxyCtx, wsConn, websocket.MessageBinary)
|
||||
|
||||
localWg := new(sync.WaitGroup)
|
||||
localWg.Add(2)
|
||||
|
||||
go func() {
|
||||
defer localWg.Done()
|
||||
io.Copy(netConn, listeningConn)
|
||||
netConn.Close()
|
||||
listeningConn.Close()
|
||||
}()
|
||||
go func() {
|
||||
defer localWg.Done()
|
||||
io.Copy(listeningConn, netConn)
|
||||
listeningConn.Close()
|
||||
netConn.Close()
|
||||
}()
|
||||
localWg.Wait()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Command) updateConnsLeft(connsLeft int32) {
|
||||
c.connectionsLeft.Store(connsLeft)
|
||||
|
||||
connInfo := ConnectionInfo{
|
||||
ConnectionsLeft: connsLeft,
|
||||
}
|
||||
@@ -808,29 +583,38 @@ func (c *Command) updateConnsLeft(connsLeft int32) {
|
||||
case "json":
|
||||
out, err := json.Marshal(&connInfo)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("error marshaling connection information: %w", err))
|
||||
c.PrintCliError(fmt.Errorf("Error marshaling connection information: %w", err))
|
||||
}
|
||||
c.UI.Output(string(out))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) handleExec(passthroughArgs []string) {
|
||||
defer c.connWg.Done()
|
||||
func (c *Command) handleExec(clientProxy *apiproxy.ClientProxy, passthroughArgs []string) {
|
||||
defer c.proxyCancel()
|
||||
|
||||
port := strconv.Itoa(c.listenerAddr.Port)
|
||||
ip := c.listenerAddr.IP.String()
|
||||
addr := c.listenerAddr.String()
|
||||
addr := clientProxy.ListenerAddress(context.Background())
|
||||
var host, port string
|
||||
var err error
|
||||
host, port, err = net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
if strings.Contains(err.Error(), "missing port") {
|
||||
host = addr
|
||||
} else {
|
||||
c.PrintCliError(fmt.Errorf("Error splitting listener addr: %w", err))
|
||||
c.execCmdReturnValue.Store(int32(3))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var args []string
|
||||
var envs []string
|
||||
var argsErr error
|
||||
|
||||
var creds apiproxy.Credentials
|
||||
if c.sessionAuthz != nil {
|
||||
if len(c.sessInfo.Credentials) > 0 {
|
||||
var err error
|
||||
creds, err = apiproxy.ParseCredentials(c.sessionAuthz.Credentials)
|
||||
creds, err = apiproxy.ParseCredentials(c.sessInfo.Credentials)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error interpreting secret: %w", err))
|
||||
c.execCmdReturnValue.Store(int32(3))
|
||||
@@ -840,7 +624,7 @@ func (c *Command) handleExec(passthroughArgs []string) {
|
||||
|
||||
switch c.Func {
|
||||
case "http":
|
||||
httpArgs, err := c.httpFlags.buildArgs(c, port, ip, addr)
|
||||
httpArgs, err := c.httpFlags.buildArgs(c, port, host, addr)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error parsing session args: %w", err))
|
||||
c.execCmdReturnValue.Store(int32(3))
|
||||
@@ -849,7 +633,7 @@ func (c *Command) handleExec(passthroughArgs []string) {
|
||||
args = append(args, httpArgs...)
|
||||
|
||||
case "postgres":
|
||||
pgArgs, pgEnvs, pgCreds, pgErr := c.postgresFlags.buildArgs(c, port, ip, addr, creds)
|
||||
pgArgs, pgEnvs, pgCreds, pgErr := c.postgresFlags.buildArgs(c, port, host, addr, creds)
|
||||
if pgErr != nil {
|
||||
argsErr = pgErr
|
||||
break
|
||||
@@ -859,10 +643,10 @@ func (c *Command) handleExec(passthroughArgs []string) {
|
||||
creds = pgCreds
|
||||
|
||||
case "rdp":
|
||||
args = append(args, c.rdpFlags.buildArgs(c, port, ip, addr)...)
|
||||
args = append(args, c.rdpFlags.buildArgs(c, port, host, addr)...)
|
||||
|
||||
case "ssh":
|
||||
sshArgs, sshEnvs, sshCreds, sshErr := c.sshFlags.buildArgs(c, port, ip, addr, creds)
|
||||
sshArgs, sshEnvs, sshCreds, sshErr := c.sshFlags.buildArgs(c, port, host, addr, creds)
|
||||
if sshErr != nil {
|
||||
argsErr = sshErr
|
||||
break
|
||||
@@ -872,7 +656,7 @@ func (c *Command) handleExec(passthroughArgs []string) {
|
||||
creds = sshCreds
|
||||
|
||||
case "kube":
|
||||
kubeArgs, err := c.kubeFlags.buildArgs(c, port, ip, addr)
|
||||
kubeArgs, err := c.kubeFlags.buildArgs(c, port, host, addr)
|
||||
if err != nil {
|
||||
c.PrintCliError(fmt.Errorf("Error parsing session args: %w", err))
|
||||
c.execCmdReturnValue.Store(int32(3))
|
||||
@@ -909,7 +693,7 @@ func (c *Command) handleExec(passthroughArgs []string) {
|
||||
|
||||
for i := range args {
|
||||
args[i] = stringReplacer(args[i], "port", port)
|
||||
args[i] = stringReplacer(args[i], "ip", ip)
|
||||
args[i] = stringReplacer(args[i], "ip", host)
|
||||
args[i] = stringReplacer(args[i], "addr", addr)
|
||||
}
|
||||
|
||||
@@ -920,7 +704,7 @@ func (c *Command) handleExec(passthroughArgs []string) {
|
||||
// Add original and network related envs here
|
||||
cmd.Env = append(os.Environ(),
|
||||
fmt.Sprintf("BOUNDARY_PROXIED_PORT=%s", port),
|
||||
fmt.Sprintf("BOUNDARY_PROXIED_IP=%s", ip),
|
||||
fmt.Sprintf("BOUNDARY_PROXIED_IP=%s", host),
|
||||
fmt.Sprintf("BOUNDARY_PROXIED_ADDR=%s", addr),
|
||||
)
|
||||
// Envs that came from subcommand handling
|
||||
|
||||
@@ -77,8 +77,8 @@ func (h *httpFlags) defaultExec() string {
|
||||
func (h *httpFlags) buildArgs(c *Command, port, ip, addr string) ([]string, error) {
|
||||
var args []string
|
||||
host := h.flagHttpHost
|
||||
if host == "" && c.sessionAuthzData.GetEndpoint() != "" {
|
||||
hostUrl := c.sessionAuthzData.GetEndpoint()
|
||||
if host == "" && c.sessInfo.Endpoint != "" {
|
||||
hostUrl := c.sessInfo.Endpoint
|
||||
u, err := url.Parse(hostUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error parsing endpoint URL: %w", err)
|
||||
@@ -94,8 +94,14 @@ func (h *httpFlags) buildArgs(c *Command, port, ip, addr string) ([]string, erro
|
||||
if host != "" {
|
||||
host = strings.TrimSuffix(host, "/")
|
||||
args = append(args, "-H", fmt.Sprintf("Host: %s", host))
|
||||
args = append(args, "--resolve", fmt.Sprintf("%s:%s:%s", host, port, ip))
|
||||
uri = fmt.Sprintf("%s://%s:%s", h.flagHttpScheme, host, port)
|
||||
switch port == "" {
|
||||
case false:
|
||||
args = append(args, "--resolve", fmt.Sprintf("%s:%s:%s", host, port, ip))
|
||||
uri = fmt.Sprintf("%s://%s:%s", h.flagHttpScheme, host, port)
|
||||
default:
|
||||
args = append(args, "--resolve", fmt.Sprintf("%s:%s", host, ip))
|
||||
uri = fmt.Sprintf("%s://%s", h.flagHttpScheme, host)
|
||||
}
|
||||
} else {
|
||||
uri = fmt.Sprintf("%s://%s", h.flagHttpScheme, addr)
|
||||
}
|
||||
|
||||
@@ -59,8 +59,8 @@ func (f *kubeFlags) defaultExec() string {
|
||||
func (f *kubeFlags) buildArgs(c *Command, port, ip, addr string) ([]string, error) {
|
||||
var args []string
|
||||
host := f.flagKubeHost
|
||||
if host == "" && c.sessionAuthzData.GetEndpoint() != "" {
|
||||
hostUrl := c.sessionAuthzData.GetEndpoint()
|
||||
if host == "" && c.sessInfo.Endpoint != "" {
|
||||
hostUrl := c.sessInfo.Endpoint
|
||||
u, err := url.Parse(hostUrl)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error parsing endpoint URL: %w", err)
|
||||
|
||||
@@ -69,7 +69,10 @@ func (p *postgresFlags) buildArgs(c *Command, port, ip, _ string, creds proxy.Cr
|
||||
|
||||
switch p.flagPostgresStyle {
|
||||
case "psql":
|
||||
args = append(args, "-p", port, "-h", ip)
|
||||
if port != "" {
|
||||
args = append(args, "-p", port)
|
||||
}
|
||||
args = append(args, "-h", ip)
|
||||
|
||||
if c.flagDbname != "" {
|
||||
args = append(args, "-d", c.flagDbname)
|
||||
|
||||
@@ -60,7 +60,7 @@ func (s *sshFlags) buildArgs(c *Command, port, ip, _ string, creds apiproxy.Cred
|
||||
retCreds = creds
|
||||
|
||||
var tryConsume bool
|
||||
switch string(target.SubtypeFromId(c.sessionAuthzData.GetTargetId())) {
|
||||
switch string(target.SubtypeFromId(c.sessInfo.TargetId)) {
|
||||
case "tcp":
|
||||
tryConsume = true
|
||||
}
|
||||
@@ -68,21 +68,23 @@ func (s *sshFlags) buildArgs(c *Command, port, ip, _ string, creds apiproxy.Cred
|
||||
switch strings.ToLower(s.flagSshStyle) {
|
||||
case "ssh":
|
||||
// Might want -t for ssh or -tt but seems fine without it for now...
|
||||
args = append(args, "-p", port)
|
||||
if port != "" {
|
||||
args = append(args, "-p", port)
|
||||
}
|
||||
|
||||
switch c.sessionAuthzData.GetType() {
|
||||
switch c.sessInfo.Type {
|
||||
case "tcp":
|
||||
// SSH detects a host key change when the localhost proxy port changes
|
||||
// This uses the host ID instead of 'localhost:port'.
|
||||
if len(c.sessionAuthzData.GetHostId()) > 0 {
|
||||
args = append(args, "-o", fmt.Sprintf("HostKeyAlias=%s", c.sessionAuthzData.GetHostId()))
|
||||
if len(c.sessInfo.HostId) > 0 {
|
||||
args = append(args, "-o", fmt.Sprintf("HostKeyAlias=%s", c.sessInfo.HostId))
|
||||
} else {
|
||||
// In cases where the Target has no host sources and has an
|
||||
// address directly attached to it, we have no Host Id. Use
|
||||
// Target Id instead. Only one address can ever be present on a
|
||||
// target, and no other host sources may be present at the same
|
||||
// time, so this is a reasonable alternative.
|
||||
args = append(args, "-o", fmt.Sprintf("HostKeyAlias=%s", c.sessionAuthzData.GetTargetId()))
|
||||
args = append(args, "-o", fmt.Sprintf("HostKeyAlias=%s", c.sessInfo.TargetId))
|
||||
}
|
||||
case "ssh":
|
||||
args = append(args, "-o", "NoHostAuthenticationForLocalhost=yes")
|
||||
@@ -110,14 +112,18 @@ func (s *sshFlags) buildArgs(c *Command, port, ip, _ string, creds apiproxy.Cred
|
||||
// when the using env-vars.
|
||||
envs = append(envs, fmt.Sprintf("SSHPASS=%s", password))
|
||||
args = append(args, "-e", "ssh")
|
||||
args = append(args, "-p", port)
|
||||
if port != "" {
|
||||
args = append(args, "-p", port)
|
||||
}
|
||||
|
||||
// sshpass cannot handle host key checking, disable localhost key verification
|
||||
// to avoid error: 'SSHPASS detected host authentication prompt. Exiting.'
|
||||
args = append(args, "-o", "NoHostAuthenticationForLocalhost=yes")
|
||||
|
||||
case "putty":
|
||||
args = append(args, "-P", port)
|
||||
if port != "" {
|
||||
args = append(args, "-P", port)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we got credentials to attempt to use for ssh or putty,
|
||||
|
||||
@@ -57,7 +57,7 @@ func TestServer_ShutdownWorker(t *testing.T) {
|
||||
recoveryWrapper, _ := wrapperWithKey(t)
|
||||
workerAuthWrapper, key := wrapperWithKey(t)
|
||||
testController := controller.NewTestController(t, controller.WithWorkerAuthKms(workerAuthWrapper), controller.WithRootKms(rootWrapper), controller.WithRecoveryKms(recoveryWrapper))
|
||||
defer testController.Shutdown()
|
||||
t.Cleanup(testController.Shutdown)
|
||||
|
||||
// Start the worker
|
||||
workerCmd := testServerCommand(t, testServerCommandOpts{})
|
||||
@@ -81,7 +81,7 @@ func TestServer_ShutdownWorker(t *testing.T) {
|
||||
tcl := targets.NewClient(client)
|
||||
tgtL, err := tcl.List(ctx, scope.Global.String(), targets.WithRecursive(true))
|
||||
require.NoError(err)
|
||||
require.Len(tgtL.Items, 2)
|
||||
require.LessOrEqual(2, len(tgtL.Items))
|
||||
tgt := tgtL.Items[0]
|
||||
require.NotNil(tgt)
|
||||
require.NotNil(tgtL.GetItems()[1])
|
||||
@@ -89,7 +89,7 @@ func TestServer_ShutdownWorker(t *testing.T) {
|
||||
// Create test server, update default port on target
|
||||
ts := helper.NewTestTcpServer(t)
|
||||
require.NotNil(ts)
|
||||
defer ts.Close()
|
||||
t.Cleanup(ts.Close)
|
||||
tgtR, err := tcl.Update(ctx, tgt.Id, tgt.Version, targets.WithTcpTargetDefaultPort(ts.Port()))
|
||||
require.NoError(err)
|
||||
require.NotNil(tgtR)
|
||||
@@ -97,7 +97,7 @@ func TestServer_ShutdownWorker(t *testing.T) {
|
||||
// Authorize and connect
|
||||
// This prevents us from running tests in parallel.
|
||||
tg.SetupSuiteTargetFilters(t)
|
||||
sess := helper.NewTestSession(ctx, t, tcl, tgt.Id)
|
||||
sess := helper.NewTestSession(ctx, t, tcl, tgt.Id, helper.WithSkipSessionTeardown(true))
|
||||
sConn := sess.Connect(ctx, t)
|
||||
|
||||
// Run initial send/receive test, make sure things are working
|
||||
|
||||
@@ -7073,6 +7073,12 @@
|
||||
"description": "Output only. The marshaled SessionAuthorizationData message containing all information that the proxy needs.",
|
||||
"readOnly": true
|
||||
},
|
||||
"connection_limit": {
|
||||
"type": "integer",
|
||||
"format": "int32",
|
||||
"description": "Output only. The connection limit being applied to this session. -1 means unlimited. This is not actually enforced on the client side but it provides for better listener handling by including it.",
|
||||
"readOnly": true
|
||||
},
|
||||
"endpoint": {
|
||||
"type": "string",
|
||||
"description": "Output only. The endpoint address that the worker will connect to, useful for setting TLS parameters.",
|
||||
|
||||
@@ -371,6 +371,9 @@ message SessionAuthorization {
|
||||
// Output only. The marshaled SessionAuthorizationData message containing all information that the proxy needs.
|
||||
string authorization_token = 90 [json_name = "authorization_token"]; // @gotags: `class:"secret"`
|
||||
|
||||
// Output only. The connection limit being applied to this session. -1 means unlimited. This is not actually enforced on the client side but it provides for better listener handling by including it.
|
||||
int32 connection_limit = 95 [json_name = "connection_limit"];
|
||||
|
||||
// Output only. The endpoint address that the worker will connect to, useful for setting TLS parameters.
|
||||
string endpoint = 100; // @gotags: `class:"public"`
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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},
|
||||
},
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user