Authenticate Handler API and SDK, and much more (#183)

This commit is contained in:
Todd Knight authored and GitHub committed 2020-07-14 17:32:47 -04:00
1 parent acce195dcb
commit 28dbcd84bd
89 files changed
+5296 -1943

No files matched your search

+36
View File
@@ -18,6 +18,7 @@ import (
"github.com/mitchellh/cli"
"github.com/pkg/errors"
"github.com/posener/complete"
"github.com/zalando/go-keyring"
)
const (
@@ -26,6 +27,8 @@ const (
// NotSetValue is a flag value for a not-set value
NotSetValue = "(not set)"
envTokenName = "WATCHTOWER_TOKEN_NAME"
)
// reRemoveWhitespace is a regular expression for stripping whitespace from
@@ -53,6 +56,7 @@ type Command struct {
flagFormat string
flagField string
FlagTokenName string
flagOutputCurlString bool
client *api.Client
@@ -161,6 +165,26 @@ func (c *Command) Client() (*api.Client, error) {
c.client.SetMaxRetries(0)
}
if c.client.Token() == "" {
tokenName := "default"
if c.FlagTokenName != "" {
tokenName = c.FlagTokenName
}
if tokenName != "none" {
token, err := keyring.Get("HashiCorp Watchtower Auth Token", tokenName)
if err != nil {
if err == keyring.ErrNotFound {
c.UI.Info("No saved credential found, continuing without")
} else {
c.UI.Error(fmt.Sprintf("Error reading auth token from system credential store: %s", err))
}
}
if token != "" {
c.client.SetToken(token)
}
}
}
return c.client, nil
}
@@ -169,6 +193,7 @@ type FlagSetBit uint
const (
FlagSetNone FlagSetBit = 1 << iota
FlagSetHTTP
FlagSetClient
FlagSetOutputField
FlagSetOutputFormat
)
@@ -274,6 +299,17 @@ func (c *Command) FlagSet(bit FlagSetBit) *FlagSets {
"is highly discouraged as it decreases the security of data " +
"transmissions to and from the Watchtower server.",
})
}
if bit&FlagSetClient != 0 {
f := set.NewFlagSet("Client Options")
f.StringVar(&StringVar{
Name: "token-name",
Target: &c.FlagTokenName,
EnvVar: envTokenName,
Usage: "If specified, the given value will be used as the name when storing the token in the system credential store. This can allow switching user identities for different commands.",
})
f.BoolVar(&BoolVar{
Name: "output-curl-string",
+64 -1
View File
@@ -3,11 +3,15 @@ package base
import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"unicode"
"unicode/utf8"
"github.com/ghodss/yaml"
"github.com/mitchellh/cli"
"github.com/mitchellh/go-wordwrap"
"github.com/ryanuber/columnize"
)
@@ -17,6 +21,39 @@ const (
hopeDelim = "♨"
)
// This is adapted from the code in the strings package for TrimSpace
var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
func trimSpaceRight(in string) string {
for stop := len(in); stop > 0; stop-- {
c := in[stop-1]
if c >= utf8.RuneSelf {
return strings.TrimFunc(in[:stop], unicode.IsSpace)
}
if asciiSpace[c] == 0 {
return in[0:stop]
}
}
return ""
}
func WrapForHelpText(lines []string) string {
var ret []string
for _, line := range lines {
line = trimSpaceRight(line)
trimmed := strings.TrimSpace(line)
diff := uint(len(line) - len(trimmed))
wrapped := wordwrap.WrapString(trimmed, TermWidth-diff)
splitWrapped := strings.Split(wrapped, "\n")
for i := range splitWrapped {
splitWrapped[i] = fmt.Sprintf("%s%s", strings.Repeat(" ", int(diff)), strings.TrimSpace(splitWrapped[i]))
}
ret = append(ret, strings.Join(splitWrapped, "\n"))
}
return strings.Join(ret, "\n")
}
type FormatOptions struct {
Format string
}
@@ -25,7 +62,7 @@ type FormatOptions struct {
type JsonFormatter struct{}
func (j JsonFormatter) Format(data interface{}) ([]byte, error) {
return json.MarshalIndent(data, "", " ")
return json.Marshal(data)
}
/*
@@ -346,3 +383,29 @@ func looksLikeDuration(k string) bool {
k == "duration" || strings.HasSuffix(k, "_duration") ||
k == "lease_max" || k == "ttl_max"
}
type Formatter interface {
//Output(ui cli.Ui, secret *api.Secret, data interface{}) error
Format(data interface{}) ([]byte, error)
}
var Formatters = map[string]Formatter{
"json": JsonFormatter{},
"table": TableFormatter{},
"yaml": YamlFormatter{},
"yml": YamlFormatter{},
}
func Format(ui cli.Ui) string {
switch ui.(type) {
case *WatchtowerUI:
return ui.(*WatchtowerUI).Format
}
format := os.Getenv(EnvWatchtowerCLIFormat)
if format == "" {
format = "table"
}
return format
}
+71 -23
View File
@@ -27,6 +27,7 @@ import (
"github.com/hashicorp/watchtower/globals"
"github.com/hashicorp/watchtower/internal/db"
"github.com/hashicorp/watchtower/internal/iam"
"github.com/hashicorp/watchtower/internal/servers/controller/handlers/authenticate"
"github.com/hashicorp/watchtower/version"
"github.com/jinzhu/gorm"
"github.com/mitchellh/cli"
@@ -59,7 +60,8 @@ type Server struct {
Listeners []*ServerListener
DefaultOrgId string
DefaultOrgId string
DevAuthMethodId string
DevDatabaseUrl string
DevDatabaseCleanupFunc func() error
@@ -418,40 +420,86 @@ func (b *Server) CreateDevDatabase(dialect string) error {
cancel()
}()
var scope *iam.Scope
var orgScope *iam.Scope
if b.DefaultOrgId != "" {
scope, err = repo.LookupScope(ctx, b.DefaultOrgId)
orgScope, err = repo.LookupScope(ctx, b.DefaultOrgId)
if err != nil {
c()
return fmt.Errorf("error looking up existing scope with org ID %q: %w", b.DefaultOrgId, err)
}
if scope != nil {
goto INFO
}
}
scope, err = iam.NewOrg()
if err != nil {
c()
return fmt.Errorf("error creating new org scope: %w", err)
}
scope, err = repo.CreateScope(ctx, scope, iam.WithPublicId(b.DefaultOrgId))
if err != nil {
c()
return fmt.Errorf("error persisting new org scope: %w", err)
}
if b.DefaultOrgId != "" {
if scope.GetPublicId() != b.DefaultOrgId {
if orgScope == nil {
orgScope, err = iam.NewOrg()
if err != nil {
c()
return fmt.Errorf("expected org ID %q, got %q after persisting", b.DefaultOrgId, scope.GetPublicId())
return fmt.Errorf("error creating new org scope: %w", err)
}
orgScope, err = repo.CreateScope(ctx, orgScope, iam.WithPublicId(b.DefaultOrgId))
if err != nil {
c()
return fmt.Errorf("error persisting new org scope: %w", err)
}
if b.DefaultOrgId != "" {
if orgScope.GetPublicId() != b.DefaultOrgId {
c()
return fmt.Errorf("expected org ID %q, got %q after persisting", b.DefaultOrgId, orgScope.GetPublicId())
}
} else {
b.DefaultOrgId = orgScope.GetPublicId()
}
} else {
b.DefaultOrgId = scope.GetPublicId()
}
INFO:
b.InfoKeys = append(b.InfoKeys, "dev org id")
ar, err := iam.NewRole(orgScope.PublicId)
if err != nil {
return fmt.Errorf("error creating in memory role for anon authen: %w", err)
}
authenRole, err := repo.CreateRole(ctx, ar, iam.WithDescription("role for anon authen"))
if err != nil {
return fmt.Errorf("error creating role for anon authen: %w", err)
}
if _, err := repo.AddRoleGrants(ctx, authenRole.PublicId, authenRole.Version, []string{"type=auth-method;actions=list,authenticate"}); err != nil {
return fmt.Errorf("error creating grant for anon authen: %w", err)
}
if _, err := repo.AddPrincipalRoles(ctx, authenRole.PublicId, authenRole.Version+1, []string{"u_anon"}, nil); err != nil {
return fmt.Errorf("error adding principal to role for anon authen: %w", err)
}
pr, err := iam.NewRole(orgScope.PublicId)
if err != nil {
return fmt.Errorf("error creating in memory role for default dev grants: %w", err)
}
defPermsRole, err := repo.CreateRole(ctx, pr, iam.WithDescription("role for def grants"))
if err != nil {
return fmt.Errorf("error creating role for default dev grants: %w", err)
}
if _, err := repo.AddRoleGrants(ctx, defPermsRole.PublicId, defPermsRole.Version, []string{"id=*;actions=*"}); err != nil {
return fmt.Errorf("error creating grant for default dev grants: %w", err)
}
if _, err := repo.AddPrincipalRoles(ctx, defPermsRole.PublicId, defPermsRole.Version+1, []string{"u_auth"}, nil); err != nil {
return fmt.Errorf("error adding principal to role for default dev grants: %w", err)
}
// TODO: Remove this when Auth Account repo is in place.
authenticate.OrgScope = orgScope.GetPublicId()
insert := `insert into auth_method
(public_id, scope_id)
values
($1, $2);`
amId := b.DevAuthMethodId
if amId == "" {
amId = "am_1234567890"
}
authenticate.RWDb.Store(rw)
_, err = b.Database.DB().Exec(insert, amId, orgScope.GetPublicId())
if err != nil {
c()
return err
}
b.InfoKeys = append(b.InfoKeys, "dev org id", "dev auth method id")
b.Info["dev org id"] = b.DefaultOrgId
b.Info["dev auth method id"] = amId
return nil
}
+22
View File
@@ -0,0 +1,22 @@
package base
import (
"os"
"github.com/mitchellh/cli"
"golang.org/x/crypto/ssh/terminal"
)
type WatchtowerUI struct {
cli.Ui
Format string
}
var TermWidth uint = 80
func init() {
width, _, err := terminal.GetSize(int(os.Stdin.Fd()))
if err == nil {
TermWidth = uint(width)
}
}
+83
View File
@@ -6,10 +6,12 @@ import (
"syscall"
"github.com/hashicorp/watchtower/internal/cmd/base"
"github.com/hashicorp/watchtower/internal/cmd/commands/authenticate"
"github.com/hashicorp/watchtower/internal/cmd/commands/config"
"github.com/hashicorp/watchtower/internal/cmd/commands/controller"
"github.com/hashicorp/watchtower/internal/cmd/commands/dev"
"github.com/hashicorp/watchtower/internal/cmd/commands/hosts"
"github.com/hashicorp/watchtower/internal/cmd/commands/roles"
"github.com/hashicorp/watchtower/internal/cmd/commands/scopes"
"github.com/hashicorp/watchtower/internal/cmd/commands/worker"
@@ -82,6 +84,87 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
Command: base.NewCommand(ui),
}, nil
},
"authenticate": func() (cli.Command, error) {
return &authenticate.Command{
Command: base.NewCommand(ui),
}, nil
},
"authenticate password": func() (cli.Command, error) {
return &authenticate.PasswordCommand{
Command: base.NewCommand(ui),
}, nil
},
"roles": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
}, nil
},
"roles create": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "create",
}, nil
},
"roles update": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "update",
}, nil
},
"roles read": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "read",
}, nil
},
"roles delete": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "delete",
}, nil
},
"roles list": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "list",
}, nil
},
"roles add-principals": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "add-principals",
}, nil
},
"roles set-principals": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "set-principals",
}, nil
},
"roles remove-principals": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "remove-principals",
}, nil
},
"roles add-grants": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "add-grants",
}, nil
},
"roles set-grants": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "set-grants",
}, nil
},
"roles remove-grants": func() (cli.Command, error) {
return &roles.Command{
Command: base.NewCommand(ui),
Func: "remove-grants",
}, nil
},
}
}
@@ -0,0 +1,35 @@
package authenticate
import (
"github.com/hashicorp/watchtower/internal/cmd/base"
"github.com/mitchellh/cli"
"github.com/mitchellh/go-wordwrap"
)
var _ cli.Command = (*Command)(nil)
type Command struct {
*base.Command
}
func (c *Command) Synopsis() string {
return wordwrap.WrapString("Authenticate the Watchtower commandline client", base.TermWidth)
}
func (c *Command) Help() string {
return base.WrapForHelpText([]string{
"Usage: watchtower authenticate [sub command] [options] [args]",
"",
" This command authenticates the Watchtower commandline client using a specified auth method. Examples:",
"",
" Authenticate with password auth method:",
"",
" $ watchtower authenticate password -name foo -password bar",
"",
" Please see the auth method subcommand help for detailed usage information.",
})
}
func (c *Command) Run(args []string) int {
return cli.RunResultHelp
}
@@ -0,0 +1,163 @@
package authenticate
import (
"fmt"
"os"
"strings"
"time"
"github.com/hashicorp/vault/sdk/helper/password"
"github.com/hashicorp/watchtower/api/scopes"
"github.com/hashicorp/watchtower/internal/cmd/base"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/mitchellh/go-wordwrap"
"github.com/posener/complete"
"github.com/zalando/go-keyring"
)
var _ cli.Command = (*PasswordCommand)(nil)
var _ cli.CommandAutocomplete = (*PasswordCommand)(nil)
var envPassword = "WATCHTOWER_AUTHENTICATE_PASSWORD"
var envName = "WATCHTOWER_AUTHENTICATE_NAME"
var envMethodId = "WATCHTOWER_AUTHENTICATE_METHOD_ID"
type PasswordCommand struct {
*base.Command
flagName string
flagPassword string
flagMethodId string
}
func (c *PasswordCommand) Synopsis() string {
return wordwrap.WrapString("Invoke the password auth method to authenticate with Watchtower", base.TermWidth)
}
func (c *PasswordCommand) Help() string {
return base.WrapForHelpText([]string{
"Usage: watchtower authenticate password [options] [args]",
"",
" Invoke the password auth method to authenticate the Watchtower CLI:",
"",
" $ watchtower authenticate password -name=foo -password=bar",
"",
" If more than one instance of the password auth method exists, use the -method-id flag:",
"",
` $ watchtower authenticate password -method-id am_12345 -name foo -password "bar"`,
}) + c.Flags().Help()
}
func (c *PasswordCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
f.StringVar(&base.StringVar{
Name: "name",
Target: &c.flagName,
EnvVar: envName,
Usage: "Login name",
})
f.StringVar(&base.StringVar{
Name: "password",
Target: &c.flagPassword,
EnvVar: envPassword,
Usage: "Password",
})
f.StringVar(&base.StringVar{
Name: "method-id",
Target: &c.flagMethodId,
EnvVar: envMethodId,
Usage: "Specify if more than one instance of a password auth method exists in the given org",
})
return set
}
func (c *PasswordCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *PasswordCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *PasswordCommand) Run(args []string) int {
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
switch {
case c.flagName == "":
c.UI.Error("Name must be provided via -name")
return 1
case c.flagMethodId == "":
c.UI.Error("Auth method ID must be provided via -method-id")
return 1
}
if c.flagPassword == "" {
fmt.Print("Password is not set as flag or in env, please enter it now (will be hidden): ")
value, err := password.Read(os.Stdin)
fmt.Print("\n")
if err != nil {
c.UI.Error(fmt.Sprintf("An error occurred attempting to read the password. The raw error message is shown below but usually this is because you attempted to pipe a value into the command or you are executing outside of a terminal (TTY). The raw error was:\n\n%s", err.Error()))
return 2
}
c.flagPassword = strings.TrimSpace(value)
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
org := &scopes.Org{
Client: client,
}
// note: Authenticate() calls SetToken() under the hood to set the
// auth bearer on the client so we do not need to do anything with the
// returned token after this call, so we ignore it
result, apiErr, err := org.Authenticate(c.Context, c.flagMethodId, c.flagName, c.flagPassword)
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to perform authentication: %s", err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing authentication: %s", pretty.Sprint(apiErr)))
return 1
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(base.WrapForHelpText([]string{
"",
"Authentication information:",
fmt.Sprintf(" Token: %s", result.Token),
fmt.Sprintf(" User ID: %s", result.UserId),
fmt.Sprintf(" Expiration Time: %s", result.ExpirationTime.Local().Format(time.RFC3339)),
}))
}
tokenName := "default"
if c.Command.FlagTokenName != "" {
tokenName = c.Command.FlagTokenName
}
if tokenName != "none" {
if err := keyring.Set("HashiCorp Watchtower Auth Token", tokenName, result.Token); err != nil {
c.UI.Error(fmt.Sprintf("Error saving auth token to system credential store: %s", err))
return 1
}
}
return 0
}
@@ -48,6 +48,7 @@ type Command struct {
flagDevControllerAPIListenAddr string
flagDevControllerClusterListenAddr string
flagDevOrgId string
flagDevAuthMethodId string
flagDevPassthroughDirectory string
}
@@ -119,6 +120,14 @@ func (c *Command) Flags() *base.FlagSets {
"mode.",
})
f.StringVar(&base.StringVar{
Name: "dev-auth-method-id",
Target: &c.flagDevAuthMethodId,
EnvVar: "WATCHTWER_DEV_AUTH_METHOD_ID",
Usage: "Auto-created auth method ID. This only applies when running in \"dev\" " +
"mode.",
})
f.StringVar(&base.StringVar{
Name: "dev-admin-password",
Target: &c.flagDevAdminPassword,
@@ -336,6 +345,18 @@ func (c *Command) ParseFlagsAndConfig(args []string) int {
if c.flagDevOrgId != "" {
c.Config.DefaultOrgId = c.flagDevOrgId
}
if c.flagDevAuthMethodId != "" {
if !strings.HasPrefix(c.flagDevAuthMethodId, "am_") {
c.UI.Error(fmt.Sprintf("Invalid dev auth method ID, must start with %q", "am_"))
return 1
}
if len(c.flagDevAuthMethodId) != 13 {
c.UI.Error(fmt.Sprintf("Invalid dev auth method ID, must be 10 base62 characters after %q", "am_"))
return 1
}
c.DevAuthMethodId = c.flagDevAuthMethodId
}
c.Config.PassthroughDirectory = c.flagDevPassthroughDirectory
for _, l := range c.Config.Listeners {
+21
View File
@@ -36,6 +36,7 @@ type Command struct {
flagDev bool
flagDevAdminPassword string
flagDevOrgId string
flagDevAuthMethodId string
flagDevControllerAPIListenAddr string
flagDevControllerClusterListenAddr string
flagDevPassthroughDirectory string
@@ -92,6 +93,14 @@ func (c *Command) Flags() *base.FlagSets {
"mode.",
})
f.StringVar(&base.StringVar{
Name: "dev-auth-method-id",
Target: &c.flagDevAuthMethodId,
EnvVar: "WATCHTWER_DEV_AUTH_METHOD_ID",
Usage: "Auto-created auth method ID. This only applies when running in \"dev\" " +
"mode.",
})
f.StringVar(&base.StringVar{
Name: "dev-admin-password",
Target: &c.flagDevAdminPassword,
@@ -155,6 +164,18 @@ func (c *Command) Run(args []string) int {
if c.flagDevOrgId != "" {
devConfig.DefaultOrgId = c.flagDevOrgId
}
if c.flagDevAuthMethodId != "" {
if !strings.HasPrefix(c.flagDevAuthMethodId, "am_") {
c.UI.Error(fmt.Sprintf("Invalid dev auth method ID, must start with %q", "am_"))
return 1
}
if len(c.flagDevAuthMethodId) != 13 {
c.UI.Error(fmt.Sprintf("Invalid dev auth method ID, must be 10 base62 characters after %q", "am_"))
return 1
}
c.DevAuthMethodId = c.flagDevAuthMethodId
}
devConfig.PassthroughDirectory = c.flagDevPassthroughDirectory
for _, l := range devConfig.Listeners {
+1 -1
View File
@@ -45,7 +45,7 @@ Usage: watchtower hosts create
}
func (c *CreateCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetOutputFormat)
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
+232
View File
@@ -0,0 +1,232 @@
package roles
import (
"fmt"
"net/textproto"
"strings"
"time"
"github.com/hashicorp/watchtower/api/roles"
"github.com/hashicorp/watchtower/internal/cmd/base"
"github.com/mitchellh/go-wordwrap"
)
func synopsisFunc(inFunc string) string {
if inFunc == "" {
return wordwrap.WrapString("Manage Watchtower roles", base.TermWidth)
}
return wordwrap.WrapString(fmt.Sprintf("%s a role within Watchtower", textproto.CanonicalMIMEHeaderKey(inFunc)), base.TermWidth)
}
func principalsGrantsSynopsisFunc(inFunc string, principals bool) string {
var in string
switchStr := "principals (users, groups)"
if !principals {
switchStr = "grants"
}
switch {
case strings.HasPrefix(inFunc, "add"):
in = fmt.Sprintf("Add %s to", switchStr)
case strings.HasPrefix(inFunc, "set"):
in = fmt.Sprintf("Set the full contents of the %s on", switchStr)
case strings.HasPrefix(inFunc, "remove"):
in = fmt.Sprintf("Remove %s from", switchStr)
}
return wordwrap.WrapString(fmt.Sprintf("%s a role within Watchtower", in), base.TermWidth)
}
func baseHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles [sub command] [options] [args]",
"",
" This command allows operations on Watchtower roles. Examples:",
"",
" Create a role:",
"",
` $ watchtower roles create -name foo -description "For ProdOps usage"`,
"",
" Add a grant to a role:",
"",
` $ watchtower roles add-grants -id r_1234567890 -grant "type=host-catalog;actions=create,delete"`,
"",
" Please see the role subcommand help for detailed usage information.",
})
}
func createHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles create [options] [args]",
"",
" Create a role. Example:",
"",
` $ watchtower roles create -name ops -description "Role for ops grants"`,
"",
"",
})
}
func updateHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles update [options] [args]",
"",
" Update a role given its ID. Example:",
"",
` $ watchtower roles update -id r_1234567890 -description "Development host grants"`,
})
}
func readHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles read [options] [args]",
"",
" Read a role given its ID. Example:",
"",
` $ watchtower roles read -id r_1234567890`,
})
}
func deleteHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles delete [options] [args]",
"",
" Delete a role given its ID. Example:",
"",
` $ watchtower roles delete -id r_1234567890`,
})
}
func listHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles list [options] [args]",
"",
" List roles within a scope. Example:",
"",
` $ watchtower roles list -org o_1234567890`,
})
}
func addPrincipalsHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles add-principals [options] [args]",
"",
` Adds principals (users, groups) to a role given its ID. The "user" and "group" flags can be specified multiple times. Example:`,
"",
` $ watchtower roles add-principals -id r_1234567890 -user u_1234567890`,
})
}
func setPrincipalsHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles set-principals [options] [args]",
"",
` Sets the complete set of principals (users, groups) on a role given its ID. The "user" and "group" flags can be specified multiple times. Example:`,
"",
` $ watchtower roles set-principals -id r_1234567890 -user u_anon -group sg_1234567890`,
})
}
func removePrincipalsHelp() string {
return base.WrapForHelpText([]string{
"Usage: watchtower roles remove-principals [options] [args]",
"",
` Removes principals (users, groups) from a role given its ID. The "user" and "group" flags can be specified multiple times. Example:`,
"",
` $ watchtower roles remove-principals -id r_1234567890 -group sg_1234567890`,
})
}
func populateFlags(c *Command, f *base.FlagSet, flagNames []string) {
for _, name := range flagNames {
switch name {
case "id":
f.StringVar(&base.StringVar{
Name: "id",
Target: &c.flagId,
Usage: "ID of the role to operate on",
})
case "name":
f.StringVar(&base.StringVar{
Name: "name",
Target: &c.flagName,
Usage: "Name to set on the role",
})
case "description":
f.StringVar(&base.StringVar{
Name: "description",
Target: &c.flagDescription,
Usage: "Description to set on the role",
})
case "grantscopeid":
f.StringVar(&base.StringVar{
Name: "grant-scope-id",
Target: &c.flagGrantScopeId,
Usage: "The scope ID for grants set on the role",
})
case "principal":
f.StringSliceVar(&base.StringSliceVar{
Name: "principal",
Target: &c.flagPrincipals,
Usage: "The principals (users or groups) to add, remove, or set. May be specified multiple times.",
})
case "grant":
f.StringSliceVar(&base.StringSliceVar{
Name: "grant",
Target: &c.flagGrants,
Usage: "The grants to add, remove, or set. May be specified multiple times. Can be in compact string format or JSON (be sure to escape JSON properly).",
})
}
}
}
func generateRoleTableOutput(role *roles.Role) string {
var output []string
if true {
output = []string{
"",
"Role information:",
fmt.Sprintf(" ID: %s", role.Id),
fmt.Sprintf(" Created At: %s", role.CreatedTime.Local().Format(time.RFC3339)),
fmt.Sprintf(" Updated At: %s", role.UpdatedTime.Local().Format(time.RFC3339)),
fmt.Sprintf(" Version: %d", role.Version),
}
}
if role.Name != nil {
output = append(output,
fmt.Sprintf(" Name: %s", *role.Name),
)
}
if role.Description != nil {
output = append(output,
fmt.Sprintf(" Description: %s", *role.Description),
)
}
if role.GrantScopeId != nil {
output = append(output,
fmt.Sprintf(" Grant Scope ID: %s", *role.GrantScopeId),
)
}
if len(role.Principals) > 0 {
output = append(output,
fmt.Sprintf(" Principals: %s", ""),
)
}
for _, principal := range role.Principals {
output = append(output,
fmt.Sprintf(" ID: %s", principal.Id),
fmt.Sprintf(" Type: %s", principal.Type),
fmt.Sprintf(" Scope ID: %s", principal.ScopeId),
)
}
if len(role.GrantsCanonical) > 0 {
output = append(output,
fmt.Sprintf(" Canonical Grants: %s", ""),
)
}
for _, grant := range role.GrantsCanonical {
output = append(output,
fmt.Sprintf(" %s", grant),
)
}
return base.WrapForHelpText(output)
}
+363
View File
@@ -0,0 +1,363 @@
package roles
import (
"context"
"fmt"
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/watchtower/api"
"github.com/hashicorp/watchtower/api/roles"
"github.com/hashicorp/watchtower/api/scopes"
"github.com/hashicorp/watchtower/internal/cmd/base"
"github.com/hashicorp/watchtower/internal/perms"
"github.com/kr/pretty"
"github.com/mitchellh/cli"
"github.com/posener/complete"
)
var _ cli.Command = (*Command)(nil)
var _ cli.CommandAutocomplete = (*Command)(nil)
type Command struct {
*base.Command
Func string
flagId string
flagName string
flagDescription string
flagGrantScopeId string
flagPrincipals []string
flagGrants []string
}
func (c *Command) Synopsis() string {
switch c.Func {
case "create", "update", "read", "delete", "list":
return synopsisFunc(c.Func)
case "add-principals", "set-principals", "remove-principals":
return principalsGrantsSynopsisFunc(c.Func, true)
case "add-grants", "set-grants", "remove-grants":
return principalsGrantsSynopsisFunc(c.Func, false)
}
return "Manage Watchtower roles"
}
var helpMap = map[string]func() string{
"create": createHelp,
"update": updateHelp,
"read": readHelp,
"delete": deleteHelp,
"list": listHelp,
"add-principals": addPrincipalsHelp,
"set-principals": setPrincipalsHelp,
"remove-principals": removePrincipalsHelp,
"add-grants": addPrincipalsHelp,
"set-grants": setPrincipalsHelp,
"remove-grants": removePrincipalsHelp,
}
var flagsMap = map[string][]string{
"create": {"name", "description", "grantscopeid"},
"update": {"id", "name", "description", "grantscopeid"},
"read": {"id"},
"delete": {"id"},
"add-principals": {"id", "principal"},
"set-principals": {"id", "principal"},
"remove-principals": {"id", "principal"},
"add-grants": {"id", "grant"},
"set-grants": {"id", "grant"},
"remove-grants": {"id", "grant"},
}
func (c *Command) Help() string {
if c.Func == "" {
return baseHelp()
}
return helpMap[c.Func]() + "\n\n" + c.Flags().Help()
}
func (c *Command) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
populateFlags(c, f, flagsMap[c.Func])
return set
}
func (c *Command) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *Command) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *Command) Run(args []string) int {
if c.Func == "" {
return cli.RunResultHelp
}
f := c.Flags()
if err := f.Parse(args); err != nil {
c.UI.Error(err.Error())
return 1
}
if strutil.StrListContains(flagsMap[c.Func], "id") && c.flagId == "" {
c.UI.Error("ID is required but not passed in via -id")
return 1
}
client, err := c.Client()
if err != nil {
c.UI.Error(fmt.Sprintf("Error creating API client: %s", err.Error()))
return 2
}
role := &roles.Role{
Client: client,
Id: c.flagId,
}
switch c.flagName {
case "":
case "null":
role.SetDefault("name")
default:
role.Name = api.String(c.flagName)
}
switch c.flagDescription {
case "":
case "null":
role.SetDefault("description")
default:
role.Description = api.String(c.flagDescription)
}
switch c.flagGrantScopeId {
case "":
case "null":
role.SetDefault("grantscopeid")
default:
role.GrantScopeId = api.String(c.flagGrantScopeId)
}
principals := c.flagPrincipals
grants := c.flagGrants
switch c.Func {
case "add-principals", "remove-principals":
if len(c.flagPrincipals) == 0 {
c.UI.Error("No principals supplied via -principal")
return 1
}
case "add-grants", "remove-grants":
if len(c.flagGrants) == 0 {
c.UI.Error("No grants supplied via -grant")
return 1
}
case "set-principals":
switch len(c.flagPrincipals) {
case 0:
case 1:
if c.flagPrincipals[0] == "null" {
principals = []string{}
}
}
if principals == nil {
c.UI.Error("No principals supplied via -principals")
return 1
}
case "set-grants":
switch len(c.flagGrants) {
case 0:
case 1:
if c.flagGrants[0] == "null" {
grants = []string{}
}
}
if grants == nil {
c.UI.Error("No grants supplied via -grant")
return 1
}
}
if len(grants) > 0 {
for _, grant := range grants {
_, err := perms.Parse("global", "", grant)
if err != nil {
c.UI.Error(fmt.Errorf("Grant %q could not be parsed successfully: %w", grant, err).Error())
return 1
}
}
}
var apiErr *api.Error
type crudl interface {
CreateRole(context.Context, *roles.Role) (*roles.Role, *api.Error, error)
UpdateRole(context.Context, *roles.Role) (*roles.Role, *api.Error, error)
ReadRole(context.Context, *roles.Role) (*roles.Role, *api.Error, error)
DeleteRole(context.Context, *roles.Role) (bool, *api.Error, error)
ListRoles(context.Context) ([]*roles.Role, *api.Error, error)
}
var actor crudl
var existed bool
var listedRoles []*roles.Role
switch {
case client.Project() != "":
project := &scopes.Project{
Client: client,
}
actor = project
case client.Org() != "":
org := &scopes.Org{
Client: client,
}
actor = org
default:
// TODO: Handle global case
c.UI.Error("TODO")
}
if actor == nil {
c.UI.Error("Unable to determine the right scope for the command")
return 1
}
// Perform check-and-set when needed
switch c.Func {
case "create", "read", "delete", "list":
// These don't udpate so don't need the existing version
default:
existingRole, existingApiErr, existingErr := actor.ReadRole(c.Context, role)
if existingErr != nil {
c.UI.Error(fmt.Sprintf("Error performing initial check-and-set read: %s", err.Error()))
return 2
}
if existingApiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing initial check-and-set read: %s", pretty.Sprint(apiErr)))
return 1
}
role.Version = existingRole.Version
}
switch c.Func {
case "create":
role, apiErr, err = actor.CreateRole(c.Context, role)
case "update":
role, apiErr, err = actor.UpdateRole(c.Context, role)
case "read":
role, apiErr, err = actor.ReadRole(c.Context, role)
case "delete":
existed, apiErr, err = actor.DeleteRole(c.Context, role)
case "list":
listedRoles, apiErr, err = actor.ListRoles(c.Context)
case "add-principals":
role, apiErr, err = role.AddPrincipals(c.Context, principals)
case "set-principals":
role, apiErr, err = role.SetPrincipals(c.Context, principals)
case "remove-principals":
role, apiErr, err = role.RemovePrincipals(c.Context, principals)
case "add-grants":
role, apiErr, err = role.AddGrants(c.Context, grants)
case "set-grants":
role, apiErr, err = role.SetGrants(c.Context, grants)
case "remove-grants":
role, apiErr, err = role.RemoveGrants(c.Context, grants)
}
plural := "role"
if c.Func == "list" {
plural = "roles"
}
if err != nil {
c.UI.Error(fmt.Sprintf("Error trying to %s %s: %s", c.Func, plural, err.Error()))
return 2
}
if apiErr != nil {
c.UI.Error(fmt.Sprintf("Error from controller when performing %s on %s: %s", c.Func, plural, pretty.Sprint(apiErr)))
return 1
}
switch c.Func {
case "delete":
switch base.Format(c.UI) {
case "json":
c.UI.Output("null")
case "table":
output := "The delete operation completed successfully"
switch existed {
case true:
output += "."
default:
output += ", however the resource did not exist at the time."
}
c.UI.Output(output)
}
return 0
case "list":
if len(listedRoles) == 0 {
c.UI.Output("No roles found")
return 0
}
switch base.Format(c.UI) {
case "json":
b, err := base.JsonFormatter{}.Format(listedRoles)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting to JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
case "table":
var output []string
output = []string{
"",
"Role information:",
}
for i, r := range listedRoles {
if i > 0 {
output = append(output, "")
}
if true {
output = append(output,
fmt.Sprintf(" ID: %s", r.Id),
)
}
if r.Name != nil {
output = append(output,
fmt.Sprintf(" Name: %s", *r.Name),
)
}
if r.Description != nil {
output = append(output,
fmt.Sprintf(" Description: %s", *r.Description),
)
}
}
c.UI.Output(base.WrapForHelpText(output))
}
return 0
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(generateRoleTableOutput(role))
case "json":
b, err := base.JsonFormatter{}.Format(role)
if err != nil {
c.UI.Error(fmt.Errorf("Error formatting to JSON: %w", err).Error())
return 1
}
c.UI.Output(string(b))
}
return 0
}
+36
View File
@@ -0,0 +1,36 @@
package scopes
import (
"fmt"
"time"
"github.com/hashicorp/watchtower/api/scopes"
"github.com/hashicorp/watchtower/internal/cmd/base"
)
func printProject(in *scopes.Project) string {
var ret []string
// This if true is here to line up columns for easy editing
if true {
ret = append(ret, []string{
"",
"Project information:",
fmt.Sprintf(" ID: %s", in.Id),
fmt.Sprintf(" Created Time: %s", in.CreatedTime.Local().Format(time.RFC3339)),
fmt.Sprintf(" Updated Time: %s", in.UpdatedTime.Local().Format(time.RFC3339)),
}...,
)
}
if in.Name != nil {
ret = append(ret,
fmt.Sprintf(" Name: %s", *in.Name),
)
}
if in.Description != nil {
ret = append(ret,
fmt.Sprintf(" Description: %s", *in.Description),
)
}
return base.WrapForHelpText(ret)
}
@@ -43,7 +43,7 @@ Usage: watchtower projects create
}
func (c *CreateProjectCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetOutputFormat)
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
@@ -105,8 +105,11 @@ func (c *CreateProjectCommand) Run(args []string) int {
case apiErr != nil:
c.UI.Error(pretty.Sprint(apiErr))
return 2
default:
c.UI.Info(pretty.Sprint(project))
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(printProject(project))
}
return 0
+6 -3
View File
@@ -43,7 +43,7 @@ Usage: watchtower projects read
}
func (c *ReadProjectCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetOutputFormat)
set := c.FlagSet(base.FlagSetHTTP | base.FlagSetClient | base.FlagSetOutputFormat)
f := set.NewFlagSet("Command Options")
@@ -97,8 +97,11 @@ func (c *ReadProjectCommand) Run(args []string) int {
case apiErr != nil:
c.UI.Error(pretty.Sprint(apiErr))
return 2
default:
c.UI.Info(pretty.Sprint(project))
}
switch base.Format(c.UI) {
case "table":
c.UI.Output(printProject(project))
}
return 0
-34
View File
@@ -1,34 +0,0 @@
package cmd
import (
"os"
"github.com/hashicorp/watchtower/internal/cmd/base"
"github.com/mitchellh/cli"
)
type Formatter interface {
//Output(ui cli.Ui, secret *api.Secret, data interface{}) error
Format(data interface{}) ([]byte, error)
}
var Formatters = map[string]Formatter{
"json": base.JsonFormatter{},
"table": base.TableFormatter{},
"yaml": base.YamlFormatter{},
"yml": base.YamlFormatter{},
}
func Format(ui cli.Ui) string {
switch ui.(type) {
case *WatchtowerUI:
return ui.(*WatchtowerUI).format
}
format := os.Getenv(base.EnvWatchtowerCLIFormat)
if format == "" {
format = "table"
}
return format
}
+5 -10
View File
@@ -18,11 +18,6 @@ import (
"github.com/mitchellh/cli"
)
type WatchtowerUI struct {
cli.Ui
format string
}
// setupEnv parses args and may replace them and sets some env vars to known
// values based on format options
func setupEnv(args []string) (retArgs []string, format string, outputCurlString bool) {
@@ -128,7 +123,7 @@ func RunCustom(args []string, runOpts *RunOptions) int {
uiErrWriter = ioutil.Discard
}
ui := &WatchtowerUI{
ui := &base.WatchtowerUI{
Ui: &cli.ColoredUi{
ErrorColor: cli.UiColorRed,
WarnColor: cli.UiColorYellow,
@@ -138,10 +133,10 @@ func RunCustom(args []string, runOpts *RunOptions) int {
ErrorWriter: uiErrWriter,
},
},
format: format,
Format: format,
}
serverCmdUi := &WatchtowerUI{
serverCmdUi := &base.WatchtowerUI{
Ui: &cli.ColoredUi{
ErrorColor: cli.UiColorRed,
WarnColor: cli.UiColorYellow,
@@ -150,10 +145,10 @@ func RunCustom(args []string, runOpts *RunOptions) int {
Writer: runOpts.Stdout,
},
},
format: format,
Format: format,
}
if _, ok := Formatters[format]; !ok {
if _, ok := base.Formatters[format]; !ok {
ui.Error(fmt.Sprintf("Invalid output format: %s", format))
return 1
}