fix: preserve account data and validate CLI operations

This commit is contained in:
objz committed 2026-10-01 17:40:14 +02:00
1 parent 22a3eebe78
commit 2b6750a971
11 files changed
+300 -119

No files matched your search

+55 -41
View File
@@ -34,26 +34,36 @@ pub enum AuthResult {
pub struct AccountStore { pub struct AccountStore {
pub accounts: Vec<Account>, pub accounts: Vec<Account>,
path: PathBuf, path: PathBuf,
load_error: Option<String>,
} }
impl AccountStore { impl AccountStore {
pub fn load() -> Self { pub fn load() -> Self {
let path = account_store_path(); Self::load_from(account_store_path())
let accounts = match std::fs::read_to_string(&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(content) => match serde_json::from_str(&content) {
Ok(accounts) => accounts, Ok(accounts) => (accounts, None),
Err(e) => { Err(e) => {
tracing::warn!("Failed to parse accounts file {}: {}", path.display(), 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 => { Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
tracing::debug!("No accounts file at {}", path.display()); tracing::debug!("No accounts file at {}", path.display());
Vec::new() (Vec::new(), None)
} }
Err(e) => { Err(e) => {
tracing::warn!("Failed to read accounts file {}: {}", path.display(), 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!( tracing::debug!(
@@ -61,36 +71,25 @@ impl AccountStore {
accounts.len(), accounts.len(),
path.display() path.display()
); );
Self { accounts, path } Self {
accounts,
path,
load_error,
}
} }
pub fn save(&self) { pub fn save(&self) -> std::io::Result<()> {
if let Some(parent) = self.path.parent() if let Some(error) = &self.load_error {
&& let Err(e) = std::fs::create_dir_all(parent) return Err(std::io::Error::other(error.clone()));
{
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),
} }
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> { pub fn active_account(&self) -> Option<&Account> {
@@ -103,25 +102,31 @@ impl AccountStore {
.any(|account| account.account_type == AccountType::Microsoft) .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 { let Some(account) = self.accounts.get(index) else {
// out-of-range: leave the current selection untouched. marking // out-of-range: leave the current selection untouched. marking
// every account inactive here would break the single-active // every account inactive here would break the single-active
// invariant and orphan the store with no usable account. // invariant and orphan the store with no usable account.
tracing::warn!("Tried to select missing account index {}", index); tracing::warn!("Tried to select missing account index {}", index);
return; return Ok(());
}; };
let previous = self.accounts.clone();
let username = account.username.clone(); let username = account.username.clone();
for (i, acc) in self.accounts.iter_mut().enumerate() { for (i, acc) in self.accounts.iter_mut().enumerate() {
acc.active = i == index; acc.active = i == index;
} }
tracing::info!("Selected account '{}'", username); 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. // if an account with the same uuid already exists, replace it.
// first account added auto-becomes active so there's always a selection. // 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 uuid = &account.uuid;
let replaced = self.accounts.iter().any(|a| a.uuid == *uuid); let replaced = self.accounts.iter().any(|a| a.uuid == *uuid);
// re-adding the currently active account must not drop the selection: // re-adding the currently active account must not drop the selection:
@@ -141,14 +146,19 @@ impl AccountStore {
account_type, account_type,
username 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() { if index >= self.accounts.len() {
tracing::warn!("Tried to remove missing account index {}", index); tracing::warn!("Tried to remove missing account index {}", index);
return; return Ok(());
} }
let previous = self.accounts.clone();
let account = self.accounts.remove(index); let account = self.accounts.remove(index);
tracing::info!( tracing::info!(
"Removed {:?} account '{}'", "Removed {:?} account '{}'",
@@ -159,7 +169,11 @@ impl AccountStore {
self.accounts[0].active = true; self.accounts[0].active = true;
tracing::debug!("Activated fallback account '{}'", self.accounts[0].username); 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
View File
@@ -90,6 +90,9 @@ async fn run_full_oauth_flow() -> Result<(String, Option<String>), String> {
} }
pub fn start_microsoft_auth() -> Arc<Mutex<Option<AuthResult>>> { 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: Arc<Mutex<Option<AuthResult>>> = Arc::new(Mutex::new(None));
let result_clone = result.clone(); let result_clone = result.clone();
@@ -110,7 +113,12 @@ async fn run_full_auth_flow() -> AuthResult {
Err(e) => return AuthResult::Error(e), 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( async fn exchange_and_build_account(
@@ -158,8 +166,8 @@ async fn exchange_and_build_account(
account_type: AccountType::Microsoft, account_type: AccountType::Microsoft,
active: false, active: false,
refresh_token: ms_refresh_token.map(|s| s.to_owned()), refresh_token: ms_refresh_token.map(|s| s.to_owned()),
cached_mc_token: None, cached_mc_token: Some(mc_token.access_token().as_ref().to_owned()),
cached_mc_token_expires_at: None, cached_mc_token_expires_at: Some(chrono::Utc::now().timestamp() + MC_TOKEN_CACHE_TTL_SECS),
}) })
} }
+63 -26
View File
@@ -8,6 +8,7 @@ impl AccountStore {
Self { Self {
accounts: Vec::new(), accounts: Vec::new(),
path, path,
load_error: None,
} }
} }
} }
@@ -58,6 +59,7 @@ fn make_store(dir: &std::path::Path) -> AccountStore {
AccountStore { AccountStore {
accounts: Vec::new(), accounts: Vec::new(),
path: dir.join("accounts.json"), path: dir.join("accounts.json"),
load_error: None,
} }
} }
@@ -77,7 +79,7 @@ fn microsoft_account(name: &str) -> Account {
fn store_add_first_becomes_active() { fn store_add_first_becomes_active() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); 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_eq!(store.accounts.len(), 1);
assert!(store.accounts[0].active); assert!(store.accounts[0].active);
} }
@@ -86,8 +88,8 @@ fn store_add_first_becomes_active() {
fn store_add_second_stays_inactive() { fn store_add_second_stays_inactive() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.add(create_offline_account("Bob")); store.add(create_offline_account("Bob")).unwrap();
assert_eq!(store.accounts.len(), 2); assert_eq!(store.accounts.len(), 2);
assert!(store.accounts[0].active); assert!(store.accounts[0].active);
assert!(!store.accounts[1].active); assert!(!store.accounts[1].active);
@@ -97,11 +99,11 @@ fn store_add_second_stays_inactive() {
fn store_add_duplicate_uuid_replaces() { fn store_add_duplicate_uuid_replaces() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); 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"); let mut dup = create_offline_account("Alice");
dup.username = "AliceRenamed".to_owned(); dup.username = "AliceRenamed".to_owned();
dup.uuid = store.accounts[0].uuid.clone(); dup.uuid = store.accounts[0].uuid.clone();
store.add(dup); store.add(dup).unwrap();
assert_eq!(store.accounts.len(), 1); assert_eq!(store.accounts.len(), 1);
assert_eq!(store.accounts[0].username, "AliceRenamed"); 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() { fn store_has_microsoft_account_when_one_exists() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); 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()); assert!(!store.has_microsoft_account());
store.add(microsoft_account("Owner")); store.add(microsoft_account("Owner")).unwrap();
assert!(store.has_microsoft_account()); assert!(store.has_microsoft_account());
} }
@@ -128,8 +130,8 @@ fn store_has_microsoft_account_when_one_exists() {
fn store_active_account_returns_active() { fn store_active_account_returns_active() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.add(create_offline_account("Bob")); store.add(create_offline_account("Bob")).unwrap();
let active = store.active_account().unwrap(); let active = store.active_account().unwrap();
assert_eq!(active.username, "Alice"); assert_eq!(active.username, "Alice");
} }
@@ -138,9 +140,9 @@ fn store_active_account_returns_active() {
fn store_set_active_changes_active() { fn store_set_active_changes_active() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.add(create_offline_account("Bob")); store.add(create_offline_account("Bob")).unwrap();
store.set_active(1); store.set_active(1).unwrap();
assert!(!store.accounts[0].active); assert!(!store.accounts[0].active);
assert!(store.accounts[1].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() { fn store_set_active_out_of_bounds_keeps_selection() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.add(create_offline_account("Bob")); store.add(create_offline_account("Bob")).unwrap();
store.set_active(99); store.set_active(99).unwrap();
assert!( assert!(
store.accounts[0].active, store.accounts[0].active,
"existing selection must survive a bad index" "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() { fn store_add_replacing_active_keeps_active() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.add(create_offline_account("Bob")); store.add(create_offline_account("Bob")).unwrap();
let mut dup = create_offline_account("Alice"); let mut dup = create_offline_account("Alice");
dup.username = "AliceRenamed".to_owned(); dup.username = "AliceRenamed".to_owned();
store.add(dup); store.add(dup).unwrap();
assert!( assert!(
store.accounts.iter().any(|a| a.active), store.accounts.iter().any(|a| a.active),
"re-adding the active account must not orphan the selection" "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() { fn store_remove_activates_first_remaining() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.add(create_offline_account("Bob")); store.add(create_offline_account("Bob")).unwrap();
store.remove(0); store.remove(0).unwrap();
assert_eq!(store.accounts.len(), 1); assert_eq!(store.accounts.len(), 1);
assert_eq!(store.accounts[0].username, "Bob"); assert_eq!(store.accounts[0].username, "Bob");
assert!(store.accounts[0].active); assert!(store.accounts[0].active);
@@ -192,8 +194,8 @@ fn store_remove_activates_first_remaining() {
fn store_remove_out_of_bounds_noop() { fn store_remove_out_of_bounds_noop() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.remove(5); store.remove(5).unwrap();
assert_eq!(store.accounts.len(), 1); assert_eq!(store.accounts.len(), 1);
} }
@@ -201,9 +203,9 @@ fn store_remove_out_of_bounds_noop() {
fn store_save_and_reload() { fn store_save_and_reload() {
let tmp = tempfile::tempdir().unwrap(); let tmp = tempfile::tempdir().unwrap();
let mut store = make_store(tmp.path()); let mut store = make_store(tmp.path());
store.add(create_offline_account("Alice")); store.add(create_offline_account("Alice")).unwrap();
store.add(create_offline_account("Bob")); store.add(create_offline_account("Bob")).unwrap();
store.save(); store.save().unwrap();
let reloaded = AccountStore { let reloaded = AccountStore {
accounts: serde_json::from_str( accounts: serde_json::from_str(
@@ -211,8 +213,43 @@ fn store_save_and_reload() {
) )
.unwrap(), .unwrap(),
path: tmp.path().join("accounts.json"), path: tmp.path().join("accounts.json"),
load_error: None,
}; };
assert_eq!(reloaded.accounts.len(), 2); assert_eq!(reloaded.accounts.len(), 2);
assert_eq!(reloaded.accounts[0].username, "Alice"); assert_eq!(reloaded.accounts[0].username, "Alice");
assert!(reloaded.accounts[0].active); 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");
}
+44 -25
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: GPL-3.0-only // SPDX-License-Identifier: GPL-3.0-only
use std::io; use std::io;
use std::sync::{Arc, Mutex};
use std::time::Duration; use std::time::Duration;
use clap::ArgMatches; use clap::ArgMatches;
@@ -58,22 +59,11 @@ async fn add_account(matches: &ArgMatches) -> CliResult {
// then one for the final auth result. not the prettiest pattern // then one for the final auth result. not the prettiest pattern
// but it keeps the oauth complexity out of the CLI layer. // but it keeps the oauth complexity out of the CLI layer.
async fn add_microsoft_account() -> CliResult { async fn add_microsoft_account() -> CliResult {
if let Ok(mut slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() {
*slot = None;
}
let result_arc = crate::auth::start_microsoft_auth(); let result_arc = crate::auth::start_microsoft_auth();
loop { let info = wait_for_device_code(&result_arc).await?;
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock() println!("Open: {}", info.verification_uri);
&& let Some(info) = slot.as_ref() println!("Code: {}", info.user_code);
{
println!("Open: {}", info.verification_uri);
println!("Code: {}", info.user_code);
break;
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
loop { loop {
if let Ok(slot) = result_arc.lock() if let Ok(slot) = result_arc.lock()
@@ -82,7 +72,7 @@ async fn add_microsoft_account() -> CliResult {
return match result { return match result {
AuthResult::Success(account) => { AuthResult::Success(account) => {
let mut store = AccountStore::load(); let mut store = AccountStore::load();
store.add(account.clone()); store.add(account.clone())?;
println!("Added Microsoft account '{}'.", account.username); println!("Added Microsoft account '{}'.", account.username);
Ok(()) Ok(())
} }
@@ -93,6 +83,24 @@ async fn add_microsoft_account() -> CliResult {
} }
} }
async fn wait_for_device_code(
result: &Arc<Mutex<Option<AuthResult>>>,
) -> io::Result<crate::auth::DeviceCodeInfo> {
loop {
if let Ok(slot) = crate::auth::DEVICE_CODE_DISPLAY.lock()
&& let Some(info) = slot.as_ref()
{
return Ok(info.clone());
}
if let Ok(slot) = result.lock()
&& let Some(AuthResult::Error(message)) = slot.as_ref()
{
return Err(io::Error::other(message.clone()));
}
tokio::time::sleep(Duration::from_millis(200)).await;
}
}
fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult { fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
let username = username.trim(); let username = username.trim();
if username.is_empty() { if username.is_empty() {
@@ -105,22 +113,21 @@ fn add_offline_account(store: &mut AccountStore, username: &str) -> CliResult {
.into()); .into());
} }
store.add(crate::auth::create_offline_account(username)); store.add(crate::auth::create_offline_account(username))?;
Ok(()) Ok(())
} }
fn delete_account(matches: &ArgMatches) -> CliResult { fn delete_account(matches: &ArgMatches) -> CliResult {
let username = required_arg(matches, "username")?; let username = required_arg(matches, "username")?;
let mut store = AccountStore::load(); let mut store = AccountStore::load();
let index = find_account_index(&store.accounts, username) let index = find_account_index(&store.accounts, username)?;
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?;
if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? { if !matches.get_flag("yes") && !confirm(&format!("Delete '{}'", username))? {
println!("Cancelled."); println!("Cancelled.");
return Ok(()); return Ok(());
} }
store.remove(index); store.remove(index)?;
println!("Deleted '{}'.", username); println!("Deleted '{}'.", username);
Ok(()) Ok(())
} }
@@ -128,17 +135,29 @@ fn delete_account(matches: &ArgMatches) -> CliResult {
fn use_account(matches: &ArgMatches) -> CliResult { fn use_account(matches: &ArgMatches) -> CliResult {
let username = required_arg(matches, "username")?; let username = required_arg(matches, "username")?;
let mut store = AccountStore::load(); let mut store = AccountStore::load();
let index = find_account_index(&store.accounts, username) let index = find_account_index(&store.accounts, username)?;
.ok_or_else(|| io::Error::other(format!("account '{}' not found", username)))?; store.set_active(index)?;
store.set_active(index);
println!("Active account set to '{}'.", username); println!("Active account set to '{}'.", username);
Ok(()) Ok(())
} }
fn find_account_index(accounts: &[Account], username: &str) -> Option<usize> { fn find_account_index(accounts: &[Account], selector: &str) -> io::Result<usize> {
accounts if let Some(index) = accounts.iter().position(|account| account.uuid == selector) {
return Ok(index);
}
let mut matches = accounts
.iter() .iter()
.position(|account| account.username.eq_ignore_ascii_case(username)) .enumerate()
.filter(|(_, account)| account.username.eq_ignore_ascii_case(selector));
let (index, _) = matches
.next()
.ok_or_else(|| io::Error::other(format!("account '{selector}' not found")))?;
if matches.next().is_some() {
return Err(io::Error::other(format!(
"Account '{selector}' is ambiguous; use its UUID"
)));
}
Ok(index)
} }
use super::utils::{confirm, required_arg}; use super::utils::{confirm, required_arg};
+14 -6
View File
@@ -128,12 +128,10 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult {
loop { loop {
match crate::instance::runtime::get(name) { match crate::instance::runtime::get(name) {
Some(RunState::Crashed(Some(code))) => { Some(RunState::Crashed(Some(code))) => {
println!("Game exited with status {}", code); return Err(io::Error::other(format!("Game exited with status {code}")).into());
break;
} }
Some(RunState::Crashed(None)) => { Some(RunState::Crashed(None)) => {
println!("Game was terminated"); return Err(io::Error::other("Game was terminated without an exit code").into());
break;
} }
Some(_) => tokio::time::sleep(Duration::from_millis(500)).await, Some(_) => tokio::time::sleep(Duration::from_millis(500)).await,
None => { None => {
@@ -297,10 +295,10 @@ fn apply_config_update(
) -> CliResult { ) -> CliResult {
match key { match key {
"memory-max" => { "memory-max" => {
config.memory_max = crate::instance::normalize_memory_value(value); config.memory_max = parse_memory_update(value)?;
} }
"memory-min" => { "memory-min" => {
config.memory_min = crate::instance::normalize_memory_value(value); config.memory_min = parse_memory_update(value)?;
} }
"java-path" => { "java-path" => {
config.java_path = if value.is_empty() { config.java_path = if value.is_empty() {
@@ -327,6 +325,16 @@ fn apply_config_update(
Ok(()) Ok(())
} }
fn parse_memory_update(value: &str) -> Result<Option<String>, io::Error> {
if value.is_empty() {
Ok(None)
} else {
crate::instance::normalize_memory_value(value)
.map(Some)
.ok_or_else(|| io::Error::other(format!("invalid memory size '{value}'")))
}
}
#[cfg(test)] #[cfg(test)]
#[path = "tests/instance.rs"] #[path = "tests/instance.rs"]
mod tests; mod tests;
+20 -11
View File
@@ -71,19 +71,28 @@ pub(crate) fn resolve_log_path(
instance: &str, instance: &str,
file: Option<&str>, file: Option<&str>,
) -> Result<PathBuf, io::Error> { ) -> Result<PathBuf, io::Error> {
if let Some(name) = file { let log_dir = crate::instance::logs::files::log_dir(instances_dir, instance);
let path = crate::instance::logs::files::log_dir(instances_dir, instance).join(name); let path = if let Some(name) = file {
if !path.exists() { let filename = Path::new(name);
return Err(io::Error::other(format!("log '{}' not found", name))); if !crate::storage::safe_relative_path(filename) || filename.components().count() != 1 {
return Err(io::Error::other("log file must be a single filename"));
} }
return Ok(path); log_dir.join(filename)
} else {
crate::instance::logs::files::scan_log_files(instances_dir, instance)
.into_iter()
.next()
.map(|entry| entry.path)
.ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))?
};
let log_dir = std::fs::canonicalize(log_dir)?;
let path = std::fs::canonicalize(path)?;
if path.parent() != Some(log_dir.as_path()) || !path.is_file() {
return Err(io::Error::other(
"log file is outside the instance log directory",
));
} }
Ok(path)
crate::instance::logs::files::scan_log_files(instances_dir, instance)
.into_iter()
.next()
.map(|entry| entry.path)
.ok_or_else(|| io::Error::other(format!("no log files found for '{}'", instance)))
} }
use super::utils::{require_instance, required_arg}; use super::utils::{require_instance, required_arg};
+34 -1
View File
@@ -20,7 +20,7 @@ fn microsoft_account() -> Account {
fn creates_offline_account_after_microsoft_account_exists() { fn creates_offline_account_after_microsoft_account_exists() {
let temp = tempfile::tempdir().unwrap(); let temp = tempfile::tempdir().unwrap();
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json")); let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
store.add(microsoft_account()); store.add(microsoft_account()).unwrap();
add_offline_account(&mut store, "Steve").expect("offline account should be added"); add_offline_account(&mut store, "Steve").expect("offline account should be added");
assert_eq!(store.accounts.len(), 2); assert_eq!(store.accounts.len(), 2);
@@ -45,3 +45,36 @@ fn rejects_empty_offline_username() {
let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json")); let mut store = AccountStore::empty_for_test(temp.path().join("accounts.json"));
assert!(add_offline_account(&mut store, " ").is_err()); assert!(add_offline_account(&mut store, " ").is_err());
} }
#[test]
fn duplicate_usernames_require_a_unique_account_selector() {
let mut microsoft = microsoft_account();
microsoft.username = "Steve".to_owned();
let offline = crate::auth::create_offline_account("Steve");
let accounts = vec![microsoft, offline.clone()];
assert!(super::find_account_index(&accounts, "Steve").is_err());
assert_eq!(
super::find_account_index(&accounts, &offline.uuid).unwrap(),
1
);
}
#[test]
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(
"device code failed".to_owned(),
))));
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
let error = runtime
.block_on(super::wait_for_device_code(&result))
.unwrap_err();
assert!(error.to_string().contains("device code failed"));
}
+12
View File
@@ -17,3 +17,15 @@ fn rejects_invalid_resolution_format() {
assert!(parse_resolution("1920xa").is_err()); assert!(parse_resolution("1920xa").is_err());
assert!(parse_resolution("0x1080").is_err()); assert!(parse_resolution("0x1080").is_err());
} }
#[test]
fn invalid_memory_update_keeps_existing_setting() {
let mut config: crate::instance::InstanceConfig = serde_json::from_value(serde_json::json!({
"name": "test", "game_version": "1.21.1", "loader": "vanilla",
"loader_version": null, "created": "2026-01-01T00:00:00Z", "memory_max": "8G"
}))
.unwrap();
assert!(super::apply_config_update(&mut config, "memory-max", "garbage").is_err());
assert_eq!(config.memory_max.as_deref(), Some("8G"));
}
+18
View File
@@ -32,3 +32,21 @@ fn resolves_named_log_file() {
Some("latest.log") Some("latest.log")
); );
} }
#[test]
fn rejects_log_paths_outside_the_instance() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("demo/minecraft/logs/launches");
std::fs::create_dir_all(&dir).unwrap();
let outside = tmp.path().join("outside.txt");
std::fs::write(&outside, "private").unwrap();
assert!(resolve_log_path(tmp.path(), "demo", Some(outside.to_str().unwrap())).is_err());
assert!(resolve_log_path(tmp.path(), "demo", Some("../../outside.txt")).is_err());
#[cfg(unix)]
{
std::os::unix::fs::symlink(&outside, dir.join("escape.log")).unwrap();
assert!(resolve_log_path(tmp.path(), "demo", Some("escape.log")).is_err());
assert!(resolve_log_path(tmp.path(), "demo", None).is_err());
}
}
+1
View File
@@ -23,6 +23,7 @@ pub fn required_arg<'a>(matches: &'a ArgMatches, name: &str) -> Result<&'a str,
// checks for instance.json rather than just the directory, since a folder // checks for instance.json rather than just the directory, since a folder
// without config is just a sad empty directory pretending to be an instance // without config is just a sad empty directory pretending to be an instance
pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> { pub fn require_instance(instances_dir: &std::path::Path, name: &str) -> Result<(), io::Error> {
crate::instance::manager::validate_name(name).map_err(io::Error::other)?;
if !instances_dir.join(name).join("instance.json").exists() { if !instances_dir.join(name).join("instance.json").exists() {
return Err(io::Error::other(format!("Instance '{name}' not found"))); return Err(io::Error::other(format!("Instance '{name}' not found")));
} }
+28 -6
View File
@@ -153,7 +153,23 @@ pub fn clear_disposable_caches(meta_dir: &Path) -> io::Result<()> {
Ok(()) Ok(())
} }
pub fn safe_relative_path(path: &Path) -> bool {
let mut components = path.components();
components
.next()
.is_some_and(|part| matches!(part, std::path::Component::Normal(_)))
&& components.all(|part| matches!(part, std::path::Component::Normal(_)))
}
pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> { pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
write_atomic_with_mode(path, bytes, false)
}
pub fn write_atomic_private(path: &Path, bytes: &[u8]) -> io::Result<()> {
write_atomic_with_mode(path, bytes, true)
}
fn write_atomic_with_mode(path: &Path, bytes: &[u8], private: bool) -> io::Result<()> {
let parent = path let parent = path
.parent() .parent()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?;
@@ -167,10 +183,16 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
let result = (|| { let result = (|| {
use std::io::Write; use std::io::Write;
let mut file = std::fs::OpenOptions::new() let mut options = std::fs::OpenOptions::new();
.create_new(true) options.create_new(true).write(true);
.write(true) #[cfg(unix)]
.open(&temporary)?; if private {
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
#[cfg(not(unix))]
let _ = private;
let mut file = options.open(&temporary)?;
file.write_all(bytes)?; file.write_all(bytes)?;
file.sync_all()?; file.sync_all()?;
replace_file(&temporary, path) replace_file(&temporary, path)
@@ -182,12 +204,12 @@ pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
} }
#[cfg(not(windows))] #[cfg(not(windows))]
fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
std::fs::rename(source, destination) std::fs::rename(source, destination)
} }
#[cfg(windows)] #[cfg(windows)]
fn replace_file(source: &Path, destination: &Path) -> io::Result<()> { pub(crate) fn replace_file(source: &Path, destination: &Path) -> io::Result<()> {
if !destination.exists() { if !destination.exists() {
return std::fs::rename(source, destination); return std::fs::rename(source, destination);
} }