fix: serialize account updates and isolate authentication attempts

This commit is contained in:
objz committed 2026-10-01 23:21:49 +02:00
1 parent 7362354109
commit eb436c2ab8
10 files changed
+297 -160

No files matched your search

+88 -58
View File
@@ -78,10 +78,15 @@ impl AccountStore {
}
}
pub fn save(&self) -> std::io::Result<()> {
pub fn check_loaded(&self) -> std::io::Result<()> {
if let Some(error) = &self.load_error {
return Err(std::io::Error::other(error.clone()));
}
Ok(())
}
fn save(&self) -> std::io::Result<()> {
self.check_loaded()?;
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!(
@@ -104,53 +109,33 @@ impl AccountStore {
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.
// Invalid selection must leave the active account intact.
tracing::warn!("Tried to select missing account index {}", index);
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);
if let Err(error) = self.save() {
self.accounts = previous;
return Err(error);
}
Ok(())
let uuid = account.uuid.clone();
self.update(|accounts| {
if !accounts.iter().any(|account| account.uuid == uuid) {
return Err(std::io::Error::other("Selected account no longer exists"));
}
for account in accounts {
account.active = account.uuid == uuid;
}
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) -> 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:
// the replacement takes over the old account's active flag.
let replaced_active = self.accounts.iter().any(|a| a.uuid == *uuid && a.active);
let account_type = account.account_type.clone();
let username = account.username.clone();
self.accounts.retain(|a| a.uuid != *uuid);
let mut account = account;
if self.accounts.is_empty() || replaced_active {
account.active = true;
}
self.accounts.push(account);
tracing::info!(
"{} {:?} account '{}'",
if replaced { "Updated" } else { "Added" },
account_type,
username
);
if let Err(error) = self.save() {
self.accounts = previous;
return Err(error);
}
Ok(())
self.update(|accounts| {
let replaced_active = accounts
.iter()
.any(|old| old.uuid == account.uuid && old.active);
accounts.retain(|old| old.uuid != account.uuid);
let mut account = account;
account.active = accounts.is_empty() || replaced_active;
accounts.push(account);
Ok(())
})
}
pub fn remove(&mut self, index: usize) -> std::io::Result<()> {
@@ -158,21 +143,68 @@ impl AccountStore {
tracing::warn!("Tried to remove missing account index {}", index);
return Ok(());
}
let previous = self.accounts.clone();
let account = self.accounts.remove(index);
tracing::info!(
"Removed {:?} account '{}'",
account.account_type,
account.username
);
if account.active && !self.accounts.is_empty() {
self.accounts[0].active = true;
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username);
let uuid = self.accounts[index].uuid.clone();
self.update(|accounts| {
let index = accounts
.iter()
.position(|account| account.uuid == uuid)
.ok_or_else(|| std::io::Error::other("Selected account no longer exists"))?;
let account = accounts.remove(index);
if account.active
&& let Some(first) = accounts.first_mut()
{
first.active = true;
}
Ok(())
})
}
pub fn update_credentials(
&mut self,
uuid: &str,
refresh: Option<String>,
token: &str,
expires: Option<i64>,
) -> std::io::Result<()> {
if refresh.is_none() && expires.is_none() {
return Ok(());
}
if let Err(error) = self.save() {
self.accounts = previous;
return Err(error);
self.update(|accounts| {
let account = accounts
.iter_mut()
.find(|account| account.uuid == uuid)
.ok_or_else(|| std::io::Error::other("Authenticated account no longer exists"))?;
if let Some(refresh) = refresh {
account.refresh_token = Some(refresh);
}
if let Some(expires) = expires {
account.cached_mc_token = Some(token.to_owned());
account.cached_mc_token_expires_at = Some(expires);
}
Ok(())
})
}
fn update(
&mut self,
update: impl FnOnce(&mut Vec<Account>) -> std::io::Result<()>,
) -> std::io::Result<()> {
use fs2::FileExt;
self.check_loaded()?;
if let Some(parent) = self.path.parent() {
std::fs::create_dir_all(parent)?;
}
let lock = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(self.path.with_extension("lock"))?;
lock.lock_exclusive()?;
let mut current = Self::load_from(self.path.clone());
current.check_loaded()?;
update(&mut current.accounts)?;
current.save()?;
self.accounts = current.accounts;
Ok(())
}
}
@@ -181,9 +213,7 @@ pub fn account_store_path() -> PathBuf {
crate::config::get_config_path().join("accounts.json")
}
// deterministic fake uuid from a username, formatted as uuid v3 with the proper
// version and variant bits set. not cryptographically meaningful, just needs to
// be consistent so the same offline name always maps to the same uuid.
// Keep the existing mapping so saved offline player data retains its identifier.
pub fn offline_uuid(username: &str) -> String {
use std::hash::{DefaultHasher, Hash, Hasher};
let mut hasher = DefaultHasher::new();
+1 -1
View File
@@ -8,4 +8,4 @@ pub use accounts::{
Account, AccountStore, AccountType, AuthResult, account_store_path, create_offline_account,
offline_uuid,
};
pub use oauth::{DEVICE_CODE_DISPLAY, DeviceCodeInfo, refresh_and_get_token, start_microsoft_auth};
pub use oauth::{DeviceCodeInfo, MicrosoftAuth, refresh_and_get_token, start_microsoft_auth};
+72 -51
View File
@@ -3,7 +3,7 @@
// device code auth is used because it works without a redirect URI, which is nice for a TUI.
use std::sync::{Arc, LazyLock, Mutex};
use std::sync::{Arc, Mutex};
use minecraft_msa_auth::MinecraftAuthorizationFlow;
use oauth2::basic::BasicClient;
@@ -20,7 +20,6 @@ const DEVICE_CODE_URL: &str = "https://login.microsoftonline.com/consumers/oauth
const MSA_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize";
const MSA_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";
const MC_PROFILE_URL: &str = "https://api.minecraftservices.com/minecraft/profile";
const MC_TOKEN_CACHE_TTL_SECS: i64 = 20 * 60 * 60;
const MC_TOKEN_CACHE_REFRESH_MARGIN_SECS: i64 = 5 * 60;
#[derive(Debug, Clone, PartialEq)]
@@ -48,10 +47,16 @@ fn normalize_profile_uuid(id: &str) -> Option<String> {
})
}
pub static DEVICE_CODE_DISPLAY: LazyLock<Arc<Mutex<Option<DeviceCodeInfo>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
#[derive(Default)]
pub struct MicrosoftAuth {
pub result: Arc<Mutex<Option<AuthResult>>>,
pub device_code: Arc<Mutex<Option<DeviceCodeInfo>>>,
}
async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
async fn run_full_oauth_flow(
http_client: &reqwest::Client,
display: &Mutex<Option<DeviceCodeInfo>>,
) -> Result<(String, Option<String>), String> {
let oauth_client = BasicClient::new(ClientId::new(CLIENT_ID.to_owned()))
.set_auth_uri(AuthUrl::new(MSA_AUTHORIZE_URL.to_owned()).map_err(|e| e.to_string())?)
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?)
@@ -59,17 +64,15 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
DeviceAuthorizationUrl::new(DEVICE_CODE_URL.to_owned()).map_err(|e| e.to_string())?,
);
let http_client = reqwest::Client::new();
let details: StandardDeviceAuthorizationResponse = oauth_client
.exchange_device_code()
.add_scope(Scope::new("XboxLive.signin".to_owned()))
.add_scope(Scope::new("offline_access".to_owned()))
.request_async(&http_client)
.request_async(http_client)
.await
.map_err(|e| format!("Device code request failed: {e}"))?;
if let Ok(mut slot) = DEVICE_CODE_DISPLAY.lock() {
if let Ok(mut slot) = display.lock() {
*slot = Some(DeviceCodeInfo {
user_code: details.user_code().secret().to_owned(),
verification_uri: details.verification_uri().to_string(),
@@ -79,7 +82,7 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
let token = oauth_client
.exchange_device_access_token(&details)
.request_async(&http_client, tokio::time::sleep, None)
.request_async(http_client, tokio::time::sleep, None)
.await
.map_err(|e| format!("Authentication failed: {e}"))?;
@@ -89,26 +92,29 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
Ok((ms_access_token, ms_refresh_token))
}
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();
pub fn start_microsoft_auth() -> MicrosoftAuth {
let auth = MicrosoftAuth::default();
let result_clone = auth.result.clone();
let device_code = auth.device_code.clone();
tokio::spawn(async move {
let outcome = run_full_auth_flow().await;
let outcome = run_full_auth_flow(&device_code).await;
if let Ok(mut slot) = result_clone.lock() {
*slot = Some(outcome);
crate::feedback::request_redraw();
}
});
result
auth
}
async fn run_full_auth_flow() -> AuthResult {
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow().await {
async fn run_full_auth_flow(display: &Mutex<Option<DeviceCodeInfo>>) -> AuthResult {
let http_client = match auth_http_client() {
Ok(client) => client,
Err(error) => return AuthResult::Error(error),
};
let (ms_access_token, ms_refresh_token) = match run_full_oauth_flow(&http_client, display).await
{
Ok(pair) => pair,
Err(e) => return AuthResult::Error(e),
};
@@ -118,41 +124,33 @@ async fn run_full_auth_flow() -> AuthResult {
"Microsoft did not return a refresh token; try signing in again".to_owned(),
);
};
exchange_and_build_account(&ms_access_token, Some(refresh_token)).await
exchange_and_build_account(&http_client, &ms_access_token, Some(refresh_token)).await
}
fn auth_http_client() -> Result<reqwest::Client, String> {
reqwest::Client::builder()
.connect_timeout(std::time::Duration::from_secs(30))
.timeout(std::time::Duration::from_secs(30))
.build()
.map_err(|error| format!("Could not create authentication HTTP client: {error}"))
}
async fn exchange_and_build_account(
client: &reqwest::Client,
ms_access_token: &str,
ms_refresh_token: Option<&str>,
) -> AuthResult {
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
let mc_flow = MinecraftAuthorizationFlow::new(client.clone());
let mc_token = match mc_flow.exchange_microsoft_token(ms_access_token).await {
Ok(t) => t,
Err(e) => return AuthResult::Error(format!("Minecraft auth failed: {e}")),
};
let client = reqwest::Client::new();
let profile_resp = match client
.get(MC_PROFILE_URL)
.header(
"Authorization",
format!("Bearer {}", mc_token.access_token().as_ref()),
)
.send()
.await
{
Ok(r) => r,
Err(e) => return AuthResult::Error(format!("Profile fetch failed: {e}")),
};
if !profile_resp.status().is_success() {
return AuthResult::Error("Account does not own Minecraft".to_owned());
}
let profile: McProfile = match profile_resp.json().await {
Ok(p) => p,
Err(e) => return AuthResult::Error(format!("Profile parse failed: {e}")),
};
let profile =
match fetch_profile(client, MC_PROFILE_URL, mc_token.access_token().as_ref()).await {
Ok(p) => p,
Err(e) => return AuthResult::Error(e),
};
// mojang returns uuids without dashes
let uuid = match normalize_profile_uuid(&profile.id) {
@@ -167,10 +165,35 @@ async fn exchange_and_build_account(
active: false,
refresh_token: ms_refresh_token.map(|s| s.to_owned()),
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),
cached_mc_token_expires_at: Some(
chrono::Utc::now().timestamp() + i64::from(mc_token.expires_in()),
),
})
}
async fn fetch_profile(
client: &reqwest::Client,
url: &str,
token: &str,
) -> Result<McProfile, String> {
let response = client
.get(url)
.bearer_auth(token)
.send()
.await
.map_err(|e| format!("Profile fetch failed: {e}"))?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Err("Account does not own Minecraft".to_owned());
}
let response = response
.error_for_status()
.map_err(|e| format!("Profile fetch failed: {e}"))?;
response
.json()
.await
.map_err(|e| format!("Profile parse failed: {e}"))
}
fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
let (Some(cached), Some(expires_at)) = (
account.cached_mc_token.as_deref(),
@@ -179,7 +202,7 @@ fn valid_cached_mc_token(account: &Account, now: i64) -> Option<&str> {
return None;
};
if now < expires_at - MC_TOKEN_CACHE_REFRESH_MARGIN_SECS {
if now < expires_at.saturating_sub(MC_TOKEN_CACHE_REFRESH_MARGIN_SECS) {
Some(cached)
} else {
None
@@ -214,7 +237,7 @@ pub async fn refresh_and_get_token(
)
.set_token_uri(TokenUrl::new(MSA_TOKEN_URL.to_owned()).map_err(|e| e.to_string())?);
let http_client = reqwest::Client::new();
let http_client = auth_http_client()?;
let token = oauth_client
.exchange_refresh_token(&RefreshToken::new(refresh.to_owned()))
@@ -227,15 +250,13 @@ pub async fn refresh_and_get_token(
let ms_access_token = token.access_token().secret().to_owned();
let new_refresh = token.refresh_token().map(|r| r.secret().to_owned());
let mc_flow = MinecraftAuthorizationFlow::new(reqwest::Client::new());
let mc_flow = MinecraftAuthorizationFlow::new(http_client);
let mc_token = mc_flow
.exchange_microsoft_token(&ms_access_token)
.await
.map_err(|e| format!("Minecraft auth failed: {e}"))?;
// minecraft-msa-auth does not expose this expiry here, so cache
// conservatively and refresh before the token gets close.
let expires_at = chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS;
let expires_at = chrono::Utc::now().timestamp() + i64::from(mc_token.expires_in());
Ok((
mc_token.access_token().as_ref().to_owned(),
+34 -3
View File
@@ -49,9 +49,6 @@ fn create_offline_account_fields() {
assert_eq!(acc.account_type, AccountType::Offline);
assert!(!acc.active);
assert!(acc.refresh_token.is_none());
// pin the uuid to the deterministic offline_uuid output so a regression
// in the uuid derivation (e.g. salt change) would fail this test, not
// just a non-empty-string check that any garbage would pass.
assert_eq!(acc.uuid, offline_uuid("TestPlayer"));
}
@@ -248,8 +245,42 @@ fn invalid_account_file_cannot_be_overwritten_by_a_new_account() {
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.check_loaded().is_err());
assert!(store.add(microsoft_account("Owner")).is_err());
assert!(store.accounts.is_empty());
assert_eq!(std::fs::read(path).unwrap(), b"{broken credentials");
}
#[test]
fn stale_account_mutations_preserve_new_credentials_and_selection() {
let tmp = tempfile::tempdir().unwrap();
let mut first = make_store(tmp.path());
first.add(microsoft_account("Owner")).unwrap();
first.add(create_offline_account("Player")).unwrap();
let mut stale = AccountStore::load_from(first.path.clone());
let uuid = first.accounts[0].uuid.clone();
first
.update_credentials(
&uuid,
Some("new-refresh".to_owned()),
"new-token",
Some(12345),
)
.unwrap();
first.add(create_offline_account("New")).unwrap();
stale.set_active(1).unwrap();
assert_eq!(stale.accounts.len(), 3);
assert_eq!(
stale.accounts[0].refresh_token.as_deref(),
Some("new-refresh")
);
first
.update_credentials(&uuid, None, "newer-token", Some(23456))
.unwrap();
assert_eq!(first.active_account().unwrap().username, "Player");
assert_eq!(
first.accounts[0].cached_mc_token.as_deref(),
Some("newer-token")
);
}
+37
View File
@@ -3,6 +3,42 @@
use super::*;
#[tokio::test]
async fn profile_status_errors_and_stalls_are_reported_accurately() {
use wiremock::{Mock, MockServer, ResponseTemplate, matchers::path};
let server = MockServer::start().await;
let client = reqwest::Client::builder()
.read_timeout(std::time::Duration::from_millis(30))
.build()
.unwrap();
for status in [404, 401, 429, 503] {
let route = format!("/{status}");
Mock::given(path(&route))
.respond_with(ResponseTemplate::new(status))
.mount(&server)
.await;
let error = fetch_profile(&client, &format!("{}{route}", server.uri()), "test")
.await
.err()
.unwrap();
if status == 404 {
assert!(error.contains("does not own"));
} else {
assert!(error.contains(&status.to_string()));
assert!(!error.contains("does not own"));
}
}
Mock::given(path("/stall"))
.respond_with(ResponseTemplate::new(200).set_delay(std::time::Duration::from_secs(1)))
.mount(&server)
.await;
assert!(
fetch_profile(&client, &format!("{}/stall", server.uri()), "test")
.await
.is_err()
);
}
fn microsoft_account(cached_mc_token_expires_at: Option<i64>) -> Account {
Account {
uuid: "00000000-0000-0000-0000-000000000000".to_owned(),
@@ -29,6 +65,7 @@ fn cached_mc_token_expires_inside_refresh_margin() {
let account = microsoft_account(Some(now + MC_TOKEN_CACHE_REFRESH_MARGIN_SECS));
assert!(valid_cached_mc_token(&account, now).is_none());
assert!(valid_cached_mc_token(&microsoft_account(Some(i64::MIN)), now).is_none());
}
#[test]