1use crate::oidc::TokenSet;
19use crate::program::{ENV, TOP};
20use serde::{Deserialize, Serialize};
21use std::fmt;
22use std::fs;
23use std::path::{Path, PathBuf};
24
25pub const REFRESH_WINDOW_SECS: i64 = 60;
29
30#[derive(Clone, Serialize, Deserialize)]
36pub struct KeycloakSession {
37 pub issuer: String,
38 pub client_id: String,
39 pub refresh_token: String,
42 pub access_token: String,
44 pub access_expires_at: i64,
46}
47
48impl KeycloakSession {
49 pub fn needs_refresh(&self, now: i64) -> bool {
55 self.access_expires_at.saturating_sub(now) < REFRESH_WINDOW_SECS
56 }
57
58 pub fn apply(&mut self, tokens: &TokenSet, now: i64) {
64 self.access_token = tokens.access_token.clone();
65 if let Some(rt) = &tokens.refresh_token {
66 self.refresh_token = rt.clone();
67 }
68 self.access_expires_at = tokens.access_expires_at(now);
69 }
70}
71
72impl fmt::Debug for KeycloakSession {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 f.debug_struct("KeycloakSession")
76 .field("issuer", &self.issuer)
77 .field("client_id", &self.client_id)
78 .field("refresh_token", &"<redacted>")
79 .field("access_token", &"<redacted>")
80 .field("access_expires_at", &self.access_expires_at)
81 .finish()
82 }
83}
84
85pub fn same_server(a: &str, b: &str) -> bool {
100 let norm = |s: &str| s.trim().trim_end_matches('/').to_string();
101 norm(a) == norm(b)
102}
103
104#[derive(Clone)]
106pub enum Credential {
107 ApiKey(String),
109 Keycloak(KeycloakSession),
111}
112
113impl fmt::Debug for Credential {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 match self {
117 Self::ApiKey(_) => f.write_str("Credential::ApiKey(<redacted>)"),
118 Self::Keycloak(s) => write!(f, "Credential::Keycloak({s:?})"),
119 }
120 }
121}
122
123#[derive(Serialize, Deserialize)]
130pub struct Credentials {
131 pub server_url: String,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub token: Option<String>,
135 #[serde(default)]
139 pub email: String,
140 #[serde(default, skip_serializing_if = "Option::is_none")]
142 pub auth: Option<KeycloakSession>,
143}
144
145impl fmt::Debug for Credentials {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 f.debug_struct("Credentials")
149 .field("server_url", &self.server_url)
150 .field("token", &self.token.as_ref().map(|_| "<redacted>"))
151 .field("email", &self.email)
152 .field("auth", &self.auth)
153 .finish()
154 }
155}
156
157impl Credentials {
158 pub fn keycloak(server_url: &str, email: String, session: KeycloakSession) -> Self {
181 let preserved_token = Self::load()
182 .filter(|existing| same_server(&existing.server_url, server_url))
183 .and_then(|existing| existing.token);
184 Self {
185 server_url: server_url.to_string(),
186 token: preserved_token,
187 email,
188 auth: Some(session),
189 }
190 }
191
192 pub fn credential(&self) -> Option<Credential> {
196 if let Some(session) = &self.auth {
197 return Some(Credential::Keycloak(session.clone()));
198 }
199 self.token.clone().map(Credential::ApiKey)
200 }
201
202 pub fn path() -> Result<PathBuf, std::io::Error> {
212 Self::path_in(dirs::config_dir())
213 }
214
215 fn path_in(config_dir: Option<PathBuf>) -> Result<PathBuf, std::io::Error> {
224 let dir = config_dir.ok_or_else(|| {
225 std::io::Error::new(
226 std::io::ErrorKind::NotFound,
227 "cannot determine the user config directory: set XDG_CONFIG_HOME (or HOME) so \
228 credentials can be stored under $XDG_CONFIG_HOME/visdom/",
229 )
230 })?;
231 Ok(crate::layout::user_dir_in(&dir).join("credentials.json"))
232 }
233
234 fn legacy_path() -> Option<PathBuf> {
237 let path = Self::path().ok()?;
238 Some(crate::layout::legacy_sibling(path.parent()?)?.join("credentials.json"))
239 }
240
241 pub fn existing_path() -> Result<PathBuf, std::io::Error> {
244 let path = Self::path()?;
245 if !path.exists() {
246 if let Some(legacy) = Self::legacy_path().filter(|p| p.exists()) {
247 return Ok(legacy);
248 }
249 }
250 Ok(path)
251 }
252
253 pub fn path_for_display() -> String {
257 match Self::existing_path() {
258 Ok(p) => p.display().to_string(),
259 Err(_) => "<no user config directory: set XDG_CONFIG_HOME or HOME>".to_string(),
260 }
261 }
262
263 pub fn load() -> Option<Self> {
264 let path = Self::existing_path().ok()?;
265 let content = fs::read_to_string(&path).ok()?;
266 serde_json::from_str(&content).ok()
267 }
268
269 pub fn save(&self) -> Result<(), std::io::Error> {
288 self.save_to(&Self::path()?)?;
289 if let Some(legacy) = Self::legacy_path() {
293 match fs::remove_file(&legacy) {
294 Ok(()) => {}
295 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
296 Err(e) => {
298 return Err(std::io::Error::new(
299 e.kind(),
300 format!(
301 "the new login is saved, but the previous one at {} could not be \
302 removed ({e}); remove it by hand",
303 legacy.display()
304 ),
305 ))
306 }
307 }
308 Self::remove_temp_files_beside(&legacy, None);
309 }
310 Ok(())
311 }
312
313 fn save_to(&self, path: &std::path::Path) -> Result<(), std::io::Error> {
315 if let Some(parent) = path.parent() {
316 fs::create_dir_all(parent)?;
317 }
318 let json = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
319
320 let mut opts = fs::OpenOptions::new();
321 opts.write(true).create_new(true);
324 #[cfg(unix)]
327 {
328 use std::os::unix::fs::OpenOptionsExt;
329 opts.mode(0o600);
330 }
331
332 const ATTEMPTS: usize = 8;
337 let mut last_err = None;
338 for _ in 0..ATTEMPTS {
339 let tmp = path.with_file_name(Self::temp_file_name());
340 let file = match opts.open(&tmp) {
341 Ok(f) => f,
342 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
343 last_err = Some(e);
344 continue;
345 }
346 Err(e) => return Err(e),
347 };
348
349 let write_result = (|| {
350 use std::io::Write;
351 let mut file = file;
352 file.write_all(json.as_bytes())?;
353 file.sync_all()
354 })();
355 if let Err(e) = write_result {
356 let _ = fs::remove_file(&tmp);
357 return Err(e);
358 }
359 if let Err(e) = fs::rename(&tmp, path) {
360 let _ = fs::remove_file(&tmp);
361 return Err(e);
362 }
363 Self::remove_temp_files_beside(path, Some(Self::TEMP_STALE_AFTER));
366 return Ok(());
367 }
368 Err(last_err.unwrap_or_else(|| {
369 std::io::Error::new(
370 std::io::ErrorKind::AlreadyExists,
371 "could not create a unique temporary credentials file",
372 )
373 }))
374 }
375
376 const TEMP_PREFIX: &'static str = ".credentials.json.tmp";
380
381 const TEMP_STALE_AFTER: std::time::Duration = std::time::Duration::from_secs(3600);
386
387 fn remove_temp_files_beside(path: &std::path::Path, min_age: Option<std::time::Duration>) {
394 let Some(dir) = path.parent().map(PathBuf::from) else {
395 return;
396 };
397 let Ok(entries) = fs::read_dir(&dir) else {
398 return;
399 };
400 for entry in entries.flatten() {
401 let name = entry.file_name();
402 let Some(name) = name.to_str() else { continue };
403 if !name.starts_with(Self::TEMP_PREFIX) {
404 continue;
405 }
406 if let Some(min_age) = min_age {
407 let recent = entry
408 .metadata()
409 .and_then(|m| m.modified())
410 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
411 .map(|age| age < min_age)
412 .unwrap_or(true);
415 if recent {
416 continue;
417 }
418 }
419 let _ = fs::remove_file(entry.path());
420 }
421 }
422
423 fn temp_file_name() -> String {
431 use std::sync::atomic::{AtomicU64, Ordering};
432 static COUNTER: AtomicU64 = AtomicU64::new(0);
433 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
434 let nanos = std::time::SystemTime::now()
435 .duration_since(std::time::UNIX_EPOCH)
436 .map(|d| d.subsec_nanos())
437 .unwrap_or(0);
438 format!(
439 "{}{}.{}.{}",
440 Self::TEMP_PREFIX,
441 std::process::id(),
442 n,
443 nanos
444 )
445 }
446
447 pub fn persist_session(
468 server_url: &str,
469 session: &KeycloakSession,
470 ) -> Result<(), std::io::Error> {
471 let Some(mut creds) = Self::load() else {
472 return Ok(());
473 };
474 if !same_server(&creds.server_url, server_url) {
475 eprintln!(
476 "Warning: not saving the refreshed token — the credentials file is for \
477 '{}', but this session is for '{}'. The refreshed token applies to this \
478 process only; every later command will refresh again.",
479 creds.server_url, server_url
480 );
481 return Ok(());
482 }
483 creds.auth = Some(session.clone());
484 creds.save_to(&Self::existing_path()?)
488 }
489
490 pub fn delete() -> Result<(), std::io::Error> {
506 let path = Self::path()?;
507 if path.exists() {
508 fs::remove_file(&path)?;
509 }
510 Self::remove_temp_files_beside(&path, None);
511 if let Some(legacy) = Self::legacy_path() {
513 if legacy.exists() {
514 fs::remove_file(&legacy)?;
515 }
516 Self::remove_temp_files_beside(&legacy, None);
517 }
518 Ok(())
519 }
520}
521
522#[allow(clippy::type_complexity)]
552pub fn resolve_credentials(
553 project_root: &Path,
554) -> Result<(Option<String>, Option<Credential>), Box<dyn std::error::Error>> {
555 resolve_credentials_inner(project_root, true)
556}
557
558#[allow(clippy::type_complexity)]
571pub fn resolve_credentials_quiet(
572 project_root: &Path,
573) -> Result<(Option<String>, Option<Credential>), Box<dyn std::error::Error>> {
574 resolve_credentials_inner(project_root, false)
575}
576
577#[allow(clippy::type_complexity)]
578fn resolve_credentials_inner(
579 project_root: &Path,
580 warn_on_conflict: bool,
581) -> Result<(Option<String>, Option<Credential>), Box<dyn std::error::Error>> {
582 let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
584
585 let creds = Credentials::load();
587
588 let config = crate::config::TracevaultConfig::load(project_root);
600 let config_server_url = config.as_ref().and_then(|c| c.server_url.clone());
601 let config_api_key = config.as_ref().and_then(|c| c.api_key.clone());
602
603 if warn_on_conflict {
609 if let Some((file_url, config_url)) = config_url_conflict(
610 config_server_url.as_deref(),
611 creds.as_ref().map(|c| c.server_url.as_str()),
612 std::env::var("TRACEVAULT_SERVER_URL").is_ok(),
613 ) {
614 static WARNED: std::sync::Once = std::sync::Once::new();
618 WARNED.call_once(|| {
619 eprintln!("{}", config_mismatch_warning(file_url, config_url));
620 });
621 }
622 }
623
624 let server_url = std::env::var("TRACEVAULT_SERVER_URL")
626 .ok()
627 .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
628 .or(config_server_url);
629
630 let credential = match env_key {
632 Some(key) => Some(Credential::ApiKey(key)),
635 None => {
636 let from_file = creds.as_ref().and_then(Credentials::credential);
637 if from_file.is_some() {
638 let file_url = creds.as_ref().map_or("", |c| c.server_url.as_str());
652 if let Some(target) = server_url.as_deref() {
653 if !same_server(file_url, target) {
654 return Err(server_mismatch_error(file_url, target));
655 }
656 }
657 }
658 from_file.or_else(|| config_api_key.map(Credential::ApiKey))
663 }
664 };
665
666 Ok((server_url, credential))
667}
668
669pub(crate) fn config_url_conflict<'a>(
689 config_url: Option<&'a str>,
690 file_url: Option<&'a str>,
691 env_url_set: bool,
692) -> Option<(&'a str, &'a str)> {
693 if env_url_set {
694 return None;
695 }
696 let (config_url, file_url) = (config_url?, file_url?);
697 (!same_server(file_url, config_url)).then_some((file_url, config_url))
698}
699
700fn config_mismatch_warning(file_url: &str, config_url: &str) -> String {
708 format!(
709 "{TOP}: warning: this repo's .visdom/tracing.toml pins '{config_url}', but you \
710 are logged in to '{file_url}' — using '{file_url}'. Run `{TOP} login --server-url \
711 {config_url}` to use the repo's instance, or remove `server_url` from \
712 .visdom/tracing.toml to silence this."
713 )
714}
715
716fn server_mismatch_error(file_url: &str, target: &str) -> Box<dyn std::error::Error> {
733 format!(
734 "refusing to use the saved credentials: the credentials file is for '{file_url}', but \
735 this command is targeting '{target}'. A credential issued by one Visdom instance \
736 must not be sent to another.\n\
737 Either unset {ENV}_SERVER_URL to use '{file_url}', or run `{TOP} login \
738 --server-url {target}`. If '{target}' is the same instance reached through a different \
739 address (e.g. a port-forward), set {ENV}_API_KEY to a `tvk_` key for it instead."
740 )
741 .into()
742}
743
744#[cfg(test)]
745mod tests {
746 use super::*;
747
748 fn with_credentials_file(
753 body: &str,
754 ) -> (
755 tempfile::TempDir,
756 tokio::sync::MutexGuard<'static, ()>,
757 crate::test_helpers::EnvVarGuard,
758 ) {
759 let env_lock = crate::test_helpers::lock_env_mutation_sync();
760 let dir = tempfile::tempdir().unwrap();
761 let mut guard = crate::test_helpers::EnvVarGuard::new();
762 guard.set("XDG_CONFIG_HOME", dir.path());
763 let creds_dir = dir.path().join("visdom");
764 fs::create_dir_all(&creds_dir).unwrap();
765 fs::write(creds_dir.join("credentials.json"), body).unwrap();
766 (dir, env_lock, guard)
767 }
768
769 const NOW: i64 = 1_800_000_000;
772
773 fn write_keycloak_file(dir: &std::path::Path, server_url: &str, issuer: &str, expires_at: i64) {
775 let creds_dir = dir.join("visdom");
776 fs::create_dir_all(&creds_dir).unwrap();
777 fs::write(
778 creds_dir.join("credentials.json"),
779 format!(
780 r#"{{"server_url":"{server_url}","email":"a@b.com","auth":{{"issuer":"{issuer}","client_id":"tracing-cli","refresh_token":"old-rt","access_token":"old-at","access_expires_at":{expires_at}}}}}"#
781 ),
782 )
783 .unwrap();
784 }
785
786 type ResolveFixture = (
792 tempfile::TempDir,
793 tokio::sync::MutexGuard<'static, ()>,
794 crate::test_helpers::EnvVarGuard,
795 );
796
797 fn resolve_fixture_with(file_body: Option<&str>, env_url: Option<&str>) -> ResolveFixture {
802 let env_lock = crate::test_helpers::lock_env_mutation_sync();
803 let dir = tempfile::tempdir().unwrap();
804 let mut guard = crate::test_helpers::EnvVarGuard::new();
805 guard.set("XDG_CONFIG_HOME", dir.path());
806 guard.remove("TRACEVAULT_API_KEY");
809 match env_url {
810 Some(u) => guard.set("TRACEVAULT_SERVER_URL", u),
811 None => guard.remove("TRACEVAULT_SERVER_URL"),
812 }
813 if let Some(body) = file_body {
814 let creds_dir = dir.path().join("visdom");
815 fs::create_dir_all(&creds_dir).unwrap();
816 fs::write(creds_dir.join("credentials.json"), body).unwrap();
817 }
818 (dir, env_lock, guard)
819 }
820
821 fn resolve_fixture(file_server_url: &str, env_url: Option<&str>) -> ResolveFixture {
823 let fixture = resolve_fixture_with(None, env_url);
824 write_keycloak_file(
825 fixture.0.path(),
826 file_server_url,
827 "https://idp.test/realms/v",
828 NOW + 3600,
829 );
830 fixture
831 }
832
833 fn resolve_fixture_api_key(file_server_url: &str, env_url: Option<&str>) -> ResolveFixture {
835 resolve_fixture_with(
836 Some(&format!(
837 r#"{{"server_url":"{file_server_url}","token":"tvk_from_file","email":"a@b.com"}}"#
838 )),
839 env_url,
840 )
841 }
842
843 #[test]
852 fn a_mismatched_server_url_refuses_either_kind_of_file_credential() {
853 for kind in ["keycloak session", "api key"] {
854 let (dir, _lock, _guard) = if kind == "keycloak session" {
855 resolve_fixture(
856 "https://instance-b.example.com",
857 Some("https://instance-a.example.com"),
858 )
859 } else {
860 resolve_fixture_api_key(
861 "https://instance-b.example.com",
862 Some("https://instance-a.example.com"),
863 )
864 };
865
866 let err = resolve_credentials(dir.path())
867 .expect_err("a credential for another instance must not be handed out");
868 let msg = err.to_string();
869 assert!(
872 msg.contains("https://instance-b.example.com"),
873 "{kind}: must name the file's server: {msg}"
874 );
875 assert!(
876 msg.contains("https://instance-a.example.com"),
877 "{kind}: must name the targeted server: {msg}"
878 );
879 assert!(msg.contains("TRACEVAULT_SERVER_URL"), "{kind}: {msg}");
883 assert!(msg.contains("tracevault login"), "{kind}: {msg}");
884 assert!(msg.contains("TRACEVAULT_API_KEY"), "{kind}: {msg}");
885 assert!(
886 !msg.contains("tvk_from_file"),
887 "{kind}: the error must not echo the credential: {msg}"
888 );
889 }
890 }
891
892 #[test]
899 fn a_matching_server_url_modulo_trailing_slash_still_resolves() {
900 let (dir, _lock, _guard) =
901 resolve_fixture("https://example.com/", Some("https://example.com"));
902
903 let (url, credential) =
904 resolve_credentials(dir.path()).expect("a trailing slash is not a different instance");
905 assert_eq!(url.as_deref(), Some("https://example.com"));
906 assert!(matches!(credential, Some(Credential::Keycloak(_))));
907 }
908
909 #[test]
912 fn no_env_override_resolves_the_files_session_unchanged() {
913 let (dir, _lock, _guard) = resolve_fixture("https://example.com", None);
914
915 let (url, credential) = resolve_credentials(dir.path()).expect("the normal case must work");
916 assert_eq!(url.as_deref(), Some("https://example.com"));
917 assert!(matches!(credential, Some(Credential::Keycloak(_))));
918 }
919
920 #[test]
925 fn a_config_api_key_containing_equals_signs_is_not_truncated() {
926 let (dir, _lock, _guard) = resolve_fixture_with(None, None);
927 let config_dir = dir.path().join(".visdom");
928 fs::create_dir_all(&config_dir).unwrap();
929 fs::write(
930 config_dir.join("tracing.toml"),
931 "server_url = \"https://example.com\"\napi_key = \"tvk_YWJjZA==\"\n",
932 )
933 .unwrap();
934
935 let (url, credential) = resolve_credentials(dir.path()).unwrap();
936 assert_eq!(url.as_deref(), Some("https://example.com"));
937 match credential {
938 Some(Credential::ApiKey(k)) => assert_eq!(
939 k, "tvk_YWJjZA==",
940 "the key must survive verbatim, `=` padding and all"
941 ),
942 other => panic!("expected the config API key, got {other:?}"),
943 }
944 }
945
946 #[test]
950 fn a_config_lookalike_field_is_not_mistaken_for_the_real_one() {
951 let (dir, _lock, _guard) = resolve_fixture_with(None, None);
952 let config_dir = dir.path().join(".visdom");
953 fs::create_dir_all(&config_dir).unwrap();
954 fs::write(
955 config_dir.join("tracing.toml"),
956 "server_url = \"https://real.example.com\"\n\
957 [user_context]\n\
958 enable = false\n",
959 )
960 .unwrap();
961
962 let (url, credential) = resolve_credentials(dir.path()).unwrap();
963 assert_eq!(url.as_deref(), Some("https://real.example.com"));
964 assert!(
965 credential.is_none(),
966 "no api_key is configured anywhere, so there is no credential"
967 );
968 }
969
970 #[test]
975 fn a_config_api_key_is_unaffected_by_a_mismatched_server_url() {
976 let (dir, _lock, _guard) =
977 resolve_fixture_with(None, Some("https://instance-a.example.com"));
978 let config_dir = dir.path().join(".visdom");
979 fs::create_dir_all(&config_dir).unwrap();
980 fs::write(
981 config_dir.join("tracing.toml"),
982 "server_url = \"https://instance-b.example.com\"\napi_key = \"tvk_from_config\"\n",
983 )
984 .unwrap();
985
986 let (url, credential) = resolve_credentials(dir.path())
987 .expect("a config-supplied key must never be second-guessed");
988 assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
989 match credential {
990 Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_from_config"),
991 other => panic!("expected the config API key, got {other:?}"),
992 }
993 }
994
995 #[test]
998 fn an_env_api_key_is_unaffected_by_a_mismatched_server_url() {
999 let (dir, _lock, mut guard) = resolve_fixture(
1000 "https://instance-b.example.com",
1001 Some("https://instance-a.example.com"),
1002 );
1003 guard.set("TRACEVAULT_API_KEY", "tvk_abc");
1004
1005 let (url, credential) = resolve_credentials(dir.path())
1006 .expect("an explicitly supplied API key must never be second-guessed");
1007 assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
1008 match credential {
1009 Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_abc"),
1010 other => panic!("expected the env API key, got {other:?}"),
1011 }
1012 }
1013
1014 fn write_project_config(root: &std::path::Path, body: &str) {
1020 let config_dir = root.join(".visdom");
1021 fs::create_dir_all(&config_dir).unwrap();
1022 fs::write(config_dir.join("tracing.toml"), body).unwrap();
1023 }
1024
1025 #[test]
1026 fn a_config_url_differing_from_the_files_is_a_conflict() {
1027 assert_eq!(
1028 config_url_conflict(
1029 Some("https://pinned.example.com"),
1030 Some("https://login.example.com"),
1031 false
1032 ),
1033 Some(("https://login.example.com", "https://pinned.example.com")),
1034 "the file's URL is returned first, as the one actually used"
1035 );
1036 }
1037
1038 #[test]
1043 fn a_trailing_slash_is_not_a_conflict() {
1044 assert_eq!(
1045 config_url_conflict(
1046 Some("https://example.com"),
1047 Some("https://example.com/"),
1048 false
1049 ),
1050 None
1051 );
1052 }
1053
1054 #[test]
1057 fn an_env_server_url_suppresses_the_conflict() {
1058 assert_eq!(
1059 config_url_conflict(
1060 Some("https://pinned.example.com"),
1061 Some("https://login.example.com"),
1062 true
1063 ),
1064 None
1065 );
1066 }
1067
1068 #[test]
1070 fn a_missing_side_is_never_a_conflict() {
1071 assert_eq!(
1072 config_url_conflict(None, Some("https://login.example.com"), false),
1073 None
1074 );
1075 assert_eq!(
1076 config_url_conflict(Some("https://pinned.example.com"), None, false),
1077 None
1078 );
1079 }
1080
1081 #[test]
1084 fn the_warning_names_both_urls_and_the_winner() {
1085 let msg = config_mismatch_warning("https://login.example.com", "http://localhost:8080");
1086 assert!(
1087 msg.contains("http://localhost:8080"),
1088 "must name the pin: {msg}"
1089 );
1090 assert!(
1091 msg.contains("https://login.example.com"),
1092 "must name the login: {msg}"
1093 );
1094 assert!(
1095 msg.contains("tracing.toml"),
1096 "must name where the pin lives: {msg}"
1097 );
1098 assert!(
1099 msg.contains("tracevault login"),
1100 "must name the way forward: {msg}"
1101 );
1102 }
1103
1104 #[test]
1110 fn a_conflicting_config_url_still_resolves_to_the_files_instance() {
1111 for kind in ["keycloak session", "api key"] {
1112 let (dir, _lock, _guard) = if kind == "keycloak session" {
1113 resolve_fixture("https://instance-b.example.com", None)
1114 } else {
1115 resolve_fixture_api_key("https://instance-b.example.com", None)
1116 };
1117 write_project_config(dir.path(), "server_url = \"https://attacker.invalid\"\n");
1118
1119 let (url, credential) = resolve_credentials(dir.path())
1120 .expect("a conflicting config must warn, never break the command");
1121 assert_eq!(
1122 url.as_deref(),
1123 Some("https://instance-b.example.com"),
1124 "{kind}: the config URL must stay inert"
1125 );
1126 assert!(credential.is_some(), "{kind}: the credential must survive");
1127 }
1128 }
1129
1130 #[test]
1134 fn a_conflicting_config_with_its_own_key_still_resolves_to_the_file() {
1135 let (dir, _lock, _guard) = resolve_fixture("https://instance-b.example.com", None);
1136 write_project_config(
1137 dir.path(),
1138 "server_url = \"https://instance-a.example.com\"\napi_key = \"tvk_from_config\"\n",
1139 );
1140
1141 let (url, credential) = resolve_credentials(dir.path()).unwrap();
1142 assert_eq!(url.as_deref(), Some("https://instance-b.example.com"));
1143 assert!(
1144 matches!(credential, Some(Credential::Keycloak(_))),
1145 "the file's session wins; the config key is never reached"
1146 );
1147 }
1148
1149 #[test]
1152 fn a_config_server_url_is_used_when_there_is_no_credentials_file() {
1153 let (dir, _lock, _guard) = resolve_fixture_with(None, None);
1154 write_project_config(
1155 dir.path(),
1156 "server_url = \"https://instance-a.example.com\"\n",
1157 );
1158
1159 let (url, _credential) = resolve_credentials(dir.path()).unwrap();
1160 assert_eq!(url.as_deref(), Some("https://instance-a.example.com"));
1161 }
1162
1163 #[test]
1176 fn load_old_credentials_with_org_slug_still_parses() {
1177 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1178 let dir = tempfile::tempdir().unwrap();
1179 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1180 _guard.set("XDG_CONFIG_HOME", dir.path());
1181
1182 let creds_dir = dir.path().join("visdom");
1183 fs::create_dir_all(&creds_dir).unwrap();
1184 fs::write(
1185 creds_dir.join("credentials.json"),
1186 r#"{"server_url":"https://example.com","token":"tok","email":"a@b.com","org_slug":"x"}"#,
1187 )
1188 .unwrap();
1189
1190 let creds =
1191 Credentials::load().expect("old credentials.json with org_slug must still parse");
1192 assert_eq!(creds.server_url, "https://example.com");
1193 assert_eq!(creds.token.as_deref(), Some("tok"));
1194 assert_eq!(creds.email, "a@b.com");
1195 }
1196
1197 #[test]
1200 fn flat_token_file_loads_as_api_key() {
1201 let (_dir, _lock, _guard) = with_credentials_file(
1202 r#"{"server_url":"https://example.com","token":"tvk_abc","email":"a@b.com"}"#,
1203 );
1204 let creds = Credentials::load().expect("flat credentials file must load");
1205 match creds.credential() {
1206 Some(Credential::ApiKey(k)) => assert_eq!(k, "tvk_abc"),
1207 other => panic!("expected an ApiKey credential, got {other:?}"),
1208 }
1209 }
1210
1211 #[test]
1213 fn file_with_auth_object_loads_as_keycloak() {
1214 let (_dir, _lock, _guard) = with_credentials_file(
1215 r#"{
1216 "server_url":"https://example.com",
1217 "email":"a@b.com",
1218 "auth":{
1219 "issuer":"https://idp.test/realms/visdom",
1220 "client_id":"tracing-cli",
1221 "refresh_token":"rt",
1222 "access_token":"at",
1223 "access_expires_at":1893456000
1224 }
1225 }"#,
1226 );
1227 let creds = Credentials::load().expect("keycloak credentials file must load");
1228 match creds.credential() {
1229 Some(Credential::Keycloak(s)) => {
1230 assert_eq!(s.issuer, "https://idp.test/realms/visdom");
1231 assert_eq!(s.client_id, "tracing-cli");
1232 assert_eq!(s.refresh_token, "rt");
1233 assert_eq!(s.access_token, "at");
1234 assert_eq!(s.access_expires_at, 1_893_456_000);
1235 }
1236 other => panic!("expected a Keycloak credential, got {other:?}"),
1237 }
1238 }
1239
1240 #[test]
1241 fn no_token_and_no_auth_yields_no_credential() {
1242 let (_dir, _lock, _guard) =
1243 with_credentials_file(r#"{"server_url":"https://example.com","email":"a@b.com"}"#);
1244 let creds = Credentials::load().unwrap();
1245 assert!(creds.credential().is_none());
1246 }
1247
1248 #[test]
1251 fn needs_refresh_only_inside_the_sixty_second_window() {
1252 let session = KeycloakSession {
1253 issuer: "https://idp.test/realms/visdom".into(),
1254 client_id: "tracing-cli".into(),
1255 refresh_token: "rt".into(),
1256 access_token: "at".into(),
1257 access_expires_at: 1_000_000,
1258 };
1259 assert!(!session.needs_refresh(1_000_000 - 61));
1260 assert!(!session.needs_refresh(1_000_000 - 60));
1261 assert!(session.needs_refresh(1_000_000 - 59));
1262 assert!(session.needs_refresh(1_000_000));
1263 assert!(session.needs_refresh(1_000_001));
1264 }
1265
1266 #[test]
1267 fn apply_keeps_the_previous_refresh_token_when_none_is_returned() {
1268 let mut session = KeycloakSession {
1269 issuer: "i".into(),
1270 client_id: "c".into(),
1271 refresh_token: "old-rt".into(),
1272 access_token: "old-at".into(),
1273 access_expires_at: 10,
1274 };
1275 session.apply(
1276 &TokenSet {
1277 access_token: "new-at".into(),
1278 refresh_token: None,
1279 expires_in: 300,
1280 },
1281 1_000,
1282 );
1283 assert_eq!(session.access_token, "new-at");
1284 assert_eq!(session.refresh_token, "old-rt");
1285 assert_eq!(session.access_expires_at, 1_300);
1286
1287 session.apply(
1288 &TokenSet {
1289 access_token: "newer-at".into(),
1290 refresh_token: Some("new-rt".into()),
1291 expires_in: 60,
1292 },
1293 2_000,
1294 );
1295 assert_eq!(session.refresh_token, "new-rt");
1296 assert_eq!(session.access_expires_at, 2_060);
1297 }
1298
1299 #[test]
1302 fn save_round_trips_keycloak_and_is_owner_only() {
1303 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1304 let dir = tempfile::tempdir().unwrap();
1305 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1306 _guard.set("XDG_CONFIG_HOME", dir.path());
1307
1308 let session = KeycloakSession {
1309 issuer: "https://idp.test/realms/visdom".into(),
1310 client_id: "tracing-cli".into(),
1311 refresh_token: "rt".into(),
1312 access_token: "at".into(),
1313 access_expires_at: 42,
1314 };
1315 Credentials::keycloak("https://example.com", "a@b.com".into(), session)
1316 .save()
1317 .unwrap();
1318
1319 let raw = fs::read_to_string(Credentials::path().unwrap()).unwrap();
1320 assert!(
1321 !raw.contains("\"token\""),
1322 "a Keycloak file must not carry an api-key `token` field: {raw}"
1323 );
1324 let reloaded = Credentials::load().unwrap();
1325 assert!(matches!(
1326 reloaded.credential(),
1327 Some(Credential::Keycloak(_))
1328 ));
1329
1330 #[cfg(unix)]
1331 {
1332 use std::os::unix::fs::PermissionsExt;
1333 let mode = fs::metadata(Credentials::path().unwrap())
1334 .unwrap()
1335 .permissions()
1336 .mode();
1337 assert_eq!(mode & 0o777, 0o600, "credentials must be owner-only");
1338 }
1339
1340 let leftovers: Vec<_> = fs::read_dir(dir.path().join("visdom"))
1342 .unwrap()
1343 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1344 .filter(|n| n != "credentials.json")
1345 .collect();
1346 assert!(
1347 leftovers.is_empty(),
1348 "temp files left behind: {leftovers:?}"
1349 );
1350 }
1351
1352 #[cfg(unix)]
1361 #[test]
1362 fn a_stale_world_readable_temp_file_cannot_relax_the_credential_mode() {
1363 use std::os::unix::fs::PermissionsExt;
1364
1365 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1366 let dir = tempfile::tempdir().unwrap();
1367 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1368 _guard.set("XDG_CONFIG_HOME", dir.path());
1369
1370 let creds_dir = dir.path().join("visdom");
1371 fs::create_dir_all(&creds_dir).unwrap();
1372 let stale = creds_dir.join(format!(".credentials.json.tmp{}", std::process::id()));
1373 fs::write(&stale, "leftover from a crashed run").unwrap();
1374 fs::set_permissions(&stale, fs::Permissions::from_mode(0o644)).unwrap();
1375
1376 Credentials::keycloak(
1377 "https://example.com",
1378 "a@b.com".into(),
1379 KeycloakSession {
1380 issuer: "i".into(),
1381 client_id: "c".into(),
1382 refresh_token: "rt".into(),
1383 access_token: "at".into(),
1384 access_expires_at: 1,
1385 },
1386 )
1387 .save()
1388 .expect("a stale temp file must not fail the save");
1389
1390 let mode = fs::metadata(Credentials::path().unwrap())
1391 .unwrap()
1392 .permissions()
1393 .mode();
1394 assert_eq!(
1395 mode & 0o777,
1396 0o600,
1397 "credentials.json inherited the stale temp file's mode"
1398 );
1399 let stale_contents = fs::read_to_string(&stale).unwrap();
1401 assert!(
1402 !stale_contents.contains("rt"),
1403 "secrets were written into the pre-existing temp file: {stale_contents}"
1404 );
1405 }
1406
1407 #[test]
1411 fn repeated_saves_in_one_process_do_not_collide() {
1412 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1413 let dir = tempfile::tempdir().unwrap();
1414 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1415 _guard.set("XDG_CONFIG_HOME", dir.path());
1416
1417 let session = KeycloakSession {
1418 issuer: "i".into(),
1419 client_id: "c".into(),
1420 refresh_token: "rt".into(),
1421 access_token: "at".into(),
1422 access_expires_at: 1,
1423 };
1424 for i in 0..5 {
1425 Credentials::keycloak(
1426 "https://example.com",
1427 format!("a{i}@b.com"),
1428 session.clone(),
1429 )
1430 .save()
1431 .unwrap_or_else(|e| panic!("save #{i} failed: {e}"));
1432 }
1433 assert_eq!(Credentials::load().unwrap().email, "a4@b.com");
1434
1435 let leftovers: Vec<_> = fs::read_dir(dir.path().join("visdom"))
1437 .unwrap()
1438 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1439 .filter(|n| n != "credentials.json")
1440 .collect();
1441 assert!(
1442 leftovers.is_empty(),
1443 "temp files left behind: {leftovers:?}"
1444 );
1445 }
1446
1447 #[test]
1452 fn delete_also_removes_leftover_temp_files() {
1453 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1454 let dir = tempfile::tempdir().unwrap();
1455 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1456 _guard.set("XDG_CONFIG_HOME", dir.path());
1457
1458 let creds_dir = dir.path().join("visdom");
1459 fs::create_dir_all(&creds_dir).unwrap();
1460 fs::write(creds_dir.join("credentials.json"), "{}").unwrap();
1461 let old_shape = creds_dir.join(".credentials.json.tmp4242");
1463 let new_shape = creds_dir.join(".credentials.json.tmp4242.0.123");
1464 fs::write(&old_shape, r#"{"auth":{"refresh_token":"still-live-rt"}}"#).unwrap();
1465 fs::write(&new_shape, r#"{"auth":{"refresh_token":"still-live-rt"}}"#).unwrap();
1466
1467 Credentials::delete().unwrap();
1468
1469 assert!(!Credentials::path().unwrap().exists());
1470 let remaining: Vec<_> = fs::read_dir(&creds_dir)
1471 .unwrap()
1472 .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
1473 .collect();
1474 assert!(
1475 remaining.is_empty(),
1476 "logout left credential material on disk: {remaining:?}"
1477 );
1478 }
1479
1480 #[test]
1484 fn save_sweeps_only_old_temp_files() {
1485 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1486 let dir = tempfile::tempdir().unwrap();
1487 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1488 _guard.set("XDG_CONFIG_HOME", dir.path());
1489
1490 let creds_dir = dir.path().join("visdom");
1491 fs::create_dir_all(&creds_dir).unwrap();
1492 let fresh = creds_dir.join(".credentials.json.tmp999.0.1");
1493 fs::write(&fresh, "in flight in another process").unwrap();
1494
1495 Credentials::keycloak(
1496 "https://example.com",
1497 "a@b.com".into(),
1498 KeycloakSession {
1499 issuer: "i".into(),
1500 client_id: "c".into(),
1501 refresh_token: "rt".into(),
1502 access_token: "at".into(),
1503 access_expires_at: 1,
1504 },
1505 )
1506 .save()
1507 .unwrap();
1508
1509 assert!(
1510 fresh.exists(),
1511 "a just-created temp file may still be in flight elsewhere; sweeping it would break \
1512 that process's rename"
1513 );
1514 }
1515
1516 #[test]
1522 fn path_fails_instead_of_inventing_a_relative_home() {
1523 let err = Credentials::path_in(None)
1524 .expect_err("no config directory must not yield a guessed path");
1525 let msg = err.to_string();
1526 assert!(
1527 msg.contains("XDG_CONFIG_HOME") && msg.contains("HOME"),
1528 "the error must name the variables to set: {msg}"
1529 );
1530 assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
1531
1532 let shown = Credentials::path_for_display();
1535 assert!(
1536 !shown.starts_with('~'),
1537 "a `~`-prefixed path must never be presented as a location: {shown}"
1538 );
1539
1540 let dir = tempfile::tempdir().unwrap();
1542 assert_eq!(
1543 Credentials::path_in(Some(dir.path().to_path_buf())).unwrap(),
1544 dir.path().join("visdom").join("credentials.json")
1545 );
1546 }
1547
1548 #[test]
1554 fn keycloak_preserves_an_existing_api_key_for_the_same_server() {
1555 let (_dir, _lock, _guard) = with_credentials_file(
1558 r#"{"server_url":"https://example.com/","token":"tvk_precious","email":"old@b.com"}"#,
1559 );
1560
1561 Credentials::keycloak(
1562 "https://example.com",
1563 "new@b.com".into(),
1564 KeycloakSession {
1565 issuer: "i".into(),
1566 client_id: "c".into(),
1567 refresh_token: "rt".into(),
1568 access_token: "at".into(),
1569 access_expires_at: 1,
1570 },
1571 )
1572 .save()
1573 .unwrap();
1574
1575 let reloaded = Credentials::load().unwrap();
1576 assert_eq!(
1577 reloaded.token.as_deref(),
1578 Some("tvk_precious"),
1579 "login destroyed an API key it did not come to replace"
1580 );
1581 assert_eq!(reloaded.email, "new@b.com");
1582 assert!(matches!(
1584 reloaded.credential(),
1585 Some(Credential::Keycloak(_))
1586 ));
1587 }
1588
1589 #[test]
1593 fn keycloak_does_not_carry_over_another_servers_api_key() {
1594 let (_dir, _lock, _guard) = with_credentials_file(
1595 r#"{"server_url":"https://instance-b.example.com","token":"tvk_for_b","email":"b@b.com"}"#,
1596 );
1597
1598 Credentials::keycloak(
1599 "https://instance-a.example.com",
1600 "a@b.com".into(),
1601 KeycloakSession {
1602 issuer: "i".into(),
1603 client_id: "c".into(),
1604 refresh_token: "rt".into(),
1605 access_token: "at".into(),
1606 access_expires_at: 1,
1607 },
1608 )
1609 .save()
1610 .unwrap();
1611
1612 let reloaded = Credentials::load().unwrap();
1613 assert_eq!(
1614 reloaded.token, None,
1615 "another instance's key must not be moved into this instance's file"
1616 );
1617 assert_eq!(reloaded.server_url, "https://instance-a.example.com");
1618 }
1619
1620 #[test]
1623 fn persist_session_preserves_other_fields() {
1624 let (_dir, _lock, _guard) = with_credentials_file(
1625 r#"{
1626 "server_url":"https://example.com",
1627 "email":"a@b.com",
1628 "auth":{"issuer":"i","client_id":"c","refresh_token":"rt","access_token":"at","access_expires_at":1}
1629 }"#,
1630 );
1631 let mut session = match Credentials::load().unwrap().credential() {
1632 Some(Credential::Keycloak(s)) => s,
1633 other => panic!("expected Keycloak, got {other:?}"),
1634 };
1635 session.apply(
1636 &TokenSet {
1637 access_token: "at2".into(),
1638 refresh_token: Some("rt2".into()),
1639 expires_in: 300,
1640 },
1641 1_000,
1642 );
1643 Credentials::persist_session("https://example.com", &session).unwrap();
1644
1645 let reloaded = Credentials::load().unwrap();
1646 assert_eq!(reloaded.email, "a@b.com");
1647 assert_eq!(reloaded.server_url, "https://example.com");
1648 let auth = reloaded.auth.unwrap();
1649 assert_eq!(auth.access_token, "at2");
1650 assert_eq!(auth.refresh_token, "rt2");
1651 assert_eq!(auth.access_expires_at, 1_300);
1652 }
1653
1654 #[test]
1658 fn persist_session_leaves_another_servers_file_alone() {
1659 let original = r#"{"server_url":"https://instance-b.example.com","email":"b@b.com","auth":{"issuer":"i","client_id":"c","refresh_token":"b-rt","access_token":"b-at","access_expires_at":99}}"#;
1660 let (_dir, _lock, _guard) = with_credentials_file(original);
1661
1662 let a_session = KeycloakSession {
1663 issuer: "i".into(),
1664 client_id: "c".into(),
1665 refresh_token: "a-rt".into(),
1666 access_token: "a-at".into(),
1667 access_expires_at: 1_234,
1668 };
1669 Credentials::persist_session("https://instance-a.example.com", &a_session)
1670 .expect("a foreign file is a skip, not an error");
1671
1672 let after = fs::read_to_string(Credentials::path().unwrap()).unwrap();
1673 assert_eq!(after, original, "another server's file was overwritten");
1674
1675 fs::write(
1681 Credentials::path().unwrap(),
1682 r#"{"server_url":"https://instance-a.example.com/","email":"a@b.com","auth":{"issuer":"i","client_id":"c","refresh_token":"old","access_token":"old","access_expires_at":1}}"#,
1683 )
1684 .unwrap();
1685 Credentials::persist_session("https://instance-a.example.com", &a_session).unwrap();
1686 let auth = Credentials::load().unwrap().auth.unwrap();
1687 assert_eq!(
1688 auth.access_token, "a-at",
1689 "a trailing slash must not block a legitimate persist"
1690 );
1691 }
1692
1693 #[test]
1699 fn same_server_normalises_trailing_slashes_and_whitespace() {
1700 assert!(same_server(
1701 "https://x.example.com",
1702 "https://x.example.com/"
1703 ));
1704 assert!(same_server(
1705 " https://x.example.com/ ",
1706 "https://x.example.com"
1707 ));
1708 assert!(!same_server(
1709 "https://x.example.com",
1710 "https://y.example.com"
1711 ));
1712 assert!(!same_server(
1714 "https://x.example.com",
1715 "https://x.example.com/tv"
1716 ));
1717 }
1718
1719 #[test]
1720 fn persist_session_on_a_missing_file_is_not_an_error() {
1721 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1722 let dir = tempfile::tempdir().unwrap();
1723 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1724 _guard.set("XDG_CONFIG_HOME", dir.path());
1725
1726 let session = KeycloakSession {
1727 issuer: "i".into(),
1728 client_id: "c".into(),
1729 refresh_token: "rt".into(),
1730 access_token: "at".into(),
1731 access_expires_at: 1,
1732 };
1733 Credentials::persist_session("https://example.com", &session)
1734 .expect("a logged-out user must not turn a refresh into a hard error");
1735 assert!(
1736 !Credentials::path().unwrap().exists(),
1737 "persist_session must not resurrect a deleted credentials file"
1738 );
1739 }
1740
1741 #[test]
1742 fn debug_impls_redact_secrets() {
1743 let creds = Credentials {
1744 server_url: "https://example.com".into(),
1745 token: Some("tvk_secret".into()),
1746 email: "a@b".into(),
1747 auth: None,
1748 };
1749 let dbg = format!("{creds:?}");
1750 assert!(!dbg.contains("tvk_secret"), "api key leaked: {dbg}");
1751
1752 let creds = Credentials::keycloak(
1753 "https://example.com",
1754 "a@b".into(),
1755 KeycloakSession {
1756 issuer: "i".into(),
1757 client_id: "c".into(),
1758 refresh_token: "secret-rt".into(),
1759 access_token: "secret-at".into(),
1760 access_expires_at: 1,
1761 },
1762 );
1763 let dbg = format!("{creds:?}");
1764 assert!(!dbg.contains("secret-rt"), "refresh token leaked: {dbg}");
1765 assert!(!dbg.contains("secret-at"), "access token leaked: {dbg}");
1766 }
1767
1768 const LEGACY_LOGIN: &str = r#"{"server_url":"https://example.com","email":"a@b.com","auth":{"issuer":"i","client_id":"c","refresh_token":"rt","access_token":"at","access_expires_at":1}}"#;
1769
1770 fn legacy_login() -> (
1773 tempfile::TempDir,
1774 tokio::sync::MutexGuard<'static, ()>,
1775 crate::test_helpers::EnvVarGuard,
1776 ) {
1777 let env_lock = crate::test_helpers::lock_env_mutation_sync();
1778 let dir = tempfile::tempdir().unwrap();
1779 let mut guard = crate::test_helpers::EnvVarGuard::new();
1780 guard.set("XDG_CONFIG_HOME", dir.path());
1781 fs::create_dir_all(dir.path().join("tracevault")).unwrap();
1782 fs::write(dir.path().join("tracevault/credentials.json"), LEGACY_LOGIN).unwrap();
1783 (dir, env_lock, guard)
1784 }
1785
1786 #[test]
1787 fn a_legacy_login_is_read_and_a_refresh_stays_in_its_file() {
1788 let (dir, _lock, _guard) = legacy_login();
1789 let mut session = match Credentials::load().unwrap().credential() {
1790 Some(Credential::Keycloak(s)) => s,
1791 other => panic!("expected Keycloak, got {other:?}"),
1792 };
1793 session.apply(
1794 &TokenSet {
1795 access_token: "at2".into(),
1796 refresh_token: Some("rt2".into()),
1797 expires_in: 300,
1798 },
1799 1_000,
1800 );
1801 Credentials::persist_session("https://example.com", &session).unwrap();
1802
1803 let legacy = fs::read_to_string(dir.path().join("tracevault/credentials.json")).unwrap();
1805 assert!(legacy.contains("rt2"), "{legacy}");
1806 assert!(!dir.path().join("visdom/credentials.json").exists());
1807 assert_eq!(
1808 Credentials::load().unwrap().auth.unwrap().refresh_token,
1809 "rt2"
1810 );
1811 }
1812
1813 #[test]
1814 fn a_new_login_replaces_the_legacy_one() {
1815 let (dir, _lock, _guard) = legacy_login();
1816 let mut creds = Credentials::load().unwrap();
1817 creds.email = "new@b.com".into();
1818 creds.save().unwrap();
1819
1820 assert!(!dir.path().join("tracevault/credentials.json").exists());
1821 assert_eq!(
1822 Credentials::path().unwrap(),
1823 dir.path().join("visdom/credentials.json")
1824 );
1825 assert_eq!(Credentials::load().unwrap().email, "new@b.com");
1826 }
1827
1828 #[test]
1829 fn logging_out_forgets_the_legacy_login_too() {
1830 let (dir, _lock, _guard) = legacy_login();
1831 fs::write(
1832 dir.path().join("tracevault/.credentials.json.tmp1.0.1"),
1833 LEGACY_LOGIN,
1834 )
1835 .unwrap();
1836
1837 Credentials::delete().unwrap();
1838
1839 assert!(Credentials::load().is_none());
1840 let left: Vec<_> = fs::read_dir(dir.path().join("tracevault"))
1841 .unwrap()
1842 .map(|e| e.unwrap().file_name())
1843 .collect();
1844 assert!(left.is_empty(), "{left:?}");
1845 }
1846}