Skip to content

Commit

Permalink
Merge pull request #67 from quorumcontrol/fix/check-other-err-values
Browse files Browse the repository at this point in the history
Check for other errors from gokeychain.AddItem
  • Loading branch information
mtibben committed Apr 22, 2020
2 parents c2a5408 + e16c51d commit 329bccb
Showing 1 changed file with 37 additions and 25 deletions.
62 changes: 37 additions & 25 deletions keychain.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,36 @@ func (k *keychain) GetMetadata(key string) (Metadata, error) {
return md, nil
}

func (k *keychain) updateItem(kc gokeychain.Keychain, kcItem gokeychain.Item, account string) error {
queryItem := gokeychain.NewItem()
queryItem.SetSecClass(gokeychain.SecClassGenericPassword)
queryItem.SetService(k.service)
queryItem.SetAccount(account)
queryItem.SetMatchLimit(gokeychain.MatchLimitOne)
queryItem.SetReturnAttributes(true)

if k.path != "" {
queryItem.SetMatchSearchList(kc)
}

results, err := gokeychain.QueryItem(queryItem)
if err != nil {
return fmt.Errorf("Failed to query keychain: %v", err)
}
if len(results) == 0 {
return errors.New("no results")
}

// Don't call SetAccess() as this will cause multiple prompts on update, even when we are not updating the AccessList
kcItem.SetAccess(nil)

if err := gokeychain.UpdateItem(queryItem, kcItem); err != nil {
return fmt.Errorf("Failed to update item in keychain: %v", err)
}

return nil
}

func (k *keychain) Set(item Item) error {
var kc gokeychain.Keychain

Expand Down Expand Up @@ -162,33 +192,15 @@ func (k *keychain) Set(item Item) error {

debugf("Adding service=%q, label=%q, account=%q, trusted=%v to osx keychain %q", k.service, item.Label, item.Key, isTrusted, k.path)

if err := gokeychain.AddItem(kcItem); err == gokeychain.ErrorDuplicateItem {
debugf("Item already exists, updating")
queryItem := gokeychain.NewItem()
queryItem.SetSecClass(gokeychain.SecClassGenericPassword)
queryItem.SetService(k.service)
queryItem.SetAccount(item.Key)
queryItem.SetMatchLimit(gokeychain.MatchLimitOne)
queryItem.SetReturnAttributes(true)

if k.path != "" {
queryItem.SetMatchSearchList(kc)
}

results, err := gokeychain.QueryItem(queryItem)
if err != nil {
return fmt.Errorf("Failed to query keychain: %v", err)
}
if len(results) == 0 {
return errors.New("no results")
}
err := gokeychain.AddItem(kcItem)

// Don't call SetAccess() as this will cause multiple prompts on update, even when we are not updating the AccessList
kcItem.SetAccess(nil)
if err == gokeychain.ErrorDuplicateItem {
debugf("Item already exists, updating")
err = k.updateItem(kc, kcItem, item.Key)
}

if err := gokeychain.UpdateItem(queryItem, kcItem); err != nil {
return fmt.Errorf("Failed to update item in keychain: %v", err)
}
if err != nil {
return err
}

return nil
Expand Down

0 comments on commit 329bccb

Please sign in to comment.