1use std::time::Duration;
5
6use serde_json::json;
7use url::{Url, form_urlencoded};
8use zeroize::Zeroizing;
9
10use self::{
11 cpace::SignIn,
12 enrollment::enroll_device,
13 ui::{SsoLoginResult, SsoUi},
14};
15use super::{
16 credentials::SsoCredentials,
17 device::ClientInfo,
18 error::OnePasswordError,
19 login::{AUTH_COMPLETE_ENDPOINT, AUTH_START_ENDPOINT, SignInMethods, fetch_auth_methods},
20 mac::MacSigner,
21 opdata::{AesKey, decode64_loose},
22 rest::RestClient,
23 session::Session,
24 srp::perform_and_verify_with_x,
25 wire::{AuthComplete, LoginInfo, NewSession, SsoLoginUrl, SsoSession},
26};
27
28mod cpace;
29mod enrollment;
30#[cfg(test)]
31mod fake_server;
32#[cfg(test)]
33mod flow_tests;
34#[cfg(test)]
35mod test_support;
36pub mod ui;
37
38const SSO_START_ENDPOINT: &str = "v3/auth/sso/oidc/start";
39const SSO_VERIFY_ENDPOINT: &str = "v3/auth/sso/oidc/verify";
40const DEVICE_NOT_ENROLLED: &str = "device_not_enrolled";
41
42pub(super) struct Timing {
44 until_result_delay: Duration,
47 until_result_attempts: u32,
49 enrollment_poll_interval: Duration,
52 enrollment_poll_timeout: Duration,
54}
55
56impl Default for Timing {
57 fn default() -> Timing {
58 Timing {
59 until_result_delay: Duration::from_millis(500),
60 until_result_attempts: 20,
61 enrollment_poll_interval: Duration::from_secs(2),
62 enrollment_poll_timeout: Duration::from_secs(5 * 60),
63 }
64 }
65}
66
67impl Timing {
68 fn enrollment_poll_attempts(&self) -> u128 {
70 self.enrollment_poll_timeout
71 .as_nanos()
72 .checked_div(self.enrollment_poll_interval.as_nanos())
73 .unwrap_or(0)
74 }
75}
76
77pub(super) async fn sso_login(
83 credentials: &SsoCredentials,
84 client_info: &ClientInfo,
85 ui: &dyn SsoUi,
86 rest: &RestClient,
87 timing: &Timing,
88) -> Result<(Session, Zeroizing<Vec<u8>>), OnePasswordError> {
89 let login_info = fetch_auth_methods(&credentials.username, rest).await?;
91
92 let account = require_sso(&login_info, &credentials.username)?;
94
95 let sso_rest = rest.with_base_url(account.api_url());
97
98 let sso_login_url = start_sso_login(&account, &sso_rest).await?;
100
101 let (code, state) = perform_sso_login(&sso_login_url, ui).await?;
103
104 let sso_session = verify_sso_login(&code, &state, client_info, &sso_rest).await?;
106
107 let sso_rest = sso_rest.with_session_id(&sso_session.user.session_uuid)?;
109
110 sso_session.require_new_device()?;
112
113 let sign_in = SignIn {
115 username: &credentials.username,
116 sign_in_address: &account.sign_in_address,
117 sign_in_token: &sso_session.sso_auth.sign_in_token_details.token,
118 };
119 let bundle = enroll_device(sign_in, ui, &sso_rest, timing).await?;
120
121 let srp_x = Zeroizing::new(decode64_loose(&bundle.srpx)?);
123 let master_key = Zeroizing::new(decode64_loose(&bundle.auk.k)?);
124 let (session_key, session_rest) = login(
125 &credentials.username,
126 &account,
127 client_info,
128 &sso_session,
129 &srp_x,
130 &sso_rest,
131 )
132 .await?;
133
134 Ok((Session::new(session_key, session_rest), master_key))
136}
137
138struct SsoAccount {
140 user_uuid: String,
141 sign_in_address: String,
144}
145
146impl SsoAccount {
147 fn api_url(&self) -> String {
149 format!("{}/api", self.sign_in_address.trim_end_matches('/'))
150 }
151}
152
153fn require_sso(login_info: &LoginInfo, username: &str) -> Result<SsoAccount, OnePasswordError> {
156 if !SignInMethods::of(login_info).sso {
157 return Err(OnePasswordError::Unsupported(format!(
158 "no SSO login method found for account {username}"
159 )));
160 }
161
162 let (Some(user_uuid), Some(sign_in_address)) = (
163 non_empty(&login_info.user_uuid),
164 non_empty(&login_info.sign_in_address),
165 ) else {
166 return Err(OnePasswordError::Internal(
167 "SSO login info is missing userUuid or signInAddress".into(),
168 ));
169 };
170 validate_sign_in_address(sign_in_address)?;
171
172 Ok(SsoAccount {
173 user_uuid: user_uuid.to_string(),
174 sign_in_address: sign_in_address.to_string(),
175 })
176}
177
178fn non_empty(value: &Option<String>) -> Option<&str> {
179 value.as_deref().filter(|value| !value.is_empty())
180}
181
182fn validate_sign_in_address(address: &str) -> Result<(), OnePasswordError> {
186 let valid = Url::parse(address).is_ok_and(|url| {
187 has_allowed_scheme(&url)
188 && url.has_host()
189 && url.query().is_none()
190 && url.fragment().is_none()
191 });
192 if !valid {
193 return Err(OnePasswordError::Internal(
194 "the SSO sign-in address is not an https URL".into(),
195 ));
196 }
197 Ok(())
198}
199
200fn has_allowed_scheme(url: &Url) -> bool {
203 url.scheme() == "https" || (cfg!(test) && url.scheme() == "http")
204}
205
206fn is_web_url(url: &str) -> bool {
207 Url::parse(url).is_ok_and(|url| has_allowed_scheme(&url) && url.has_host())
208}
209
210fn is_redirect_uri(url: &str) -> bool {
213 is_web_url(url)
214 || Url::parse(url).is_ok_and(|url| url.scheme() == "onepassword" && url.has_host())
215}
216
217async fn start_sso_login(
219 account: &SsoAccount,
220 rest: &RestClient,
221) -> Result<String, OnePasswordError> {
222 let response: SsoLoginUrl = rest
223 .post_json(SSO_START_ENDPOINT, json!({ "userUuid": account.user_uuid }))
224 .await?;
225 Ok(response.auth_redirect)
226}
227
228async fn perform_sso_login(
231 sso_login_url: &str,
232 ui: &dyn SsoUi,
233) -> Result<(String, String), OnePasswordError> {
234 if !is_web_url(sso_login_url) {
236 return Err(OnePasswordError::Internal(
237 "the SSO login URL is not an https URL".into(),
238 ));
239 }
240
241 let redirect_to = url_parameter(sso_login_url, "redirect_uri").ok_or_else(|| {
242 OnePasswordError::Internal("no redirect_uri found in the SSO login URL".into())
243 })?;
244 if !is_redirect_uri(&redirect_to) {
245 return Err(OnePasswordError::Internal(
246 "the SSO redirect URI is neither an https nor a onepassword URL".into(),
247 ));
248 }
249
250 let redirected_to = match ui.perform_sso_login(sso_login_url, &redirect_to).await {
251 SsoLoginResult::RedirectedTo(url) => url,
252 SsoLoginResult::Cancel => return Err(OnePasswordError::Canceled),
253 };
254
255 let code = url_parameter(&redirected_to, "code").ok_or_else(|| {
257 OnePasswordError::Internal("no code returned from the SSO provider".into())
258 })?;
259 let state = url_parameter(&redirected_to, "state").ok_or_else(|| {
260 OnePasswordError::Internal("no state returned from the SSO provider".into())
261 })?;
262 Ok((code, state))
263}
264
265async fn verify_sso_login(
267 code: &str,
268 state: &str,
269 client_info: &ClientInfo,
270 rest: &RestClient,
271) -> Result<SsoSession, OnePasswordError> {
272 rest.post_json(
273 SSO_VERIFY_ENDPOINT,
274 json!({
275 "code": code,
276 "state": state,
277 "device": client_info.sso_verify_device_body(),
278 }),
279 )
280 .await
281}
282
283impl SsoSession {
284 fn require_new_device(&self) -> Result<(), OnePasswordError> {
287 if self.state != DEVICE_NOT_ENROLLED {
288 return Err(OnePasswordError::Internal(format!(
289 "unexpected SSO session state: {}",
290 self.state
291 )));
292 }
293 Ok(())
294 }
295}
296
297async fn login(
302 username: &str,
303 account: &SsoAccount,
304 client_info: &ClientInfo,
305 sso_session: &SsoSession,
306 srp_x: &[u8],
307 rest: &RestClient,
308) -> Result<(AesKey, RestClient), OnePasswordError> {
309 let sign_in_token = sso_session.sso_auth.sign_in_token_details.token.as_str();
310
311 let started = start_auth(
313 sign_in_token,
314 &client_info.device_uuid,
315 &account.user_uuid,
316 rest,
317 )
318 .await?;
319 let (Some(key_uuid), Some(auth)) = (started.key_uuid, started.auth) else {
320 return Err(OnePasswordError::Internal(format!(
321 "missing SRP parameters in the start response, its status is '{}'",
322 started.status
323 )));
324 };
325
326 let session_key = perform_and_verify_with_x(
329 srp_x,
330 username,
331 &key_uuid,
332 &decode64_loose(&auth.salt)?,
333 &sso_session.user.session_uuid,
334 rest,
335 )
336 .await?;
337
338 let signed_rest = rest.with_signer(MacSigner::with_request_id(&session_key, 1));
340
341 complete_auth(client_info, sign_in_token, &session_key, &signed_rest).await?;
343
344 Ok((session_key, signed_rest))
345}
346
347async fn start_auth(
348 sign_in_token: &str,
349 device_uuid: &str,
350 user_uuid: &str,
351 rest: &RestClient,
352) -> Result<NewSession, OnePasswordError> {
353 rest.post_json(
354 AUTH_START_ENDPOINT,
355 json!({
356 "signInToken": sign_in_token,
357 "deviceUuid": device_uuid,
358 "userUuid": user_uuid,
359 }),
360 )
361 .await
362}
363
364async fn complete_auth(
365 client_info: &ClientInfo,
366 sign_in_token: &str,
367 session_key: &AesKey,
368 rest: &RestClient,
369) -> Result<(), OnePasswordError> {
370 let response: AuthComplete = rest
371 .post_encrypted_json(
372 AUTH_COMPLETE_ENDPOINT,
373 json!({
374 "client": client_info.client_id(),
375 "signInToken": sign_in_token,
376 "device": client_info.sso_complete_device_body(),
377 }),
378 session_key,
379 )
380 .await?;
381
382 if response.mfa.is_some() {
383 return Err(OnePasswordError::Unsupported(
384 "two-factor authentication after SSO is not supported".into(),
385 ));
386 }
387 Ok(())
388}
389
390fn url_parameter(url: &str, name: &str) -> Option<String> {
393 let (url, fragment) = url.split_once('#').unwrap_or((url, ""));
394 let query = url.split_once('?').map_or("", |(_, query)| query);
395
396 [query, fragment]
397 .into_iter()
398 .flat_map(|part| form_urlencoded::parse(part.as_bytes()))
399 .find(|(key, _)| key == name)
400 .map(|(_, value)| value.into_owned())
401 .filter(|value| !value.is_empty())
402}
403
404#[cfg(test)]
405mod tests {
406 use std::sync::Mutex;
407
408 use async_trait::async_trait;
409 use serde_json::json;
410 use wiremock::{Mock, MockServer, ResponseTemplate, matchers};
411
412 use super::{
413 fake_server::{client_info, verify_response},
414 test_support::{rest_client, vectors},
415 ui::SsoEnrollmentContext,
416 *,
417 };
418
419 const LOGIN_URL: &str = "https://idp.example.com/authorize?client_id=abc&response_type=code\
420 &redirect_uri=https%3A%2F%2Facme.1password.com%2Fsso%2Foidc%2Fredirect%2F&scope=openid";
421 const REDIRECT_TO: &str = "https://acme.1password.com/sso/oidc/redirect/";
422
423 struct ScriptedUi {
425 result: Mutex<Option<SsoLoginResult>>,
426 calls: Mutex<Vec<(String, String)>>,
427 }
428
429 impl ScriptedUi {
430 fn new(result: SsoLoginResult) -> ScriptedUi {
431 ScriptedUi {
432 result: Mutex::new(Some(result)),
433 calls: Mutex::new(Vec::new()),
434 }
435 }
436
437 fn redirected_to(url: &str) -> ScriptedUi {
438 ScriptedUi::new(SsoLoginResult::RedirectedTo(url.into()))
439 }
440
441 fn calls(&self) -> Vec<(String, String)> {
442 self.calls.lock().expect("not poisoned").clone()
443 }
444 }
445
446 #[async_trait]
447 impl SsoUi for ScriptedUi {
448 async fn perform_sso_login(
449 &self,
450 sso_login_url: &str,
451 redirect_to: &str,
452 ) -> SsoLoginResult {
453 self.calls
454 .lock()
455 .expect("not poisoned")
456 .push((sso_login_url.into(), redirect_to.into()));
457 self.result
458 .lock()
459 .expect("not poisoned")
460 .take()
461 .expect("the login runs once")
462 }
463
464 async fn begin_sso_enrollment(&self) -> Box<dyn SsoEnrollmentContext> {
465 unreachable!("the login steps never enroll")
466 }
467 }
468
469 fn login_info(user_uuid: Option<&str>, sign_in_address: Option<&str>) -> LoginInfo {
470 serde_json::from_value(json!({
471 "userUuid": user_uuid,
472 "signInAddress": sign_in_address,
473 "authMethods": [
474 {"type": "PASSWORD+SK"},
475 {"type": "OIDC", "provider": "Acme", "iconUrl": null},
476 ],
477 }))
478 .expect("valid login info")
479 }
480
481 fn sso_account() -> SsoAccount {
482 require_sso(
483 &login_info(Some("USERUUID"), Some("https://acme.1password.com")),
484 "[email protected]",
485 )
486 .expect("an SSO account")
487 }
488
489 fn session(state: &str) -> SsoSession {
490 serde_json::from_value(verify_response(state)).expect("a valid session")
491 }
492
493 #[test]
494 fn requires_the_oidc_method() {
495 let mut info = login_info(Some("USERUUID"), Some("https://acme.1password.com"));
496 info.auth_methods.retain(|method| method.kind != "OIDC");
497
498 let error = require_sso(&info, "[email protected]").err();
499
500 assert!(
501 matches!(&error, Some(OnePasswordError::Unsupported(what)) if what.contains("[email protected]")),
502 "unexpected result: {error:?}"
503 );
504 }
505
506 #[test]
507 fn requires_the_user_uuid_and_the_sign_in_address() {
508 for (user_uuid, sign_in_address) in [
509 (None, Some("https://acme.1password.com")),
510 (Some(""), Some("https://acme.1password.com")),
511 (Some("USERUUID"), None),
512 (Some("USERUUID"), Some("")),
513 (None, None),
514 ] {
515 let error =
516 require_sso(&login_info(user_uuid, sign_in_address), "[email protected]").err();
517
518 assert!(
519 matches!(error, Some(OnePasswordError::Internal(_))),
520 "unexpected result for {user_uuid:?} and {sign_in_address:?}: {error:?}"
521 );
522 }
523 }
524
525 #[test]
526 fn accepts_the_login_info_of_an_sso_account() {
527 let account = sso_account();
528
529 assert_eq!(account.user_uuid, "USERUUID");
530 assert_eq!(account.sign_in_address, "https://acme.1password.com");
531 assert_eq!(account.api_url(), "https://acme.1password.com/api");
532 }
533
534 #[test]
535 fn a_trailing_slash_is_not_doubled_in_the_api_url() {
536 let account = require_sso(
537 &login_info(Some("USERUUID"), Some("https://acme.1password.com/")),
538 "[email protected]",
539 )
540 .expect("an SSO account");
541
542 assert_eq!(account.sign_in_address, "https://acme.1password.com/");
543 assert_eq!(account.api_url(), "https://acme.1password.com/api");
544 }
545
546 #[test]
547 fn accepts_the_address_forms_of_a_web_server() {
548 for address in [
549 "https://acme.1password.com",
550 "https://acme.1password.com/",
551 "http://127.0.0.1:8080",
552 "https://sso.example.com:8443/base",
553 ] {
554 require_sso(
555 &login_info(Some("USERUUID"), Some(address)),
556 "[email protected]",
557 )
558 .unwrap_or_else(|error| panic!("'{address}' is rejected: {error}"));
559 }
560 }
561
562 #[test]
563 fn rejects_a_sign_in_address_that_is_not_a_web_address() {
564 for address in [
565 "acme.1password.com",
566 "//acme.1password.com",
567 "/api",
568 "ftp://acme.1password.com",
569 "file://acme.1password.com/api",
570 "javascript:alert(1)",
571 "mailto:[email protected]",
572 "https://",
573 "https://acme.1password.com?next=/",
574 "https://acme.1password.com/?",
575 "https://acme.1password.com#top",
576 "https://acme.1password.com/#",
577 "not a url",
578 "http://user:[email protected]?next=/",
579 "ftp://user:[email protected]",
580 ] {
581 let error = require_sso(
582 &login_info(Some("USERUUID"), Some(address)),
583 "[email protected]",
584 )
585 .err();
586
587 assert!(
588 matches!(&error, Some(OnePasswordError::Internal(what)) if !what.contains(address) && !what.contains("SECRET")),
589 "unexpected result for '{address}': {error:?}"
590 );
591 }
592 }
593
594 #[tokio::test]
595 async fn start_sends_only_the_user_uuid() {
596 let server = MockServer::start().await;
597 server
598 .register(
599 Mock::given(matchers::method("POST"))
600 .and(matchers::path("/api/v3/auth/sso/oidc/start"))
601 .and(matchers::body_json(json!({"userUuid": "USERUUID"})))
602 .respond_with(
603 ResponseTemplate::new(200)
604 .set_body_json(json!({"authRedirect": LOGIN_URL})),
605 )
606 .expect(1),
607 )
608 .await;
609
610 let url = start_sso_login(&sso_account(), &rest_client(&server))
611 .await
612 .expect("starts");
613
614 assert_eq!(url, LOGIN_URL);
615 server.verify().await;
616 }
617
618 #[tokio::test]
619 async fn start_returns_a_server_error() {
620 let server = MockServer::start().await;
621 server
622 .register(
623 Mock::given(matchers::path("/api/v3/auth/sso/oidc/start")).respond_with(
624 ResponseTemplate::new(400)
625 .set_body_json(json!({"errorCode": 117, "errorMessage": "gone"})),
626 ),
627 )
628 .await;
629
630 let error = start_sso_login(&sso_account(), &rest_client(&server))
631 .await
632 .err();
633
634 assert!(matches!(error, Some(OnePasswordError::NotFound)));
635 }
636
637 #[tokio::test]
638 async fn perform_returns_the_code_and_state_of_the_c_example() {
639 let redirect = vectors().redirect;
640 let ui = ScriptedUi::redirected_to(&redirect.url);
641
642 let (code, state) = perform_sso_login(LOGIN_URL, &ui).await.expect("performs");
643
644 assert_eq!(code, redirect.code);
645 assert_eq!(state, redirect.state);
646 assert_eq!(
647 ui.calls(),
648 [(LOGIN_URL.to_string(), REDIRECT_TO.to_string())]
649 );
650 }
651
652 #[tokio::test]
653 async fn perform_accepts_the_desktop_app_redirect_uri() {
654 let login_url = "https://idp.example.com/authorize?client_id=abc\
655 &redirect_uri=onepassword%3A%2F%2Fsso%2Foidc%2Fredirect&response_mode=query";
656 let ui = ScriptedUi::redirected_to("onepassword://sso/oidc/redirect?code=c0de&state=st4te");
657
658 let (code, state) = perform_sso_login(login_url, &ui).await.expect("performs");
659
660 assert_eq!((code.as_str(), state.as_str()), ("c0de", "st4te"));
661 assert_eq!(
662 ui.calls(),
663 [(
664 login_url.to_string(),
665 "onepassword://sso/oidc/redirect".to_string()
666 )]
667 );
668 }
669
670 #[tokio::test]
671 async fn perform_reads_the_parameters_from_the_query_too() {
672 let ui = ScriptedUi::redirected_to("https://acme.1password.com/cb?code=c0de&state=st4te");
673
674 let (code, state) = perform_sso_login(LOGIN_URL, &ui).await.expect("performs");
675
676 assert_eq!((code.as_str(), state.as_str()), ("c0de", "st4te"));
677 }
678
679 #[tokio::test]
680 async fn perform_does_not_mistake_session_state_for_state() {
681 let ui = ScriptedUi::redirected_to(
682 "https://acme.1password.com/cb#session_state=WRONG&code=c0de&state=st4te",
683 );
684
685 let (_, state) = perform_sso_login(LOGIN_URL, &ui).await.expect("performs");
686
687 assert_eq!(state, "st4te");
688 }
689
690 #[tokio::test]
691 async fn perform_requires_a_state_of_its_own() {
692 let ui = ScriptedUi::redirected_to(
693 "https://acme.1password.com/cb#code=c0de&session_state=WRONG",
694 );
695
696 let error = perform_sso_login(LOGIN_URL, &ui).await.err();
697
698 assert!(
699 matches!(&error, Some(OnePasswordError::Internal(what)) if what.contains("no state")),
700 "unexpected result: {error:?}"
701 );
702 }
703
704 #[tokio::test]
705 async fn perform_form_decodes_the_redirect() {
706 let ui = ScriptedUi::redirected_to("https://acme.1password.com/cb#code=a%2Bb&state=c+d");
707
708 let (code, state) = perform_sso_login(LOGIN_URL, &ui).await.expect("performs");
709
710 assert_eq!(code, "a+b");
711 assert_eq!(state, "c d");
712 }
713
714 #[tokio::test]
715 async fn perform_requires_a_code_and_a_state() {
716 for (url, missing) in [
717 ("https://acme.1password.com/cb#state=st4te", "code"),
718 ("https://acme.1password.com/cb#code=&state=st4te", "code"),
719 ("https://acme.1password.com/cb#code=c0de", "state"),
720 ("https://acme.1password.com/cb#code=c0de&state=", "state"),
721 ("https://acme.1password.com/cb", "code"),
722 ] {
723 let error = perform_sso_login(LOGIN_URL, &ScriptedUi::redirected_to(url))
724 .await
725 .err();
726
727 assert!(
728 matches!(&error, Some(OnePasswordError::Internal(what)) if what.contains(&format!("no {missing}"))),
729 "unexpected result for '{url}': {error:?}"
730 );
731 }
732 }
733
734 #[tokio::test]
735 async fn perform_requires_a_redirect_uri_before_asking_the_user() {
736 for login_url in [
737 "https://idp.example.com/authorize?client_id=abc",
738 "https://idp.example.com/authorize?post_redirect_uri=https%3A%2F%2Fexample.com",
739 "https://idp.example.com/authorize?redirect_uri=",
740 ] {
741 let ui = ScriptedUi::redirected_to("https://acme.1password.com/cb#code=c&state=s");
742
743 let error = perform_sso_login(login_url, &ui).await.err();
744
745 assert!(
746 matches!(&error, Some(OnePasswordError::Internal(what)) if what.contains("redirect_uri")),
747 "unexpected result for '{login_url}': {error:?}"
748 );
749 assert!(ui.calls().is_empty());
750 }
751 }
752
753 #[tokio::test]
754 async fn perform_rejects_a_redirect_uri_that_is_not_a_web_address() {
755 for redirect_uri in [
756 "javascript%3Aalert(1)",
757 "file%3A%2F%2F%2Fcb",
758 "ftp%3A%2F%2Facme.1password.com%2Fcb",
759 "%2F%2Facme.1password.com%2Fcb",
760 "acme.1password.com%2Fcb",
761 "onepassword%3A%2Fsso",
762 ] {
763 let login_url = format!(
764 "https://idp.example.com/authorize?redirect_uri={redirect_uri}&state=SECRET"
765 );
766 let ui = ScriptedUi::redirected_to("https://acme.1password.com/cb#code=c&state=s");
767
768 let error = perform_sso_login(&login_url, &ui).await.err();
769
770 assert!(
771 matches!(&error, Some(OnePasswordError::Internal(what)) if what.contains("redirect URI") && !what.contains("SECRET")),
772 "unexpected result for '{login_url}': {error:?}"
773 );
774 assert!(ui.calls().is_empty(), "'{login_url}' reached the user");
775 }
776 }
777
778 #[tokio::test]
779 async fn perform_rejects_a_login_url_that_is_not_a_web_address() {
780 for login_url in [
781 "javascript:alert(1)//?redirect_uri=https%3A%2F%2Facme.1password.com&state=SECRET",
782 "file://idp.example.com/authorize?redirect_uri=https%3A%2F%2Facme.1password.com&state=SECRET",
783 "ftp://idp.example.com/authorize?redirect_uri=https%3A%2F%2Facme.1password.com&state=SECRET",
784 "file:///authorize?redirect_uri=https%3A%2F%2Facme.1password.com&state=SECRET",
785 "https://?redirect_uri=https%3A%2F%2Facme.1password.com&state=SECRET",
786 "//idp.example.com/authorize?redirect_uri=https%3A%2F%2Facme.1password.com&state=SECRET",
787 "idp.example.com/authorize?redirect_uri=https%3A%2F%2Facme.1password.com&state=SECRET",
788 ] {
789 let ui = ScriptedUi::redirected_to("https://acme.1password.com/cb#code=c&state=s");
790
791 let error = perform_sso_login(login_url, &ui).await.err();
792
793 assert!(
794 matches!(&error, Some(OnePasswordError::Internal(what)) if !what.contains("SECRET")),
795 "unexpected result for '{login_url}': {error:?}"
796 );
797 assert!(ui.calls().is_empty(), "'{login_url}' reached the user");
798 }
799 }
800
801 #[tokio::test]
802 async fn perform_reports_a_cancel_as_canceled() {
803 let ui = ScriptedUi::new(SsoLoginResult::Cancel);
804
805 let error = perform_sso_login(LOGIN_URL, &ui).await.err();
806
807 assert!(
808 matches!(error, Some(OnePasswordError::Canceled)),
809 "unexpected result: {error:?}"
810 );
811 assert_eq!(ui.calls().len(), 1);
812 }
813
814 #[test]
815 fn url_parameters_match_whole_keys_in_the_query_and_the_fragment() {
816 let url = "https://h/p?x_code=1&code=2&y=code=3#z=4&code=5";
817
818 assert_eq!(url_parameter(url, "code").as_deref(), Some("2"));
819 assert_eq!(url_parameter(url, "x_code").as_deref(), Some("1"));
820 assert_eq!(url_parameter(url, "z").as_deref(), Some("4"));
821 assert_eq!(url_parameter(url, "y").as_deref(), Some("code=3"));
822 assert_eq!(url_parameter(url, "cod"), None);
823 assert_eq!(
824 url_parameter("https://h/p#code=5", "code").as_deref(),
825 Some("5")
826 );
827 assert_eq!(
828 url_parameter("https://h/p?a&code=1", "code").as_deref(),
829 Some("1")
830 );
831 }
832
833 #[test]
834 fn url_parameters_are_form_decoded() {
835 assert_eq!(
836 url_parameter("u?a=%E2%9C%93+%2B%3D%26", "a").as_deref(),
837 Some("\u{2713} +=&")
838 );
839 }
840
841 #[tokio::test]
842 async fn verify_sends_the_code_state_and_device_descriptor() {
843 let server = MockServer::start().await;
844 server
845 .register(
846 Mock::given(matchers::method("POST"))
847 .and(matchers::path("/api/v3/auth/sso/oidc/verify"))
848 .and(matchers::body_json(json!({
849 "code": "c0de",
850 "state": "st4te",
851 "device": client_info().sso_verify_device_body(),
852 })))
853 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
854 "type": "device_not_enrolled",
855 "user": {
856 "sessionUuid": "SESSIONUUID",
857 "accountUuid": "ACCOUNTUUID",
858 "userUuid": "USERUUID",
859 "email": "[email protected]",
860 },
861 "ssoAuth": {
862 "signInTokenDetails": {
863 "token": "SIGN_IN_TOKEN",
864 "publicKey": "PUBLICKEY",
865 "exp": "2030-01-01T00:00:00Z",
866 },
867 },
868 })))
869 .expect(1),
870 )
871 .await;
872
873 let session = verify_sso_login("c0de", "st4te", &client_info(), &rest_client(&server))
874 .await
875 .expect("verifies");
876
877 assert_eq!(session.state, "device_not_enrolled");
878 assert_eq!(session.user.session_uuid, "SESSIONUUID");
879 assert_eq!(
880 session.sso_auth.sign_in_token_details.token.as_str(),
881 "SIGN_IN_TOKEN"
882 );
883 server.verify().await;
884 }
885
886 #[tokio::test]
887 async fn verify_returns_a_server_error() {
888 let server = MockServer::start().await;
889 server
890 .register(
891 Mock::given(matchers::path("/api/v3/auth/sso/oidc/verify")).respond_with(
892 ResponseTemplate::new(400)
893 .set_body_json(json!({"errorCode": 500, "errorMessage": "bad code"})),
894 ),
895 )
896 .await;
897
898 let error = verify_sso_login("c0de", "st4te", &client_info(), &rest_client(&server))
899 .await
900 .err();
901
902 assert!(
903 matches!(error, Some(OnePasswordError::Internal(what)) if what.contains("bad code"))
904 );
905 }
906
907 #[test]
908 fn the_sign_in_token_stays_out_of_debug_output() {
909 let output = format!("{:?}", session("device_not_enrolled"));
910
911 assert!(!output.contains("SIGN_IN_TOKEN"), "leaked: {output}");
912 }
913
914 #[test]
915 fn a_new_device_is_not_enrolled() {
916 assert!(session("device_not_enrolled").require_new_device().is_ok());
917 }
918
919 #[test]
920 fn any_other_session_state_is_an_error() {
921 for state in ["", "found", "Found", "device_deleted", "unknown"] {
922 let error = session(state).require_new_device().err();
923
924 assert!(
925 matches!(&error, Some(OnePasswordError::Internal(what)) if what.contains(state)),
926 "unexpected result for '{state}': {error:?}"
927 );
928 }
929 }
930}