Debian Codegraph @

third_party/rust/authenticator/src/authenticatorservice.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use crate::ctap2::commands::client_pin::Pin;
6 use crate::ctap2::server::{
7 AuthenticationExtensionsClientInputs, PublicKeyCredentialDescriptor,
8 PublicKeyCredentialParameters, PublicKeyCredentialUserEntity, RelyingParty,
9 ResidentKeyRequirement, UserVerificationRequirement,
10 };
11 use crate::errors::*;
12 use crate::manager::Manager;
13 use crate::statecallback::StateCallback;
14 use std::sync::{mpsc::Sender, Arc, Mutex};
15
16 #[derive(Debug, Clone)]
17 pub struct RegisterArgs {
18 pub client_data_hash: [u8; 32],
19 pub relying_party: RelyingParty,
20 pub origin: String,
21 pub user: PublicKeyCredentialUserEntity,
22 pub pub_cred_params: Vec<PublicKeyCredentialParameters>,
23 pub exclude_list: Vec<PublicKeyCredentialDescriptor>,
24 pub user_verification_req: UserVerificationRequirement,
25 pub resident_key_req: ResidentKeyRequirement,
26 pub extensions: AuthenticationExtensionsClientInputs,
27 pub pin: Option<Pin>,
28 pub use_ctap1_fallback: bool,
29 }
30
31 #[derive(Debug, Clone)]
32 pub struct SignArgs {
33 pub client_data_hash: [u8; 32],
34 pub origin: String,
35 pub relying_party_id: String,
36 pub allow_list: Vec<PublicKeyCredentialDescriptor>,
37 pub user_verification_req: UserVerificationRequirement,
38 pub user_presence_req: bool,
39 pub extensions: AuthenticationExtensionsClientInputs,
40 pub pin: Option<Pin>,
41 pub use_ctap1_fallback: bool,
42 }
43
44 pub trait AuthenticatorTransport {
45 /// The implementation of this method must return quickly and should
46 /// report its status via the status and callback methods
47 fn register(
48 &mut self,
49 timeout: u64,
50 ctap_args: RegisterArgs,
51 status: Sender<crate::StatusUpdate>,
52 callback: StateCallback<crate::Result<crate::RegisterResult>>,
53 ) -> crate::Result<()>;
54
55 /// The implementation of this method must return quickly and should
56 /// report its status via the status and callback methods
57 fn sign(
58 &mut self,
59 timeout: u64,
60 ctap_args: SignArgs,
61 status: Sender<crate::StatusUpdate>,
62 callback: StateCallback<crate::Result<crate::SignResult>>,
63 ) -> crate::Result<()>;
64
65 fn cancel(&mut self) -> crate::Result<()>;
66 fn reset(
67 &mut self,
68 timeout: u64,
69 status: Sender<crate::StatusUpdate>,
70 callback: StateCallback<crate::Result<crate::ResetResult>>,
71 ) -> crate::Result<()>;
72 fn set_pin(
73 &mut self,
74 timeout: u64,
75 new_pin: Pin,
76 status: Sender<crate::StatusUpdate>,
77 callback: StateCallback<crate::Result<crate::ResetResult>>,
78 ) -> crate::Result<()>;
79 fn manage(
80 &mut self,
81 timeout: u64,
82 status: Sender<crate::StatusUpdate>,
83 callback: StateCallback<crate::Result<crate::ManageResult>>,
84 ) -> crate::Result<()>;
85 }
86
87 pub struct AuthenticatorService {
88 transports: Vec<Arc<Mutex<Box<dyn AuthenticatorTransport + Send>>>>,
89 }
90
91 fn clone_and_configure_cancellation_callback<T>(
92 mut callback: StateCallback<T>,
93 transports_to_cancel: Vec<Arc<Mutex<Box<dyn AuthenticatorTransport + Send>>>>,
94 ) -> StateCallback<T> {
95 callback.add_uncloneable_observer(Box::new(move || {
96 debug!(
97 "Callback observer is running, cancelling \
98 {} unchosen transports...",
99 transports_to_cancel.len()
100 );
101 for transport_mutex in &transports_to_cancel {
102 if let Err(e) = transport_mutex.lock().unwrap().cancel() {
103 error!("Cancellation failed: {:?}", e);
104 }
105 }
106 }));
107 callback
108 }
109
110 impl AuthenticatorService {
111 pub fn new() -> crate::Result<Self> {
112 Ok(Self {
113 transports: Vec::new(),
114 })
115 }
116
117 /// Add any detected platform transports
118 pub fn add_detected_transports(&mut self) {
119 self.add_u2f_usb_hid_platform_transports();
120 }
121
122 pub fn add_transport(&mut self, boxed_token: Box<dyn AuthenticatorTransport + Send>) {
123 self.transports.push(Arc::new(Mutex::new(boxed_token)))
124 }
125
126 pub fn add_u2f_usb_hid_platform_transports(&mut self) {
127 match Manager::new() {
128 Ok(token) => self.add_transport(Box::new(token)),
129 Err(e) => error!("Could not add CTAP2 HID transport: {}", e),
130 }
131 }
132
133 pub fn register(
134 &mut self,
135 timeout: u64,
136 args: RegisterArgs,
137 status: Sender<crate::StatusUpdate>,
138 callback: StateCallback<crate::Result<crate::RegisterResult>>,
139 ) -> crate::Result<()> {
140 let iterable_transports = self.transports.clone();
141 if iterable_transports.is_empty() {
142 return Err(AuthenticatorError::NoConfiguredTransports);
143 }
144
145 debug!(
146 "register called with {} transports, iterable is {}",
147 self.transports.len(),
148 iterable_transports.len()
149 );
150
151 for (idx, transport_mutex) in iterable_transports.iter().enumerate() {
152 let mut transports_to_cancel = iterable_transports.clone();
153 transports_to_cancel.remove(idx);
154
155 debug!(
156 "register transports_to_cancel {}",
157 transports_to_cancel.len()
158 );
159
160 transport_mutex.lock().unwrap().register(
161 timeout,
162 args.clone(),
163 status.clone(),
164 clone_and_configure_cancellation_callback(callback.clone(), transports_to_cancel),
165 )?;
166 }
167
168 Ok(())
169 }
170
171 pub fn sign(
172 &mut self,
173 timeout: u64,
174 args: SignArgs,
175 status: Sender<crate::StatusUpdate>,
176 callback: StateCallback<crate::Result<crate::SignResult>>,
177 ) -> crate::Result<()> {
178 let iterable_transports = self.transports.clone();
179 if iterable_transports.is_empty() {
180 return Err(AuthenticatorError::NoConfiguredTransports);
181 }
182
183 for (idx, transport_mutex) in iterable_transports.iter().enumerate() {
184 let mut transports_to_cancel = iterable_transports.clone();
185 transports_to_cancel.remove(idx);
186
187 transport_mutex.lock().unwrap().sign(
188 timeout,
189 args.clone(),
190 status.clone(),
191 clone_and_configure_cancellation_callback(callback.clone(), transports_to_cancel),
192 )?;
193 }
194
195 Ok(())
196 }
197
198 pub fn cancel(&mut self) -> crate::Result<()> {
199 if self.transports.is_empty() {
200 return Err(AuthenticatorError::NoConfiguredTransports);
201 }
202
203 for transport_mutex in &mut self.transports {
204 transport_mutex.lock().unwrap().cancel()?;
205 }
206
207 Ok(())
208 }
209
210 pub fn reset(
211 &mut self,
212 timeout: u64,
213 status: Sender<crate::StatusUpdate>,
214 callback: StateCallback<crate::Result<crate::ResetResult>>,
215 ) -> crate::Result<()> {
216 let iterable_transports = self.transports.clone();
217 if iterable_transports.is_empty() {
218 return Err(AuthenticatorError::NoConfiguredTransports);
219 }
220
221 debug!(
222 "reset called with {} transports, iterable is {}",
223 self.transports.len(),
224 iterable_transports.len()
225 );
226
227 for (idx, transport_mutex) in iterable_transports.iter().enumerate() {
228 let mut transports_to_cancel = iterable_transports.clone();
229 transports_to_cancel.remove(idx);
230
231 debug!("reset transports_to_cancel {}", transports_to_cancel.len());
232
233 transport_mutex.lock().unwrap().reset(
234 timeout,
235 status.clone(),
236 clone_and_configure_cancellation_callback(callback.clone(), transports_to_cancel),
237 )?;
238 }
239
240 Ok(())
241 }
242
243 pub fn set_pin(
244 &mut self,
245 timeout: u64,
246 new_pin: Pin,
247 status: Sender<crate::StatusUpdate>,
248 callback: StateCallback<crate::Result<crate::ResetResult>>,
249 ) -> crate::Result<()> {
250 let iterable_transports = self.transports.clone();
251 if iterable_transports.is_empty() {
252 return Err(AuthenticatorError::NoConfiguredTransports);
253 }
254
255 debug!(
256 "reset called with {} transports, iterable is {}",
257 self.transports.len(),
258 iterable_transports.len()
259 );
260
261 for (idx, transport_mutex) in iterable_transports.iter().enumerate() {
262 let mut transports_to_cancel = iterable_transports.clone();
263 transports_to_cancel.remove(idx);
264
265 debug!("reset transports_to_cancel {}", transports_to_cancel.len());
266
267 transport_mutex.lock().unwrap().set_pin(
268 timeout,
269 new_pin.clone(),
270 status.clone(),
271 clone_and_configure_cancellation_callback(callback.clone(), transports_to_cancel),
272 )?;
273 }
274
275 Ok(())
276 }
277
278 pub fn manage(
279 &mut self,
280 timeout: u64,
281 status: Sender<crate::StatusUpdate>,
282 callback: StateCallback<crate::Result<crate::ManageResult>>,
283 ) -> crate::Result<()> {
284 let iterable_transports = self.transports.clone();
285 if iterable_transports.is_empty() {
286 return Err(AuthenticatorError::NoConfiguredTransports);
287 }
288
289 debug!(
290 "Manage called with {} transports, iterable is {}",
291 self.transports.len(),
292 iterable_transports.len()
293 );
294
295 for (idx, transport_mutex) in iterable_transports.iter().enumerate() {
296 let mut transports_to_cancel = iterable_transports.clone();
297 transports_to_cancel.remove(idx);
298
299 debug!("reset transports_to_cancel {}", transports_to_cancel.len());
300
301 transport_mutex.lock().unwrap().manage(
302 timeout,
303 status.clone(),
304 clone_and_configure_cancellation_callback(callback.clone(), transports_to_cancel),
305 )?;
306 }
307
308 Ok(())
309 }
310 }
311
312 ////////////////////////////////////////////////////////////////////////
313 // Tests
314 ////////////////////////////////////////////////////////////////////////
315
316 #[cfg(test)]
317 mod tests {
318 use super::{AuthenticatorService, AuthenticatorTransport, Pin, RegisterArgs, SignArgs};
319 use crate::consts::PARAMETER_SIZE;
320 use crate::ctap2::server::{
321 PublicKeyCredentialUserEntity, RelyingParty, ResidentKeyRequirement,
322 UserVerificationRequirement,
323 };
324 use crate::errors::AuthenticatorError;
325 use crate::statecallback::StateCallback;
326 use crate::StatusUpdate;
327 use std::sync::atomic::{AtomicBool, Ordering};
328 use std::sync::mpsc::{channel, Sender};
329 use std::sync::Arc;
330 use std::{io, thread};
331
332 fn init() {
333 let _ = env_logger::builder().is_test(true).try_init();
334 }
335
336 pub struct TestTransportDriver {
337 consent: bool,
338 was_cancelled: Arc<AtomicBool>,
339 }
340
341 impl TestTransportDriver {
342 pub fn new(consent: bool) -> io::Result<Self> {
343 Ok(Self {
344 consent,
345 was_cancelled: Arc::new(AtomicBool::new(false)),
346 })
347 }
348 }
349
350 impl AuthenticatorTransport for TestTransportDriver {
351 fn register(
352 &mut self,
353 _timeout: u64,
354 _args: RegisterArgs,
355 _status: Sender<crate::StatusUpdate>,
356 callback: StateCallback<crate::Result<crate::RegisterResult>>,
357 ) -> crate::Result<()> {
358 if self.consent {
359 // The value we send is ignored, and this is easier than constructing a
360 // RegisterResult
361 let rv = Err(AuthenticatorError::Platform);
362 thread::spawn(move || callback.call(rv));
363 }
364 Ok(())
365 }
366
367 fn sign(
368 &mut self,
369 _timeout: u64,
370 _ctap_args: SignArgs,
371 _status: Sender<crate::StatusUpdate>,
372 callback: StateCallback<crate::Result<crate::SignResult>>,
373 ) -> crate::Result<()> {
374 if self.consent {
375 // The value we send is ignored, and this is easier than constructing a
376 // RegisterResult
377 let rv = Err(AuthenticatorError::Platform);
378 thread::spawn(move || callback.call(rv));
379 }
380 Ok(())
381 }
382
383 fn cancel(&mut self) -> crate::Result<()> {
384 self.was_cancelled
385 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
386 .map_or(
387 Err(crate::errors::AuthenticatorError::U2FToken(
388 crate::errors::U2FTokenError::InvalidState,
389 )),
390 |_| Ok(()),
391 )
392 }
393
394 fn reset(
395 &mut self,
396 _timeout: u64,
397 _status: Sender<crate::StatusUpdate>,
398 _callback: StateCallback<crate::Result<crate::ResetResult>>,
399 ) -> crate::Result<()> {
400 unimplemented!();
401 }
402
403 fn set_pin(
404 &mut self,
405 _timeout: u64,
406 _new_pin: Pin,
407 _status: Sender<crate::StatusUpdate>,
408 _callback: StateCallback<crate::Result<crate::ResetResult>>,
409 ) -> crate::Result<()> {
410 unimplemented!();
411 }
412
413 fn manage(
414 &mut self,
415 _timeout: u64,
416 _status: Sender<crate::StatusUpdate>,
417 _callback: StateCallback<crate::Result<crate::ManageResult>>,
418 ) -> crate::Result<()> {
419 unimplemented!();
420 }
421 }
422
423 fn mk_challenge() -> [u8; PARAMETER_SIZE] {
424 [0x11; PARAMETER_SIZE]
425 }
426
427 #[test]
428 fn test_no_transports() {
429 init();
430 let (status_tx, _) = channel::<StatusUpdate>();
431
432 let mut s = AuthenticatorService::new().unwrap();
433 assert_matches!(
434 s.register(
435 1_000,
436 RegisterArgs {
437 client_data_hash: mk_challenge(),
438 relying_party: RelyingParty {
439 id: "example.com".to_string(),
440 name: None,
441 },
442 origin: "example.com".to_string(),
443 user: PublicKeyCredentialUserEntity {
444 id: "user_id".as_bytes().to_vec(),
445 name: Some("A. User".to_string()),
446 display_name: None,
447 },
448 pub_cred_params: vec![],
449 exclude_list: vec![],
450 user_verification_req: UserVerificationRequirement::Preferred,
451 resident_key_req: ResidentKeyRequirement::Preferred,
452 extensions: Default::default(),
453 pin: None,
454 use_ctap1_fallback: false,
455 },
456 status_tx.clone(),
457 StateCallback::new(Box::new(move |_rv| {})),
458 )
459 .unwrap_err(),
460 crate::errors::AuthenticatorError::NoConfiguredTransports
461 );
462
463 assert_matches!(
464 s.sign(
465 1_000,
466 SignArgs {
467 client_data_hash: mk_challenge(),
468 origin: "example.com".to_string(),
469 relying_party_id: "example.com".to_string(),
470 allow_list: vec![],
471 user_verification_req: UserVerificationRequirement::Preferred,
472 user_presence_req: true,
473 extensions: Default::default(),
474 pin: None,
475 use_ctap1_fallback: false,
476 },
477 status_tx,
478 StateCallback::new(Box::new(move |_rv| {})),
479 )
480 .unwrap_err(),
481 crate::errors::AuthenticatorError::NoConfiguredTransports
482 );
483
484 assert_matches!(
485 s.cancel().unwrap_err(),
486 crate::errors::AuthenticatorError::NoConfiguredTransports
487 );
488 }
489
490 #[test]
491 fn test_cancellation_register() {
492 init();
493 let (status_tx, _) = channel::<StatusUpdate>();
494
495 let mut s = AuthenticatorService::new().unwrap();
496 let ttd_one = TestTransportDriver::new(true).unwrap();
497 let ttd_two = TestTransportDriver::new(false).unwrap();
498 let ttd_three = TestTransportDriver::new(false).unwrap();
499
500 let was_cancelled_one = ttd_one.was_cancelled.clone();
501 let was_cancelled_two = ttd_two.was_cancelled.clone();
502 let was_cancelled_three = ttd_three.was_cancelled.clone();
503
504 s.add_transport(Box::new(ttd_one));
505 s.add_transport(Box::new(ttd_two));
506 s.add_transport(Box::new(ttd_three));
507
508 let callback = StateCallback::new(Box::new(move |_rv| {}));
509 assert!(s
510 .register(
511 1_000,
512 RegisterArgs {
513 client_data_hash: mk_challenge(),
514 relying_party: RelyingParty {
515 id: "example.com".to_string(),
516 name: None,
517 },
518 origin: "example.com".to_string(),
519 user: PublicKeyCredentialUserEntity {
520 id: "user_id".as_bytes().to_vec(),
521 name: Some("A. User".to_string()),
522 display_name: None,
523 },
524 pub_cred_params: vec![],
525 exclude_list: vec![],
526 user_verification_req: UserVerificationRequirement::Preferred,
527 resident_key_req: ResidentKeyRequirement::Preferred,
528 extensions: Default::default(),
529 pin: None,
530 use_ctap1_fallback: false,
531 },
532 status_tx,
533 callback.clone(),
534 )
535 .is_ok());
536 callback.wait();
537
538 assert!(!was_cancelled_one.load(Ordering::SeqCst));
539 assert!(was_cancelled_two.load(Ordering::SeqCst));
540 assert!(was_cancelled_three.load(Ordering::SeqCst));
541 }
542
543 #[test]
544 fn test_cancellation_sign() {
545 init();
546 let (status_tx, _) = channel::<StatusUpdate>();
547
548 let mut s = AuthenticatorService::new().unwrap();
549 let ttd_one = TestTransportDriver::new(true).unwrap();
550 let ttd_two = TestTransportDriver::new(false).unwrap();
551 let ttd_three = TestTransportDriver::new(false).unwrap();
552
553 let was_cancelled_one = ttd_one.was_cancelled.clone();
554 let was_cancelled_two = ttd_two.was_cancelled.clone();
555 let was_cancelled_three = ttd_three.was_cancelled.clone();
556
557 s.add_transport(Box::new(ttd_one));
558 s.add_transport(Box::new(ttd_two));
559 s.add_transport(Box::new(ttd_three));
560
561 let callback = StateCallback::new(Box::new(move |_rv| {}));
562 assert!(s
563 .sign(
564 1_000,
565 SignArgs {
566 client_data_hash: mk_challenge(),
567 origin: "example.com".to_string(),
568 relying_party_id: "example.com".to_string(),
569 allow_list: vec![],
570 user_verification_req: UserVerificationRequirement::Preferred,
571 user_presence_req: true,
572 extensions: Default::default(),
573 pin: None,
574 use_ctap1_fallback: false,
575 },
576 status_tx,
577 callback.clone(),
578 )
579 .is_ok());
580 callback.wait();
581
582 assert!(!was_cancelled_one.load(Ordering::SeqCst));
583 assert!(was_cancelled_two.load(Ordering::SeqCst));
584 assert!(was_cancelled_three.load(Ordering::SeqCst));
585 }
586
587 #[test]
588 fn test_cancellation_race() {
589 init();
590 let (status_tx, _) = channel::<StatusUpdate>();
591
592 let mut s = AuthenticatorService::new().unwrap();
593 // Let both of these race which one provides consent.
594 let ttd_one = TestTransportDriver::new(true).unwrap();
595 let ttd_two = TestTransportDriver::new(true).unwrap();
596
597 let was_cancelled_one = ttd_one.was_cancelled.clone();
598 let was_cancelled_two = ttd_two.was_cancelled.clone();
599
600 s.add_transport(Box::new(ttd_one));
601 s.add_transport(Box::new(ttd_two));
602
603 let callback = StateCallback::new(Box::new(move |_rv| {}));
604 assert!(s
605 .register(
606 1_000,
607 RegisterArgs {
608 client_data_hash: mk_challenge(),
609 relying_party: RelyingParty {
610 id: "example.com".to_string(),
611 name: None,
612 },
613 origin: "example.com".to_string(),
614 user: PublicKeyCredentialUserEntity {
615 id: "user_id".as_bytes().to_vec(),
616 name: Some("A. User".to_string()),
617 display_name: None,
618 },
619 pub_cred_params: vec![],
620 exclude_list: vec![],
621 user_verification_req: UserVerificationRequirement::Preferred,
622 resident_key_req: ResidentKeyRequirement::Preferred,
623 extensions: Default::default(),
624 pin: None,
625 use_ctap1_fallback: false,
626 },
627 status_tx,
628 callback.clone(),
629 )
630 .is_ok());
631 callback.wait();
632
633 let one = was_cancelled_one.load(Ordering::SeqCst);
634 let two = was_cancelled_two.load(Ordering::SeqCst);
635 assert!(
636 one ^ two,
637 "asserting that one={} xor two={} is true",
638 one,
639 two
640 );
641 }
642 }