splashboard 2.10.2

A customizable terminal splash screen with plugin-based data sources
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Shared HTTP client + auth for the `github_*` fetcher family. Reads `GH_TOKEN` or
//! `GITHUB_TOKEN` (in that order) once per process. The host defaults to `github.com` but
//! can be redirected to a GitHub Enterprise Server via `GH_HOST` / `GITHUB_HOST` (and
//! optionally `GH_API_URL` / `GH_GRAPHQL_URL` for older `<host>/api/v3` deployments). Host
//! selection is env-var-only — a `.splashboard.toml` cannot redirect traffic to an
//! attacker-chosen origin, so the token cannot leak by design.
//!
//! The rest helpers accept a path like `"/user"` or `"/repos/foo/bar"`; the base URL is joined
//! here so fetchers stay free of URL plumbing. GraphQL goes through a single POST helper.

use std::sync::{Mutex, OnceLock};
use std::time::Duration;

use reqwest::{Client, StatusCode};
use serde::Deserialize;
use serde::de::DeserializeOwned;

use crate::fetcher::FetchError;

const DEFAULT_HOST: &str = "github.com";
const USER_AGENT: &str = concat!("splashboard/", env!("CARGO_PKG_VERSION"));

fn read_env(var: &str) -> Option<String> {
    std::env::var(var).ok().and_then(|raw| normalize_env(&raw))
}

/// Trim whitespace and a trailing `/` so callers can rely on host / URL values being free of
/// surface-level user typos like `GH_API_URL=https://ghe.example.com/api/v3/`. Returns `None`
/// when the value collapses to empty after normalization so the caller can fall back to the
/// default.
fn normalize_env(raw: &str) -> Option<String> {
    let v = raw.trim().trim_end_matches('/');
    (!v.is_empty()).then(|| v.to_owned())
}

pub(crate) fn host() -> &'static str {
    static HOST: OnceLock<String> = OnceLock::new();
    HOST.get_or_init(|| {
        read_env("GH_HOST")
            .or_else(|| read_env("GITHUB_HOST"))
            .unwrap_or_else(|| DEFAULT_HOST.into())
            // Normalize to lowercase so SCP-style remote parsing (`git@<host>:`) and
            // `eq_ignore_ascii_case` checks against `"github.com"` stay consistent when
            // the user types `GH_HOST=GitHub.com`. DNS is case-insensitive so this
            // doesn't affect URL composition.
            .to_ascii_lowercase()
    })
    .as_str()
}

/// REST API base URL. Defaults to `https://api.<host>` (github.com and modern GHE).
/// Override via `GH_API_URL` / `GITHUB_API_URL` for older `<host>/api/v3` GHE deployments
/// (the env var name matches GitHub Actions' standard `GITHUB_API_URL`).
pub(crate) fn api_base() -> &'static str {
    static API_BASE: OnceLock<String> = OnceLock::new();
    API_BASE.get_or_init(|| {
        read_env("GH_API_URL")
            .or_else(|| read_env("GITHUB_API_URL"))
            .unwrap_or_else(|| format!("https://api.{}", host()))
    })
}

/// GraphQL endpoint. Defaults to `https://api.<host>/graphql`. Override via
/// `GH_GRAPHQL_URL` / `GITHUB_GRAPHQL_URL` for older `<host>/api/graphql` GHE deployments
/// (matches GitHub Actions' standard `GITHUB_GRAPHQL_URL` env var).
pub(crate) fn graphql_url() -> &'static str {
    static GRAPHQL_URL: OnceLock<String> = OnceLock::new();
    GRAPHQL_URL.get_or_init(|| {
        read_env("GH_GRAPHQL_URL")
            .or_else(|| read_env("GITHUB_GRAPHQL_URL"))
            .unwrap_or_else(|| format!("https://api.{}/graphql", host()))
    })
}

pub(crate) fn web_base() -> &'static str {
    static WEB_BASE: OnceLock<String> = OnceLock::new();
    WEB_BASE.get_or_init(|| format!("https://{}", host()))
}

pub(crate) fn api_repos_prefix() -> &'static str {
    static API_REPOS_PREFIX: OnceLock<String> = OnceLock::new();
    API_REPOS_PREFIX.get_or_init(|| format!("{}/repos/", api_base()))
}

const ACCEPT: &str = "application/vnd.github+json";
const API_VERSION: &str = "2022-11-28";
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
static AUTHENTICATED_USER_CACHE: OnceLock<Mutex<Option<String>>> = OnceLock::new();

pub fn http() -> &'static Client {
    static CLIENT: OnceLock<Client> = OnceLock::new();
    CLIENT.get_or_init(|| {
        Client::builder()
            .user_agent(USER_AGENT)
            .timeout(REQUEST_TIMEOUT)
            .gzip(true)
            .build()
            .expect("reqwest client should build with default config")
    })
}

pub fn resolve_token() -> Result<String, FetchError> {
    std::env::var("GH_TOKEN")
        .or_else(|_| std::env::var("GITHUB_TOKEN"))
        .map_err(|_| FetchError::Failed("GH_TOKEN / GITHUB_TOKEN not set".into()))
}

/// Login of the token-authenticated user. Resolved lazily via `GET /user` and memoised for the
/// rest of the process so we never spend more than one roundtrip on a value that never changes
/// within a session. Lets `github_avatar` / `github_user` work with zero config when a token is
/// already set.
pub async fn resolve_authenticated_user() -> Result<String, FetchError> {
    let slot = AUTHENTICATED_USER_CACHE.get_or_init(|| Mutex::new(None));
    if let Some(cached) = slot.lock().ok().and_then(|g| g.clone()) {
        return Ok(cached);
    }
    #[derive(Deserialize)]
    struct Me {
        login: String,
    }
    let me: Me = rest_get("/user").await?;
    if let Ok(mut g) = slot.lock() {
        *g = Some(me.login.clone());
    }
    Ok(me.login)
}

#[cfg(test)]
pub(crate) fn clear_authenticated_user_cache() {
    if let Ok(mut guard) = AUTHENTICATED_USER_CACHE
        .get_or_init(|| Mutex::new(None))
        .lock()
    {
        *guard = None;
    }
}

/// REST GET → deserialize JSON. Non-2xx responses surface the GitHub-reported `message` when
/// present (`{"message":"Not Found"}`) so the runtime's error placeholder and the log line
/// are both actionable.
pub async fn rest_get<T: DeserializeOwned>(path: &str) -> Result<T, FetchError> {
    let token = resolve_token()?;
    let url = format!("{}{path}", api_base());
    let res = http()
        .get(&url)
        .bearer_auth(&token)
        .header("Accept", ACCEPT)
        .header("X-GitHub-Api-Version", API_VERSION)
        .send()
        .await
        .map_err(|e| FetchError::Failed(format!("github request failed: {e}")))?;
    parse_json(res).await
}

/// GraphQL POST. GitHub returns 200 even on query errors, so we also look at the `errors` array.
pub async fn graphql<T: DeserializeOwned>(
    query: &str,
    variables: serde_json::Value,
) -> Result<T, FetchError> {
    let token = resolve_token()?;
    let body = serde_json::json!({ "query": query, "variables": variables });
    let res = http()
        .post(graphql_url())
        .bearer_auth(&token)
        .header("Accept", ACCEPT)
        .header("X-GitHub-Api-Version", API_VERSION)
        .json(&body)
        .send()
        .await
        .map_err(|e| FetchError::Failed(format!("github graphql request failed: {e}")))?;
    let wrapper: GqlResponse<T> = parse_json(res).await?;
    if let Some(errs) = wrapper.errors.filter(|e| !e.is_empty()) {
        let joined = errs
            .iter()
            .map(|e| e.message.as_str())
            .collect::<Vec<_>>()
            .join("; ");
        return Err(FetchError::Failed(format!("github graphql: {joined}")));
    }
    wrapper
        .data
        .ok_or_else(|| FetchError::Failed("github graphql: empty data".into()))
}

async fn parse_json<T: DeserializeOwned>(res: reqwest::Response) -> Result<T, FetchError> {
    let status = res.status();
    let bytes = res
        .bytes()
        .await
        .map_err(|e| FetchError::Failed(format!("github response body: {e}")))?;
    if !status.is_success() {
        return Err(FetchError::Failed(error_message(status, &bytes)));
    }
    serde_json::from_slice(&bytes)
        .map_err(|e| FetchError::Failed(format!("github json parse: {e}")))
}

fn error_message(status: StatusCode, body: &[u8]) -> String {
    #[derive(Deserialize)]
    struct ApiError {
        message: Option<String>,
    }
    let reported = serde_json::from_slice::<ApiError>(body)
        .ok()
        .and_then(|e| e.message);
    match reported {
        Some(m) => format!("github {status}: {m}"),
        None => format!("github {status}"),
    }
}

#[derive(Debug, Deserialize)]
struct GqlResponse<T> {
    data: Option<T>,
    #[serde(default)]
    errors: Option<Vec<GqlError>>,
}

#[derive(Debug, Deserialize)]
struct GqlError {
    message: String,
}

#[cfg(test)]
mod tests {
    use std::future::Future;
    use std::io::{Read, Write};
    use std::net::TcpListener;
    use std::thread;

    use serde::Deserialize;

    use super::*;

    #[derive(Debug, Deserialize)]
    struct TestPayload {
        login: String,
    }

    /// Serialises env mutation with other env-touching tests. `GH_TOKEN` / `GITHUB_TOKEN` are
    /// read unconditionally inside `resolve_token`, so two parallel tests racing on the same
    /// vars would otherwise flap.
    struct EnvGuard {
        _lock: std::sync::MutexGuard<'static, ()>,
        restore: Vec<(&'static str, Option<String>)>,
    }

    impl EnvGuard {
        fn set(pairs: &[(&'static str, Option<&str>)]) -> Self {
            let lock = crate::paths::TEST_ENV_LOCK
                .lock()
                .unwrap_or_else(|e| e.into_inner());
            let restore = pairs
                .iter()
                .map(|(k, v)| {
                    let prev = std::env::var(k).ok();
                    match v {
                        Some(value) => unsafe { std::env::set_var(k, value) },
                        None => unsafe { std::env::remove_var(k) },
                    }
                    (*k, prev)
                })
                .collect();
            Self {
                _lock: lock,
                restore,
            }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for (k, v) in &self.restore {
                match v {
                    Some(value) => unsafe { std::env::set_var(k, value) },
                    None => unsafe { std::env::remove_var(k) },
                }
            }
        }
    }

    #[test]
    fn normalize_env_strips_trailing_slash() {
        assert_eq!(
            normalize_env("https://ghe.example.com/api/v3/").as_deref(),
            Some("https://ghe.example.com/api/v3")
        );
    }

    #[test]
    fn normalize_env_handles_whitespace_and_empty() {
        assert_eq!(
            normalize_env("  github.com  ").as_deref(),
            Some("github.com")
        );
        assert_eq!(normalize_env("   ").as_deref(), None);
        assert_eq!(normalize_env("").as_deref(), None);
        assert_eq!(normalize_env("/").as_deref(), None);
    }

    #[test]
    fn normalize_env_preserves_clean_values() {
        assert_eq!(
            normalize_env("https://ghe.example.com/api/v3").as_deref(),
            Some("https://ghe.example.com/api/v3")
        );
        assert_eq!(normalize_env("github.com").as_deref(), Some("github.com"));
    }

    #[test]
    fn resolve_token_prefers_gh_token() {
        let _g = EnvGuard::set(&[
            ("GH_TOKEN", Some("from-gh")),
            ("GITHUB_TOKEN", Some("from-github")),
        ]);
        assert_eq!(resolve_token().unwrap(), "from-gh");
    }

    #[test]
    fn resolve_token_falls_back_to_github_token() {
        let _g = EnvGuard::set(&[("GH_TOKEN", None), ("GITHUB_TOKEN", Some("fallback"))]);
        assert_eq!(resolve_token().unwrap(), "fallback");
    }

    #[test]
    fn resolve_token_fails_when_both_missing() {
        let _g = EnvGuard::set(&[("GH_TOKEN", None), ("GITHUB_TOKEN", None)]);
        assert!(resolve_token().is_err());
    }

    #[test]
    fn http_reuses_the_same_client() {
        assert!(std::ptr::eq(http(), http()));
    }

    #[test]
    fn resolve_authenticated_user_returns_cached_login() {
        let _g = EnvGuard::set(&[("GH_TOKEN", None), ("GITHUB_TOKEN", None)]);
        clear_authenticated_user_cache();
        *AUTHENTICATED_USER_CACHE
            .get_or_init(|| Mutex::new(None))
            .lock()
            .unwrap() = Some("octocat".into());

        assert_eq!(run_async(resolve_authenticated_user()).unwrap(), "octocat");
        clear_authenticated_user_cache();
    }

    #[test]
    fn resolve_authenticated_user_requires_a_token_without_cache() {
        let _g = EnvGuard::set(&[("GH_TOKEN", None), ("GITHUB_TOKEN", None)]);
        clear_authenticated_user_cache();

        let err = run_async(resolve_authenticated_user()).unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message == "GH_TOKEN / GITHUB_TOKEN not set"
        ));
    }

    #[test]
    fn graphql_requires_a_token_before_sending() {
        let _g = EnvGuard::set(&[("GH_TOKEN", None), ("GITHUB_TOKEN", None)]);

        let err = run_async(graphql::<TestPayload>(
            "query { viewer { login } }",
            serde_json::json!({}),
        ))
        .unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message == "GH_TOKEN / GITHUB_TOKEN not set"
        ));
    }

    /// `\n` in a bearer token makes `reqwest::RequestBuilder::send()` fail synchronously
    /// at builder time — the `map_err` arm wrapping `send` is otherwise only reachable on
    /// real network failure to `api.github.com`, which we don't want in tests.
    #[test]
    fn rest_get_send_error_surfaces_request_failed() {
        let _g = EnvGuard::set(&[("GH_TOKEN", Some("tok\nbreak")), ("GITHUB_TOKEN", None)]);

        let err = run_async(rest_get::<TestPayload>("/user")).unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message.starts_with("github request failed:")
        ));
    }

    /// Same `\n`-in-token trick for the GraphQL POST path: covers the `send().await.map_err`
    /// arm in `graphql` without needing to mock or reach the live API.
    #[test]
    fn graphql_send_error_surfaces_request_failed() {
        let _g = EnvGuard::set(&[("GH_TOKEN", Some("tok\nbreak")), ("GITHUB_TOKEN", None)]);

        let err = run_async(graphql::<TestPayload>(
            "query { viewer { login } }",
            serde_json::json!({}),
        ))
        .unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message.starts_with("github graphql request failed:")
        ));
    }

    /// Cache miss → `rest_get("/user")` error propagates through `?` to the caller; verifies
    /// the `if let Some(cached) = ...` Some-arm is not the only path being exercised.
    #[test]
    fn resolve_authenticated_user_propagates_rest_get_error_on_cache_miss() {
        let _g = EnvGuard::set(&[("GH_TOKEN", Some("tok\nbreak")), ("GITHUB_TOKEN", None)]);
        clear_authenticated_user_cache();

        let err = run_async(resolve_authenticated_user()).unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message.starts_with("github request failed:")
        ));
    }

    #[test]
    fn parse_json_deserializes_success_bodies() {
        let payload = parse_test_payload("200 OK", r#"{"login":"octocat"}"#).unwrap();
        assert_eq!(payload.login, "octocat");
    }

    #[test]
    fn parse_json_surfaces_reported_api_messages() {
        let err = parse_test_payload("404 Not Found", r#"{"message":"Not Found"}"#).unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message == "github 404 Not Found: Not Found"
        ));
    }

    #[test]
    fn parse_json_falls_back_to_status_without_a_message() {
        let err = parse_test_payload("500 Internal Server Error", "{}").unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message == "github 500 Internal Server Error"
        ));
    }

    #[test]
    fn parse_json_surfaces_json_parse_errors() {
        let err = parse_test_payload("200 OK", "not-json").unwrap_err();

        assert!(matches!(
            err,
            FetchError::Failed(message) if message.contains("github json parse")
        ));
    }

    fn parse_test_payload(status: &str, body: &str) -> Result<TestPayload, FetchError> {
        let (url, server) = serve_once(status, body);
        let response = run_async(async {
            let response = http().get(&url).send().await.unwrap();
            parse_json::<TestPayload>(response).await
        });
        server.join().unwrap();
        response
    }

    fn serve_once(status: &str, body: &str) -> (String, thread::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let status = status.to_owned();
        let body = body.to_owned();
        let handle = thread::spawn(move || {
            let (mut stream, _) = listener.accept().unwrap();
            let mut request = [0; 1024];
            let _ = stream.read(&mut request);
            let response = format!(
                "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
            stream.write_all(response.as_bytes()).unwrap();
            stream.flush().unwrap();
        });
        (format!("http://{addr}"), handle)
    }

    fn run_async<T>(future: impl Future<Output = T>) -> T {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap()
            .block_on(future)
    }
}