Skip to main content

lockbook_server_lib/billing/
stripe_service.rs

1use crate::billing::billing_model::{BillingPlatform, StripeUserInfo};
2use crate::billing::billing_service::LockBillingWorkflowError;
3use crate::document_service::DocumentService;
4use crate::guard::ServerTx;
5use crate::schema::Account;
6use crate::{ClientError, RequestContext, ServerError, ServerState, StripeWebhookError};
7use constant_time_eq::constant_time_eq;
8use google_androidpublisher3::hyper::body::Bytes;
9use google_androidpublisher3::hyper::header::HeaderValue;
10use hmac::{Hmac, Mac};
11use lb_rs::model::api::{
12    AdminStripeAccountCheck, AdminStripeAccountStatus, AdminStripeSnapshot, AdminSyncStripeError,
13    AdminSyncStripeRequest, AdminSyncStripeResponse, StripeAccountState, StripeBillingPortalError,
14    StripeBillingPortalRequest, StripeBillingPortalResponse, StripeCheckoutError,
15    StripeCheckoutRequest, StripeCheckoutResponse,
16};
17use lb_rs::model::file_metadata::Owner;
18use libsecp256k1::PublicKey;
19use sha2::Sha256;
20use std::collections::HashMap;
21use std::time::Duration;
22use tracing::*;
23use uuid::Uuid;
24
25use super::app_store_client::AppStoreClient;
26use super::google_play_client::GooglePlayClient;
27use super::stripe_client::{StripeClient, StripeSubscription};
28
29const CHECKOUT_SUCCESS_URL: &str = "https://lockbook.net/checkout/thanks/";
30const CHECKOUT_CANCEL_URL: &str = "https://lockbook.net/checkout/canceled/";
31const BILLING_PORTAL_RETURN_URL: &str = "https://lockbook.net";
32const WEBHOOK_TOLERANCE_SECS: u64 = 300;
33const MAX_LOCK_WAIT: Duration = Duration::from_secs(5);
34pub(crate) const MIN_LOCK_RETRY_SLEEP: Duration = Duration::from_millis(50);
35
36type HmacSha256 = Hmac<Sha256>;
37
38impl<S, A, G, D> ServerState<S, A, G, D>
39where
40    S: StripeClient,
41    A: AppStoreClient,
42    G: GooglePlayClient,
43    D: DocumentService,
44{
45    pub async fn stripe_checkout(
46        &self, context: RequestContext<StripeCheckoutRequest>,
47    ) -> Result<StripeCheckoutResponse, ServerError<StripeCheckoutError>> {
48        if self.is_sub_account(&context.public_key).await {
49            return Err(ClientError(StripeCheckoutError::NotPermissioned));
50        }
51
52        let mut account = self.lock_subscription_profile(&context.public_key).await?;
53        let result = self
54            .stripe_checkout_url(&context.public_key, &mut account)
55            .await;
56        self.release_subscription_profile::<StripeCheckoutError>(context.public_key, account)
57            .await?;
58        Ok(StripeCheckoutResponse { url: result? })
59    }
60
61    async fn stripe_checkout_url(
62        &self, public_key: &PublicKey, account: &mut Account,
63    ) -> Result<String, ServerError<StripeCheckoutError>> {
64        if account.billing_info.is_premium() {
65            return Err(ClientError(StripeCheckoutError::AlreadyPremium));
66        }
67
68        let owner = Owner(*public_key);
69        let (customer_id, is_new) = match self.stripe_customer_of(public_key, account).await {
70            Some(customer_id) => {
71                self.record_stripe_customer::<StripeCheckoutError>(&customer_id, owner)
72                    .await?;
73                (customer_id, false)
74            }
75            None => {
76                let customer_id = self.stripe_client.create_customer().await?;
77                self.record_stripe_customer::<StripeCheckoutError>(&customer_id, owner)
78                    .await?;
79                (customer_id, true)
80            }
81        };
82
83        if !is_new {
84            // A paid subscription whose webhook hasn't arrived yet still counts — heal local DB
85            // now so clients polling after AlreadyPremium immediately see Premium.
86            let subscriptions = self.stripe_client.list_subscriptions(&customer_id).await?;
87            if let Some(info) = billing_from_subscriptions(&customer_id, &subscriptions) {
88                apply_stripe_sync(owner, &customer_id, account, Some(&info));
89                return Err(ClientError(StripeCheckoutError::AlreadyPremium));
90            }
91
92            self.stripe_client
93                .expire_open_checkout_sessions(&customer_id)
94                .await?;
95        }
96
97        let price_id = &self.config.billing.stripe.premium_price_id;
98        Ok(self
99            .stripe_client
100            .create_checkout_session(
101                &customer_id,
102                price_id,
103                CHECKOUT_SUCCESS_URL,
104                CHECKOUT_CANCEL_URL,
105            )
106            .await?)
107    }
108
109    pub async fn stripe_billing_portal(
110        &self, context: RequestContext<StripeBillingPortalRequest>,
111    ) -> Result<StripeBillingPortalResponse, ServerError<StripeBillingPortalError>> {
112        if self.is_sub_account(&context.public_key).await {
113            return Err(ClientError(StripeBillingPortalError::NotPermissioned));
114        }
115
116        let account = self
117            .index_db
118            .lock()
119            .await
120            .schema
121            .accounts
122            .get(&Owner(context.public_key))
123            .cloned()
124            .ok_or(ClientError(StripeBillingPortalError::UserNotFound))?;
125
126        let customer_id = self
127            .stripe_customer_of(&context.public_key, &account)
128            .await
129            .ok_or(ClientError(StripeBillingPortalError::NotStripeCustomer))?;
130
131        let url = self
132            .stripe_client
133            .create_billing_portal_session(&customer_id, BILLING_PORTAL_RETURN_URL)
134            .await?;
135
136        Ok(StripeBillingPortalResponse { url })
137    }
138
139    /// Best-effort immediate cancellation of any live Stripe subscriptions when a Lockbook account
140    /// is deleted. Checks Stripe live by `customer_id` first (catching pre-webhook checkouts and
141    /// multiple live subs), falling back to any cached `subscription_id`.
142    pub async fn cancel_stripe_on_account_delete(
143        &self, customer_id: Option<&str>, fallback_subscription_id: Option<&str>,
144    ) {
145        if let Some(customer_id) = customer_id {
146            match self.stripe_client.list_subscriptions(customer_id).await {
147                Ok(subs) => {
148                    for sub in subs.into_iter().filter(StripeSubscription::is_live) {
149                        if let Err(err) = self
150                            .stripe_client
151                            .cancel_subscription_immediately(&sub.id)
152                            .await
153                        {
154                            warn!(
155                                subscription_id = sub.id.as_str(),
156                                ?err,
157                                "Failed to cancel Stripe subscription on account delete"
158                            );
159                        }
160                    }
161                    return;
162                }
163                Err(err) => {
164                    warn!(
165                        customer_id,
166                        ?err,
167                        "Failed to list Stripe subscriptions on account delete"
168                    );
169                }
170            }
171        }
172        if let Some(subscription_id) = fallback_subscription_id {
173            if let Err(err) = self
174                .stripe_client
175                .cancel_subscription_immediately(subscription_id)
176                .await
177            {
178                warn!(
179                    subscription_id,
180                    ?err,
181                    "Failed to cancel cached Stripe subscription on account delete"
182                );
183            }
184        }
185    }
186
187    async fn record_stripe_customer<T: std::fmt::Debug>(
188        &self, customer_id: &str, owner: Owner,
189    ) -> Result<(), ServerError<T>> {
190        let mut db = self.index_db.lock().await;
191        if db.schema.stripe_ids.get(customer_id) == Some(&owner) {
192            return Ok(());
193        }
194        let mut tx = ServerTx::begin(&mut db)?;
195        tx.stripe_ids.insert(customer_id.to_string(), owner)?;
196        tx.end()?;
197        Ok(())
198    }
199
200    /// The Stripe customer that belongs to this account, if one was ever created.
201    async fn stripe_customer_of(
202        &self, public_key: &PublicKey, account: &Account,
203    ) -> Option<String> {
204        if let Some(BillingPlatform::Stripe(info)) = &account.billing_info.billing_platform {
205            if !info.customer_id.is_empty() {
206                return Some(info.customer_id.clone());
207            }
208        }
209        let owner = Owner(*public_key);
210        self.index_db
211            .lock()
212            .await
213            .schema
214            .stripe_ids
215            .iter()
216            .find(|(_, o)| **o == owner)
217            .map(|(customer_id, _)| customer_id.clone())
218    }
219
220    /// Makes the billing of the account behind `customer_id` match Stripe's live subscriptions now.
221    /// Holding the account's billing lock across the fetch applies concurrent events in order.
222    pub async fn sync_stripe_customer(
223        &self, customer_id: &str,
224    ) -> Result<(), ServerError<StripeWebhookError>> {
225        let owner = self
226            .index_db
227            .lock()
228            .await
229            .schema
230            .stripe_ids
231            .get(customer_id)
232            .copied();
233        let Some(owner) = owner else {
234            warn!(?customer_id, "Ignoring stripe event for a customer with no account");
235            return Ok(());
236        };
237
238        let Some(mut account) = self
239            .lock_for_stripe_sync(&owner)
240            .await
241            .map_err(|msg| internal!("{msg}"))?
242        else {
243            warn!(?owner, "Ignoring stripe event for a deleted account");
244            return Ok(());
245        };
246
247        let result = self.current_stripe_billing(customer_id).await;
248        if let Ok(live_info) = &result {
249            apply_stripe_sync(owner, customer_id, &mut account, live_info.as_ref());
250        }
251        self.release_subscription_profile::<StripeWebhookError>(owner.0, account)
252            .await?;
253        result.map(|_| ())
254    }
255
256    async fn lock_for_stripe_sync(&self, owner: &Owner) -> Result<Option<Account>, String> {
257        let deadline = tokio::time::Instant::now() + MAX_LOCK_WAIT;
258        let sleep = self
259            .config
260            .billing
261            .time_between_lock_attempts
262            .max(MIN_LOCK_RETRY_SLEEP);
263        loop {
264            match self.lock_subscription_profile(&owner.0).await {
265                Ok(account) => return Ok(Some(account)),
266                Err(ClientError(LockBillingWorkflowError::ExistingRequestPending)) => {
267                    if tokio::time::Instant::now() >= deadline {
268                        return Err(format!(
269                            "Timed out waiting for billing lock for {owner:?}; letting Stripe retry"
270                        ));
271                    }
272                    tokio::time::sleep(sleep).await;
273                }
274                Err(ClientError(LockBillingWorkflowError::UserNotFound)) => return Ok(None),
275                Err(err) => return Err(format!("Cannot lock billing for {owner:?}: {err:?}")),
276            }
277        }
278    }
279
280    /// Admin check/reconcile of cached Stripe billing against live Stripe.
281    pub async fn admin_sync_stripe(
282        &self, context: RequestContext<AdminSyncStripeRequest>,
283    ) -> Result<AdminSyncStripeResponse, ServerError<AdminSyncStripeError>> {
284        {
285            let db = self.index_db.lock().await;
286            if !Self::is_admin::<AdminSyncStripeError>(
287                &db.schema,
288                &context.public_key,
289                &self.config.admin.admins,
290            )? {
291                return Err(ClientError(AdminSyncStripeError::NotPermissioned));
292            }
293        }
294
295        let targets: Vec<(String, Owner, String)> = match &context.request.username {
296            Some(username) => {
297                let (owner, account) = {
298                    let db = self.index_db.lock().await;
299                    let owner = *db
300                        .schema
301                        .usernames
302                        .get(username)
303                        .ok_or(ClientError(AdminSyncStripeError::UserNotFound))?;
304                    let account = db
305                        .schema
306                        .accounts
307                        .get(&owner)
308                        .cloned()
309                        .ok_or(ClientError(AdminSyncStripeError::UserNotFound))?;
310                    (owner, account)
311                };
312                let customer_id = self
313                    .stripe_customer_of(&owner.0, &account)
314                    .await
315                    .ok_or(ClientError(AdminSyncStripeError::NotStripeCustomer))?;
316                vec![(account.username, owner, customer_id)]
317            }
318            None => {
319                let db = self.index_db.lock().await;
320                let is_live_account = |owner: &Owner| {
321                    db.schema
322                        .owned_files
323                        .get(owner)
324                        .is_some_and(|ids| !ids.is_empty())
325                };
326                let mut by_owner: HashMap<Owner, (String, String)> = HashMap::new();
327                for (owner, account) in db.schema.accounts.iter() {
328                    if !is_live_account(owner) {
329                        continue;
330                    }
331                    if let Some(BillingPlatform::Stripe(info)) =
332                        &account.billing_info.billing_platform
333                    {
334                        if !info.customer_id.is_empty() {
335                            by_owner.insert(
336                                *owner,
337                                (account.username.clone(), info.customer_id.clone()),
338                            );
339                        }
340                    }
341                }
342                for (customer_id, owner) in db.schema.stripe_ids.iter() {
343                    if !is_live_account(owner) {
344                        continue;
345                    }
346                    if let Some(account) = db.schema.accounts.get(owner) {
347                        by_owner
348                            .entry(*owner)
349                            .or_insert_with(|| (account.username.clone(), customer_id.clone()));
350                    }
351                }
352                let mut list: Vec<(String, Owner, String)> = by_owner
353                    .into_iter()
354                    .map(|(owner, (username, cus_id))| (username, owner, cus_id))
355                    .collect();
356                list.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.2.cmp(&b.2)));
357                list
358            }
359        };
360
361        let mut results = Vec::with_capacity(targets.len());
362        for (username, owner, customer_id) in targets {
363            let status = self
364                .check_or_sync_stripe_account(owner, &customer_id, context.request.apply)
365                .await;
366            results.push(AdminStripeAccountCheck { username, customer_id, status });
367        }
368
369        Ok(AdminSyncStripeResponse { results })
370    }
371
372    async fn check_or_sync_stripe_account(
373        &self, owner: Owner, customer_id: &str, apply: bool,
374    ) -> AdminStripeAccountStatus {
375        if !apply {
376            let account = self
377                .index_db
378                .lock()
379                .await
380                .schema
381                .accounts
382                .get(&owner)
383                .cloned();
384            let Some(account) = account else {
385                return AdminStripeAccountStatus::Error("Account no longer exists".into());
386            };
387            let live_info = match self.current_stripe_billing(customer_id).await {
388                Ok(info) => info,
389                Err(err) => return AdminStripeAccountStatus::Error(format!("{err:?}")),
390            };
391            return compare_stripe_state(&account, customer_id, live_info.as_ref());
392        }
393
394        let mut account = match self.lock_for_stripe_sync(&owner).await {
395            Ok(Some(account)) => account,
396            Ok(None) => return AdminStripeAccountStatus::Error("Account no longer exists".into()),
397            Err(msg) => return AdminStripeAccountStatus::Error(msg),
398        };
399
400        let live_result = self.current_stripe_billing(customer_id).await;
401        let status = match live_result {
402            Err(err) => AdminStripeAccountStatus::Error(format!("{err:?}")),
403            Ok(live_info) => {
404                let status = compare_stripe_state(&account, customer_id, live_info.as_ref());
405                if matches!(status, AdminStripeAccountStatus::Drifted { .. }) {
406                    apply_stripe_sync(owner, customer_id, &mut account, live_info.as_ref());
407                }
408                status
409            }
410        };
411
412        if let Err(err) = self
413            .release_subscription_profile::<AdminSyncStripeError>(owner.0, account)
414            .await
415        {
416            return AdminStripeAccountStatus::Error(format!(
417                "Failed to save account after Stripe sync: {err:?}"
418            ));
419        }
420
421        // Backfill stripe_ids even when InSync so future webhooks always find this customer.
422        if !matches!(status, AdminStripeAccountStatus::Error(_)) {
423            if let Err(err) = self
424                .record_stripe_customer::<AdminSyncStripeError>(customer_id, owner)
425                .await
426            {
427                return AdminStripeAccountStatus::Error(format!(
428                    "Failed to record stripe_ids mapping: {err:?}"
429                ));
430            }
431        }
432
433        status
434    }
435
436    /// The customer's live Stripe subscription, if any.
437    async fn current_stripe_billing(
438        &self, customer_id: &str,
439    ) -> Result<Option<StripeUserInfo>, ServerError<StripeWebhookError>> {
440        let subscriptions = self.stripe_client.list_subscriptions(customer_id).await?;
441        Ok(billing_from_subscriptions(customer_id, &subscriptions))
442    }
443
444    /// Verifies `Stripe-Signature` (HMAC-SHA256 + timestamp tolerance) and returns the customer ID
445    /// for events that can change subscription state. Parses raw JSON so Stripe webhook API
446    /// version changes cannot break deserialization.
447    pub fn verify_webhook_and_get_customer(
448        &self, request_body: &Bytes, stripe_sig: HeaderValue,
449    ) -> Result<Option<String>, ServerError<StripeWebhookError>> {
450        let payload = std::str::from_utf8(request_body).map_err(|e| {
451            ClientError(StripeWebhookError::InvalidBody(format!("Cannot get body as str: {e:?}")))
452        })?;
453        let sig = stripe_sig.to_str().map_err(|e| {
454            ClientError(StripeWebhookError::InvalidHeader(format!(
455                "Cannot get header as str: {e:?}"
456            )))
457        })?;
458
459        info!("Verifying a stripe webhook request");
460        let now_secs = self.clock.now().0 / 1000;
461        verify_stripe_signature(
462            payload,
463            sig,
464            &self.config.billing.stripe.signing_secret,
465            now_secs,
466        )?;
467
468        let value: serde_json::Value = serde_json::from_str(payload).map_err(|e| {
469            ClientError(StripeWebhookError::ParseError(format!("Invalid webhook JSON: {e:?}")))
470        })?;
471
472        let event_type = value.get("type").and_then(|v| v.as_str()).ok_or_else(|| {
473            ClientError(StripeWebhookError::InvalidBody("Missing webhook event type".into()))
474        })?;
475
476        let relevant = matches!(
477            event_type,
478            "checkout.session.completed"
479                | "customer.subscription.created"
480                | "customer.subscription.updated"
481                | "customer.subscription.deleted"
482                | "invoice.paid"
483                | "invoice.payment_failed"
484        );
485        if !relevant {
486            debug!(?event_type, "Ignoring stripe event");
487            return Ok(None);
488        }
489
490        let customer = value
491            .pointer("/data/object/customer")
492            .and_then(|v| {
493                v.as_str()
494                    .or_else(|| v.get("id").and_then(|id| id.as_str()))
495            })
496            .map(ToOwned::to_owned);
497        if customer.is_none() {
498            warn!(?event_type, "Relevant stripe webhook event has no customer id");
499        }
500        Ok(customer)
501    }
502}
503
504fn verify_stripe_signature(
505    payload: &str, header: &str, secret: &str, now_secs: i64,
506) -> Result<(), ServerError<StripeWebhookError>> {
507    if secret.is_empty() {
508        return Err(internal!("Stripe webhook signing secret is empty"));
509    }
510
511    let mut timestamp: Option<i64> = None;
512    let mut signatures: Vec<&str> = Vec::new();
513    for part in header.split(',') {
514        let Some((key, value)) = part.trim().split_once('=') else {
515            continue;
516        };
517        match key.trim() {
518            "t" => {
519                timestamp = value.trim().parse::<i64>().ok();
520            }
521            "v1" => signatures.push(value.trim()),
522            _ => {}
523        }
524    }
525
526    let t = timestamp.ok_or_else(|| {
527        ClientError(StripeWebhookError::InvalidHeader("Missing or invalid timestamp".into()))
528    })?;
529    if signatures.is_empty() {
530        return Err(ClientError(StripeWebhookError::InvalidHeader("Missing v1 signature".into())));
531    }
532    if now_secs.abs_diff(t) > WEBHOOK_TOLERANCE_SECS {
533        return Err(ClientError(StripeWebhookError::InvalidHeader(format!(
534            "Timestamp outside tolerance: {t}"
535        ))));
536    }
537
538    let mut mac = HmacSha256::new_from_slice(secret.as_bytes())
539        .map_err(|e| internal!("Invalid Stripe webhook signing secret: {e:?}"))?;
540    mac.update(format!("{t}.{payload}").as_bytes());
541    let expected = mac.finalize().into_bytes();
542
543    let matched = signatures.into_iter().any(|sig_hex| {
544        hex::decode(sig_hex).is_ok_and(|decoded| constant_time_eq(&expected, &decoded))
545    });
546    if !matched {
547        return Err(ClientError(StripeWebhookError::InvalidHeader("Bad signature".into())));
548    }
549    Ok(())
550}
551
552fn is_other_platform_premium(account: &Account) -> bool {
553    account.billing_info.is_premium()
554        && !matches!(account.billing_info.billing_platform, Some(BillingPlatform::Stripe(_)))
555}
556
557fn stripe_snapshot(info: &StripeUserInfo) -> AdminStripeSnapshot {
558    AdminStripeSnapshot {
559        subscription_id: info.subscription_id.clone(),
560        last_4: info.last_4.clone(),
561        expiration_time: info.expiration_time,
562        account_state: info.account_state.clone(),
563    }
564}
565
566fn compare_stripe_state(
567    account: &Account, customer_id: &str, live_info: Option<&StripeUserInfo>,
568) -> AdminStripeAccountStatus {
569    let stripe = live_info.map(stripe_snapshot);
570    if is_other_platform_premium(account) {
571        return AdminStripeAccountStatus::OtherPlatformPremium { stripe };
572    }
573    // A lapsed Stripe customer must never touch a recoverable mobile record (e.g. OnHold,
574    // FailedToRenew) or a newer Stripe customer on the same Lockbook account.
575    if live_info.is_none() {
576        match &account.billing_info.billing_platform {
577            Some(BillingPlatform::AppStore(_) | BillingPlatform::GooglePlay(_)) => {
578                return AdminStripeAccountStatus::InSync;
579            }
580            Some(BillingPlatform::Stripe(cur)) if cur.customer_id != customer_id => {
581                return AdminStripeAccountStatus::InSync;
582            }
583            _ => {}
584        }
585    }
586    let cached = match &account.billing_info.billing_platform {
587        Some(BillingPlatform::Stripe(info)) if info.customer_id == customer_id => {
588            Some(stripe_snapshot(info))
589        }
590        _ => None,
591    };
592    if cached == stripe {
593        AdminStripeAccountStatus::InSync
594    } else {
595        AdminStripeAccountStatus::Drifted { cached, stripe }
596    }
597}
598
599/// Applies Stripe's live state for `customer_id` to `account`.
600///
601/// - A live subscription writes `Some(BillingPlatform::Stripe(Ok))` unless another platform is
602///   already Premium.
603/// - No live subscription clears `billing_platform` to `None`, **only** when `billing_platform`
604///   currently points to `Stripe(customer_id)` — never clobbering recoverable mobile records
605///   (`GooglePlay::OnHold`, `AppStore::FailedToRenew`) or a newer Stripe customer on this owner.
606fn apply_stripe_sync(
607    owner: Owner, customer_id: &str, account: &mut Account, live_info: Option<&StripeUserInfo>,
608) {
609    match live_info {
610        Some(info) => {
611            if is_other_platform_premium(account) {
612                error!(?owner, "Stripe subscription for an account premium on another platform");
613            } else {
614                info!(?owner, state = ?info.account_state, "Syncing live stripe billing");
615                account.billing_info.billing_platform = Some(BillingPlatform::Stripe(info.clone()));
616            }
617        }
618        None => {
619            if matches!(
620                &account.billing_info.billing_platform,
621                Some(BillingPlatform::Stripe(cur)) if cur.customer_id == customer_id
622            ) {
623                info!(?owner, customer_id, "Clearing ended stripe billing");
624                account.billing_info.billing_platform = None;
625            }
626        }
627    }
628}
629
630fn billing_from_subscriptions(
631    customer_id: &str, subscriptions: &[StripeSubscription],
632) -> Option<StripeUserInfo> {
633    let subscription = subscriptions
634        .iter()
635        .filter(|s| s.is_live())
636        .max_by_key(|s| s.current_period_end)?;
637
638    Some(StripeUserInfo {
639        customer_id: customer_id.to_string(),
640        customer_name: Uuid::nil(),
641        price_id: subscription.price_id.clone(),
642        payment_method_id: subscription.payment_method_id.clone(),
643        last_4: subscription.card_last4.clone(),
644        subscription_id: subscription.id.clone(),
645        // Stripe counts seconds; every client reads milliseconds.
646        expiration_time: subscription.current_period_end.saturating_mul(1000),
647        account_state: StripeAccountState::Ok,
648    })
649}
650
651#[cfg(test)]
652mod tests {
653    use super::*;
654    use crate::billing::billing_model::{AppStoreUserInfo, GooglePlayUserInfo};
655    use crate::router_service::retired_card_upgrade;
656    use lb_rs::model::api::{
657        AppStoreAccountState, ErrorWrapper, FREE_TIER_USAGE_SIZE, GooglePlayAccountState,
658        PREMIUM_TIER_USAGE_SIZE,
659    };
660    use lb_rs::model::wire::{WIRE_FORMAT_HEADER, WireFormat};
661
662    fn make_sub(
663        id: &str, status: &str, current_period_end: u64, card_last4: &str,
664    ) -> StripeSubscription {
665        StripeSubscription {
666            id: id.into(),
667            status: status.into(),
668            current_period_end,
669            created: 1_700_000_000,
670            cancel_at_period_end: false,
671            cancel_at: None,
672            price_id: "price_monthly".into(),
673            payment_method_id: "pm_1".into(),
674            card_last4: card_last4.into(),
675        }
676    }
677
678    fn sign(secret: &str, t: i64, payload: &str) -> String {
679        let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).unwrap();
680        mac.update(format!("{t}.{payload}").as_bytes());
681        hex::encode(mac.finalize().into_bytes())
682    }
683
684    #[test]
685    fn verify_stripe_signature_checks_hmac_rotation_and_timestamps() {
686        let secret = "whsec_test_secret";
687        let now = 1_700_000_000;
688        let payload =
689            r#"{"type":"customer.subscription.updated","data":{"object":{"customer":"cus_1"}}}"#;
690        let sig = sign(secret, now, payload);
691
692        // Valid single signature and dual-v1 secret rotation header.
693        verify_stripe_signature(payload, &format!("t={now},v1={sig}"), secret, now).unwrap();
694        verify_stripe_signature(payload, &format!("t={now},v1=deadbeef,v1={sig}"), secret, now)
695            .unwrap();
696
697        // Bad sig, stale/future timestamps, i64::MIN overflow, missing fields rejected as 400.
698        for bad in [
699            format!("t={now},v1=deadbeef"),
700            format!("t={},v1={}", now - 600, sign(secret, now - 600, payload)),
701            format!("t={},v1={}", now + 600, sign(secret, now + 600, payload)),
702            "t=-9223372036854775808,v1=00".into(),
703            format!("v1={sig}"),
704            format!("t={now}"),
705        ] {
706            assert!(matches!(
707                verify_stripe_signature(payload, &bad, secret, now),
708                Err(ClientError(StripeWebhookError::InvalidHeader(_)))
709            ));
710        }
711
712        // Empty signing secret fails closed as 500.
713        assert!(matches!(
714            verify_stripe_signature(payload, &format!("t={now},v1={sig}"), "", now),
715            Err(ServerError::InternalError(_))
716        ));
717    }
718
719    #[test]
720    fn billing_from_subscriptions_and_apply_sync_invariants() {
721        let owner = Owner(PublicKey::from_secret_key(&lb_rs::model::pubkey::generate_key()));
722        let mut account = Account { username: "alice".into(), billing_info: Default::default() };
723
724        // Live active (empty Link last_4) -> Ok with milliseconds expiration.
725        let live =
726            billing_from_subscriptions("cus_1", &[make_sub("sub_1", "active", 1_800_000_000, "")])
727                .unwrap();
728        assert_eq!(live.expiration_time, 1_800_000_000_000);
729        assert_eq!(live.last_4, "");
730        assert_eq!(live.account_state, StripeAccountState::Ok);
731        apply_stripe_sync(owner, "cus_1", &mut account, Some(&live));
732        assert_eq!(account.billing_info.data_cap(), PREMIUM_TIER_USAGE_SIZE);
733
734        // past_due stays Premium; re-subscribing picks live sub_2 over old canceled sub_1.
735        let past_due = billing_from_subscriptions(
736            "cus_1",
737            &[make_sub("sub_1", "past_due", 1_800_000_000, "4242")],
738        )
739        .unwrap();
740        assert_eq!(past_due.account_state, StripeAccountState::Ok);
741        let resub = billing_from_subscriptions(
742            "cus_1",
743            &[
744                make_sub("sub_1", "canceled", 1_800_000_000, "4242"),
745                make_sub("sub_2", "active", 1_900_000_000, "1111"),
746            ],
747        )
748        .unwrap();
749        assert_eq!(resub.subscription_id, "sub_2");
750        assert_eq!(resub.last_4, "1111");
751
752        // Ended sub -> None, clears matching Stripe customer to Free (None).
753        assert!(
754            billing_from_subscriptions(
755                "cus_1",
756                &[make_sub("sub_1", "canceled", 1_800_000_000, "4242")]
757            )
758            .is_none()
759        );
760        apply_stripe_sync(owner, "cus_1", &mut account, None);
761        assert!(account.billing_info.billing_platform.is_none());
762        assert_eq!(account.billing_info.data_cap(), FREE_TIER_USAGE_SIZE);
763
764        // Lapsed old customer never wipes a newer active Stripe customer on the same owner.
765        let newer = billing_from_subscriptions(
766            "cus_new",
767            &[make_sub("sub_new", "active", 1_900_000_000, "9999")],
768        )
769        .unwrap();
770        apply_stripe_sync(owner, "cus_new", &mut account, Some(&newer));
771        assert_eq!(
772            compare_stripe_state(&account, "cus_old", None),
773            AdminStripeAccountStatus::InSync
774        );
775        apply_stripe_sync(owner, "cus_old", &mut account, None);
776        assert!(matches!(
777            &account.billing_info.billing_platform,
778            Some(BillingPlatform::Stripe(s)) if s.customer_id == "cus_new"
779        ));
780
781        // Lapsed Stripe never wipes recoverable GooglePlay(OnHold); live Stripe never wipes active AppStore(Ok).
782        account.billing_info.billing_platform =
783            Some(BillingPlatform::GooglePlay(GooglePlayUserInfo {
784                purchase_token: "tok".into(),
785                subscription_product_id: "prod".into(),
786                subscription_offer_id: "offer".into(),
787                expiration_time: 1_900_000_000_000,
788                account_state: GooglePlayAccountState::OnHold,
789            }));
790        assert_eq!(
791            compare_stripe_state(&account, "cus_old", None),
792            AdminStripeAccountStatus::InSync
793        );
794        apply_stripe_sync(owner, "cus_old", &mut account, None);
795        assert!(matches!(
796            &account.billing_info.billing_platform,
797            Some(BillingPlatform::GooglePlay(g)) if g.account_state == GooglePlayAccountState::OnHold
798        ));
799
800        account.billing_info.billing_platform = Some(BillingPlatform::AppStore(AppStoreUserInfo {
801            account_token: "tok".into(),
802            original_transaction_id: "tx1".into(),
803            subscription_product_id: "prod".into(),
804            expiration_time: 1_900_000_000_000,
805            account_state: AppStoreAccountState::Ok,
806        }));
807        assert!(matches!(
808            compare_stripe_state(&account, "cus_old", Some(&newer)),
809            AdminStripeAccountStatus::OtherPlatformPremium { .. }
810        ));
811        apply_stripe_sync(owner, "cus_old", &mut account, Some(&newer));
812        assert!(matches!(
813            &account.billing_info.billing_platform,
814            Some(BillingPlatform::AppStore(_))
815        ));
816    }
817
818    #[tokio::test]
819    async fn retired_card_upgrade_returns_client_update_required_in_both_wire_formats() {
820        let filter = retired_card_upgrade();
821
822        for (header, fmt) in [(None, WireFormat::Json), (Some("bincode"), WireFormat::Bincode)] {
823            let mut req = warp::test::request()
824                .method("POST")
825                .path("/upgrade-account-stripe");
826            if let Some(h) = header {
827                req = req.header(WIRE_FORMAT_HEADER, h);
828            }
829            let resp = req.reply(&filter).await;
830            assert_eq!(resp.status(), warp::http::StatusCode::BAD_REQUEST);
831            let parsed: Result<(), ErrorWrapper<()>> = fmt.deserialize(resp.body()).unwrap();
832            assert_eq!(parsed, Err(ErrorWrapper::ClientUpdateRequired));
833        }
834    }
835}