From 1b4c00f8d5fc7b59b0f29c3c2b5e0d093f231f68 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:02:06 +0300 Subject: [PATCH 1/4] fix(menubar): follow GH_HOST and gh's own host for the Copilot env and gh rungs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1286 taught the credential files to carry the GitHub host their token came from, but the environment and `gh auth token` rungs carried none, so they were always addressed to api.github.com. A user whose only Copilot credential is a GitHub Enterprise Cloud login — GH_TOKEN exported alongside GH_HOST, or `gh auth login --hostname .ghe.com` — got a 401 and a terminal failure with nothing to act on. The environment rung now reads GH_HOST out of the same environment as the token. The gh rung resolves the host from gh's own hosts.yml, found via GH_CONFIG_DIR, then XDG_CONFIG_HOME/gh, then ~/.config/gh, and picked the way gh picks the host for `gh auth token`: GH_HOST, else the single configured host, else dotcom. That is a file read rather than a second `gh auth status` spawn, because gh writes hosts.yml for every login, keyring-backed ones included. Both are new untrusted inputs, so they stay raw all the way to `apiHost(for:)`, where #1286's character validation refuses a crafted value such as `evil.com?.ghe.com` before any URL exists — that host passes the `.ghe.com` suffix check but builds a URL whose host is api.evil.com, which would then receive the Authorization header. --- .../Data/CopilotHostEndpoint.swift | 80 ++++++++++++++++++- .../Data/CopilotSubscriptionService.swift | 63 +++++++++++---- 2 files changed, 124 insertions(+), 19 deletions(-) diff --git a/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift b/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift index d116316f..0a35f0e9 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CopilotHostEndpoint.swift @@ -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[.. 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") + } } diff --git a/mac/Sources/CodeBurnMenubar/Data/CopilotSubscriptionService.swift b/mac/Sources/CodeBurnMenubar/Data/CopilotSubscriptionService.swift index 97c7fcc4..125bb800 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CopilotSubscriptionService.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CopilotSubscriptionService.swift @@ -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 From 53cd44daf20ec2e9cf64702a8d56cb5534167279 Mon Sep 17 00:00:00 2001 From: ozymandiashh <234437643+ozymandiashh@users.noreply.github.com> Date: Sat, 12 Sep 2026 21:02:19 +0300 Subject: [PATCH 2/4] fix(menubar): give the pasted Copilot token a GitHub host of its own MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The last rung of the chain is a token the user pastes into Settings, and an enterprise personal access token pasted there was still sent to api.github.com. Settings now takes the host beside the token, defaulting to github.com, and saves both in the same provider Keychain record so the host a request is addressed to always comes from the entry that carried the token. A host no endpoint can be derived from is refused at the field instead of being stored and reported later as a terminal fetch failure, and the crafted values #1286 guarded against are refused there too. Clearing the token clears the host with it, so a stale tenant can never be paired with the next token. The record's decoding moves into an extension and reads every key with decodeIfPresent: Swift's synthesized init(from:) ignores a property's default and throws on a missing key, so adding a field would otherwise make every credential saved before it unreadable — for every provider, not just Copilot. The dormant connection row no longer promises api.github.com before anything has been fetched; it names a host only once one has answered. Tests cover the three new host sources with a hostile value each, the rung wiring for all five rungs, the gh hosts.yml key scan, and that a record written before the host field still decodes. --- .../Data/CapacityDockProviderCredential.swift | 31 ++- .../Data/CopilotQuotaPresentation.swift | 23 +++ .../CodeBurnMenubar/Views/SettingsView.swift | 46 ++++- .../CopilotHostEndpointTests.swift | 120 ++++++++++++ .../CopilotQuotaTests.swift | 184 +++++++++++++++++- 5 files changed, 397 insertions(+), 7 deletions(-) diff --git a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift index 3e6015f2..8d74687c 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CapacityDockProviderCredential.swift @@ -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 { diff --git a/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift b/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift index 41cd30c8..d49331f5 100644 --- a/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift +++ b/mac/Sources/CodeBurnMenubar/Data/CopilotQuotaPresentation.swift @@ -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