LibreChat/api/server/routes/auth.2fa-ratelimit.test.js
Danny Avila 9cf33cc8be
🧿 fix: Bind Login Flows to the Browser That Started Them (#15880)
* 🧿 fix: Bind Login Flows to the Browser That Started Them

Social OAuth logins (Google, Facebook, GitHub, Discord, Apple) now store a random state in an HttpOnly cookie scoped to the callback path and only exchange the returned code when the callback carries that state. Apple's form_post callback uses a SameSite=None cookie, and passport-apple's own fixed state no longer bypasses the store.

Local login, temp-token 2FA verification and admin local login reject requests a browser sent from another origin (Sec-Fetch-Site, falling back to Origin vs Host), trusting DOMAIN_CLIENT and DOMAIN_SERVER. Requests without browser fetch metadata, such as server-side callers, pass unchanged.

The sessionless OAuth callbacks drop failureMessage, which wrote to req.session and turned any rejected callback into a 500.

* 🧿 fix: Configure Login State Cookies and Localize Origin Rejections

- OAuth state cookies take secureCookie and maxAgeMs from the caller; registration.oauthStateTtlMs in librechat.yaml sets the lifetime (default 10 minutes).
- Secure deployments use a __Host- cookie at Path=/ so a sibling subdomain cannot plant a state.
- The cookie keeps up to three pending states, so logins started in separate tabs all complete, and an unmatched callback no longer discards them.
- passport-apple's preset state is dropped by deferStateToStore in packages/api.
- The Origin fallback compares scheme and host against the request itself.
- The same-origin rejection carries ErrorTypes.AUTH_CROSS_ORIGIN, which the login and 2FA screens show as a localized message.

* 🧿 refactor: Sign Login State Against a Per-Browser Binding

- The OAuth state store keeps a random per-browser binding in a __Host- cookie (reused across flows) and signs each state as issuedAt.nonce.HMAC(JWT_SECRET, provider, binding, issuedAt, nonce). Nothing is stored per flow, so any number of tabs complete, each state expires on its own clock, and concurrent starts no longer overwrite each other.
- The experimental server entrypoint passes its app config to configureSocialLogins.
- The same-origin guard also trusts an explicitly configured ADMIN_PANEL_URL.

* 🧿 fix: Keep Separate Bindings for Racing First Logins

A browser without a login-state binding now gets one under a cookie name with a random suffix, so two tabs that start their first login at once each keep their own binding. Later starts reuse an existing binding, and a callback is accepted when its state was signed for any binding the browser presents.

* 🧿 fix: Sanitize Request-Derived Values in the Cross-Site Rejection Log

The same-origin guard logged the request Origin and path verbatim. A non-browser client fully controls the Origin header, and the console transport uses a printf format that does not escape control characters, so a crafted value could forge log lines. Strip ASCII control characters (CR, LF, NUL and the rest) before logging, matching the pattern apiNotFound already uses.
2026-09-13 11:47:29 -04:00

123 lines
4.6 KiB
JavaScript

const express = require('express');
const request = require('supertest');
const mockSetTwoFactorTempUser = jest.fn((req, res, next) => next());
const mockTwoFactorTempLimiter = jest.fn((req, res, next) => next());
const mockCheckBan = jest.fn((req, res, next) => next());
const mockVerify2FAWithTempToken = jest.fn((req, res) => res.status(204).end());
jest.mock('@librechat/api', () => ({
createSetBalanceConfig: jest.fn(() => (req, res, next) => next()),
forceRefreshCloudFrontAuthCookies: jest.fn(),
}));
jest.mock('~/server/controllers/AuthController', () => ({
refreshController: jest.fn((req, res) => res.status(204).end()),
registrationController: jest.fn((req, res) => res.status(204).end()),
resetPasswordController: jest.fn((req, res) => res.status(204).end()),
resetPasswordRequestController: jest.fn((req, res) => res.status(204).end()),
graphTokenController: jest.fn((req, res) => res.status(204).end()),
}));
jest.mock('~/server/controllers/TwoFactorController', () => ({
enable2FA: jest.fn((req, res) => res.status(204).end()),
verify2FA: jest.fn((req, res) => res.status(204).end()),
confirm2FA: jest.fn((req, res) => res.status(204).end()),
disable2FA: jest.fn((req, res) => res.status(204).end()),
regenerateBackupCodes: jest.fn((req, res) => res.status(204).end()),
}));
jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({
verify2FAWithTempToken: (...args) => mockVerify2FAWithTempToken(...args),
}));
jest.mock('~/server/controllers/auth/LogoutController', () => ({
logoutController: jest.fn((req, res) => res.status(204).end()),
}));
jest.mock('~/server/controllers/auth/LoginController', () => ({
loginController: jest.fn((req, res) => res.status(204).end()),
}));
jest.mock('~/models', () => ({
findBalanceByUser: jest.fn(),
upsertBalanceFields: jest.fn(),
}));
jest.mock('~/server/services/Config', () => ({
getAppConfig: jest.fn(),
}));
jest.mock('~/server/middleware', () => {
const pass = (req, res, next) => next();
return {
logHeaders: pass,
requireSameOrigin: pass,
loginLimiter: pass,
setTwoFactorTempUser: (...args) => mockSetTwoFactorTempUser(...args),
twoFactorTempLimiter: (...args) => mockTwoFactorTempLimiter(...args),
checkBan: (...args) => mockCheckBan(...args),
validateEmailLogin: pass,
requireLocalAuth: pass,
requireLdapAuth: pass,
registerLimiter: pass,
checkInviteUser: pass,
validateRegistration: pass,
resetPasswordLimiter: pass,
resetPasswordSubmissionLimiter: pass,
validatePasswordReset: pass,
requireJwtAuth: pass,
};
});
const authRouter = require('./auth');
describe('POST /api/auth/2fa/verify-temp rate limiting', () => {
let app;
beforeEach(() => {
jest.clearAllMocks();
mockSetTwoFactorTempUser.mockImplementation((req, res, next) => next());
mockTwoFactorTempLimiter.mockImplementation((req, res, next) => next());
mockCheckBan.mockImplementation((req, res, next) => next());
mockVerify2FAWithTempToken.mockImplementation((req, res) => res.status(204).end());
app = express();
app.use(express.json());
app.use('/api/auth', authRouter);
});
it('sets the temp user before limiting, checking bans, and verifying temp 2FA tokens', async () => {
await request(app).post('/api/auth/2fa/verify-temp').send({ token: '123456' }).expect(204);
expect(mockSetTwoFactorTempUser).toHaveBeenCalledTimes(1);
expect(mockTwoFactorTempLimiter).toHaveBeenCalledTimes(1);
expect(mockCheckBan).toHaveBeenCalledTimes(1);
expect(mockVerify2FAWithTempToken).toHaveBeenCalledTimes(1);
expect(mockSetTwoFactorTempUser.mock.invocationCallOrder[0]).toBeLessThan(
mockTwoFactorTempLimiter.mock.invocationCallOrder[0],
);
expect(mockTwoFactorTempLimiter.mock.invocationCallOrder[0]).toBeLessThan(
mockCheckBan.mock.invocationCallOrder[0],
);
expect(mockCheckBan.mock.invocationCallOrder[0]).toBeLessThan(
mockVerify2FAWithTempToken.mock.invocationCallOrder[0],
);
});
it('does not verify the temp 2FA token after the limiter rejects the request', async () => {
mockTwoFactorTempLimiter.mockImplementation((req, res) =>
res.status(429).json({ message: 'Too many verification attempts' }),
);
const response = await request(app)
.post('/api/auth/2fa/verify-temp')
.send({ token: '123456' })
.expect(429);
expect(response.body).toEqual({ message: 'Too many verification attempts' });
expect(mockSetTwoFactorTempUser).toHaveBeenCalledTimes(1);
expect(mockCheckBan).not.toHaveBeenCalled();
expect(mockVerify2FAWithTempToken).not.toHaveBeenCalled();
});
});