fix: serialize account updates and isolate authentication attempts
This commit is contained in:
1 parent
7362354109
commit
eb436c2ab8
10 files changed
+297
-160
No files matched your search
+88
-58
@@ -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
@@ -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
@@ -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(),
|
||||
|
||||
@@ -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")
|
||||
);
|
||||
}
|
||||
@@ -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(µsoft_account(Some(i64::MIN)), now).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+10
-10
@@ -2,7 +2,6 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::io;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::ArgMatches;
|
||||
@@ -24,6 +23,7 @@ pub async fn handle_account(matches: &ArgMatches) -> CliResult {
|
||||
|
||||
fn list_accounts() -> CliResult {
|
||||
let store = AccountStore::load();
|
||||
store.check_loaded()?;
|
||||
let rows = store
|
||||
.accounts
|
||||
.iter()
|
||||
@@ -32,11 +32,12 @@ fn list_accounts() -> CliResult {
|
||||
active_marker(account.active).to_string(),
|
||||
account.username.clone(),
|
||||
format!("{:?}", account.account_type),
|
||||
account.uuid.clone(),
|
||||
]
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
print_table(&[" ", "Username", "Type"], &rows);
|
||||
print_table(&[" ", "Username", "Type", "UUID"], &rows);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -54,10 +55,6 @@ async fn add_account(matches: &ArgMatches) -> CliResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// microsoft auth runs on a background thread via device code flow.
|
||||
// polls two shared slots: one for the device code to display,
|
||||
// then one for the final auth result. not the prettiest pattern
|
||||
// but it keeps the oauth complexity out of the CLI layer.
|
||||
async fn add_microsoft_account() -> CliResult {
|
||||
let result_arc = crate::auth::start_microsoft_auth();
|
||||
|
||||
@@ -66,7 +63,7 @@ async fn add_microsoft_account() -> CliResult {
|
||||
println!("Code: {}", info.user_code);
|
||||
|
||||
loop {
|
||||
if let Ok(slot) = result_arc.lock()
|
||||
if let Ok(slot) = result_arc.result.lock()
|
||||
&& let Some(result) = slot.as_ref()
|
||||
{
|
||||
return match result {
|
||||
@@ -84,15 +81,15 @@ async fn add_microsoft_account() -> CliResult {
|
||||
}
|
||||
|
||||
async fn wait_for_device_code(
|
||||
result: &Arc<Mutex<Option<AuthResult>>>,
|
||||
result: &crate::auth::MicrosoftAuth,
|
||||
) -> io::Result<crate::auth::DeviceCodeInfo> {
|
||||
loop {
|
||||
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
|
||||
if let Ok(slot) = result.device_code.lock()
|
||||
&& let Some(info) = slot.as_ref()
|
||||
{
|
||||
return Ok(info.clone());
|
||||
}
|
||||
if let Ok(slot) = result.lock()
|
||||
if let Ok(slot) = result.result.lock()
|
||||
&& let Some(AuthResult::Error(message)) = slot.as_ref()
|
||||
{
|
||||
return Err(io::Error::other(message.clone()));
|
||||
@@ -102,6 +99,7 @@ async fn wait_for_device_code(
|
||||
}
|
||||
|
||||
fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
|
||||
store.check_loaded()?;
|
||||
let username = username.trim();
|
||||
if username.is_empty() {
|
||||
return Err(io::Error::other("offline username cannot be empty").into());
|
||||
@@ -120,6 +118,7 @@ fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
|
||||
fn delete_account(matches: &ArgMatches) -> CliResult {
|
||||
let username = required_arg(matches, "username")?;
|
||||
let mut store = AccountStore::load();
|
||||
store.check_loaded()?;
|
||||
let index = find_account_index(&store.accounts, username)?;
|
||||
|
||||
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
|
||||
@@ -135,6 +134,7 @@ fn delete_account(matches: &ArgMatches) -> CliResult {
|
||||
fn use_account(matches: &ArgMatches) -> CliResult {
|
||||
let username = required_arg(matches, "username")?;
|
||||
let mut store = AccountStore::load();
|
||||
store.check_loaded()?;
|
||||
let index = find_account_index(&store.accounts, username)?;
|
||||
store.set_active(index)?;
|
||||
println!("Active account set to '{}'.", username);
|
||||
|
||||
@@ -65,10 +65,10 @@ fn device_code_failure_does_not_wait_for_a_code() {
|
||||
let _guard = crate::tests::TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|error| error.into_inner());
|
||||
*crate::auth::DEVICE_CODE_DISPLAY.lock().unwrap() = None;
|
||||
let result = std::sync::Arc::new(std::sync::Mutex::new(Some(crate::auth::AuthResult::Error(
|
||||
let result = crate::auth::MicrosoftAuth::default();
|
||||
*result.result.lock().unwrap() = Some(crate::auth::AuthResult::Error(
|
||||
"device code failed".to_owned(),
|
||||
))));
|
||||
));
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_time()
|
||||
.build()
|
||||
|
||||
@@ -731,6 +731,9 @@ pub async fn launch(
|
||||
let name = config.name.clone();
|
||||
|
||||
let mut account_store = crate::auth::AccountStore::load();
|
||||
account_store
|
||||
.check_loaded()
|
||||
.map_err(|error| LaunchError::Auth(error.to_string()))?;
|
||||
let account =
|
||||
select_launch_account(&account_store.accounts, config.preferred_account.as_deref());
|
||||
let Some(acc) = account.cloned() else {
|
||||
@@ -753,25 +756,7 @@ pub async fn launch(
|
||||
AccountType::Offline => ("0".to_string(), None, None),
|
||||
};
|
||||
|
||||
if let Some(stored) = account_store
|
||||
.accounts
|
||||
.iter_mut()
|
||||
.find(|a| a.uuid == acc.uuid)
|
||||
{
|
||||
let mut changed = false;
|
||||
if let Some(new_rt) = new_refresh {
|
||||
stored.refresh_token = Some(new_rt);
|
||||
changed = true;
|
||||
}
|
||||
if let Some(expires) = new_expires {
|
||||
stored.cached_mc_token = Some(token.clone());
|
||||
stored.cached_mc_token_expires_at = Some(expires);
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
account_store.save()?;
|
||||
}
|
||||
}
|
||||
account_store.update_credentials(&acc.uuid, new_refresh, &token, new_expires)?;
|
||||
|
||||
let user_type = match acc.account_type {
|
||||
AccountType::Microsoft => "msa",
|
||||
|
||||
@@ -29,6 +29,46 @@ fn offline_account_requires_a_microsoft_account_and_can_be_dismissed() {
|
||||
assert!(matches!(state.add_mode, AddMode::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_login_cannot_publish_the_next_attempts_device_code() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let first = auth::MicrosoftAuth::default();
|
||||
let stale_display = first.device_code.clone();
|
||||
let mut state = AccountState {
|
||||
store: AccountStore::empty_for_test(temp.path().join("accounts.json")),
|
||||
list_state: Default::default(),
|
||||
add_mode: AddMode::DeviceCodeWaiting {
|
||||
info: DeviceCodeInfo {
|
||||
user_code: String::new(),
|
||||
verification_uri: String::new(),
|
||||
},
|
||||
pending: first,
|
||||
},
|
||||
};
|
||||
handle_key(&key(KeyCode::Esc), &mut state);
|
||||
let second = auth::MicrosoftAuth::default();
|
||||
*second.device_code.lock().unwrap() = Some(DeviceCodeInfo {
|
||||
user_code: "current".to_owned(),
|
||||
verification_uri: "current-uri".to_owned(),
|
||||
});
|
||||
state.add_mode = AddMode::DeviceCodeWaiting {
|
||||
info: DeviceCodeInfo {
|
||||
user_code: String::new(),
|
||||
verification_uri: String::new(),
|
||||
},
|
||||
pending: second,
|
||||
};
|
||||
*stale_display.lock().unwrap() = Some(DeviceCodeInfo {
|
||||
user_code: "stale".to_owned(),
|
||||
verification_uri: "stale-uri".to_owned(),
|
||||
});
|
||||
drain_device_code(&mut state);
|
||||
let AddMode::DeviceCodeWaiting { info, .. } = &state.add_mode else {
|
||||
panic!("login must still be pending")
|
||||
};
|
||||
assert_eq!(info.user_code, "current");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_type_popup_uses_the_theme_surface() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use crossterm::event::{KeyCode, KeyEvent};
|
||||
use ratatui::{
|
||||
Frame,
|
||||
@@ -28,7 +26,7 @@ pub enum AddMode {
|
||||
OfflineBlocked,
|
||||
DeviceCodeWaiting {
|
||||
info: DeviceCodeInfo,
|
||||
pending: Arc<Mutex<Option<AuthResult>>>,
|
||||
pending: auth::MicrosoftAuth,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -58,7 +56,7 @@ impl AccountState {
|
||||
// can't block on it because the TUI needs to keep rendering
|
||||
pub fn drain_auth_result(&mut self) {
|
||||
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
|
||||
let result = match pending.lock() {
|
||||
let result = match pending.result.lock() {
|
||||
Ok(mut slot) => slot.take(),
|
||||
_ => None,
|
||||
};
|
||||
@@ -208,9 +206,9 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
|
||||
}
|
||||
|
||||
pub fn drain_device_code(state: &mut AccountState) {
|
||||
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode
|
||||
if let AddMode::DeviceCodeWaiting { info, pending } = &mut state.add_mode
|
||||
&& info.user_code.is_empty()
|
||||
&& let Ok(mut slot) = auth::DEVICE_CODE_DISPLAY.lock()
|
||||
&& let Ok(mut slot) = pending.device_code.lock()
|
||||
&& let Some(dc_info) = slot.take()
|
||||
{
|
||||
info.user_code = dc_info.user_code;
|
||||
@@ -345,15 +343,10 @@ fn render_account_list(
|
||||
}
|
||||
|
||||
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
|
||||
let area = frame.area();
|
||||
let x = area.x + (area.width.saturating_sub(width)) / 2;
|
||||
let y = area.y + (area.height.saturating_sub(height)) / 2;
|
||||
Rect {
|
||||
x,
|
||||
y,
|
||||
width: width.min(area.width),
|
||||
height: height.min(area.height),
|
||||
}
|
||||
frame.area().centered(
|
||||
ratatui::layout::Constraint::Length(width),
|
||||
ratatui::layout::Constraint::Length(height),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_choose_popup(frame: &mut Frame) {
|
||||
|
||||
Reference in new issue
Block a user