refactor root-keys to use the latest UX features

UX flow for requesting passwords is now more or less complete...

this yak is shaved?
This commit is contained in:
bunnie 2021-07-29 03:30:03 +08:00
parent 78c0b30382
commit 86a5c34a5b
10 changed files with 173 additions and 110 deletions

View file

@ -88,7 +88,7 @@ pub(crate) struct UxContext {
/// opcode ID for AudioFrame
pub audioframe_id: Option<u32>,
}
const MAX_UX_CONTEXTS: usize = 5;
const MAX_UX_CONTEXTS: usize = 6;
pub(crate) const MAX_CANVASES: usize = 32;
// const BOOT_APP_NAME: &'static str = "shellchat"; // this is the app to display on boot -- we will eventually need this once we have more than one app?
pub const ROOTKEY_MODAL_NAME: &'static str = "rootkeys modal";
@ -585,7 +585,7 @@ fn imef_cb(s: String::<4000>) {
#[xous::xous_main]
fn xmain() -> ! {
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Info);
log::set_max_level(log::LevelFilter::Debug);
info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();

View file

@ -43,11 +43,12 @@ pub struct Menu<'a> {
pub line_height: i16,
pub canvas_width: Option<i16>,
pub helper_data: Option<Buffer<'a>>,
pub name: String::<128>,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum MenuOpcode {
Redraw,
pub enum MenuOpcode { // note: this should match ModalOpcode, for compatibility with the generic helper function
Redraw = 0x4000_0000, // set the high bit so that "standard" enums don't conflict with the Modal-specific opcodes
Rawkeys,
Quit,
}
@ -86,8 +87,12 @@ impl<'a> Menu<'a> {
line_height,
canvas_width: None,
helper_data: None,
name: String::<128>::from_str(name),
}
}
pub fn activate(&self) {
self.gam.raise_menu(self.name.to_str()).expect("couldn't activate menu");
}
/// this function spawns a client-side thread to forward redraw and key event
/// messages on to a local server. The goal is to keep the local server's SID

View file

@ -75,7 +75,7 @@ impl ItemName {
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone, Eq, PartialEq)]
pub struct TextEntryPayload(String::<256>);
pub struct TextEntryPayload(pub String::<256>);
impl TextEntryPayload {
pub fn new() -> Self {
TextEntryPayload(String::<256>::new())
@ -792,10 +792,11 @@ pub struct Modal<'a> {
pub inverted: bool,
pub style: GlyphStyle,
pub helper_data: Option<Buffer<'a>>,
pub name: String::<128>,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum ModalOpcode {
pub enum ModalOpcode { // if changes are made here, also update MenuOpcode
Redraw = 0x4000_0000, // set the high bit so that "standard" enums don't conflict with the Modal-specific opcodes
Rawkeys,
Quit,
@ -947,10 +948,14 @@ impl<'a> Modal<'a> {
inverted,
style,
helper_data: None,
name: String::<128>::from_str(name),
};
recompute_canvas(&mut modal, action, top_text, bot_text, style);
modal
}
pub fn activate(&self) {
self.gam.raise_modal(self.name.to_str()).expect("couldn't activate modal");
}
/// this function spawns a client-side thread to forward redraw and key event
/// messages on to a local server. The goal is to keep the local server's SID
@ -1011,7 +1016,7 @@ impl<'a> Modal<'a> {
self.modify(None, None, false, Some(err_msg.to_str()), false, None);
} else {
if close {
log::trace!("closing modal");
log::debug!("closing modal");
// if it's a "close" button, invoke the GAM to put our box away
self.gam.relinquish_focus().unwrap();
}

View file

@ -12,8 +12,8 @@ use xous_ipc::String;
*/
// if you add more UxContexts, and you want them authorized by the GAM, add their names here.
const TOKEN_SLOTS: usize = 6;
const EXPECTED_BOOT_CONTEXTS: [&'static str; TOKEN_SLOTS] = ["shellchat", "main menu", "status", "emoji menu", "rootkeys modal", "rtc modal"];
const TOKEN_SLOTS: usize = 7;
const EXPECTED_BOOT_CONTEXTS: [&'static str; TOKEN_SLOTS] = ["shellchat", "main menu", "status", "emoji menu", "rootkeys modal", "rtc modal", "rootkeys menu"];
#[derive(Copy, Clone, Debug)]
pub(crate) struct NamedToken {
@ -50,7 +50,10 @@ impl<'a> TokenManager {
valid = true;
}
}
if !valid { return None }
if !valid {
log::error!("Server {} is not pre-registered in gam/src/tokens.rs. Did you forget to register it?", name);
return None
}
// now check if it hasn't already been registered
let mut registered = false;
for maybe_token in self.tokens.iter() {
@ -63,7 +66,10 @@ impl<'a> TokenManager {
_ => ()
}
}
if registered { return None }
if registered {
log::error!("Attempt to re-register a UX context: {}", name);
return None
}
// now do the registration
let token = [self.trng.get_u32().unwrap(), self.trng.get_u32().unwrap(), self.trng.get_u32().unwrap(), self.trng.get_u32().unwrap(),];
log::trace!("registering {} to {:x?}", name, token);

View file

@ -8,5 +8,25 @@
"en": "Password request\nSoftware update key\nSecurity: Critical",
"zh": "输入密码\n软件更新\n安全含义:至关重要 ",
"en-audio": "Enter update password. This password is critically important."
},
"rootkeys.policy_clear": {
"en": "Clear after use",
"zh": "使用后删除",
"en-audio": "Clear password after use"
},
"rootkeys.policy_suspend": {
"en": "Retain until sleep",
"zh": "睡眠后删除",
"en-audio": "Retain password until sleep"
},
"rootkeys.policy_idle": {
"en": "Retain until timeout",
"zh": "保留到延时",
"en-audio": "Retain until timeout"
},
"rootkeys.policy_keep": {
"en": "Retain until reboot",
"zh": "保留到启动",
"en-audio": "Retain until reboot"
}
}

View file

@ -1,7 +1,7 @@
pub(crate) const SERVER_NAME_KEYS: &str = "_Root key server and update manager_";
#[allow(dead_code)]
pub(crate) const ROOTKEY_MODAL_NAME: &'static str = "rootkeys modal";
pub(crate) const ROOTKEY_MENU_NAME: &'static str = "rootkeys menu";
#[allow(dead_code)]
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
@ -14,6 +14,14 @@ pub(crate) enum Opcode {
/// UX opcodes
PasswordModalEntry,
PasswordPolicy,
RaisePolicyMenu,
MenuRedraw,
MenuKeys,
MenuDrop,
ModalRedraw,
ModalKeys,
ModalDrop,
/// Suspend/resume callback
SuspendResume,
@ -33,6 +41,7 @@ pub struct ProgressReport {
pub finished: bool,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum PasswordRetentionPolicy {
AlwaysKeep,
EraseOnSuspend,

View file

@ -229,12 +229,4 @@ impl RootKeys {
// re-allow suspend/resume ops
self.susres.set_suspendable(true).expect("couldn't re-allow suspend/resume");
}
pub fn test_ux(&mut self, arg: usize) {
match arg {
0 => self.gam.raise_modal(ROOTKEY_MODAL_NAME).expect("couldn't raise modal"),
1 => self.gam.relinquish_focus().expect("couldn't hide modal"),
_ => log::info!("test_ux got unrecognized arg: {}", arg),
};
}
}

View file

@ -119,7 +119,7 @@ impl RootKeys {
pub fn test_ux(&mut self, arg: usize) {
send_message(self.conn,
Message::new_blocking_scalar(Opcode::TestUx.to_usize().unwrap(),
Message::new_scalar(Opcode::TestUx.to_usize().unwrap(),
arg, 0, 0, 0)
).expect("couldn't send test message");
}

View file

@ -9,9 +9,12 @@ use xous_ipc::{String, Buffer};
use num_traits::*;
use gam::modal::*;
use gam::menu::*;
use locales::t;
use core::fmt::Write;
#[cfg(target_os = "none")]
mod implementation;
#[cfg(target_os = "none")]
@ -43,90 +46,15 @@ mod implementation {
pub fn try_init_keys(&mut self, _maybe_progress: Option<xous::SID>) {
}
pub fn test_ux(&mut self, arg: usize) {
match arg {
0 => self.gam.raise_modal(ROOTKEY_MODAL_NAME).expect("couldn't raise modal"),
1 => self.gam.relinquish_focus().expect("couldn't hide modal"),
_ => log::info!("test_ux got unrecognized arg: {}", arg),
};
}
}
}
pub(crate) fn rootkeys_ux_thread() {
let xns = xous_names::XousNames::new().unwrap();
let main_conn = xns.request_connection_blocking(api::SERVER_NAME_KEYS).expect("rootkeys password thread can't connect to main thread");
let password_action = gam::modal::TextEntry {
is_password: true,
visibility: gam::modal::TextEntryVisibility::LastChars,
action_conn: main_conn,
action_opcode: Opcode::PasswordModalEntry.to_u32().unwrap(),
action_payload: TextEntryPayload::new(),
validator: None,
};
log::trace!("building ux thread modal");
let mut modal = gam::Modal::new(
crate::api::ROOTKEY_MODAL_NAME,
gam::ActionType::TextEntry(password_action),
Some(t!("rootpass.top", xous::LANG)),
None,
GlyphStyle::Small,
4
);
loop {
let msg = xous::receive_message(modal.sid).unwrap();
log::trace!("ux message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(ModalOpcode::Redraw) => {
modal.redraw();
},
Some(ModalOpcode::Rawkeys) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [
if let Some(a) = core::char::from_u32(k1 as u32) {
a
} else {
'\u{0000}'
},
if let Some(a) = core::char::from_u32(k2 as u32) {
a
} else {
'\u{0000}'
},
if let Some(a) = core::char::from_u32(k3 as u32) {
a
} else {
'\u{0000}'
},
if let Some(a) = core::char::from_u32(k4 as u32) {
a
} else {
'\u{0000}'
},
];
modal.key_event(keys);
}),
Some(ModalOpcode::Quit) => {
break;
},
None => {
log::error!("unknown opcode {:?}", msg.body.id());
}
}
}
log::trace!("password modal thread exit, destroying servers");
// do we want to add a deregister_ux call to the system?
xous::destroy_server(modal.sid).unwrap();
}
#[xous::xous_main]
fn xmain() -> ! {
use crate::implementation::RootKeys;
log_server::init_wait().unwrap();
log::set_max_level(log::LevelFilter::Trace);
log::set_max_level(log::LevelFilter::Debug);
log::info!("my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();
@ -144,11 +72,69 @@ fn xmain() -> ! {
log::trace!("ready to accept requests");
// register a suspend/resume listener
let sr_cid = xous::connect(keys_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object");
let main_cid = xous::connect(keys_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(&xns, api::Opcode::SuspendResume as u32, main_cid).expect("couldn't create suspend/resume object");
xous::create_thread_0(rootkeys_ux_thread).expect("couldn't start rootkeys UX thread");
// create a policy menu object
let mut policy_menu = gam::menu::Menu::new(crate::ROOTKEY_MENU_NAME);
policy_menu.add_item(MenuItem {
name: String::<64>::from_str(t!("rootkeys.policy_keep", xous::LANG)),
action_conn: main_cid,
action_opcode: Opcode::PasswordPolicy.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::AlwaysKeep.to_u32().unwrap(), 0, 0, 0,]),
close_on_select: true,
});
policy_menu.add_item(MenuItem {
name: String::<64>::from_str(t!("rootkeys.policy_idle", xous::LANG)),
action_conn: main_cid,
action_opcode: Opcode::PasswordPolicy.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::EraseOnIdle.to_u32().unwrap(), 0, 0, 0,]),
close_on_select: true,
});
policy_menu.add_item(MenuItem {
name: String::<64>::from_str(t!("rootkeys.policy_suspend", xous::LANG)),
action_conn: main_cid,
action_opcode: Opcode::PasswordPolicy.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::EraseOnSuspend.to_u32().unwrap(), 0, 0, 0,]),
close_on_select: true,
});
policy_menu.add_item(MenuItem {
name: String::<64>::from_str(t!("rootkeys.policy_clear", xous::LANG)),
action_conn: main_cid,
action_opcode: Opcode::PasswordPolicy.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::AlwaysPurge.to_u32().unwrap(), 0, 0, 0,]),
close_on_select: true,
});
policy_menu.spawn_helper(keys_sid, policy_menu.sid,
Opcode::MenuRedraw.to_u32().unwrap(),
Opcode::MenuKeys.to_u32().unwrap(),
Opcode::MenuDrop.to_u32().unwrap());
//xous::create_thread_0(rootkeys_ux_thread).expect("couldn't start rootkeys UX thread");
let password_action = gam::modal::TextEntry {
is_password: true,
visibility: gam::modal::TextEntryVisibility::LastChars,
action_conn: main_cid,
action_opcode: Opcode::PasswordModalEntry.to_u32().unwrap(),
action_payload: TextEntryPayload::new(),
validator: None,
};
let mut password_modal = gam::Modal::new(
crate::api::ROOTKEY_MODAL_NAME,
gam::ActionType::TextEntry(password_action),
Some(t!("rootpass.top", xous::LANG)),
None,
GlyphStyle::Small,
4
);
password_modal.spawn_helper(keys_sid, password_modal.sid,
Opcode::ModalRedraw.to_u32().unwrap(),
Opcode::ModalKeys.to_u32().unwrap(),
Opcode::ModalDrop.to_u32().unwrap(),
);
let mut cur_plaintext = String::<256>::new();
let mut cur_policy: Option<PasswordRetentionPolicy> = None;
loop {
let msg = xous::receive_message(keys_sid).unwrap();
log::trace!("message: {:?}", msg);
@ -165,16 +151,61 @@ fn xmain() -> ! {
let sid = xous::SID::from_u32(s0 as u32, s1 as u32, s2 as u32, s3 as u32);
keys.try_init_keys(Some(sid));
}),
Some(Opcode::TestUx) => msg_blocking_scalar_unpack!(msg, arg, _, _, _, {
keys.test_ux(arg);
xous::return_scalar(msg.sender, 0).expect("couldn't unblock sender");
Some(Opcode::TestUx) => msg_scalar_unpack!(msg, arg, _, _, _, {
log::debug!("activating password modal");
password_modal.activate();
//policy_menu.activate();
}),
Some(Opcode::PasswordModalEntry) => {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut plaintext_pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap();
log::info!("got pw entry: {}", plaintext_pw.as_str());
write!(cur_plaintext, "{}", plaintext_pw.as_str()).expect("couldn't copy plaintext password");
plaintext_pw.volatile_clear(); // ensure the data is destroyed after printing
buf.volatile_clear();
log::info!("cur_plaintext: {}", cur_plaintext);
// now explicitly request a policy decision
xous::send_message(main_cid,
Message::new_scalar(Opcode::RaisePolicyMenu.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't raise policy menu follow-up dialogue");
},
Some(Opcode::RaisePolicyMenu) => {
xous::yield_slice(); // let any pending redraws happen before raising this menu
log::debug!("raising policy menu");
policy_menu.activate();
}
Some(Opcode::PasswordPolicy) => msg_scalar_unpack!(msg, policy_code, _, _, _, {
cur_policy = FromPrimitive::from_usize(policy_code);
log::info!("cur_policy: {:?}", cur_policy);
}),
Some(Opcode::MenuRedraw) => {
policy_menu.redraw();
},
Some(Opcode::MenuKeys) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [
if let Some(a) = core::char::from_u32(k1 as u32) {a} else {'\u{0000}'},
if let Some(a) = core::char::from_u32(k2 as u32) {a} else {'\u{0000}'},
if let Some(a) = core::char::from_u32(k3 as u32) {a} else {'\u{0000}'},
if let Some(a) = core::char::from_u32(k4 as u32) {a} else {'\u{0000}'},
];
policy_menu.key_event(keys);
}),
Some(Opcode::MenuDrop) => {
panic!("Menu handler for rootkeys quit unexpectedly");
},
Some(Opcode::ModalRedraw) => {
password_modal.redraw();
},
Some(Opcode::ModalKeys) => msg_scalar_unpack!(msg, k1, k2, k3, k4, {
let keys = [
if let Some(a) = core::char::from_u32(k1 as u32) {a} else {'\u{0000}'},
if let Some(a) = core::char::from_u32(k2 as u32) {a} else {'\u{0000}'},
if let Some(a) = core::char::from_u32(k3 as u32) {a} else {'\u{0000}'},
if let Some(a) = core::char::from_u32(k4 as u32) {a} else {'\u{0000}'},
];
password_modal.key_event(keys);
}),
Some(Opcode::ModalDrop) => {
panic!("Password modal for rootkeys quit unexpectedly")
}
Some(Opcode::Quit) => {
log::warn!("password thread received quit, exiting.");

View file

@ -50,16 +50,11 @@ impl<'a> ShellCmdApi<'a> for Keys {
if let Some(sub_cmd) = tokens.next() {
match sub_cmd {
"ux0" => {
"ux" => {
self.rootkeys.test_ux(0);
//debug_here::debug_here!();
write!(ret, "show UX").unwrap();
}
"ux1" => {
self.rootkeys.test_ux(1);
//debug_here::debug_here!();
write!(ret, "hide UX").unwrap();
}
"usblock" => {
env.llio.debug_usb(Some(true)).unwrap();
write!(ret, "USB debug port locked out; one word at 0x80000000 is disclosable via USB.").unwrap();