LibreChat/api/server/services/AuthService.spec.js
Danny Avila 77712c825f
Some checks are pending
Docker Dev Branch Images Build / build (Dockerfile, lc-dev, node) (push) Waiting to run
Docker Dev Branch Images Build / build (Dockerfile.multi, lc-dev-api, api-build) (push) Waiting to run
🏢 feat: Tenant-Scoped App Config in Auth Login Flows (#12434)
* feat: add resolveAppConfigForUser utility for tenant-scoped auth config

TypeScript utility in packages/api that wraps getAppConfig in
tenantStorage.run() when the user has a tenantId, falling back to
baseOnly for new users or non-tenant deployments. Uses DI pattern
(getAppConfig passed as parameter) for testability.

Auth flows apply role-level overrides only (userId not passed)
because user/group principal resolution is deferred to post-auth.

* feat: tenant-scoped app config in auth login flows

All auth strategies (LDAP, SAML, OpenID, social login) now use a
two-phase domain check consistent with requestPasswordReset:

1. Fast-fail with base config (memory-cached, zero DB queries)
2. DB user lookup
3. Tenant-scoped re-check via resolveAppConfigForUser (only when
   user has a tenantId; otherwise reuse base config)

This preserves the original fast-fail protection against globally
blocked domains while enabling tenant-specific config overrides.

OpenID error ordering preserved: AUTH_FAILED checked before domain
re-check so users with wrong providers get the correct error type.

registerUser unchanged (baseOnly, no user identity yet).

* test: add tenant-scoped config tests for auth strategies

Add resolveAppConfig.spec.ts in packages/api with 8 tests:
- baseOnly fallback for null/undefined/no-tenant users
- tenant-scoped config with role and tenantId
- ALS context propagation verified inside getAppConfig callback
- undefined role with tenantId edge case

Update strategy and AuthService tests to mock resolveAppConfigForUser
via @librechat/api. Tests verify two-phase domain check behavior:
fast-fail before DB, tenant re-check after. Non-tenant users reuse
base config without calling resolveAppConfigForUser.

* refactor: skip redundant domain re-check for non-tenant users

Guard the second isEmailDomainAllowed call with appConfig !== baseConfig
in SAML, OpenID, and social strategies. For non-tenant users the tenant
config is the same base config object, so the second check is a no-op.

Narrow eslint-disable in resolveAppConfig.spec.ts to the specific
require line instead of blanket file-level suppression.

* fix: address review findings — consistency, tests, and ordering

- Consolidate duplicate require('@librechat/api') in AuthService.js
- Add two-phase domain check to LDAP (base fast-fail before findUser),
  making all strategies consistent with PR description
- Add appConfig !== baseConfig guard to requestPasswordReset second
  domain check, consistent with SAML/OpenID/social strategies
- Move SAML provider check before tenant config resolution to avoid
  unnecessary resolveAppConfigForUser call for wrong-provider users
- Add tenant domain rejection tests to SAML, OpenID, and social specs
  verifying that tenant config restrictions actually block login
- Add error propagation tests to resolveAppConfig.spec.ts
- Remove redundant mockTenantStorage alias in resolveAppConfig.spec.ts
- Narrow eslint-disable to specific require line

* test: add tenant domain rejection test for LDAP strategy

Covers the appConfig !== baseConfig && !isEmailDomainAllowed path,
consistent with SAML, OpenID, and social strategy specs.

* refactor: rename resolveAppConfig to app/resolve per AGENTS.md

Rename resolveAppConfig.ts → resolve.ts and
resolveAppConfig.spec.ts → resolve.spec.ts to align with
the project's concise naming convention.

* fix: remove fragile reference-equality guard, add logging and docs

Remove appConfig !== baseConfig guard from all strategies and
requestPasswordReset. The guard relied on implicit cache-backend
identity semantics (in-memory Keyv returns same object reference)
that would silently break with Redis or cloned configs. The second
isEmailDomainAllowed call is a cheap synchronous check — always
running it is clearer and eliminates the coupling.

Add audit logging to requestPasswordReset domain blocks (base and
tenant), consistent with all auth strategies.

Extract duplicated error construction into makeDomainDeniedError().

Wrap resolveAppConfigForUser in requestPasswordReset with try/catch
to prevent DB errors from leaking to the client via the controller's
generic catch handler.

Document the dual tenantId propagation (ALS for DB isolation,
explicit param for cache key) in resolveAppConfigForUser JSDoc.

Add comment documenting the LDAP error-type ordering change
(cross-provider users from blocked domains now get 'domain not
allowed' instead of AUTH_FAILED).

Assert resolveAppConfigForUser is not called on LDAP provider
mismatch path.

* fix: return generic response for tenant domain block in password reset

Tenant-scoped domain rejection in requestPasswordReset now returns the
same generic "If an account with that email exists..." response instead
of an Error. This prevents user-enumeration: an attacker cannot
distinguish between "email not found" and "tenant blocks this domain"
by comparing HTTP responses.

The base-config fast-fail (pre-user-lookup) still returns an Error
since it fires before any user existence is revealed.

* docs: document phase 1 vs phase 2 domain check behavior in JSDoc

Phase 1 (base config, pre-findUser) intentionally returns Error/400
to reveal globally blocked domains without confirming user existence.
Phase 2 (tenant config, post-findUser) returns generic 200 to prevent
user-enumeration. This distinction is now explicit in the JSDoc.
2026-03-27 16:08:43 -04:00

341 lines
11 KiB
JavaScript

jest.mock('@librechat/data-schemas', () => ({
logger: { info: jest.fn(), warn: jest.fn(), debug: jest.fn(), error: jest.fn() },
DEFAULT_SESSION_EXPIRY: 900000,
DEFAULT_REFRESH_TOKEN_EXPIRY: 604800000,
}));
jest.mock('librechat-data-provider', () => ({
ErrorTypes: {},
SystemRoles: { USER: 'USER', ADMIN: 'ADMIN' },
errorsToString: jest.fn(),
}));
jest.mock('@librechat/api', () => ({
isEnabled: jest.fn((val) => val === 'true' || val === true),
checkEmailConfig: jest.fn(),
isEmailDomainAllowed: jest.fn(),
math: jest.fn((val, fallback) => (val ? Number(val) : fallback)),
shouldUseSecureCookie: jest.fn(() => false),
resolveAppConfigForUser: jest.fn(async (_getAppConfig, _user) => ({})),
}));
jest.mock('~/models', () => ({
findUser: jest.fn(),
findToken: jest.fn(),
createUser: jest.fn(),
updateUser: jest.fn(),
countUsers: jest.fn(),
getUserById: jest.fn(),
findSession: jest.fn(),
createToken: jest.fn(),
deleteTokens: jest.fn(),
deleteSession: jest.fn(),
createSession: jest.fn(),
generateToken: jest.fn(),
deleteUserById: jest.fn(),
generateRefreshToken: jest.fn(),
}));
jest.mock('~/strategies/validators', () => ({ registerSchema: { parse: jest.fn() } }));
jest.mock('~/server/services/Config', () => ({ getAppConfig: jest.fn() }));
jest.mock('~/server/utils', () => ({ sendEmail: jest.fn() }));
const {
shouldUseSecureCookie,
isEmailDomainAllowed,
resolveAppConfigForUser,
} = require('@librechat/api');
const { findUser } = require('~/models');
const { getAppConfig } = require('~/server/services/Config');
const { setOpenIDAuthTokens, requestPasswordReset } = require('./AuthService');
/** Helper to build a mock Express response */
function mockResponse() {
const cookies = {};
const res = {
cookie: jest.fn((name, value, options) => {
cookies[name] = { value, options };
}),
_cookies: cookies,
};
return res;
}
/** Helper to build a mock Express request with session */
function mockRequest(sessionData = {}) {
return {
session: { openidTokens: null, ...sessionData },
};
}
describe('setOpenIDAuthTokens', () => {
const env = process.env;
beforeEach(() => {
jest.clearAllMocks();
process.env = {
...env,
JWT_REFRESH_SECRET: 'test-refresh-secret',
OPENID_REUSE_TOKENS: 'true',
};
});
afterAll(() => {
process.env = env;
});
describe('token selection (id_token vs access_token)', () => {
it('should return id_token when both id_token and access_token are present', () => {
const tokenset = {
id_token: 'the-id-token',
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(result).toBe('the-id-token');
});
it('should return access_token when id_token is not available', () => {
const tokenset = {
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(result).toBe('the-access-token');
});
it('should return access_token when id_token is undefined', () => {
const tokenset = {
id_token: undefined,
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(result).toBe('the-access-token');
});
it('should return access_token when id_token is null', () => {
const tokenset = {
id_token: null,
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(result).toBe('the-access-token');
});
it('should return id_token even when id_token and access_token differ', () => {
const tokenset = {
id_token: 'id-token-jwt-signed-by-idp',
access_token: 'opaque-graph-api-token',
refresh_token: 'refresh-token',
};
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(result).toBe('id-token-jwt-signed-by-idp');
expect(result).not.toBe('opaque-graph-api-token');
});
});
describe('session token storage', () => {
it('should store the original access_token in session (not id_token)', () => {
const tokenset = {
id_token: 'the-id-token',
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = mockRequest();
const res = mockResponse();
setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(req.session.openidTokens.accessToken).toBe('the-access-token');
expect(req.session.openidTokens.refreshToken).toBe('the-refresh-token');
});
});
describe('cookie secure flag', () => {
it('should call shouldUseSecureCookie for every cookie set', () => {
const tokenset = {
id_token: 'the-id-token',
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = mockRequest();
const res = mockResponse();
setOpenIDAuthTokens(tokenset, req, res, 'user-123');
// token_provider + openid_user_id (session path, so no refreshToken/openid_access_token cookies)
const secureCalls = shouldUseSecureCookie.mock.calls.length;
expect(secureCalls).toBeGreaterThanOrEqual(2);
// Verify all cookies use the result of shouldUseSecureCookie
for (const [, cookie] of Object.entries(res._cookies)) {
expect(cookie.options.secure).toBe(false);
}
});
it('should set secure: true when shouldUseSecureCookie returns true', () => {
shouldUseSecureCookie.mockReturnValue(true);
const tokenset = {
id_token: 'the-id-token',
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = mockRequest();
const res = mockResponse();
setOpenIDAuthTokens(tokenset, req, res, 'user-123');
for (const [, cookie] of Object.entries(res._cookies)) {
expect(cookie.options.secure).toBe(true);
}
});
it('should use shouldUseSecureCookie for cookie fallback path (no session)', () => {
shouldUseSecureCookie.mockReturnValue(false);
const tokenset = {
id_token: 'the-id-token',
access_token: 'the-access-token',
refresh_token: 'the-refresh-token',
};
const req = { session: null };
const res = mockResponse();
setOpenIDAuthTokens(tokenset, req, res, 'user-123');
// In the cookie fallback path, we get: refreshToken, openid_access_token, token_provider, openid_user_id
expect(res.cookie).toHaveBeenCalledWith(
'refreshToken',
expect.any(String),
expect.objectContaining({ secure: false }),
);
expect(res.cookie).toHaveBeenCalledWith(
'openid_access_token',
expect.any(String),
expect.objectContaining({ secure: false }),
);
expect(res.cookie).toHaveBeenCalledWith(
'token_provider',
'openid',
expect.objectContaining({ secure: false }),
);
});
});
describe('edge cases', () => {
it('should return undefined when tokenset is null', () => {
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(null, req, res, 'user-123');
expect(result).toBeUndefined();
});
it('should return undefined when access_token is missing', () => {
const tokenset = { refresh_token: 'refresh' };
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(result).toBeUndefined();
});
it('should return undefined when no refresh token is available', () => {
const tokenset = { access_token: 'access', id_token: 'id' };
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123');
expect(result).toBeUndefined();
});
it('should use existingRefreshToken when tokenset has no refresh_token', () => {
const tokenset = {
id_token: 'the-id-token',
access_token: 'the-access-token',
};
const req = mockRequest();
const res = mockResponse();
const result = setOpenIDAuthTokens(tokenset, req, res, 'user-123', 'existing-refresh');
expect(result).toBe('the-id-token');
expect(req.session.openidTokens.refreshToken).toBe('existing-refresh');
});
});
});
describe('requestPasswordReset', () => {
beforeEach(() => {
jest.clearAllMocks();
isEmailDomainAllowed.mockReturnValue(true);
getAppConfig.mockResolvedValue({
registration: { allowedDomains: ['example.com'] },
});
resolveAppConfigForUser.mockResolvedValue({
registration: { allowedDomains: ['example.com'] },
});
});
it('should fast-fail with base config before DB lookup for blocked domains', async () => {
isEmailDomainAllowed.mockReturnValue(false);
const req = { body: { email: 'blocked@evil.com' }, ip: '127.0.0.1' };
const result = await requestPasswordReset(req);
expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
expect(findUser).not.toHaveBeenCalled();
expect(result).toBeInstanceOf(Error);
});
it('should call resolveAppConfigForUser for tenant user', async () => {
const user = {
_id: 'user-tenant',
email: 'user@example.com',
tenantId: 'tenant-x',
role: 'USER',
};
findUser.mockResolvedValue(user);
const req = { body: { email: 'user@example.com' }, ip: '127.0.0.1' };
await requestPasswordReset(req);
expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, user);
});
it('should reuse baseConfig for non-tenant user without calling resolveAppConfigForUser', async () => {
findUser.mockResolvedValue({ _id: 'user-no-tenant', email: 'user@example.com' });
const req = { body: { email: 'user@example.com' }, ip: '127.0.0.1' };
await requestPasswordReset(req);
expect(resolveAppConfigForUser).not.toHaveBeenCalled();
});
it('should return generic response when tenant config blocks the domain (non-enumerable)', async () => {
const user = {
_id: 'user-tenant',
email: 'user@example.com',
tenantId: 'tenant-x',
role: 'USER',
};
findUser.mockResolvedValue(user);
isEmailDomainAllowed.mockReturnValueOnce(true).mockReturnValueOnce(false);
const req = { body: { email: 'user@example.com' }, ip: '127.0.0.1' };
const result = await requestPasswordReset(req);
expect(result).not.toBeInstanceOf(Error);
expect(result.message).toContain('If an account with that email exists');
});
});