Tie together the database-driven session handling with the worker and add relevant CLI comands (#370)

This commit is contained in:
Jeff Mitchell authored and GitHub committed 2020-09-19 00:18:17 -04:00
1 parent fd8ceb6cc4
commit 07a7e9750a
57 files changed
+2548 -826

No files matched your search

+2 -4
View File
@@ -362,8 +362,7 @@ func (c *Command) FlagSet(bit FlagSetBit) *FlagSets {
f.BoolVar(&BoolVar{
Name: "output-curl-string",
Target: &c.flagOutputCurlString,
Usage: "Instead of executing the request, print an equivalent cURL " +
"command string and exit.",
Usage: "Instead of executing the request, print an equivalent cURL command string and exit.",
})
}
@@ -386,8 +385,7 @@ func (c *Command) FlagSet(bit FlagSetBit) *FlagSets {
Default: "table",
EnvVar: EnvBoundaryCLIFormat,
Completion: complete.PredictSet("table", "json", "yaml"),
Usage: "Print the output in the given format. Valid formats " +
"are \"table\", \"json\", or \"yaml\".",
Usage: "Print the output in the given format. Valid formats are \"table\" or \"json\".",
})
}
}
+13
View File
@@ -65,6 +65,13 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
"proxy": func() (cli.Command, error) {
return &proxy.Command{
Command: base.NewCommand(ui),
Func: "proxy",
}, nil
},
"connect": func() (cli.Command, error) {
return &proxy.Command{
Command: base.NewCommand(ui),
Func: "connect",
}, nil
},
@@ -558,6 +565,12 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
Command: base.NewCommand(ui),
}, nil
},
"targets authorize": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
Func: "authorize",
}, nil
},
"targets read": func() (cli.Command, error) {
return &targets.Command{
Command: base.NewCommand(ui),
+31
View File
@@ -0,0 +1,31 @@
package proxy
import (
"github.com/hashicorp/boundary/internal/cmd/base"
)
func generateConnectionInfoTableOutput(in ConnectionInfo) string {
var ret []string
nonAttributeMap := map[string]interface{}{
"Protocol": in.Protocol,
"Address": in.Address,
"Port": in.Port,
}
maxLength := 0
for k := range nonAttributeMap {
if len(k) > maxLength {
maxLength = len(k)
}
}
ret = append(ret, "", "Proxy listening information:")
ret = append(ret,
// We do +2 because there is another +2 offset for host sets below
base.WrapMap(2, maxLength+2, nonAttributeMap),
)
return base.WrapForHelpText(ret)
}
+163 -43
View File
@@ -4,6 +4,7 @@ import (
"crypto/ed25519"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"io/ioutil"
@@ -15,60 +16,109 @@ import (
"github.com/btcsuite/btcutil/base58"
"github.com/golang/protobuf/proto"
"github.com/hashicorp/boundary/api/targets"
"github.com/hashicorp/boundary/globals"
"github.com/hashicorp/boundary/internal/cmd/base"
wpbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
targetspb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/targets"
"github.com/hashicorp/boundary/internal/proxy"
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/vault/sdk/helper/base62"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wspb"
)
type ConnectionInfo struct {
Address string `json:"address"`
Port int `json:"port"`
Protocol string `json:"protocol"`
}
var _ cli.Command = (*Command)(nil)
var _ cli.CommandAutocomplete = (*Command)(nil)
type Command struct {
*base.Command
flagAuth string
flagAuthz string
flagListenAddr string
flagListenPort int
flagVerbose bool
flagTargetId string
flagHostId string
Func string
}
func (c *Command) Synopsis() string {
return "Launch the Boundary CLI in proxy mode"
switch c.Func {
case "proxy":
return "Launch the Boundary CLI in proxy mode"
case "connect":
return "Authorize a session against a target and launch a proxied connection"
}
return ""
}
func (c *Command) Help() string {
return base.WrapForHelpText([]string{
"Usage: boundary proxy [options] [args]",
"",
" This command allows launching the Boundary CLI in proxy mode. In this mode, the CLI expects to take in an authorization string returned from a Boundary controller. The CLI will then create a connection to a Boundary worker and ready a listening port for a local connection.",
"",
" Example:",
"",
` $ boundary proxy -auth "UgxzX29mVEpwNUt6QlGiAQ..."`,
"",
" Please see the {{type}}s subcommand help for detailed usage information.",
}) + c.Flags().Help()
switch c.Func {
case "proxy":
return base.WrapForHelpText([]string{
"Usage: boundary proxy [options] [args]",
"",
" This command allows launching the Boundary CLI in proxy mode. In this mode, the CLI expects to take in an authorization string returned from a Boundary controller. The CLI will then create a connection to a Boundary worker and ready a listening port for a local connection.",
"",
" Example:",
"",
` $ boundary proxy -auth "UgxzX29mVEpwNUt6QlGiAQ..."`,
}) + c.Flags().Help()
case "connect":
return base.WrapForHelpText([]string{
"Usage: boundary connect [options] [args]",
"",
` This command performs a target authorization and proxy launch in one command; it is equivalent to sending the output of "boundary targets authorize" into "boundary proxy". See the help output for those commands for more information.`,
"",
" Example:",
"",
` $ boundary connect -target-id ttcp_1234567890"`,
}) + c.Flags().Help()
}
return ""
}
func (c *Command) Flags() *base.FlagSets {
set := c.FlagSet(0)
bits := base.FlagSetOutputFormat
if c.Func == "connect" {
bits = base.FlagSetHTTP | base.FlagSetClient | bits
}
set := c.FlagSet(bits)
f := set.NewFlagSet("Proxy Options")
f.StringVar(&base.StringVar{
Name: "auth",
Target: &c.flagAuth,
EnvVar: "BOUNDARY_PROXY_AUTH",
Completion: complete.PredictAnything,
Usage: `The authorization string returned from the Boundary controller. If set to "-", the command will attempt to read in the authorization string from standard input.`,
})
switch c.Func {
case "proxy":
f.StringVar(&base.StringVar{
Name: "authz",
Target: &c.flagAuthz,
EnvVar: "BOUNDARY_PROXY_AUTHZ",
Completion: complete.PredictAnything,
Usage: `The authorization string returned from the Boundary controller. If set to "-", the command will attempt to read in the authorization string from standard input.`,
})
case "connect":
f.StringVar(&base.StringVar{
Name: "target-id",
Target: &c.flagTargetId,
Usage: "The ID of the target to authorize against.",
})
f.StringVar(&base.StringVar{
Name: "host-id",
Target: &c.flagHostId,
Usage: "The ID of a specific host to connect to out of the hosts from the target's host sets. If not specified, one is chosen at random.",
})
}
f.StringVar(&base.StringVar{
Name: "listen-addr",
@@ -112,7 +162,7 @@ func (c *Command) Run(args []string) int {
return 1
}
var handshake proxy.Handshake
var handshake proxy.ClientHandshake
var err error
if handshake.TofuToken, err = base62.Random(20); err != nil {
c.UI.Error(fmt.Errorf("Could not derive random bytes for tofu token: %w", err).Error())
@@ -128,38 +178,85 @@ func (c *Command) Run(args []string) int {
return 1
}
if c.flagAuth == "-" {
authBytes, err := ioutil.ReadAll(os.Stdin)
authzString := c.flagAuthz
switch c.Func {
case "proxy":
if authzString == "-" {
authBytes, err := ioutil.ReadAll(os.Stdin)
if err != nil {
c.UI.Error(fmt.Errorf("No authorization string was provided and encountered the following error attempting to read it from stdin: %w", err).Error())
return 1
}
if len(authBytes) == 0 {
c.UI.Error("No authorization data read from stdin")
return 1
}
authzString = string(authBytes)
}
if authzString == "" {
c.UI.Error("Authorization data was empty")
return 1
}
if authzString[0] == '{' {
// Attempt to decode the JSON output of an authorize call and pull the
// token out of there
var sa targets.SessionAuthorization
if err := json.Unmarshal([]byte(authzString), &sa); err == nil {
authzString = sa.AuthorizationToken
}
}
case "connect":
if c.flagTargetId == "" {
c.UI.Error("Target ID must be provided")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Errorf("No authorization string was provided and encountered the following error attempting to read it from stdin: %w", err).Error())
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
targetClient := targets.NewClient(client)
var opts []targets.Option
if len(c.flagHostId) != 0 {
opts = append(opts, targets.WithHostId(c.flagHostId))
}
sar, apiErr, err := targetClient.Authorize(c.Context, c.flagTargetId, opts...)
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to authorize a session against target: %s", err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing authorize on a session against target: %s", pretty.Sprint(apiErr)))
return 1
}
if len(authBytes) == 0 {
c.UI.Error("No authorization data read from stdin")
return 1
}
c.flagAuth = string(authBytes)
sa := sar.GetItem().(*targets.SessionAuthorization)
authzString = sa.AuthorizationToken
}
marshaled := base58.Decode(c.flagAuth)
marshaled := base58.Decode(authzString)
if len(marshaled) == 0 {
c.UI.Error("Zero length authorization information after decoding")
return 1
}
sessionResponseInfo := new(wpbs.GetSessionResponse)
if err := proto.Unmarshal(marshaled, sessionResponseInfo); err != nil {
c.UI.Error(fmt.Errorf("Unable to proto-decode authorization string: %w", err).Error())
data := new(targetspb.SessionAuthorizationData)
if err := proto.Unmarshal(marshaled, data); err != nil {
c.UI.Error(fmt.Errorf("Unable to proto-decode authorization data: %w", err).Error())
return 1
}
sessionInfo := sessionResponseInfo.GetSession()
if len(sessionInfo.GetWorkerInfo()) == 0 {
if len(data.GetWorkerInfo()) == 0 {
c.UI.Error("No workers found in authorization string")
return 1
}
parsedCert, err := x509.ParseCertificate(sessionInfo.Certificate)
parsedCert, err := x509.ParseCertificate(data.Certificate)
if err != nil {
c.UI.Error(fmt.Errorf("Unable to decode mTLS certificate: %w", err).Error())
return 1
@@ -176,8 +273,8 @@ func (c *Command) Run(args []string) int {
tlsConf := &tls.Config{
Certificates: []tls.Certificate{
{
Certificate: [][]byte{sessionInfo.Certificate},
PrivateKey: ed25519.PrivateKey(sessionInfo.PrivateKey),
Certificate: [][]byte{data.Certificate},
PrivateKey: ed25519.PrivateKey(data.PrivateKey),
Leaf: parsedCert,
},
},
@@ -198,9 +295,8 @@ func (c *Command) Run(args []string) int {
c.UI.Error(fmt.Errorf("Error starting listening port: %w", err).Error())
return 1
}
c.UI.Info(fmt.Sprintf("%s", listener.Addr().String()))
workerAddr := sessionInfo.GetWorkerInfo()[0].GetAddress()
workerAddr := data.GetWorkerInfo()[0].GetAddress()
conn, resp, err := websocket.Dial(
c.Context,
@@ -239,9 +335,33 @@ func (c *Command) Run(args []string) int {
}
if err := wspb.Write(c.Context, conn, &handshake); err != nil {
c.UI.Error(fmt.Errorf("error sending tofu token to worker: %w", err).Error())
c.UI.Error(fmt.Errorf("error sending handshake to worker: %w", err).Error())
return 1
}
var handshakeResult proxy.HandshakeResult
if err := wspb.Read(c.Context, conn, &handshakeResult); err != nil {
c.UI.Error(fmt.Errorf("error reading handshake result: %w", err).Error())
return 1
}
listenerAddr := listener.Addr().(*net.TCPAddr)
connInfo := ConnectionInfo{
Protocol: "tcp",
Address: listenerAddr.IP.String(),
Port: listenerAddr.Port,
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateConnectionInfoTableOutput(connInfo))
case "json":
out, err := json.Marshal(&connInfo)
if err != nil {
c.UI.Error(fmt.Errorf("error marshaling connection information: %w", err).Error())
return 1
}
c.UI.Output(string(out))
}
// Get a wrapped net.Conn so we can use io.Copy
netConn := websocket.NetConn(c.Context, conn, websocket.MessageBinary)
+29
View File
@@ -94,6 +94,35 @@ func generateTargetTableOutput(in *targets.Target) string {
return base.WrapForHelpText(ret)
}
func generateAuthorizationTableOutput(in *targets.SessionAuthorization) string {
var ret []string
nonAttributeMap := map[string]interface{}{
"Session ID": in.SessionId,
"Target ID": in.TargetId,
"Scope ID": in.Scope.Id,
"Created Time": in.CreatedTime.Local().Format(time.RFC3339),
"Type": in.Type,
"Authorization Token": in.AuthorizationToken,
}
maxLength := 0
for k := range nonAttributeMap {
if len(k) > maxLength {
maxLength = len(k)
}
}
ret = append(ret, "", "Target information:")
ret = append(ret,
// We do +2 because there is another +2 offset for host sets below
base.WrapMap(2, maxLength+2, nonAttributeMap),
)
return base.WrapForHelpText(ret)
}
var attributeMap = map[string]string{
"default_port": "Default Port",
}
+47 -4
View File
@@ -25,6 +25,7 @@ type Command struct {
Func string
flagHostSets []string
flagHostId string
}
func (c *Command) Synopsis() string {
@@ -39,6 +40,7 @@ func (c *Command) Synopsis() string {
}
var flagsMap = map[string][]string{
"authorize": {"id", "host-id"},
"read": {"id"},
"delete": {"id"},
"list": {"scope-id"},
@@ -89,7 +91,7 @@ func (c *Command) Help() string {
})
case "add-host-sets":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary target add-host-sets [sub command] [options] [args]",
"Usage: boundary target add-host-sets [options] [args]",
"",
" This command allows adding host-set resources to target resources. Example:",
"",
@@ -99,7 +101,7 @@ func (c *Command) Help() string {
})
case "remove-host-sets":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary target remove-host-sets [sub command] [options] [args]",
"Usage: boundary target remove-host-sets [options] [args]",
"",
" This command allows removing host-set resources from target resources. Example:",
"",
@@ -109,7 +111,7 @@ func (c *Command) Help() string {
})
case "set-host-sets":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary target set-host-sets [sub command] [options] [args]",
"Usage: boundary target set-host-sets [options] [args]",
"",
" This command allows setting the complete set of host-set resources on a target resource. Example:",
"",
@@ -117,6 +119,16 @@ func (c *Command) Help() string {
"",
` $ boundary targets set-host-sets -id ttcp_1234567890 -host-set hsst_1234567890`,
})
case "authorize":
helpStr = base.WrapForHelpText([]string{
"Usage: boundary target authorize [options] [args]",
"",
" This command allows fetching session authorization credentials against a target. Example:",
"",
" Set host-set resources on a tcp-type target:",
"",
` $ boundary targets authorize -id ttcp_1234567890`,
})
default:
helpStr = helpMap[c.Func]()
}
@@ -137,6 +149,12 @@ func (c *Command) Flags() *base.FlagSets {
Target: &c.flagHostSets,
Usage: "The host-set resources to add, remove, or set. May be specified multiple times.",
})
case "host-id":
f.StringVar(&base.StringVar{
Name: "host-id",
Target: &c.flagHostId,
Usage: "The ID of a specific host to connect to out of the hosts from the target's host sets. If not specified, one is chosen at random.",
})
}
}
@@ -220,6 +238,10 @@ func (c *Command) Run(args []string) int {
hostSets = nil
}
}
case "authorize":
if len(c.flagHostId) != 0 {
opts = append(opts, targets.WithHostId(c.flagHostId))
}
}
// Perform check-and-set when needed
@@ -243,6 +265,7 @@ func (c *Command) Run(args []string) int {
var result api.GenericResult
var listResult api.GenericListResult
var apiErr *api.Error
var sar *targets.SessionAuthorizationResult
switch c.Func {
case "read":
@@ -261,11 +284,16 @@ func (c *Command) Run(args []string) int {
result, apiErr, err = targetClient.RemoveHostSets(c.Context, c.FlagId, version, hostSets, opts...)
case "set-host-sets":
result, apiErr, err = targetClient.SetHostSets(c.Context, c.FlagId, version, hostSets, opts...)
case "authorize":
sar, apiErr, err = targetClient.Authorize(c.Context, c.FlagId, opts...)
}
plural := "target"
if c.Func == "list" {
switch c.Func {
case "list":
plural = "targets"
case "authorize":
plural = "a session against target"
}
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
@@ -343,6 +371,21 @@ func (c *Command) Run(args []string) int {
c.UI.Output(base.WrapForHelpText(output))
}
return 0
case "authorize":
sa := sar.GetItem().(*targets.SessionAuthorization)
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateAuthorizationTableOutput(sa))
case "json":
b, err := base.JsonFormatter{}.Format(sa)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting as JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
target := result.GetItem().(*targets.Target)
+1 -1
View File
@@ -183,7 +183,7 @@ func RunCustom(args []string, runOpts *RunOptions) int {
fmt.Fprint(runOpts.Stderr, "cURL command not set by API operation; run without -output-curl-string to see the generated error\n")
return exitCode
}
if api.LastOutputStringError.Error() != api.ErrOutputStringRequest {
if !strings.Contains(api.LastOutputStringError.Error(), api.ErrOutputStringRequest) {
runOpts.Stdout.Write([]byte(fmt.Sprintf("Error creating request string: %s\n", api.LastOutputStringError.Error())))
return 1
}