Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 38 additions & 9 deletions modules/auth/controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,31 @@ const token = async (req, res) => {
.json({ user, tokenExpiresIn: Date.now() + config.jwt.expiresIn * 1000, abilities, pendingRequests });
};

/**
* Known OAuth providers — used to validate the `provider` argument and `key` argument
* before constructing dynamic query paths, preventing prototype-pollution-style injections.
*/
const ALLOWED_PROVIDERS = new Set(['google', 'apple']);
const ALLOWED_PROVIDER_KEYS = new Set(['sub', 'id', 'email']);

/**
* @desc Check whether `:strategy` (from `req.params.strategy`) is both an allowlisted
* provider AND actually registered with passport at boot time. A provider in
* ALLOWED_PROVIDERS is only registered (modules/auth/strategies/local/{provider}.js)
* when its config carries valid credentials — otherwise passport never sees it.
* Guards the `/api/auth/:strategy` and `/api/auth/:strategy/callback` routes so an
* unknown or disabled strategy name is rejected with a clean 404 before it can reach
* passport.authenticate(), which otherwise throws synchronously ("Unknown
* authentication strategy") for an unregistered name.
* `passport._strategy` is documented `@api private` in passport's own source, but it
* is the single source of truth for "is this strategy registered" — asking config
* directly would mean duplicating each provider's own credential-presence check here
* and risking drift from modules/auth/strategies/local/*.js over time.
* @param {string} strategy - strategy name from req.params.strategy
* @returns {boolean} true when strategy is both allowlisted and registered with passport
*/
const isEnabledOAuthProvider = (strategy) => ALLOWED_PROVIDERS.has(strategy) && Boolean(passport._strategy(strategy));

Comment thread
coderabbitai[bot] marked this conversation as resolved.
/**
* @desc Endpoint for oautCall
* @param {Object} req - Express request object
Expand All @@ -447,16 +472,13 @@ const token = async (req, res) => {
*/
const oauthCall = (req, res, next) => {
const strategy = req.params.strategy;
passport.authenticate(strategy)(req, res, next);
if (!isEnabledOAuthProvider(strategy)) {
return next(new AppError('oAuth, unsupported provider', { status: 404, code: 'OAUTH_PROVIDER_NOT_FOUND' }));
}
// session: false — stateless JWT stack, no express-session middleware is mounted.
return passport.authenticate(strategy, { session: false })(req, res, next);
};

/**
* Known OAuth providers — used to validate the `provider` argument and `key` argument
* before constructing dynamic query paths, preventing prototype-pollution-style injections.
*/
const ALLOWED_PROVIDERS = new Set(['google', 'apple']);
const ALLOWED_PROVIDER_KEYS = new Set(['sub', 'id', 'email']);

/**
* @desc Resolve or create a user from an OAuth profile. Lookup order:
* 1. Primary identity (provider + providerData[key])
Expand Down Expand Up @@ -659,12 +681,19 @@ const oauthErrorRedirect = (res, err, fallbackTitle) => {
*/
const oauthCallback = async (req, res, next) => {
const strategy = req.params.strategy;
if (!isEnabledOAuthProvider(strategy)) {
return next(new AppError('oAuth, unsupported provider', { status: 404, code: 'OAUTH_PROVIDER_NOT_FOUND' }));
}
// The identity is always derived server-side from the provider's response via
// passport.authenticate(). The part that was previously unsafe was trusting a
// client-asserted identity from the request body (email, key, value) with no
// provider-token verification — a caller who knows a victim's identifier could
// have minted that victim's session. That branch is now removed entirely.
passport.authenticate(strategy, (err, user) => {
// No `{ session: false }` here: passport.authenticate()'s callback form (a
// function as the 2nd/3rd arg) never calls req.logIn() itself — session
// establishment is entirely the caller's responsibility below (JWT + cookie,
// no express-session) — so the `session` option has nothing to act on.
return passport.authenticate(strategy, (err, user) => {
if (err) {
logger.error(
{ err: { message: err?.message, code: err?.code, stack: err?.stack }, strategy },
Expand Down
45 changes: 45 additions & 0 deletions modules/auth/tests/auth.integration.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,15 @@ describe('Auth integration tests:', () => {
}
});

// Safety net alongside each test's own manual mockRestore(): jest.config.js
// only sets `clearMocks` (resets calls, not implementations), so a spy left
// dangling by a failing assertion earlier in a test would otherwise leak its
// stubbed truthy passport._strategy()/mockRejectedValueOnce() into later
// tests in this block.
afterEach(() => {
jest.restoreAllMocks();
});

test('should create user with default provider when none is specified', async () => {
const result = await UserService.create({
firstName: 'No',
Expand Down Expand Up @@ -625,6 +634,18 @@ describe('Auth integration tests:', () => {
// identity payload. A request that claims to be a known account by email
// (no server-side provider-token verification) must be rejected, not
// turned into a victim session. The callback always delegates to passport.
//
// Simulate 'google' being registered with passport (bypasses the
// isEnabledOAuthProvider guard, covered separately for oauthCall/oauthCallback)
// and stub passport.authenticate the same way a real OAuth2 strategy would
// behave for this request: there is no valid provider code, so authentication
// fails regardless of what the attacker put in the body. Without this stub the
// request would 404 at the guard before ever reaching the identity-trust logic
// this test protects.
const strategySpy = jest.spyOn(passport, '_strategy').mockReturnValue({});
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(null, false),
);
const victimEmail = 'oauthcb-victim@test.com';
let victim;
try {
Expand All @@ -649,13 +670,26 @@ describe('Auth integration tests:', () => {
const tokenCookie = result.headers['set-cookie']?.find((c) => c.startsWith('TOKEN='));
expect(tokenCookie).toBeUndefined();
expect(result.status).not.toBe(200);
// Confirm the request reached oauthCallback's post-authenticate
// identity-trust logic (not the 404 provider-registration guard) —
// the redirect must carry the "no user" error, never the guard's code.
expect(result.status).toBe(302);
expect(result.headers.location).toContain('/token');
expect(result.headers.location).not.toContain('OAUTH_PROVIDER_NOT_FOUND');
} finally {
authenticateSpy.mockRestore();
strategySpy.mockRestore();
try { if (victim) await UserService.remove(victim); } catch (_) { /* cleanup */ }
}
});

test('should set tokenCookieOptions and redirect on classic web oAuth success', async () => {
const mockUserId = 'mock-oauth-user-id-123';
// Simulate 'google' being registered with passport (isEnabledOAuthProvider's
// guard check) — this test targets oauthCallback's post-authenticate
// handling, not the provider-registration guard itself (covered separately
// for oauthCall).
const strategySpy = jest.spyOn(passport, '_strategy').mockReturnValue({});
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(null, { id: mockUserId }),
);
Expand All @@ -675,9 +709,11 @@ describe('Auth integration tests:', () => {
expect(redirectCalls[0]).toMatchObject({ code: 302 });
expect(redirectCalls[0].url).toMatch(/\/token$/);
authenticateSpy.mockRestore();
strategySpy.mockRestore();
});

test('should handle GET callback when req.body is undefined (Express 5)', async () => {
const strategySpy = jest.spyOn(passport, '_strategy').mockReturnValue({});
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(null, { id: 'mock-get-cb-user' }),
);
Expand All @@ -694,11 +730,13 @@ describe('Auth integration tests:', () => {
expect(cookies.TOKEN).toBeDefined();
expect(redirectCalls[0]).toMatchObject({ code: 302 });
authenticateSpy.mockRestore();
strategySpy.mockRestore();
});

test('should log and redirect with canonical error envelope when classic web oAuth errors out', async () => {
const oauthErr = new Error('token exchange failed');
oauthErr.code = 'OAUTH_TOKEN_EXCHANGE';
const strategySpy = jest.spyOn(passport, '_strategy').mockReturnValue({});
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(oauthErr, null),
);
Expand Down Expand Up @@ -743,6 +781,7 @@ describe('Auth integration tests:', () => {

loggerSpy.mockRestore();
authenticateSpy.mockRestore();
strategySpy.mockRestore();
});

test('should redirect with canonical envelope preserving AppError details.message', async () => {
Expand All @@ -751,6 +790,7 @@ describe('Auth integration tests:', () => {
code: 'VALIDATION_ERROR',
details: { message: 'Registration is currently deactivated' },
});
const strategySpy = jest.spyOn(passport, '_strategy').mockReturnValue({});
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(oauthErr, null),
);
Expand Down Expand Up @@ -781,9 +821,11 @@ describe('Auth integration tests:', () => {

loggerSpy.mockRestore();
authenticateSpy.mockRestore();
strategySpy.mockRestore();
});

test('should fall back to OAUTH_ERROR code for plain Error without code', async () => {
const strategySpy = jest.spyOn(passport, '_strategy').mockReturnValue({});
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(new Error('boom'), null),
);
Expand All @@ -805,9 +847,11 @@ describe('Auth integration tests:', () => {

loggerSpy.mockRestore();
authenticateSpy.mockRestore();
strategySpy.mockRestore();
});

test('should log and redirect with canonical envelope when no user is returned by passport', async () => {
const strategySpy = jest.spyOn(passport, '_strategy').mockReturnValue({});
const authenticateSpy = jest.spyOn(passport, 'authenticate').mockImplementationOnce(
(strategy, callback) => () => callback(null, null),
);
Expand Down Expand Up @@ -851,6 +895,7 @@ describe('Auth integration tests:', () => {

loggerSpy.mockRestore();
authenticateSpy.mockRestore();
strategySpy.mockRestore();
});

test('should find an existing OAuth user via checkOAuthUserProfile', async () => {
Expand Down
Loading
Loading