fix: preserve account data and validate CLI operations
This commit is contained in:
1 parent
22a3eebe78
commit
2b6750a971
11 files changed
+300
-119
No files matched your search
+55
-41
@@ -34,26 +34,36 @@ pub enum AuthResult {
|
||||
pub struct AccountStore {
|
||||
pub accounts: Vec<Account>,
|
||||
path: PathBuf,
|
||||
load_error: Option<String>,
|
||||
}
|
||||
|
||||
impl AccountStore {
|
||||
pub fn load() -> Self {
|
||||
let path = account_store_path();
|
||||
let accounts = match std::fs::read_to_string(&path) {
|
||||
Self::load_from(account_store_path())
|
||||
}
|
||||
|
||||
fn load_from(path: PathBuf) -> Self {
|
||||
let (accounts, load_error) = match std::fs::read_to_string(&path) {
|
||||
Ok(content) => match serde_json::from_str(&content) {
|
||||
Ok(accounts) => accounts,
|
||||
Ok(accounts) => (accounts, None),
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), e);
|
||||
Vec::new()
|
||||
(
|
||||
Vec::new(),
|
||||
Some(format!("Invalid accounts file {}: {e}", path.display())),
|
||||
)
|
||||
}
|
||||
},
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
tracing::debug!("No accounts file at {}", path.display());
|
||||
Vec::new()
|
||||
(Vec::new(), None)
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("Failed to read accounts file {}: {}", path.display(), e);
|
||||
Vec::new()
|
||||
(
|
||||
Vec::new(),
|
||||
Some(format!("Cannot read accounts file {}: {e}", path.display())),
|
||||
)
|
||||
}
|
||||
};
|
||||
tracing::debug!(
|
||||
@@ -61,36 +71,25 @@ impl AccountStore {
|
||||
accounts.len(),
|
||||
path.display()
|
||||
);
|
||||
Self { accounts, path }
|
||||
Self {
|
||||
accounts,
|
||||
path,
|
||||
load_error,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn save(&self) {
|
||||
if let Some(parent) = self.path.parent()
|
||||
&& let Err(e) = std::fs::create_dir_all(parent)
|
||||
{
|
||||
tracing::error!("Failed to create accounts directory: {}", e);
|
||||
return;
|
||||
}
|
||||
match serde_json::to_string_pretty(&self.accounts) {
|
||||
Ok(json) => {
|
||||
// this file holds microsoft refresh tokens: a torn write on
|
||||
// crash would permanently lock the user out, so write atomically.
|
||||
if let Err(e) = crate::storage::write_atomic(&self.path, json.as_bytes()) {
|
||||
tracing::error!(
|
||||
"Failed to write accounts file {}: {}",
|
||||
self.path.display(),
|
||||
e
|
||||
);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"Saved {} account(s) to {}",
|
||||
self.accounts.len(),
|
||||
self.path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(e) => tracing::error!("Failed to serialize accounts: {}", e),
|
||||
pub fn save(&self) -> std::io::Result<()> {
|
||||
if let Some(error) = &self.load_error {
|
||||
return Err(std::io::Error::other(error.clone()));
|
||||
}
|
||||
let json = serde_json::to_vec_pretty(&self.accounts).map_err(std::io::Error::other)?;
|
||||
crate::storage::write_atomic_private(&self.path, &json)?;
|
||||
tracing::debug!(
|
||||
"Saved {} account(s) to {}",
|
||||
self.accounts.len(),
|
||||
self.path.display()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn active_account(&self) -> Option<&Account> {
|
||||
@@ -103,25 +102,31 @@ impl AccountStore {
|
||||
.any(|account| account.account_type == AccountType::Microsoft)
|
||||
}
|
||||
|
||||
pub fn set_active(&mut self, index: usize) {
|
||||
pub fn set_active(&mut self, index: usize) -> std::io::Result<()> {
|
||||
let Some(account) = self.accounts.get(index) else {
|
||||
// out-of-range: leave the current selection untouched. marking
|
||||
// every account inactive here would break the single-active
|
||||
// invariant and orphan the store with no usable account.
|
||||
tracing::warn!("Tried to select missing account index {}", index);
|
||||
return;
|
||||
return Ok(());
|
||||
};
|
||||
let previous = self.accounts.clone();
|
||||
let username = account.username.clone();
|
||||
for (i, acc) in self.accounts.iter_mut().enumerate() {
|
||||
acc.active = i == index;
|
||||
}
|
||||
tracing::info!("Selected account '{}'", username);
|
||||
self.save();
|
||||
if let Err(error) = self.save() {
|
||||
self.accounts = previous;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// if an account with the same uuid already exists, replace it.
|
||||
// first account added auto-becomes active so there's always a selection.
|
||||
pub fn add(&mut self, account: Account) {
|
||||
pub fn add(&mut self, account: Account) -> std::io::Result<()> {
|
||||
let previous = self.accounts.clone();
|
||||
let uuid = &account.uuid;
|
||||
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
|
||||
// re-adding the currently active account must not drop the selection:
|
||||
@@ -141,14 +146,19 @@ impl AccountStore {
|
||||
account_type,
|
||||
username
|
||||
);
|
||||
self.save();
|
||||
if let Err(error) = self.save() {
|
||||
self.accounts = previous;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, index: usize) {
|
||||
pub fn remove(&mut self, index: usize) -> std::io::Result<()> {
|
||||
if index >= self.accounts.len() {
|
||||
tracing::warn!("Tried to remove missing account index {}", index);
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let previous = self.accounts.clone();
|
||||
let account = self.accounts.remove(index);
|
||||
tracing::info!(
|
||||
"Removed {:?} account '{}'",
|
||||
@@ -159,7 +169,11 @@ impl AccountStore {
|
||||
self.accounts[0].active = true;
|
||||
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username);
|
||||
}
|
||||
self.save();
|
||||
if let Err(error) = self.save() {
|
||||
self.accounts = previous;
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+11
-3
@@ -90,6 +90,9 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
|
||||
}
|
||||
|
||||
pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> {
|
||||
if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() {
|
||||
*slot = None;
|
||||
}
|
||||
let result: Arc<Mutex<Option<AuthResult>>> = Arc::new(Mutex::new(None));
|
||||
let result_clone = result.clone();
|
||||
|
||||
@@ -110,7 +113,12 @@ async fn run_full_auth_flow() -> AuthResult {
|
||||
Err(e) => return AuthResult::Error(e),
|
||||
};
|
||||
|
||||
exchange_and_build_account(&ms_access_token, ms_refresh_token.as_deref()).await
|
||||
let Some(refresh_token) = ms_refresh_token.as_deref() else {
|
||||
return AuthResult::Error(
|
||||
"Microsoft did not return a refresh token; try signing in again".to_owned(),
|
||||
);
|
||||
};
|
||||
exchange_and_build_account(&ms_access_token, Some(refresh_token)).await
|
||||
}
|
||||
|
||||
async fn exchange_and_build_account(
|
||||
@@ -158,8 +166,8 @@ async fn exchange_and_build_account(
|
||||
account_type: AccountType::Microsoft,
|
||||
active: false,
|
||||
refresh_token: ms_refresh_token.map(|s| s.to_owned()),
|
||||
cached_mc_token: None,
|
||||
cached_mc_token_expires_at: None,
|
||||
cached_mc_token: Some(mc_token.access_token().as_ref().to_owned()),
|
||||
cached_mc_token_expires_at: Some(chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+63
-26
@@ -8,6 +8,7 @@ impl AccountStore {
|
||||
Self {
|
||||
accounts: Vec::new(),
|
||||
path,
|
||||
load_error: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,6 +59,7 @@ fn make_store(dir: &std::path::Path) -> AccountStore {
|
||||
AccountStore {
|
||||
accounts: Vec::new(),
|
||||
path: dir.join("accounts.json"),
|
||||
load_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +79,7 @@ fn microsoft_account(name: &str) -> Account {
|
||||
fn store_add_first_becomes_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
assert!(store.accounts[0].active);
|
||||
}
|
||||
@@ -86,8 +88,8 @@ fn store_add_first_becomes_active() {
|
||||
fn store_add_second_stays_inactive() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
assert_eq!(store.accounts.len(), 2);
|
||||
assert!(store.accounts[0].active);
|
||||
assert!(!store.accounts[1].active);
|
||||
@@ -97,11 +99,11 @@ fn store_add_second_stays_inactive() {
|
||||
fn store_add_duplicate_uuid_replaces() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
let mut dup = create_offline_account("Alice");
|
||||
dup.username = "AliceRenamed".to_owned();
|
||||
dup.uuid = store.accounts[0].uuid.clone();
|
||||
store.add(dup);
|
||||
store.add(dup).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
assert_eq!(store.accounts[0].username, "AliceRenamed");
|
||||
}
|
||||
@@ -117,10 +119,10 @@ fn store_active_account_none_when_empty() {
|
||||
fn store_has_microsoft_account_when_one_exists() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Offline"));
|
||||
store.add(create_offline_account("Offline")).unwrap();
|
||||
assert!(!store.has_microsoft_account());
|
||||
|
||||
store.add(microsoft_account("Owner"));
|
||||
store.add(microsoft_account("Owner")).unwrap();
|
||||
assert!(store.has_microsoft_account());
|
||||
}
|
||||
|
||||
@@ -128,8 +130,8 @@ fn store_has_microsoft_account_when_one_exists() {
|
||||
fn store_active_account_returns_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
let active = store.active_account().unwrap();
|
||||
assert_eq!(active.username, "Alice");
|
||||
}
|
||||
@@ -138,9 +140,9 @@ fn store_active_account_returns_active() {
|
||||
fn store_set_active_changes_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.set_active(1);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.set_active(1).unwrap();
|
||||
assert!(!store.accounts[0].active);
|
||||
assert!(store.accounts[1].active);
|
||||
}
|
||||
@@ -149,9 +151,9 @@ fn store_set_active_changes_active() {
|
||||
fn store_set_active_out_of_bounds_keeps_selection() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.set_active(99);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.set_active(99).unwrap();
|
||||
assert!(
|
||||
store.accounts[0].active,
|
||||
"existing selection must survive a bad index"
|
||||
@@ -163,11 +165,11 @@ fn store_set_active_out_of_bounds_keeps_selection() {
|
||||
fn store_add_replacing_active_keeps_active() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
let mut dup = create_offline_account("Alice");
|
||||
dup.username = "AliceRenamed".to_owned();
|
||||
store.add(dup);
|
||||
store.add(dup).unwrap();
|
||||
assert!(
|
||||
store.accounts.iter().any(|a| a.active),
|
||||
"re-adding the active account must not orphan the selection"
|
||||
@@ -180,9 +182,9 @@ fn store_add_replacing_active_keeps_active() {
|
||||
fn store_remove_activates_first_remaining() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.remove(0);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.remove(0).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
assert_eq!(store.accounts[0].username, "Bob");
|
||||
assert!(store.accounts[0].active);
|
||||
@@ -192,8 +194,8 @@ fn store_remove_activates_first_remaining() {
|
||||
fn store_remove_out_of_bounds_noop() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.remove(5);
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.remove(5).unwrap();
|
||||
assert_eq!(store.accounts.len(), 1);
|
||||
}
|
||||
|
||||
@@ -201,9 +203,9 @@ fn store_remove_out_of_bounds_noop() {
|
||||
fn store_save_and_reload() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(create_offline_account("Alice"));
|
||||
store.add(create_offline_account("Bob"));
|
||||
store.save();
|
||||
store.add(create_offline_account("Alice")).unwrap();
|
||||
store.add(create_offline_account("Bob")).unwrap();
|
||||
store.save().unwrap();
|
||||
|
||||
let reloaded = AccountStore {
|
||||
accounts: serde_json::from_str(
|
||||
@@ -211,8 +213,43 @@ fn store_save_and_reload() {
|
||||
)
|
||||
.unwrap(),
|
||||
path: tmp.path().join("accounts.json"),
|
||||
load_error: None,
|
||||
};
|
||||
assert_eq!(reloaded.accounts.len(), 2);
|
||||
assert_eq!(reloaded.accounts[0].username, "Alice");
|
||||
assert!(reloaded.accounts[0].active);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn account_file_remains_owner_only_after_replacement() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let mut store = make_store(tmp.path());
|
||||
store.add(microsoft_account("Owner")).unwrap();
|
||||
let path = tmp.path().join("accounts.json");
|
||||
assert_eq!(
|
||||
std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
store.add(create_offline_account("Player")).unwrap();
|
||||
assert_eq!(
|
||||
std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
|
||||
0o600
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_account_file_cannot_be_overwritten_by_a_new_account() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("accounts.json");
|
||||
std::fs::write(&path, b"{broken credentials").unwrap();
|
||||
let mut store = AccountStore::load_from(path.clone());
|
||||
|
||||
assert!(store.add(microsoft_account("Owner")).is_err());
|
||||
assert!(store.accounts.is_empty());
|
||||
assert_eq!(std::fs::read(path).unwrap(), b"{broken credentials");
|
||||
}
|
||||
Reference in new issue
Block a user