1use crate::consumer_controls_binding::ConsumerControlsEvent;
6use crate::input_handler::{InputHandlerStatus, UnhandledInputHandler};
7use crate::{input_device, metrics};
8use anyhow::{anyhow, Context as _, Error};
9use async_trait::async_trait;
10use async_utils::hanging_get::server::HangingGet;
11use fidl::endpoints::DiscoverableProtocolMarker as _;
12use fidl_fuchsia_media::AudioRenderUsage2;
13use fidl_fuchsia_media_sounds::{PlaySoundError, PlayerMarker};
14use fidl_fuchsia_recovery::FactoryResetMarker;
15use fidl_fuchsia_recovery_policy::{DeviceRequest, DeviceRequestStream};
16use fidl_fuchsia_recovery_ui::{
17 FactoryResetCountdownRequestStream, FactoryResetCountdownState,
18 FactoryResetCountdownWatchResponder,
19};
20use fuchsia_async::{MonotonicDuration, MonotonicInstant, Task, TimeoutExt, Timer};
21use fuchsia_inspect::health::Reporter;
22use futures::StreamExt;
23use metrics_registry::*;
24use std::cell::RefCell;
25use std::fs::{self, File};
26use std::path::Path;
27use std::rc::Rc;
28use {fidl_fuchsia_input_report as fidl_input_report, fidl_fuchsia_io as fio};
29
30#[derive(Clone, Copy, Debug, PartialEq)]
72enum FactoryResetState {
73 Disallowed,
74 Idle,
75 ButtonCountdown { deadline: MonotonicInstant },
76 ResetCountdown { deadline: MonotonicInstant },
77 Resetting,
78}
79
80const FACTORY_RESET_DISALLOWED_PATH: &'static str = "/data/factory_reset_disallowed";
81const FACTORY_RESET_SOUND_PATH: &'static str = "/config/data/chirp-start-tone.wav";
82
83const BUTTON_TIMEOUT: MonotonicDuration = MonotonicDuration::from_millis(500);
84const RESET_TIMEOUT: MonotonicDuration = MonotonicDuration::from_seconds(10);
85const EARCON_TIMEOUT: MonotonicDuration = MonotonicDuration::from_millis(2000);
87
88type NotifyFn = Box<
89 dyn Fn(
90 &(FactoryResetState, metrics::MetricsLogger),
91 FactoryResetCountdownWatchResponder,
92 ) -> bool
93 + Send,
94>;
95type ResetCountdownHangingGet = HangingGet<
96 (FactoryResetState, metrics::MetricsLogger),
97 FactoryResetCountdownWatchResponder,
98 NotifyFn,
99>;
100
101pub struct FactoryResetHandler {
104 factory_reset_state: RefCell<FactoryResetState>,
105 countdown_hanging_get: RefCell<ResetCountdownHangingGet>,
106
107 pub inspect_status: InputHandlerStatus,
109
110 metrics_logger: metrics::MetricsLogger,
111}
112
113fn is_reset_requested(event: &ConsumerControlsEvent) -> bool {
118 event.pressed_buttons.iter().any(|button| match button {
119 fidl_input_report::ConsumerControlButton::FactoryReset => true,
120 _ => false,
121 })
122}
123
124impl FactoryResetHandler {
125 pub fn new(
128 input_handlers_node: &fuchsia_inspect::Node,
129 metrics_logger: metrics::MetricsLogger,
130 ) -> Rc<Self> {
131 let initial_state = if Path::new(FACTORY_RESET_DISALLOWED_PATH).exists() {
132 FactoryResetState::Disallowed
133 } else {
134 FactoryResetState::Idle
135 };
136
137 let countdown_hanging_get =
138 FactoryResetHandler::init_hanging_get(initial_state, metrics_logger.clone());
139 let inspect_status = InputHandlerStatus::new(
140 input_handlers_node,
141 "factory_reset_handler",
142 false,
143 );
144
145 Rc::new(Self {
146 factory_reset_state: RefCell::new(initial_state),
147 countdown_hanging_get: RefCell::new(countdown_hanging_get),
148 inspect_status,
149 metrics_logger,
150 })
151 }
152
153 pub fn handle_factory_reset_countdown_request_stream(
158 self: Rc<Self>,
159 mut stream: FactoryResetCountdownRequestStream,
160 ) -> impl futures::Future<Output = Result<(), Error>> {
161 let subscriber = self.countdown_hanging_get.borrow_mut().new_subscriber();
162
163 async move {
164 while let Some(request_result) = stream.next().await {
165 let watcher = request_result?
166 .into_watch()
167 .ok_or_else(|| anyhow!("Failed to get FactoryResetCoundown Watcher"))?;
168 subscriber.register(watcher)?;
169 }
170
171 Ok(())
172 }
173 }
174
175 pub fn handle_recovery_policy_device_request_stream(
180 self: Rc<Self>,
181 mut stream: DeviceRequestStream,
182 ) -> impl futures::Future<Output = Result<(), Error>> {
183 async move {
184 while let Some(request_result) = stream.next().await {
185 let DeviceRequest::SetIsLocalResetAllowed { allowed, .. } = request_result?;
186 match self.factory_reset_state() {
187 FactoryResetState::Disallowed if allowed => {
188 self.set_factory_reset_state(FactoryResetState::Idle);
190 fs::remove_file(FACTORY_RESET_DISALLOWED_PATH).with_context(|| {
191 format!("failed to remove {}", FACTORY_RESET_DISALLOWED_PATH)
192 })?
193 }
194 _ if !allowed => {
195 self.set_factory_reset_state(FactoryResetState::Disallowed);
197 let _: File =
198 File::create(FACTORY_RESET_DISALLOWED_PATH).with_context(|| {
199 format!("failed to create {}", FACTORY_RESET_DISALLOWED_PATH)
200 })?;
201 }
202 _ => (),
203 }
204 }
205
206 Ok(())
207 }
208 }
209
210 async fn handle_allowed_event(self: &Rc<Self>, event: &ConsumerControlsEvent) {
213 if is_reset_requested(event) {
214 if let Err(error) = self.start_button_countdown().await {
215 self.metrics_logger.log_error(
216 InputPipelineErrorMetricDimensionEvent::FactoryResetFailedToReset,
217 std::format!("Failed to factory reset device: {:?}", error),
218 );
219 }
220 }
221 }
222
223 fn handle_disallowed_event(self: &Rc<Self>, event: &ConsumerControlsEvent) {
226 if is_reset_requested(event) {
227 self.metrics_logger.log_error(
228 InputPipelineErrorMetricDimensionEvent::FactoryResetNotAllowedReset,
229 "Attempted to factory reset a device that is not allowed to reset",
230 );
231 }
232 }
233
234 fn handle_button_countdown_event(self: &Rc<Self>, event: &ConsumerControlsEvent) {
237 if !is_reset_requested(event) {
238 self.set_factory_reset_state(FactoryResetState::Idle);
240 }
241 }
242
243 fn handle_reset_countdown_event(self: &Rc<Self>, event: &ConsumerControlsEvent) {
246 if !is_reset_requested(event) {
247 self.set_factory_reset_state(FactoryResetState::Idle);
249 }
250 }
251
252 fn init_hanging_get(
253 initial_state: FactoryResetState,
254 metrics_logger: metrics::MetricsLogger,
255 ) -> ResetCountdownHangingGet {
256 let notify_fn: NotifyFn = Box::new(|(state, metrics_logger), responder| {
257 let deadline = match state {
258 FactoryResetState::ResetCountdown { deadline } => {
259 Some(deadline.into_nanos() as i64)
260 }
261 _ => None,
262 };
263
264 let countdown_state =
265 FactoryResetCountdownState { scheduled_reset_time: deadline, ..Default::default() };
266
267 if responder.send(&countdown_state).is_err() {
268 metrics_logger.log_error(
269 InputPipelineErrorMetricDimensionEvent::FactoryResetFailedToSendCountdown,
270 "Failed to send factory reset countdown state",
271 );
272 }
273
274 true
275 });
276
277 ResetCountdownHangingGet::new((initial_state, metrics_logger), notify_fn)
278 }
279
280 fn set_factory_reset_state(self: &Rc<Self>, state: FactoryResetState) {
282 *self.factory_reset_state.borrow_mut() = state;
283 self.countdown_hanging_get
284 .borrow_mut()
285 .new_publisher()
286 .set((state, self.metrics_logger.clone()));
287 }
288
289 fn factory_reset_state(self: &Rc<Self>) -> FactoryResetState {
290 *self.factory_reset_state.borrow()
291 }
292
293 async fn start_button_countdown(self: &Rc<Self>) -> Result<(), Error> {
296 let deadline = MonotonicInstant::after(BUTTON_TIMEOUT);
297 self.set_factory_reset_state(FactoryResetState::ButtonCountdown { deadline });
298
299 Timer::new(MonotonicInstant::after(BUTTON_TIMEOUT)).await;
301
302 match self.factory_reset_state() {
304 FactoryResetState::ButtonCountdown { deadline: state_deadline }
305 if state_deadline == deadline =>
306 {
307 self.start_reset_countdown().await?;
309 }
310 _ => {
311 log::info!("Factory reset request cancelled");
312 }
313 }
314
315 Ok(())
316 }
317
318 async fn start_reset_countdown(self: &Rc<Self>) -> Result<(), Error> {
321 let deadline = MonotonicInstant::after(RESET_TIMEOUT);
322 self.set_factory_reset_state(FactoryResetState::ResetCountdown { deadline });
323
324 Timer::new(MonotonicInstant::after(RESET_TIMEOUT)).await;
326
327 match self.factory_reset_state() {
329 FactoryResetState::ResetCountdown { deadline: state_deadline }
330 if state_deadline == deadline =>
331 {
332 self.reset().await?;
334 }
335 _ => {
336 log::info!("Factory reset request cancelled");
337 }
338 }
339
340 Ok(())
341 }
342
343 async fn play_reset_sound(self: &Rc<Self>) -> Result<(), Error> {
345 log::debug!("Getting sound");
346 let (sound_endpoint, server_end) = fidl::endpoints::create_endpoints::<fio::FileMarker>();
348 let () = fuchsia_fs::file::open_channel_in_namespace(
349 FACTORY_RESET_SOUND_PATH,
350 fuchsia_fs::PERM_READABLE,
351 server_end,
352 )
353 .context("Failed to open factory reset sound file")?;
354
355 log::debug!("Playing sound");
356 let sound_player = fuchsia_component::client::connect_to_protocol::<PlayerMarker>()
358 .with_context(|| format!("failed to connect to {}", PlayerMarker::PROTOCOL_NAME))?;
359
360 log::debug!("Connected to player");
361 let sound_id = 0;
362 let _duration: i64 = sound_player
363 .add_sound_from_file(sound_id, sound_endpoint)
364 .await
365 .context("AddSoundFromFile error")?
366 .map_err(zx::Status::from_raw)
367 .context("AddSoundFromFile failed")?;
368 log::debug!("Added sound from file");
369
370 sound_player
371 .play_sound2(sound_id, AudioRenderUsage2::Media)
372 .await
373 .context("PlaySound2 error")?
374 .map_err(|err: PlaySoundError| anyhow!("PlaySound2 failed: {:?}", err))?;
375
376 log::debug!("Played sound");
377
378 Ok(())
379 }
380
381 async fn reset(self: &Rc<Self>) -> Result<(), Error> {
383 log::info!("Beginning reset sequence");
384 if let Err(error) = self
385 .play_reset_sound()
386 .on_timeout(EARCON_TIMEOUT, || Err(anyhow!("play_reset_sound took too long")))
387 .await
388 {
389 log::warn!("Failed to play reset sound: {:?}", error);
390 }
391
392 self.set_factory_reset_state(FactoryResetState::Resetting);
394 log::info!("Calling {}.Reset", FactoryResetMarker::PROTOCOL_NAME);
395 let factory_reset = fuchsia_component::client::connect_to_protocol::<FactoryResetMarker>()
396 .with_context(|| {
397 format!("failed to connect to {}", FactoryResetMarker::PROTOCOL_NAME)
398 })?;
399 factory_reset.reset().await.context("failed while calling Reset")?;
400 Ok(())
401 }
402}
403
404#[async_trait(?Send)]
405impl UnhandledInputHandler for FactoryResetHandler {
406 async fn handle_unhandled_input_event(
410 self: Rc<Self>,
411 unhandled_input_event: input_device::UnhandledInputEvent,
412 ) -> Vec<input_device::InputEvent> {
413 match unhandled_input_event {
414 input_device::UnhandledInputEvent {
415 device_event: input_device::InputDeviceEvent::ConsumerControls(ref event),
416 device_descriptor: input_device::InputDeviceDescriptor::ConsumerControls(_),
417 event_time: _,
418 trace_id: _,
419 } => {
420 self.inspect_status.count_received_event(input_device::InputEvent::from(
421 unhandled_input_event.clone(),
422 ));
423 match self.factory_reset_state() {
424 FactoryResetState::Idle => {
425 let event_clone = event.clone();
426 Task::local(async move { self.handle_allowed_event(&event_clone).await })
427 .detach()
428 }
429 FactoryResetState::Disallowed => self.handle_disallowed_event(event),
430 FactoryResetState::ButtonCountdown { deadline: _ } => {
431 self.handle_button_countdown_event(event)
432 }
433 FactoryResetState::ResetCountdown { deadline: _ } => {
434 self.handle_reset_countdown_event(event)
435 }
436 FactoryResetState::Resetting => {
437 log::warn!("Recieved an input event while factory resetting the device")
438 }
439 };
440 }
441 _ => (),
442 };
443
444 vec![input_device::InputEvent::from(unhandled_input_event)]
445 }
446
447 fn set_handler_healthy(self: std::rc::Rc<Self>) {
448 self.inspect_status.health_node.borrow_mut().set_ok();
449 }
450
451 fn set_handler_unhealthy(self: std::rc::Rc<Self>, msg: &str) {
452 self.inspect_status.health_node.borrow_mut().set_unhealthy(msg);
453 }
454}
455
456#[cfg(test)]
457mod tests {
458 use super::*;
459 use crate::consumer_controls_binding::ConsumerControlsDeviceDescriptor;
460 use crate::input_handler::InputHandler;
461 use assert_matches::assert_matches;
462 use fidl::endpoints::create_proxy_and_stream;
463 use fidl_fuchsia_recovery_policy::{DeviceMarker, DeviceProxy};
464 use fidl_fuchsia_recovery_ui::{FactoryResetCountdownMarker, FactoryResetCountdownProxy};
465 use fuchsia_async::TestExecutor;
466 use pretty_assertions::assert_eq;
467 use std::pin::pin;
468 use std::task::Poll;
469
470 fn create_factory_reset_countdown_proxy(
471 reset_handler: Rc<FactoryResetHandler>,
472 ) -> FactoryResetCountdownProxy {
473 let (countdown_proxy, countdown_stream) =
474 create_proxy_and_stream::<FactoryResetCountdownMarker>();
475
476 let stream_fut =
477 reset_handler.clone().handle_factory_reset_countdown_request_stream(countdown_stream);
478
479 Task::local(async move {
480 if stream_fut.await.is_err() {
481 log::warn!("Failed to handle factory reset countdown request stream");
482 }
483 })
484 .detach();
485
486 countdown_proxy
487 }
488
489 fn create_recovery_policy_proxy(reset_handler: Rc<FactoryResetHandler>) -> DeviceProxy {
490 let (device_proxy, device_stream) = create_proxy_and_stream::<DeviceMarker>();
491
492 Task::local(async move {
493 if reset_handler
494 .handle_recovery_policy_device_request_stream(device_stream)
495 .await
496 .is_err()
497 {
498 log::warn!("Failed to handle recovery policy device request stream");
499 }
500 })
501 .detach();
502
503 device_proxy
504 }
505
506 fn create_input_device_descriptor() -> input_device::InputDeviceDescriptor {
507 input_device::InputDeviceDescriptor::ConsumerControls(ConsumerControlsDeviceDescriptor {
508 buttons: vec![
509 fidl_input_report::ConsumerControlButton::CameraDisable,
510 fidl_input_report::ConsumerControlButton::FactoryReset,
511 fidl_input_report::ConsumerControlButton::MicMute,
512 fidl_input_report::ConsumerControlButton::Pause,
513 fidl_input_report::ConsumerControlButton::VolumeDown,
514 fidl_input_report::ConsumerControlButton::VolumeUp,
515 ],
516 device_id: 0,
517 })
518 }
519
520 fn create_reset_consumer_controls_event() -> ConsumerControlsEvent {
521 ConsumerControlsEvent::new(vec![fidl_input_report::ConsumerControlButton::FactoryReset])
522 }
523
524 fn create_non_reset_consumer_controls_event() -> ConsumerControlsEvent {
525 ConsumerControlsEvent::new(vec![
526 fidl_input_report::ConsumerControlButton::CameraDisable,
527 fidl_input_report::ConsumerControlButton::MicMute,
528 fidl_input_report::ConsumerControlButton::Pause,
529 fidl_input_report::ConsumerControlButton::VolumeDown,
530 fidl_input_report::ConsumerControlButton::VolumeUp,
531 ])
532 }
533
534 fn create_non_reset_input_event() -> input_device::UnhandledInputEvent {
535 let device_event = input_device::InputDeviceEvent::ConsumerControls(
536 create_non_reset_consumer_controls_event(),
537 );
538
539 input_device::UnhandledInputEvent {
540 device_event,
541 device_descriptor: create_input_device_descriptor(),
542 event_time: zx::MonotonicInstant::get(),
543 trace_id: None,
544 }
545 }
546
547 fn create_reset_input_event() -> input_device::UnhandledInputEvent {
548 let device_event = input_device::InputDeviceEvent::ConsumerControls(
549 create_reset_consumer_controls_event(),
550 );
551
552 input_device::UnhandledInputEvent {
553 device_event,
554 device_descriptor: create_input_device_descriptor(),
555 event_time: zx::MonotonicInstant::get(),
556 trace_id: None,
557 }
558 }
559
560 #[fuchsia::test]
561 async fn is_reset_requested_looks_for_reset_signal() {
562 let reset_event = create_reset_consumer_controls_event();
563 let non_reset_event = create_non_reset_consumer_controls_event();
564
565 assert!(
566 is_reset_requested(&reset_event),
567 "Should reset when the reset signal is received."
568 );
569 assert!(
570 !is_reset_requested(&non_reset_event),
571 "Should only reset when the reset signal is received."
572 );
573 }
574
575 #[fuchsia::test]
576 async fn factory_reset_countdown_listener_gets_initial_state() {
577 let inspector = fuchsia_inspect::Inspector::default();
578 let test_node = inspector.root().create_child("test_node");
579 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
580 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
581 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
582 assert_eq!(reset_state.scheduled_reset_time, None);
583 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
584 }
585
586 #[fuchsia::test]
587 fn factory_reset_countdown_listener_is_notified_on_state_change() -> Result<(), Error> {
588 let mut executor = TestExecutor::new_with_fake_time();
589 let inspector = fuchsia_inspect::Inspector::default();
590 let test_node = inspector.root().create_child("test_node");
591 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
592 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
593
594 let get_countdown_state = |executor: &mut TestExecutor| {
595 let mut fut = countdown_proxy.watch();
596 loop {
597 match executor.run_until_stalled(&mut fut) {
599 Poll::Pending => continue,
600 Poll::Ready(state) => {
601 return state.expect("Failed to get countdown state");
602 }
603 }
604 }
605 };
606
607 let countdown_state = get_countdown_state(&mut executor);
610 let handler_state = reset_handler.factory_reset_state();
611 assert_eq!(countdown_state.scheduled_reset_time, None);
612 assert_eq!(handler_state, FactoryResetState::Idle);
613
614 let reset_event = create_reset_input_event();
616 let mut handle_input_event_fut =
617 pin!(reset_handler.clone().handle_unhandled_input_event(reset_event));
618 assert_matches!(executor.run_until_stalled(&mut handle_input_event_fut), Poll::Ready(events) => {
619 assert_matches!(events.as_slice(), [input_device::InputEvent { .. }]);
620 });
621
622 let countdown_state = get_countdown_state(&mut executor);
624 let handler_state = reset_handler.factory_reset_state();
625 assert_eq!(countdown_state.scheduled_reset_time, None);
626 assert_matches!(handler_state, FactoryResetState::ButtonCountdown { deadline: _ });
627
628 executor.set_fake_time(MonotonicInstant::after(MonotonicDuration::from_millis(500)));
630 executor.wake_expired_timers();
631
632 let countdown_state = get_countdown_state(&mut executor);
635 let handler_state = reset_handler.factory_reset_state();
636 assert_matches!(countdown_state.scheduled_reset_time, Some(_));
637 assert_matches!(handler_state, FactoryResetState::ResetCountdown { deadline: _ });
638
639 executor.set_fake_time(MonotonicInstant::after(MonotonicDuration::from_seconds(10)));
641 executor.wake_expired_timers();
642
643 let countdown_state = get_countdown_state(&mut executor);
646 let handler_state = reset_handler.factory_reset_state();
647 assert_eq!(countdown_state.scheduled_reset_time, None);
648 assert_eq!(handler_state, FactoryResetState::Resetting);
649
650 Ok(())
651 }
652
653 #[fuchsia::test]
654 async fn recovery_policy_requests_update_reset_handler_state() {
655 let inspector = fuchsia_inspect::Inspector::default();
656 let test_node = inspector.root().create_child("test_node");
657 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
658 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
659
660 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
662 assert_eq!(reset_state.scheduled_reset_time, None);
663 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
664
665 let device_proxy = create_recovery_policy_proxy(reset_handler.clone());
667 device_proxy.set_is_local_reset_allowed(false).expect("Failed to set recovery policy");
668
669 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
671 assert_eq!(reset_state.scheduled_reset_time, None);
672 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Disallowed);
673
674 let reset_event = create_reset_input_event();
676 reset_handler.clone().handle_unhandled_input_event(reset_event).await;
677
678 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Disallowed);
680
681 let device_proxy = create_recovery_policy_proxy(reset_handler.clone());
683 device_proxy.set_is_local_reset_allowed(true).expect("Failed to set recovery policy");
684
685 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
687 assert_eq!(reset_state.scheduled_reset_time, None);
688 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
689 }
690
691 #[fuchsia::test]
692 fn handle_allowed_event_changes_state_with_reset() {
693 let mut executor = TestExecutor::new();
694
695 let reset_event = create_reset_consumer_controls_event();
696 let inspector = fuchsia_inspect::Inspector::default();
697 let test_node = inspector.root().create_child("test_node");
698 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
699 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
700
701 let reset_state = executor
703 .run_singlethreaded(countdown_proxy.watch())
704 .expect("Failed to get countdown state");
705 assert_eq!(reset_state.scheduled_reset_time, None);
706 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
707
708 let handle_allowed_event_fut = reset_handler.handle_allowed_event(&reset_event);
709 futures::pin_mut!(handle_allowed_event_fut);
710 assert_eq!(executor.run_until_stalled(&mut handle_allowed_event_fut), Poll::Pending);
711
712 assert_matches!(
714 executor.run_singlethreaded(countdown_proxy.watch()),
715 Ok(FactoryResetCountdownState { scheduled_reset_time: None, .. })
716 );
717 assert_matches!(
718 reset_handler.factory_reset_state(),
719 FactoryResetState::ButtonCountdown { deadline: _ }
720 );
721 }
722
723 #[fuchsia::test]
724 async fn handle_allowed_event_wont_change_state_without_reset() {
725 let inspector = fuchsia_inspect::Inspector::default();
726 let test_node = inspector.root().create_child("test_node");
727 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
728 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
729
730 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
732 assert_eq!(reset_state.scheduled_reset_time, None);
733 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
734
735 let non_reset_event = create_non_reset_consumer_controls_event();
736 reset_handler.clone().handle_allowed_event(&non_reset_event).await;
737
738 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
740 }
741
742 #[fuchsia::test]
743 async fn handle_disallowed_event_wont_change_state() {
744 let inspector = fuchsia_inspect::Inspector::default();
745 let test_node = inspector.root().create_child("test_node");
746 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
747 *reset_handler.factory_reset_state.borrow_mut() = FactoryResetState::Disallowed;
748
749 let reset_event = create_reset_consumer_controls_event();
752 reset_handler.handle_disallowed_event(&reset_event);
753 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Disallowed);
754
755 let non_reset_event = create_non_reset_consumer_controls_event();
756 reset_handler.handle_disallowed_event(&non_reset_event);
757 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Disallowed);
758 }
759
760 #[fuchsia::test]
761 async fn handle_button_countdown_event_changes_state_when_reset_no_longer_requested() {
762 let inspector = fuchsia_inspect::Inspector::default();
763 let test_node = inspector.root().create_child("test_node");
764 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
765
766 let deadline = MonotonicInstant::after(BUTTON_TIMEOUT);
767 *reset_handler.factory_reset_state.borrow_mut() =
768 FactoryResetState::ButtonCountdown { deadline };
769
770 let non_reset_event = create_non_reset_consumer_controls_event();
773 reset_handler.handle_button_countdown_event(&non_reset_event);
774 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
775 }
776
777 #[fuchsia::test]
778 async fn handle_reset_countdown_event_changes_state_when_reset_no_longer_requested() {
779 let inspector = fuchsia_inspect::Inspector::default();
780 let test_node = inspector.root().create_child("test_node");
781 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
782
783 *reset_handler.factory_reset_state.borrow_mut() =
784 FactoryResetState::ResetCountdown { deadline: MonotonicInstant::now() };
785
786 let non_reset_event = create_non_reset_consumer_controls_event();
789 reset_handler.handle_reset_countdown_event(&non_reset_event);
790 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
791 }
792
793 #[fuchsia::test]
794 async fn factory_reset_disallowed_during_button_countdown() {
795 let inspector = fuchsia_inspect::Inspector::default();
796 let test_node = inspector.root().create_child("test_node");
797 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
798 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
799
800 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
802 assert_eq!(reset_state.scheduled_reset_time, None);
803 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
804
805 let reset_event = create_reset_input_event();
807 reset_handler.clone().handle_unhandled_input_event(reset_event).await;
808
809 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
811 assert_eq!(reset_state.scheduled_reset_time, None);
812 assert_matches!(
813 reset_handler.factory_reset_state(),
814 FactoryResetState::ButtonCountdown { deadline: _ }
815 );
816
817 let device_proxy = create_recovery_policy_proxy(reset_handler.clone());
819 device_proxy.set_is_local_reset_allowed(false).expect("Failed to set recovery policy");
820
821 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
823 assert_eq!(reset_state.scheduled_reset_time, None);
824 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Disallowed);
825 }
826
827 #[fuchsia::test]
828 async fn factory_reset_disallowed_during_reset_countdown() {
829 let inspector = fuchsia_inspect::Inspector::default();
830 let test_node = inspector.root().create_child("test_node");
831 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
832 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
833
834 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
836 assert_eq!(reset_state.scheduled_reset_time, None);
837 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
838
839 let reset_event = create_reset_input_event();
841 reset_handler.clone().handle_unhandled_input_event(reset_event).await;
842
843 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
845 assert_eq!(reset_state.scheduled_reset_time, None);
846 assert_matches!(
847 reset_handler.factory_reset_state(),
848 FactoryResetState::ButtonCountdown { deadline: _ }
849 );
850
851 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
853 assert_matches!(reset_state.scheduled_reset_time, Some(_));
854 assert_matches!(
855 reset_handler.factory_reset_state(),
856 FactoryResetState::ResetCountdown { deadline: _ }
857 );
858
859 let device_proxy = create_recovery_policy_proxy(reset_handler.clone());
861 device_proxy.set_is_local_reset_allowed(false).expect("Failed to set recovery policy");
862
863 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
865 assert_eq!(reset_state.scheduled_reset_time, None);
866 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Disallowed);
867 }
868
869 #[fuchsia::test]
870 async fn factory_reset_cancelled_during_button_countdown() {
871 let inspector = fuchsia_inspect::Inspector::default();
872 let test_node = inspector.root().create_child("test_node");
873 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
874 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
875
876 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
878 assert_eq!(reset_state.scheduled_reset_time, None);
879 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
880
881 let reset_event = create_reset_input_event();
883 reset_handler.clone().handle_unhandled_input_event(reset_event).await;
884
885 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
887 assert_eq!(reset_state.scheduled_reset_time, None);
888 assert_matches!(
889 reset_handler.factory_reset_state(),
890 FactoryResetState::ButtonCountdown { deadline: _ }
891 );
892
893 let non_reset_event = create_non_reset_input_event();
895 reset_handler.clone().handle_unhandled_input_event(non_reset_event).await;
896
897 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
899 assert_eq!(reset_state.scheduled_reset_time, None);
900 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
901 }
902
903 #[fuchsia::test]
904 async fn factory_reset_cancelled_during_reset_countdown() {
905 let inspector = fuchsia_inspect::Inspector::default();
906 let test_node = inspector.root().create_child("test_node");
907 let reset_handler = FactoryResetHandler::new(&test_node, metrics::MetricsLogger::default());
908 let countdown_proxy = create_factory_reset_countdown_proxy(reset_handler.clone());
909
910 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
912 assert_eq!(reset_state.scheduled_reset_time, None);
913 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
914
915 let reset_event = create_reset_input_event();
917 reset_handler.clone().handle_unhandled_input_event(reset_event).await;
918
919 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
921 assert_eq!(reset_state.scheduled_reset_time, None);
922 assert_matches!(
923 reset_handler.factory_reset_state(),
924 FactoryResetState::ButtonCountdown { deadline: _ }
925 );
926
927 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
929 assert_matches!(reset_state.scheduled_reset_time, Some(_));
930 assert_matches!(
931 reset_handler.factory_reset_state(),
932 FactoryResetState::ResetCountdown { deadline: _ }
933 );
934
935 let non_reset_event = create_non_reset_input_event();
937 reset_handler.clone().handle_unhandled_input_event(non_reset_event).await;
938
939 let reset_state = countdown_proxy.watch().await.expect("Failed to get countdown state");
941 assert_eq!(reset_state.scheduled_reset_time, None);
942 assert_eq!(reset_handler.factory_reset_state(), FactoryResetState::Idle);
943 }
944
945 #[fuchsia::test]
946 fn factory_reset_handler_initialized_with_inspect_node() {
947 let inspector = fuchsia_inspect::Inspector::default();
948 let fake_handlers_node = inspector.root().create_child("input_handlers_node");
949 let _handler =
950 FactoryResetHandler::new(&fake_handlers_node, metrics::MetricsLogger::default());
951 diagnostics_assertions::assert_data_tree!(inspector, root: {
952 input_handlers_node: {
953 factory_reset_handler: {
954 events_received_count: 0u64,
955 events_handled_count: 0u64,
956 last_received_timestamp_ns: 0u64,
957 "fuchsia.inspect.Health": {
958 status: "STARTING_UP",
959 start_timestamp_nanos: diagnostics_assertions::AnyProperty
962 },
963 }
964 }
965 });
966 }
967
968 #[fuchsia::test]
969 async fn factory_reset_handler_inspect_counts_events() {
970 let inspector = fuchsia_inspect::Inspector::default();
971 let fake_handlers_node = inspector.root().create_child("input_handlers_node");
972 let reset_handler =
973 FactoryResetHandler::new(&fake_handlers_node, metrics::MetricsLogger::default());
974
975 let reset_event = create_reset_input_event();
977 reset_handler.clone().handle_unhandled_input_event(reset_event).await;
978
979 let mut handled_event = input_device::InputEvent::from(create_reset_input_event());
981 handled_event.handled = input_device::Handled::Yes;
982 reset_handler.clone().handle_input_event(handled_event).await;
983
984 let non_reset_event = create_non_reset_input_event();
986 let last_event_timestamp: u64 =
987 non_reset_event.clone().event_time.into_nanos().try_into().unwrap();
988 reset_handler.clone().handle_unhandled_input_event(non_reset_event).await;
989
990 diagnostics_assertions::assert_data_tree!(inspector, root: {
991 input_handlers_node: {
992 factory_reset_handler: {
993 events_received_count: 2u64,
994 events_handled_count: 0u64,
995 last_received_timestamp_ns: last_event_timestamp,
996 "fuchsia.inspect.Health": {
997 status: "STARTING_UP",
998 start_timestamp_nanos: diagnostics_assertions::AnyProperty
1001 },
1002 }
1003 }
1004 });
1005 }
1006}