-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.rs
More file actions
1270 lines (1146 loc) · 49.1 KB
/
Copy pathjwt.rs
File metadata and controls
1270 lines (1146 loc) · 49.1 KB
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! JWT session management for the CLI.
//!
//! A *session* is the `{access_token, refresh_token}` pair returned by
//! `/o/token/`. Access tokens are short-lived (5 min); refresh tokens
//! last 7 days for PKCE-origin sessions, 36 h for api-token-origin.
//!
//! The session is cached in `~/.hotdata/session.json` (mode 0600).
//! Before every API call, [`ensure_access_token`] decides what to do:
//!
//! | Cached state | Action |
//! |---|---|
//! | Access token valid for > 30 s | return it directly |
//! | Access expiring or expired, refresh token valid | call `/o/token/` with `grant_type=refresh_token` |
//! | Refresh token dead, `api_key` present | re-mint via `grant_type=api_token` |
//! | Refresh token dead, no `api_key` | return an error — user must `hotdata auth` again |
//!
//! The raw `hd_...` API token (flow 3 in the design doc) is *never*
//! persisted to the session file — it stays in the main config or the
//! `HOTDATA_API_KEY` env var and is only used transiently to mint.
use crate::config;
use crate::util;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};
const CLIENT_ID: &str = "hotdata-cli";
/// Refresh early so callers don't race an expiring token.
const REFRESH_LEEWAY_SECONDS: u64 = 30;
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Session {
pub access_token: String,
/// Unix timestamp when `access_token` expires.
pub access_expires_at: u64,
pub refresh_token: String,
/// Unix timestamp when `refresh_token` hits its absolute TTL. Not
/// precisely enforced client-side (server will reject); stored as
/// a soft hint so we know when to skip the refresh attempt and go
/// straight to the re-mint path.
pub refresh_expires_at: u64,
/// How this session was originally minted. Informational.
#[serde(default)]
pub source: String,
}
/// Path to the session cache file. Returns `None` if the home
/// directory can't be resolved — in which case we operate without
/// caching.
pub fn session_path() -> Option<PathBuf> {
config::config_dir().ok().map(|d| d.join("session.json"))
}
pub fn load_session() -> Option<Session> {
let path = session_path()?;
let raw = fs::read_to_string(&path).ok()?;
serde_json::from_str(&raw).ok()
}
pub fn save_session(session: &Session) -> Result<(), String> {
let path = session_path().ok_or_else(|| "no session path available".to_string())?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| format!("mkdir failed: {e}"))?;
}
let json =
serde_json::to_string_pretty(session).map_err(|e| format!("serialize failed: {e}"))?;
// mode 0600 — session file contains a refresh token, treat it like a
// credential on disk.
use std::os::unix::fs::OpenOptionsExt;
let mut f = fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.mode(0o600)
.open(&path)
.map_err(|e| format!("open failed: {e}"))?;
f.write_all(json.as_bytes())
.map_err(|e| format!("write failed: {e}"))?;
Ok(())
}
pub fn clear_session() {
if let Some(path) = session_path() {
let _ = fs::remove_file(path);
}
}
fn now_unix() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0)
}
#[derive(Deserialize)]
struct TokenResponse {
access_token: String,
expires_in: u64,
refresh_token: Option<String>,
}
fn session_from_response(
resp: TokenResponse,
fallback_refresh: Option<String>,
source: &str,
) -> Session {
let refresh_token = resp.refresh_token.or(fallback_refresh).unwrap_or_default();
// We don't know the exact refresh TTL server-side (7 d or 36 h
// depending on origin). Store a conservative estimate so we don't
// refresh-attempt with a known-dead token; server enforces the
// real deadline.
let refresh_ttl = if source == "api_token" {
36 * 60 * 60
} else {
7 * 24 * 60 * 60
};
Session {
access_token: resp.access_token,
access_expires_at: now_unix() + resp.expires_in,
refresh_token,
refresh_expires_at: now_unix() + refresh_ttl,
source: source.to_string(),
}
}
fn oauth_base(profile: &config::ProfileConfig) -> String {
// DOT (`/o/authorize/`, `/o/token/`, …) is mounted on the webapp
// (app_url), not the API. The api_url host typically only serves
// the `/v1` runtimedb routes.
profile
.app_url
.to_string()
.trim_end_matches('/')
.to_string()
}
/// Build a redacted JSON view of a form body for `--debug` printing.
/// `util::send_debug` takes the printable body separately from the
/// wire body, so we hand it this masked view while the actual `.form()`
/// payload sends real values.
fn redacted_form_body(params: &[(&str, &str)]) -> serde_json::Value {
let masked: serde_json::Map<String, serde_json::Value> = params
.iter()
.map(|(k, v)| {
let display = match *k {
"code" | "code_verifier" | "api_token" | "refresh_token" => {
util::mask_credential(v)
}
_ => v.to_string(),
};
(k.to_string(), serde_json::Value::String(display))
})
.collect();
serde_json::Value::Object(masked)
}
/// Token-endpoint responses contain the access + refresh JWTs in
/// plaintext. Mask both before printing, but return the unredacted
/// body so the caller can still parse real values out of it.
const TOKEN_REDACT_KEYS: &[&str] = &["access_token", "refresh_token"];
/// Exchange a CLI registration PKCE code for a session.
///
/// The `/auth/cli-register/` flow issues a short-lived `CLIAuthCode` (not a
/// full OAuth code). This function POSTs it to `/v1/auth/token` to get an
/// opaque API token, then immediately mints a full JWT session via
/// `mint_from_api_token` so the on-disk state is identical to a normal login.
pub fn exchange_cli_register_code(
profile: &config::ProfileConfig,
code: &str,
code_verifier: &str,
) -> Result<Session, String> {
let url = format!("{}/v1/auth/token", oauth_base(profile));
let body = serde_json::json!({ "code": code, "code_verifier": code_verifier });
let body_log = serde_json::json!({
"code": util::mask_credential(code),
"code_verifier": util::mask_credential(code_verifier),
});
let client = reqwest::blocking::Client::new();
let req = client.post(&url).json(&body);
let (status, body_text) =
util::send_debug_with_redaction(&client, req, Some(&body_log), &["token"])
.map_err(|e| format!("connection error: {e}"))?;
if !status.is_success() {
return Err(format!(
"registration token exchange failed: HTTP {status}: {body_text}"
));
}
#[derive(Deserialize)]
struct RegisterResponse {
token: String,
}
let resp: RegisterResponse =
serde_json::from_str(&body_text).map_err(|e| format!("malformed token response: {e}"))?;
mint_from_api_token(profile, &resp.token)
}
/// Exchange a PKCE authorization code for a session.
pub fn mint_from_pkce_code(
profile: &config::ProfileConfig,
code: &str,
code_verifier: &str,
redirect_uri: &str,
) -> Result<Session, String> {
let url = format!("{}/o/token/", oauth_base(profile));
let params = [
("grant_type", "authorization_code"),
("code", code),
("code_verifier", code_verifier),
("redirect_uri", redirect_uri),
("client_id", CLIENT_ID),
];
let client = reqwest::blocking::Client::new();
let req = client.post(&url).form(¶ms);
let body_log = redacted_form_body(¶ms);
let (status, body_text) =
util::send_debug_with_redaction(&client, req, Some(&body_log), TOKEN_REDACT_KEYS)
.map_err(|e| format!("connection error: {e}"))?;
if !status.is_success() {
return Err(format!("token exchange failed: HTTP {status}: {body_text}"));
}
let body: TokenResponse =
serde_json::from_str(&body_text).map_err(|e| format!("malformed token response: {e}"))?;
Ok(session_from_response(body, None, "pkce"))
}
/// Exchange an opaque API token for a session.
pub fn mint_from_api_token(
profile: &config::ProfileConfig,
api_token: &str,
) -> Result<Session, String> {
let url = format!("{}/o/token/", oauth_base(profile));
let params = [
("grant_type", "api_token"),
("api_token", api_token),
("client_id", CLIENT_ID),
];
let client = reqwest::blocking::Client::new();
let req = client.post(&url).form(¶ms);
let body_log = redacted_form_body(¶ms);
let (status, body_text) =
util::send_debug_with_redaction(&client, req, Some(&body_log), TOKEN_REDACT_KEYS)
.map_err(|e| format!("connection error: {e}"))?;
if !status.is_success() {
return Err(format!(
"api_token exchange failed: HTTP {status}: {body_text}"
));
}
let body: TokenResponse =
serde_json::from_str(&body_text).map_err(|e| format!("malformed token response: {e}"))?;
Ok(session_from_response(body, None, "api_token"))
}
/// Refresh an existing session via the refresh-token grant.
pub fn refresh(profile: &config::ProfileConfig, session: &Session) -> Result<Session, String> {
let url = format!("{}/o/token/", oauth_base(profile));
let params = [
("grant_type", "refresh_token"),
("refresh_token", session.refresh_token.as_str()),
("client_id", CLIENT_ID),
];
let client = reqwest::blocking::Client::new();
let req = client.post(&url).form(¶ms);
let body_log = redacted_form_body(¶ms);
let (status, body_text) =
util::send_debug_with_redaction(&client, req, Some(&body_log), TOKEN_REDACT_KEYS)
.map_err(|e| format!("connection error: {e}"))?;
if !status.is_success() {
return Err(format!("refresh failed: HTTP {status}: {body_text}"));
}
let body: TokenResponse =
serde_json::from_str(&body_text).map_err(|e| format!("malformed token response: {e}"))?;
Ok(session_from_response(
body,
// Rotation is off server-side, so the same refresh token
// should come back — but fall back to the old one if the
// server decides to drop it from the response.
Some(session.refresh_token.clone()),
&session.source,
))
}
/// Return a valid access token, minting or refreshing as needed.
///
/// The caller passes in whatever credential they want to fall back on
/// (an `hd_...` API key from `--api-key`, env var, or config). If the
/// cached session is usable it's returned without touching the API;
/// otherwise the session is refreshed/re-minted and persisted.
pub fn ensure_access_token(
profile: &config::ProfileConfig,
api_key_fallback: Option<&str>,
) -> Result<String, String> {
// 0) An explicit identity override (`--api-key`, `HOTDATA_API_KEY`,
// or `.env`) is asserting a specific identity for *this invocation*.
// The on-disk session may belong to a completely different user
// from a prior `hotdata auth` and must not be reused. Mint fresh
// and deliberately skip persisting so we don't clobber the
// interactive session. Surface the real mint error here too — if
// the override key is bad, "HTTP 401" is more useful than the
// generic "session expired" message the cache-fallthrough returns.
//
// Only `ApiKeySource::Config` continues to honor the cache: that's
// a stable identity persisted in config.yml, paired with a session
// minted from that same identity.
if matches!(
profile.api_key_source,
config::ApiKeySource::Flag | config::ApiKeySource::Env
) && let Some(api_key) = api_key_fallback
{
let session = mint_from_api_token(profile, api_key)?;
return Ok(session.access_token);
}
let now = now_unix();
// 1) Cached session is still good.
if let Some(session) = load_session() {
if !session.access_token.is_empty()
&& now + REFRESH_LEEWAY_SECONDS < session.access_expires_at
{
return Ok(session.access_token);
}
// 2) Access expired but refresh might still work.
if !session.refresh_token.is_empty() && now < session.refresh_expires_at {
match refresh(profile, &session) {
Ok(new_session) => {
let tok = new_session.access_token.clone();
let _ = save_session(&new_session);
return Ok(tok);
}
Err(_) => {
// Refresh rejected — fall through to re-mint.
clear_session();
}
}
}
}
// 3) No cache, or refresh is dead → need a fresh mint.
if let Some(api_key) = api_key_fallback {
match mint_from_api_token(profile, api_key) {
Ok(session) => {
let tok = session.access_token.clone();
save_session(&session)?;
return Ok(tok);
}
Err(_) => {
// API token rejected (revoked, expired, or invalid).
// Fall through to the re-auth hint — hide the raw HTTP
// error from the user; the api.rs caller appends a
// `hotdata auth` hint.
}
}
}
Err("session expired or revoked".into())
}
/// Which credential source the [`CliTokenProvider`] serves bearers from.
///
/// Carries the 4-level auth-source precedence (database env -> sandbox env ->
/// on-disk sandbox session -> user session/api_key). The wrapper (`src/sdk.rs`)
/// picks the variant at construction time; the provider re-runs the
/// corresponding blocking CLI function on every request so session.json, the
/// 30s leeway
/// table, no-clobber for Flag/Env, and clear-on-dead-refresh stay owned by
/// the CLI — the SDK never re-implements JWT exchange.
#[derive(Debug, Clone)]
pub enum AuthMode {
/// `HOTDATA_DATABASE_TOKEN` env var (a `databases run` child).
DatabaseEnv { api_url: String },
/// `HOTDATA_SANDBOX_TOKEN` env var (a `sandbox run` child).
SandboxEnv { api_url: String },
/// `~/.hotdata/sandbox_session.json` is present (`sandbox set <id>`).
SandboxSession { api_url: String },
/// Normal user-scoped CLI session in `~/.hotdata/session.json`, with an
/// optional `hd_...` api-key fallback to mint from.
Session {
profile: config::ProfileConfig,
api_key_fallback: Option<String>,
},
}
/// A CLI-owned [`BearerTokenProvider`](hotdata::auth::BearerTokenProvider)
/// installed on the SDK's `Configuration.token_provider`.
///
/// `bearer_value` delegates to the CLI's existing *synchronous* token
/// functions (which own session.json, PKCE-minted refresh tokens, and the
/// `/o/token/` `client_id=hotdata-cli` attribution). They already return a
/// ready `eyJ...` JWT, which the SDK passes through unchanged — so the SDK's
/// own `TokenManager` is bypassed for the user-JWT path and the CLI keeps
/// full ownership of auth. The blocking functions run inside
/// `spawn_blocking` so they don't stall the wrapper's async runtime.
#[derive(Debug, Clone)]
pub struct CliTokenProvider {
mode: AuthMode,
}
impl CliTokenProvider {
pub fn new(mode: AuthMode) -> Self {
Self { mode }
}
/// Resolve a fresh bearer synchronously. Pure delegation to the existing
/// CLI auth functions; returns the JWT to put on the wire, or an error
/// string describing why no token could be obtained.
fn resolve_blocking(mode: &AuthMode) -> Result<String, String> {
match mode {
AuthMode::DatabaseEnv { api_url } => crate::database_session::refresh_from_env(api_url)
.ok_or_else(|| "HOTDATA_DATABASE_TOKEN is empty".to_string()),
AuthMode::SandboxEnv { api_url } => crate::sandbox_session::refresh_from_env(api_url)
.ok_or_else(|| "HOTDATA_SANDBOX_TOKEN is empty".to_string()),
AuthMode::SandboxSession { api_url } => {
crate::sandbox_session::ensure_access_token(api_url)
.ok_or_else(|| "sandbox session expired".to_string())
}
AuthMode::Session {
profile,
api_key_fallback,
} => ensure_access_token(profile, api_key_fallback.as_deref()),
}
}
}
#[async_trait::async_trait]
impl hotdata::auth::BearerTokenProvider for CliTokenProvider {
async fn bearer_value(&self) -> Result<String, hotdata::auth::TokenExchangeError> {
let mode = self.mode.clone();
// The CLI auth functions are blocking (reqwest::blocking I/O + file
// writes). Run them on a blocking thread so the multi-thread runtime's
// worker threads (and concurrent rayon block_on calls) aren't stalled.
let resolved = tokio::task::spawn_blocking(move || Self::resolve_blocking(&mode))
.await
.unwrap_or_else(|e| Err(format!("token resolution task failed: {e}")));
resolved.map_err(|body| {
// Surface as a 401 so `Configuration::resolve_bearer_token` logs the
// cause and the request proceeds to a 401 the wrapper shapes into
// the "run hotdata auth" hint.
hotdata::auth::TokenExchangeError::Status { status: 401, body }
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{ApiUrl, AppUrl, ProfileConfig, test_helpers::with_temp_config_dir};
fn mock_profile(url: &str) -> ProfileConfig {
ProfileConfig {
app_url: AppUrl(Some(url.to_string())),
api_url: ApiUrl(Some(url.to_string())),
..Default::default()
}
}
fn cached_session(access_offset: i64, refresh_offset: i64) -> Session {
let now = now_unix() as i64;
Session {
access_token: "cached-jwt".into(),
access_expires_at: (now + access_offset).max(0) as u64,
refresh_token: "cached-refresh".into(),
refresh_expires_at: (now + refresh_offset).max(0) as u64,
source: "pkce".into(),
}
}
// --- session persistence ---
#[test]
fn session_round_trip() {
let (_tmp, _guard) = with_temp_config_dir();
let s = Session {
access_token: "a".into(),
access_expires_at: 100,
refresh_token: "r".into(),
refresh_expires_at: 200,
source: "pkce".into(),
};
save_session(&s).unwrap();
let loaded = load_session().unwrap();
assert_eq!(loaded.access_token, "a");
assert_eq!(loaded.access_expires_at, 100);
assert_eq!(loaded.refresh_token, "r");
assert_eq!(loaded.refresh_expires_at, 200);
assert_eq!(loaded.source, "pkce");
}
#[test]
fn session_file_is_mode_0600() {
use std::os::unix::fs::PermissionsExt;
let (_tmp, _guard) = with_temp_config_dir();
save_session(&Session::default()).unwrap();
let path = session_path().unwrap();
let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(
mode, 0o600,
"session file must be 0600 (contains refresh token)"
);
}
#[test]
fn load_session_returns_none_when_missing() {
let (_tmp, _guard) = with_temp_config_dir();
assert!(load_session().is_none());
}
#[test]
fn load_session_returns_none_when_corrupt() {
let (_tmp, _guard) = with_temp_config_dir();
let path = session_path().unwrap();
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, "not json").unwrap();
assert!(load_session().is_none());
}
#[test]
fn clear_session_removes_file() {
let (_tmp, _guard) = with_temp_config_dir();
save_session(&Session::default()).unwrap();
assert!(load_session().is_some());
clear_session();
assert!(load_session().is_none());
// Idempotent — clearing again is a no-op.
clear_session();
}
// --- mint_from_pkce_code ---
#[test]
fn mint_from_pkce_code_success() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::AllOf(vec![
mockito::Matcher::UrlEncoded("grant_type".into(), "authorization_code".into()),
mockito::Matcher::UrlEncoded("code".into(), "auth-code".into()),
mockito::Matcher::UrlEncoded("code_verifier".into(), "verifier".into()),
mockito::Matcher::UrlEncoded(
"redirect_uri".into(),
"http://127.0.0.1:1234/".into(),
),
mockito::Matcher::UrlEncoded("client_id".into(), "hotdata-cli".into()),
]))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
r#"{"access_token":"jwt-abc","expires_in":300,"refresh_token":"refresh-xyz"}"#,
)
.create();
let profile = mock_profile(&server.url());
let session =
mint_from_pkce_code(&profile, "auth-code", "verifier", "http://127.0.0.1:1234/")
.unwrap();
m.assert();
assert_eq!(session.access_token, "jwt-abc");
assert_eq!(session.refresh_token, "refresh-xyz");
assert_eq!(session.source, "pkce");
assert!(session.access_expires_at > now_unix());
// PKCE-origin sessions get the 7-day refresh TTL hint.
let ttl = session.refresh_expires_at.saturating_sub(now_unix());
assert!((7 * 24 * 60 * 60 - 5..=7 * 24 * 60 * 60 + 5).contains(&ttl));
}
#[test]
fn mint_from_pkce_code_trims_trailing_slash_in_app_url() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"a","expires_in":1,"refresh_token":"r"}"#)
.create();
// Append a trailing slash — oauth_base must strip it so we don't
// end up POSTing to `//o/token/`.
let url = format!("{}/", server.url());
let profile = mock_profile(&url);
mint_from_pkce_code(&profile, "c", "v", "uri").unwrap();
m.assert();
}
#[test]
fn mint_from_pkce_code_http_error_includes_status_and_body() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.with_status(403)
.with_body("forbidden by policy")
.create();
let profile = mock_profile(&server.url());
let err = mint_from_pkce_code(&profile, "c", "v", "uri").unwrap_err();
m.assert();
assert!(err.contains("403"), "got: {err}");
assert!(err.contains("forbidden by policy"), "got: {err}");
}
#[test]
fn mint_from_pkce_code_malformed_response() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.with_status(200)
.with_body("not json")
.create();
let profile = mock_profile(&server.url());
let err = mint_from_pkce_code(&profile, "c", "v", "uri").unwrap_err();
m.assert();
assert!(err.contains("malformed"), "got: {err}");
}
#[test]
fn mint_from_pkce_code_connection_error() {
let profile = mock_profile("http://127.0.0.1:1");
let err = mint_from_pkce_code(&profile, "c", "v", "uri").unwrap_err();
assert!(err.contains("connection"), "got: {err}");
}
// --- exchange_cli_register_code ---
#[test]
fn exchange_cli_register_code_success() {
let mut server = mockito::Server::new();
// Step 1: exchange the PKCE code for an opaque API token.
let token_mock = server
.mock("POST", "/v1/auth/token")
.match_body(mockito::Matcher::Json(serde_json::json!({
"code": "reg-code",
"code_verifier": "verifier",
})))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"token":"hd_tok"}"#)
.create();
// Step 2: mint_from_api_token exchanges the opaque token for a JWT.
let mint_mock = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::AllOf(vec![
mockito::Matcher::UrlEncoded("grant_type".into(), "api_token".into()),
mockito::Matcher::UrlEncoded("api_token".into(), "hd_tok".into()),
]))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"jwt-abc","expires_in":300,"refresh_token":"r"}"#)
.create();
let profile = mock_profile(&server.url());
let session = exchange_cli_register_code(&profile, "reg-code", "verifier").unwrap();
token_mock.assert();
mint_mock.assert();
assert_eq!(session.access_token, "jwt-abc");
assert_eq!(session.source, "api_token");
}
#[test]
fn exchange_cli_register_code_http_error() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/v1/auth/token")
.with_status(401)
.with_body("invalid code")
.create();
let profile = mock_profile(&server.url());
let err = exchange_cli_register_code(&profile, "bad-code", "v").unwrap_err();
m.assert();
assert!(err.contains("401"), "got: {err}");
}
#[test]
fn exchange_cli_register_code_malformed_response() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/v1/auth/token")
.with_status(200)
.with_body("not json")
.create();
let profile = mock_profile(&server.url());
let err = exchange_cli_register_code(&profile, "code", "v").unwrap_err();
m.assert();
assert!(err.contains("malformed"), "got: {err}");
}
#[test]
fn exchange_cli_register_code_connection_error() {
let profile = mock_profile("http://127.0.0.1:1");
let err = exchange_cli_register_code(&profile, "code", "v").unwrap_err();
assert!(err.contains("connection"), "got: {err}");
}
// --- mint_from_api_token ---
#[test]
fn mint_from_api_token_success_uses_36h_refresh_ttl() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::AllOf(vec![
mockito::Matcher::UrlEncoded("grant_type".into(), "api_token".into()),
mockito::Matcher::UrlEncoded("api_token".into(), "hd_xyz".into()),
mockito::Matcher::UrlEncoded("client_id".into(), "hotdata-cli".into()),
]))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"jwt-1","expires_in":300,"refresh_token":"r1"}"#)
.create();
let profile = mock_profile(&server.url());
let session = mint_from_api_token(&profile, "hd_xyz").unwrap();
m.assert();
assert_eq!(session.access_token, "jwt-1");
assert_eq!(session.refresh_token, "r1");
assert_eq!(session.source, "api_token");
// api_token-origin sessions get the shorter 36h refresh TTL hint.
let ttl = session.refresh_expires_at.saturating_sub(now_unix());
assert!((36 * 60 * 60 - 5..=36 * 60 * 60 + 5).contains(&ttl));
}
#[test]
fn mint_from_api_token_http_error() {
let mut server = mockito::Server::new();
let m = server.mock("POST", "/o/token/").with_status(401).create();
let profile = mock_profile(&server.url());
let err = mint_from_api_token(&profile, "bad-key").unwrap_err();
m.assert();
assert!(err.contains("401"), "got: {err}");
}
// --- refresh ---
#[test]
fn refresh_keeps_old_refresh_token_when_server_omits_it() {
// Rotation-off case: server returns no refresh_token, and we
// must carry the old one forward so the next refresh works.
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::AllOf(vec![
mockito::Matcher::UrlEncoded("grant_type".into(), "refresh_token".into()),
mockito::Matcher::UrlEncoded("refresh_token".into(), "stable-refresh".into()),
]))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"new-jwt","expires_in":300}"#)
.create();
let profile = mock_profile(&server.url());
let session = Session {
refresh_token: "stable-refresh".into(),
source: "pkce".into(),
..Default::default()
};
let new_session = refresh(&profile, &session).unwrap();
m.assert();
assert_eq!(new_session.access_token, "new-jwt");
assert_eq!(new_session.refresh_token, "stable-refresh");
// Source is carried over from the original session.
assert_eq!(new_session.source, "pkce");
}
#[test]
fn refresh_uses_rotated_refresh_token_when_server_returns_one() {
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"new-jwt","expires_in":300,"refresh_token":"rotated"}"#)
.create();
let profile = mock_profile(&server.url());
let session = Session {
refresh_token: "old".into(),
source: "api_token".into(),
..Default::default()
};
let new_session = refresh(&profile, &session).unwrap();
m.assert();
assert_eq!(new_session.refresh_token, "rotated");
assert_eq!(new_session.source, "api_token");
}
#[test]
fn refresh_http_error() {
let mut server = mockito::Server::new();
let m = server.mock("POST", "/o/token/").with_status(400).create();
let profile = mock_profile(&server.url());
let session = Session {
refresh_token: "x".into(),
..Default::default()
};
let err = refresh(&profile, &session).unwrap_err();
m.assert();
assert!(err.contains("400"), "got: {err}");
}
// --- ensure_access_token: each branch of the decision table ---
#[test]
fn ensure_returns_cached_token_without_http_when_valid() {
let (_tmp, _guard) = with_temp_config_dir();
// 10 min into the future, well past REFRESH_LEEWAY_SECONDS.
save_session(&cached_session(600, 7 * 24 * 3600)).unwrap();
// Profile points at a port that's not listening — if the code
// reached out to the network this would surface as an error.
let profile = mock_profile("http://127.0.0.1:1");
let token = ensure_access_token(&profile, None).unwrap();
assert_eq!(token, "cached-jwt");
}
#[test]
fn ensure_refreshes_when_inside_leeway_window() {
// Token still has a few seconds left but is inside the 30s
// leeway, so the orchestrator should refresh proactively.
let (_tmp, _guard) = with_temp_config_dir();
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"refresh_token".into(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"refreshed-jwt","expires_in":300}"#)
.create();
save_session(&cached_session(5, 86400)).unwrap();
let profile = mock_profile(&server.url());
let token = ensure_access_token(&profile, None).unwrap();
m.assert();
assert_eq!(token, "refreshed-jwt");
// New session was persisted to disk.
assert_eq!(load_session().unwrap().access_token, "refreshed-jwt");
}
#[test]
fn ensure_refreshes_when_access_expired() {
let (_tmp, _guard) = with_temp_config_dir();
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"refresh_token".into(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"refreshed-jwt","expires_in":300}"#)
.create();
save_session(&cached_session(-10, 86400)).unwrap();
let profile = mock_profile(&server.url());
let token = ensure_access_token(&profile, None).unwrap();
m.assert();
assert_eq!(token, "refreshed-jwt");
}
#[test]
fn ensure_falls_back_to_api_token_mint_when_refresh_rejected() {
let (_tmp, _guard) = with_temp_config_dir();
let mut server = mockito::Server::new();
let refresh_mock = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"refresh_token".into(),
))
.with_status(400)
.with_body("invalid_grant")
.create();
let mint_mock = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"api_token".into(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"reminted-jwt","expires_in":300,"refresh_token":"r2"}"#)
.create();
save_session(&cached_session(-10, 86400)).unwrap();
let profile = mock_profile(&server.url());
let token = ensure_access_token(&profile, Some("hd_xyz")).unwrap();
refresh_mock.assert();
mint_mock.assert();
assert_eq!(token, "reminted-jwt");
let loaded = load_session().unwrap();
assert_eq!(loaded.access_token, "reminted-jwt");
assert_eq!(loaded.source, "api_token");
}
#[test]
fn ensure_mints_from_api_token_when_no_session() {
let (_tmp, _guard) = with_temp_config_dir();
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"api_token".into(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"fresh-jwt","expires_in":300,"refresh_token":"r"}"#)
.create();
let profile = mock_profile(&server.url());
let token = ensure_access_token(&profile, Some("hd_xyz")).unwrap();
m.assert();
assert_eq!(token, "fresh-jwt");
assert_eq!(load_session().unwrap().access_token, "fresh-jwt");
}
#[test]
fn ensure_skips_refresh_when_refresh_ttl_expired() {
// Refresh token is past its soft TTL — the orchestrator should
// skip the refresh attempt entirely and go straight to the
// api_token re-mint path.
let (_tmp, _guard) = with_temp_config_dir();
let mut server = mockito::Server::new();
let mint_mock = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"api_token".into(),
))
.with_status(200)
.with_header("content-type", "application/json")
.with_body(r#"{"access_token":"reminted","expires_in":300,"refresh_token":"r"}"#)
.expect(1)
.create();
// Refresh path must NOT be hit.
let refresh_mock = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"refresh_token".into(),
))
.expect(0)
.create();
save_session(&cached_session(-10, -10)).unwrap();
let profile = mock_profile(&server.url());
let token = ensure_access_token(&profile, Some("hd_xyz")).unwrap();
mint_mock.assert();
refresh_mock.assert();
assert_eq!(token, "reminted");
}
#[test]
fn ensure_errors_when_no_session_and_no_api_key() {
let (_tmp, _guard) = with_temp_config_dir();
let profile = mock_profile("http://127.0.0.1:1");
let err = ensure_access_token(&profile, None).unwrap_err();
assert!(err.contains("session"), "got: {err}");
}
#[test]
fn ensure_errors_when_api_token_rejected() {
let (_tmp, _guard) = with_temp_config_dir();
let mut server = mockito::Server::new();
let m = server
.mock("POST", "/o/token/")
.match_body(mockito::Matcher::UrlEncoded(
"grant_type".into(),
"api_token".into(),
))
.with_status(401)
.create();
let profile = mock_profile(&server.url());
let err = ensure_access_token(&profile, Some("revoked")).unwrap_err();
m.assert();
// Error is the generic "session expired or revoked" — the raw
// HTTP status is suppressed so api.rs can append a clean
// re-auth hint.
assert!(err.contains("session"), "got: {err}");
}
// --- ensure_access_token: --api-key (Flag source) overrides cache ---