setActiveCredential clears every host level active credential representation and copies the user's stored credential into the active slot, preserving its storage form. It neither sets the active user nor writes the config, so it can also be used to restore state after a failed switch. It reports whe
(hostname, user string)
| 659 | // config, so it can also be used to restore state after a failed switch. It reports whether a credential was found |
| 660 | // for the user. |
| 661 | func (c *AuthConfig) setActiveCredential(hostname, user string) (bool, error) { |
| 662 | // Idempotently clear the non-expiring active representations so that no stale token can outrank the credential we |
| 663 | // are about to activate. Refreshable credentials have no host-level active copy, so there is nothing to clear for |
| 664 | // them; they are resolved per-user through the active user key. |
| 665 | _ = keyring.Delete(keyringServiceName(hostname), "") |
| 666 | _ = c.cfg.Remove([]string{hostsKey, hostname, oauthTokenKey}) |
| 667 | |
| 668 | // The non-expiring keyring token is checked first so the common non-refreshable user does not pay an extra |
| 669 | // refreshable-slot keyring miss on every lookup. On a hit, copy it into the host active slot. This keyring-first |
| 670 | // order is kept identical to TokenForUser so activation and resolution never disagree about which credential is |
| 671 | // current, even in the mixed state that write paths keep unreachable. |
| 672 | if token, err := keyring.Get(keyringServiceName(hostname), user); err == nil { |
| 673 | if err = keyring.Set(keyringServiceName(hostname), "", token); err != nil { |
| 674 | return false, fmt.Errorf("failed to move active token in keyring: %v", err) |
| 675 | } |
| 676 | return true, nil |
| 677 | } |
| 678 | |
| 679 | // Then the managed refreshable credential. It lives only in the per-user slot and is surfaced as active through the |
| 680 | // active user key, so confirming it exists is all that activation needs. |
| 681 | if _, _, err := c.refreshableForUser(hostname, user); err == nil { |
| 682 | return true, nil |
| 683 | } else if !errors.Is(err, errRefreshableNotFound) { |
| 684 | return false, err |
| 685 | } |
| 686 | |
| 687 | // Otherwise fall back to a non-expiring credential in the insecure config. |
| 688 | if token, err := c.cfg.Get([]string{hostsKey, hostname, usersKey, user, oauthTokenKey}); err == nil { |
| 689 | c.cfg.Set([]string{hostsKey, hostname, oauthTokenKey}, token) |
| 690 | return true, nil |
| 691 | } |
| 692 | |
| 693 | return false, nil |
| 694 | } |
| 695 | |
| 696 | func (c *AuthConfig) UsersForHost(hostname string) []string { |
| 697 | users, err := c.cfg.Keys([]string{hostsKey, hostname, usersKey}) |