From d6afc9d88efd16021e22e0f54260597f9a321052 Mon Sep 17 00:00:00 2001 From: Pierre Brisorgueil Date: Mon, 16 Nov 2026 15:10:48 +0100 Subject: [PATCH 1/3] fix(billing): only org owners and admins can checkout or open the portal Members keep read rights on subscription, usage and extras balance/ledger. Closes #4290 --- MIGRATIONS.md | 12 ++ modules/billing/policies/billing.policy.js | 18 +- .../tests/billing.abilities.unit.tests.js | 77 +++++++++ .../tests/billing.policy.integration.tests.js | 163 ++++++++++++++++++ 4 files changed, 265 insertions(+), 5 deletions(-) create mode 100644 modules/billing/tests/billing.abilities.unit.tests.js create mode 100644 modules/billing/tests/billing.policy.integration.tests.js diff --git a/MIGRATIONS.md b/MIGRATIONS.md index 019009a09..8c4af4377 100644 --- a/MIGRATIONS.md +++ b/MIGRATIONS.md @@ -4,6 +4,18 @@ Breaking changes and upgrade notes for downstream projects. --- +## billing: only organization owners and admins can pay — checkout, extras checkout, Stripe portal (2026-11-16) + +#4290: `billingAbilities` now grants `create` on `BillingCheckout`, `BillingPortal` and `BillingExtrasCheckout` only to a membership whose `role` is `owner` or `admin`. A plain `member` gets **403** on `POST /api/billing/checkout`, `POST /api/billing/portal` and `POST /api/billing/extras/checkout`, and those three rules disappear from the abilities sent to the client (signin, signup, token refresh, organization switch). Members keep `read` on `BillingSubscription`, `BillingUsage`, `BillingExtrasBalance` and `BillingExtrasLedger`. Platform admins are unchanged. + +### Action for downstream + +- **Nothing to do if your billing policy is the stack's.** A solo user is the owner of their own organization and keeps every right. +- **Your own code or tests that start a checkout or open the portal as a `member`**: run them as an owner or admin instead. +- **Vue**: ship the matching Vue stack update in the same batch — the organization billing tab now needs `create BillingPortal` and the pricing page hides checkout from members. + +--- + ## Node 26 required: `.nvmrc` 26, `FROM node:26-slim`, `engines.node` `>=26.0.0` (2026-11-09) #4263: the stack now declares and builds on Node 26. `.npmrc` carries `engine-strict=true`, so **`npm ci` fails with `EBADENGINE` on Node 24** (or any Node below 26) as soon as this change is merged. `engines.npm` stays `>=11.0.0`. CI needs no change of its own: `actions/setup-node` reads `.nvmrc` via `node-version-file`. diff --git a/modules/billing/policies/billing.policy.js b/modules/billing/policies/billing.policy.js index f8f35da5e..02afafa3f 100644 --- a/modules/billing/policies/billing.policy.js +++ b/modules/billing/policies/billing.policy.js @@ -1,6 +1,10 @@ /** * Billing ability definitions for CASL document-level authorization. */ +import { MEMBERSHIP_ROLES } from '../../organizations/lib/constants.js'; + +/** Membership roles allowed to pay for the organization (checkout, extras, Stripe portal). */ +const BILLING_MANAGER_ROLES = [MEMBERSHIP_ROLES.OWNER, MEMBERSHIP_ROLES.ADMIN]; /** * Register billing-related subjects for path-level resolution. @@ -39,7 +43,9 @@ export function billingSubjectRegistration({ registerPathSubject }) { /** * Define billing-related abilities for an authenticated user. - * Any authenticated user with an organization membership can manage billing. + * Every organization member can read the subscription, usage and extras balance/ledger. + * Only owners and admins can pay for the organization: start a plan checkout, + * buy extras, or open the Stripe billing portal. * @param {Object} user - The authenticated user * @param {Object|null} membership - Optional organization membership * @param {Object} builder - CASL AbilityBuilder helpers @@ -54,14 +60,16 @@ export function billingAbilities(user, membership, { can }) { if (!membership) return; - can('create', 'BillingCheckout'); - can('create', 'BillingPortal'); can('read', 'BillingSubscription'); can('read', 'BillingUsage'); - // Extras: members can purchase packs and read their own balance/ledger - can('create', 'BillingExtrasCheckout'); can('read', 'BillingExtrasBalance'); can('read', 'BillingExtrasLedger'); + + if (BILLING_MANAGER_ROLES.includes(membership.role)) { + can('create', 'BillingCheckout'); + can('create', 'BillingPortal'); + can('create', 'BillingExtrasCheckout'); + } } /** diff --git a/modules/billing/tests/billing.abilities.unit.tests.js b/modules/billing/tests/billing.abilities.unit.tests.js new file mode 100644 index 000000000..030a0f1b6 --- /dev/null +++ b/modules/billing/tests/billing.abilities.unit.tests.js @@ -0,0 +1,77 @@ +/** + * Module dependencies. + */ +import { describe, test, expect } from '@jest/globals'; +import { AbilityBuilder, createMongoAbility } from '@casl/ability'; + +import { billingAbilities } from '../policies/billing.policy.js'; +import { MEMBERSHIP_ROLES } from '../../organizations/lib/constants.js'; + +/** + * Unit tests for billingAbilities with a real CASL AbilityBuilder: only organization + * owners and admins can pay for the organization (checkout, extras checkout, Stripe + * portal); every member keeps the billing read rights. + */ + +const PAY_SUBJECTS = ['BillingCheckout', 'BillingPortal', 'BillingExtrasCheckout']; +const READ_SUBJECTS = ['BillingSubscription', 'BillingUsage', 'BillingExtrasBalance', 'BillingExtrasLedger']; + +/** + * Build a real CASL ability from billingAbilities. + * @param {Object} user - user fixture + * @param {Object|null} membership - membership fixture (plain object, as defineAbilityFor passes it) + * @returns {import('@casl/ability').MongoAbility} built ability + */ +function buildAbility(user, membership) { + const { can, cannot, build } = new AbilityBuilder(createMongoAbility); + billingAbilities(user, membership, { can, cannot }); + return build(); +} + +/** + * @param {string} role - membership role + * @returns {Object} membership fixture + */ +const membership = (role) => ({ role, organizationId: '507f1f77bcf86cd799439011' }); + +const user = { _id: 'u1', roles: ['user'] }; + +describe('billingAbilities (real CASL):', () => { + describe.each([MEMBERSHIP_ROLES.OWNER, MEMBERSHIP_ROLES.ADMIN])('%s', (role) => { + test.each(PAY_SUBJECTS)('can create %s', (subject) => { + expect(buildAbility(user, membership(role)).can('create', subject)).toBe(true); + }); + + test.each(READ_SUBJECTS)('can read %s', (subject) => { + expect(buildAbility(user, membership(role)).can('read', subject)).toBe(true); + }); + }); + + describe('member', () => { + test.each(PAY_SUBJECTS)('cannot create %s', (subject) => { + expect(buildAbility(user, membership(MEMBERSHIP_ROLES.MEMBER)).can('create', subject)).toBe(false); + }); + + test.each(READ_SUBJECTS)('can still read %s', (subject) => { + expect(buildAbility(user, membership(MEMBERSHIP_ROLES.MEMBER)).can('read', subject)).toBe(true); + }); + }); + + test('membership without a role gets no pay rights', () => { + const ability = buildAbility(user, { organizationId: 'x' }); + for (const subject of PAY_SUBJECTS) expect(ability.can('create', subject)).toBe(false); + }); + + test('no membership gets no billing rights', () => { + const ability = buildAbility(user, null); + for (const subject of [...PAY_SUBJECTS, ...READ_SUBJECTS]) { + expect(ability.can('create', subject)).toBe(false); + expect(ability.can('read', subject)).toBe(false); + } + }); + + test('platform admin manages everything, whatever the membership', () => { + const ability = buildAbility({ roles: ['user', 'admin'] }, membership(MEMBERSHIP_ROLES.MEMBER)); + for (const subject of PAY_SUBJECTS) expect(ability.can('create', subject)).toBe(true); + }); +}); diff --git a/modules/billing/tests/billing.policy.integration.tests.js b/modules/billing/tests/billing.policy.integration.tests.js new file mode 100644 index 000000000..8ff7d6272 --- /dev/null +++ b/modules/billing/tests/billing.policy.integration.tests.js @@ -0,0 +1,163 @@ +/** + * Module dependencies. + */ +import request from 'supertest'; +import path from 'path'; + +import { beforeAll, afterAll, describe, test, expect } from '@jest/globals'; +import { bootstrap } from '../../../lib/app.js'; +import config from '../../../config/index.js'; + +/** + * Billing policy integration tests — through the real auth, organization and policy + * middlewares. Only organization owners and admins can start a plan checkout, an + * extras checkout or open the Stripe portal; a plain member gets 403 on all three + * and keeps read access. The abilities sent to the client say the same thing. + * + * Owner/admin requests send a body the route validator rejects (unknown key): a 422 + * proves the policy let the request through without reaching Stripe. + */ +describe('Billing policy — owner/admin only pay routes:', () => { + let app; + let UserService; + let MembershipService; + let MembershipRepository; + let OrganizationsRepository; + + const PASSWORD = 'W@os.jsI$Aw3$0m3'; + const EMAILS = { + owner: 'billing-policy-owner@test.com', + admin: 'billing-policy-admin@test.com', + member: 'billing-policy-member@test.com', + }; + const PAY_ROUTES = ['/api/billing/checkout', '/api/billing/portal', '/api/billing/extras/checkout']; + const PAY_SUBJECTS = ['BillingCheckout', 'BillingPortal', 'BillingExtrasCheckout']; + const originalOrganizations = { ...config.organizations }; + + const agents = {}; + const users = {}; + const signupAbilities = {}; + const switchAbilities = {}; + let orgId; + + /** + * @param {Array} abilities - serialized CASL rules + * @param {string} subject - CASL subject + * @returns {boolean} true when a `create` rule exists for the subject + */ + const hasCreate = (abilities, subject) => abilities.some((r) => r.action === 'create' && r.subject === subject && !r.inverted); + + /** + * Remove a user, their memberships and the organizations they own. + * @param {string} email - user email + * @returns {Promise} + */ + const cleanup = async (email) => { + try { + const existing = await UserService.getBrut({ email }); + if (!existing) return; + const memberships = await MembershipRepository.list({ userId: existing._id }); + for (const m of memberships) { + if (m.role !== 'owner') continue; + const id = m.organizationId._id || m.organizationId; + await MembershipRepository.deleteMany({ organizationId: id }); + await OrganizationsRepository.deleteMany({ _id: id }); + } + await MembershipRepository.deleteMany({ userId: existing._id }); + await UserService.remove(existing); + } catch (_) { /* cleanup — ignore */ } + }; + + beforeAll(async () => { + config.organizations = { ...config.organizations, enabled: true, autoCreate: true, domainMatching: false }; + app = (await bootstrap()).app; + UserService = (await import(path.resolve('./modules/users/services/users.service.js'))).default; + MembershipService = (await import(path.resolve('./modules/organizations/services/organizations.membership.service.js'))).default; + MembershipRepository = (await import(path.resolve('./modules/organizations/repositories/organizations.membership.repository.js'))).default; + OrganizationsRepository = (await import(path.resolve('./modules/organizations/repositories/organizations.repository.js'))).default; + + for (const email of Object.values(EMAILS)) await cleanup(email); + + for (const [key, email] of Object.entries(EMAILS)) { + agents[key] = request.agent(app); + const res = await agents[key] + .post('/api/auth/signup') + .send({ firstName: 'Billing', lastName: key, email, password: PASSWORD, provider: 'local' }) + .expect(200); + users[key] = res.body.user; + signupAbilities[key] = res.body.abilities; + } + + orgId = String(users.owner.currentOrganization); + await MembershipService.create({ userId: users.admin.id || users.admin._id, organizationId: orgId, role: 'admin' }); + await MembershipService.create({ userId: users.member.id || users.member._id, organizationId: orgId, role: 'member' }); + + // Billing routes act on the caller's current organization: move admin and member into the owner's. + for (const key of ['admin', 'member']) { + const res = await agents[key].post(`/api/organizations/${orgId}/switch`).expect(200); + switchAbilities[key] = res.body.data.abilities; + } + }); + + afterAll(async () => { + for (const email of Object.values(EMAILS)) await cleanup(email); + config.organizations = originalOrganizations; + }); + + describe('pay routes', () => { + test.each(PAY_ROUTES)('member gets 403 from the policy on POST %s', async (route) => { + const res = await agents.member.post(route).send({ bogus: true }); + expect(res.status).toBe(403); + expect(res.body.description).toBe('User is not authorized'); + }); + + test.each(PAY_ROUTES)('owner passes the policy on POST %s', async (route) => { + const res = await agents.owner.post(route).send({ bogus: true }); + expect(res.status).toBe(422); + }); + + test.each(PAY_ROUTES)('admin passes the policy on POST %s', async (route) => { + const res = await agents.admin.post(route).send({ bogus: true }); + expect(res.status).toBe(422); + }); + }); + + describe('member read routes stay open', () => { + test.each(['/api/billing/subscription', '/api/billing/usage', '/api/billing/extras/balance', '/api/billing/extras/ledger'])( + 'member is not refused by the policy on GET %s', + async (route) => { + const res = await agents.member.get(route); + expect(res.status).not.toBe(403); + }, + ); + }); + + describe('abilities sent to the client', () => { + test.each(PAY_SUBJECTS)('owner signup response grants create %s', (subject) => { + expect(hasCreate(signupAbilities.owner, subject)).toBe(true); + }); + + test.each(PAY_SUBJECTS)('admin switch response grants create %s', (subject) => { + expect(hasCreate(switchAbilities.admin, subject)).toBe(true); + }); + + test.each(PAY_SUBJECTS)('member switch response does not grant create %s', (subject) => { + expect(hasCreate(switchAbilities.member, subject)).toBe(false); + }); + + test('token refresh: owner has the pay rights, member has none', async () => { + const owner = (await agents.owner.get('/api/auth/token').expect(200)).body.abilities; + const member = (await agents.member.get('/api/auth/token').expect(200)).body.abilities; + for (const subject of PAY_SUBJECTS) { + expect(hasCreate(owner, subject)).toBe(true); + expect(hasCreate(member, subject)).toBe(false); + } + expect(member.some((r) => r.action === 'read' && r.subject === 'BillingSubscription')).toBe(true); + }); + + test('signin: member signed back in keeps no pay rights', async () => { + const res = await agents.member.post('/api/auth/signin').send({ email: EMAILS.member, password: PASSWORD }).expect(200); + for (const subject of PAY_SUBJECTS) expect(hasCreate(res.body.abilities, subject)).toBe(false); + }); + }); +}); From 74d665eeb28a8fa2fc5d5aa7ea514eab73956c80 Mon Sep 17 00:00:00 2001 From: Pierre Brisorgueil Date: Mon, 16 Nov 2026 15:31:14 +0100 Subject: [PATCH 2/3] docs(policy): membership role now drives billing pay rights --- lib/middlewares/policy.js | 2 +- modules/billing/policies/billing.policy.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/middlewares/policy.js b/lib/middlewares/policy.js index d5122de2a..0fc3bdc4f 100644 --- a/lib/middlewares/policy.js +++ b/lib/middlewares/policy.js @@ -87,7 +87,7 @@ const registerAbilities = (entry) => { * Build a CASL ability instance for a given user and optional membership. * Iterates over all registered ability builder functions from module policy files. * @param {Object|null} user - The authenticated user, or null/undefined for guests - * @param {Object|null} [membership] - Optional organization membership (reserved for future use) + * @param {Object|null} [membership] - Optional organization membership; policies read its `role` (e.g. billing pay rights) * @returns {Promise} CASL ability instance */ const defineAbilityFor = async (user, membership) => { diff --git a/modules/billing/policies/billing.policy.js b/modules/billing/policies/billing.policy.js index 02afafa3f..f1cbb3a93 100644 --- a/modules/billing/policies/billing.policy.js +++ b/modules/billing/policies/billing.policy.js @@ -47,7 +47,7 @@ export function billingSubjectRegistration({ registerPathSubject }) { * Only owners and admins can pay for the organization: start a plan checkout, * buy extras, or open the Stripe billing portal. * @param {Object} user - The authenticated user - * @param {Object|null} membership - Optional organization membership + * @param {Object|null} membership - Organization membership; its `role` decides the pay rights * @param {Object} builder - CASL AbilityBuilder helpers * @param {Function} builder.can - Grant an ability * @returns {void} From 734df377da64d614c6537a4d7afdb11ac6839b3d Mon Sep 17 00:00:00 2001 From: Pierre Brisorgueil Date: Mon, 16 Nov 2026 15:38:29 +0100 Subject: [PATCH 3/3] test(billing): assert 200 success on member read routes --- modules/billing/tests/billing.policy.integration.tests.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/billing/tests/billing.policy.integration.tests.js b/modules/billing/tests/billing.policy.integration.tests.js index 8ff7d6272..1bd6b2de3 100644 --- a/modules/billing/tests/billing.policy.integration.tests.js +++ b/modules/billing/tests/billing.policy.integration.tests.js @@ -127,7 +127,8 @@ describe('Billing policy — owner/admin only pay routes:', () => { 'member is not refused by the policy on GET %s', async (route) => { const res = await agents.member.get(route); - expect(res.status).not.toBe(403); + expect(res.status).toBe(200); + expect(res.body.type).toBe('success'); }, ); });