Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions components/fxa-client/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,14 @@ pub enum FxaEvent {
///
/// This event is valid for the `Authenticating` state.
CompleteOAuthFlow { code: String, state: String },
/// Handle an `fxaccounts:change_password` WebChannel message on the device that just changed
/// its password. `json_payload` is the `data` object of that message and contains the new
/// session token. The state machine swaps the session token for a new refresh token and
/// re-initialises the device record.
///
/// This event is valid for the `Connected` and `AuthIssues` states. In `Authenticating` it
/// is a no-op so the in-progress OAuth flow is not disrupted.
HandleWebChannelPasswordChange { json_payload: String },
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

total nit, but it seems the "Handle" part doesn't make sense here, even though it kinda made sense on the function.

And I like the idea of this becoming an event, but think handle_web_channel_login should also become an event for consistency, then the functions can be removed in a followup?

/// Cancel an OAuth flow.
///
/// Use this to cancel an in-progress OAuth, returning to [FxaState::Disconnected] so the
Expand Down
1 change: 1 addition & 0 deletions components/fxa-client/src/fxa_client.udl
Original file line number Diff line number Diff line change
Expand Up @@ -992,6 +992,7 @@ interface FxaEvent {
CompleteOAuthFlow(string code, string state);
CancelOAuthFlow();
CheckAuthorizationStatus();
HandleWebChannelPasswordChange(string json_payload);
Disconnect();
CallGetProfile();
};
Expand Down
48 changes: 5 additions & 43 deletions components/fxa-client/src/internal/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,11 @@ impl FirefoxAccount {
})
}
PushPayload::PasswordChanged | PushPayload::PasswordReset => {
let status = self.check_authorization_status()?;
// clear any device or client data due to password change.
self.clear_devices_and_attached_clients_cache();
Ok(if !status.active {
AccountEvent::AccountAuthStateChanged
} else {
info!("Password change event, but no action required");
AccountEvent::Unknown
})
// Emit the event and let the
// CheckAuthorizationStatus arm verify with the
// server before committing to AuthIssues.
Ok(AccountEvent::AccountAuthStateChanged)
}
PushPayload::Unknown => {
info!("Unknown Push command.");
Expand Down Expand Up @@ -138,14 +134,8 @@ pub struct AccountDestroyedPushPayload {
#[cfg(test)]
mod tests {
use super::*;
use crate::internal::http_client::IntrospectResponse;
use crate::internal::http_client::MockFxAClient;
use crate::internal::oauth::RefreshToken;
use crate::internal::CachedResponse;
use crate::internal::Config;
use mockall::predicate::always;
use mockall::predicate::eq;
use std::sync::Arc;

#[test]
fn test_deserialize_send_tab_command() {
Expand Down Expand Up @@ -196,26 +186,12 @@ mod tests {
fn test_push_password_reset() {
let mut fxa =
FirefoxAccount::with_config(Config::stable_dev("12345678", "https://foo.bar"));
let mut client = MockFxAClient::new();
client
.expect_check_refresh_token_status()
.with(always(), eq("refresh_token"))
.times(1)
.returning(|_, _| Ok(IntrospectResponse { active: false }));
fxa.set_client(Arc::new(client));
let refresh_token_scopes = std::collections::HashSet::new();
fxa.state.force_refresh_token(RefreshToken {
token: "refresh_token".to_owned(),
scopes: refresh_token_scopes,
});
fxa.state.force_current_device_id("my_id");
fxa.devices_cache = Some(CachedResponse {
response: vec![],
cached_at: 0,
etag: "".to_string(),
});
let json = "{\"version\":1,\"command\":\"fxaccounts:password_reset\"}";
assert!(fxa.devices_cache.is_some());
let event = fxa.handle_push_message(json).unwrap();
assert!(matches!(event, AccountEvent::AccountAuthStateChanged));
assert!(fxa.devices_cache.is_none());
Expand All @@ -225,28 +201,14 @@ mod tests {
fn test_push_password_change() {
let mut fxa =
FirefoxAccount::with_config(Config::stable_dev("12345678", "https://foo.bar"));
let mut client = MockFxAClient::new();
client
.expect_check_refresh_token_status()
.with(always(), eq("refresh_token"))
.times(1)
.returning(|_, _| Ok(IntrospectResponse { active: true }));
fxa.set_client(Arc::new(client));
let refresh_token_scopes = std::collections::HashSet::new();
fxa.state.force_refresh_token(RefreshToken {
token: "refresh_token".to_owned(),
scopes: refresh_token_scopes,
});
fxa.state.force_current_device_id("my_id");
fxa.devices_cache = Some(CachedResponse {
response: vec![],
cached_at: 0,
etag: "".to_string(),
});
let json = "{\"version\":1,\"command\":\"fxaccounts:password_changed\"}";
assert!(fxa.devices_cache.is_some());
let event = fxa.handle_push_message(json).unwrap();
assert!(matches!(event, AccountEvent::Unknown));
assert!(matches!(event, AccountEvent::AccountAuthStateChanged));
assert!(fxa.devices_cache.is_none());
}
#[test]
Expand Down
1 change: 1 addition & 0 deletions components/fxa-client/src/state_machine/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ impl fmt::Display for FxaEvent {
Self::CompleteOAuthFlow { .. } => "CompleteOAthFlow",
Self::CancelOAuthFlow => "CancelOAthFlow",
Self::CheckAuthorizationStatus => "CheckAuthorizationStatus",
Self::HandleWebChannelPasswordChange { .. } => "HandleWebChannelPwdChange",
Self::Disconnect => "Disconnect",
Self::CallGetProfile => "CallGetProfile",
};
Expand Down
4 changes: 4 additions & 0 deletions components/fxa-client/src/state_machine/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ impl<'a> RetryingAccount<'a> {
self.with_auth_recovery(|a| a.complete_oauth_flow(code, state))
}

pub fn handle_web_channel_password_change(&mut self, json_payload: &str) -> Result<()> {
self.with_auth_recovery(|a| a.handle_web_channel_password_change(json_payload))
}

/// Cancels any existing OAuth flow before starting a new one.
pub fn begin_oauth_flow(
&mut self,
Expand Down
83 changes: 83 additions & 0 deletions components/fxa-client/src/state_machine/transitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,9 @@ pub fn transition(
initial_state,
})
}
// A WebChannel password change while an OAuth flow is in progress
// is a no-op; let the flow finish.
(s @ S::Authenticating { .. }, FxaEvent::HandleWebChannelPasswordChange { .. }) => Ok(s),
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd say it's still "unexpected" though - so maybe log a warning? I agree doing nothing is correct though.


// ── From Connected ──────────────────────────────────────────────
(S::Connected, FxaEvent::Disconnect) => {
Expand Down Expand Up @@ -180,6 +183,17 @@ pub fn transition(
initial_state: FxaRustAuthState::Connected,
})
}
(S::Connected, FxaEvent::HandleWebChannelPasswordChange { json_payload }) => {
account
.handle_web_channel_password_change(&json_payload)
.to_state_machine_err(|| S::AuthIssues)?;
// Token swap succeeded; auth is valid.
let dc = account.device_config().clone();
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seems like this clone shouldn't be necessary?

if let Err(e) = account.initialize_device(&dc.name, dc.device_type, &dc.capabilities) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this makes sense, but doesn't this mean ios will be doing the re-registration twice?

(also slightly confused why the oauth code explicitly fetches the current device config at https://github.com/mozilla/application-services/blob/main/components/fxa-client/src/internal/oauth.rs#L382 before re-registering it, when it seems like what you do here is easier and less error prone?)

crate::warn!("initialize_device failed after password change; device record may be stale: {e}");
}
Ok(S::Connected)
}

// ── From AuthIssues ─────────────────────────────────────────────
(
Expand All @@ -203,6 +217,18 @@ pub fn transition(
account.disconnect();
Ok(S::Disconnected)
}
(S::AuthIssues, FxaEvent::HandleWebChannelPasswordChange { json_payload }) => {
// A concurrent sync/401 may have pushed us here
// before the webchannel ran. The new session token still recovers us.
account
.handle_web_channel_password_change(&json_payload)
.to_state_machine_err(|| S::AuthIssues)?;
let dc = account.device_config().clone();
if let Err(e) = account.initialize_device(&dc.name, dc.device_type, &dc.capabilities) {
crate::warn!("initialize_device failed after password change; device record may be stale: {e}");
}
Ok(S::Connected)
}

// ── Invalid (state, event) pair ─────────────────────────────────
(state, event) => Err(StateMachineErr::Fatal(Box::new(
Expand Down Expand Up @@ -305,4 +331,61 @@ mod tests {
let result = transition(&mut wrapper, FxaState::Disconnected, FxaEvent::Disconnect);
assert_fatal_invalid_transition(result);
}

fn assert_handled_lands_at(
result: std::result::Result<FxaState, StateMachineErr>,
expected: FxaState,
) {
match result {
Err(StateMachineErr::Handled { target, .. }) => assert_eq!(target, expected),
Err(StateMachineErr::Fatal(cause)) => panic!("expected Handled, got Fatal({cause:?})"),
Ok(s) => panic!("expected Handled, got Ok({s:?})"),
}
}

#[test]
fn connected_handle_web_channel_password_change_is_valid_transition() {
nss_as::ensure_initialized();
let mut account = mock_account();
let mut wrapper = RetryingAccount::new(&mut account);
let result = transition(
&mut wrapper,
FxaState::Connected,
FxaEvent::HandleWebChannelPasswordChange {
json_payload: "{}".to_owned(),
},
);
assert_handled_lands_at(result, FxaState::AuthIssues);
}

#[test]
fn auth_issues_handle_web_channel_password_change_is_valid_transition() {
nss_as::ensure_initialized();
let mut account = mock_account();
let mut wrapper = RetryingAccount::new(&mut account);
let result = transition(
&mut wrapper,
FxaState::AuthIssues,
FxaEvent::HandleWebChannelPasswordChange {
json_payload: "{}".to_owned(),
},
);
assert_handled_lands_at(result, FxaState::AuthIssues);
}

#[test]
fn authenticating_handle_web_channel_password_change_stays_in_authenticating() {
nss_as::ensure_initialized();
let mut account = mock_account();
let mut wrapper = RetryingAccount::new(&mut account);
let from = authenticating_from(FxaRustAuthState::Connected);
let result = transition(
&mut wrapper,
from.clone(),
FxaEvent::HandleWebChannelPasswordChange {
json_payload: "{}".to_owned(),
},
);
assert_eq!(result.unwrap(), from);
}
}