Skip to content

feat(auth): Better multi-account gh account usage #13768 - #13781

Draft
platinummonkey wants to merge 3 commits into
cli:trunkfrom
platinummonkey:feature/context-scoped-accounts
Draft

platinummonkey wants to merge 3 commits into
cli:trunkfrom
platinummonkey:feature/context-scoped-accounts

Conversation

@platinummonkey

Copy link
Copy Markdown

FIXES #13768

Automatically select which authenticated account gh acts as based on local, API-free context (working directory and base-repo owner) instead of the single global active account. This addresses #13768: multiple accounts on the same host (e.g. an EMU + a personal github.com identity) cannot be disambiguated by host, and gh auth switch mutates global state, which is unsafe for concurrent agents.

New account_rules config key (gitdir + owner maps) and an explicit --account / GH_ACCOUNT override. Resolution wraps the HTTP client's token getter and never mutates persistent state.

Token precedence: env token (GH_TOKEN etc.) > --account/GH_ACCOUNT > rules >
globally active account. When no rules or override are configured, behavior is byte-identical to before.

gh auth status now shows which account resolves for the current context, and GH_DEBUG traces resolution, so automatic switching is observable rather than silent.

Automatically select which authenticated account gh acts as based on local,
API-free context (working directory and base-repo owner) instead of the single
global active account. This addresses cli#13768: multiple accounts on the
same host (e.g. an EMU + a personal github.com identity) cannot be disambiguated
by host, and `gh auth switch` mutates global state, which is unsafe for
concurrent agents.

New `account_rules` config key (gitdir + owner maps) and an explicit
`--account` / `GH_ACCOUNT` override. Resolution wraps the HTTP client's token
getter and never mutates persistent state.

Token precedence: env token (GH_TOKEN etc.) > --account/GH_ACCOUNT > rules >
globally active account. When no rules or override are configured, behavior is
byte-identical to before.

`gh auth status` now shows which account resolves for the current context, and
GH_DEBUG traces resolution, so automatic switching is observable rather than
silent.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@github-actions github-actions Bot added external pull request originating outside of the CLI core team needs-triage needs to be reviewed labels Jul 2, 2026
# Conflicts:
#	pkg/cmd/auth/status/status.go

@jamesng-minhkhoi jamesng-minhkhoi left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the draft — this is exactly the shape I'd want for #13768, and it resolves correctly for the concurrent-agents case (global state never touched). I checked out the branch locally and go test ./internal/accountrules/... ./pkg/cmd/factory/... ./internal/config/... passes on go1.27. Three findings, mostly edge cases:

1. A trailing @ account value silently disables the host check
parseAccount (internal/accountrules/accountrules.go:97-103) on "user@" yields Host: "", and the resolver skips its host check when acct.Host == "" (pkg/cmd/factory/account_resolver.go:81) — so a typo'd rule applies to every host, including enterprise hosts it was never meant for.

Suggested fix (fail loudly at parse/load):

func parseAccount(value, defaultHost string) Account {
	value = strings.TrimSpace(value)
	if i := strings.LastIndex(value, "@"); i >= 0 {
		host := value[i+1:]
		if host == "" {
			host = defaultHost
		}
		return Account{User: value[:i], Host: host}
	}
	return Account{User: value, Host: defaultHost}
}

(or reject empty hosts with an error at config parse so users see the typo).

2. Nondeterministic winner on equal-length gitdir prefixes
longestPrefixMatch (accountrules.go:108-125) iterates over a map; rules like ~/work and ~/work/ both clean to the same path, and on equal len(p) the winner depends on map order — resolution becomes random per process. Widening ties deterministically (e.g. iterate sort.Strings(prefixes), later key wins, or reject same-length distinct keys at load) would make repeated runs stable.

@jamesng-minhkhoi

Copy link
Copy Markdown

Continuing the review — two more items:

3. ctx.Owner can diverge from the documented "base repository owner"
The resolver takes remotes[0].RepoOwner() (pkg/cmd/factory/account_resolver.go:123, same in writeAccountResolution). remotes[0] is only the base because of the upstream > github > origin sort in pkg/cmd/factory/default.go. In fork setups where the parent remote is renamed (or the base is pinned via Remote.Resolved == "base" from github.base-style config), remotes[0] is the fork: the owner rule then matches the personal login instead of the org. ResolvedRemotes.BaseRepo() already honors the Resolved == "base" marker — reusing that logic (API-free parts of it) would keep the two notions consistent, or at minimum the Owner doc comment should note this nuance so users writing owner rules know exactly what matches.

4. GH_ACCOUNT in a shell profile is a wide blast radius
accountrules.Override() falls back to GH_ACCOUNT for every invocation, so an exported GH_ACCOUNT silently beats both rules and the active account — including gh auth login/auth refresh flows. Precedence is documented, but it might deserve a prominent warning in the gh auth status resolution block ("override came from the environment"), which would also make the "why does every repo act as X?" mystery obvious after-the-fact.

Nit: flagOverride is a package-level var set from PersistentPreRunE; fine in production (cobra runs once per process) but worth switching to dependency injection if the package ever gets run under t.Parallel.

Verified locally on go1.27.3/darwin-arm64: go test ./internal/accountrules/... ./pkg/cmd/factory/... ./internal/config/... — all green.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

external pull request originating outside of the CLI core team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Better multi-account gh account usage

3 participants