add basis management functions and debug some basis issues

there's some problems with the automatic basis unionization
feature. now debugging...
This commit is contained in:
bunnie 2022-06-26 02:11:13 +08:00
parent 475fadb255
commit e62c9bf3d3
5 changed files with 270 additions and 90 deletions

View file

@ -1,4 +1,34 @@
{ {
"vault.basis.name": {
"en": "Enter name of Basis to unlock:",
"ja": "ロックを解除する基準の名前を入力してください:",
"zh": "输入要解锁的基础名称:",
"en-tts": "Enter name of Basis to unlock:"
},
"vault.basis.create": {
"en": "Enter name of Basis to create:",
"ja": "作成する基準の名前を入力します:",
"zh": "输入要创建的基础名称:",
"en-tts": "Enter name of Basis to create:"
},
"vault.basis.created_mount": {
"en": "Basis created. Mount it now?",
"ja": "ベーシスが作成されました。 今それをマウントしますか?",
"zh": "创建的基础。 现在装吗?",
"en-tts": "Basis created. Mount it now?"
},
"vault.basis.none": {
"en": "No active secret Bases. Would you like to create one?",
"ja": "アクティブな秘密の根拠はありません。 作成しますか?",
"zh": "没有有效的秘密基础。 你想创建一个吗?",
"en-tts": "No active secret Bases. Would you like to create one?"
},
"vault.basis.unmount": {
"en": "Select the Bases to unmount:",
"ja": "アンマウントするベースを選択します:",
"zh": "选择要卸载的基础:",
"en-tts": "Select the Bases to unmount:"
},
"vault.edit_dialog": { "vault.edit_dialog": {
"en": "Make your changes and press enter.\nUse the d-pad to navigate entries.", "en": "Make your changes and press enter.\nUse the d-pad to navigate entries.",
"ja": "変更を加えてEnterキーを押します。 D-PADを使用してエントリをナビゲートします。", "ja": "変更を加えてEnterキーを押します。 D-PADを使用してエントリをナビゲートします。",
@ -17,6 +47,12 @@
"zh": "现在自动输入...", "zh": "现在自动输入...",
"en-tts": "Autotyping..." "en-tts": "Autotyping..."
}, },
"vault.error.basis_unlock_error": {
"en": "Basis does not exist. Or maybe wrong password?",
"ja": "根拠は存在しません。 または多分間違ったパスワード?",
"zh": "基础不存在。 或者密码错误?",
"en-tts": "Basis does not exist. Or maybe wrong password?"
},
"vault.error.mount_pddb": { "vault.error.mount_pddb": {
"en": "PDDB not mounted. Please init root keys and then init PDDB.", "en": "PDDB not mounted. Please init root keys and then init PDDB.",
"ja": "PDDBがマウントされていません。 ルートキーを初期化してから、PDDBを初期化してください。", "ja": "PDDBがマウントされていません。 ルートキーを初期化してから、PDDBを初期化してください。",
@ -359,6 +395,18 @@
"zh": "更改字体", "zh": "更改字体",
"en-tts": "🔇" "en-tts": "🔇"
}, },
"vault.menu_unlock_basis": {
"en": "Unlock secret Basis",
"ja": "シークレットベースのロックを解除",
"zh": "解锁秘密基础",
"en-tts": "Unlock secret basis"
},
"vault.menu_manage_basis": {
"en": "Manage Bases",
"ja": "管理基盤",
"zh": "管理基础",
"en-tts": "Manage Bases"
},
"vault.menu_close": { "vault.menu_close": {
"en": "Close submenu", "en": "Close submenu",
"ja": "メニューを閉じる", "ja": "メニューを閉じる",

View file

@ -1,6 +1,7 @@
use core::convert::TryFrom; use core::convert::TryFrom;
use std::thread; use std::{thread, io::ErrorKind};
use gam::TextEntryPayload; use gam::TextEntryPayload;
use pddb::BasisRetentionPolicy;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use num_traits::*; use num_traits::*;
use xous::{SID, msg_blocking_scalar_unpack, Message, send_message}; use xous::{SID, msg_blocking_scalar_unpack, Message, send_message};
@ -58,6 +59,8 @@ pub(crate) enum ActionOp {
MenuEditStage2, MenuEditStage2,
MenuDeleteStage2, MenuDeleteStage2,
MenuClose, MenuClose,
MenuUnlockBasis,
MenuManageBasis,
/// Internal ops /// Internal ops
UpdateMode, UpdateMode,
Quit, Quit,
@ -103,6 +106,16 @@ pub(crate) fn start_actions_thread(
manager.retrieve_db(); manager.retrieve_db();
manager.deactivate(); manager.deactivate();
}, },
Some(ActionOp::MenuUnlockBasis) => {
manager.activate();
manager.unlock_basis();
manager.deactivate();
},
Some(ActionOp::MenuManageBasis) => {
manager.activate();
manager.manage_basis();
manager.deactivate();
}
Some(ActionOp::MenuClose) => { Some(ActionOp::MenuClose) => {
// dummy activate/de-activate cycle because we have to trigger a redraw of the underlying UX // dummy activate/de-activate cycle because we have to trigger a redraw of the underlying UX
manager.activate(); manager.activate();
@ -876,6 +889,87 @@ impl ActionManager {
} }
il.sort(); il.sort();
} }
pub(crate) fn unlock_basis(&mut self) {
let name = match self.modals
.alert_builder(t!("vault.basis.name", xous::LANG))
.field(None, Some(name_validator))
.build()
{
Ok(text) => {
text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string()
},
_ => {log::error!("Name entry failed"); self.action_active.store(false, Ordering::SeqCst); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) {
Ok(_) => log::debug!("Basis {} unlocked", name),
Err(e) => match e.kind() {
ErrorKind::PermissionDenied => {
self.report_err(t!("vault.error.basis_unlock_error", xous::LANG), None::<std::io::Error>)
},
_ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
}
}
pub(crate) fn manage_basis(&mut self) {
let mut bases = self.pddb.borrow().list_basis();
bases.retain(|name| name != pddb::PDDB_DEFAULT_SYSTEM_BASIS);
let b: Vec<&str> = bases.iter().map(AsRef::as_ref).collect();
if bases.len() > 0 {
self.modals
.add_list(
b
).expect("couldn't create unmount modal");
match self.modals.get_checkbox(t!("vault.basis.unmount", xous::LANG)) {
Ok(unmount) => {
for b in unmount {
match self.pddb.borrow().lock_basis(&b) {
Ok(_) => log::debug!("basis {} locked", b),
Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
}
}
Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
} else {
if self.yes_no_approval(t!("vault.basis.none", xous::LANG)) {
let name = match self.modals
.alert_builder(t!("vault.basis.create", xous::LANG))
.field(None, Some(name_validator))
.build()
{
Ok(text) => {
text.content()[0].content.as_str().unwrap_or("UTF-8 error").to_string()
},
Err(e) => {self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)); return}
};
self.tt.sleep_ms(SWAP_DELAY_MS).unwrap();
match self.pddb.borrow().create_basis(&name) {
Ok(_) => {
if self.yes_no_approval(t!("vault.basis.created_mount", xous::LANG)) {
match self.pddb.borrow().unlock_basis(&name, Some(BasisRetentionPolicy::Persist)) {
Ok(_) => log::debug!("Basis {} unlocked", name),
Err(e) => match e.kind() {
ErrorKind::PermissionDenied => {
self.report_err(t!("vault.error.basis_unlock_error", xous::LANG), None::<std::io::Error>)
},
_ => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
}
} else {
// do nothing
}
}
Err(e) => self.report_err(t!("vault.error.internal_error", xous::LANG), Some(e)),
}
} else {
// do nothing
}
}
}
#[cfg(feature="testing")] #[cfg(feature="testing")]
pub(crate) fn populate_tests(&mut self) { pub(crate) fn populate_tests(&mut self) {
use crate::ux::serialize_app_info; use crate::ux::serialize_app_info;

View file

@ -22,6 +22,20 @@ pub fn create_submenu(vault_conn: xous::CID, actions_conn: xous::CID, menu_mgr:
action_payload: MenuPayload::Scalar([0, 0, 0, 0]), action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true, close_on_select: true,
}); });
menu_items.push(MenuItem {
name: xous_ipc::String::from_str(t!("vault.menu_unlock_basis", xous::LANG)),
action_conn: Some(actions_conn),
action_opcode: ActionOp::MenuUnlockBasis.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
menu_items.push(MenuItem {
name: xous_ipc::String::from_str(t!("vault.menu_manage_basis", xous::LANG)),
action_conn: Some(actions_conn),
action_opcode: ActionOp::MenuManageBasis.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
menu_items.push(MenuItem { menu_items.push(MenuItem {
name: xous_ipc::String::from_str(t!("vault.menu_change_font", xous::LANG)), name: xous_ipc::String::from_str(t!("vault.menu_change_font", xous::LANG)),
action_conn: Some(vault_conn), action_conn: Some(vault_conn),

View file

@ -256,6 +256,14 @@ impl BasisCache {
tt: ticktimer_server::Ticktimer::new().unwrap(), tt: ticktimer_server::Ticktimer::new().unwrap(),
} }
} }
/// Returns a Vec which is a list of Bases to visit, in order of visitation, to create the union view.
pub(crate) fn access_list(&self) -> Vec::<String> {
let mut al = Vec::<String>::new();
for entry in self.cache.iter().rev() {
al.push(entry.name.to_string());
}
al
}
fn select_basis(&mut self, basis_name: Option<&str>) -> Option<usize> { fn select_basis(&mut self, basis_name: Option<&str>) -> Option<usize> {
if self.cache.len() == 0 { if self.cache.len() == 0 {
log::error!("Can't select basis: PDDB is not mounted"); log::error!("Can't select basis: PDDB is not mounted");
@ -941,6 +949,7 @@ impl BasisCache {
} }
} else { } else {
for basis in self.cache.iter_mut() { for basis in self.cache.iter_mut() {
log::info!("syncing {}", basis.name);
basis.sync(hw)?; basis.sync(hw)?;
} }
} }

View file

@ -779,12 +779,13 @@ fn main() -> ! {
buffer.replace(mgmt).unwrap(); buffer.replace(mgmt).unwrap();
} }
Some(Opcode::KeyRequest) => { Some(Opcode::KeyRequest) => {
for basis in basis_cache.access_list().iter() {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut req: PddbKeyRequest = buffer.to_original::<PddbKeyRequest, _>().unwrap(); let mut req: PddbKeyRequest = buffer.to_original::<PddbKeyRequest, _>().unwrap();
let bname = if req.basis_specified { let bname = if req.basis_specified {
Some(req.basis.as_str().unwrap()) Some(req.basis.as_str().unwrap())
} else { } else {
None Some(basis.as_str())
}; };
let dict = req.dict.as_str().expect("dict utf-8 decode error"); let dict = req.dict.as_str().expect("dict utf-8 decode error");
let key = req.key.as_str().expect("key utf-8 decode error"); let key = req.key.as_str().expect("key utf-8 decode error");
@ -848,6 +849,7 @@ fn main() -> ! {
req.result = PddbRequestCode::NoErr; req.result = PddbRequestCode::NoErr;
buffer.replace(req).unwrap(); buffer.replace(req).unwrap();
} }
}
Some(Opcode::KeyDrop) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, _, { Some(Opcode::KeyDrop) => msg_blocking_scalar_unpack!(msg, t0, t1, t2, _, {
let token: ApiToken = [t0 as u32, t1 as u32, t2 as u32]; let token: ApiToken = [t0 as u32, t1 as u32, t2 as u32];
if let Some(rec) = token_dict.remove(&token) { if let Some(rec) = token_dict.remove(&token) {
@ -1124,13 +1126,21 @@ fn main() -> ! {
let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance
let token = pbuf.token; let token = pbuf.token;
if let Some(rec) = token_dict.get(&token) { if let Some(rec) = token_dict.get(&token) {
for basis in basis_cache.access_list().iter() {
let temp = if let Some (name) = &rec.basis {Some(name)} else {Some(basis)};
log::info!("accessing {:?}", temp);
match basis_cache.key_read(&mut pddb_os, match basis_cache.key_read(&mut pddb_os,
&rec.dict, &rec.key, &rec.dict, &rec.key,
&mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), &mut pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize),
if let Some (name) = &rec.basis {Some(&name)} else {None}) { // this is a bit inefficient because if a specific basis is specified *and* the key does not exist,
// it'll retry the same basis for a number of times equal to the number of bases open.
// However, usually, there's only 1-2 bases open, and usually, if you specify a basis,
// the key will be a hit, so, we let it stand.
if let Some (name) = &rec.basis {Some(&name)} else {Some(basis)}) {
Ok(readlen) => { Ok(readlen) => {
pbuf.len = readlen as u16; pbuf.len = readlen as u16;
pbuf.retcode = PddbRetcode::Ok; pbuf.retcode = PddbRetcode::Ok;
break;
} }
Err(e) => match e.kind() { Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost,
@ -1139,6 +1149,7 @@ fn main() -> ! {
_ => pbuf.retcode = PddbRetcode::InternalError, _ => pbuf.retcode = PddbRetcode::InternalError,
} }
} }
}
} else { } else {
pbuf.retcode = PddbRetcode::BasisLost; pbuf.retcode = PddbRetcode::BasisLost;
} }
@ -1149,14 +1160,16 @@ fn main() -> ! {
let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance let pbuf = PddbBuf::from_slice_mut(buffer.as_mut()); // direct translation, no serialization necessary for performance
let token = pbuf.token; let token = pbuf.token;
if let Some(rec) = token_dict.get(&token) { if let Some(rec) = token_dict.get(&token) {
for basis in basis_cache.access_list().iter() {
match basis_cache.key_update(&mut pddb_os, match basis_cache.key_update(&mut pddb_os,
&rec.dict, &rec.key, &rec.dict, &rec.key,
&pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize), &pbuf.data[..pbuf.len as usize], Some(pbuf.position as usize),
rec.alloc_hint, if let Some (name) = &rec.basis {Some(&name)} else {None}, rec.alloc_hint, if let Some (name) = &rec.basis {Some(&name)} else {Some(basis)},
false false
) { ) {
Ok(_) => { Ok(_) => {
pbuf.retcode = PddbRetcode::Ok; pbuf.retcode = PddbRetcode::Ok;
break;
} }
Err(e) => match e.kind() { Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost, std::io::ErrorKind::NotFound => pbuf.retcode = PddbRetcode::BasisLost,
@ -1165,6 +1178,7 @@ fn main() -> ! {
_ => pbuf.retcode = PddbRetcode::InternalError, _ => pbuf.retcode = PddbRetcode::InternalError,
} }
} }
}
} else { } else {
pbuf.retcode = PddbRetcode::BasisLost; pbuf.retcode = PddbRetcode::BasisLost;
} }
@ -1188,6 +1202,7 @@ fn main() -> ! {
let mut note = String::from(t!("pddb.menu.listbasis_response", xous::LANG)); let mut note = String::from(t!("pddb.menu.listbasis_response", xous::LANG));
for basis in bases.iter() { for basis in bases.iter() {
note.push_str(basis); note.push_str(basis);
note.push_str("\n");
} }
modals.show_notification(&note, None).expect("couldn't show basis list"); modals.show_notification(&note, None).expect("couldn't show basis list");
}, },