fix(subscription): require team admin for billing actions

Subscription actions ran on the session team without a role check. A user
who switched the session to a team where they are only a member could
cancel, refund, or change that team's subscription.

- Lock the team id at mount and require admin or owner of that team
- Check the locked team and the role again in every billing action
- Reject actions after the session switched to another team
This commit is contained in:
Andras Bacsai
2026-10-05 17:04:05 +02:00
parent 0da202b39d
commit 3987f97a8e
2 changed files with 209 additions and 15 deletions
+52 -15
View File
@@ -11,11 +11,15 @@ use App\Models\Team;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Stripe\StripeClient;
class Actions extends Component
{
#[Locked]
public ?int $teamId = null;
public $server_limits = 0;
public int $quantity = UpdateSubscriptionQuantity::MIN_SERVER_LIMIT;
@@ -46,16 +50,21 @@ class Actions extends Component
public function mount(): void
{
$team = currentTeam();
abort_unless($team && auth()->user()->isAdminOfTeam($team->id), 403);
$this->teamId = $team->id;
$this->server_limits = Team::serverLimit();
$this->quantity = (int) $this->server_limits;
$this->billingInterval = currentTeam()->subscription?->billingInterval() ?? 'monthly';
$this->billingInterval = $team->subscription?->billingInterval() ?? 'monthly';
$this->canDeleteAccount = app(DeleteUserAccount::class)->blockers(Auth::user(), removeTeamResources: true) === [];
}
public function loadPricePreview(int $quantity): void
{
$team = $this->authorizedTeam();
$this->quantity = $quantity;
$result = (new UpdateSubscriptionQuantity)->fetchPricePreview(currentTeam(), $quantity);
$result = (new UpdateSubscriptionQuantity)->fetchPricePreview($team, $quantity);
$this->pricePreview = $result['success'] ? $result['preview'] : null;
}
@@ -64,6 +73,8 @@ class Actions extends Component
// non-destructive, reversible billing adjustment (prorated by Stripe).
public function updateQuantity(string $password = ''): bool
{
$team = $this->authorizedTeam();
if ($this->quantity < UpdateSubscriptionQuantity::MIN_SERVER_LIMIT) {
$this->dispatch('error', 'Minimum server limit is '.UpdateSubscriptionQuantity::MIN_SERVER_LIMIT.'.');
$this->quantity = UpdateSubscriptionQuantity::MIN_SERVER_LIMIT;
@@ -76,7 +87,7 @@ class Actions extends Component
}
$previousServerLimit = (int) $this->server_limits;
$result = (new UpdateSubscriptionQuantity)->execute(currentTeam(), $this->quantity);
$result = (new UpdateSubscriptionQuantity)->execute($team, $this->quantity);
if ($result['success']) {
$this->auditSubscriptionChange('quantity_updated', [
@@ -98,23 +109,26 @@ class Actions extends Component
public function loadRefundEligibility(): void
{
$this->authorizedTeam();
$this->checkRefundEligibility();
$this->refundCheckLoading = false;
}
public function stripeCustomerPortal(): void
{
$session = getStripeCustomerPortalSession(currentTeam());
$session = getStripeCustomerPortalSession($this->authorizedTeam());
redirect($session->url);
}
public function refundSubscription(string $password): bool|string
{
$team = $this->authorizedTeam();
if (! shouldSkipPasswordConfirmation() && ! Hash::check($password, auth()->user()->password)) {
return 'Invalid password.';
}
$result = app(RefundSubscription::class)->execute(currentTeam());
$result = app(RefundSubscription::class)->execute($team);
if ($result['success']) {
$this->auditSubscriptionChange('refunded');
@@ -131,6 +145,8 @@ class Actions extends Component
public function cancelImmediately(string $password, array $selectedActions = []): bool|string
{
$team = $this->authorizedTeam();
if (! shouldSkipPasswordConfirmation() && ! Hash::check($password, auth()->user()->password)) {
return 'Invalid password.';
}
@@ -141,7 +157,7 @@ class Actions extends Component
}
$refund = in_array('refundLatestPayment', $selectedActions, true);
if (! $this->cancelSubscriptionNow($refund)) {
if (! $this->cancelSubscriptionNow($team, $refund)) {
$this->dispatch('error', 'Something went wrong with the '.($refund ? 'refund' : 'cancellation').'. Please <a href="'.config('constants.urls.contact').'" target="_blank" class="underline">contact us</a>.');
return true;
@@ -159,11 +175,13 @@ class Actions extends Component
public function cancelAtPeriodEnd(string $password): bool|string
{
$team = $this->authorizedTeam();
if (! shouldSkipPasswordConfirmation() && ! Hash::check($password, auth()->user()->password)) {
return 'Invalid password.';
}
$result = (new CancelSubscriptionAtPeriodEnd)->execute(currentTeam());
$result = (new CancelSubscriptionAtPeriodEnd)->execute($team);
if ($result['success']) {
$this->auditSubscriptionChange('cancellation_scheduled', ['cancel_at_period_end' => true]);
@@ -179,7 +197,8 @@ class Actions extends Component
public function resumeSubscription(): bool
{
$result = (new ResumeSubscription)->execute(currentTeam());
$team = $this->authorizedTeam();
$result = (new ResumeSubscription)->execute($team);
if ($result['success']) {
$this->auditSubscriptionChange('resumed');
@@ -193,10 +212,8 @@ class Actions extends Component
return true;
}
private function cancelSubscriptionNow(bool $refund): bool
private function cancelSubscriptionNow(Team $team, bool $refund): bool
{
$team = currentTeam();
if ($refund) {
// Eligibility is re-validated server-side inside RefundSubscription::execute()
$result = app(RefundSubscription::class)->execute($team);
@@ -267,6 +284,24 @@ class Actions extends Component
return true;
}
/**
* Resolve the team locked at mount, rejecting the request when the session
* switched to another team or the user is no longer an admin of that team.
*/
private function authorizedTeam(): Team
{
$team = currentTeam();
abort_unless(
$this->teamId !== null
&& $team?->id === $this->teamId
&& auth()->user()->isAdminOfTeam($this->teamId),
403
);
return $team;
}
/**
* Record a user-triggered subscription change for the current team.
*
@@ -274,7 +309,7 @@ class Actions extends Component
*/
private function auditSubscriptionChange(string $action, array $context = []): void
{
$team = currentTeam();
$team = $this->authorizedTeam();
auditLog("ui.subscription.{$action}", [
'team_id' => $team?->id,
@@ -287,13 +322,15 @@ class Actions extends Component
private function checkRefundEligibility(): void
{
if (! isCloud() || ! currentTeam()->subscription?->stripe_subscription_id) {
$team = $this->authorizedTeam();
if (! isCloud() || ! $team->subscription?->stripe_subscription_id) {
return;
}
try {
$this->refundAlreadyUsed = currentTeam()->subscription?->stripe_refunded_at !== null;
$result = (new RefundSubscription)->checkEligibility(currentTeam());
$this->refundAlreadyUsed = $team->subscription?->stripe_refunded_at !== null;
$result = (new RefundSubscription)->checkEligibility($team);
$this->isRefundEligible = $result['eligible'];
$this->refundDaysRemaining = $result['days_remaining'];
@@ -0,0 +1,157 @@
<?php
use App\Livewire\Subscription\Actions;
use App\Models\InstanceSettings;
use App\Models\Subscription;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
use Stripe\Service\SubscriptionService;
use Stripe\Stripe;
use Stripe\StripeClient;
uses(RefreshDatabase::class);
beforeEach(function () {
config()->set('constants.coolify.self_hosted', false);
config()->set('subscription.provider', 'stripe');
config()->set('subscription.stripe_api_key', 'sk_test_fake');
InstanceSettings::unguarded(fn () => InstanceSettings::query()->create(['id' => 0]));
$this->originalStripeApiBase = Stripe::$apiBase;
Stripe::$apiBase = 'http://127.0.0.1:1';
$this->stripeResolved = false;
$this->app->bind(StripeClient::class, function () {
$this->stripeResolved = true;
throw new RuntimeException('Stripe must not be called.');
});
$this->user = User::factory()->create();
$this->ownTeam = Team::factory()->create();
$this->ownTeam->members()->attach($this->user->id, ['role' => 'owner']);
Subscription::create([
'team_id' => $this->ownTeam->id,
'stripe_subscription_id' => 'sub_own_team',
'stripe_customer_id' => 'cus_own_team',
'stripe_invoice_paid' => true,
'stripe_plan_id' => 'price_test_123',
'stripe_cancel_at_period_end' => false,
'stripe_past_due' => false,
]);
$this->otherTeam = Team::factory()->create();
$this->otherTeam->members()->attach($this->user->id, ['role' => 'member']);
$this->otherSubscription = Subscription::create([
'team_id' => $this->otherTeam->id,
'stripe_subscription_id' => 'sub_other_team',
'stripe_customer_id' => 'cus_other_team',
'stripe_invoice_paid' => true,
'stripe_plan_id' => 'price_test_123',
'stripe_cancel_at_period_end' => true,
'stripe_past_due' => false,
]);
$this->actingAs($this->user);
});
afterEach(function () {
Stripe::$apiBase = $this->originalStripeApiBase;
});
dataset('subscription billing actions', [
'updateQuantity' => [fn ($component) => $component->set('quantity', 5)->call('updateQuantity')],
'loadPricePreview' => [fn ($component) => $component->call('loadPricePreview', 5)],
'refundSubscription' => [fn ($component) => $component->call('refundSubscription', 'password')],
'cancelImmediately' => [fn ($component) => $component->call('cancelImmediately', 'password')],
'cancelImmediately with refund' => [fn ($component) => $component->call('cancelImmediately', 'password', ['refundLatestPayment'])],
'cancelAtPeriodEnd' => [fn ($component) => $component->call('cancelAtPeriodEnd', 'password')],
'resumeSubscription' => [fn ($component) => $component->call('resumeSubscription')],
'loadRefundEligibility' => [fn ($component) => $component->call('loadRefundEligibility')],
'stripeCustomerPortal' => [fn ($component) => $component->call('stripeCustomerPortal')],
]);
function expectOtherTeamSubscriptionUntouched(): void
{
$subscription = test()->otherSubscription->fresh();
expect($subscription->stripe_subscription_id)->toBe('sub_other_team')
->and((bool) $subscription->stripe_invoice_paid)->toBeTrue()
->and((bool) $subscription->stripe_cancel_at_period_end)->toBeTrue()
->and($subscription->stripe_refunded_at)->toBeNull()
->and(test()->stripeResolved)->toBeFalse();
}
test('a team member cannot mount the subscription actions', function () {
session(['currentTeam' => $this->otherTeam]);
Livewire::test(Actions::class)->assertForbidden();
expectOtherTeamSubscriptionUntouched();
});
test('a team admin can mount the subscription actions and lock the team', function (string $role) {
$this->otherTeam->members()->updateExistingPivot($this->user->id, ['role' => $role]);
$this->user->unsetRelation('teams');
session(['currentTeam' => $this->otherTeam]);
Livewire::test(Actions::class)
->assertOk()
->assertSet('teamId', $this->otherTeam->id);
})->with(['admin', 'owner']);
test('an admin can still resume the subscription of the locked team', function () {
$this->otherTeam->members()->updateExistingPivot($this->user->id, ['role' => 'admin']);
$this->user->unsetRelation('teams');
session(['currentTeam' => $this->otherTeam]);
$stripe = Mockery::mock(StripeClient::class);
$stripe->subscriptions = Mockery::mock(SubscriptionService::class);
$stripe->subscriptions->shouldReceive('update')->once()->with('sub_other_team', ['cancel_at_period_end' => false]);
$this->instance(StripeClient::class, $stripe);
Livewire::test(Actions::class)
->call('resumeSubscription')
->assertOk()
->assertDispatched('success');
expect((bool) $this->otherSubscription->fresh()->stripe_cancel_at_period_end)->toBeFalse();
});
test('a billing action is rejected after the session switches to a team where the user is a member', function (Closure $action) {
session(['currentTeam' => $this->ownTeam]);
$component = Livewire::test(Actions::class)->assertOk();
session(['currentTeam' => $this->otherTeam]);
$action($component)->assertForbidden();
expectOtherTeamSubscriptionUntouched();
})->with('subscription billing actions');
test('a billing action is rejected after the user is demoted to member of the locked team', function (Closure $action) {
$this->otherTeam->members()->updateExistingPivot($this->user->id, ['role' => 'admin']);
$this->user->unsetRelation('teams');
session(['currentTeam' => $this->otherTeam]);
$component = Livewire::test(Actions::class)->assertOk();
$this->otherTeam->members()->updateExistingPivot($this->user->id, ['role' => 'member']);
$this->user->unsetRelation('teams');
$action($component)->assertForbidden();
expectOtherTeamSubscriptionUntouched();
})->with('subscription billing actions');
test('the locked team id cannot be changed by the client', function () {
session(['currentTeam' => $this->ownTeam]);
Livewire::test(Actions::class)->set('teamId', $this->otherTeam->id);
})->throws(CannotUpdateLockedPropertyException::class);