Skip to content

Conversation

@cyprain-okeke
Copy link
Contributor

🎟️ Tracking

https://bitwarden.atlassian.net/browse/PM-29595

📔 Objective

Feature: Allow users to revert Premium-to-Organization upgrades during trial period

Summary
Enables users who upgraded from Premium to Organization to revert the upgrade during the trial period. If they cancel during trial, the subscription reverts to their original Premium plan instead of being canceled.

Key Changes

  1. Reversion logic in SubscriberService:
  • Added TryRevertPremiumUpgradeAsync() that checks for premium upgrade metadata when an organization cancels
  • If metadata exists and the subscription is in trial, reverts to Premium instead of canceling
  • Restores the user's Premium status, storage, and subscription details
  1. Metadata tracking:
  • Added metadata keys in StripeConstants to track upgrade info:
    • PreviousPremiumPriceId
    • PreviousPremiumUserId
    • UpgradedOrganizationId
    • PreviousPeriodEndDate
    • PreviousAdditionalStorage
    • PreviousStoragePriceId
  1. Metadata cleanup:
  • Added CleanupPremiumUpgradeMetadataAfterTrialAsync() in SubscriptionUpdatedHandler to remove reversion metadata after the trial ends successfully

📸 Screenshots

⏰ Reminders before review

  • Contributor guidelines followed
  • All formatters and local linters executed and passed
  • Written new unit and / or integration tests where applicable
  • Protected functional changes with optionality (feature flags)
  • Used internationalization (i18n) for all UI strings
  • CI builds passed
  • Communicated to DevOps any deployment requirements
  • Updated any necessary documentation (Confluence, contributing docs) or informed the documentation team

🦮 Reviewer guidelines

  • 👍 (:+1:) or similar for great changes
  • 📝 (:memo:) or ℹ️ (:information_source:) for notes or general info
  • ❓ (:question:) for questions
  • 🤔 (:thinking:) or 💭 (:thought_balloon:) for more open inquiry that's not quite a confirmed issue and could potentially benefit from discussion
  • 🎨 (:art:) for suggestions / improvements
  • ❌ (:x:) or ⚠️ (:warning:) for more significant problems or concerns needing attention
  • 🌱 (:seedling:) or ♻️ (:recycle:) for future improvements or indications of technical debt
  • ⛏ (:pick:) for minor or nitpick changes

@cyprain-okeke cyprain-okeke requested a review from a team as a code owner January 15, 2026 15:47
@codecov
Copy link

codecov bot commented Jan 15, 2026

Codecov Report

❌ Patch coverage is 85.63218% with 25 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.06%. Comparing base (75a8570) to head (c7528df).

Files with missing lines Patch % Lines
...ling/Services/Implementations/SubscriberService.cs 90.15% 9 Missing and 4 partials ⚠️
...ices/Implementations/SubscriptionUpdatedHandler.cs 69.23% 10 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6849      +/-   ##
==========================================
+ Coverage   56.00%   56.06%   +0.06%     
==========================================
  Files        1966     1966              
  Lines       86875    87047     +172     
  Branches     7737     7755      +18     
==========================================
+ Hits        48650    48805     +155     
- Misses      36426    36437      +11     
- Partials     1799     1805       +6     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

cyprain-okeke and others added 3 commits January 15, 2026 17:39
…mium-reverts-an-organization-upgrade-during-the-trial-period
…mium-reverts-an-organization-upgrade-during-the-trial-period
@github-actions
Copy link
Contributor

github-actions bot commented Jan 16, 2026

Logo
Checkmarx One – Scan Summary & Details9c1cfc98-b947-48bc-8b74-fc4c5fb340d2

New Issues (2)

Checkmarx found the following issues in this Pull Request

# Severity Issue Source File / Package Checkmarx Insight
1 MEDIUM CSRF /src/Api/Billing/Controllers/AccountsController.cs: 107
detailsMethod at line 107 of /src/Api/Billing/Controllers/AccountsController.cs gets a parameter from a user request from subscriberService. This param...
Attack Vector
2 MEDIUM CSRF /src/Api/Billing/Controllers/VNext/AccountBillingVNextController.cs: 123
detailsMethod at line 123 of /src/Api/Billing/Controllers/VNext/AccountBillingVNextController.cs gets a parameter from a user request from request. Thi...
Attack Vector

Copy link
Contributor

@amorask-bitwarden amorask-bitwarden left a comment

Choose a reason for hiding this comment

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

Nice work here, just a few questions and thoughts on the logic.

private async Task<bool> TryRevertPremiumUpgradeAsync(Subscription subscription, Organization organization)
{
// Extract all metadata once
var metadata = subscription.Metadata ?? new Dictionary<string, string>();
Copy link
Contributor

Choose a reason for hiding this comment

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


// STEP 2: Get the current Premium plan details from pricing client
var premiumPlan = await pricingClient.GetAvailablePremiumPlan();
if (premiumPlan == null || !premiumPlan.Available)
Copy link
Contributor

Choose a reason for hiding this comment

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

pricingClient.GetAvailablePremiumPlan throws a NotFoundException. It does not return null which is why the result isn't nullable.

updatedMetadata.Remove(MetadataKeys.OrganizationId);

// STEP 6: Update Stripe subscription
var updateOptions = new SubscriptionUpdateOptions
Copy link
Contributor

Choose a reason for hiding this comment

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

What's the periodEnd variable for? Is that supposed to go somewhere in here?

Copy link
Contributor

Choose a reason for hiding this comment

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

❓ Same question.

{
// STEP 1: Fastest check first - check if subscription has premium upgrade metadata
// This avoids expensive deserialization for subscriptions without this metadata
if (subscription.Metadata == null ||
Copy link
Contributor

Choose a reason for hiding this comment

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

subscription.metadata is not a nullable property.

if (cancelImmediately)
{
if (subscription.Metadata != null && subscription.Metadata.ContainsKey("organizationId"))
if (subscription.Metadata.ContainsKey("organizationId"))
Copy link
Contributor

Choose a reason for hiding this comment

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

⛏️ Let's use StripeConstants.MetadataKeys here.

// rather than "reversion failed" - the cancellation should proceed normally.

// Check if metadata exists
if (metadata == null)
Copy link
Contributor

Choose a reason for hiding this comment

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

⛏️ Mentioned this a couple of times - a Subscription's metadata is not a nullable property in Stripe's API so this check is not necessary.

// Check if this is a Premium-to-Organization upgrade that can be reverted
if (subscriber is Organization organization)
{
var canRevert = await TryRevertPremiumUpgradeAsync(subscription, organization);
Copy link
Contributor

Choose a reason for hiding this comment

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

❌ This is confusing. Your method that actually does the reversion of the premium upgrade returns a boolean that indicates whether the organization can revert in the first place? I think these should be 2 methods: 1 to check of an organization can revert and another to do the reversion.

updatedMetadata.Remove(MetadataKeys.OrganizationId);

// STEP 6: Update Stripe subscription
var updateOptions = new SubscriptionUpdateOptions
Copy link
Contributor

Choose a reason for hiding this comment

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

❓ Same question.

var premiumPlans = await _pricingClient.ListPremiumPlans();
var premiumPriceIds = premiumPlans.SelectMany(p => new[] { p.Seat.StripePriceId, p.Storage.StripePriceId }).ToHashSet();
return subscription.Items.Any(i => premiumPriceIds.Contains(i.Price.Id));
if (premiumPlans == null || !premiumPlans.Any())
Copy link
Contributor

Choose a reason for hiding this comment

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

The response from ListPremiumPlans is also not nullable.

}

var premiumPriceIds = premiumPlans
.Where(p => p.Seat != null && p.Storage != null)
Copy link
Contributor

Choose a reason for hiding this comment

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

Neither of these are nullable.

.SelectMany(p => new[] { p.Seat.StripePriceId, p.Storage.StripePriceId })
.ToHashSet();

return subscription.Items.Any(i => i.Price != null && premiumPriceIds.Contains(i.Price.Id));
Copy link
Contributor

Choose a reason for hiding this comment

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

Price is not nullable.

// Get all plan IDs that include Secrets Manager support to check if the organization has secret manager in the
// previous and/or current subscriptions.
var planIdsOfPlansWithSecretManager = (await _pricingClient.ListPlans())
var plans = await _pricingClient.ListPlans();
Copy link
Contributor

Choose a reason for hiding this comment

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

Why are we making changes to the RemovePasswordManagerCouponIfRemovingSecretsManagerTrialAsync as part of this work?


// STEP 5: Check if subscription still has OrganizationId (race condition check)
// If reversion already happened, OrganizationId would be removed and we should skip cleanup
if (!subscription.Metadata.ContainsKey(StripeConstants.MetadataKeys.OrganizationId))
Copy link
Contributor

Choose a reason for hiding this comment

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

Can you explain this logic here?

Copy link
Contributor

@amorask-bitwarden amorask-bitwarden left a comment

Choose a reason for hiding this comment

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

Just a couple small things then we're good to go.

/// <param name="subscription">The Stripe subscription to check</param>
/// <param name="organization">The organization attempting to cancel</param>
/// <returns>True if the reversion is possible, false otherwise</returns>
private Task<bool> CanRevertPremiumUpgradeAsync(Subscription subscription, Organization organization)
Copy link
Contributor

Choose a reason for hiding this comment

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

❓ Why is this returning a Task? Also, can we rename it to something more aligned with the process? Something along the lines of IsRevertingPremiumUpgrade?

// Check if this is a Premium-to-Organization upgrade that can be reverted
if (subscriber is Organization organization)
{
var canRevert = await CanRevertPremiumUpgradeAsync(subscription, organization);
Copy link
Contributor

Choose a reason for hiding this comment

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

⛏️ canRevert is unnecessary.

if (IsRevertingPremiumUpgrade(subscription, organization))
{
    await RevertPremiumUpgradeAsync(subscription, organization);
    return;
}

Copy link
Contributor

@amorask-bitwarden amorask-bitwarden left a comment

Choose a reason for hiding this comment

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

Nice work - thank you for handling the feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants