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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
//! Integration tests for the ghtkn SDK.
//!
//! These tests verify cross-module behavior with mocked dependencies.
//! No network access or real system keyring is required.

use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Duration;

use chrono::{DateTime, TimeZone, Utc};
use pretty_assertions::assert_eq;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

use ghtkn::browser::{Browser, BrowserError};
use ghtkn::config::{App, Config};
use ghtkn::deviceflow::{DeviceCodeResponse, DeviceCodeUI};
use ghtkn::keyring::{AccessToken, DEFAULT_SERVICE_KEY, Keyring, KeyringBackend};
use ghtkn::{Client, InputGet};

// ---------------------------------------------------------------------------
// Mock keyring backend (same pattern as unit tests, but accessible here)
// ---------------------------------------------------------------------------

struct MockBackend {
    store: Mutex<HashMap<(String, String), String>>,
}

impl MockBackend {
    fn new() -> Self {
        Self {
            store: Mutex::new(HashMap::new()),
        }
    }

    /// Pre-populate the mock keyring with a raw JSON string.
    fn insert(&self, service: &str, user: &str, json: &str) {
        let mut store = self.store.lock().unwrap();
        store.insert((service.to_string(), user.to_string()), json.to_string());
    }
}

impl KeyringBackend for MockBackend {
    fn get(&self, service: &str, user: &str) -> ghtkn::Result<Option<String>> {
        let store = self.store.lock().unwrap();
        Ok(store.get(&(service.to_string(), user.to_string())).cloned())
    }

    fn set(&self, service: &str, user: &str, password: &str) -> ghtkn::Result<()> {
        let mut store = self.store.lock().unwrap();
        store.insert(
            (service.to_string(), user.to_string()),
            password.to_string(),
        );
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Test 1: Config loading -> app selection -> keyring roundtrip
// ---------------------------------------------------------------------------

#[test]
fn config_load_select_keyring_roundtrip() {
    // 1. Create a temp config file.
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("ghtkn.yaml");
    std::fs::write(
        &config_path,
        "apps:\n  - name: my-app\n    client_id: Iv1.abc123\n    git_owner: myorg\n",
    )
    .unwrap();

    // 2. Read and validate the config.
    let cfg = ghtkn::config::read(&config_path).unwrap().unwrap();
    cfg.validate().unwrap();
    assert_eq!(cfg.apps.len(), 1);

    // 3. Select the app.
    let app = ghtkn::config::select_app(&cfg, "", "myorg").unwrap();
    assert_eq!(app.name, "my-app");
    assert_eq!(app.client_id, "Iv1.abc123");

    // 4. Store a token in a mock keyring using the app's client_id as key.
    let backend = MockBackend::new();
    let keyring = ghtkn::keyring::Keyring::with_backend(Box::new(backend));

    let token = AccessToken {
        access_token: "ghu_roundtrip_token".into(),
        expiration_date: Utc.with_ymd_and_hms(2025, 12, 31, 23, 59, 59).unwrap(),
        login: "testuser".into(),
    };
    keyring
        .set(DEFAULT_SERVICE_KEY, &app.client_id, &token)
        .unwrap();

    // 5. Read the token back from the keyring.
    let got = keyring
        .get(DEFAULT_SERVICE_KEY, &app.client_id)
        .unwrap()
        .unwrap();
    assert_eq!(got.access_token, "ghu_roundtrip_token");
    assert_eq!(got.login, "testuser");
    assert_eq!(
        got.expiration_date,
        Utc.with_ymd_and_hms(2025, 12, 31, 23, 59, 59).unwrap()
    );
}

// ---------------------------------------------------------------------------
// Test 2: Token expiration threshold logic
// ---------------------------------------------------------------------------

#[test]
fn token_expiration_threshold_logic() {
    let backend = MockBackend::new();
    let keyring = ghtkn::keyring::Keyring::with_backend(Box::new(backend));

    // Store a token that expires in 10 minutes from now.
    let expiration = Utc::now() + chrono::Duration::minutes(10);
    let token = AccessToken {
        access_token: "ghu_threshold_test".into(),
        expiration_date: expiration,
        login: "testuser".into(),
    };
    keyring
        .set(DEFAULT_SERVICE_KEY, "threshold-app", &token)
        .unwrap();

    // Read the token back.
    let got = keyring
        .get(DEFAULT_SERVICE_KEY, "threshold-app")
        .unwrap()
        .unwrap();

    // With a 5-minute threshold, the token should still be valid
    // (10 min remaining > 5 min threshold).
    let five_min = Duration::from_secs(5 * 60);
    let min_exp_5 = chrono::Duration::from_std(five_min).unwrap_or(chrono::Duration::zero());
    let expired_5 = Utc::now() + min_exp_5 > got.expiration_date;
    assert!(
        !expired_5,
        "token with 10 min remaining should be valid with 5 min threshold"
    );

    // With a 15-minute threshold, the token should be considered expired
    // (10 min remaining < 15 min threshold).
    let fifteen_min = Duration::from_secs(15 * 60);
    let min_exp_15 = chrono::Duration::from_std(fifteen_min).unwrap_or(chrono::Duration::zero());
    let expired_15 = Utc::now() + min_exp_15 > got.expiration_date;
    assert!(
        expired_15,
        "token with 10 min remaining should be expired with 15 min threshold"
    );
}

// ---------------------------------------------------------------------------
// Test 3: Config validation catches all error cases
// ---------------------------------------------------------------------------

#[test]
fn config_validation_catches_empty_apps() {
    let cfg = Config { apps: vec![] };
    let err = cfg.validate().unwrap_err();
    assert!(
        err.to_string().contains("apps is required"),
        "unexpected error: {err}"
    );
}

#[test]
fn config_validation_catches_empty_name() {
    let cfg = Config {
        apps: vec![App {
            name: String::new(),
            client_id: "xxx".into(),
            git_owner: String::new(),
        }],
    };
    let err = cfg.validate().unwrap_err();
    assert!(
        err.to_string().contains("name is required"),
        "unexpected error: {err}"
    );
}

#[test]
fn config_validation_catches_empty_client_id() {
    let cfg = Config {
        apps: vec![App {
            name: "app".into(),
            client_id: String::new(),
            git_owner: String::new(),
        }],
    };
    let err = cfg.validate().unwrap_err();
    assert!(
        err.to_string().contains("client_id is required"),
        "unexpected error: {err}"
    );
}

#[test]
fn config_validation_catches_duplicate_names() {
    let cfg = Config {
        apps: vec![
            App {
                name: "dup".into(),
                client_id: "xxx".into(),
                git_owner: String::new(),
            },
            App {
                name: "dup".into(),
                client_id: "yyy".into(),
                git_owner: String::new(),
            },
        ],
    };
    let err = cfg.validate().unwrap_err();
    assert!(
        err.to_string().contains("app name must be unique"),
        "unexpected error: {err}"
    );
}

#[test]
fn config_validation_catches_duplicate_git_owners() {
    let cfg = Config {
        apps: vec![
            App {
                name: "app1".into(),
                client_id: "xxx".into(),
                git_owner: "same-owner".into(),
            },
            App {
                name: "app2".into(),
                client_id: "yyy".into(),
                git_owner: "same-owner".into(),
            },
        ],
    };
    let err = cfg.validate().unwrap_err();
    assert!(
        err.to_string().contains("app git_owner must be unique"),
        "unexpected error: {err}"
    );
}

// ---------------------------------------------------------------------------
// Test 4: Keyring JSON compatibility with Go SDK
// ---------------------------------------------------------------------------

#[test]
fn keyring_json_compatible_with_go_sdk() {
    // This is the exact JSON format the Go SDK stores in the keyring.
    let go_sdk_json = r#"{"access_token":"ghu_abc123","expiration_date":"2025-06-15T12:00:00Z","login":"testuser"}"#;

    // Set up a mock keyring pre-populated with the Go SDK JSON.
    let backend = MockBackend::new();
    backend.insert(DEFAULT_SERVICE_KEY, "Iv1.go_client", go_sdk_json);
    let keyring = ghtkn::keyring::Keyring::with_backend(Box::new(backend));

    // The Rust SDK should be able to parse it correctly.
    let token = keyring
        .get(DEFAULT_SERVICE_KEY, "Iv1.go_client")
        .unwrap()
        .unwrap();

    assert_eq!(token.access_token, "ghu_abc123");
    assert_eq!(token.login, "testuser");
    assert_eq!(
        token.expiration_date,
        Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap()
    );
}

#[test]
fn keyring_json_roundtrip_produces_go_compatible_format() {
    // Store a token via the Rust SDK and verify the JSON matches Go SDK format.
    let backend = MockBackend::new();
    let keyring = ghtkn::keyring::Keyring::with_backend(Box::new(backend));

    let token = AccessToken {
        access_token: "ghu_rust_token".into(),
        expiration_date: Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap(),
        login: "rustuser".into(),
    };
    keyring
        .set(DEFAULT_SERVICE_KEY, "Iv1.rust", &token)
        .unwrap();

    // Read back the raw JSON and verify field names match the Go SDK.
    let got = keyring
        .get(DEFAULT_SERVICE_KEY, "Iv1.rust")
        .unwrap()
        .unwrap();
    assert_eq!(got.access_token, "ghu_rust_token");
    assert_eq!(got.login, "rustuser");
    assert_eq!(
        got.expiration_date,
        Utc.with_ymd_and_hms(2025, 6, 15, 12, 0, 0).unwrap()
    );

    // Verify the underlying JSON uses the exact Go SDK field names.
    // We re-serialize and check.
    let json = serde_json::to_string(&got).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert!(
        parsed.get("access_token").is_some(),
        "missing access_token field"
    );
    assert!(
        parsed.get("expiration_date").is_some(),
        "missing expiration_date field"
    );
    assert!(parsed.get("login").is_some(), "missing login field");
    // Verify no extra fields.
    assert_eq!(
        parsed.as_object().unwrap().len(),
        3,
        "expected exactly 3 fields in serialized JSON"
    );
}

#[test]
fn keyring_go_sdk_json_with_subsecond_precision() {
    // The Go SDK may store timestamps with or without fractional seconds.
    // Verify we handle both.
    let json_with_nanos = r#"{"access_token":"ghu_nano","expiration_date":"2025-06-15T12:00:00.123456789Z","login":"nanouser"}"#;

    let backend = MockBackend::new();
    backend.insert(DEFAULT_SERVICE_KEY, "Iv1.nano", json_with_nanos);
    let keyring = ghtkn::keyring::Keyring::with_backend(Box::new(backend));

    let token = keyring
        .get(DEFAULT_SERVICE_KEY, "Iv1.nano")
        .unwrap()
        .unwrap();
    assert_eq!(token.access_token, "ghu_nano");
    assert_eq!(token.login, "nanouser");
}

// ---------------------------------------------------------------------------
// Test 5: App selection priority matches Go SDK
// ---------------------------------------------------------------------------

#[test]
fn app_selection_priority_owner_first() {
    let cfg = Config {
        apps: vec![
            App {
                name: "default-app".into(),
                client_id: "cid_default".into(),
                git_owner: "default-org".into(),
            },
            App {
                name: "owner-app".into(),
                client_id: "cid_owner".into(),
                git_owner: "target-org".into(),
            },
            App {
                name: "named-app".into(),
                client_id: "cid_named".into(),
                git_owner: String::new(),
            },
        ],
    };
    cfg.validate().unwrap();

    // Priority 1: owner match takes precedence over everything.
    let app = ghtkn::config::select_app(&cfg, "named-app", "target-org").unwrap();
    assert_eq!(app.name, "owner-app", "owner match should take priority");
}

#[test]
fn app_selection_priority_default_when_no_key() {
    let cfg = Config {
        apps: vec![
            App {
                name: "first-app".into(),
                client_id: "cid_first".into(),
                git_owner: String::new(),
            },
            App {
                name: "second-app".into(),
                client_id: "cid_second".into(),
                git_owner: String::new(),
            },
        ],
    };
    cfg.validate().unwrap();

    // Priority 2: empty key and empty owner returns first app.
    let app = ghtkn::config::select_app(&cfg, "", "").unwrap();
    assert_eq!(
        app.name, "first-app",
        "empty key/owner should return first app"
    );
}

#[test]
fn app_selection_priority_name_match() {
    let cfg = Config {
        apps: vec![
            App {
                name: "first-app".into(),
                client_id: "cid_first".into(),
                git_owner: String::new(),
            },
            App {
                name: "target-app".into(),
                client_id: "cid_target".into(),
                git_owner: String::new(),
            },
        ],
    };
    cfg.validate().unwrap();

    // Priority 3: name match.
    let app = ghtkn::config::select_app(&cfg, "target-app", "").unwrap();
    assert_eq!(app.name, "target-app", "name match should work");
}

#[test]
fn app_selection_owner_miss_falls_through() {
    let cfg = Config {
        apps: vec![
            App {
                name: "first-app".into(),
                client_id: "cid_first".into(),
                git_owner: "org1".into(),
            },
            App {
                name: "second-app".into(),
                client_id: "cid_second".into(),
                git_owner: "org2".into(),
            },
        ],
    };
    cfg.validate().unwrap();

    // Owner miss with empty key falls through to default (first app).
    let app = ghtkn::config::select_app(&cfg, "", "nonexistent-org").unwrap();
    assert_eq!(
        app.name, "first-app",
        "owner miss with empty key should return first app"
    );

    // Owner miss with name key falls through to name match.
    let app = ghtkn::config::select_app(&cfg, "second-app", "nonexistent-org").unwrap();
    assert_eq!(
        app.name, "second-app",
        "owner miss should fall through to name match"
    );

    // Owner miss + name miss returns None.
    let app = ghtkn::config::select_app(&cfg, "nonexistent", "nonexistent-org");
    assert!(app.is_none(), "owner miss + name miss should return None");
}

// ---------------------------------------------------------------------------
// Test 6: Config file read -> validate -> select roundtrip with multiple apps
// ---------------------------------------------------------------------------

#[test]
fn full_config_roundtrip_multiple_apps() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("ghtkn.yaml");
    std::fs::write(
        &config_path,
        r#"apps:
  - name: personal
    client_id: Iv1.personal123
  - name: work
    client_id: Iv1.work456
    git_owner: my-company
  - name: oss
    client_id: Iv1.oss789
    git_owner: open-source-org
"#,
    )
    .unwrap();

    let cfg = ghtkn::config::read(&config_path).unwrap().unwrap();
    cfg.validate().unwrap();

    assert_eq!(cfg.apps.len(), 3);

    // Default (no key, no owner) returns first app.
    let app = ghtkn::config::select_app(&cfg, "", "").unwrap();
    assert_eq!(app.name, "personal");

    // Select by owner.
    let app = ghtkn::config::select_app(&cfg, "", "my-company").unwrap();
    assert_eq!(app.name, "work");

    // Select by name.
    let app = ghtkn::config::select_app(&cfg, "oss", "").unwrap();
    assert_eq!(app.name, "oss");
}

// ---------------------------------------------------------------------------
// StoreToken recovery, caching, token_or_none
// ---------------------------------------------------------------------------

struct NoopBrowser;

impl Browser for NoopBrowser {
    fn open(&self, _url: &str) -> Result<(), BrowserError> {
        Ok(())
    }
}

struct NoopUI;

impl DeviceCodeUI for NoopUI {
    fn show(
        &self,
        _device_code: &DeviceCodeResponse,
        _expiration_date: DateTime<Utc>,
    ) -> Result<(), ghtkn::Error> {
        Ok(())
    }
}

/// Keyring backend that reads return "no entry" and writes always fail.
struct FailingWriteBackend;

impl KeyringBackend for FailingWriteBackend {
    fn get(&self, _service: &str, _user: &str) -> ghtkn::Result<Option<String>> {
        Ok(None)
    }

    fn set(&self, _service: &str, _user: &str, _password: &str) -> ghtkn::Result<()> {
        Err(ghtkn::Error::Keyring(
            "simulated keyring write failure".into(),
        ))
    }
}

/// Mount wiremock mocks on separate servers so the test validates that
/// `/login/*` requests hit `github_base_url` and `/user` hits `api_base_url`.
async fn mount_device_flow_mocks(github_server: &MockServer, api_server: &MockServer) {
    Mock::given(method("POST"))
        .and(path("/login/device/code"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "device_code": "dc_test",
            "user_code": "ABCD-1234",
            "verification_uri": "https://github.com/login/device",
            "expires_in": 900,
            "interval": 0
        })))
        .mount(github_server)
        .await;

    Mock::given(method("POST"))
        .and(path("/login/oauth/access_token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "access_token": "ghu_test_token_abc",
            "expires_in": 28800
        })))
        .mount(github_server)
        .await;

    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(
            ResponseTemplate::new(200).set_body_json(serde_json::json!({"login": "testuser"})),
        )
        .mount(api_server)
        .await;
}

/// Build a Client with separate base URLs so the test validates correct routing.
fn make_test_client(github_uri: &str, api_uri: &str) -> Client {
    let mut client = Client::new();
    client.set_browser(Box::new(NoopBrowser));
    client.set_device_code_ui(Box::new(NoopUI));
    client.set_keyring(Keyring::with_backend(Box::new(FailingWriteBackend)));
    client.set_github_base_url(github_uri.to_string());
    client.set_api_base_url(api_uri.to_string());
    client
}

/// token() recovers from StoreToken and caches the result.
///
/// The failing keyring triggers StoreToken, but TokenSource::token()
/// extracts the token and returns Ok. A second call returns the cached
/// token without hitting the server again.
///
/// Uses two MockServers to verify `/login/*` hits `github_base_url`
/// and `/user` hits `api_base_url`.
#[tokio::test(start_paused = true)]
async fn test_token_store_token_recovery_and_caching() {
    let github_server = MockServer::start().await;
    let api_server = MockServer::start().await;
    mount_device_flow_mocks(&github_server, &api_server).await;

    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("ghtkn.yaml");
    std::fs::write(
        &config_path,
        "apps:\n  - name: test-app\n    client_id: test_client_id\n",
    )
    .unwrap();

    let client = make_test_client(&github_server.uri(), &api_server.uri());
    let ts = client.token_source(InputGet {
        config_file_path: config_path.to_str().unwrap().to_string(),
        ..Default::default()
    });

    // First call recovers the token despite keyring write failure.
    let token = ts.token().await.expect("should recover from StoreToken");
    assert_eq!(token, "ghu_test_token_abc");

    // Verify each server received only its expected requests.
    let github_requests = github_server.received_requests().await.unwrap();
    assert_eq!(
        github_requests.len(),
        2,
        "github_server should receive exactly 2 requests (device/code + access_token)"
    );

    let api_requests = api_server.received_requests().await.unwrap();
    assert_eq!(
        api_requests.len(),
        1,
        "api_server should receive exactly 1 request (/user)"
    );

    // Record totals before the second call.
    let github_count_before = github_requests.len();
    let api_count_before = api_requests.len();

    // Second call returns cached token — no new server requests.
    let token2 = ts.token().await.expect("should return cached token");
    assert_eq!(token2, "ghu_test_token_abc");

    assert_eq!(
        github_server.received_requests().await.unwrap().len(),
        github_count_before,
        "second call should use cached token, not hit github_server"
    );
    assert_eq!(
        api_server.received_requests().await.unwrap().len(),
        api_count_before,
        "second call should use cached token, not hit api_server"
    );
}

/// token_or_none() returns None when the config file doesn't exist.
#[tokio::test]
async fn test_token_or_none_returns_none_on_error() {
    let github_server = MockServer::start().await;
    let api_server = MockServer::start().await;
    // no mocks mounted — any request would 404 / be unexpected

    let dir = tempfile::tempdir().unwrap();
    let missing_config = dir.path().join("ghtkn.yaml");

    let client = make_test_client(&github_server.uri(), &api_server.uri());
    let ts = client.token_source(InputGet {
        config_file_path: missing_config.to_str().unwrap().to_string(),
        ..Default::default()
    });

    let result = ts.token_or_none().await;
    assert!(
        result.is_none(),
        "should return None when config is missing"
    );
}

/// token_or_none() returns Some on success (via StoreToken recovery).
#[tokio::test(start_paused = true)]
async fn test_token_or_none_returns_some_on_success() {
    let github_server = MockServer::start().await;
    let api_server = MockServer::start().await;
    mount_device_flow_mocks(&github_server, &api_server).await;

    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("ghtkn.yaml");
    std::fs::write(
        &config_path,
        "apps:\n  - name: test-app\n    client_id: test_client_id\n",
    )
    .unwrap();

    let client = make_test_client(&github_server.uri(), &api_server.uri());
    let ts = client.token_source(InputGet {
        config_file_path: config_path.to_str().unwrap().to_string(),
        ..Default::default()
    });

    let result = ts.token_or_none().await;
    assert_eq!(
        result,
        Some("ghu_test_token_abc".to_string()),
        "should return Some(token) on success"
    );
}