Skip to main content

wechat_protocol/
account.rs

1//! Account data owned by NativeClient. Network workers take temporary snapshots;
2//! they never hold the state lock while waiting for transport.
3use super::{AccountState, NativeClient, NativeOptions};
4use anyhow::{ensure, Context, Result};
5use serde::{Deserialize, Serialize};
6use std::{
7    future::Future,
8    sync::{
9        atomic::{AtomicBool, AtomicU64, Ordering},
10        Arc, Mutex, MutexGuard,
11    },
12    time::Duration,
13};
14use tokio::sync::Notify;
15use zeroize::Zeroizing;
16
17#[path = "account_components.rs"]
18mod components;
19
20/// The operation stopped before business bytes were handed to transport. This
21/// marker is never attached to a timeout, rejected reply or post-handoff fence.
22#[derive(Debug)]
23pub struct NativeRequestNotSubmitted;
24
25impl std::fmt::Display for NativeRequestNotSubmitted {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        f.write_str("Native request stopped before business submission")
28    }
29}
30
31impl std::error::Error for NativeRequestNotSubmitted {}
32
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum AccountLifecycle {
36    Active,
37    Stopped,
38    Transferred,
39}
40
41/// Non-secret account lifecycle information. Credentials require an explicit
42/// export; status/debug output must never contain an AccountState.
43#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "camelCase")]
45pub struct AccountStatus {
46    pub lifecycle: AccountLifecycle,
47    pub revision: u64,
48    pub credential_generation: u64,
49    pub in_flight: usize,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq)]
53pub struct AccountIdentity {
54    pub uin: u32,
55    pub own_username: String,
56}
57
58/// Cheap authority check for account workers. It carries no credentials and
59/// becomes invalid on shutdown or any accepted credential renewal. It cannot
60/// replace the final submission guard on an authenticated signaling request.
61#[derive(Clone)]
62pub struct AccountLease {
63    authority: Arc<Authority>,
64    credential_generation: u64,
65}
66struct Authority {
67    active: AtomicBool,
68    credential_generation: AtomicU64,
69}
70impl AccountLease {
71    pub fn current(&self) -> bool {
72        self.authority.active.load(Ordering::Acquire)
73            && self.authority.credential_generation.load(Ordering::Acquire)
74                == self.credential_generation
75    }
76}
77
78/// Correlation values must be recorded with the application's send intent before
79/// submission. Neither a task ID nor a transport error authorizes a blind retry.
80#[derive(Clone, Debug)]
81pub struct TextSendOptions {
82    pub created_at: u32,
83    pub client_message_id: u32,
84    pub source: Option<String>,
85}
86
87/// Persist an accepted account update before it becomes visible to other client
88/// operations. Implementations store data only: they must not call back into the
89/// client, perform network operations, or implement authentication/retry policy.
90/// A failed write leaves in-memory state unchanged and never retries a request.
91pub trait AccountPersistence: Send + Sync {
92    fn persist(&self, previous: &AccountState, accepted: &AccountState) -> Result<()>;
93}
94
95/// A verified response could not commit its account update. The response may
96/// still be retained independently; this error never authorizes resubmission.
97#[derive(Debug)]
98pub struct AccountPersistenceFailed;
99impl std::fmt::Display for AccountPersistenceFailed {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.write_str("Accepted account update could not be persisted")
102    }
103}
104impl std::error::Error for AccountPersistenceFailed {}
105
106/// One reserved terminal operation. Reservation stops account admission without
107/// sending anything. An embedding daemon can commit local logout inhibition
108/// before consuming this token to submit its optional remote logout.
109/// Dropping the token leaves the account stopped and sends no request.
110pub struct PendingLogout {
111    exchange: Arc<Exchange>,
112    state: AccountState,
113    options: NativeOptions,
114}
115
116impl PendingLogout {
117    pub async fn submit(self) -> Result<super::LogoutReply> {
118        self.submit_guarded(|| Ok(())).await
119    }
120
121    /// Recheck the embedding application's committed logout operation immediately
122    /// before business handoff. This token is consumed even on failure; neither
123    /// a cancelled waiter nor an uncertain response permits automatic resubmission.
124    pub async fn submit_guarded<F>(self, before_submit: F) -> Result<super::LogoutReply>
125    where
126        F: FnOnce() -> Result<()> + Send + 'static,
127    {
128        self.exchange.account.drain_to(1).await?;
129        let cancellation = Arc::new(AtomicBool::new(false));
130        let _cancel_on_drop = CancelOnDrop(cancellation.clone());
131        tokio::task::spawn_blocking(move || {
132            let Self {
133                exchange,
134                mut state,
135                options,
136            } = self;
137            let mut transport = NativeClient::new(options)?;
138            let before_submit = Mutex::new(Some(before_submit));
139            transport.submission_guard = Some(Arc::new(move || {
140                let check = (|| {
141                    ensure!(
142                        !cancellation.load(Ordering::Acquire),
143                        "Account logout cancelled before submission"
144                    );
145                    exchange.check_logout()
146                })();
147                check.map_err(|error| error.context(NativeRequestNotSubmitted))?;
148                let guard = before_submit
149                    .lock()
150                    .map_err(|_| anyhow::anyhow!("Logout guard unavailable"))?
151                    .take()
152                    .context("Logout already submitted")?;
153                guard().map_err(|error| error.context(NativeRequestNotSubmitted))
154            }));
155            transport.logout_snapshot(&mut state)
156        })
157        .await
158        .context("Account logout worker failed")?
159    }
160}
161
162pub(super) struct OwnedAccount {
163    data: Mutex<AccountData>,
164    changed: Notify,
165    authority: Arc<Authority>,
166    components: components::AccountComponents,
167}
168
169struct AccountData {
170    state: Option<AccountState>,
171    revision: u64,
172    credential_generation: u64,
173    lifecycle: AccountLifecycle,
174    in_flight: usize,
175    persistence: Option<Arc<dyn AccountPersistence>>,
176}
177
178struct Exchange {
179    account: Arc<OwnedAccount>,
180    revision: u64,
181    credential_generation: u64,
182    non_cookie: [u8; 32],
183}
184
185struct CancelOnDrop(Arc<AtomicBool>);
186
187impl Drop for CancelOnDrop {
188    fn drop(&mut self) {
189        self.0.store(true, Ordering::Release);
190    }
191}
192
193impl OwnedAccount {
194    fn lock(&self) -> Result<MutexGuard<'_, AccountData>> {
195        self.data
196            .lock()
197            .map_err(|_| anyhow::anyhow!("Account state lock poisoned"))
198    }
199
200    fn begin(self: &Arc<Self>) -> Result<(Exchange, AccountState)> {
201        self.begin_with_terminal(false)
202    }
203
204    fn begin_with_terminal(self: &Arc<Self>, terminal: bool) -> Result<(Exchange, AccountState)> {
205        let mut data = self.lock()?;
206        ensure!(
207            data.lifecycle == AccountLifecycle::Active
208                && self.authority.active.load(Ordering::Acquire),
209            "Account is stopped"
210        );
211        let state = data
212            .state
213            .as_ref()
214            .context("Account state transferred")?
215            .clone();
216        let non_cookie = non_cookie_digest(&state)?;
217        data.in_flight = data
218            .in_flight
219            .checked_add(1)
220            .context("Too many account requests")?;
221        let exchange = Exchange {
222            account: self.clone(),
223            revision: data.revision,
224            credential_generation: data.credential_generation,
225            non_cookie,
226        };
227        if terminal {
228            data.lifecycle = AccountLifecycle::Stopped;
229            self.authority.active.store(false, Ordering::Release);
230        }
231        drop(data);
232        if terminal {
233            self.changed.notify_waiters();
234        }
235        Ok((exchange, state))
236    }
237
238    fn stop(&self) -> Result<()> {
239        self.authority.active.store(false, Ordering::Release);
240        {
241            let mut data = self.lock()?;
242            if data.lifecycle == AccountLifecycle::Active {
243                data.lifecycle = AccountLifecycle::Stopped;
244            }
245        }
246        self.changed.notify_waiters();
247        Ok(())
248    }
249
250    async fn stopped(&self) {
251        loop {
252            let notified = self.changed.notified();
253            tokio::pin!(notified);
254            notified.as_mut().enable();
255            if !self
256                .lock()
257                .is_ok_and(|data| data.lifecycle == AccountLifecycle::Active)
258            {
259                return;
260            }
261            notified.await;
262        }
263    }
264
265    async fn stop_and_drain(&self) -> Result<()> {
266        self.stop()?;
267        self.drain_to(0).await
268    }
269
270    async fn drain_to(&self, remaining: usize) -> Result<()> {
271        loop {
272            let notified = self.changed.notified();
273            tokio::pin!(notified);
274            notified.as_mut().enable();
275            if self.lock()?.in_flight == remaining {
276                return Ok(());
277            }
278            notified.await;
279        }
280    }
281}
282
283impl Exchange {
284    fn check_logout(&self) -> Result<()> {
285        let data = self.account.lock()?;
286        ensure!(
287            data.lifecycle == AccountLifecycle::Stopped && data.in_flight == 1,
288            "Logout is not the exclusive account operation"
289        );
290        let current = data.state.as_ref().context("Account state transferred")?;
291        ensure!(
292            data.credential_generation == self.credential_generation
293                && non_cookie_digest(current)? == self.non_cookie,
294            "Account authentication superseded logout"
295        );
296        Ok(())
297    }
298    /// Check immediately before handing business bytes to transport. A request
299    /// already handed off cannot be recalled by a later shutdown.
300    fn check(&self) -> Result<()> {
301        let data = self.account.lock()?;
302        ensure!(
303            data.lifecycle == AccountLifecycle::Active,
304            "Account stopped during request"
305        );
306        let current = data.state.as_ref().context("Account state transferred")?;
307        ensure!(
308            data.credential_generation == self.credential_generation
309                && non_cookie_digest(current)? == self.non_cookie,
310            "Account credentials changed during request"
311        );
312        Ok(())
313    }
314
315    fn accept_cookie(&self, returned: &AccountState) -> Result<()> {
316        returned.validate()?;
317        ensure!(
318            non_cookie_digest(returned)? == self.non_cookie,
319            "Unexpected account credential change"
320        );
321        let mut data = self.account.lock()?;
322        ensure!(
323            data.lifecycle == AccountLifecycle::Active,
324            "Account stopped during request"
325        );
326        let current = data.state.as_ref().context("Account state transferred")?;
327        ensure!(
328            data.credential_generation == self.credential_generation
329                && non_cookie_digest(current)? == self.non_cookie,
330            "Account credentials changed during request"
331        );
332        // A concurrent response already adopted a newer cookie. Preserve that
333        // whole accepted state rather than overwriting it with a stale snapshot.
334        if data.revision == self.revision && current.cookie != returned.cookie {
335            let revision = data
336                .revision
337                .checked_add(1)
338                .context("Account revision exhausted")?;
339            if let Some(storage) = &data.persistence {
340                storage
341                    .persist(current, returned)
342                    .map_err(|error| error.context(AccountPersistenceFailed))?;
343            }
344            data.state
345                .as_mut()
346                .context("Account state transferred")?
347                .cookie
348                .clone_from(&returned.cookie);
349            data.revision = revision;
350        }
351        Ok(())
352    }
353
354    fn accept_credentials(&self, returned: AccountState) -> Result<()> {
355        returned.validate()?;
356        let mut data = self.account.lock()?;
357        ensure!(
358            data.lifecycle == AccountLifecycle::Active,
359            "Account stopped during authentication"
360        );
361        let current = data.state.as_ref().context("Account state transferred")?;
362        ensure!(
363            data.credential_generation == self.credential_generation
364                && non_cookie_digest(current)? == self.non_cookie,
365            "Account authentication superseded"
366        );
367        ensure!(
368            current.uin == returned.uin
369                && current.own_username == returned.own_username
370                && current.device.device_id == returned.device.device_id
371                && current.device.device_type == returned.device.device_type
372                && current.device.client_version == returned.device.client_version,
373            "Account authentication identity mismatch"
374        );
375        let revision = data
376            .revision
377            .checked_add(1)
378            .context("Account revision exhausted")?;
379        let generation = data
380            .credential_generation
381            .checked_add(1)
382            .context("Account credential generation exhausted")?;
383        if let Some(storage) = &data.persistence {
384            storage
385                .persist(current, &returned)
386                .map_err(|error| error.context(AccountPersistenceFailed))?;
387        }
388        data.state = Some(returned);
389        data.revision = revision;
390        data.credential_generation = generation;
391        self.account
392            .authority
393            .credential_generation
394            .store(generation, Ordering::Release);
395        Ok(())
396    }
397}
398
399impl Drop for Exchange {
400    fn drop(&mut self) {
401        // Release even after a worker panic. Other access still fails closed
402        // when the mutex is poisoned; waiters must nevertheless be awakened.
403        let mut data = self
404            .account
405            .data
406            .lock()
407            .unwrap_or_else(|error| error.into_inner());
408        data.in_flight -= 1;
409        drop(data);
410        self.account.changed.notify_waiters();
411    }
412}
413
414fn non_cookie_digest(state: &AccountState) -> Result<[u8; 32]> {
415    let mut without_cookie = state.clone();
416    zeroize::Zeroize::zeroize(&mut without_cookie.cookie);
417    without_cookie.cookie.clear();
418    let encoded = Zeroizing::new(serde_json::to_vec(&without_cookie)?);
419    Ok(openssl::sha::sha256(&encoded))
420}
421
422impl NativeClient {
423    pub(super) fn check_snapshot_transport(&self) -> Result<()> {
424        ensure!(
425            self.account.is_none(),
426            "Explicit-state transport cannot use a bound account client"
427        );
428        Ok(())
429    }
430
431    pub(super) fn check_submission(&self) -> Result<()> {
432        if let Some(check) = &self.submission_guard {
433            check()?;
434        }
435        Ok(())
436    }
437    /// Bind an accepted account to this client. Clones share the same owner;
438    /// construction performs no network operation or credential persistence.
439    pub fn from_account(state: AccountState, options: NativeOptions) -> Result<Self> {
440        state.validate()?;
441        let mut client = Self::new(options)?;
442        client.account = Some(Arc::new(OwnedAccount {
443            data: Mutex::new(AccountData {
444                state: Some(state),
445                revision: 0,
446                credential_generation: 0,
447                lifecycle: AccountLifecycle::Active,
448                in_flight: 0,
449                persistence: None,
450            }),
451            changed: Notify::new(),
452            authority: Arc::new(Authority {
453                active: AtomicBool::new(true),
454                credential_generation: AtomicU64::new(0),
455            }),
456            components: components::AccountComponents::default(),
457        }));
458        Ok(client)
459    }
460
461    /// Use a data-only storage callback for accepted updates. The supplied state
462    /// must already be loaded from accepted storage; construction does not write
463    /// it back or treat importing bytes as a new authentication acceptance.
464    pub fn from_account_with_persistence(
465        state: AccountState,
466        options: NativeOptions,
467        persistence: Arc<dyn AccountPersistence>,
468    ) -> Result<Self> {
469        let client = Self::from_account(state, options)?;
470        client.owned_account()?.lock()?.persistence = Some(persistence);
471        Ok(client)
472    }
473
474    fn owned_account(&self) -> Result<&Arc<OwnedAccount>> {
475        self.account
476            .as_ref()
477            .context("Native client has no bound account")
478    }
479
480    pub fn account_status(&self) -> Result<AccountStatus> {
481        let data = self.owned_account()?.lock()?;
482        Ok(AccountStatus {
483            lifecycle: data.lifecycle,
484            revision: data.revision,
485            credential_generation: data.credential_generation,
486            in_flight: data.in_flight,
487        })
488    }
489
490    pub fn account_identity(&self) -> Result<AccountIdentity> {
491        let data = self.owned_account()?.lock()?;
492        let state = data.state.as_ref().context("Account state transferred")?;
493        Ok(AccountIdentity {
494            uin: state.uin,
495            own_username: state.own_username.clone(),
496        })
497    }
498
499    pub fn account_lease(&self) -> Result<AccountLease> {
500        let account = self.owned_account()?;
501        let data = account.lock()?;
502        ensure!(
503            data.lifecycle == AccountLifecycle::Active
504                && account.authority.active.load(Ordering::Acquire),
505            "Account is stopped"
506        );
507        Ok(AccountLease {
508            authority: account.authority.clone(),
509            credential_generation: data.credential_generation,
510        })
511    }
512
513    /// Export secret state for persistence. This snapshot does not transfer
514    /// ownership or authorize another writer; use quiesce_and_export for handoff.
515    pub fn export_account_state(&self) -> Result<AccountState> {
516        self.owned_account()?
517            .lock()?
518            .state
519            .as_ref()
520            .cloned()
521            .context("Account state transferred")
522    }
523
524    /// Stop account-bound admission and wait for admitted network workers to
525    /// finish. Cancelling this future does not reopen admission.
526    pub async fn shutdown(&self) -> Result<()> {
527        self.owned_account()?.stop_and_drain().await
528    }
529
530    /// Fence new submissions immediately. Network requests already handed off
531    /// retain their uncertain outcome; shutdown waits for their workers to exit.
532    pub fn stop(&self) -> Result<()> {
533        self.owned_account()?.stop()
534    }
535
536    /// Reserve one terminal operation before the embedding application commits
537    /// its own local inhibition. No network work is started by reservation.
538    pub fn prepare_logout(&self) -> Result<PendingLogout> {
539        let account = self.owned_account()?;
540        let (exchange, state) = account
541            .begin_with_terminal(true)
542            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
543        Ok(PendingLogout {
544            exchange: Arc::new(exchange),
545            state,
546            options: self.options.clone(),
547        })
548    }
549
550    /// Completes when this account owner stops, including through another clone.
551    pub async fn stopped(&self) -> Result<()> {
552        self.owned_account()?.stopped().await;
553        Ok(())
554    }
555
556    /// Stop and drain the client, then move its credentials out exactly once.
557    /// All cloned handles remain stopped and cannot export the transferred state.
558    pub async fn quiesce_and_export(&self) -> Result<AccountState> {
559        let account = self.owned_account()?;
560        account.stop_and_drain().await?;
561        let mut data = account.lock()?;
562        let state = data
563            .state
564            .take()
565            .context("Account state already transferred")?;
566        data.lifecycle = AccountLifecycle::Transferred;
567        Ok(state)
568    }
569
570    async fn account_request<T, F>(&self, operation: F) -> Result<T>
571    where
572        T: Send + 'static,
573        F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>
574            + Send
575            + 'static,
576    {
577        let (exchange, state) = self
578            .owned_account()?
579            .begin()
580            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
581        let options = self.options.clone();
582        let cancellation = Arc::new(AtomicBool::new(false));
583        let _cancel_on_drop = CancelOnDrop(cancellation.clone());
584        tokio::task::spawn_blocking(move || {
585            Self::execute_account_request(options, exchange, state, cancellation, operation)
586        })
587        .await
588        .context("Account request worker failed")?
589    }
590
591    fn account_request_blocking<T, F>(&self, operation: F) -> Result<T>
592    where
593        F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
594    {
595        let (exchange, state) = self
596            .owned_account()?
597            .begin()
598            .map_err(|error| error.context(NativeRequestNotSubmitted))?;
599        Self::execute_account_request(
600            self.options.clone(),
601            exchange,
602            state,
603            Arc::new(AtomicBool::new(false)),
604            operation,
605        )
606    }
607
608    fn execute_account_request<T, F>(
609        options: NativeOptions,
610        exchange: Exchange,
611        mut state: AccountState,
612        cancellation: Arc<AtomicBool>,
613        operation: F,
614    ) -> Result<T>
615    where
616        F: FnOnce(&NativeClient, &mut AccountState, &dyn Fn() -> Result<()>) -> Result<T>,
617    {
618        let exchange = Arc::new(exchange);
619        // This transport gets a temporary request snapshot, not another owner.
620        let mut transport = NativeClient::new(options)?;
621        let submission_exchange = exchange.clone();
622        let prior_admission = AtomicBool::new(false);
623        transport.submission_guard = Some(Arc::new(move || {
624            let check = (|| {
625                ensure!(
626                    !cancellation.load(Ordering::Acquire),
627                    "Account request cancelled before submission"
628                );
629                submission_exchange.check()
630            })();
631            match check {
632                Ok(()) => {
633                    prior_admission.store(true, Ordering::Release);
634                    Ok(())
635                }
636                Err(error) if !prior_admission.load(Ordering::Acquire) => {
637                    Err(error.context(NativeRequestNotSubmitted))
638                }
639                // A logical operation can contain several chunks. Stopping a
640                // later chunk never proves the entire operation was unsent.
641                Err(error) => Err(error),
642            }
643        }));
644        let result = operation(&transport, &mut state, &|| transport.check_submission());
645        // Cookie adoption still follows verified transport when a decoded
646        // application result rejects the operation. Preserve original uncertainty.
647        let accepted = exchange.accept_cookie(&state);
648        match result {
649            Ok(value) => {
650                accepted?;
651                Ok(value)
652            }
653            Err(error) => match accepted {
654                Ok(()) => Err(error),
655                Err(account_error) => Err(error.context(account_error)),
656            },
657        }
658    }
659}
660
661#[path = "account_request.rs"]
662mod request;
663pub use request::AccountRequest;
664
665#[path = "account_push.rs"]
666mod push;
667pub use push::AccountPushConnection;
668
669#[path = "account_operations.rs"]
670mod operations;
671
672async fn wait_for_poll<R, C, S>(reply: R, cancellation: C, stopped: S) -> Result<Vec<u8>>
673where
674    R: Future<Output = Result<Vec<u8>>>,
675    C: Future<Output = ()>,
676    S: Future<Output = ()>,
677{
678    tokio::select! {
679        biased;
680        () = stopped => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
681        () = cancellation => Err(crate::calls::host_transport::CallLiveSyncInterrupted.into()),
682        result = reply => result,
683    }
684}
685
686#[cfg(test)]
687#[path = "account_tests.rs"]
688mod tests;