ghtkn 0.1.1

GitHub token management — OAuth device flow with keyring caching and config-driven app selection
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
//! Token manager and public client API.
//!
//! Orchestrates the full token flow: config -> keyring -> device flow -> GitHub
//! API -> keyring store. Provides the [`Client`] as the main entry point and
//! [`TokenSource`] for cached, on-demand token retrieval.

use std::path::PathBuf;
use std::time::Duration;

use chrono::{DateTime, Utc};

use crate::browser::{Browser, DefaultBrowser};
use crate::config::{self, App};
use crate::deviceflow::{DeviceCodeUI, DeviceFlowClient, SimpleDeviceCodeUI};
use crate::error::Error;
use crate::github::GitHubClient;
use crate::keyring::{AccessToken, DEFAULT_SERVICE_KEY, Keyring};
use crate::log::Logger;

/// Input parameters for token retrieval.
///
/// All fields have sensible defaults. Use [`Default::default`] for the common
/// case and override individual fields as needed.
pub struct InputGet {
    /// Custom keyring service name. When empty, [`DEFAULT_SERVICE_KEY`] is used.
    pub keyring_service: String,
    /// App selection by name. When empty, falls back to the `GHTKN_APP`
    /// environment variable.
    pub app_name: String,
    /// Custom config file path. When empty, the platform-specific default is
    /// auto-detected via [`config::get_path`].
    pub config_file_path: String,
    /// App selection by git owner (used for git-credential integration).
    pub app_owner: String,
    /// Minimum remaining token lifetime before renewal. A token whose
    /// expiration is within this duration of "now" is treated as expired.
    pub min_expiration: Duration,
}

impl Default for InputGet {
    fn default() -> Self {
        Self {
            keyring_service: String::new(),
            app_name: String::new(),
            config_file_path: String::new(),
            app_owner: String::new(),
            min_expiration: Duration::ZERO,
        }
    }
}

/// The main client for GitHub token management.
///
/// Owns all dependencies (logger, browser, device-code UI, keyring) and lends
/// them to the underlying [`DeviceFlowClient`] when a new token must be created.
///
/// # Example
///
/// ```no_run
/// use ghtkn::{Client, InputGet};
///
/// # async fn run() -> ghtkn::Result<()> {
/// let client = Client::new();
/// let (token, app) = client.get(&InputGet::default()).await?;
/// println!("token for {}: {}...", app.name, &token.access_token[..8]);
/// # Ok(())
/// # }
/// ```
pub struct Client {
    logger: Logger,
    device_code_ui: Box<dyn DeviceCodeUI>,
    browser: Box<dyn Browser>,
    keyring: Keyring,
    github_base_url: String,
    api_base_url: String,
}

impl Client {
    /// Create a new client with default dependencies.
    pub fn new() -> Self {
        Self {
            logger: Logger::new(),
            device_code_ui: Box::new(SimpleDeviceCodeUI),
            browser: Box::new(DefaultBrowser),
            keyring: Keyring::new(),
            github_base_url: "https://github.com".to_string(),
            api_base_url: "https://api.github.com".to_string(),
        }
    }

    /// Set a custom logger.
    pub fn set_logger(&mut self, logger: Logger) {
        self.logger = logger;
    }

    /// Set a custom device code UI.
    pub fn set_device_code_ui(&mut self, ui: Box<dyn DeviceCodeUI>) {
        self.device_code_ui = ui;
    }

    /// Set a custom browser opener.
    pub fn set_browser(&mut self, browser: Box<dyn Browser>) {
        self.browser = browser;
    }

    /// Set a custom keyring (e.g. with a mock backend for testing).
    pub fn set_keyring(&mut self, keyring: Keyring) {
        self.keyring = keyring;
    }

    /// Set a custom GitHub base URL (e.g. for GitHub Enterprise Server).
    pub fn set_github_base_url(&mut self, url: String) {
        self.github_base_url = url.trim_end_matches('/').to_string();
    }

    /// Set a custom GitHub API base URL (e.g. for GitHub Enterprise Server).
    pub fn set_api_base_url(&mut self, url: String) {
        self.api_base_url = url.trim_end_matches('/').to_string();
    }

    /// Create a reusable [`TokenSource`] that caches the access token.
    ///
    /// Consumes the `Client` and returns a `TokenSource` that can be
    /// called repeatedly to get a cached token.
    pub fn token_source(self, input: InputGet) -> TokenSource {
        TokenSource::new(self, input)
    }

    /// Get a GitHub access token.
    ///
    /// Flow:
    /// 1. Determine config file path (from input or auto-detect)
    /// 2. Read and validate YAML config
    /// 3. Select app (by owner, by name, or first)
    /// 4. Check keyring for cached, non-expired token
    /// 5. If expired/missing: device flow -> get user login -> store in keyring
    /// 6. Return token and app config
    pub async fn get(&self, input: &InputGet) -> crate::Result<(AccessToken, App)> {
        // 1. Determine config path.
        let config_path = if input.config_file_path.is_empty() {
            config::get_path(|k| std::env::var(k).ok(), std::env::consts::OS)?
        } else {
            PathBuf::from(&input.config_file_path)
        };

        // 2. Read and validate config.
        let cfg = config::read(&config_path)?
            .ok_or_else(|| Error::Config("configuration file is empty".into()))?;
        cfg.validate()?;

        // 3. Select app.
        let app_name = if input.app_name.is_empty() {
            std::env::var("GHTKN_APP").unwrap_or_default()
        } else {
            input.app_name.clone()
        };

        let app = config::select_app(&cfg, &app_name, &input.app_owner)
            .ok_or_else(|| Error::Config("no matching app found".into()))?
            .clone();

        // 4. Resolve keyring service.
        let service = if input.keyring_service.is_empty() {
            DEFAULT_SERVICE_KEY.to_string()
        } else {
            input.keyring_service.clone()
        };

        // 5. Try keyring, fall back to device flow.
        //
        // StoreToken is non-fatal: the token was obtained but the keyring
        // write failed.  Re-wrap it so the caller's (token, app) are the
        // ones from the error, exactly like Go's
        // `return token, app, ErrStoreToken`.
        match self
            .get_or_create_token(&service, &app, input.min_expiration)
            .await
        {
            Ok(token) => Ok((token, app)),
            Err(Error::StoreToken { message, token, .. }) => Err(Error::StoreToken {
                message,
                token,
                app: Box::new(app),
            }),
            Err(e) => Err(e),
        }
    }

    /// Try to retrieve a valid token from the keyring; create one if
    /// missing or expired.
    async fn get_or_create_token(
        &self,
        service: &str,
        app: &App,
        min_expiration: Duration,
    ) -> crate::Result<AccessToken> {
        match self.keyring.get(service, &app.client_id) {
            Ok(Some(token)) => {
                if check_expired(token.expiration_date, min_expiration) {
                    // Token expired — log and fall through to create a new one.
                    if let Some(cb) = &self.logger.expire {
                        cb(token.expiration_date);
                    }
                } else {
                    return Ok(token);
                }
            }
            Ok(None) => {
                if let Some(cb) = &self.logger.access_token_is_not_found_in_keyring {
                    cb();
                }
            }
            Err(e) => {
                if let Some(cb) = &self.logger.failed_to_get_access_token_from_keyring {
                    cb(&e.to_string());
                }
            }
        }

        self.create_token(service, app).await
    }

    /// Run the device flow to obtain a fresh token, fetch the user login,
    /// and store the result in the keyring.
    ///
    /// If the keyring write fails, returns [`Error::StoreToken`] carrying the
    /// token and app (matching Go SDK's `ErrStoreToken` non-fatal sentinel).
    async fn create_token(&self, service: &str, app: &App) -> crate::Result<AccessToken> {
        let http_client = reqwest::Client::new();

        let df_client = DeviceFlowClient::with_base_url(
            http_client,
            self.browser.as_ref(),
            &self.logger,
            self.device_code_ui.as_ref(),
            self.github_base_url.clone(),
        );

        let df_token = df_client.create(&app.client_id).await?;

        // Get user login via GET /user.
        let gh_client =
            GitHubClient::with_base_url(&df_token.access_token, self.api_base_url.clone());
        let user = gh_client.get_user().await?;

        let kr_token = AccessToken {
            access_token: df_token.access_token,
            expiration_date: df_token.expiration_date,
            login: user.login,
        };

        // Store in keyring — non-fatal. On failure return StoreToken with
        // the token and app so callers can still use them (matches Go SDK's
        // `return token, app, ErrStoreToken`).
        if let Err(e) = self.keyring.set(service, &app.client_id, &kr_token) {
            return Err(Error::StoreToken {
                message: e.to_string(),
                token: Box::new(kr_token),
                app: Box::new(app.clone()),
            });
        }

        Ok(kr_token)
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

/// Cached token source for repeated access.
///
/// Wraps a [`Client`] and caches the token after the first successful
/// retrieval. Thread-safe via an internal `tokio::sync::Mutex`.
pub struct TokenSource {
    client: Client,
    input: InputGet,
    cached: tokio::sync::Mutex<Option<String>>,
}

impl TokenSource {
    /// Create a new `TokenSource` that will retrieve tokens using the given
    /// client and input parameters.
    pub fn new(client: Client, input: InputGet) -> Self {
        Self {
            client,
            input,
            cached: tokio::sync::Mutex::new(None),
        }
    }

    /// Get a token, returning a cached value if available.
    ///
    /// Handles [`Error::StoreToken`] transparently: if the token was obtained
    /// but the keyring write failed, the token is still cached and returned.
    pub async fn token(&self) -> crate::Result<String> {
        let mut cached = self.cached.lock().await;
        if let Some(token) = cached.as_ref() {
            return Ok(token.clone());
        }
        let access_token = match self.client.get(&self.input).await {
            Ok((token, _)) => token.access_token,
            Err(Error::StoreToken { token, message, .. }) => {
                tracing::warn!(error = message, "keyring write failed, using token anyway");
                token.access_token
            }
            Err(e) => return Err(e),
        };
        *cached = Some(access_token.clone());
        Ok(access_token)
    }

    /// Get a token if available, returning `None` on any error.
    ///
    /// This is the recommended entry point for consumers using ghtkn as a
    /// fallback token source (like mise or aqua). All errors are treated
    /// as "no token available" and logged via `tracing::warn!`.
    ///
    /// **Note**: On a cache miss, this triggers the full OAuth device flow
    /// (opens browser, waits for user authorization). Gate calls behind an
    /// opt-in check (e.g. an environment variable) if this is undesirable.
    pub async fn token_or_none(&self) -> Option<String> {
        match self.token().await {
            Ok(token) => Some(token),
            Err(e) => {
                tracing::warn!(error = %e, "ghtkn token unavailable");
                None
            }
        }
    }
}

/// Check whether a token should be considered expired.
///
/// Returns `true` if `now + min_expiration` is after `expiration_date`,
/// meaning the token has less than `min_expiration` remaining.
fn check_expired(expiration_date: DateTime<Utc>, min_expiration: Duration) -> bool {
    let min_exp = chrono::Duration::from_std(min_expiration).unwrap_or(chrono::Duration::zero());
    Utc::now() + min_exp > expiration_date
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use chrono::{TimeZone, Utc};

    use super::*;

    // ---------------------------------------------------------------
    // check_expired
    // ---------------------------------------------------------------

    #[test]
    fn test_check_expired_not_expired() {
        // Token expires far in the future -- should NOT be expired.
        let expiration = Utc::now() + chrono::Duration::hours(8);
        assert!(!check_expired(expiration, Duration::ZERO));
    }

    #[test]
    fn test_check_expired_is_expired() {
        // Token expired in the past -- should be expired.
        let expiration = Utc::now() - chrono::Duration::hours(1);
        assert!(check_expired(expiration, Duration::ZERO));
    }

    #[test]
    fn test_check_expired_with_min_expiration() {
        // Token expires in 5 minutes, but we require 10 minutes remaining.
        let expiration = Utc::now() + chrono::Duration::minutes(5);
        let min_exp = Duration::from_secs(10 * 60); // 10 minutes
        assert!(check_expired(expiration, min_exp));
    }

    #[test]
    fn test_check_expired_with_min_expiration_sufficient() {
        // Token expires in 20 minutes, we require 10 minutes remaining.
        let expiration = Utc::now() + chrono::Duration::minutes(20);
        let min_exp = Duration::from_secs(10 * 60); // 10 minutes
        assert!(!check_expired(expiration, min_exp));
    }

    #[test]
    fn test_check_expired_exactly_at_boundary() {
        // Token at exact Unix epoch should definitely be expired.
        let expiration = Utc.with_ymd_and_hms(1970, 1, 1, 0, 0, 0).unwrap();
        assert!(check_expired(expiration, Duration::ZERO));
    }

    // ---------------------------------------------------------------
    // InputGet defaults
    // ---------------------------------------------------------------

    #[test]
    fn test_input_get_default() {
        let input = InputGet::default();
        assert!(input.keyring_service.is_empty());
        assert!(input.app_name.is_empty());
        assert!(input.config_file_path.is_empty());
        assert!(input.app_owner.is_empty());
        assert_eq!(input.min_expiration, Duration::ZERO);
    }

    // ---------------------------------------------------------------
    // Client builder pattern
    // ---------------------------------------------------------------

    #[test]
    fn test_client_new() {
        // Should not panic.
        let _client = Client::new();
    }

    #[test]
    fn test_client_default() {
        // Default impl should not panic.
        let _client = Client::default();
    }

    #[test]
    fn test_client_set_logger() {
        let mut client = Client::new();
        let logger = Logger::new();
        client.set_logger(logger);
    }

    #[test]
    fn test_client_set_device_code_ui() {
        let mut client = Client::new();
        client.set_device_code_ui(Box::new(SimpleDeviceCodeUI));
    }

    #[test]
    fn test_client_set_browser() {
        let mut client = Client::new();
        client.set_browser(Box::new(DefaultBrowser));
    }

    #[test]
    fn test_client_set_keyring() {
        let mut client = Client::new();
        client.set_keyring(Keyring::new());
    }

    #[test]
    fn test_client_set_github_base_url_trims_trailing_slash() {
        let mut client = Client::new();
        client.set_github_base_url("https://ghe.example.com/".to_string());
        assert_eq!(client.github_base_url, "https://ghe.example.com");
    }

    #[test]
    fn test_client_set_api_base_url_trims_trailing_slash() {
        let mut client = Client::new();
        client.set_api_base_url("https://ghe.example.com/api/v3/".to_string());
        assert_eq!(client.api_base_url, "https://ghe.example.com/api/v3");
    }

    // ---------------------------------------------------------------
    // TokenSource
    // ---------------------------------------------------------------

    #[test]
    fn test_token_source_new() {
        // Should not panic.
        let _ts = TokenSource::new(Client::new(), InputGet::default());
    }
}