LibreChat/api/server/routes/auth.cloudfront.test.js
Marco Beretta 92432e95d5
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
Sync Locize Translations & Create Translation PR / Sync Translation Keys with Locize (push) Waiting to run
Sync Locize Translations & Create Translation PR / Create Translation PR on Version Published (push) Blocked by required conditions
🔐 feat: Enforce Required Two-Factor Authentication (#14731)
* feat: enforce required two-factor authentication

Require local and LDAP accounts to enroll in TOTP before they can use the
app when ENFORCE_TWO_FACTOR_AUTHENTICATION is set. Sign-in, refresh, bearer
verification, optional share auth and image authorization all route an
unenrolled account into a staged setup flow, and every bearer credential
minted before enrollment or a password reset is retired.

Password reset retirement uses the existing credentialsChangedAt stamp, and
commitPasswordReset clears any staged enrollment in the same write. Passkey
sign-in follows the same enrollment gate as password sign-in.

* test: cover passkey sign-in handing off to required enrollment

* refactor: keep Mongoose user types out of two-factor auth contracts

* fix: withdraw a minted session when its retirement recheck fails

* fix: hold Agent API keys and the reset CLI to the required two-factor policy

* fix: adopt a setup token handed off after the setup screen mounted

* fix: move every tab that receives an enrollment hand-off into setup

* fix: read the enrollment gate's retirement cutoff in system scope

* fix: clear minted session cookies before the fallible session deletion

* fix: adopt a setup token persisted before the setup screen subscribed
2026-10-01 23:39:51 +02:00

184 lines
6.2 KiB
JavaScript

const express = require('express');
const request = require('supertest');
const mockForceRefreshCloudFrontAuthCookies = jest.fn();
jest.mock('@librechat/api', () => ({
limiterCache: jest.fn(),
createTwoFactorManagementLimiter: jest.fn(() => (req, res, next) => next()),
createSetBalanceConfig: jest.fn(() => (req, res, next) => next()),
requireTwoFactorSetupToken: jest.fn((req, res, next) => next()),
requireTwoFactorSetupAcknowledgementToken: jest.fn((req, res, next) => next()),
requireTwoFactorSetupFinalizationToken: jest.fn((req, res, next) => next()),
forceRefreshCloudFrontAuthCookies: (...args) => mockForceRefreshCloudFrontAuthCookies(...args),
blockTwoFactorDisableWhenRequired: jest.fn((req, res, next) => next()),
}));
jest.mock('~/server/controllers/AuthController', () => ({
refreshController: jest.fn((req, res) => res.status(200).end()),
registrationController: jest.fn((req, res) => res.status(200).end()),
resetPasswordController: jest.fn((req, res) => res.status(200).end()),
resetPasswordRequestController: jest.fn((req, res) => res.status(200).end()),
graphTokenController: jest.fn((req, res) => res.status(200).end()),
}));
jest.mock('~/server/controllers/TwoFactorController', () => ({
enable2FA: jest.fn((req, res) => res.status(200).end()),
verify2FA: jest.fn((req, res) => res.status(200).end()),
confirm2FA: jest.fn((req, res) => res.status(200).end()),
disable2FA: jest.fn((req, res) => res.status(200).end()),
regenerateBackupCodes: jest.fn((req, res) => res.status(200).end()),
}));
jest.mock('~/server/controllers/auth/TwoFactorAuthController', () => ({
verify2FAWithTempToken: jest.fn((req, res) => res.status(200).end()),
confirm2FASetupWithTempToken: jest.fn((req, res) => res.status(200).end()),
acknowledge2FASetup: jest.fn((req, res) => res.status(200).end()),
finalize2FASetup: jest.fn((req, res) => res.status(200).end()),
}));
jest.mock('~/server/controllers/auth/PasskeyController', () => ({
listPasskeys: jest.fn((req, res) => res.status(204).end()),
updatePasskey: jest.fn((req, res) => res.status(204).end()),
removePasskey: jest.fn((req, res) => res.status(204).end()),
authenticatePasskey: jest.fn((req, res, next) => next()),
loginPasskeyOptions: jest.fn((req, res) => res.status(204).end()),
registerPasskeyOptions: jest.fn((req, res) => res.status(204).end()),
registerPasskeyVerify: jest.fn((req, res) => res.status(204).end()),
}));
jest.mock('~/server/controllers/auth/LogoutController', () => ({
logoutController: jest.fn((req, res) => res.status(200).end()),
}));
jest.mock('~/server/controllers/auth/LoginController', () => ({
loginController: jest.fn((req, res) => res.status(200).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,
passkeyLimiter: pass,
passkeyStepUpLimiter: pass,
setTwoFactorTempUser: pass,
setTwoFactorAcknowledgementTempUser: pass,
setTwoFactorFinalizationTempUser: pass,
twoFactorTempLimiter: pass,
twoFactorSetupLimiter: pass,
checkBan: pass,
blockRetiredSetupToken: pass,
validateEmailLogin: pass,
requireLocalAuth: pass,
requireLdapAuth: pass,
registerLimiter: pass,
checkInviteUser: pass,
validateRegistration: pass,
resetPasswordLimiter: pass,
resetPasswordSubmissionLimiter: pass,
validatePasswordReset: pass,
requireJwtAuth: jest.fn((req, res, next) => {
if (req.headers.authorization !== 'Bearer ok') {
return res.status(401).json({ message: 'Unauthorized' });
}
req.user = { _id: 'user123', tenantId: 'tenantA' };
if (req.headers['x-cloudfront-warmed'] === 'true') {
req.cloudFrontAuthCookieRefreshResult = {
enabled: true,
attempted: true,
refreshed: true,
expiresInSec: 1800,
refreshAfterSec: 1500,
};
}
return next();
}),
};
});
const authRouter = require('./auth');
describe('POST /api/auth/cloudfront/refresh', () => {
let app;
beforeEach(() => {
jest.clearAllMocks();
app = express();
app.use(express.json());
app.use('/api/auth', authRouter);
});
it('requires authentication', async () => {
await request(app).post('/api/auth/cloudfront/refresh').expect(401);
expect(mockForceRefreshCloudFrontAuthCookies).not.toHaveBeenCalled();
});
it('returns 404 when CloudFront cookie mode is disabled', async () => {
mockForceRefreshCloudFrontAuthCookies.mockReturnValue({
enabled: false,
attempted: false,
refreshed: false,
reason: 'cloudfront_disabled',
});
const response = await request(app)
.post('/api/auth/cloudfront/refresh')
.set('Authorization', 'Bearer ok')
.expect(404);
expect(response.status).toBe(404);
});
it('returns cookie refresh timing when CloudFront cookies are refreshed', async () => {
mockForceRefreshCloudFrontAuthCookies.mockReturnValue({
enabled: true,
attempted: true,
refreshed: true,
expiresInSec: 1800,
refreshAfterSec: 1500,
});
const response = await request(app)
.post('/api/auth/cloudfront/refresh')
.set('Authorization', 'Bearer ok')
.expect(200);
expect(response.body).toEqual({
ok: true,
expiresInSec: 1800,
refreshAfterSec: 1500,
});
expect(mockForceRefreshCloudFrontAuthCookies).toHaveBeenCalledWith(
expect.objectContaining({ user: { _id: 'user123', tenantId: 'tenantA' } }),
expect.any(Object),
{ _id: 'user123', tenantId: 'tenantA' },
);
});
it('reuses the auth middleware refresh result instead of minting cookies twice', async () => {
const response = await request(app)
.post('/api/auth/cloudfront/refresh')
.set('Authorization', 'Bearer ok')
.set('x-cloudfront-warmed', 'true')
.expect(200);
expect(response.body).toEqual({
ok: true,
expiresInSec: 1800,
refreshAfterSec: 1500,
});
expect(mockForceRefreshCloudFrontAuthCookies).not.toHaveBeenCalled();
});
});