Skip to content

Commit 24ed307

Browse files
committed
feat(github): support GitHub Enterprise Server via GH_HOST / GITHUB_HOST
Adds an env-var-only host override so the `github_*` fetcher family (and `git_repo_name`'s github-remote detection) can target a GitHub Enterprise Server instance instead of github.com. Reads `GH_HOST` (matches the `gh` CLI), then `GITHUB_HOST` (mirrors splashboard's `GITHUB_TOKEN` / `GITHUB_USER` env-var family), defaulting to `github.com`. URL composition defaults to `api.<host>` for REST and `api.<host>/graphql` for GraphQL — same shape as github.com, matching what the API returns in `url` / `repository_url` payload fields so the strip-prefix code works identically for both. Resolved ONCE per process via OnceLock-cached statics so URL composition has zero per-request env reads. Older `<host>/api/v3` path-based GHE deployments can override the API URLs explicitly via `GH_API_URL` / `GITHUB_API_URL` and `GH_GRAPHQL_URL` / `GITHUB_GRAPHQL_URL` — the `GITHUB_*` names match the standard env vars GitHub Actions exposes (`GITHUB_API_URL`, `GITHUB_GRAPHQL_URL`): GH_HOST=ghe.example.com GH_API_URL=https://ghe.example.com/api/v3 GH_GRAPHQL_URL=https://ghe.example.com/api/graphql Avatar handling: github.com keeps the unchanged `<host>/<user>.png` public shortcut. GHE indirects through `/users/<login>` to get the server-signed `avatar_url` (the public shortcut redirects to `/login`). `slug_from_url` now accepts any non-empty SCP-style user — some GHE deployments configure a non-`git` SSH user (e.g. `<orgname>@<ghe-host>: owner/name`), so restricting to `git@` would drop those remotes. When `GH_HOST` is set, the configured host is tried first; github.com is a fallback so a user with a GHE-set shell can still parse github.com remotes. Safety::Safe is preserved. The override is env-var-only — a malicious `.splashboard.toml` cannot redirect a user's token to an attacker-chosen origin, only the user's shell can. This is the same property that the existing `GH_TOKEN` / `GITHUB_TOKEN` env vars already rely on. Minimal-diff approach: no public-API signature changes. For github.com (GH_HOST unset), every fetcher hits the same URLs as upstream with the same number of HTTP roundtrips and the same response handling — the only structural change is that `avatar.rs::download_avatar` gains an unreachable GHE branch in its compiled async state machine. Live-verified against a GitHub Enterprise instance (REST + GraphQL contributions calendar + notifications + avatar) and api.github.com (regression).
1 parent d2fe366 commit 24ed307

5 files changed

Lines changed: 133 additions & 30 deletions

File tree

‎src/fetcher/github/avatar.rs‎

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1-
//! `github_avatar` — download a github.com avatar PNG and expose it as `Body::Image`.
1+
//! `github_avatar` — download an avatar PNG and expose it as `Body::Image`.
22
//!
3-
//! Safety::Safe: the host is hardcoded (`github.com/<user>.png`), so config can't redirect
4-
//! traffic to a different origin. No auth is needed — the endpoint is public — so we do not
5-
//! attach `GH_TOKEN`, avoiding accidental token exposure along the redirect chain.
3+
//! - github.com: keeps the original public shortcut (`https://github.com/<user>.png`).
4+
//! - GHE: the public shortcut redirects to `/login`, so we indirect through
5+
//! `/users/<login>` to get the server-signed `avatar_url`.
6+
//!
7+
//! Safety::Safe: the host is resolved via `client::host()` (env-var-only), so a malicious
8+
//! `.splashboard.toml` cannot redirect traffic to an attacker-chosen origin.
69
//!
710
//! Caching: the PNG is written to `$SPLASHBOARD_HOME/cache/avatars/<user>-<size>.png`. The
811
//! fetcher framework already gates re-downloads via `refresh_interval`; we default to one day
@@ -19,10 +22,9 @@ use crate::payload::{Body, ImageData, Payload};
1922
use crate::render::Shape;
2023

2124
use super::super::{FetchContext, FetchError, Fetcher, Safety};
22-
use super::client::{http, resolve_authenticated_user};
25+
use super::client::{host, http, rest_get, resolve_authenticated_user, web_base};
2326
use super::common::cache_key;
2427

25-
const AVATAR_BASE: &str = "https://github.com";
2628
const DEFAULT_SIZE: u32 = 200;
2729

2830
const OPTION_SCHEMAS: &[OptionSchema] = &[
@@ -103,7 +105,11 @@ async fn download_avatar(user: &str, size: u32) -> Result<PathBuf, FetchError> {
103105
.ok_or_else(|| FetchError::Failed("$HOME not available for avatar cache".into()))?;
104106
std::fs::create_dir_all(&out_dir)
105107
.map_err(|e| FetchError::Failed(format!("create avatar cache dir: {e}")))?;
106-
let url = format!("{AVATAR_BASE}/{user}.png?size={size}");
108+
let url = if host().eq_ignore_ascii_case("github.com") {
109+
format!("{}/{user}.png?size={size}", web_base())
110+
} else {
111+
resolve_ghe_avatar_url(user, size).await?
112+
};
107113
let res = http()
108114
.get(&url)
109115
.send()
@@ -126,6 +132,19 @@ async fn download_avatar(user: &str, size: u32) -> Result<PathBuf, FetchError> {
126132
Ok(path)
127133
}
128134

135+
#[derive(Debug, Deserialize)]
136+
struct UserAvatar {
137+
avatar_url: String,
138+
}
139+
140+
/// GHE-only: resolve the server-signed avatar URL via `/users/<login>` and append a size
141+
/// query so the source is small enough for the media_image renderer.
142+
async fn resolve_ghe_avatar_url(user: &str, size: u32) -> Result<String, FetchError> {
143+
let me: UserAvatar = rest_get(&format!("/users/{user}")).await?;
144+
let sep = if me.avatar_url.contains('?') { '&' } else { '?' };
145+
Ok(format!("{}{sep}s={size}", me.avatar_url))
146+
}
147+
129148
fn image_extension(bytes: &[u8]) -> &'static str {
130149
if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
131150
"png"

‎src/fetcher/github/client.rs‎

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,64 @@ use serde::de::DeserializeOwned;
1515

1616
use crate::fetcher::FetchError;
1717

18-
const API_BASE: &str = "https://api.github.com";
19-
const GRAPHQL_URL: &str = "https://api.github.com/graphql";
18+
const DEFAULT_HOST: &str = "github.com";
2019
const USER_AGENT: &str = concat!("splashboard/", env!("CARGO_PKG_VERSION"));
20+
21+
fn read_env(var: &str) -> Option<String> {
22+
std::env::var(var)
23+
.ok()
24+
.map(|s| s.trim().to_owned())
25+
.filter(|s| !s.is_empty())
26+
}
27+
28+
pub(crate) fn host() -> &'static str {
29+
static HOST: OnceLock<String> = OnceLock::new();
30+
HOST.get_or_init(|| {
31+
read_env("GH_HOST")
32+
.or_else(|| read_env("GITHUB_HOST"))
33+
.unwrap_or_else(|| DEFAULT_HOST.into())
34+
// Normalize to lowercase so SCP-style remote parsing (`git@<host>:`) and
35+
// `eq_ignore_ascii_case` checks against `"github.com"` stay consistent when
36+
// the user types `GH_HOST=GitHub.com`. DNS is case-insensitive so this
37+
// doesn't affect URL composition.
38+
.to_ascii_lowercase()
39+
})
40+
.as_str()
41+
}
42+
43+
/// REST API base URL. Defaults to `https://api.<host>` (github.com and modern GHE).
44+
/// Override via `GH_API_URL` / `GITHUB_API_URL` for older `<host>/api/v3` GHE deployments
45+
/// (the env var name matches GitHub Actions' standard `GITHUB_API_URL`).
46+
pub(crate) fn api_base() -> &'static str {
47+
static API_BASE: OnceLock<String> = OnceLock::new();
48+
API_BASE.get_or_init(|| {
49+
read_env("GH_API_URL")
50+
.or_else(|| read_env("GITHUB_API_URL"))
51+
.unwrap_or_else(|| format!("https://api.{}", host()))
52+
})
53+
}
54+
55+
/// GraphQL endpoint. Defaults to `https://api.<host>/graphql`. Override via
56+
/// `GH_GRAPHQL_URL` / `GITHUB_GRAPHQL_URL` for older `<host>/api/graphql` GHE deployments
57+
/// (matches GitHub Actions' standard `GITHUB_GRAPHQL_URL` env var).
58+
pub(crate) fn graphql_url() -> &'static str {
59+
static GRAPHQL_URL: OnceLock<String> = OnceLock::new();
60+
GRAPHQL_URL.get_or_init(|| {
61+
read_env("GH_GRAPHQL_URL")
62+
.or_else(|| read_env("GITHUB_GRAPHQL_URL"))
63+
.unwrap_or_else(|| format!("https://api.{}/graphql", host()))
64+
})
65+
}
66+
67+
pub(crate) fn web_base() -> &'static str {
68+
static WEB_BASE: OnceLock<String> = OnceLock::new();
69+
WEB_BASE.get_or_init(|| format!("https://{}", host()))
70+
}
71+
72+
pub(crate) fn api_repos_prefix() -> &'static str {
73+
static API_REPOS_PREFIX: OnceLock<String> = OnceLock::new();
74+
API_REPOS_PREFIX.get_or_init(|| format!("{}/repos/", api_base()))
75+
}
2176
const ACCEPT: &str = "application/vnd.github+json";
2277
const API_VERSION: &str = "2022-11-28";
2378
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
@@ -76,7 +131,7 @@ pub(crate) fn clear_authenticated_user_cache() {
76131
/// are both actionable.
77132
pub async fn rest_get<T: DeserializeOwned>(path: &str) -> Result<T, FetchError> {
78133
let token = resolve_token()?;
79-
let url = format!("{API_BASE}{path}");
134+
let url = format!("{}{path}", api_base());
80135
let res = http()
81136
.get(&url)
82137
.bearer_auth(&token)
@@ -96,7 +151,7 @@ pub async fn graphql<T: DeserializeOwned>(
96151
let token = resolve_token()?;
97152
let body = serde_json::json!({ "query": query, "variables": variables });
98153
let res = http()
99-
.post(GRAPHQL_URL)
154+
.post(graphql_url())
100155
.bearer_auth(&token)
101156
.header("Accept", ACCEPT)
102157
.header("X-GitHub-Api-Version", API_VERSION)

‎src/fetcher/github/common.rs‎

Lines changed: 41 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -117,30 +117,58 @@ fn remote_slug(repo: &gix::Repository) -> Option<RepoSlug> {
117117
slug_from_url(&url.to_bstring().to_string())
118118
}
119119

120-
/// Parses the github URL shapes splashboard supports:
121-
/// - `[email protected]:owner/name(.git)?`
122-
/// - `https://github.com/owner/name(.git)?`
123-
/// - `https://<user>(:<token>)[email protected]/owner/name(.git)?`
124-
/// - `ssh://[email protected]/owner/name(.git)?`
120+
/// Parses the github URL shapes splashboard supports against the configured host:
121+
/// - `<user>@<host>:owner/name(.git)?` (SCP-style; `<user>` is conventionally `git` on
122+
/// github.com but can be anything — Microsoft GHE uses `microsoft@...`, for instance)
123+
/// - `https://<host>/owner/name(.git)?`
124+
/// - `https://<user>(:<token>)?@<host>/owner/name(.git)?`
125+
/// - `ssh://<user>@<host>/owner/name(.git)?`
125126
///
126-
/// Anything that isn't github.com returns `None` — splashboard's github fetchers target the
127-
/// github.com API and silently accepting a gitlab remote would be misleading.
127+
/// When `GH_HOST` is set, the configured host wins; we also try github.com as a fallback so
128+
/// a user with a GHE shell can still parse github.com remotes.
128129
pub fn slug_from_url(url: &str) -> Option<RepoSlug> {
129-
let rest = url
130-
.strip_prefix("[email protected]:")
131-
.or_else(|| strip_https_github_prefix(url))
132-
.or_else(|| url.strip_prefix("ssh://[email protected]/"))?;
130+
let host = super::client::host();
131+
parse_with_host(host, url).or_else(|| {
132+
if host.eq_ignore_ascii_case("github.com") {
133+
None
134+
} else {
135+
parse_with_host("github.com", url)
136+
}
137+
})
138+
}
139+
140+
fn parse_with_host(host: &str, url: &str) -> Option<RepoSlug> {
141+
let rest = strip_scp_prefix(host, url)
142+
.or_else(|| strip_https_prefix(host, url))
143+
.or_else(|| strip_ssh_prefix(host, url))?;
133144
let rest = rest.strip_suffix(".git").unwrap_or(rest);
134145
RepoSlug::parse(rest)
135146
}
136147

137-
fn strip_https_github_prefix(url: &str) -> Option<&str> {
148+
fn strip_scp_prefix<'a>(host: &str, url: &'a str) -> Option<&'a str> {
149+
let (userinfo, rest) = url.split_once('@')?;
150+
if userinfo.is_empty() || userinfo.contains([':', '/']) {
151+
return None;
152+
}
153+
rest.strip_prefix(&format!("{host}:")[..])
154+
}
155+
156+
fn strip_https_prefix<'a>(host: &str, url: &'a str) -> Option<&'a str> {
138157
let after_scheme = url.strip_prefix("https://")?;
139158
let after_userinfo = match after_scheme.split_once('@') {
140159
Some((userinfo, rest)) if !userinfo.contains('/') => rest,
141160
_ => after_scheme,
142161
};
143-
after_userinfo.strip_prefix("github.com/")
162+
after_userinfo.strip_prefix(&format!("{host}/")[..])
163+
}
164+
165+
fn strip_ssh_prefix<'a>(host: &str, url: &'a str) -> Option<&'a str> {
166+
let after_scheme = url.strip_prefix("ssh://")?;
167+
let (userinfo, rest) = after_scheme.split_once('@')?;
168+
if userinfo.is_empty() || userinfo.contains([':', '/']) {
169+
return None;
170+
}
171+
rest.strip_prefix(&format!("{host}/")[..])
144172
}
145173

146174
#[allow(dead_code)]

‎src/fetcher/github/items.rs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ use crate::fetcher::forge_items::{self, ForgeRow};
1212
use crate::payload::Body;
1313
use crate::render::Shape;
1414

15+
use super::client::api_repos_prefix;
1516
use super::common::{RepoSlug, parse_timestamp};
1617

1718
#[derive(Debug, Deserialize, Default)]
@@ -47,10 +48,10 @@ pub struct SearchResult {
4748
pub items: Vec<IssueItem>,
4849
}
4950

50-
/// Extracts `owner/name` from a GitHub API repository URL
51-
/// (`https://api.github.com/repos/owner/name`).
51+
/// Extracts `owner/name` from a GitHub API repository URL. The prefix tracks the configured
52+
/// host via `client::api_repos_prefix()`.
5253
pub fn repo_from_url(url: &str) -> Option<RepoSlug> {
53-
let rest = url.strip_prefix("https://api.github.com/repos/")?;
54+
let rest = url.strip_prefix(api_repos_prefix())?;
5455
RepoSlug::parse(rest)
5556
}
5657

‎src/fetcher/github/notifications.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use crate::render::Shape;
1313
use crate::samples;
1414

1515
use super::super::{FetchContext, FetchError, Fetcher, Safety};
16-
use super::client::rest_get;
16+
use super::client::{api_repos_prefix, rest_get, web_base};
1717
use super::common::{cache_key, parse_options, parse_timestamp, payload};
1818

1919
const SHAPES: &[Shape] = &[
@@ -222,8 +222,8 @@ fn short_repo(full: &str) -> String {
222222
/// or doesn't match the expected prefix; callers fall back to leaving the row unlinked.
223223
fn subject_html_url(n: &Notification) -> Option<String> {
224224
let url = n.subject.url.as_deref()?;
225-
let rest = url.strip_prefix("https://api.github.com/repos/")?;
226-
Some(format!("https://github.com/{rest}"))
225+
let rest = url.strip_prefix(api_repos_prefix())?;
226+
Some(format!("{}/{rest}", web_base()))
227227
}
228228

229229
#[cfg(test)]

0 commit comments

Comments
 (0)