-
-
Notifications
You must be signed in to change notification settings - Fork 10
fix(users/organizations/auth): prevent 500 on signin when org deleted without cascade (#3709) #3713
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
PierreBrisorgueil
merged 4 commits into
master
from
fix/3709-dangling-org-cascade-and-signin-guard
May 28, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2207602
fix(users): repair co-member currentOrganization on sole-owner deleti…
PierreBrisorgueil 6bce74b
fix(organizations): harden autoSetCurrentOrganization to skip null-po…
PierreBrisorgueil 7c02787
fix(auth): add regression guard for data-integrity anomaly on signin …
PierreBrisorgueil 19f69c6
fix(users): guard null org in deletion-cascade nextOrg (#3709)
PierreBrisorgueil File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
modules/organizations/tests/organizations.crud.dangling-org.unit.tests.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| /** | ||
| * Unit tests — autoSetCurrentOrganization must not crash when membership.organizationId | ||
| * is null after populate (deleted org, dangling ref). Issue #3709. | ||
| */ | ||
| import { jest, describe, test, expect } from '@jest/globals'; | ||
|
|
||
| const mockMembershipFindOne = jest.fn(); | ||
| const mockMembershipList = jest.fn(); | ||
| const mockUpdateById = jest.fn(); | ||
| const mockOrgRemove = jest.fn(); | ||
|
|
||
| jest.unstable_mockModule('../../../lib/services/logger.js', () => ({ | ||
| default: { error: jest.fn(), warn: jest.fn(), info: jest.fn() }, | ||
| })); | ||
|
|
||
| jest.unstable_mockModule('../repositories/organizations.repository.js', () => ({ | ||
| default: { | ||
| create: jest.fn(), | ||
| findOne: jest.fn().mockResolvedValue(null), | ||
| remove: mockOrgRemove, | ||
| list: jest.fn().mockResolvedValue([]), | ||
| update: jest.fn(), | ||
| get: jest.fn(), | ||
| exists: jest.fn().mockResolvedValue(false), | ||
| updateById: jest.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| jest.unstable_mockModule('../repositories/organizations.membership.repository.js', () => ({ | ||
| default: { | ||
| create: jest.fn(), | ||
| deleteMany: jest.fn(), | ||
| list: mockMembershipList, | ||
| findOne: mockMembershipFindOne, | ||
| update: jest.fn(), | ||
| remove: jest.fn(), | ||
| count: jest.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| jest.unstable_mockModule('../../users/services/users.service.js', () => ({ | ||
| default: { | ||
| updateById: mockUpdateById, | ||
| findWithFilter: jest.fn().mockResolvedValue([]), | ||
| getBrut: jest.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| jest.unstable_mockModule('../../../lib/helpers/emailVerification.js', () => ({ | ||
| assertEmailVerified: jest.fn(), | ||
| })); | ||
|
|
||
| jest.unstable_mockModule('../../../config/index.js', () => ({ | ||
| default: { organizations: { enabled: true } }, | ||
| })); | ||
|
|
||
| const { default: OrgCrudService } = await import('../services/organizations.crud.service.js'); | ||
|
|
||
| describe('autoSetCurrentOrganization — dangling org ref (#3709):', () => { | ||
| const user = { _id: 'uid1', id: 'uid1', currentOrganization: null }; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| mockUpdateById.mockResolvedValue({}); | ||
| }); | ||
|
|
||
| test('should not throw when membership.organizationId is null after populate', async () => { | ||
| // Simulate: user has an active membership but the org is deleted (populate yields null) | ||
| mockMembershipList.mockResolvedValue([ | ||
| { _id: 'm1', organizationId: null, status: 'active' }, // null = deleted org | ||
| ]); | ||
|
|
||
| // Must not throw; must set currentOrganization to null (no live org) | ||
| const result = await OrgCrudService.autoSetCurrentOrganization({ ...user }); | ||
| expect(result.currentOrganization).toBeNull(); | ||
| expect(mockUpdateById).toHaveBeenCalledWith('uid1', { currentOrganization: null }); | ||
| }); | ||
|
|
||
| test('should skip null-org memberships and pick first live org when mixed', async () => { | ||
| // Two memberships: first has deleted org (null populate), second has live org | ||
| mockMembershipList.mockResolvedValue([ | ||
| { _id: 'm1', organizationId: null, status: 'active' }, // deleted org | ||
| { _id: 'm2', organizationId: { _id: 'org2' }, status: 'active' }, // live org | ||
| ]); | ||
|
|
||
| const result = await OrgCrudService.autoSetCurrentOrganization({ ...user }); | ||
| expect(result.currentOrganization).toBe('org2'); | ||
| expect(mockUpdateById).toHaveBeenCalledWith('uid1', { currentOrganization: 'org2' }); | ||
| }); | ||
|
|
||
| test('should return user unchanged when currentOrganization is set and membership is live with a live org', async () => { | ||
| const userWithOrg = { _id: 'uid1', id: 'uid1', currentOrganization: { _id: 'org1' } }; | ||
| mockMembershipFindOne.mockResolvedValue({ _id: 'm1', organizationId: { _id: 'org1' } }); | ||
|
|
||
| const result = await OrgCrudService.autoSetCurrentOrganization(userWithOrg); | ||
| // Early return — no updateById called | ||
| expect(mockUpdateById).not.toHaveBeenCalled(); | ||
| expect(result.currentOrganization).toEqual({ _id: 'org1' }); | ||
| }); | ||
|
|
||
| test('should fall through and clear currentOrganization when membership exists but org is null-populated', async () => { | ||
| // Membership still exists (findOne returns it) but org is deleted (organizationId = null) | ||
| const userWithOrg = { _id: 'uid1', id: 'uid1', currentOrganization: { _id: 'org1' } }; | ||
| // findOne called in early branch — membership exists (stillActive truthy) but org deleted | ||
| mockMembershipFindOne.mockResolvedValue({ _id: 'm1', organizationId: null }); | ||
| // list called in fallback branch — also returns the same dangling membership | ||
| mockMembershipList.mockResolvedValue([ | ||
| { _id: 'm1', organizationId: null, status: 'active' }, | ||
| ]); | ||
|
|
||
| const result = await OrgCrudService.autoSetCurrentOrganization(userWithOrg); | ||
| expect(result.currentOrganization).toBeNull(); | ||
| expect(mockUpdateById).toHaveBeenCalledWith('uid1', { currentOrganization: null }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| /** | ||
| * E2E test: user deletion cascades org cleanup so co-members can still sign in. | ||
| * Repro from issue #3709: User A (sole owner) deleted → Org X removed. | ||
| * User B (active member of Org X, currentOrganization=X) must be able to sign in | ||
| * without 500, with currentOrganization cleared to null. | ||
| */ | ||
| import request from 'supertest'; | ||
| import path from 'path'; | ||
| import { bootstrap } from '../../../lib/app.js'; | ||
| import mongooseService from '../../../lib/services/mongoose.js'; | ||
| import config from '../../../config/index.js'; | ||
|
|
||
| describe('users.service.remove cascade (#3709):', () => { | ||
| let UserService; | ||
| let OrganizationsRepository; | ||
| let MembershipRepository; | ||
| let agent; | ||
|
|
||
| const originalOrganizations = { ...config.organizations }; | ||
|
|
||
| beforeAll(async () => { | ||
| try { | ||
| const init = await bootstrap(); | ||
| UserService = (await import(path.resolve('./modules/users/services/users.service.js'))).default; | ||
| OrganizationsRepository = (await import(path.resolve('./modules/organizations/repositories/organizations.repository.js'))).default; | ||
| MembershipRepository = (await import(path.resolve('./modules/organizations/repositories/organizations.membership.repository.js'))).default; | ||
| agent = request.agent(init.app); | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| config.organizations = { ...originalOrganizations }; | ||
| try { | ||
| await mongooseService.disconnect(); | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
| }); | ||
|
|
||
| describe('User B can sign in after User A (sole owner) is deleted', () => { | ||
| let userA; | ||
| let userB; | ||
| let orgX; | ||
| let agentA; | ||
| let agentB; | ||
|
|
||
| beforeAll(async () => { | ||
| config.organizations = { enabled: true, autoCreate: true, domainMatching: false }; | ||
| agentA = request.agent(agent.app); | ||
| agentB = request.agent(agent.app); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| // Best-effort cleanup | ||
| try { | ||
| if (userB) await UserService.remove(userB); | ||
| } catch (_) { /* cleanup */ } | ||
| try { | ||
| if (orgX) { | ||
| await MembershipRepository.deleteMany({ organizationId: orgX._id }); | ||
| await OrganizationsRepository.deleteMany({ _id: orgX._id }); | ||
| } | ||
| } catch (_) { /* cleanup */ } | ||
| }); | ||
|
|
||
| test('should not 500 on signin when currentOrganization points to a deleted org (issue #3709 repro)', async () => { | ||
| // Step 1: User A signs up — auto-creates Org X | ||
| try { | ||
| const resA = await agentA | ||
| .post('/api/auth/signup') | ||
| .send({ | ||
| firstName: 'CascadeA', | ||
| lastName: 'User', | ||
| email: 'cascade-a-3709@test.com', | ||
| password: 'W@os.jsI$Aw3$0m3', | ||
| provider: 'local', | ||
| }) | ||
| .expect(200); | ||
| userA = resA.body.user; | ||
| orgX = resA.body.organization; | ||
| expect(orgX).toBeDefined(); | ||
| expect(orgX).not.toBeNull(); | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
|
|
||
| // Step 2: User B signs up separately | ||
| try { | ||
| const resB = await agentB | ||
| .post('/api/auth/signup') | ||
| .send({ | ||
| firstName: 'CascadeB', | ||
| lastName: 'User', | ||
| email: 'cascade-b-3709@test.com', | ||
| password: 'W@os.jsI$Aw3$0m3', | ||
| provider: 'local', | ||
| }) | ||
| .expect(200); | ||
| userB = resB.body.user; | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
|
|
||
| // Step 3: Directly create an ACTIVE membership for User B on Org X + set currentOrganization | ||
| // (bypassing invite flow for test speed) | ||
| try { | ||
| const MembershipService = (await import(path.resolve('./modules/organizations/services/organizations.membership.service.js'))).default; | ||
| await MembershipService.create({ | ||
| userId: userB._id || userB.id, | ||
| organizationId: orgX._id, | ||
| role: 'member', | ||
| status: 'active', | ||
| }); | ||
| // Set User B's currentOrganization to Org X directly | ||
| await UserService.updateById(userB._id || userB.id, { currentOrganization: orgX._id }); | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
|
|
||
| // Step 4: Delete User A (sole owner of Org X) — this should cascade-delete Org X + all memberships | ||
| try { | ||
| const brutUserA = await UserService.getBrut({ id: userA.id }); | ||
| await UserService.remove(brutUserA); | ||
| userA = null; // Mark as cleaned | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
|
|
||
| // Step 5: Verify Org X no longer exists | ||
| try { | ||
| const org = await OrganizationsRepository.get(orgX._id); | ||
| expect(org).toBeNull(); | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
|
|
||
| // Step 6: Verify User B's currentOrganization has been cleared (not left dangling) | ||
| try { | ||
| const brutUserB = await UserService.getBrut({ id: userB.id }); | ||
| // currentOrganization must be null or undefined — not the deleted org ID | ||
| const currentOrgId = brutUserB.currentOrganization?._id || brutUserB.currentOrganization; | ||
| expect(currentOrgId == null || String(currentOrgId) !== String(orgX._id)).toBe(true); | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
|
|
||
| // Step 7: User B signs in — must NOT 500 (was: "Cannot read properties of null (reading '_id')") | ||
| try { | ||
| const signinRes = await agentB | ||
| .post('/api/auth/signin') | ||
| .send({ email: 'cascade-b-3709@test.com', password: 'W@os.jsI$Aw3$0m3' }) | ||
| .expect(200); // Must be 200, not 500 | ||
|
|
||
| expect(signinRes.body.type).toBe('success'); | ||
| // currentOrganization must NOT be the deleted Org X (could be null or User B's own org) | ||
| const signedInOrgId = signinRes.body.user.currentOrganization?._id || signinRes.body.user.currentOrganization; | ||
| expect(signedInOrgId == null || String(signedInOrgId) !== String(orgX._id)).toBe(true); | ||
| } catch (err) { | ||
| console.log(err); | ||
| expect(err).toBeFalsy(); | ||
| } | ||
| }); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.