Add read:self and delete:self to auth tokens and add logout command (#1162)

This commit is contained in:
Jeff Mitchell authored and GitHub committed 2021-04-23 13:45:08 -04:00
1 parent 3fe94335d4
commit e6af51943d
20 files changed
+966 -223

No files matched your search

+1 -144
View File
@@ -3,8 +3,6 @@ package base
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
@@ -12,19 +10,15 @@ import (
"os"
"os/signal"
"regexp"
"runtime"
"strings"
"sync"
"syscall"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/authtokens"
"github.com/hashicorp/boundary/sdk/wrapper"
nkeyring "github.com/jefferai/keyring"
"github.com/mitchellh/cli"
"github.com/pkg/errors"
"github.com/posener/complete"
zkeyring "github.com/zalando/go-keyring"
)
const (
@@ -126,7 +120,7 @@ func MakeShutdownCh() chan struct{} {
// Client returns the HTTP API client. The client is cached on the command to
// save performance on future calls.
func (c *Command) Client(opt ...Option) (*api.Client, error) {
// Read the test client if present
// Read the cached client if present
if c.client != nil {
return c.client, nil
}
@@ -242,143 +236,6 @@ func (c *Command) Client(opt ...Option) (*api.Client, error) {
return c.client, nil
}
func (c *Command) DiscoverKeyringTokenInfo() (string, string, error) {
tokenName := "default"
if c.FlagTokenName != "" {
tokenName = c.FlagTokenName
}
if tokenName == "none" {
c.UI.Warn(`"-token-name=none" is deprecated, please use "-keyring-type=none"`)
c.FlagKeyringType = "none"
}
if c.FlagKeyringType == "none" {
return "", "", nil
}
// Set so we can look it up later when printing out curl strings
os.Setenv(EnvTokenName, tokenName)
var foundKeyringType bool
keyringType := c.FlagKeyringType
switch runtime.GOOS {
case "windows":
switch keyringType {
case "auto", "wincred", "pass":
foundKeyringType = true
if keyringType == "auto" {
keyringType = "wincred"
}
}
case "darwin":
switch keyringType {
case "auto", "keychain", "pass":
foundKeyringType = true
if keyringType == "auto" {
keyringType = "keychain"
}
}
default:
switch keyringType {
case "auto", "secret-service", "pass":
foundKeyringType = true
if keyringType == "auto" {
keyringType = "pass"
}
}
}
if !foundKeyringType {
return "", "", fmt.Errorf("Given keyring type %q is not valid, or not valid for this platform", c.FlagKeyringType)
}
var available bool
switch keyringType {
case "wincred", "keychain":
available = true
case "pass", "secret-service":
avail := nkeyring.AvailableBackends()
for _, a := range avail {
if keyringType == string(a) {
available = true
}
}
}
if !available {
return "", "", fmt.Errorf("Keyring type %q is not available on this machine. For help with setting up keyrings, see https://www.boundaryproject.io/docs/api-clients/cli.", keyringType)
}
os.Setenv(EnvKeyringType, keyringType)
return keyringType, tokenName, nil
}
func (c *Command) ReadTokenFromKeyring(keyringType, tokenName string) *authtokens.AuthToken {
var token string
var err error
switch keyringType {
case "none":
return nil
case "wincred", "keychain":
token, err = zkeyring.Get(StoredTokenName, tokenName)
if err != nil {
if err == zkeyring.ErrNotFound {
c.UI.Error("No saved credential found, continuing without")
} else {
c.UI.Error(fmt.Sprintf("Error reading auth token from keyring: %s", err))
c.UI.Warn("Token must be provided via BOUNDARY_TOKEN env var or -token flag. Reading the token can also be disabled via -keyring-type=none.")
}
token = ""
}
default:
krConfig := nkeyring.Config{
LibSecretCollectionName: "login",
PassPrefix: "HashiCorp_Boundary",
AllowedBackends: []nkeyring.BackendType{nkeyring.BackendType(keyringType)},
}
kr, err := nkeyring.Open(krConfig)
if err != nil {
c.UI.Error(fmt.Sprintf("Error opening keyring: %s", err))
c.UI.Warn("Token must be provided via BOUNDARY_TOKEN env var or -token flag. Reading the token can also be disabled via -keyring-type=none.")
break
}
item, err := kr.Get(tokenName)
if err != nil {
c.UI.Error(fmt.Sprintf("Error fetching token from keyring: %s", err))
c.UI.Warn("Token must be provided via BOUNDARY_TOKEN env var or -token flag. Reading the token can also be disabled via -keyring-type=none.")
break
}
token = string(item.Data)
}
if token != "" {
tokenBytes, err := base64.RawStdEncoding.DecodeString(token)
switch {
case err != nil:
c.UI.Error(fmt.Errorf("Error base64-unmarshaling stored token from system credential store: %w", err).Error())
case len(tokenBytes) == 0:
c.UI.Error("Zero length token after decoding stored token from system credential store")
default:
var authToken authtokens.AuthToken
if err := json.Unmarshal(tokenBytes, &authToken); err != nil {
c.UI.Error(fmt.Sprintf("Error unmarshaling stored token information after reading from system credential store: %s", err))
} else {
return &authToken
}
}
}
return nil
}
type FlagSetBit uint
const (
+3 -1
View File
@@ -62,6 +62,7 @@ func (b *Server) CreateInitialLoginRole(ctx context.Context) (*iam.Role, error)
"id=*;type=scope;actions=list,no-op",
"id=*;type=auth-method;actions=authenticate,list",
"id={{account.id}};actions=read,change-password",
"id=*;type=auth-token;actions=list,read:self,delete:self",
}); err != nil {
return nil, fmt.Errorf("error creating grant for default generated grants: %w", err)
}
@@ -517,7 +518,8 @@ func (b *Server) CreateInitialTarget(ctx context.Context) (target.Target, error)
b.Info["generated target id"] = b.DevTargetId
// If we have an unprivileged dev user, add user to the role that grants
// list/read:self/cancel:self, and an authorize-session role
// list/read:self/cancel:self on sessions, read:self/delete:self/list on
// tokens, and an authorize-session role
if b.DevUnprivilegedUserId != "" {
iamRepo, err := iam.NewRepository(rw, rw, kmsCache, iam.WithRandomReader(b.SecureRandomReader))
if err != nil {
+173
View File
@@ -0,0 +1,173 @@
package base
import (
"encoding/base64"
"encoding/json"
"fmt"
"os"
"runtime"
"strings"
"github.com/hashicorp/boundary/api/authtokens"
nkeyring "github.com/jefferai/keyring"
"github.com/pkg/errors"
zkeyring "github.com/zalando/go-keyring"
)
const (
NoneKeyring = "none"
AutoKeyring = "auto"
WincredKeyring = "wincred"
PassKeyring = "pass"
KeychainKeyring = "keychain"
SecretServiceKeyring = "secret-service"
DefaultTokenName = "default"
LoginCollection = "login"
PassPrefix = "HashiCorp_Boundary"
)
func (c *Command) DiscoverKeyringTokenInfo() (string, string, error) {
tokenName := DefaultTokenName
if c.FlagTokenName != "" {
tokenName = c.FlagTokenName
}
if tokenName == NoneKeyring {
c.UI.Warn(`"-token-name=none" is deprecated, please use "-keyring-type=none"`)
c.FlagKeyringType = NoneKeyring
}
if c.FlagKeyringType == NoneKeyring {
return "", "", nil
}
// Set so we can look it up later when printing out curl strings
os.Setenv(EnvTokenName, tokenName)
var foundKeyringType bool
keyringType := c.FlagKeyringType
switch runtime.GOOS {
case "windows":
switch keyringType {
case AutoKeyring, WincredKeyring, PassKeyring:
foundKeyringType = true
if keyringType == AutoKeyring {
keyringType = WincredKeyring
}
}
case "darwin":
switch keyringType {
case AutoKeyring, KeychainKeyring, PassKeyring:
foundKeyringType = true
if keyringType == AutoKeyring {
keyringType = KeychainKeyring
}
}
default:
switch keyringType {
case AutoKeyring, SecretServiceKeyring, PassKeyring:
foundKeyringType = true
if keyringType == AutoKeyring {
keyringType = PassKeyring
}
}
}
if !foundKeyringType {
return "", "", fmt.Errorf("Given keyring type %q is not valid, or not valid for this platform", c.FlagKeyringType)
}
var available bool
switch keyringType {
case WincredKeyring, KeychainKeyring:
available = true
case PassKeyring, SecretServiceKeyring:
avail := nkeyring.AvailableBackends()
for _, a := range avail {
if keyringType == string(a) {
available = true
}
}
}
if !available {
return "", "", fmt.Errorf("Keyring type %q is not available on this machine. For help with setting up keyrings, see https://www.boundaryproject.io/docs/api-clients/cli.", keyringType)
}
os.Setenv(EnvKeyringType, keyringType)
return keyringType, tokenName, nil
}
func (c *Command) ReadTokenFromKeyring(keyringType, tokenName string) *authtokens.AuthToken {
var token string
var err error
switch keyringType {
case NoneKeyring:
return nil
case WincredKeyring, KeychainKeyring:
token, err = zkeyring.Get(StoredTokenName, tokenName)
if err != nil {
if err == zkeyring.ErrNotFound {
c.UI.Error("No saved credential found, continuing without")
} else {
c.UI.Error(fmt.Sprintf("Error reading auth token from keyring: %s", err))
c.UI.Warn("Token must be provided via BOUNDARY_TOKEN env var or -token flag. Reading the token can also be disabled via -keyring-type=none.")
}
token = ""
}
default:
krConfig := nkeyring.Config{
LibSecretCollectionName: LoginCollection,
PassPrefix: PassPrefix,
AllowedBackends: []nkeyring.BackendType{nkeyring.BackendType(keyringType)},
}
kr, err := nkeyring.Open(krConfig)
if err != nil {
c.UI.Error(fmt.Sprintf("Error opening keyring: %s", err))
c.UI.Warn("Token must be provided via BOUNDARY_TOKEN env var or -token flag. Reading the token can also be disabled via -keyring-type=none.")
break
}
item, err := kr.Get(tokenName)
if err != nil {
c.UI.Error(fmt.Sprintf("Error fetching token from keyring: %s", err))
c.UI.Warn("Token must be provided via BOUNDARY_TOKEN env var or -token flag. Reading the token can also be disabled via -keyring-type=none.")
break
}
token = string(item.Data)
}
if token != "" {
tokenBytes, err := base64.RawStdEncoding.DecodeString(token)
switch {
case err != nil:
c.UI.Error(fmt.Errorf("Error base64-unmarshaling stored token from system credential store: %w", err).Error())
case len(tokenBytes) == 0:
c.UI.Error("Zero length token after decoding stored token from system credential store")
default:
var authToken authtokens.AuthToken
if err := json.Unmarshal(tokenBytes, &authToken); err != nil {
c.UI.Error(fmt.Sprintf("Error unmarshaling stored token information after reading from system credential store: %s", err))
} else {
return &authToken
}
}
}
return nil
}
func TokenIdFromToken(token string) (string, error) {
split := strings.Split(token, "_")
if len(split) < 3 {
return "", errors.New("Unexpected stored token format")
}
return strings.Join(split[0:2], "_"), nil
}
+7
View File
@@ -14,6 +14,7 @@ import (
"github.com/hashicorp/boundary/internal/cmd/commands/hostcatalogscmd"
"github.com/hashicorp/boundary/internal/cmd/commands/hostscmd"
"github.com/hashicorp/boundary/internal/cmd/commands/hostsetscmd"
"github.com/hashicorp/boundary/internal/cmd/commands/logout"
"github.com/hashicorp/boundary/internal/cmd/commands/rolescmd"
"github.com/hashicorp/boundary/internal/cmd/commands/scopescmd"
"github.com/hashicorp/boundary/internal/cmd/commands/server"
@@ -539,6 +540,12 @@ func initCommands(ui, serverCmdUi cli.Ui, runOpts *RunOptions) {
}, nil
},
"logout": func() (cli.Command, error) {
return &logout.LogoutCommand{
Command: base.NewCommand(ui),
}, nil
},
"roles": func() (cli.Command, error) {
return &rolescmd.Command{
Command: base.NewCommand(ui),
@@ -130,11 +130,6 @@ func (c *Command) Run(args []string) int {
return base.CommandUserError
}
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return base.CommandUserError
}
var opts []authtokens.Option
if strutil.StrListContains(flagsMap[c.Func], "scope-id") {
@@ -1,13 +1,60 @@
package authtokenscmd
import (
"errors"
"fmt"
"time"
"github.com/hashicorp/boundary/api/authtokens"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/hashicorp/boundary/sdk/strutil"
)
const selfFlag = "self"
func init() {
extraFlagsHandlingFunc = extraFlagsHandlingFuncImpl
}
func extraFlagsHandlingFuncImpl(c *Command, _ *base.FlagSets, _ *[]authtokens.Option) bool {
if c.Func != "delete" && c.Func != "read" {
if strutil.StrListContains(flagsMap[c.Func], "id") && c.FlagId == "" {
c.PrintCliError(errors.New("ID is required but not passed in via -id"))
return false
}
return true
}
if c.FlagId == "" {
fmt.Printf("No ID provided; %s the stored token? (Pass an ID of %q to suppress this question.) y/n: ", c.Func, selfFlag)
var yesNo string
fmt.Scanf("%s", &yesNo)
switch yesNo {
case "y", "Y":
c.FlagId = selfFlag
default:
c.PrintCliError(errors.New(`"Y" or "y" not provided, refusing to continue`))
return false
}
}
if c.FlagId == selfFlag {
// We should have already read this and have it cached
client, err := c.Client()
if err != nil {
c.PrintCliError(fmt.Errorf("Error reading cached API client: %w", err))
return false
}
c.FlagId, err = base.TokenIdFromToken(client.Token())
if err != nil {
c.PrintCliError(err)
return false
}
}
return true
}
func (c *Command) printListTable(items []*authtokens.AuthToken) string {
if len(items) == 0 {
return "No auth tokens found"
+16 -19
View File
@@ -1,8 +1,6 @@
package config
import (
"fmt"
"github.com/hashicorp/boundary/api/authtokens"
"github.com/hashicorp/boundary/internal/cmd/base"
"github.com/mitchellh/cli"
@@ -25,7 +23,7 @@ type TokenCommand struct {
}
func (c *TokenCommand) Synopsis() string {
return fmt.Sprintf("Get the stored token, or its properties")
return "Get the stored token, or its properties"
}
func (c *TokenCommand) Help() string {
@@ -125,27 +123,29 @@ func (c *TokenCommand) Run(args []string) (ret int) {
// Read from client first as that will override keyring anyways
var authToken *authtokens.AuthToken
// Fallback to env/CLI
client, err := c.Client()
if err != nil {
c.UI.Error(err.Error())
return base.CommandCliError
}
if client.Token() != "" {
authToken = &authtokens.AuthToken{Token: client.Token()}
}
if authToken == nil {
if optCount == 1 {
// In this case we need to read the full auth token stored, not just the
// actual token value for the client.
keyringType, tokenName, err := c.DiscoverKeyringTokenInfo()
if err != nil {
c.UI.Error(err.Error())
return base.CommandCliError
}
authToken = c.ReadTokenFromKeyring(keyringType, tokenName)
} else {
// Fallback to env/CLI but we can only get just the token value this way, at
// least for now
client, err := c.Client()
if err != nil {
c.UI.Error(err.Error())
return base.CommandCliError
}
if client.Token() != "" {
authToken = &authtokens.AuthToken{Token: client.Token()}
}
}
if authToken == nil {
if authToken == nil || authToken.Token == "" {
c.UI.Error("No token could be discovered")
return base.CommandCliError
}
@@ -170,9 +170,6 @@ func (c *TokenCommand) Run(args []string) (ret int) {
c.UI.Output(authToken.AuthMethodId)
default:
if authToken.Token == "" {
return base.CommandUserError
}
c.UI.Output(authToken.Token)
}
+161
View File
@@ -0,0 +1,161 @@
package logout
import (
"errors"
"fmt"
"net/http"
"github.com/hashicorp/boundary/api"
"github.com/hashicorp/boundary/api/authtokens"
"github.com/hashicorp/boundary/internal/cmd/base"
nkeyring "github.com/jefferai/keyring"
"github.com/mitchellh/cli"
"github.com/posener/complete"
zkeyring "github.com/zalando/go-keyring"
)
var (
_ cli.Command = (*LogoutCommand)(nil)
_ cli.CommandAutocomplete = (*LogoutCommand)(nil)
)
type LogoutCommand struct {
*base.Command
Func string
}
func (c *LogoutCommand) Synopsis() string {
return "Delete the current token within Boundary and forget it locally"
}
func (c *LogoutCommand) Help() string {
var args []string
args = append(args,
"Usage: boundary logout [options]",
"",
" Delete the current token (as selected by -token-name) within Boundary and forget it from the local store. Example:",
"",
` $ boundary logout`,
"",
)
return base.WrapForHelpText(args) + c.Flags().Help()
}
func (c *LogoutCommand) Flags() *base.FlagSets {
set := c.FlagSet(base.FlagSetNone)
f := set.NewFlagSet("Command Options")
f.StringVar(&base.StringVar{
Name: "token-name",
Target: &c.FlagTokenName,
EnvVar: base.EnvTokenName,
Usage: `If specified, the given value will be used as the name when loading the token from the system credential store. This must correspond to a name used when authenticating.`,
})
f.StringVar(&base.StringVar{
Name: "keyring-type",
Target: &c.FlagKeyringType,
Default: "auto",
EnvVar: base.EnvKeyringType,
Usage: `The type of keyring to use. Defaults to "auto" which will use the Windows credential manager, OSX keychain, or cross-platform password store depending on platform. Set to "none" to disable keyring functionality. Available types, depending on platform, are: "wincred", "keychain", "pass", and "secret-service".`,
})
return set
}
func (c *LogoutCommand) AutocompleteArgs() complete.Predictor {
return complete.PredictAnything
}
func (c *LogoutCommand) AutocompleteFlags() complete.Flags {
return c.Flags().Completions()
}
func (c *LogoutCommand) Run(args []string) (ret int) {
f := c.Flags()
if err := f.Parse(args); err != nil {
c.PrintCliError(err)
return base.CommandUserError
}
client, err := c.Client()
if err != nil {
c.PrintCliError(fmt.Errorf("Error reading API client: %w", err))
return base.CommandCliError
}
if client.Token() == "" {
c.PrintCliError(errors.New("Empty or no token found in store. It might have already been deleted."))
return base.CommandUserError
}
id, err := base.TokenIdFromToken(client.Token())
if err != nil {
c.PrintCliError(err)
return base.CommandUserError
}
authtokensClient := authtokens.NewClient(client)
_, err = authtokensClient.Delete(c.Context, id)
if apiErr := api.AsServerError(err); apiErr != nil && apiErr.Response().StatusCode() == http.StatusNotFound {
c.UI.Output("The token was not found on the Boundary controller; proceeding to delete from the local store.")
goto DeleteLocal
}
if err != nil {
if apiErr := api.AsServerError(err); apiErr != nil {
c.PrintApiError(apiErr, "Error from controller when performing delete on token")
return base.CommandApiError
}
c.PrintCliError(fmt.Errorf("Error trying to delete auth token: %w", err))
return base.CommandCliError
}
c.UI.Output("The token was successfully deleted within the Boundary controller.")
DeleteLocal:
keyringType, tokenName, err := c.DiscoverKeyringTokenInfo()
if err != nil {
c.PrintCliError(fmt.Errorf("Error fetching keyring information to delete local stored token: %w", err))
return base.CommandCliError
}
if keyringType == "none" ||
tokenName == "none" ||
keyringType == "" ||
tokenName == "" {
c.UI.Output("Keyring type set to none or empty; not deleting local stored token.")
return base.CommandSuccess
}
switch keyringType {
case "wincred", "keychain":
if err := zkeyring.Delete(base.StoredTokenName, tokenName); err != nil {
c.PrintCliError(fmt.Errorf("Error deleting auth token from %q keyring: %w", keyringType, err))
return base.CommandCliError
}
default:
krConfig := nkeyring.Config{
LibSecretCollectionName: "login",
PassPrefix: "HashiCorp_Boundary",
AllowedBackends: []nkeyring.BackendType{nkeyring.BackendType(keyringType)},
}
kr, err := nkeyring.Open(krConfig)
if err != nil {
c.PrintCliError(fmt.Errorf("Error opening %q keyring: %w", keyringType, err))
return base.CommandCliError
}
if err := kr.Remove(tokenName); err != nil {
c.PrintCliError(fmt.Errorf("Error deleting token from %q keyring: %w", keyringType, err))
return base.CommandCliError
}
}
c.UI.Output("The token was successfully removed from the local credential store.")
return base.CommandSuccess
}
-1
View File
@@ -155,7 +155,6 @@ var inputStructs = map[string][]*cmdInfo{
Pkg: "authtokens",
StdActions: []string{"read", "delete", "list"},
Container: "Scope",
HasId: true,
},
},
"groups": {