mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-04-03 22:37:20 +02:00
* 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.
186 lines
5.6 KiB
JavaScript
186 lines
5.6 KiB
JavaScript
const fs = require('fs');
|
|
const LdapStrategy = require('passport-ldapauth');
|
|
const { logger } = require('@librechat/data-schemas');
|
|
const { SystemRoles, ErrorTypes } = require('librechat-data-provider');
|
|
const {
|
|
isEnabled,
|
|
getBalanceConfig,
|
|
isEmailDomainAllowed,
|
|
resolveAppConfigForUser,
|
|
} = require('@librechat/api');
|
|
const { createUser, findUser, updateUser, countUsers } = require('~/models');
|
|
const { getAppConfig } = require('~/server/services/Config');
|
|
|
|
const {
|
|
LDAP_URL,
|
|
LDAP_BIND_DN,
|
|
LDAP_BIND_CREDENTIALS,
|
|
LDAP_USER_SEARCH_BASE,
|
|
LDAP_SEARCH_FILTER,
|
|
LDAP_CA_CERT_PATH,
|
|
LDAP_FULL_NAME,
|
|
LDAP_ID,
|
|
LDAP_USERNAME,
|
|
LDAP_EMAIL,
|
|
LDAP_TLS_REJECT_UNAUTHORIZED,
|
|
LDAP_STARTTLS,
|
|
} = process.env;
|
|
|
|
// Check required environment variables
|
|
if (!LDAP_URL || !LDAP_USER_SEARCH_BASE) {
|
|
module.exports = null;
|
|
}
|
|
|
|
const searchAttributes = [
|
|
'displayName',
|
|
'mail',
|
|
'uid',
|
|
'cn',
|
|
'name',
|
|
'commonname',
|
|
'givenName',
|
|
'sn',
|
|
'sAMAccountName',
|
|
];
|
|
|
|
if (LDAP_FULL_NAME) {
|
|
searchAttributes.push(...LDAP_FULL_NAME.split(','));
|
|
}
|
|
if (LDAP_ID) {
|
|
searchAttributes.push(LDAP_ID);
|
|
}
|
|
if (LDAP_USERNAME) {
|
|
searchAttributes.push(LDAP_USERNAME);
|
|
}
|
|
if (LDAP_EMAIL) {
|
|
searchAttributes.push(LDAP_EMAIL);
|
|
}
|
|
const rejectUnauthorized = isEnabled(LDAP_TLS_REJECT_UNAUTHORIZED);
|
|
const startTLS = isEnabled(LDAP_STARTTLS);
|
|
|
|
const ldapOptions = {
|
|
server: {
|
|
url: LDAP_URL,
|
|
bindDN: LDAP_BIND_DN,
|
|
bindCredentials: LDAP_BIND_CREDENTIALS,
|
|
searchBase: LDAP_USER_SEARCH_BASE,
|
|
searchFilter: LDAP_SEARCH_FILTER || 'mail={{username}}',
|
|
searchAttributes: [...new Set(searchAttributes)],
|
|
...(LDAP_CA_CERT_PATH && {
|
|
tlsOptions: {
|
|
rejectUnauthorized,
|
|
ca: (() => {
|
|
try {
|
|
return [fs.readFileSync(LDAP_CA_CERT_PATH)];
|
|
} catch (err) {
|
|
logger.error('[ldapStrategy]', 'Failed to read CA certificate', err);
|
|
throw err;
|
|
}
|
|
})(),
|
|
},
|
|
}),
|
|
...(startTLS && { starttls: true }),
|
|
},
|
|
usernameField: 'email',
|
|
passwordField: 'password',
|
|
};
|
|
|
|
const ldapLogin = new LdapStrategy(ldapOptions, async (userinfo, done) => {
|
|
if (!userinfo) {
|
|
return done(null, false, { message: 'Invalid credentials' });
|
|
}
|
|
|
|
try {
|
|
const ldapId =
|
|
(LDAP_ID && userinfo[LDAP_ID]) || userinfo.uid || userinfo.sAMAccountName || userinfo.mail;
|
|
|
|
const fullNameAttributes = LDAP_FULL_NAME && LDAP_FULL_NAME.split(',');
|
|
const fullName =
|
|
fullNameAttributes && fullNameAttributes.length > 0
|
|
? fullNameAttributes.map((attr) => userinfo[attr]).join(' ')
|
|
: userinfo.cn || userinfo.name || userinfo.commonname || userinfo.displayName;
|
|
|
|
const username =
|
|
(LDAP_USERNAME && userinfo[LDAP_USERNAME]) || userinfo.givenName || userinfo.mail;
|
|
|
|
let mail = (LDAP_EMAIL && userinfo[LDAP_EMAIL]) || userinfo.mail || username + '@ldap.local';
|
|
mail = Array.isArray(mail) ? mail[0] : mail;
|
|
|
|
if (!userinfo.mail && !(LDAP_EMAIL && userinfo[LDAP_EMAIL])) {
|
|
logger.warn(
|
|
'[ldapStrategy]',
|
|
`No valid email attribute found in LDAP userinfo. Using fallback email: ${username}@ldap.local`,
|
|
`LDAP_EMAIL env var: ${LDAP_EMAIL || 'not set'}`,
|
|
`Available userinfo attributes: ${Object.keys(userinfo).join(', ')}`,
|
|
'Full userinfo:',
|
|
JSON.stringify(userinfo, null, 2),
|
|
);
|
|
}
|
|
|
|
// Domain check before findUser for two-phase fast-fail (consistent with SAML/OpenID/social).
|
|
// This means cross-provider users from blocked domains get 'Email domain not allowed'
|
|
// instead of AUTH_FAILED — both deny access.
|
|
const baseConfig = await getAppConfig({ baseOnly: true });
|
|
if (!isEmailDomainAllowed(mail, baseConfig?.registration?.allowedDomains)) {
|
|
logger.error(
|
|
`[LDAP Strategy] Authentication blocked - email domain not allowed [Email: ${mail}]`,
|
|
);
|
|
return done(null, false, { message: 'Email domain not allowed' });
|
|
}
|
|
|
|
let user = await findUser({ ldapId });
|
|
if (user && user.provider !== 'ldap') {
|
|
logger.info(
|
|
`[ldapStrategy] User ${user.email} already exists with provider ${user.provider}`,
|
|
);
|
|
return done(null, false, {
|
|
message: ErrorTypes.AUTH_FAILED,
|
|
});
|
|
}
|
|
|
|
const appConfig = user?.tenantId
|
|
? await resolveAppConfigForUser(getAppConfig, user)
|
|
: baseConfig;
|
|
|
|
if (!isEmailDomainAllowed(mail, appConfig?.registration?.allowedDomains)) {
|
|
logger.error(
|
|
`[LDAP Strategy] Authentication blocked - email domain not allowed [Email: ${mail}]`,
|
|
);
|
|
return done(null, false, { message: 'Email domain not allowed' });
|
|
}
|
|
|
|
if (!user) {
|
|
const isFirstRegisteredUser = (await countUsers()) === 0;
|
|
const role = isFirstRegisteredUser ? SystemRoles.ADMIN : SystemRoles.USER;
|
|
|
|
user = {
|
|
provider: 'ldap',
|
|
ldapId,
|
|
username,
|
|
email: mail,
|
|
emailVerified: true, // The ldap server administrator should verify the email
|
|
name: fullName,
|
|
role,
|
|
};
|
|
const balanceConfig = getBalanceConfig(appConfig);
|
|
const userId = await createUser(user, balanceConfig);
|
|
user._id = userId;
|
|
} else {
|
|
// Users registered in LDAP are assumed to have their user information managed in LDAP,
|
|
// so update the user information with the values registered in LDAP
|
|
user.provider = 'ldap';
|
|
user.ldapId = ldapId;
|
|
user.email = mail;
|
|
user.username = username;
|
|
user.name = fullName;
|
|
}
|
|
|
|
user = await updateUser(user._id, user);
|
|
done(null, user);
|
|
} catch (err) {
|
|
logger.error('[ldapStrategy]', err);
|
|
done(err);
|
|
}
|
|
});
|
|
|
|
module.exports = ldapLogin;
|