Merge pull request #1313 from getagentseal/fix/copilot-host-rungs

fix(menubar): follow the credential's GitHub host on every quota rung
This commit is contained in:
Resham Joshi 2026-09-12 22:16:22 +03:00 • committed by GitHub
commit 4a316dacac
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 551 additions and 36 deletions

View file

@ -8,6 +8,7 @@
### Fixed
- **The menubar second row's quota line now names the provider the flame is warning about.** "Quota remaining" picked each provider's *headline* window — weekly, else monthly, and only then the busiest one — which is the Capacity Dock's billing horizon, not a warning: on a machine with Cursor's API window at 100% and Claude's 5-hour window at 18%, the row reported Monthly 9.5% and Weekly 5% and read as if nothing were near a limit. Each provider now contributes its worst window, per-model rows included, which is exactly what the menu-bar flame already tints by, so the two surfaces agree. A provider backing off after a failed fetch keeps its last-known window instead of dropping out, so the row no longer vanishes — resizing the status item — for the length of a retry, matching what the dock shows dimmed. The row is also capped at 24 characters, shortening a long provider name ("GitHub Copilot 12% left · 6d 3h") rather than letting the second line more than double the item's width, and the two-line title now carries a VoiceOver label that reads as one phrase instead of a string with a newline in it. With the setting off nothing changed: the snapshot that feeds the row is no longer even built on a refresh, and the title is the single-row composition it has always been. (#1310)
- **Every Copilot credential rung now follows its own GitHub host, not just the two read from files.** #1286 taught `hosts.json` and `apps.json` to carry the host their token came from, but the rungs that carried none — `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, and a token pasted into Settings — were still sent to `api.github.com`, so a user whose only Copilot credential is a GitHub Enterprise Cloud login got a 401 and a terminal failure with no way out. The environment rung now reads `GH_HOST` from the same environment as the token; the `gh` rung resolves the host from gh's own `hosts.yml` (`GH_CONFIG_DIR`, then `XDG_CONFIG_HOME/gh`, then `~/.config/gh`), picking it the way gh picks the host for `gh auth token` and without a second subprocess; and macOS Settings gains a GitHub host field next to the pasted token, defaulting to `github.com` and saved in the same Keychain record as the token so the two can never drift apart. Settings refuses a host no endpoint can be derived from at the field rather than storing it, the connection row no longer promises `api.github.com` before anything has been fetched, and every one of these new host sources is character-validated before a URL is built, so a crafted value such as `evil.com?.ghe.com` fails closed with no request instead of pointing the Authorization header at a host of its own choosing. `codeburn quota` is unchanged: it still reads only the editor-plugin files, which already carry their host. (#1306)
- **Copilot live quota works for GitHub Enterprise Cloud enterprises on a `*.ghe.com` host.** Both readers hardcoded `https://api.github.com/copilot_internal/user` and threw away the host their credential came from, so a data-residency enterprise signed in on `<tenant>.ghe.com` could only ever report `available: false` with "Temporarily unavailable". A discovered credential now carries its host — `hosts.json` is keyed by host and newer `apps.json` files key by `<host>:<app id>` — and the request follows it: `api.github.com` for `github.com` and for any rung that carries no host of its own (an app-name `apps.json` key, `COPILOT_GITHUB_TOKEN` / `GH_TOKEN` / `GITHUB_TOKEN`, `gh auth token`, a pasted token), and `https://api.<tenant>.ghe.com/copilot_internal/user` for an enterprise host. The token and the host always come from the same entry, with `github.com` preferred when several hosts are signed in and otherwise the first `.ghe.com` tenant in sorted order; a host neither rule can address, such as a self-hosted GitHub Enterprise Server install, fails with a message naming that host instead of sending the credential to dotcom, and unreachable-host and HTTP failures name the host that was tried. The macOS Settings connection row now says which host answered. (#1286)
## 0.9.24 - 2026-09-04

View file

@ -334,12 +334,21 @@ tolerates an absent, locked, or malformed source and falls through:
(`gho_`, `ghu_`, `ghp_`, `ghs_`, `github_pat_`). `ghr_` refresh tokens are
skipped: the usage endpoint rejects them.
3. `COPILOT_GITHUB_TOKEN`, then `GH_TOKEN`, then `GITHUB_TOKEN`, matching the
Copilot CLI's own order. A GUI-launched app rarely inherits these.
Copilot CLI's own order, with `GH_HOST` read from the same environment as
the host those tokens belong to. A GUI-launched app rarely inherits these.
4. `gh auth token`, which resolves keyring vs `~/.config/gh/hosts.yml` itself.
The binary is located the same way `CodeburnCLI` locates codeburn.
The binary is located the same way `CodeburnCLI` locates codeburn. The host
is read from that same `hosts.yml` (`GH_CONFIG_DIR`, then
`XDG_CONFIG_HOME/gh`, then `~/.config/gh`) rather than by spawning
`gh auth status`: gh writes the file for every login, keyring-backed ones
included, so a file read answers without a second subprocess. The pick
mirrors gh's own: `GH_HOST`, else the single configured host, else
`github.com`.
5. A token the user pastes into Settings, stored in CodeBurn's own
provider-scoped keychain item. A fine-grained personal access token with the
`Plan: Read-only` permission is enough.
provider-scoped keychain item together with the host typed beside it. A
fine-grained personal access token with the `Plan: Read-only` permission is
enough. Settings refuses a host no endpoint can be derived from at the
field, so an unaddressable host never reaches the keychain record.
The Copilot CLI's own keychain item (generic password service `copilot-cli`)
is deliberately **not** read. It is written by a Node keyring library, so
@ -353,8 +362,9 @@ Rung 4 costs a process spawn, so its answer is cached for `probeCacheTTL`
`hasCredential` is the cheap eligibility answer and never spawns: it
approximates rung 4 with an installed `gh` binary.
The Electron surface (`app/electron/quota/copilot.ts`) still implements only
rung 1.
Rungs 2 to 5 are the menubar's. The CLI (`src/quota/copilot.ts`) and the
Electron surface (`app/electron/quota/copilot.ts`) still implement only rung 1,
whose files already carry the host their token belongs to.
### GitHub Enterprise Cloud hosts (`*.ghe.com`)
@ -365,16 +375,25 @@ api.github.com. So a credential carries the host it was read from —
`hosts.json` is keyed by host, and newer `apps.json` files key by
`<host>:<app id>` — and the request goes to
`https://api.<tenant>.ghe.com/copilot_internal/user` for an enterprise host and
to `https://api.github.com/copilot_internal/user` for `github.com` or for any
rung that carries no host of its own (an app-name `apps.json` key, the
environment variables, `gh auth token`, a pasted token). The token and the host
to `https://api.github.com/copilot_internal/user` for `github.com` or for a
source that genuinely carries none (an app-name `apps.json` key, an
environment token with no `GH_HOST`, a gh login with no `hosts.yml` entry, a
pasted token saved before the host field existed). Every menubar rung can name
a tenant: the credential files are keyed by host, the environment rung reads
`GH_HOST`, the gh rung reads gh's `hosts.yml`, and the pasted rung saves the
host beside the token (#1306). The token and the host
always come from the same entry: with several hosts signed in, `github.com`
wins, otherwise the first `.ghe.com` tenant in sorted order, so the pick is
stable across reads; with exactly one, that host is used. A host neither rule
can address — a self-hosted GitHub Enterprise Server install, which CodeBurn
does not support — fails with a message naming that host rather than falling
back to api.github.com, because dotcom would reject the credential anyway and
must never receive it. Unreachable-host and HTTP failures name the host tried,
must never receive it. Every host source is untrusted text, `GH_HOST`, gh's
`hosts.yml` keys and the pasted host included: the normalized host is
character-validated before any URL is built, because a value like
`evil.com?.ghe.com` passes the `.ghe.com` suffix check but would build a URL
whose host is `api.evil.com` and hand it the Authorization header.
Unreachable-host and HTTP failures name the host tried,
so the symptom is no longer a bare "Temporarily unavailable". Settings shows
which host answered in the Copilot connection row. `CopilotHostEndpoint`
(macOS) and the exported helpers in `src/quota/copilot.ts` (CLI) hold the

View file

@ -5,6 +5,11 @@ import Foundation
struct CapacityDockProviderCredential: Codable, Equatable, Sendable {
var sourceMode: String = ProviderReferenceSourceMode.automatic.rawValue
var apiKey: String = ""
/// GitHub host a pasted Copilot token belongs to, empty for dotcom. It
/// lives in the same record as the token so the two can never drift apart:
/// the host a credential is sent to always comes from the entry that
/// carried the token (#1306). Unused by the other providers.
var host: String = ""
var resolvedSourceMode: ProviderReferenceSourceMode {
ProviderReferenceSourceMode(rawValue: sourceMode) ?? .automatic
@ -21,7 +26,8 @@ struct CapacityDockProviderCredential: Codable, Equatable, Sendable {
var sanitizedOverride: CapacityDockProviderCredentialOverride {
CapacityDockProviderCredentialOverride(
sourceMode: resolvedSourceMode,
apiKey: cleaned(apiKey)
apiKey: cleaned(apiKey),
host: cleaned(host)
)
}
@ -31,9 +37,32 @@ struct CapacityDockProviderCredential: Codable, Equatable, Sendable {
}
}
/// Decoding is hand-written, and lives in an extension so the memberwise
/// initializer survives. Swift's synthesized `init(from:)` ignores a property's
/// default value and throws on a missing key, so adding any field to this
/// record would make every credential saved before it unreadable — for every
/// provider, not just the one that gained the field.
extension CapacityDockProviderCredential {
private enum CodingKeys: String, CodingKey {
case sourceMode, apiKey, host
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.init(
sourceMode: try container.decodeIfPresent(String.self, forKey: .sourceMode)
?? ProviderReferenceSourceMode.automatic.rawValue,
apiKey: try container.decodeIfPresent(String.self, forKey: .apiKey) ?? "",
host: try container.decodeIfPresent(String.self, forKey: .host) ?? ""
)
}
}
struct CapacityDockProviderCredentialOverride: Equatable, Sendable {
var sourceMode: ProviderReferenceSourceMode
var apiKey: String?
/// Only Copilot populates this; see `CapacityDockProviderCredential.host`.
var host: String?
}
enum CapacityDockProviderCredentialStoreError: LocalizedError, Equatable {

View file

@ -16,13 +16,18 @@ import Foundation
/// GHES install today, and guessing that shape for any unrecognized host would
/// send credentials to a host we never verified serves this endpoint.
enum CopilotHostEndpoint {
/// Assumed for every credential source that carries no host of its own
/// (`apps.json` entries keyed by app name, the environment variables,
/// `gh auth token`, and a token pasted into Settings).
/// Assumed for every credential source that still carries no host of its
/// own: an `apps.json` entry keyed by app name, an environment token with
/// no `GH_HOST`, a `gh` login this machine has no `hosts.yml` for, and a
/// pasted token saved before the host field existed.
static let defaultHost = "github.com"
static let defaultAPIHost = "api.github.com"
/// GitHub Enterprise Cloud with data residency.
static let enterpriseCloudSuffix = ".ghe.com"
/// The variable `gh` and the Copilot CLI read to target a host other than
/// dotcom. It sits next to `GH_TOKEN` / `GITHUB_TOKEN` in the same
/// environment, so the environment rung reads both (#1306).
static let hostEnvironmentName = "GH_HOST"
private static let usagePath = "/copilot_internal/user"
/// Bare lowercased hostname. Tolerates surrounding whitespace, a scheme, a
@ -88,4 +93,73 @@ enum CopilotHostEndpoint {
let enterprise = normalized.filter { $0.hasSuffix(enterpriseCloudSuffix) }.sorted()
return enterprise.first ?? normalized.sorted().first
}
// MARK: - `gh` hosts (#1306)
/// The GitHub hosts `gh` is logged in to, read out of its `hosts.yml`.
///
/// That file is a mapping of host to per-host settings, so the hosts are
/// exactly its top-level keys — the only lines that start in column zero.
/// This is a key scan, not a YAML parser: nothing below the first level is
/// read, and every key is passed on untrusted, to be validated where the
/// URL is built.
static func hostsFromGhConfig(_ text: String) -> [String] {
var hosts: [String] = []
// Split on `isNewline`, not on "\n": Swift reads CRLF as a single
// grapheme, so splitting on "\n" leaves a CRLF file as one long line.
for rawLine in text.split(whereSeparator: \.isNewline) {
let line = String(rawLine)
// Anything indented belongs to a host's block; `#` is a comment and
// `-` starts a document marker or a sequence entry, neither of
// which is a host.
guard let first = line.first, !first.isWhitespace, first != "#", first != "-" else { continue }
guard let colon = line.firstIndex(of: ":") else { continue }
let key = line[..<colon]
.trimmingCharacters(in: .whitespaces)
.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
guard let host = normalize(key), !hosts.contains(host) else { continue }
hosts.append(host)
}
return hosts
}
/// The host a `gh auth token` answer belongs to, or nil for dotcom.
///
/// It mirrors how `gh` itself picks the host that command reads: `GH_HOST`
/// wins, otherwise the single host in `hosts.yml`, otherwise dotcom — which
/// is what `preferredHost(among:)` already computes. Where the two could
/// disagree (several tenants and no dotcom entry) `gh` resolves to dotcom,
/// finds no token there and yields nothing, so the rung never fires with a
/// host the token does not belong to.
///
/// Resolved from the config file rather than by spawning `gh auth status`:
/// `gh` writes `hosts.yml` for every login, keyring-backed ones included,
/// so a file read answers without a second subprocess.
static func ghHost(environmentHost: String?, hostsConfig: String?) -> String? {
if let host = normalize(environmentHost) { return host }
guard let hostsConfig else { return nil }
let hosts = hostsFromGhConfig(hostsConfig)
guard !hosts.isEmpty else { return nil }
return preferredHost(among: hosts.map { Optional($0) })
}
/// Where `gh` keeps `hosts.yml`: `GH_CONFIG_DIR` wins, then
/// `XDG_CONFIG_HOME/gh`, then `~/.config/gh`, matching `gh`'s own order.
static func ghHostsFileURL(
environment: [String: String] = ProcessInfo.processInfo.environment,
homeDirectory: String = NSHomeDirectory()
) -> URL {
func directory(_ name: String) -> String? {
guard let value = environment[name]?.trimmingCharacters(in: .whitespacesAndNewlines),
!value.isEmpty else { return nil }
return value
}
if let configDir = directory("GH_CONFIG_DIR") {
return URL(fileURLWithPath: configDir).appendingPathComponent("hosts.yml")
}
if let xdg = directory("XDG_CONFIG_HOME") {
return URL(fileURLWithPath: xdg).appendingPathComponent("gh/hosts.yml")
}
return URL(fileURLWithPath: homeDirectory).appendingPathComponent(".config/gh/hosts.yml")
}
}

View file

@ -78,6 +78,29 @@ enum CopilotQuotaPresentation {
explicitlyDisconnected ? disconnectedSettingsDetail : noCredentialsSettingsDetail
}
/// Settings connection-row detail before anything has been fetched. It
/// used to promise `api.github.com`, which is wrong for every enterprise
/// tenant now that each rung can carry its own host (#1306): with no
/// answer yet there is no host to name, so it names one only when a
/// previous snapshot already proved which host answers.
static func dormantSettingsDetail(apiHost: String?) -> String {
guard let apiHost, !apiHost.isEmpty, apiHost != CopilotHostEndpoint.defaultAPIHost else {
return "Tap Load Quota to fetch live usage from GitHub."
}
return "Tap Load Quota to fetch live usage from \(apiHost)."
}
/// Why a host typed next to the pasted token cannot be used, or nil when
/// it can. Rejecting it in Settings turns what would otherwise be a
/// terminal fetch failure into an answer at the field the user typed —
/// and keeps an unaddressable host out of the Keychain record entirely.
static func pastedHostRejection(_ raw: String) -> String? {
let host = CopilotHostEndpoint.normalize(raw) ?? CopilotHostEndpoint.defaultHost
guard CopilotHostEndpoint.apiHost(for: host) == nil else { return nil }
return "CodeBurn cannot read Copilot quota for \(host). "
+ "Use github.com or a GitHub Enterprise Cloud host (*.ghe.com)."
}
/// Snapshot age past which a loaded view stamps an "as of <time>" caption,
/// so a bar can never silently masquerade as current.
static let stalenessThreshold: TimeInterval = 10 * 60

View file

@ -30,9 +30,11 @@ struct CopilotUsage: Sendable, Equatable {
/// dotcom (#1286).
struct CopilotCredential: Sendable, Equatable {
let token: String
/// Host the token was read from, or nil when the source carries none
/// (`apps.json` keyed by app name, the environment variables, `gh`, or a
/// token pasted into Settings), which is dotcom.
/// Host the token was read from, or nil when the source carries none,
/// which is dotcom. Every rung can carry one: the credential files are
/// keyed by host, the environment rung reads `GH_HOST`, the `gh` rung
/// resolves the host of the login that answered, and a pasted token is
/// saved with the host typed next to it (#1306).
let host: String?
init(token: String, host: String? = nil) {
@ -139,12 +141,16 @@ enum CopilotSubscriptionService {
var appsURL: URL
/// The Copilot CLI's config directory (~/.copilot).
var copilotDirURL: URL
/// `gh`'s `hosts.yml`, read only to learn which host the `gh` rung's
/// token belongs to. Never a token source: `gh auth token` owns that.
var ghHostsURL: URL = CopilotHostEndpoint.ghHostsFileURL()
var environment: @Sendable (String) -> String?
/// `gh auth token`. Uncached: the service owns the caching so tests can
/// drive the probe directly.
var ghAuthToken: @Sendable () -> String?
/// Token the user pasted into CodeBurn's own Copilot settings.
var savedToken: @Sendable () -> String?
/// Token the user pasted into CodeBurn's own Copilot settings, with
/// the host saved beside it.
var savedCredential: @Sendable () -> CopilotCredential?
var now: @Sendable () -> Date
static let live = Deps(
@ -159,9 +165,10 @@ enum CopilotSubscriptionService {
hostsURL: URL(fileURLWithPath: NSHomeDirectory() + "/.config/github-copilot/hosts.json"),
appsURL: URL(fileURLWithPath: NSHomeDirectory() + "/.config/github-copilot/apps.json"),
copilotDirURL: URL(fileURLWithPath: NSHomeDirectory() + "/.copilot"),
ghHostsURL: CopilotHostEndpoint.ghHostsFileURL(),
environment: { ProcessInfo.processInfo.environment[$0] },
ghAuthToken: { runGhAuthToken() },
savedToken: { savedCopilotToken() },
savedCredential: { savedCopilotCredential() },
now: { Date() }
)
}
@ -191,9 +198,14 @@ enum CopilotSubscriptionService {
/// 1. legacy editor-plugin files: `hosts.json` then `apps.json` (both
/// carry the GitHub host the token belongs to)
/// 2. `~/.copilot/config.json` then `~/.copilot/settings.json`
/// 3. `COPILOT_GITHUB_TOKEN`, `GH_TOKEN`, `GITHUB_TOKEN`
/// 4. `gh auth token`
/// 5. a token pasted into CodeBurn's Copilot settings
/// 3. `COPILOT_GITHUB_TOKEN`, `GH_TOKEN`, `GITHUB_TOKEN`, with `GH_HOST`
/// as the host those tokens belong to
/// 4. `gh auth token`, with the host taken from `gh`'s own `hosts.yml`
/// 5. a token pasted into CodeBurn's Copilot settings, with the host saved
/// beside it
///
/// Every rung can therefore name a GitHub Enterprise Cloud tenant; only a
/// source that genuinely carries no host falls back to dotcom (#1306).
///
/// The Copilot CLI's own Keychain item (service `copilot-cli`) is
/// deliberately not read: it is written by a Node keyring library, so
@ -212,11 +224,26 @@ enum CopilotSubscriptionService {
let token = tokenFromCopilotCLIJSON(data) { return CopilotCredential(token: token) }
}
for name in environmentTokenNames {
if let token = nonEmpty(deps.environment(name)) { return CopilotCredential(token: token) }
if let token = nonEmpty(deps.environment(name)) {
return CopilotCredential(
token: token,
host: nonEmpty(deps.environment(CopilotHostEndpoint.hostEnvironmentName)))
}
}
if let token = cachedGhToken(deps: deps) { return CopilotCredential(token: token) }
guard let token = nonEmpty(deps.savedToken()) else { return nil }
return CopilotCredential(token: token)
if let token = cachedGhToken(deps: deps) {
return CopilotCredential(token: token, host: ghHost(deps: deps))
}
return deps.savedCredential()
}
/// Host of the login `gh auth token` answered for. Read from `hosts.yml`
/// rather than by spawning `gh auth status`: the `gh` rung already costs
/// one process, and `gh` writes that file for every login.
private static func ghHost(deps: Deps) -> String? {
let config = deps.readFile(deps.ghHostsURL).flatMap { String(data: $0, encoding: .utf8) }
return CopilotHostEndpoint.ghHost(
environmentHost: deps.environment(CopilotHostEndpoint.hostEnvironmentName),
hostsConfig: config)
}
/// Reads the `oauth_token` entries out of a credential map and picks one
@ -388,10 +415,14 @@ enum CopilotSubscriptionService {
}
/// Gated on the non-secret presence index so the common "nothing pasted"
/// case never touches Keychain at all.
private static func savedCopilotToken() -> String? {
/// case never touches Keychain at all. The host comes out of the same
/// record as the token, so the two cannot drift; a record saved before the
/// host field existed carries none and stays dotcom.
private static func savedCopilotCredential() -> CopilotCredential? {
guard CapacityDockProviderCredentialPresence.contains(providerID) else { return nil }
return (try? CapacityDockProviderCredentialStore.load(for: providerID))?.sanitizedOverride.apiKey
let override = (try? CapacityDockProviderCredentialStore.load(for: providerID))?.sanitizedOverride
guard let token = nonEmpty(override?.apiKey) else { return nil }
return CopilotCredential(token: token, host: override?.host)
}
// MARK: - Fetch

View file

@ -1400,7 +1400,7 @@ private struct CopilotSettingsTab: View {
}
CopilotTokenSection()
Section {
Text("Copilot live-quota tracking reads a GitHub token that is already on this Mac, read-only. Nothing is copied or stored. CodeBurn looks at the editor plugin files in `~/.config/github-copilot`, the Copilot CLI's `~/.copilot` files, the COPILOT_GITHUB_TOKEN, GH_TOKEN and GITHUB_TOKEN variables, `gh auth token`, and finally a token you paste below. Usage tracking works without any of this; only the live quota bars need a token. A credential found for a GitHub Enterprise Cloud host is queried on that tenant's own API (api.<tenant>.ghe.com) and never sent to api.github.com.")
Text("Copilot live-quota tracking reads a GitHub token that is already on this Mac, read-only. Nothing is copied or stored. CodeBurn looks at the editor plugin files in `~/.config/github-copilot`, the Copilot CLI's `~/.copilot` files, the COPILOT_GITHUB_TOKEN, GH_TOKEN and GITHUB_TOKEN variables, `gh auth token`, and finally a token you paste below. Usage tracking works without any of this; only the live quota bars need a token. Every one of those carries the GitHub host it belongs to — the plugin files are keyed by host, the variables are read with GH_HOST, the `gh` login with the host in gh's own hosts.yml, and a pasted token with the host you type beside it — and a credential for a GitHub Enterprise Cloud host is queried on that tenant's own API (api.<tenant>.ghe.com), never sent to api.github.com.")
.font(.system(size: 11))
.foregroundStyle(.secondary)
} header: {
@ -1417,12 +1417,18 @@ private struct CopilotSettingsTab: View {
private struct CopilotTokenSection: View {
@Environment(AppStore.self) private var store
@State private var token = ""
/// The GitHub host the pasted token belongs to. An enterprise PAT is not a
/// dotcom token, so this rung has to carry a host like the credential
/// files do (#1306).
@State private var host = CopilotHostEndpoint.defaultHost
@State private var isSaving = false
@State private var errorText: String?
var body: some View {
Section {
SecureField("GitHub token", text: $token)
TextField("GitHub host", text: $host, prompt: Text(CopilotHostEndpoint.defaultHost))
.disableAutocorrection(true)
HStack {
Button("Save & Connect") { save(token) }
.buttonStyle(.borderedProminent)
@ -1441,22 +1447,53 @@ private struct CopilotTokenSection: View {
} header: {
Text("Paste a token")
} footer: {
Text("Optional, and only needed when nothing else on this Mac is signed in. A fine-grained personal access token with the \"Plan: Read-only\" permission is enough. The token is saved in CodeBurn's own Keychain item and is used only to read your Copilot quota.")
Text("Optional, and only needed when nothing else on this Mac is signed in. A fine-grained personal access token with the \"Plan: Read-only\" permission is enough. Leave the host at github.com unless the token was minted on a GitHub Enterprise Cloud tenant, in which case enter that tenant's host (<tenant>.ghe.com) so the token is never sent to api.github.com. Both are saved in CodeBurn's own Keychain item and are used only to read your Copilot quota.")
.font(.system(size: 11))
}
.task { await loadSavedHost() }
}
/// Shows the host already on file so a saved tenant is not silently
/// replaced with github.com on the next save. Gated on the non-secret
/// presence index, so a Mac with nothing pasted never touches Keychain.
private func loadSavedHost() async {
guard CapacityDockProviderCredentialPresence.contains(CopilotSubscriptionService.providerID) else { return }
guard let saved = try? await CapacityDockProviderCredentialStore.loadAsync(
for: CopilotSubscriptionService.providerID
).sanitizedOverride.host else { return }
host = saved
}
private func save(_ raw: String) {
let trimmedToken = raw.trimmingCharacters(in: .whitespacesAndNewlines)
// Clearing drops the host with the token: a host on its own addresses
// nothing, and leaving it behind would pair it with the next token.
if trimmedToken.isEmpty {
persist(CapacityDockProviderCredential())
return
}
// Refuse a host no endpoint can be derived from at the field the user
// typed, instead of saving it and reporting a terminal fetch failure.
if let rejection = CopilotQuotaPresentation.pastedHostRejection(host) {
errorText = rejection
return
}
let resolvedHost = CopilotHostEndpoint.normalize(host) ?? CopilotHostEndpoint.defaultHost
persist(CapacityDockProviderCredential(apiKey: trimmedToken, host: resolvedHost))
}
private func persist(_ credential: CapacityDockProviderCredential) {
isSaving = true
errorText = nil
Task {
defer { isSaving = false }
do {
try await CapacityDockProviderCredentialStore.saveAsync(
CapacityDockProviderCredential(apiKey: raw),
credential,
for: CopilotSubscriptionService.providerID
)
token = ""
if credential.isEmpty { host = CopilotHostEndpoint.defaultHost }
CopilotSubscriptionService.resetProbeCache()
await store.connectCopilot()
} catch {
@ -1535,7 +1572,8 @@ private struct CopilotConnectionRow: View {
case .transientFailure: return store.copilotError ?? "GitHub rate-limited; auto-retrying."
case .bootstrapping: return "Looking for a GitHub token on this Mac."
case .loading: return "Background refresh in progress."
case .dormant: return "Tap Load Quota to fetch live usage from api.github.com."
case .dormant:
return CopilotQuotaPresentation.dormantSettingsDetail(apiHost: store.copilotUsage?.apiHost)
case .notBootstrapped:
return CopilotQuotaPresentation.settingsNotConnectedDetail(
explicitlyDisconnected: CopilotExplicitDisconnect.isSet(defaults: store.copilotQuotaRuntime.defaults)

View file

@ -95,4 +95,124 @@ final class CopilotHostEndpointTests: XCTestCase {
XCTAssertEqual(
CopilotHostEndpoint.preferredHost(among: ["github.acme-corp.net", "acme.ghe.com"]), "acme.ghe.com")
}
// MARK: - `gh` hosts.yml (#1306)
func testGhConfigHostsAreItsTopLevelKeys() {
let yaml = """
github.com:
users:
octocat:
oauth_token: gho_dotcom
git_protocol: https
user: octocat
acme.ghe.com:
user: octocat
"""
XCTAssertEqual(CopilotHostEndpoint.hostsFromGhConfig(yaml), ["github.com", "acme.ghe.com"])
}
/// Only column-zero keys are hosts. Anything indented belongs to a host's
/// block, and reading one as a host would send the token somewhere else.
func testGhConfigIgnoresNestedKeysCommentsAndBlankLines() {
let yaml = "# written by gh\r\n---\r\nacme.ghe.com:\r\n users:\r\n octocat:\r\n oauth_token: gho_x\r\n\r\n"
XCTAssertEqual(CopilotHostEndpoint.hostsFromGhConfig(yaml), ["acme.ghe.com"])
XCTAssertTrue(CopilotHostEndpoint.hostsFromGhConfig("").isEmpty)
XCTAssertTrue(CopilotHostEndpoint.hostsFromGhConfig(" oauth_token: gho_x\n").isEmpty)
// Quoted keys and duplicate spellings collapse to one host.
XCTAssertEqual(
CopilotHostEndpoint.hostsFromGhConfig("\"ACME.ghe.com\":\n user: a\nacme.ghe.com:\n user: b\n"),
["acme.ghe.com"])
}
/// Mirrors how gh itself resolves the host `gh auth token` reads: GH_HOST
/// first, then the single configured host, then dotcom.
func testGhHostPrefersGHHostThenTheConfiguredLogin() {
XCTAssertEqual(
CopilotHostEndpoint.ghHost(environmentHost: "acme.ghe.com", hostsConfig: "github.com:\n user: a\n"),
"acme.ghe.com")
XCTAssertEqual(
CopilotHostEndpoint.ghHost(environmentHost: nil, hostsConfig: "acme.ghe.com:\n user: a\n"),
"acme.ghe.com")
// Several logins: dotcom wins, which is also what gh falls back to.
XCTAssertEqual(
CopilotHostEndpoint.ghHost(
environmentHost: nil,
hostsConfig: "acme.ghe.com:\n user: a\ngithub.com:\n user: b\n"),
"github.com")
// No file and no variable is a hostless rung, i.e. dotcom.
XCTAssertNil(CopilotHostEndpoint.ghHost(environmentHost: nil, hostsConfig: nil))
XCTAssertNil(CopilotHostEndpoint.ghHost(environmentHost: " ", hostsConfig: "# empty\n"))
}
/// Each new host source is untrusted text of its own. A crafted value
/// still has to reach `apiHost` as-is and be refused there, rather than
/// being laundered into a host the suffix check would approve.
func testCraftedHostFromEachNewSourceIsRefusedBeforeAURLIsBuilt() {
let crafted = "evil.com?.ghe.com"
// gh's hosts.yml
XCTAssertEqual(CopilotHostEndpoint.hostsFromGhConfig("\(crafted):\n user: a\n"), [crafted])
XCTAssertEqual(
CopilotHostEndpoint.ghHost(environmentHost: nil, hostsConfig: "\(crafted):\n user: a\n"), crafted)
// GH_HOST
XCTAssertEqual(CopilotHostEndpoint.ghHost(environmentHost: crafted, hostsConfig: nil), crafted)
// …and every one of them fails closed at the single choke point.
XCTAssertNil(CopilotHostEndpoint.apiHost(for: crafted))
XCTAssertNil(CopilotHostEndpoint.usageURL(for: crafted))
// The pasted-token field refuses it before it is ever stored.
XCTAssertNotNil(CopilotQuotaPresentation.pastedHostRejection(crafted))
XCTAssertNotNil(CopilotQuotaPresentation.pastedHostRejection("github.acme-corp.net"))
XCTAssertNil(CopilotQuotaPresentation.pastedHostRejection("acme.ghe.com"))
XCTAssertNil(CopilotQuotaPresentation.pastedHostRejection(" "))
}
func testGhHostsFileURLFollowsGhsOwnConfigDirOrder() {
XCTAssertEqual(
CopilotHostEndpoint.ghHostsFileURL(
environment: ["GH_CONFIG_DIR": "/opt/ghcfg", "XDG_CONFIG_HOME": "/xdg"],
homeDirectory: "/Users/dev").path,
"/opt/ghcfg/hosts.yml")
XCTAssertEqual(
CopilotHostEndpoint.ghHostsFileURL(
environment: ["XDG_CONFIG_HOME": "/xdg"], homeDirectory: "/Users/dev").path,
"/xdg/gh/hosts.yml")
XCTAssertEqual(
CopilotHostEndpoint.ghHostsFileURL(environment: ["GH_CONFIG_DIR": " "], homeDirectory: "/Users/dev").path,
"/Users/dev/.config/gh/hosts.yml")
}
// MARK: - Pasted-token host storage
/// The host rides in the same Keychain record as the token, and that
/// record has to keep decoding for every credential saved before the field
/// existed — for every provider, not just Copilot.
func testCredentialRecordDecodesWithAndWithoutTheHostField() throws {
let legacy = #"{"sourceMode":"api","apiKey":"synthetic"}"#.data(using: .utf8)!
let decodedLegacy = try JSONDecoder().decode(CapacityDockProviderCredential.self, from: legacy)
XCTAssertEqual(decodedLegacy.apiKey, "synthetic")
XCTAssertEqual(decodedLegacy.host, "")
XCTAssertNil(decodedLegacy.sanitizedOverride.host)
let current = CapacityDockProviderCredential(apiKey: "synthetic", host: "acme.ghe.com")
let roundTripped = try JSONDecoder().decode(
CapacityDockProviderCredential.self, from: try JSONEncoder().encode(current))
XCTAssertEqual(roundTripped, current)
XCTAssertEqual(roundTripped.sanitizedOverride.host, "acme.ghe.com")
// A host with no token is not a credential.
XCTAssertTrue(CapacityDockProviderCredential(host: "acme.ghe.com").isEmpty)
}
// MARK: - Dormant Settings detail
func testDormantDetailNamesNoHostUntilOneHasAnswered() {
XCTAssertEqual(
CopilotQuotaPresentation.dormantSettingsDetail(apiHost: nil),
"Tap Load Quota to fetch live usage from GitHub.")
XCTAssertEqual(
CopilotQuotaPresentation.dormantSettingsDetail(apiHost: "api.github.com"),
"Tap Load Quota to fetch live usage from GitHub.")
XCTAssertEqual(
CopilotQuotaPresentation.dormantSettingsDetail(apiHost: "api.acme.ghe.com"),
"Tap Load Quota to fetch live usage from api.acme.ghe.com.")
}
}

View file

@ -48,7 +48,9 @@ final class CopilotQuotaTests: XCTestCase {
settings: String? = nil,
environment: [String: String] = [:],
ghToken: String? = nil,
ghHostsYAML: String? = nil,
savedToken: String? = nil,
savedHost: String? = nil,
recorder: RequestRecorder,
readFile: (@Sendable (URL) -> Data?)? = nil,
now: (@Sendable () -> Date)? = nil,
@ -66,18 +68,20 @@ final class CopilotQuotaTests: XCTestCase {
case "apps.json": return apps?.data(using: .utf8)
case "config.json": return config?.data(using: .utf8)
case "settings.json": return settings?.data(using: .utf8)
case "hosts.yml": return ghHostsYAML?.data(using: .utf8)
default: return nil
}
},
hostsURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.config/github-copilot/hosts.json"),
appsURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.config/github-copilot/apps.json"),
copilotDirURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.copilot"),
ghHostsURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.config/gh/hosts.yml"),
environment: { environment[$0] },
ghAuthToken: {
onGhProbe?()
return ghToken
},
savedToken: { savedToken },
savedCredential: { savedToken.map { CopilotCredential(token: $0, host: savedHost) } },
now: now ?? { Self.now }
)
}
@ -435,6 +439,181 @@ final class CopilotQuotaTests: XCTestCase {
XCTAssertEqual(authorization(recorder), "token github_pat_pasted")
}
// MARK: - Host-carrying rungs (#1306)
/// An enterprise PAT exported as GH_TOKEN went to api.github.com and came
/// back 401. GH_HOST sits next to it in the same environment and names the
/// host the token belongs to.
func testEnvironmentTokenFollowsGHHost() async throws {
let recorder = RequestRecorder()
let deps = Self.makeDeps(
hosts: nil,
environment: ["GH_TOKEN": "gho_env-tenant", "GH_HOST": "acme.ghe.com"],
recorder: recorder
) { request in
Self.okJson(request, Self.usageBody)
}
let usage = try await CopilotSubscriptionService.refresh(deps: deps)
XCTAssertEqual(
recorder.requests.first?.url?.absoluteString,
"https://api.acme.ghe.com/copilot_internal/user")
XCTAssertEqual(authorization(recorder), "token gho_env-tenant")
XCTAssertEqual(usage.apiHost, "api.acme.ghe.com")
}
func testEnvironmentTokenWithoutGHHostStaysOnDotcom() async throws {
let recorder = RequestRecorder()
let deps = Self.makeDeps(
hosts: nil,
environment: ["GITHUB_TOKEN": "gho_env-dotcom"],
recorder: recorder
) { request in
Self.okJson(request, Self.usageBody)
}
_ = try await CopilotSubscriptionService.refresh(deps: deps)
XCTAssertEqual(
recorder.requests.first?.url?.absoluteString,
"https://api.github.com/copilot_internal/user")
}
/// `gh auth login --hostname <tenant>.ghe.com` writes that host into gh's
/// own hosts.yml; the token `gh auth token` hands back belongs to it.
func testGhTokenFollowsTheHostInGhHostsYML() async throws {
let recorder = RequestRecorder()
let deps = Self.makeDeps(
hosts: nil,
ghToken: "gho_gh-tenant",
ghHostsYAML: """
acme.ghe.com:
users:
octocat:
oauth_token: gho_gh-tenant
git_protocol: https
""",
recorder: recorder
) { request in
Self.okJson(request, Self.usageBody)
}
let usage = try await CopilotSubscriptionService.refresh(deps: deps)
XCTAssertEqual(
recorder.requests.first?.url?.absoluteString,
"https://api.acme.ghe.com/copilot_internal/user")
XCTAssertEqual(authorization(recorder), "token gho_gh-tenant")
XCTAssertEqual(usage.apiHost, "api.acme.ghe.com")
}
/// gh resolves `gh auth token` against GH_HOST first, so we must too, and
/// a hosts.yml listing dotcom as well keeps the pick on dotcom.
func testGhHostEnvironmentOverridesTheConfigFileAndDotcomWinsAmongSeveral() async throws {
let overridden = RequestRecorder()
let deps = Self.makeDeps(
hosts: nil,
environment: ["GH_HOST": "acme.ghe.com"],
ghToken: "gho_gh-tenant",
ghHostsYAML: "github.com:\n user: octocat\n",
recorder: overridden
) { request in
Self.okJson(request, Self.usageBody)
}
_ = try await CopilotSubscriptionService.refresh(deps: deps)
XCTAssertEqual(
overridden.requests.first?.url?.absoluteString,
"https://api.acme.ghe.com/copilot_internal/user")
CopilotSubscriptionService.resetProbeCache()
let several = RequestRecorder()
let bothHosts = Self.makeDeps(
hosts: nil,
ghToken: "gho_gh-dotcom",
ghHostsYAML: "acme.ghe.com:\n user: octocat\ngithub.com:\n user: octocat\n",
recorder: several
) { request in
Self.okJson(request, Self.usageBody)
}
_ = try await CopilotSubscriptionService.refresh(deps: bothHosts)
XCTAssertEqual(
several.requests.first?.url?.absoluteString,
"https://api.github.com/copilot_internal/user")
}
func testGhTokenWithNoHostsFileStaysOnDotcom() async throws {
let recorder = RequestRecorder()
let deps = Self.makeDeps(hosts: nil, ghToken: "gho_gh-cli", recorder: recorder) { request in
Self.okJson(request, Self.usageBody)
}
_ = try await CopilotSubscriptionService.refresh(deps: deps)
XCTAssertEqual(
recorder.requests.first?.url?.absoluteString,
"https://api.github.com/copilot_internal/user")
}
func testPastedTokenFollowsTheHostSavedBesideIt() async throws {
let recorder = RequestRecorder()
let deps = Self.makeDeps(
hosts: nil,
savedToken: "github_pat_tenant",
savedHost: "acme.ghe.com",
recorder: recorder
) { request in
Self.okJson(request, Self.usageBody)
}
let usage = try await CopilotSubscriptionService.refresh(deps: deps)
XCTAssertEqual(
recorder.requests.first?.url?.absoluteString,
"https://api.acme.ghe.com/copilot_internal/user")
XCTAssertEqual(authorization(recorder), "token github_pat_tenant")
XCTAssertEqual(usage.apiHost, "api.acme.ghe.com")
}
/// GH_HOST, gh's hosts.yml and the pasted host are three new untrusted
/// inputs. A crafted value passes the `.ghe.com` suffix check but would
/// build a URL pointing at a host of its own choosing, so each one has to
/// fail closed with no request at all.
func testHostileHostFromAnyNewSourceFailsClosedWithoutARequest() async {
let crafted = "evil.com?.ghe.com"
let sources: [(String, CopilotSubscriptionService.Deps, RequestRecorder)] = {
var cases: [(String, CopilotSubscriptionService.Deps, RequestRecorder)] = []
let envRecorder = RequestRecorder()
cases.append(("GH_HOST", Self.makeDeps(
hosts: nil,
environment: ["GH_TOKEN": "gho_env", "GH_HOST": crafted],
recorder: envRecorder
) { request in Self.okJson(request, Self.usageBody) }, envRecorder))
let ghRecorder = RequestRecorder()
cases.append(("hosts.yml", Self.makeDeps(
hosts: nil,
ghToken: "gho_gh",
ghHostsYAML: "\(crafted):\n user: octocat\n",
recorder: ghRecorder
) { request in Self.okJson(request, Self.usageBody) }, ghRecorder))
let pastedRecorder = RequestRecorder()
cases.append(("pasted host", Self.makeDeps(
hosts: nil,
savedToken: "github_pat_pasted",
savedHost: crafted,
recorder: pastedRecorder
) { request in Self.okJson(request, Self.usageBody) }, pastedRecorder))
return cases
}()
for (source, deps, recorder) in sources {
CopilotSubscriptionService.resetProbeCache()
do {
_ = try await CopilotSubscriptionService.refresh(deps: deps)
XCTFail("\(source): expected unsupportedHost")
} catch let error as CopilotSubscriptionService.FetchError {
guard case let .unsupportedHost(host) = error else {
return XCTFail("\(source): expected unsupportedHost, got \(error)")
}
XCTAssertEqual(host, crafted)
XCTAssertTrue(error.isTerminal)
} catch {
XCTFail("\(source): unexpected error: \(error)")
}
XCTAssertTrue(recorder.requests.isEmpty, "\(source): built a request")
}
}
func testEveryRungAbsentStillReportsNoCredentialsWithoutFetching() async {
let recorder = RequestRecorder()
let deps = Self.makeDeps(
@ -674,9 +853,10 @@ final class CopilotQuotaTests: XCTestCase {
hostsURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.config/github-copilot/hosts.json"),
appsURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.config/github-copilot/apps.json"),
copilotDirURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.copilot"),
ghHostsURL: URL(fileURLWithPath: "/tmp/codeburn-tests/.config/gh/hosts.yml"),
environment: { _ in nil },
ghAuthToken: { nil },
savedToken: { nil },
savedCredential: { nil },
now: { Self.now }
)
do {