Skip to content

Commit

Permalink
Merge pull request #395 from reubenmiller/fix-session-decrypt-error
Browse files Browse the repository at this point in the history
fix: fix handling of encrypted sessions
  • Loading branch information
reubenmiller authored Jun 15, 2024
2 parents 9d01d77 + f2f1b87 commit 418bb13
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 19 deletions.
24 changes: 17 additions & 7 deletions pkg/cmd/factory/c8yclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,15 @@ func CreateCumulocityClient(f *cmdutil.Factory, sessionFile, username, password
if tenant == "" {
tenant = cfg.GetTenant()
}

authErrors := make([]error, 0)
if password == "" {
pass, err := cfg.GetPassword()
if !disableEncryptionCheck && err != nil {
return nil, err
// Only log errors
if pass, err := cfg.GetPassword(); err == nil {
password = pass
} else {
authErrors = append(authErrors, err)
}
password = pass
}

c8yURL := cfg.GetHost()
Expand Down Expand Up @@ -209,9 +212,16 @@ func CreateCumulocityClient(f *cmdutil.Factory, sessionFile, username, password
})

// load authentication
if err := loadAuthentication(cfg, client); !disableEncryptionCheck && err != nil {
log.Warnf("Could not load authentication. %s", err)
return nil, err
if err := loadAuthentication(cfg, client); err != nil {
// Only log errors
authErrors = append(authErrors, err)
} else {
// Clear any existing auth errors
authErrors = nil
}

if !disableEncryptionCheck && len(authErrors) > 0 {
log.Warnf("Could not load authentication. error=%v", authErrors[0])
}

timeout := cfg.RequestTimeout()
Expand Down
19 changes: 14 additions & 5 deletions pkg/cmd/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,15 @@ func NewCmdRoot(f *cmdutil.Factory, version, buildDate string) *CmdRoot {
// Command "listAssets" is deprecated,
fmt.Fprintf(f.IOStreams.ErrOut, "Command \"%s\" is deprecated, %s\n", cmd.CommandPath(), notice)
}
return ccmd.checkSessionExists(cmd, args)
cmdErr := ccmd.checkSessionExists(cmd, args)

if cmdErr != nil {
logg, logErr := f.Logger()
if logg != nil && logErr == nil {
logg.Warnf("Check existing session failed. %s", cmdErr)
}
}
return cmdErr
},
}

Expand Down Expand Up @@ -500,7 +508,6 @@ func ConvertToCobraCommands(f *cmdutil.Factory, cmd *cobra.Command, extensions [
// Enable flag parsing when using tab completion, otherwise disable it
// as it affects passing the arguments to the extension binary
disableFlagParsing := !isTabCompletionCommand()
_ = disableFlagParsing

log, err := f.Logger()
if err != nil {
Expand Down Expand Up @@ -773,9 +780,11 @@ func (c *CmdRoot) Configure(disableEncryptionCheck, forceVerbose, forceDebug boo
return c.client, nil
}
client, err := factory.CreateCumulocityClient(c.Factory, c.SessionFile, c.SessionUsername, c.SessionPassword, disableEncryptionCheck)()
if c.SessionUsername != "" || c.SessionPassword != "" {
client.AuthorizationMethod = c8y.AuthMethodBasic
c.log.Debug("Forcing basic authentication as user provided username/password")
if client != nil {
if c.SessionUsername != "" || c.SessionPassword != "" {
client.AuthorizationMethod = c8y.AuthMethodBasic
c.log.Debug("Forcing basic authentication as user provided username/password")
}
}

if c.log != nil {
Expand Down
10 changes: 7 additions & 3 deletions pkg/cmd/sessions/set/set.manual.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ func NewCmdSet(f *cmdutil.Factory) *CmdSet {
completion.WithValidateSet("shell", "auto", "bash", "zsh", "fish", "powershell"),
completion.WithValidateSet("loginType", c8y.AuthMethodOAuth2Internal, c8y.AuthMethodBasic),
)
// Disable the encryption check, as the login handler will take care
// of checking the encryption
cmdutil.DisableEncryptionCheck(cmd)
ccmd.SubCommand = subcommand.NewSubCommand(cmd)

return ccmd
Expand Down Expand Up @@ -131,7 +134,7 @@ func (n *CmdSet) RunE(cmd *cobra.Command, args []string) error {
if n.LoginType == c8y.AuthMethodBasic {
cfg.Logger.Infof("Clearing any existing token when using %s auth", c8y.AuthMethodBasic)
os.Unsetenv("C8Y_TOKEN")
if cfg.MustGetToken() != "" {
if cfg.MustGetToken(false) != "" {
cfg.SetToken("")
n.onSave(nil)
}
Expand All @@ -157,7 +160,7 @@ func (n *CmdSet) RunE(cmd *cobra.Command, args []string) error {
client.SetToken("")
} else {
// Check if token is valid for the minimum period
if tok := cfg.MustGetToken(); tok != "" {
if tok := cfg.MustGetToken(true); tok != "" {
shouldBeValidFor := cfg.TokenValidFor()
expiresSoon, expiresAt := ShouldRenewToken(tok, shouldBeValidFor)

Expand All @@ -170,6 +173,7 @@ func (n *CmdSet) RunE(cmd *cobra.Command, args []string) error {
}
} else {
log.Infof("Ignoring invalid token")
client.SetToken("")
}
}
}
Expand Down Expand Up @@ -258,7 +262,7 @@ func hasChanged(client *c8y.Client, cfg *config.Config) bool {
return true
}

if client.Token != "" && client.Token != cfg.MustGetToken() && cfg.StoreToken() {
if client.Token != "" && client.Token != cfg.MustGetToken(false) && cfg.StoreToken() {
return true
}

Expand Down
10 changes: 6 additions & 4 deletions pkg/config/cliConfiguration.go
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,7 @@ func (c Config) GetEnvironmentVariables(client *c8y.Client, setPassword bool) ma
c8yVersion := c.GetCumulocityVersion()
username := c.GetUsername()
password := c.MustGetPassword()
token := c.MustGetToken()
token := c.MustGetToken(false)
authHeaderValue := ""
authHeader := ""

Expand Down Expand Up @@ -949,10 +949,12 @@ func (c *Config) MustGetPassword() string {
}

// MustGetToken returns the decrypted token if there are no encryption errors, otherwise it will return an encrypted value
func (c *Config) MustGetToken() string {
func (c *Config) MustGetToken(silent bool) string {
decryptedValue, err := c.GetToken()
if err != nil {
c.Logger.Warningf("Could not decrypt token. %s", err)
if !silent {
c.Logger.Warningf("Could not decrypt token. %s", err)
}
}
return decryptedValue
}
Expand Down Expand Up @@ -1039,7 +1041,7 @@ func (c *Config) bindEnv(name string, defaultValue interface{}) error {
// DecryptSession decrypts a session (as long as the encryption passphrase has already been provided)
func (c *Config) DecryptSession() error {
c.SetPassword(c.MustGetPassword())
c.SetToken(c.MustGetToken())
c.SetToken(c.MustGetToken(false))
return c.WritePersistentConfig()
}

Expand Down

0 comments on commit 418bb13

Please sign in to comment.