[Fix] User deletion & migration

This commit is contained in:
Alex 2026-08-09 02:51:47 +02:00
commit 7dc98ef29b
Signed by: alex
SSH key fingerprint: SHA256:D1+Ub8o0v4K5y1JNivW8IxEOelqLSvPmUzBbDIoZkRQ
20 changed files with 742 additions and 129 deletions

View file

@ -33,11 +33,70 @@ fn delete_dir_recursive(directory: &Path) -> bool {
}
#[allow(dead_code)]
pub fn delete_user_directory(user_id: i64) {
pub fn delete_user_directory(user_id: i64) -> io::Result<()> {
let user_dir = Path::new(&get_directory())
.join("users")
.join(user_id.to_string());
let _ = delete_dir_recursive(&user_dir);
if !user_dir.exists() {
return Ok(());
}
fs::remove_dir_all(user_dir)
}
pub fn credential_path(user_id: i64) -> PathBuf {
storage_directory().join("credentials").join(format!("{user_id}.tu"))
}
pub fn read_user_credential(user_id: i64) -> io::Result<Option<String>> {
let path = credential_path(user_id);
match fs::read_to_string(path) {
Ok(value) => Ok(Some(value)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}
/// Resolve a credential by immutable account id. A valid legacy
/// `<username>.tu` is migrated atomically the first time it is encountered.
pub fn read_user_credential_with_legacy(user_id: i64, username: &str) -> io::Result<Option<String>> {
if let Some(credential) = read_user_credential(user_id)? {
return Ok(Some(credential));
}
let legacy = storage_file("", format!("{username}.tu"))?;
let credential = match fs::read_to_string(&legacy) {
Ok(value) => value,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let parsed = crate::tu::TuCredential::parse(&credential)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
if parsed.user_id != user_id {
return Err(io::Error::new(io::ErrorKind::InvalidData, "legacy credential user id mismatch"));
}
write_user_credential(user_id, &parsed.to_canonical_string())?;
fs::remove_file(legacy)?;
Ok(Some(parsed.to_canonical_string()))
}
pub fn write_user_credential(user_id: i64, credential: &str) -> io::Result<()> {
let path = credential_path(user_id);
let parent = path.parent().expect("credential path has parent");
fs::create_dir_all(parent)?;
let temporary = parent.join(format!(".{user_id}.tu.tmp"));
fs::write(&temporary, credential)?;
if let Err(error) = fs::rename(&temporary, &path) {
let _ = fs::remove_file(&temporary);
return Err(error);
}
Ok(())
}
pub fn remove_user_credential(user_id: i64) -> io::Result<()> {
match fs::remove_file(credential_path(user_id)) {
Ok(()) => Ok(()),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error),
}
}
pub fn load_file_buf(path: &str, name: &str) -> io::Result<BufReader<File>> {

View file

@ -1,3 +1,4 @@
pub mod crypto_helper;
pub mod crypto_util;
pub mod file_util;
pub mod tu;

95
iota-util/src/tu.rs Normal file
View file

@ -0,0 +1,95 @@
//! Strict parsing and storage-independent handling of user credentials.
//!
//! A `.tu` file is deliberately identified by the account id embedded in its
//! contents. Its filename is presentation data owned by the CLI, never an
//! account authority.
use crate::crypto_helper::{keyring_from_base64, keyring_to_base64};
use mtp::crypto::{Keyring, PublicKeyBundle};
use std::fmt;
pub const MAX_PROTOCOL_ID: i64 = (1_i64 << 48) - 1;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TuError {
InvalidFormat,
InvalidUserId,
InvalidKeyring,
}
impl fmt::Display for TuError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::InvalidFormat => "invalid .tu credential format",
Self::InvalidUserId => "invalid .tu user id",
Self::InvalidKeyring => "invalid .tu keyring",
})
}
}
impl std::error::Error for TuError {}
pub struct TuCredential {
pub user_id: i64,
pub omega_host: String,
pub keyring: Keyring,
}
impl fmt::Debug for TuCredential {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TuCredential")
.field("user_id", &self.user_id)
.field("omega_host", &self.omega_host)
.field("keyring", &"<redacted>")
.finish()
}
}
impl TuCredential {
pub fn parse(input: &str) -> Result<Self, TuError> {
let (identity, encoded_keyring) = input.trim().split_once("::").ok_or(TuError::InvalidFormat)?;
if encoded_keyring.is_empty() || encoded_keyring.contains("::") {
return Err(TuError::InvalidFormat);
}
let (user_id, omega_host) = identity.split_once('@').ok_or(TuError::InvalidFormat)?;
if omega_host.trim().is_empty() || omega_host.contains('@') {
return Err(TuError::InvalidFormat);
}
let user_id = user_id.parse::<i64>().map_err(|_| TuError::InvalidUserId)?;
if !(1..=MAX_PROTOCOL_ID).contains(&user_id) {
return Err(TuError::InvalidUserId);
}
let keyring = keyring_from_base64(encoded_keyring).ok_or(TuError::InvalidKeyring)?;
Ok(Self { user_id, omega_host: omega_host.trim().to_owned(), keyring })
}
pub fn public_key_bundle(&self) -> PublicKeyBundle {
self.keyring.public_key_bundle()
}
pub fn to_canonical_string(&self) -> String {
format!("{}@{}::{}", self.user_id, self.omega_host, keyring_to_base64(&self.keyring))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::crypto_helper::generate_keyring;
#[test]
fn round_trip_is_canonical() {
let credential = TuCredential { user_id: 42, omega_host: "omega.example:443".into(), keyring: generate_keyring() };
let parsed = TuCredential::parse(&credential.to_canonical_string()).unwrap();
assert_eq!(parsed.user_id, 42);
assert_eq!(parsed.omega_host, "omega.example:443");
assert_eq!(parsed.to_canonical_string(), credential.to_canonical_string());
}
#[test]
fn rejects_malformed_credentials() {
for value in ["", "1@omega", "@omega::abc", "0@omega::abc", "281474976710656@omega::abc", "1@::abc", "1@omega::abc::def"] {
assert!(TuCredential::parse(value).is_err(), "{value}");
}
}
}