mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-04-03 06:17:21 +02:00
🏢 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.
This commit is contained in:
parent
5972a21479
commit
77712c825f
13 changed files with 2428 additions and 1880 deletions
|
|
@ -13,6 +13,7 @@ const {
|
|||
checkEmailConfig,
|
||||
isEmailDomainAllowed,
|
||||
shouldUseSecureCookie,
|
||||
resolveAppConfigForUser,
|
||||
} = require('@librechat/api');
|
||||
const {
|
||||
findUser,
|
||||
|
|
@ -255,19 +256,52 @@ const registerUser = async (user, additionalData = {}) => {
|
|||
};
|
||||
|
||||
/**
|
||||
* Request password reset
|
||||
* Request password reset.
|
||||
*
|
||||
* Uses a two-phase domain check: fast-fail with the memory-cached base config
|
||||
* (zero DB queries) to block globally denied domains before user lookup, then
|
||||
* re-check with tenant-scoped config after user lookup so tenant-specific
|
||||
* restrictions are enforced.
|
||||
*
|
||||
* Phase 1 (base check) returns an Error (HTTP 400) — this intentionally reveals
|
||||
* that the domain is globally blocked, but fires before any DB lookup so it
|
||||
* cannot confirm user existence. Phase 2 (tenant check) returns the generic
|
||||
* success message (HTTP 200) to prevent user-enumeration via status codes.
|
||||
*
|
||||
* @param {ServerRequest} req
|
||||
*/
|
||||
const requestPasswordReset = async (req) => {
|
||||
const { email } = req.body;
|
||||
const appConfig = await getAppConfig({ baseOnly: true });
|
||||
if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
|
||||
|
||||
const baseConfig = await getAppConfig({ baseOnly: true });
|
||||
if (!isEmailDomainAllowed(email, baseConfig?.registration?.allowedDomains)) {
|
||||
logger.warn(
|
||||
`[requestPasswordReset] Blocked - email domain not allowed [Email: ${email}] [IP: ${req.ip}]`,
|
||||
);
|
||||
const error = new Error(ErrorTypes.AUTH_FAILED);
|
||||
error.code = ErrorTypes.AUTH_FAILED;
|
||||
error.message = 'Email domain not allowed';
|
||||
return error;
|
||||
}
|
||||
const user = await findUser({ email }, 'email _id');
|
||||
|
||||
const user = await findUser({ email }, 'email _id role tenantId');
|
||||
let appConfig = baseConfig;
|
||||
if (user?.tenantId) {
|
||||
try {
|
||||
appConfig = await resolveAppConfigForUser(getAppConfig, user);
|
||||
} catch (err) {
|
||||
logger.error('[requestPasswordReset] Failed to resolve tenant config, using base:', err);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
|
||||
logger.warn(
|
||||
`[requestPasswordReset] Tenant config blocked domain [Email: ${email}] [IP: ${req.ip}]`,
|
||||
);
|
||||
return {
|
||||
message: 'If an account with that email exists, a password reset link has been sent to it.',
|
||||
};
|
||||
}
|
||||
const emailEnabled = checkEmailConfig();
|
||||
|
||||
logger.warn(`[requestPasswordReset] [Password reset request initiated] [Email: ${email}]`);
|
||||
|
|
|
|||
|
|
@ -14,6 +14,7 @@ jest.mock('@librechat/api', () => ({
|
|||
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(),
|
||||
|
|
@ -35,8 +36,14 @@ 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 } = require('@librechat/api');
|
||||
const { setOpenIDAuthTokens } = require('./AuthService');
|
||||
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() {
|
||||
|
|
@ -267,3 +274,68 @@ describe('setOpenIDAuthTokens', () => {
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue