Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🔐 fix: Apply Base Config Overrides Before Sign-In and Refuse Script Policy Links (#17351)

Danny Avila0abbf3313d14
diff --git a/api/server/routes/__tests__/config.spec.js b/api/server/routes/__tests__/config.spec.js
index b2470b5017..57282f228d 100644
--- a/api/server/routes/__tests__/config.spec.js
+++ b/api/server/routes/__tests__/config.spec.js
@@ -124,31 +124,93 @@ afterEach(() => {
describe('GET /api/config', () => {
describe('unauthenticated (no req.user)', () => {
- it('should call getAppConfig with baseOnly when no tenant context', async () => {
+ it('should resolve the __base__ overrides without runtime augmentation when no tenant context', async () => {
mockGetAppConfig.mockResolvedValue(baseAppConfig);
mockGetTenantId.mockReturnValue(undefined);
const app = createApp(null);
await request(app).get('/api/config');
- expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ skipRuntimeAugmentation: true });
+ expect(mockGetAppConfig).not.toHaveBeenCalledWith(
+ expect.objectContaining({ failClosed: true }),
+ );
+ });
+
+ it('should serve the pre-login config: __base__ socialLogins and interface, YAML Turnstile', async () => {
+ mockGetTenantId.mockReturnValue(undefined);
+ mockResolveBuildInfo.mockReturnValue({
+ commit: 'abc1234def',
+ commitShort: 'abc1234',
+ branch: 'main',
+ buildDate: '2026-01-01T00:00:00.000Z',
+ });
+ /** What the merge hands back: `turnstile` is base-only, so it is librechat.yaml's. */
+ const preLoginConfig = {
+ registration: { socialLogins: ['google', 'openid'] },
+ interfaceConfig: {
+ privacyPolicy: { externalUrl: 'https://base.example/privacy' },
+ theme: 'clickhouse',
+ buildInfo: false,
+ modelSelect: false,
+ },
+ turnstileConfig: { siteKey: 'yaml-site-key' },
+ };
+ mockGetAppConfig.mockResolvedValue(preLoginConfig);
+ const app = createApp(null);
+
+ const response = await request(app).get('/api/config');
+
+ expect(response.statusCode).toBe(200);
+ expect(mockGetAppConfig).toHaveBeenCalledTimes(1);
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ skipRuntimeAugmentation: true });
+ expect(response.body.socialLogins).toEqual(['google', 'openid']);
+ expect(response.body.interface).toEqual({
+ privacyPolicy: { externalUrl: 'https://base.example/privacy' },
+ buildInfo: false,
+ theme: 'clickhouse',
+ });
+ expect(response.body).not.toHaveProperty('buildInfo');
+ expect(response.body.turnstile).toEqual({ siteKey: 'yaml-site-key' });
+ });
+
+ it('should never serve a signed-out visitor a policy link that would run script', async () => {
+ mockGetAppConfig.mockResolvedValue({
+ ...baseAppConfig,
+ interfaceConfig: {
+ privacyPolicy: {
+ externalUrl: '\u00a0javascript:alert(document.domain)',
+ openNewTab: true,
+ },
+ termsOfService: { externalUrl: '\u0001data:text/html,<script>alert(1)</script>' },
+ },
+ });
+ const app = createApp(null);
+
+ const response = await request(app).get('/api/config');
+
+ expect(response.statusCode).toBe(200);
+ expect(response.body.interface).toEqual({
+ privacyPolicy: { openNewTab: true },
+ termsOfService: {},
+ });
});
- it('should call getAppConfig with tenantId when tenant context is present', async () => {
+ it('should resolve a tenant context in one read without an explicit tenantId', async () => {
mockGetAppConfig.mockResolvedValue(baseAppConfig);
mockGetTenantId.mockReturnValue('tenant-abc');
const app = createApp(null);
await request(app).get('/api/config');
- expect(mockGetAppConfig).toHaveBeenCalledWith({ tenantId: 'tenant-abc' });
+ expect(mockGetAppConfig).toHaveBeenCalledTimes(1);
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ skipRuntimeAugmentation: true });
});
it('should map tenant-scoped config fields in unauthenticated response', async () => {
const tenantConfig = {
...baseAppConfig,
registration: { socialLogins: ['saml'] },
- turnstileConfig: { siteKey: 'tenant-key' },
};
mockGetAppConfig.mockResolvedValue(tenantConfig);
mockGetTenantId.mockReturnValue('tenant-abc');
@@ -158,7 +220,7 @@ describe('GET /api/config', () => {
expect(response.statusCode).toBe(200);
expect(response.body.socialLogins).toEqual(['saml']);
- expect(response.body.turnstile).toEqual({ siteKey: 'tenant-key' });
+ expect(response.body.turnstile).toEqual({ siteKey: 'test-key' });
expect(response.body).not.toHaveProperty('modelSpecs');
});
@@ -391,6 +453,27 @@ describe('GET /api/config', () => {
expect(anonymous.body).not.toHaveProperty('ragEnabled');
});
+ it('drops a policy link that would run script and keeps the rest of the interface', async () => {
+ mockGetAppConfig.mockResolvedValue({
+ ...baseAppConfig,
+ interfaceConfig: {
+ privacyPolicy: { externalUrl: 'https://example.com/privacy' },
+ termsOfService: { externalUrl: 'JavaScript:alert(1)', modalAcceptance: true },
+ modelSelect: true,
+ },
+ });
+ const app = createApp(mockUser);
+
+ const response = await request(app).get('/api/config');
+
+ expect(response.statusCode).toBe(200);
+ expect(response.body.interface).toEqual({
+ privacyPolicy: { externalUrl: 'https://example.com/privacy' },
+ termsOfService: { modalAcceptance: true },
+ modelSelect: true,
+ });
+ });
+
it('should call getAppConfig with role, userId, and tenantId', async () => {
mockGetAppConfig.mockResolvedValue(baseAppConfig);
mockGetTenantId.mockReturnValue('fallback-tenant');
diff --git a/api/server/routes/config.js b/api/server/routes/config.js
index 678b83f227..65d1b26c22 100644
--- a/api/server/routes/config.js
+++ b/api/server/routes/config.js
@@ -24,6 +24,8 @@ const {
resolveCodeEnvironmentTransitionVersion,
loadConversationListLimits,
resolvePullRequestCapabilities,
+ resolvePreLoginAppConfig,
+ withSafePolicyLinks,
} = require('@librechat/api');
const {
DEFAULT_MCP_APP_CSP_LIMITS,
@@ -31,7 +33,7 @@ const {
defaultSocialLogins,
resolveMCPAppsPolicy,
} = require('librechat-data-provider');
-const { logger, getTenantId, SystemCapabilities } = require('@librechat/data-schemas');
+const { logger, SystemCapabilities } = require('@librechat/data-schemas');
const { hasCapability, hasConfigCapability } = require('~/server/middleware/roles/capabilities');
const { getLdapConfig } = require('~/server/services/Config/ldap');
const { getRumConfig } = require('~/server/services/Config/rum');
@@ -231,8 +233,7 @@ router.get('/', async function (req, res) {
const publicSharePayload = buildPublicSharePayload();
if (!req.user) {
- const tenantId = getTenantId();
- const baseConfig = await getAppConfig(tenantId ? { tenantId } : { baseOnly: true });
+ const baseConfig = await resolvePreLoginAppConfig(getAppConfig);
/** @type {Partial<TStartupConfig>} */
const payload = {
@@ -310,7 +311,7 @@ router.get('/', async function (req, res) {
sharedLinksSnapshotFilesEnabled: sharedLinksEnabled && isFileSnapshotEnabled(appConfig),
socialLogins: appConfig?.registration?.socialLogins ?? defaultSocialLogins,
projects: appConfig?.projects,
- interface: appConfig?.interfaceConfig,
+ interface: withSafePolicyLinks(appConfig?.interfaceConfig),
titleGenerationTiming: resolveTitleTiming({
appConfig,
endpoint: EModelEndpoint.agents,
diff --git a/api/server/services/AuthService.js b/api/server/services/AuthService.js
index 58e37809ce..17b024930a 100644
--- a/api/server/services/AuthService.js
+++ b/api/server/services/AuthService.js
@@ -30,6 +30,7 @@ const {
normalizeExpiresIn,
createOpenIDSessionIdentity,
resolveAppConfigForUser,
+ resolvePreAuthAppConfig,
commitPasswordReset,
getSafeErrorMetadata,
hashSecret,
@@ -68,6 +69,10 @@ const AuthTokenTypes = Object.freeze({
const latestAuthTokenOptions = Object.freeze({ sort: { createdAt: -1 } });
const genericVerificationMessage = 'Please check your email to verify your email address.';
+const genericResetMessage =
+ 'If an account with that email exists, a password reset link has been sent to it.';
+const domainNotAllowedMessage =
+ 'The email address provided cannot be used. Please use a different email address.';
const invalidEmailVerificationMessage = 'Invalid or expired email verification token';
const OPENID_SESSION_ID_TOKEN_EXPIRY_BUFFER_SECONDS = 30;
@@ -375,6 +380,12 @@ const verifyEmail = async (req) => {
/**
* Register a new user.
+ *
+ * The email domain is checked against the pre-auth config (librechat.yaml plus the
+ * `__base__` override), then against the config of the role the account would be
+ * created with (ADMIN for the deployment's first user, otherwise USER), both before
+ * the email-in-use answer so neither reveals whether an account exists.
+ *
* @param {IUser} user <email, password, name, username>
* @param {Partial<IUser>} [additionalData={}] Trusted server-provided fields, such as CLI overrides.
* @returns {Promise<{status: number, message: string, user?: IUser}>}
@@ -397,15 +408,27 @@ const registerUser = async (user, additionalData = {}) => {
let newUserId;
try {
const tenantId = getTenantId();
- const appConfig = await getAppConfig(tenantId ? { tenantId } : {});
- if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
- const errorMessage =
- 'The email address provided cannot be used. Please use a different email address.';
+ const preAuthConfig = await resolvePreAuthAppConfig(getAppConfig);
+ if (!isEmailDomainAllowed(email, preAuthConfig?.registration?.allowedDomains)) {
logger.error('[registerUser] [Registration not allowed]');
- return { status: 403, message: errorMessage };
+ return { status: 403, message: domainNotAllowedMessage };
}
- const existingUser = await findUser({ email }, 'email _id');
+ // Only the first user in the unscoped, single-tenant deployment bootstraps ADMIN.
+ // Tenant administrators must be provisioned through a trusted administrative flow.
+ const [existingUser, userCount] = await Promise.all([
+ findUser({ email }, 'email _id'),
+ tenantId ? null : countUsers(),
+ ]);
+ const role =
+ trustedAdditionalData.role ?? (userCount === 0 ? SystemRoles.ADMIN : SystemRoles.USER);
+
+ /** Checked before the email-in-use answer, which it must not depend on. */
+ const appConfig = await resolveAppConfigForUser(getAppConfig, { role });
+ if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
+ logger.error(`[registerUser] [Registration not allowed for a new ${role} account]`);
+ return { status: 403, message: domainNotAllowedMessage };
+ }
if (existingUser) {
logger.info(`[registerUser] Email in use [User ID: ${existingUser._id}]`);
@@ -415,17 +438,13 @@ const registerUser = async (user, additionalData = {}) => {
return { status: 200, message: genericVerificationMessage };
}
- // Only the first user in the unscoped, single-tenant deployment bootstraps ADMIN.
- // Tenant administrators must be provisioned through a trusted administrative flow.
- const isFirstRegisteredUser = !tenantId && (await countUsers()) === 0;
-
const newUserData = {
provider: provider ?? 'local',
email,
username,
name,
avatar: null,
- role: isFirstRegisteredUser ? SystemRoles.ADMIN : SystemRoles.USER,
+ role,
password: await hashSecret(password),
...trustedAdditionalData,
};
@@ -471,22 +490,25 @@ const registerUser = async (user, additionalData = {}) => {
/**
* 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.
+ * Uses a two-phase domain check: fast-fail with the pre-auth config (librechat.yaml
+ * plus the `__base__` override, cached) to block globally denied domains before user
+ * lookup, then re-check with the account's config (its role's overrides, in its
+ * tenant if any) after user lookup so role- and 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.
+ * that the domain is globally blocked, but fires before the user lookup so it
+ * cannot confirm user existence. Phase 2 (account check) returns the generic
+ * success message (HTTP 200) to prevent user-enumeration via status codes. It
+ * also does so without issuing a link when the account's config cannot be read,
+ * so a broader policy never decides the reset.
*
* @param {ServerRequest} req
*/
const requestPasswordReset = async (req) => {
const { email } = req.body;
- const baseConfig = await getAppConfig({ baseOnly: true });
+ const baseConfig = await resolvePreAuthAppConfig(getAppConfig);
if (!isEmailDomainAllowed(email, baseConfig?.registration?.allowedDomains)) {
logger.warn('[requestPasswordReset] Blocked - email domain not allowed');
const error = new Error(ErrorTypes.AUTH_FAILED);
@@ -497,22 +519,21 @@ const requestPasswordReset = async (req) => {
const user = await findUser({ email }, 'email _id role tenantId');
let appConfig = baseConfig;
- if (user?.tenantId) {
+ if (user) {
try {
appConfig = await resolveAppConfigForUser(getAppConfig, user);
} catch (err) {
logger.error(
- '[requestPasswordReset] Failed to resolve tenant config, using base:',
+ "[requestPasswordReset] Failed to resolve the account's config; no link issued:",
getSafeErrorMetadata(err),
);
+ return { message: genericResetMessage };
}
}
if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
- logger.warn('[requestPasswordReset] Tenant config blocked domain');
- return {
- message: 'If an account with that email exists, a password reset link has been sent to it.',
- };
+ logger.warn("[requestPasswordReset] The account's config blocked the domain");
+ return { message: genericResetMessage };
}
const emailEnabled = checkEmailConfig();
@@ -520,9 +541,7 @@ const requestPasswordReset = async (req) => {
if (!user) {
logger.warn('[requestPasswordReset] [No user found]');
- return {
- message: 'If an account with that email exists, a password reset link has been sent to it.',
- };
+ return { message: genericResetMessage };
}
await Promise.all([
@@ -561,9 +580,7 @@ const requestPasswordReset = async (req) => {
return { link };
}
- return {
- message: 'If an account with that email exists, a password reset link has been sent to it.',
- };
+ return { message: genericResetMessage };
};
/**
diff --git a/api/server/services/AuthService.spec.js b/api/server/services/AuthService.spec.js
index 51ecda44ae..af91fd6f04 100644
--- a/api/server/services/AuthService.spec.js
+++ b/api/server/services/AuthService.spec.js
@@ -67,6 +67,10 @@ jest.mock(
: undefined;
},
resolveAppConfigForUser: jest.fn(async (_getAppConfig, _user) => ({})),
+ /** Mirrors the real resolver's options so `getAppConfig` mocks still decide the result. */
+ resolvePreAuthAppConfig: jest.fn((getAppConfig) =>
+ getAppConfig({ skipRuntimeAugmentation: true, failClosed: true }),
+ ),
commitPasswordReset: jest.fn(),
createOpenIDSessionIdentity: jest.fn(
({ user, userId, openidSubject, tenantId, openidIssuer }) => {
@@ -141,6 +145,7 @@ jest.mock('~/server/utils', () => ({ sendEmail: jest.fn() }));
let checkEmailConfig;
let isEmailDomainAllowed;
let resolveAppConfigForUser;
+let resolvePreAuthAppConfig;
let setRefreshTokenCookie;
let setOpenIDMarkerCookies;
let setLocalSessionCookies;
@@ -185,6 +190,7 @@ jest.isolateModules(() => {
checkEmailConfig,
isEmailDomainAllowed,
resolveAppConfigForUser,
+ resolvePreAuthAppConfig,
commitPasswordReset,
setRefreshTokenCookie,
setOpenIDMarkerCookies,
@@ -952,17 +958,28 @@ describe('requestPasswordReset', () => {
});
});
- it('should fast-fail with base config before DB lookup for blocked domains', async () => {
+ it('should fast-fail with the pre-auth config before DB lookup for blocked domains', async () => {
isEmailDomainAllowed.mockReturnValue(false);
const req = { body: { email: '[email protected]' }, ip: '127.0.0.1' };
const result = await requestPasswordReset(req);
- expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(resolvePreAuthAppConfig).toHaveBeenCalledWith(getAppConfig);
+ expect(getAppConfig).not.toHaveBeenCalledWith({ baseOnly: true });
expect(findUser).not.toHaveBeenCalled();
expect(result).toBeInstanceOf(Error);
});
+ it('should propagate a pre-auth config read failure before the user lookup', async () => {
+ getAppConfig.mockRejectedValue(new Error('override read failed'));
+
+ const req = { body: { email: '[email protected]' }, ip: '127.0.0.1' };
+
+ await expect(requestPasswordReset(req)).rejects.toThrow('override read failed');
+ expect(findUser).not.toHaveBeenCalled();
+ expect(createToken).not.toHaveBeenCalled();
+ });
+
it('should call resolveAppConfigForUser for tenant user', async () => {
const user = {
_id: 'user-tenant',
@@ -978,13 +995,58 @@ describe('requestPasswordReset', () => {
expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, user);
});
- it('should reuse baseConfig for non-tenant user without calling resolveAppConfigForUser', async () => {
- findUser.mockResolvedValue({ _id: 'user-no-tenant', email: '[email protected]' });
+ it('should resolve the account config for a user without a tenant', async () => {
+ const user = { _id: 'user-no-tenant', email: '[email protected]', role: 'USER' };
+ findUser.mockResolvedValue(user);
const req = { body: { email: '[email protected]' }, ip: '127.0.0.1' };
await requestPasswordReset(req);
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, user);
+ });
+
+ it('should keep the pre-auth config when no account exists', async () => {
+ findUser.mockResolvedValue(null);
+
+ const req = { body: { email: '[email protected]' }, ip: '127.0.0.1' };
+ const result = await requestPasswordReset(req);
+
expect(resolveAppConfigForUser).not.toHaveBeenCalled();
+ expect(result.message).toContain('If an account with that email exists');
+ });
+
+ it("should return the generic response when a role's config blocks the domain", async () => {
+ const user = { _id: 'user-no-tenant', email: '[email protected]', role: 'USER' };
+ findUser.mockResolvedValue(user);
+ isEmailDomainAllowed.mockReturnValueOnce(true).mockReturnValueOnce(false);
+
+ const req = { body: { email: '[email protected]' }, 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');
+ expect(createToken).not.toHaveBeenCalled();
+ });
+
+ it("issues no link, with the generic answer, when the account's config cannot be read", async () => {
+ const user = { _id: 'user-no-tenant', email: '[email protected]', role: 'USER' };
+ findUser.mockResolvedValue(user);
+ getAppConfig.mockResolvedValue({ registration: { allowedDomains: ['example.com'] } });
+ resolveAppConfigForUser.mockRejectedValue(new Error('role read failed [email protected]'));
+
+ const req = { body: { email: '[email protected]' }, ip: '127.0.0.1' };
+ const result = await requestPasswordReset(req);
+
+ expect(result).toEqual({
+ message: 'If an account with that email exists, a password reset link has been sent to it.',
+ });
+ expect(deleteTokens).not.toHaveBeenCalled();
+ expect(createToken).not.toHaveBeenCalled();
+ expect(logger.error).toHaveBeenCalledWith(
+ "[requestPasswordReset] Failed to resolve the account's config; no link issued:",
+ { type: 'Error' },
+ );
+ expect(loggedText()).not.toContain('[email protected]');
});
it('should return generic response when tenant config blocks the domain (non-enumerable)', async () => {
@@ -1771,31 +1833,28 @@ describe('registerUser - allowedDomains admin-panel override', () => {
countUsers.mockResolvedValue(0);
});
- it('should resolve the full app config so admin-panel overrides on the __base__ principal apply', async () => {
+ it('should resolve the pre-auth config so admin-panel overrides on the __base__ principal apply', async () => {
// Regression guard for getAppConfig({ baseOnly: true }): that option short-circuits
// before the DB override merge, which silently ignores any admin-panel edits to
// registration.allowedDomains (the admin panel writes overrides to the __base__
- // principal in the configs collection). registerUser must request the merged config
- // so the global __base__ override is honored, same as it is for SSO callbacks via
- // checkDomainAllowed.
+ // principal in the configs collection). registerUser uses the same pre-auth config
+ // as the SSO, LDAP and password-reset checks. The tenant comes from ALS
+ // (preAuthTenantMiddleware), which scopes both the query and the cache key.
await registerUser(validUser);
+ expect(resolvePreAuthAppConfig).toHaveBeenCalledWith(getAppConfig);
expect(getAppConfig).toHaveBeenCalledTimes(1);
- expect(getAppConfig).toHaveBeenCalledWith({});
expect(getAppConfig).not.toHaveBeenCalledWith(expect.objectContaining({ baseOnly: true }));
});
- it('should pass tenantId from ALS so the merged-config cache key matches tenant-scoped DB queries', async () => {
- // /api/auth runs through preAuthTenantMiddleware, which puts a tenantId into
- // AsyncLocalStorage. Mongoose queries inside getApplicableConfigs are scoped by ALS,
- // but the per-principal merged-config cache key uses the explicit tenantId param.
- // If we don't forward the ALS tenantId, tenant A's request caches at `__default__`
- // and a later tenant B request can hit that entry — leaking config across tenants.
- getTenantId.mockReturnValue('tenant-x');
+ it('should fail closed when the pre-auth config cannot be read', async () => {
+ getAppConfig.mockRejectedValue(new Error('override read failed'));
- await registerUser(validUser);
+ const result = await registerUser(validUser);
- expect(getAppConfig).toHaveBeenCalledWith({ tenantId: 'tenant-x' });
+ expect(result).toEqual({ status: 500, message: 'Something went wrong' });
+ expect(findUser).not.toHaveBeenCalled();
+ expect(createUser).not.toHaveBeenCalled();
});
it('does not bootstrap a tenant-scoped registrant as an administrator', async () => {
@@ -1829,6 +1888,88 @@ describe('registerUser - allowedDomains admin-panel override', () => {
);
});
+ describe('the config of the role the account is created with', () => {
+ const roleConfigs = {
+ USER: { registration: { allowedDomains: ['corp.example'] } },
+ ADMIN: {
+ registration: { allowedDomains: ['example.com'] },
+ balance: { enabled: true, startBalance: 100 },
+ },
+ };
+
+ beforeEach(() => {
+ countUsers.mockResolvedValue(1);
+ resolveAppConfigForUser.mockImplementation(
+ async (_getAppConfig, { role }) => roleConfigs[role],
+ );
+ });
+
+ afterEach(() => {
+ resolveAppConfigForUser.mockImplementation(async () => ({}));
+ });
+
+ it("refuses a domain the USER role's list excludes, creating nothing", async () => {
+ isEmailDomainAllowed.mockReturnValueOnce(true).mockReturnValueOnce(false);
+
+ const result = await registerUser(validUser);
+
+ expect(result).toEqual({ status: 403, message: expect.stringMatching(/cannot be used/i) });
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, { role: 'USER' });
+ expect(isEmailDomainAllowed).toHaveBeenLastCalledWith(validUser.email, ['corp.example']);
+ expect(createUser).not.toHaveBeenCalled();
+ });
+
+ it('gives a registered email the same refusal, so it reveals no account', async () => {
+ isEmailDomainAllowed.mockReturnValueOnce(true).mockReturnValueOnce(false);
+ findUser.mockResolvedValue({ _id: 'existing-id', email: validUser.email });
+
+ const result = await registerUser(validUser);
+
+ expect(result.status).toBe(403);
+ expect(createUser).not.toHaveBeenCalled();
+ });
+
+ it("creates the deployment's first account under the ADMIN role's config", async () => {
+ countUsers.mockResolvedValue(0);
+ createUser.mockResolvedValue({ _id: 'new-user', emailVerified: true });
+
+ const result = await registerUser(validUser);
+
+ expect(result.status).toBe(200);
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, { role: 'ADMIN' });
+ expect(createUser).toHaveBeenCalledWith(
+ expect.objectContaining({ role: 'ADMIN' }),
+ roleConfigs.ADMIN.balance,
+ expect.any(Boolean),
+ true,
+ );
+ });
+
+ it('checks the role a trusted caller creates the account with', async () => {
+ createUser.mockResolvedValue({ _id: 'new-user', emailVerified: true });
+
+ const result = await registerUser(validUser, { role: 'ADMIN' });
+
+ expect(result.status).toBe(200);
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, { role: 'ADMIN' });
+ expect(createUser).toHaveBeenCalledWith(
+ expect.objectContaining({ role: 'ADMIN' }),
+ roleConfigs.ADMIN.balance,
+ expect.any(Boolean),
+ true,
+ );
+ });
+
+ it("fails closed when the role's config cannot be read", async () => {
+ resolveAppConfigForUser.mockRejectedValue(new Error('role read failed'));
+
+ const result = await registerUser(validUser);
+
+ expect(result).toEqual({ status: 500, message: 'Something went wrong' });
+ expect(createUser).not.toHaveBeenCalled();
+ });
+ });
+
it('should block registration when the resolved allowedDomains rejects the email', async () => {
isEmailDomainAllowed.mockReturnValue(false);
diff --git a/api/strategies/ldapStrategy.js b/api/strategies/ldapStrategy.js
index bf3ee10467..df4094f6a7 100644
--- a/api/strategies/ldapStrategy.js
+++ b/api/strategies/ldapStrategy.js
@@ -8,6 +8,7 @@ const {
getBalanceConfig,
provisionLdapUser,
isEmailDomainAllowed,
+ resolvePreAuthAppConfig,
resolveAppConfigForUser,
} = require('@librechat/api');
const {
@@ -128,7 +129,7 @@ const ldapLogin = new LdapStrategy(ldapOptions, async (userinfo, done) => {
// 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 });
+ const baseConfig = await resolvePreAuthAppConfig(getAppConfig);
if (!isEmailDomainAllowed(mail, baseConfig?.registration?.allowedDomains)) {
logger.error(`[LDAP Strategy] Authentication blocked - email domain not allowed`);
return done(null, false, { message: 'Email domain not allowed' });
@@ -139,7 +140,7 @@ const ldapLogin = new LdapStrategy(ldapOptions, async (userinfo, done) => {
return done(null, false, { message: ErrorTypes.AUTH_FAILED });
}
- const appConfig = found.user?.tenantId
+ const appConfig = found.user
? await resolveAppConfigForUser(getAppConfig, found.user)
: baseConfig;
diff --git a/api/strategies/ldapStrategy.spec.js b/api/strategies/ldapStrategy.spec.js
index 7e93823fdc..ab5a6c5c67 100644
--- a/api/strategies/ldapStrategy.spec.js
+++ b/api/strategies/ldapStrategy.spec.js
@@ -16,6 +16,7 @@ jest.mock('@librechat/api', () => ({
isEmailDomainAllowed: jest.fn(() => true),
getBalanceConfig: jest.fn(() => ({ enabled: false })),
resolveAppConfigForUser: jest.fn(async (_getAppConfig, _user) => ({})),
+ resolvePreAuthAppConfig: jest.requireActual('@librechat/api').resolvePreAuthAppConfig,
}));
jest.mock('~/models', () => ({
@@ -78,6 +79,8 @@ describe('ldapStrategy', () => {
updateUser.mockReset().mockImplementation(async (id, user) => ({ _id: id, ...user }));
countUsers.mockReset().mockResolvedValue(0);
isEmailDomainAllowed.mockReset().mockReturnValue(true);
+ getAppConfig.mockReset().mockResolvedValue({});
+ resolveAppConfigForUser.mockReset().mockResolvedValue({});
// Ensure requiring the strategy sets up the verify callback
jest.isolateModules(() => {
@@ -213,7 +216,7 @@ describe('ldapStrategy', () => {
expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existing);
});
- it('uses baseConfig for new user without calling resolveAppConfigForUser', async () => {
+ it('checks a new user against the pre-auth config, then the config of the role it is created with', async () => {
findUser.mockResolvedValue(null);
const userinfo = {
@@ -226,7 +229,82 @@ describe('ldapStrategy', () => {
await callVerify(userinfo);
expect(resolveAppConfigForUser).not.toHaveBeenCalled();
- expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(getAppConfig).toHaveBeenCalledWith({ skipRuntimeAugmentation: true, failClosed: true });
+ expect(getAppConfig).toHaveBeenCalledWith({
+ role: 'ADMIN',
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ });
+ expect(getAppConfig).not.toHaveBeenCalledWith({ baseOnly: true });
+ });
+
+ it("refuses a first sign-in the USER role's domain list excludes, creating nothing", async () => {
+ countUsers.mockResolvedValue(3);
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ getAppConfig.mockImplementation(async (options) =>
+ options?.role === 'USER' ? { registration: { allowedDomains: ['other.example'] } } : {},
+ );
+
+ const userinfo = { uid: 'uid-new', mail: '[email protected]', cn: 'New User' };
+ const { user, info } = await callVerify(userinfo);
+
+ expect(user).toBe(false);
+ expect(info).toEqual({ message: 'Email domain not allowed' });
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('resolves the account config for an existing user without a tenant', async () => {
+ const existing = {
+ _id: 'u4',
+ provider: 'ldap',
+ email: '[email protected]',
+ ldapId: 'uid-deployment',
+ role: 'USER',
+ };
+ findUser.mockResolvedValue(existing);
+ resolveAppConfigForUser.mockResolvedValue({
+ registration: { allowedDomains: ['other.example'] },
+ });
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+
+ const userinfo = { uid: 'uid-deployment', mail: '[email protected]', cn: 'Dep' };
+ const { user, info } = await callVerify(userinfo);
+
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existing);
+ expect(user).toBe(false);
+ expect(info).toEqual({ message: 'Email domain not allowed' });
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('rejects before the user lookup when the __base__ override excludes the domain', async () => {
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ getAppConfig.mockImplementation(async (options) =>
+ options?.baseOnly ? {} : { registration: { allowedDomains: ['corp.example'] } },
+ );
+
+ const userinfo = { uid: 'uid-new', mail: '[email protected]', cn: 'New User' };
+ const { user, info } = await callVerify(userinfo);
+
+ expect(user).toBe(false);
+ expect(info).toEqual({ message: 'Email domain not allowed' });
+ expect(findUser).not.toHaveBeenCalled();
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ });
+
+ it('fails the login when the pre-auth config cannot be read', async () => {
+ getAppConfig.mockRejectedValue(new Error('override read failed'));
+
+ const userinfo = { uid: 'uid-new', mail: '[email protected]', cn: 'New User' };
+
+ await expect(callVerify(userinfo)).rejects.toThrow('override read failed');
+ expect(findUser).not.toHaveBeenCalled();
});
it('should block login when tenant config restricts the domain', async () => {
@@ -312,7 +390,19 @@ describe('ldapStrategy', () => {
expect(user).toBe(false);
expect(info).toEqual({ message: 'Email domain not allowed' });
expect(updateUser).not.toHaveBeenCalled();
- getAppConfig.mockResolvedValue({});
+ });
+
+ it("fails the login when the recovered account's role policy rejects the email", async () => {
+ getAppConfig.mockImplementation(async (options) =>
+ options?.role === 'USER' ? { registration: { allowedDomains: ['other.example'] } } : {},
+ );
+ raceCreateWith({ _id: 'winner-id', provider: 'ldap', ldapId: 'uid-race', role: 'USER' });
+
+ const { user, info } = await callVerify(userinfo);
+
+ expect(user).toBe(false);
+ expect(info).toEqual({ message: 'Email domain not allowed' });
+ expect(updateUser).not.toHaveBeenCalled();
});
it('fails the login when the recovered account belongs to another provider', async () => {
diff --git a/api/strategies/openidStrategy.js b/api/strategies/openidStrategy.js
index 1d56aafb93..b762f2dde4 100644
--- a/api/strategies/openidStrategy.js
+++ b/api/strategies/openidStrategy.js
@@ -22,6 +22,7 @@ const {
getAvatarSaveParams,
isEmailDomainAllowed,
getAvatarFileStrategy,
+ resolvePreAuthAppConfig,
resolveAppConfigForUser,
getOpenIdProxyDispatcher,
getOpenIdRoleSyncOptions,
@@ -488,10 +489,12 @@ function getRoleSource(kind, label, tokenset, userinfo) {
}
/**
- * Applies generic OpenID role sync to the request-local user before the existing final update.
+ * Returns the role generic OpenID role sync gives `account`, or its current role when sync is
+ * off, skipped or keeps it. Role definitions are tenant-scoped, so configured roles are validated
+ * in the account's tenant, or in the request's for an account not created yet.
*/
-async function applyOpenIdRoleSync({
- user,
+async function selectOpenIdSyncRole({
+ account,
username,
tokenset,
claims,
@@ -500,14 +503,14 @@ async function applyOpenIdRoleSync({
}) {
const options = getOpenIdRoleSyncOptions();
if (!options.enabled) {
- return;
+ return account.role;
}
- if (user.role === SystemRoles.ADMIN) {
+ if (account.role === SystemRoles.ADMIN) {
logger.info(
`[openidStrategy] OpenID role sync skipped for ${username}; existing ADMIN role is not managed by generic role sync`,
);
- return;
+ return account.role;
}
const resolveGroupOverage = async () =>
@@ -526,7 +529,7 @@ async function applyOpenIdRoleSync({
logger.warn(
`[openidStrategy] OpenID role sync skipped; claim '${options.claim}' was not found, invalid, or unresolved`,
);
- return;
+ return account.role;
}
const libreChatRoles = {
@@ -536,27 +539,104 @@ async function applyOpenIdRoleSync({
logPrefix: '[openidStrategy]',
};
- /** Role definitions are tenant-scoped, so validate configured roles in the matched user's tenant. */
- const { rolePriority, fallbackRole } = user?.tenantId
- ? await tenantStorage.run({ tenantId: user.tenantId }, async () =>
+ const { rolePriority, fallbackRole } = account.tenantId
+ ? await tenantStorage.run({ tenantId: account.tenantId }, async () =>
getLibreChatRolesForOpenIdSync(libreChatRoles),
)
: await getLibreChatRolesForOpenIdSync(libreChatRoles);
const result = selectOpenIdRole({
- currentRole: user.role,
+ currentRole: account.role,
openIdRoleValues,
rolePriority,
fallbackRole,
});
+ return result.selectedRole || account.role;
+}
- if (!result.selectedRole || result.selectedRole === user.role) {
- return;
+/**
+ * Whether the token carries `OPENID_ADMIN_ROLE` at the configured path, or `undefined` when no
+ * admin role claim is configured.
+ */
+async function hasOpenIdAdminRole({ tokenset, claims, userinfo, resolvedOverageGroups }) {
+ const adminRole = process.env.OPENID_ADMIN_ROLE;
+ const adminRoleParameterPath = process.env.OPENID_ADMIN_ROLE_PARAMETER_PATH;
+ const adminRoleTokenKind = process.env.OPENID_ADMIN_ROLE_TOKEN_KIND;
+ if (!adminRole || !adminRoleParameterPath || !adminRoleTokenKind) {
+ return undefined;
}
- logger.info(
- `[openidStrategy] OpenID role sync updated role for ${username}: ${user.role || 'unset'} -> ${result.selectedRole}`,
- );
- user.role = result.selectedRole;
+ const adminRoleObject = getRoleSource(adminRoleTokenKind, 'admin role', tokenset, userinfo);
+
+ let adminRoles = get(adminRoleObject, adminRoleParameterPath);
+
+ // Handle Azure AD group overage for admin role when using ID token groups
+ if (adminRoleTokenKind === 'id' && adminRoleParameterPath === 'groups' && adminRoleObject) {
+ const hasAdminOverage =
+ adminRoleObject.hasgroups ||
+ (adminRoleObject._claim_names?.groups &&
+ adminRoleObject._claim_sources?.[adminRoleObject._claim_names.groups]);
+
+ if (hasAdminOverage) {
+ const overageGroups =
+ resolvedOverageGroups ||
+ (await resolveGroupsFromOverage(tokenset.access_token, claims.sub));
+ if (overageGroups) {
+ adminRoles = overageGroups;
+ }
+ }
+ }
+
+ let adminRoleValues = [];
+ if (Array.isArray(adminRoles)) {
+ adminRoleValues = adminRoles;
+ } else if (typeof adminRoles === 'string') {
+ adminRoleValues = adminRoles.split(/[\s,]+/).filter(Boolean);
+ }
+
+ return Boolean(adminRoles && (adminRoles === true || adminRoleValues.includes(adminRole)));
+}
+
+/**
+ * Decides, without changing the account, the role this token's claims give an account in
+ * `account.role` (in `account.tenantId`, or the request's tenant for an account not created yet):
+ * the admin role claim grants ADMIN, or moves an ADMIN without it to USER, and generic role sync
+ * maps the rest.
+ */
+async function resolveOpenIdClaimsRole(account, claimsContext) {
+ const adminClaim = await hasOpenIdAdminRole(claimsContext);
+ if (adminClaim) {
+ return { role: SystemRoles.ADMIN, adminRoleGranted: true, demoted: false };
+ }
+
+ const demoted = adminClaim === false && account.role === SystemRoles.ADMIN;
+ const role = demoted ? SystemRoles.USER : account.role;
+ const syncedRole = await selectOpenIdSyncRole({
+ ...claimsContext,
+ account: { ...account, role },
+ });
+ return { role: syncedRole, adminRoleGranted: false, demoted };
+}
+
+/** Moves the request-local `user` into the role `claimsRole` decided, before the final update. */
+function applyOpenIdClaimsRole(user, username, { role, adminRoleGranted, demoted }) {
+ if (adminRoleGranted) {
+ logger.info(
+ `[openidStrategy] User ${user._id} is an admin based on role: ${process.env.OPENID_ADMIN_ROLE}`,
+ );
+ }
+ if (demoted) {
+ logger.info(
+ `[openidStrategy] User ${user._id} demoted from admin - role no longer present in token`,
+ );
+ }
+
+ const syncedFrom = demoted ? SystemRoles.USER : user.role;
+ if (!adminRoleGranted && role !== syncedFrom) {
+ logger.info(
+ `[openidStrategy] OpenID role sync updated role for ${username}: ${syncedFrom || 'unset'} -> ${role}`,
+ );
+ }
+ user.role = role;
}
/**
@@ -582,7 +662,7 @@ async function processOpenIDAuth(tokenset, existingUsersOnly = false) {
const email = getOpenIdEmail(userinfo);
const openidIssuer = getOpenIdIssuer(claims, openidConfig);
- const baseConfig = await getAppConfig({ baseOnly: true });
+ const baseConfig = await resolvePreAuthAppConfig(getAppConfig);
if (!isEmailDomainAllowed(email, baseConfig?.registration?.allowedDomains)) {
logger.error(
`[OpenID Strategy] Authentication blocked - email domain not allowed [Identifier: ${email}]`,
@@ -606,7 +686,7 @@ async function processOpenIDAuth(tokenset, existingUsersOnly = false) {
throw new Error(ErrorTypes.AUTH_FAILED);
}
- let appConfig = user?.tenantId ? await resolveAppConfigForUser(getAppConfig, user) : baseConfig;
+ let appConfig = user ? await resolveAppConfigForUser(getAppConfig, user) : baseConfig;
if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
logger.error(
@@ -697,91 +777,47 @@ async function processOpenIDAuth(tokenset, existingUsersOnly = false) {
idOnTheSource: userinfo.oid,
};
- if (!user) {
- ({ user, appConfig } = await createOpenIDUser({
+ const claimsContext = { username, tokenset, claims, userinfo, resolvedOverageGroups };
+ let claimsRole;
+ if (user) {
+ user = applyOpenIDProfile(user, profile);
+ } else {
+ const newUserClaimsRole = await resolveOpenIdClaimsRole(
+ { role: SystemRoles.USER },
+ claimsContext,
+ );
+ const provisioned = await createOpenIDUser({
lookup,
profile,
- appConfig,
+ claimedRole: newUserClaimsRole.role,
getAppConfig,
getBalanceConfig,
createUserIfAbsent,
findBalanceByUser,
- }));
- } else {
- user = applyOpenIDProfile(user, profile);
+ });
+ ({ user, appConfig } = provisioned);
+ claimsRole = provisioned.created ? newUserClaimsRole : undefined;
}
const roleBeforeClaims = user.role;
- const adminRole = process.env.OPENID_ADMIN_ROLE;
- const adminRoleParameterPath = process.env.OPENID_ADMIN_ROLE_PARAMETER_PATH;
- const adminRoleTokenKind = process.env.OPENID_ADMIN_ROLE_TOKEN_KIND;
- let adminRoleGranted = false;
-
- if (adminRole && adminRoleParameterPath && adminRoleTokenKind) {
- const adminRoleObject = getRoleSource(adminRoleTokenKind, 'admin role', tokenset, userinfo);
-
- let adminRoles = get(adminRoleObject, adminRoleParameterPath);
-
- // Handle Azure AD group overage for admin role when using ID token groups
- if (adminRoleTokenKind === 'id' && adminRoleParameterPath === 'groups' && adminRoleObject) {
- const hasAdminOverage =
- adminRoleObject.hasgroups ||
- (adminRoleObject._claim_names?.groups &&
- adminRoleObject._claim_sources?.[adminRoleObject._claim_names.groups]);
-
- if (hasAdminOverage) {
- const overageGroups =
- resolvedOverageGroups ||
- (await resolveGroupsFromOverage(tokenset.access_token, claims.sub));
- if (overageGroups) {
- adminRoles = overageGroups;
- }
- }
- }
-
- let adminRoleValues = [];
- if (Array.isArray(adminRoles)) {
- adminRoleValues = adminRoles;
- } else if (typeof adminRoles === 'string') {
- adminRoleValues = adminRoles.split(/[\s,]+/).filter(Boolean);
- }
-
- if (adminRoles && (adminRoles === true || adminRoleValues.includes(adminRole))) {
- user.role = SystemRoles.ADMIN;
- adminRoleGranted = true;
- logger.info(`[openidStrategy] User ${user._id} is an admin based on role: ${adminRole}`);
- } else if (user.role === SystemRoles.ADMIN) {
- user.role = SystemRoles.USER;
- logger.info(
- `[openidStrategy] User ${user._id} demoted from admin - role no longer present in token`,
+ claimsRole ??= await resolveOpenIdClaimsRole(user, claimsContext);
+ applyOpenIdClaimsRole(user, username, claimsRole);
+
+ /**
+ * The earlier login-policy check ran with the role the account had before this token's
+ * claims: its stored role, or the role it was created with (a new account was also admitted
+ * under the role its claims move it into before it was created). If the admin role claim or
+ * role sync moved it into a different role, re-resolve its config (in its tenant, if any) and
+ * re-enforce `allowedDomains`, so the new role's overrides are honored and a token cannot
+ * complete login under the previous role's looser policy.
+ */
+ if (user.role !== roleBeforeClaims) {
+ appConfig = await resolveAppConfigForUser(getAppConfig, user);
+ if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) {
+ logger.error(
+ `[OpenID Strategy] Authentication blocked after a role change - email domain not allowed [Identifier: ${email}]`,
);
- }
- }
-
- if (!adminRoleGranted) {
- const roleBeforeSync = user.role;
- await applyOpenIdRoleSync({
- user,
- username,
- tokenset,
- claims,
- userinfo,
- resolvedOverageGroups,
- });
- /**
- * The earlier login-policy check ran with the pre-sync role. If role sync moved a
- * tenant user into a different role, re-resolve the tenant config and re-enforce
- * `allowedDomains` so role-scoped overrides for the new role are honored and a token
- * cannot complete login under the previous role's looser policy.
- */
- if (user?.tenantId && user.role !== roleBeforeSync) {
- const postSyncConfig = await resolveAppConfigForUser(getAppConfig, user);
- if (!isEmailDomainAllowed(email, postSyncConfig?.registration?.allowedDomains)) {
- logger.error(
- `[OpenID Strategy] Authentication blocked after role sync - email domain not allowed [Identifier: ${email}]`,
- );
- throw new Error('Email domain not allowed');
- }
+ throw new Error('Email domain not allowed');
}
}
diff --git a/api/strategies/openidStrategy.spec.js b/api/strategies/openidStrategy.spec.js
index d62eb20200..bcfa31874b 100644
--- a/api/strategies/openidStrategy.spec.js
+++ b/api/strategies/openidStrategy.spec.js
@@ -6,6 +6,7 @@ const { findUser, updateUser, findRolesByNames, createUserIfAbsent } = require('
const {
getOpenIdProxyDispatcher,
resolveAppConfigForUser,
+ isEmailDomainAllowed,
getOpenIdIssuer,
isEnabled,
} = require('@librechat/api');
@@ -101,6 +102,7 @@ jest.mock('~/models', () => ({
updateUser: jest.fn(),
findRolesByNames: jest.fn(),
findBalanceByUser: jest.fn(),
+ recordAuditEntry: jest.fn(),
}));
jest.mock('@librechat/data-schemas', () => ({
...jest.requireActual('@librechat/api'),
@@ -218,6 +220,9 @@ describe('setupOpenId', () => {
// Clear previous mock calls and reset implementations
jest.clearAllMocks();
isEnabled.mockImplementation(jest.requireActual('@librechat/api').isEnabled);
+ isEmailDomainAllowed.mockReset().mockReturnValue(true);
+ resolveAppConfigForUser.mockReset().mockResolvedValue({});
+ getAppConfig.mockReset().mockResolvedValue({});
require('~/cache/getLogStores').mockImplementation(() => ({
get: jest.fn(),
set: jest.fn(),
@@ -1295,7 +1300,7 @@ describe('setupOpenId', () => {
const { user } = await validate(tokenset);
expect(user).toBeTruthy();
- expect(user.role).toBeUndefined();
+ expect(user.role).toBe('USER');
});
it('reuses already-resolved overage groups for admin role check (no duplicate Graph call)', async () => {
@@ -1386,7 +1391,7 @@ describe('setupOpenId', () => {
// No Graph call since admin uses access token (not id)
expect(undici.fetch).not.toHaveBeenCalled();
- expect(user.role).toBeUndefined();
+ expect(user.role).toBe('USER');
});
it('resolves admin via Graph independently when OPENID_REQUIRED_ROLE is not configured', async () => {
@@ -1430,7 +1435,7 @@ describe('setupOpenId', () => {
const { user } = await validate(tokenset);
expect(user).toBeTruthy();
- expect(user.role).toBeUndefined();
+ expect(user.role).toBe('USER');
});
it('denies login and logs error when OBO exchange throws', async () => {
@@ -1537,7 +1542,8 @@ describe('setupOpenId', () => {
it('should save CloudFront IdP avatars under the shared avatar prefix', async () => {
const { getStrategyFunctions } = require('~/server/services/Files/strategies');
- getAppConfig.mockResolvedValueOnce({ fileStrategy: mockCloudfrontFileSource });
+ getAppConfig.mockResolvedValue({ fileStrategy: mockCloudfrontFileSource });
+ resolveAppConfigForUser.mockResolvedValue({ fileStrategy: mockCloudfrontFileSource });
const { user } = await validate(tokenset);
const strategyResult =
@@ -1720,8 +1726,8 @@ describe('setupOpenId', () => {
// Act
const { user } = await validate(tokenset);
- // Assert – verify that the user role is not defined
- expect(user.role).toBeUndefined();
+ // Assert – the user keeps the USER role it was created with
+ expect(user.role).toBe('USER');
});
describe('OpenID role sync', () => {
@@ -1757,7 +1763,7 @@ describe('setupOpenId', () => {
const { user } = await validate(tokenset);
- expect(user.role).toBeUndefined();
+ expect(user.role).toBe('USER');
expect(findRolesByNames).not.toHaveBeenCalled();
});
@@ -1964,6 +1970,43 @@ describe('setupOpenId', () => {
expect(details).toEqual({ message: 'Email domain not allowed' });
});
+ it('re-enforces login policy after role sync changes the role of a user without a tenant', async () => {
+ const existingUser = {
+ _id: 'existingDeploymentUserId',
+ provider: 'openid',
+ email: tokenset.claims().email,
+ openidId: tokenset.claims().sub,
+ username: 'deploymentuser',
+ name: 'Deployment User',
+ role: 'USER',
+ };
+ findUser.mockImplementation(async (query) => {
+ if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) {
+ return existingUser;
+ }
+ return null;
+ });
+ jwtDecode.mockReturnValue({
+ roles: ['requiredRole', 'BASIC-USER'],
+ permissions: ['not-admin'],
+ });
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ resolveAppConfigForUser.mockImplementation(async (_getAppConfig, user) =>
+ user.role === 'BASIC-USER' ? { registration: { allowedDomains: ['restricted.com'] } } : {},
+ );
+
+ const { user, details } = await validate(tokenset);
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(resolveAppConfigForUser).toHaveBeenLastCalledWith(
+ getAppConfig,
+ expect.objectContaining({ _id: 'existingDeploymentUserId', role: 'BASIC-USER' }),
+ );
+ });
+
it('reuses required-role overage groups for role sync', async () => {
process.env.OPENID_REQUIRED_ROLE = 'group-required';
process.env.OPENID_REQUIRED_ROLE_PARAMETER_PATH = 'groups';
@@ -2299,7 +2342,7 @@ describe('setupOpenId', () => {
const { user } = await validate(tokenset);
- expect(user.role).toBeUndefined();
+ expect(user.role).toBe('USER');
});
it('should handle array admin role value', async () => {
@@ -2333,7 +2376,7 @@ describe('setupOpenId', () => {
const { user } = await validate(tokenset);
- expect(user.role).toBeUndefined();
+ expect(user.role).toBe('USER');
});
it('should grant admin when admin role claim is a space-separated string containing the admin role', async () => {
@@ -2373,7 +2416,7 @@ describe('setupOpenId', () => {
const { user } = await validate(tokenset);
// Assert – admin role is not granted
- expect(user.role).toBeUndefined();
+ expect(user.role).toBe('USER');
});
it('should handle nested path with special characters in keys', async () => {
@@ -2594,13 +2637,253 @@ describe('setupOpenId', () => {
expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existingUser);
});
- it('should use baseConfig for new user without calling resolveAppConfigForUser', async () => {
+ it('should use the pre-auth config for a new user without calling resolveAppConfigForUser', async () => {
findUser.mockResolvedValue(null);
+ jwtDecode.mockReturnValue({ roles: ['requiredRole'], permissions: ['not-admin'] });
await validate(tokenset);
expect(resolveAppConfigForUser).not.toHaveBeenCalled();
- expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(getAppConfig).toHaveBeenCalledWith({
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ });
+ expect(getAppConfig).not.toHaveBeenCalledWith({ baseOnly: true });
+ });
+
+ describe('first login under the role its claims assign', () => {
+ const roleConfigRead = (role) => ({ role, skipRuntimeAugmentation: true, failClosed: true });
+
+ /** Resolves configs and email domains for real over `getAppConfig`; `refusedRole`'s list excludes the email. */
+ const refuseDomainIn = (refusedRole) => {
+ const actual = jest.requireActual('@librechat/api');
+ isEmailDomainAllowed.mockImplementation(actual.isEmailDomainAllowed);
+ resolveAppConfigForUser.mockImplementation(actual.resolveAppConfigForUser);
+ getAppConfig.mockImplementation(async (options) =>
+ options?.role === refusedRole
+ ? { registration: { allowedDomains: ['restricted.com'] } }
+ : {},
+ );
+ };
+
+ const enableRoleSync = (role) => {
+ process.env.OPENID_ROLE_SYNC_ENABLED = 'true';
+ process.env.OPENID_ROLE_SYNC_SOURCE = 'id';
+ process.env.OPENID_ROLE_SYNC_CLAIM = 'roles';
+ process.env.OPENID_ROLE_SYNC_ROLE_PRIORITY = role;
+ jwtDecode.mockReturnValue({ roles: ['requiredRole', role], permissions: ['not-admin'] });
+ };
+
+ it('refuses a first login the admin-claim role excludes before creating the account', async () => {
+ refuseDomainIn('ADMIN');
+
+ const { user, details } = await validate(tokenset);
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead('ADMIN'));
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('refuses a first login the role-sync role excludes before creating the account', async () => {
+ enableRoleSync('BASIC-USER');
+ refuseDomainIn('BASIC-USER');
+
+ const { user, details } = await validate(tokenset);
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead('BASIC-USER'));
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('refuses a first login the USER role excludes even when the claimed role admits it', async () => {
+ refuseDomainIn('USER');
+
+ const { user, details } = await validate(tokenset);
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ });
+
+ it('creates an admitted first login as USER, then moves it into the claimed role', async () => {
+ const { recordAuditEntry } = require('~/models');
+ enableRoleSync('BASIC-USER');
+ refuseDomainIn('NONE');
+
+ const { user } = await validate(tokenset);
+
+ expect(user.role).toBe('BASIC-USER');
+ expect(createUserIfAbsent).toHaveBeenCalledWith(
+ expect.objectContaining({ role: 'USER' }),
+ expect.anything(),
+ );
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead('USER'));
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead('BASIC-USER'));
+ expect(findRolesByNames).toHaveBeenCalledTimes(1);
+ expect(updateUser).toHaveBeenCalledWith(
+ 'newUserId',
+ expect.objectContaining({ role: 'BASIC-USER' }),
+ );
+ expect(recordAuditEntry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: { previousRole: 'USER', role: 'BASIC-USER', source: 'openid_login' },
+ }),
+ );
+ });
+
+ it('decides the claims again for the account a concurrent first login created', async () => {
+ delete process.env.OPENID_ADMIN_ROLE;
+ enableRoleSync('BASIC-USER');
+ const winner = {
+ _id: 'winnerAdminId',
+ provider: 'openid',
+ openidId: tokenset.claims().sub,
+ openidIssuer: 'https://fake-issuer.com',
+ email: tokenset.claims().email,
+ role: 'ADMIN',
+ };
+ let created = false;
+ findUser.mockImplementation(async (query) =>
+ created && query.openidId === winner.openidId ? winner : null,
+ );
+ createUserIfAbsent.mockImplementation(async () => {
+ created = true;
+ return { ok: false, error: { code: 'user_exists' } };
+ });
+
+ const { user } = await validate(tokenset);
+
+ expect(user.role).toBe('ADMIN');
+ expect(updateUser).toHaveBeenCalledWith(
+ 'winnerAdminId',
+ expect.objectContaining({ role: 'ADMIN' }),
+ );
+ });
+ });
+
+ it('re-checks an existing user the admin claim promotes to ADMIN', async () => {
+ const existingUser = {
+ _id: 'openid-promoted-user',
+ provider: 'openid',
+ openidId: '1234',
+ email: '[email protected]',
+ role: 'USER',
+ };
+ findUser.mockResolvedValue(existingUser);
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ resolveAppConfigForUser.mockImplementation(async (_getAppConfig, user) =>
+ user.role === 'ADMIN' ? { registration: { allowedDomains: ['restricted.com'] } } : {},
+ );
+
+ const { user, details } = await validate(tokenset);
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(resolveAppConfigForUser).toHaveBeenLastCalledWith(
+ getAppConfig,
+ expect.objectContaining({ _id: 'openid-promoted-user', role: 'ADMIN' }),
+ );
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('re-checks an ADMIN the token no longer grants admin, under the USER role', async () => {
+ const existingUser = {
+ _id: 'openid-demoted-user',
+ provider: 'openid',
+ openidId: '1234',
+ email: '[email protected]',
+ role: 'ADMIN',
+ };
+ findUser.mockResolvedValue(existingUser);
+ jwtDecode.mockReturnValue({ roles: ['requiredRole'], permissions: ['not-admin'] });
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ resolveAppConfigForUser.mockImplementation(async (_getAppConfig, user) =>
+ user.role === 'USER' ? { registration: { allowedDomains: ['restricted.com'] } } : {},
+ );
+
+ const { user, details } = await validate(tokenset);
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(resolveAppConfigForUser).toHaveBeenLastCalledWith(
+ getAppConfig,
+ expect.objectContaining({ _id: 'openid-demoted-user', role: 'USER' }),
+ );
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('continues under the new role config once a role change passes the re-check', async () => {
+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');
+ const existingUser = {
+ _id: 'openid-promoted-user',
+ provider: 'openid',
+ openidId: '1234',
+ email: '[email protected]',
+ role: 'USER',
+ };
+ findUser.mockResolvedValue(existingUser);
+ resolveAppConfigForUser.mockImplementation(async (_getAppConfig, user) =>
+ user.role === 'ADMIN' ? { fileStrategy: mockCloudfrontFileSource } : {},
+ );
+
+ const { user } = await validate(tokenset);
+
+ expect(user.role).toBe('ADMIN');
+ expect(getStrategyFunctions).toHaveBeenLastCalledWith(mockCloudfrontFileSource);
+ });
+
+ it('does not re-resolve the config when the claims leave the role unchanged', async () => {
+ const existingUser = {
+ _id: 'openid-admin-user',
+ provider: 'openid',
+ openidId: '1234',
+ email: '[email protected]',
+ role: 'ADMIN',
+ };
+ findUser.mockResolvedValue(existingUser);
+
+ await validate(tokenset);
+
+ expect(resolveAppConfigForUser).toHaveBeenCalledTimes(1);
+ });
+
+ it('should resolve the account config for an existing user without a tenant', async () => {
+ const existingUser = {
+ _id: 'openid-deployment-user',
+ provider: 'openid',
+ openidId: '1234',
+ email: '[email protected]',
+ role: 'USER',
+ };
+ findUser.mockResolvedValue(existingUser);
+
+ await validate(tokenset);
+
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existingUser);
+ });
+
+ it('should reject before the user lookup when the __base__ override excludes the domain', async () => {
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ getAppConfig.mockImplementation(async (options) =>
+ options?.baseOnly ? {} : { registration: { allowedDomains: ['corp.example'] } },
+ );
+
+ const { user, details } = await validate(tokenset);
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(findUser).not.toHaveBeenCalled();
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
});
it('should block login when tenant config restricts the domain', async () => {
diff --git a/api/strategies/process.js b/api/strategies/process.js
index d8a9c02ba1..d376a13da2 100644
--- a/api/strategies/process.js
+++ b/api/strategies/process.js
@@ -89,8 +89,9 @@ const finishNewSocialUser = async (newUserId, avatarUrl, appConfig) => {
/**
* Creates a new user with the provided user details. If the file strategy is not local, the avatar URL is
* processed using the specified file strategy. The new user is saved to the database with the processed or
- * original avatar URL. When a concurrent first login created the account first, that account is handled as
- * an existing user instead.
+ * original avatar URL. The account is admitted under the config of the role it is created with, so an email
+ * domain that config excludes fails the login before anything is created. When a concurrent first login
+ * created the account first, that account is handled as an existing user instead.
*
* @param {Object} params - The parameters object for user creation.
* @param {string} params.email - The email of the new user.
@@ -100,7 +101,6 @@ const finishNewSocialUser = async (newUserId, avatarUrl, appConfig) => {
* @param {string} params.providerId - The provider-specific ID of the user.
* @param {string} params.username - The username of the new user.
* @param {string} params.name - The name of the new user.
- * @param {AppConfig} appConfig - The application configuration object.
* @param {boolean} [params.emailVerified=false] - Optional. Indicates whether the user's email is verified. Defaults to false.
* @param {SocialUserLookup} params.lookup - The login's lookup, repeated when the insert loses a concurrent first login.
*
@@ -117,7 +117,6 @@ const createSocialUser = async ({
providerId,
username,
name,
- appConfig,
emailVerified,
lookup,
}) =>
@@ -132,12 +131,11 @@ const createSocialUser = async ({
name,
emailVerified,
},
- appConfig,
getBalanceConfig,
getAppConfig,
createUserIfAbsent,
findBalanceByUser,
- finishNewUser: (user) => finishNewSocialUser(user._id, avatarUrl, appConfig),
+ finishNewUser: (user, appConfig) => finishNewSocialUser(user._id, avatarUrl, appConfig),
refreshExistingUser: (user, accountConfig) =>
handleExistingUser(user, avatarUrl, accountConfig, email),
});
diff --git a/api/strategies/process.test.js b/api/strategies/process.test.js
index 63fdad6734..8cc83a8fa6 100644
--- a/api/strategies/process.test.js
+++ b/api/strategies/process.test.js
@@ -313,6 +313,61 @@ describe('createSocialUser', () => {
expect(getUserById).toHaveBeenCalledWith('newUser123');
});
+ describe('under the config of the role the account is created with', () => {
+ const { getAppConfig } = require('~/server/services/Config');
+ const params = {
+ email: '[email protected]',
+ avatarUrl: 'https://example.com/avatar.png',
+ provider: 'google',
+ providerKey: 'googleId',
+ providerId: 'google-sub-123',
+ username: 'user',
+ name: 'User',
+ emailVerified: true,
+ lookup: {
+ findUser: jest.fn(),
+ provider: 'google',
+ providerId: 'google-sub-123',
+ email: '[email protected]',
+ },
+ };
+
+ afterEach(() => {
+ getAppConfig.mockResolvedValue({});
+ });
+
+ it("refuses a domain the USER role's list excludes before creating the account", async () => {
+ getAppConfig.mockImplementation(async (options) =>
+ options?.role === 'USER' ? { registration: { allowedDomains: ['other.example'] } } : {},
+ );
+
+ const login = createSocialUser(params);
+
+ await expect(login).rejects.toMatchObject({
+ code: ErrorTypes.AUTH_FAILED,
+ message: 'Email domain not allowed',
+ });
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ });
+
+ it("stores the new account's avatar with that config's file strategy", async () => {
+ process.env.CDN_PROVIDER = FileSources.local;
+ const processAvatar = jest.fn().mockResolvedValue('https://cdn.example/avatar.png');
+ getStrategyFunctions.mockReturnValue({ processAvatar });
+ resizeAvatar.mockResolvedValue(Buffer.from('avatar'));
+ getAppConfig.mockImplementation(async (options) =>
+ options?.role === 'USER' ? { fileStrategy: FileSources.s3 } : {},
+ );
+
+ await createSocialUser(params);
+
+ expect(getStrategyFunctions).toHaveBeenCalledWith(FileSources.s3);
+ expect(updateUser).toHaveBeenCalledWith('newUser123', {
+ avatar: 'https://cdn.example/avatar.png',
+ });
+ });
+ });
+
describe('concurrent first login', () => {
const params = {
diff --git a/api/strategies/samlStrategy.js b/api/strategies/samlStrategy.js
index bdfc060ec1..acfb0fdf37 100644
--- a/api/strategies/samlStrategy.js
+++ b/api/strategies/samlStrategy.js
@@ -12,6 +12,7 @@ const {
getAvatarFileStrategy,
getAvatarSaveParams,
resolveAppConfigForUser,
+ resolvePreAuthAppConfig,
resolveSamlSubject,
TRANSIENT_SAML_NAME_ID_FORMAT,
} = require('@librechat/api');
@@ -200,7 +201,7 @@ function createSamlCallback(existingUsersOnly = false) {
const userEmail = getEmail(profile) || '';
- const baseConfig = await getAppConfig({ baseOnly: true });
+ const baseConfig = await resolvePreAuthAppConfig(getAppConfig);
if (!isEmailDomainAllowed(userEmail, baseConfig?.registration?.allowedDomains)) {
logger.error(
'[samlStrategy] Authentication blocked because the email domain is not allowed',
@@ -214,12 +215,10 @@ function createSamlCallback(existingUsersOnly = false) {
}
let user = found.user;
- let appConfig = user?.tenantId
- ? await resolveAppConfigForUser(getAppConfig, user)
- : baseConfig;
+ let appConfig = user ? await resolveAppConfigForUser(getAppConfig, user) : baseConfig;
if (!isEmailDomainAllowed(userEmail, appConfig?.registration?.allowedDomains)) {
- logger.error('[samlStrategy] Authentication blocked by the tenant email-domain policy');
+ logger.error("[samlStrategy] Authentication blocked by the account's email-domain policy");
return done(null, false, { message: 'Email domain not allowed' });
}
diff --git a/api/strategies/samlStrategy.spec.js b/api/strategies/samlStrategy.spec.js
index 0e6af7853a..ebc911b837 100644
--- a/api/strategies/samlStrategy.spec.js
+++ b/api/strategies/samlStrategy.spec.js
@@ -66,6 +66,7 @@ jest.mock('@librechat/api', () => ({
: params;
}),
resolveAppConfigForUser: jest.fn(async (_getAppConfig, _user) => ({})),
+ resolvePreAuthAppConfig: jest.requireActual('@librechat/api').resolvePreAuthAppConfig,
resolveSamlSubject: jest.fn((profile) => ({ nameID: profile.nameID })),
TRANSIENT_SAML_NAME_ID_FORMAT: 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient',
}));
@@ -262,6 +263,8 @@ describe('setupSaml', () => {
beforeEach(async () => {
jest.clearAllMocks();
verifyCallbacks.clear();
+ getAppConfig.mockResolvedValue({});
+ require('@librechat/api').isEmailDomainAllowed.mockImplementation(() => true);
// Configure mocks
const { findUser, createUserIfAbsent, updateUser, claimSamlIdentity } = require('~/models');
@@ -564,6 +567,33 @@ u7wlOSk+oFzDIO/UILIA
getAppConfig.mockResolvedValue({});
});
+ it("fails the login when the recovered account's role policy rejects the email", async () => {
+ const { isEmailDomainAllowed } = require('@librechat/api');
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ getAppConfig.mockImplementation(async (options) =>
+ options?.role === 'USER' ? { registration: { allowedDomains: ['other.example'] } } : {},
+ );
+ raceCreateWith({
+ _id: 'winner-user-id',
+ provider: 'saml',
+ samlId: baseProfile.nameID,
+ email: baseProfile.email,
+ role: 'USER',
+ });
+
+ const result = await validate(baseProfile);
+
+ expect(result.user).toBe(false);
+ expect(result.details.message).toBe('Email domain not allowed');
+ expect(getAppConfig).toHaveBeenCalledWith({
+ role: 'USER',
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ });
+ });
+
it('fails the login when another provider took the email in the meantime', async () => {
const { claimSamlIdentity, updateUser } = require('~/models');
raceCreateWith({ _id: 'local-user-id', provider: 'local', email: baseProfile.email });
@@ -785,7 +815,7 @@ u7wlOSk+oFzDIO/UILIA
it('should save CloudFront SAML avatars under the shared avatar prefix', async () => {
const { getStrategyFunctions } = require('~/server/services/Files/strategies');
- getAppConfig.mockResolvedValueOnce({ fileStrategies: { avatar: FileSources.cloudfront } });
+ getAppConfig.mockResolvedValue({ fileStrategies: { avatar: FileSources.cloudfront } });
const profile = { ...baseProfile };
const { user } = await validate(profile);
@@ -837,12 +867,75 @@ u7wlOSk+oFzDIO/UILIA
expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existingUser);
});
- it('should use baseConfig for new SAML user without calling resolveAppConfigForUser', async () => {
+ it('should check a new SAML user against the pre-auth config, then the USER role config', async () => {
const profile = { ...baseProfile };
await validate(profile);
expect(resolveAppConfigForUser).not.toHaveBeenCalled();
- expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(getAppConfig).toHaveBeenCalledWith({ skipRuntimeAugmentation: true, failClosed: true });
+ expect(getAppConfig).toHaveBeenCalledWith({
+ role: 'USER',
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ });
+ expect(getAppConfig).not.toHaveBeenCalledWith({ baseOnly: true });
+ });
+
+ it("should refuse a first sign-in the USER role's domain list excludes, creating nothing", async () => {
+ const { createUserIfAbsent, updateUser } = require('~/models');
+ require('@librechat/api').isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ getAppConfig.mockImplementation(async (options) =>
+ options?.role === 'USER' ? { registration: { allowedDomains: ['other.example'] } } : {},
+ );
+
+ const { user, details } = await validate({ ...baseProfile });
+
+ expect(user).toBe(false);
+ expect(details).toEqual({ message: 'Email domain not allowed' });
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ expect(updateUser).not.toHaveBeenCalled();
+ });
+
+ it('should resolve the account config for an existing user without a tenant', async () => {
+ const existingUser = {
+ _id: 'deployment-user-id',
+ provider: 'saml',
+ samlId: 'saml-1234',
+ email: '[email protected]',
+ role: 'USER',
+ };
+ findUser.mockResolvedValue(existingUser);
+
+ await validate({ ...baseProfile });
+
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existingUser);
+ });
+
+ it('should reject before the user lookup when the __base__ override excludes the domain', async () => {
+ const { isEmailDomainAllowed } = require('@librechat/api');
+ const { createUserIfAbsent } = require('~/models');
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ getAppConfig.mockImplementation(async (options) =>
+ options?.baseOnly ? {} : { registration: { allowedDomains: ['corp.example'] } },
+ );
+
+ const { user, details } = await validate({ ...baseProfile });
+
+ expect(user).toBe(false);
+ expect(details.message).toBe('Email domain not allowed');
+ expect(findUser).not.toHaveBeenCalled();
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ });
+
+ it('should fail the login when the pre-auth config cannot be read', async () => {
+ getAppConfig.mockRejectedValueOnce(new Error('override read failed'));
+
+ await expect(validate({ ...baseProfile })).rejects.toThrow('override read failed');
+ expect(findUser).not.toHaveBeenCalled();
});
it('should block login when tenant config restricts the domain', async () => {
diff --git a/api/strategies/socialLogin.js b/api/strategies/socialLogin.js
index e6dfd622ac..30cecf9ff9 100644
--- a/api/strategies/socialLogin.js
+++ b/api/strategies/socialLogin.js
@@ -4,6 +4,7 @@ const {
isEnabled,
findSocialUser,
isEmailDomainAllowed,
+ resolvePreAuthAppConfig,
resolveAppConfigForUser,
} = require('@librechat/api');
const { createSocialUser, handleExistingUser } = require('./process');
@@ -19,7 +20,7 @@ const socialLogin =
profile,
});
- const baseConfig = await getAppConfig({ baseOnly: true });
+ const baseConfig = await resolvePreAuthAppConfig(getAppConfig);
if (!isEmailDomainAllowed(email, baseConfig?.registration?.allowedDomains)) {
logger.error(
`[${provider}Login] Authentication blocked - email domain not allowed [Email: ${email}]`,
@@ -34,7 +35,7 @@ const socialLogin =
const lookup = { findUser, provider, providerId: id, email };
const existingUser = await findSocialUser(lookup);
- const appConfig = existingUser?.tenantId
+ const appConfig = existingUser
? await resolveAppConfigForUser(getAppConfig, existingUser)
: baseConfig;
@@ -125,7 +126,6 @@ const socialLogin =
username,
name,
emailVerified,
- appConfig,
lookup,
});
return passResult(newUser);
diff --git a/api/strategies/socialLogin.test.js b/api/strategies/socialLogin.test.js
index e5a8cbf987..76e325b2dc 100644
--- a/api/strategies/socialLogin.test.js
+++ b/api/strategies/socialLogin.test.js
@@ -3,7 +3,7 @@ const { ErrorTypes } = require('librechat-data-provider');
const { createSocialUser, handleExistingUser } = require('./process');
const socialLogin = require('./socialLogin');
const { findUser } = require('~/models');
-const { resolveAppConfigForUser } = require('@librechat/api');
+const { isEmailDomainAllowed, resolveAppConfigForUser } = require('@librechat/api');
const { getAppConfig } = require('~/server/services/Config');
jest.mock('@librechat/data-schemas', () => {
@@ -57,6 +57,11 @@ describe('socialLogin', () => {
beforeEach(() => {
jest.clearAllMocks();
+ isEmailDomainAllowed.mockReset().mockReturnValue(true);
+ getAppConfig.mockReset().mockResolvedValue({
+ fileStrategy: 'local',
+ balance: { enabled: false },
+ });
});
describe('Finding users by provider ID', () => {
@@ -349,7 +354,6 @@ describe('socialLogin', () => {
username: 'New',
name: 'New User',
emailVerified: true,
- appConfig: expect.any(Object),
lookup: { findUser, provider, providerId: googleId, email },
});
@@ -428,7 +432,7 @@ describe('socialLogin', () => {
expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existingUser);
});
- it('should use baseConfig for non-tenant user without calling resolveAppConfigForUser', async () => {
+ it('should use the pre-auth config for a new user without calling resolveAppConfigForUser', async () => {
const provider = 'google';
const googleId = 'google-new-tenant';
const email = '[email protected]';
@@ -454,11 +458,68 @@ describe('socialLogin', () => {
await loginFn(null, null, null, mockProfile, callback);
expect(resolveAppConfigForUser).not.toHaveBeenCalled();
- expect(getAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(getAppConfig).toHaveBeenCalledWith({
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ });
+ expect(getAppConfig).not.toHaveBeenCalledWith({ baseOnly: true });
+ });
+
+ it('should resolve the account config for an existing user without a tenant', async () => {
+ const email = '[email protected]';
+ const existingUser = {
+ _id: 'userDeployment',
+ email,
+ provider: 'google',
+ googleId: 'google-deployment-user',
+ role: 'USER',
+ };
+ findUser.mockResolvedValue(existingUser);
+ resolveAppConfigForUser.mockResolvedValue({ fileStrategy: 'local' });
+
+ const mockProfile = {
+ id: 'google-deployment-user',
+ emails: [{ value: email, verified: true }],
+ name: { givenName: 'Deployment', familyName: 'User' },
+ };
+ const callback = jest.fn();
+
+ await socialLogin('google', mockGetProfileDetails)(null, null, null, mockProfile, callback);
+
+ expect(resolveAppConfigForUser).toHaveBeenCalledWith(getAppConfig, existingUser);
+ expect(handleExistingUser).toHaveBeenCalledWith(
+ existingUser,
+ null,
+ { fileStrategy: 'local' },
+ email,
+ );
+ });
+
+ it('should reject before the user lookup when the __base__ override excludes the domain', async () => {
+ isEmailDomainAllowed.mockImplementation(
+ jest.requireActual('@librechat/api').isEmailDomainAllowed,
+ );
+ getAppConfig.mockImplementation(async (options) =>
+ options?.baseOnly ? {} : { registration: { allowedDomains: ['corp.example'] } },
+ );
+
+ const mockProfile = {
+ id: 'google-outsider',
+ emails: [{ value: '[email protected]', verified: true }],
+ name: { givenName: 'Out', familyName: 'Sider' },
+ };
+ const callback = jest.fn();
+
+ await socialLogin('google', mockGetProfileDetails)(null, null, null, mockProfile, callback);
+
+ expect(callback).toHaveBeenCalledWith(
+ expect.objectContaining({ message: 'Email domain not allowed' }),
+ );
+ expect(findUser).not.toHaveBeenCalled();
+ expect(createSocialUser).not.toHaveBeenCalled();
});
it('should block login when tenant config restricts the domain', async () => {
- const { isEmailDomainAllowed } = require('@librechat/api');
const provider = 'google';
const googleId = 'google-tenant-blocked';
const email = '[email protected]';
diff --git a/client/src/components/Auth/__tests__/AuthLayout.spec.tsx b/client/src/components/Auth/__tests__/AuthLayout.spec.tsx
index 42ad0f9746..fffa02b3ba 100644
--- a/client/src/components/Auth/__tests__/AuthLayout.spec.tsx
+++ b/client/src/components/Auth/__tests__/AuthLayout.spec.tsx
@@ -135,6 +135,23 @@ describe('AuthLayout legal placement', () => {
expect(document.querySelector('[role="contentinfo"] a')).toBeNull();
});
+ /** A link that would run script is no policy at all: the sign-in page renders
+ * it nowhere, so a stored `javascript:` url cannot run in a visitor's session. */
+ test('a script policy url leaves no link on the sign-in screen', () => {
+ setup({
+ pathname: 'login',
+ interfaceConfig: {
+ privacyPolicy: { externalUrl: 'javascript:alert(document.domain)' },
+ termsOfService: { externalUrl: TERMS_URL },
+ },
+ });
+
+ expect(consent()).toBeInTheDocument();
+ expect(document.querySelectorAll(`a[href="${TERMS_URL}"]`)).toHaveLength(1);
+ expect(document.querySelector('a[href^="javascript" i]')).toBeNull();
+ expect(screen.queryByRole('link', { name: /privacy policy/i })).toBeNull();
+ });
+
/** Registration renders its form, and with it the consent, only once the
* config has loaded without error. The footer bar carries the policies
* until then, so the screen is never left with neither. */
diff --git a/client/src/components/Nav/AccountSettings.tsx b/client/src/components/Nav/AccountSettings.tsx
index 24d32e5da1..a0a2121c8c 100644
--- a/client/src/components/Nav/AccountSettings.tsx
+++ b/client/src/components/Nav/AccountSettings.tsx
@@ -19,8 +19,8 @@ import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog
import useDirection, { inlineSide } from '~/hooks/Nav/useDirection';
import { useGetStartupConfig } from '~/data-provider';
import { useAuthContext } from '~/hooks/AuthContext';
+import { openInNewTab, policyUrls } from '~/utils';
import { settingsOpenAtom } from './Settings';
-import { openInNewTab } from '~/utils';
import { useLocalize } from '~/hooks';
import store from '~/store';
@@ -100,6 +100,7 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {
const localize = useLocalize();
const { user, logout } = useAuthContext();
const { data: startupConfig } = useGetStartupConfig();
+ const { privacyPolicyUrl, termsOfServiceUrl } = policyUrls(startupConfig);
const setShowSettings = useSetAtom(settingsOpenAtom);
const setShowFiles = useSetAtom(showFilesDialogAtom);
const setFilesDialogTrigger = useSetAtom(filesDialogTriggerAtom);
@@ -148,8 +149,8 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {
<DropdownMenuSeparator />
<HelpSubmenu
helpAndFaqURL={startupConfig?.helpAndFaqURL}
- termsOfServiceURL={startupConfig?.interface?.termsOfService?.externalUrl}
- privacyPolicyURL={startupConfig?.interface?.privacyPolicy?.externalUrl}
+ termsOfServiceURL={termsOfServiceUrl}
+ privacyPolicyURL={privacyPolicyUrl}
onShowShortcuts={() => setShowShortcutsDialog(true)}
/>
<Menu.MenuItem onClick={() => setShowArchived(true)} className="select-item text-sm">
diff --git a/client/src/utils/__tests__/policies.spec.ts b/client/src/utils/__tests__/policies.spec.ts
new file mode 100644
index 0000000000..f59e93a6ba
--- /dev/null
+++ b/client/src/utils/__tests__/policies.spec.ts
@@ -0,0 +1,58 @@
+import { hasPublishedPolicies, policyUrls, publishedPolicyUrl } from '../policies';
+
+describe('publishedPolicyUrl', () => {
+ it.each([
+ 'javascript:alert(document.domain)',
+ ' JavaScript:alert(1)',
+ 'java\tscript:alert(1)',
+ '\u0001javascript:alert(1)',
+ 'data:text/html,<script>alert(1)</script>',
+ 'vbscript:msgbox(1)',
+ '\u00a0javascript:alert(document.domain)',
+ '\ufeffjavascript:alert(document.domain)',
+ '\u2028javascript:alert(document.domain)',
+ '\u3000javascript:alert(document.domain)',
+ ])('publishes no link for %j, which would run script on the page that shows it', (url) => {
+ expect(publishedPolicyUrl(url)).toBeUndefined();
+ });
+
+ it.each([
+ ['https://example.com/privacy', 'https://example.com/privacy'],
+ [' /legal/terms ', '/legal/terms'],
+ ['//example.com/privacy', '//example.com/privacy'],
+ ['\u00a0https://example.com/privacy', 'https://example.com/privacy'],
+ ['mailto:[email protected]', 'mailto:[email protected]'],
+ ])('publishes %j, an http(s), mailto: or relative link', (url, published) => {
+ expect(publishedPolicyUrl(url)).toBe(published);
+ });
+
+ it('publishes nothing for a blank or missing link', () => {
+ expect(publishedPolicyUrl(' ')).toBeUndefined();
+ expect(publishedPolicyUrl(undefined)).toBeUndefined();
+ });
+});
+
+describe('policyUrls', () => {
+ it('keeps a safe policy link when the other one would run script', () => {
+ const startupConfig = {
+ interface: {
+ privacyPolicy: { externalUrl: 'javascript:alert(document.domain)' },
+ termsOfService: { externalUrl: 'https://example.com/terms' },
+ },
+ };
+
+ expect(policyUrls(startupConfig)).toEqual({
+ privacyPolicyUrl: undefined,
+ termsOfServiceUrl: 'https://example.com/terms',
+ });
+ expect(hasPublishedPolicies(startupConfig)).toBe(true);
+ });
+
+ it('counts a script link as no published policy', () => {
+ expect(
+ hasPublishedPolicies({
+ interface: { privacyPolicy: { externalUrl: 'javascript:alert(1)' } },
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/client/src/utils/policies.ts b/client/src/utils/policies.ts
index 00086e9510..ef5b99da86 100644
--- a/client/src/utils/policies.ts
+++ b/client/src/utils/policies.ts
@@ -1,3 +1,4 @@
+import { isSafeLinkUrl } from 'librechat-data-provider';
import type { TStartupConfig } from 'librechat-data-provider';
/**
@@ -5,11 +6,14 @@ import type { TStartupConfig } from 'librechat-data-provider';
* agree to read it. `externalUrl` is an optional string, so an operator can
* leave it blank; a blank one is not a published policy, because rendered as a
* link it points back at the page the reader is on and names a document that
- * does not exist.
+ * does not exist. Nor is one that is not an http(s), `mailto:`, `tel:` or
+ * relative URL: rendered as a link, a `javascript:` or `data:` URL runs script
+ * on the page that shows it, the sign-in page included. The server refuses to
+ * store or serve one; this check also covers a server that predates it.
*/
export function publishedPolicyUrl(externalUrl?: string): string | undefined {
const url = externalUrl?.trim();
- return url != null && url !== '' ? url : undefined;
+ return url != null && url !== '' && isSafeLinkUrl(url) ? url : undefined;
}
type PolicySource = {
diff --git a/e2e/specs/mock/scenarios/config-override-validation.spec.ts b/e2e/specs/mock/scenarios/config-override-validation.spec.ts
index 9f8110733b..471e48a3ed 100644
--- a/e2e/specs/mock/scenarios/config-override-validation.spec.ts
+++ b/e2e/specs/mock/scenarios/config-override-validation.spec.ts
@@ -12,7 +12,7 @@ import { withMongo } from '../db';
*/
type Session = { headers: Record<string, string>; userId: string };
-type InterfaceConfig = { contextCost?: unknown; customWelcome?: string };
+type InterfaceConfig = { contextCost?: unknown; currency?: unknown; customWelcome?: string };
async function login(
request: APIRequestContext,
@@ -250,28 +250,24 @@ test.describe('Principal config override validation', () => {
const rolePath = '/api/admin/config/role/USER';
await clearOverrides(request, admin, target.userId);
try {
- /** The role layer leaves out the required `siteKey`, which the user layer supplies. */
+ /** The role layer leaves out the required currency `code`, which the user layer supplies. */
const role = await request.put(rolePath, {
headers: admin.headers,
- data: { priority: 10, overrides: { turnstile: { options: { size: 'compact' } } } },
+ data: { priority: 10, overrides: { interface: { currency: { rate: 0.92 } } } },
});
expect(role.ok()).toBeTruthy();
const user = await request.put(configPath(target.userId), {
headers: admin.headers,
- data: { priority: 20, overrides: { turnstile: { siteKey: 'layered-site-key' } } },
+ data: { priority: 20, overrides: { interface: { currency: { code: 'EUR' } } } },
});
expect(user.ok()).toBeTruthy();
await expect
- .poll(
- async () => {
- const res = await request.get('/api/config', { headers: target.headers });
- expect(res.ok()).toBeTruthy();
- return ((await res.json()) as { turnstile?: unknown }).turnstile;
- },
- { timeout: 30000, intervals: [500, 1000, 2000] },
- )
- .toEqual({ siteKey: 'layered-site-key', options: { size: 'compact' } });
+ .poll(async () => (await readInterface(request, target)).currency, {
+ timeout: 30000,
+ intervals: [500, 1000, 2000],
+ })
+ .toEqual({ code: 'EUR', rate: 0.92 });
} finally {
await request.delete(rolePath, { headers: admin.headers });
await clearOverrides(request, admin, target.userId);
diff --git a/packages/api/src/admin/config.changes.integration.spec.ts b/packages/api/src/admin/config.changes.integration.spec.ts
index 00a4acd6e0..f5961a3468 100644
--- a/packages/api/src/admin/config.changes.integration.spec.ts
+++ b/packages/api/src/admin/config.changes.integration.spec.ts
@@ -1140,6 +1140,71 @@ describe('POST …/changes: skipped, not refused (owner decision #2)', () => {
});
});
+describe('POST …/changes: Turnstile and policy links', () => {
+ it('skips Turnstile, which stays on librechat.yaml, and stores a mailto: policy link', async () => {
+ const params = nextParams();
+
+ const set = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'turnstile.siteKey', value: 'stored-key' },
+ {
+ op: 'set',
+ fieldPath: 'interface.privacyPolicy.externalUrl',
+ value: 'mailto:[email protected]',
+ },
+ ],
+ },
+ params,
+ );
+ const tombstone = await send({ ops: [{ op: 'tombstone', fieldPath: 'turnstile' }] }, params);
+
+ expect(set.status).toBe(200);
+ expect(set.body.skipped.map(({ opIndex, reason }) => [opIndex, reason])).toEqual([
+ [0, 'base_only_section'],
+ ]);
+ expect(tombstone.status).toBe(200);
+ expect(tombstone.body.skipped.map(({ opIndex, reason }) => [opIndex, reason])).toEqual([
+ [0, 'base_only_section'],
+ ]);
+ const stored = await storedDocument(params.principalId);
+ expect(stored!.overrides).toEqual({
+ interface: { privacyPolicy: { externalUrl: 'mailto:[email protected]' } },
+ });
+ expect(stored!.tombstones).toEqual([]);
+ });
+
+ it('refuses a policy link that would run script, writing nothing', async () => {
+ const params = nextParams();
+
+ const { status, body, deps } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ {
+ op: 'set',
+ fieldPath: 'interface.termsOfService',
+ value: { externalUrl: '\u00a0JavaScript:alert(document.domain)' },
+ },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body.code).toBe('CONFIG_OVERRIDE_INVALID');
+ expect(body.issues).toEqual([
+ {
+ path: 'interface.termsOfService.externalUrl',
+ segments: ['interface', 'termsOfService', 'externalUrl'],
+ code: 'custom',
+ },
+ ]);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ expect(await storedDocument(params.principalId)).toBeNull();
+ });
+});
+
describe('POST …/changes: no-ops, dry runs and preconditions', () => {
it('writes nothing for a batch that changes nothing, keeping the revision', async () => {
const params = nextParams();
diff --git a/packages/api/src/admin/config.handler.spec.ts b/packages/api/src/admin/config.handler.spec.ts
index af274320ee..ad031fd439 100644
--- a/packages/api/src/admin/config.handler.spec.ts
+++ b/packages/api/src/admin/config.handler.spec.ts
@@ -2811,6 +2811,157 @@ describe('createAdminConfigHandlers', () => {
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
+ it('rejects a Base policy link that would run script and stores nothing', async () => {
+ const { handlers, deps } = createHandlers();
+ const params = { principalType: 'role', principalId: '__base__' };
+ const documentRes = mockRes();
+ const fieldRes = mockRes();
+
+ await handlers.upsertConfigOverrides(
+ mockReq({
+ params,
+ body: {
+ overrides: {
+ interface: {
+ privacyPolicy: { externalUrl: 'javascript:alert(document.domain)' },
+ termsOfService: { externalUrl: 'https://example.com/terms' },
+ },
+ },
+ },
+ }),
+ documentRes,
+ );
+ await handlers.patchConfigField(
+ mockReq({
+ params,
+ body: {
+ entries: [
+ {
+ fieldPath: 'interface.termsOfService.externalUrl',
+ value: '\u00a0JavaScript:alert(document.domain)',
+ },
+ ],
+ },
+ }),
+ fieldRes,
+ );
+
+ expect(documentRes.statusCode).toBe(400);
+ expect(documentRes.body?.issues).toEqual([
+ {
+ path: 'interface.privacyPolicy.externalUrl',
+ segments: ['interface', 'privacyPolicy', 'externalUrl'],
+ code: 'custom',
+ },
+ ]);
+ expect(fieldRes.statusCode).toBe(400);
+ expect(fieldRes.body?.issues).toEqual([
+ {
+ path: 'interface.termsOfService.externalUrl',
+ segments: ['interface', 'termsOfService', 'externalUrl'],
+ code: 'custom',
+ },
+ ]);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it('keeps accepting http(s), relative and blank policy links', async () => {
+ const { handlers, deps } = createHandlers();
+ const res = mockRes();
+
+ await handlers.upsertConfigOverrides(
+ mockReq({
+ params: { principalType: 'role', principalId: '__base__' },
+ body: {
+ overrides: {
+ interface: {
+ privacyPolicy: { externalUrl: 'https://example.com/privacy', openNewTab: true },
+ termsOfService: { externalUrl: '/terms', modalAcceptance: true },
+ },
+ },
+ },
+ }),
+ res,
+ );
+
+ expect(res.statusCode).toBe(201);
+ expect(writtenDraft(deps).overrides.interface).toEqual({
+ privacyPolicy: { externalUrl: 'https://example.com/privacy', openNewTab: true },
+ termsOfService: { externalUrl: '/terms', modalAcceptance: true },
+ });
+ });
+
+ it('skips a Turnstile write to Base, which stays on librechat.yaml', async () => {
+ const { handlers, deps } = createHandlers();
+ const params = { principalType: 'role', principalId: '__base__' };
+ const documentRes = mockRes();
+ const fieldRes = mockRes();
+
+ await handlers.upsertConfigOverrides(
+ mockReq({
+ params,
+ body: {
+ overrides: { turnstile: { siteKey: 'stored-key' }, interface: { modelSelect: false } },
+ },
+ }),
+ documentRes,
+ );
+ await handlers.patchConfigField(
+ mockReq({ params, body: { entries: [{ fieldPath: 'turnstile.siteKey', value: 'k' }] } }),
+ fieldRes,
+ );
+ const removals = [mockRes(), mockRes()];
+ await handlers.tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'turnstile' } }),
+ removals[0],
+ );
+ await handlers.deleteConfigField(
+ mockReq({ params, query: { fieldPath: 'turnstile.siteKey' } }),
+ removals[1],
+ );
+
+ expect(documentRes.statusCode).toBe(201);
+ expect(writtenDraft(deps).overrides).toEqual({ interface: { modelSelect: false } });
+ expect(fieldRes.statusCode).toBe(200);
+ expect(removals.map((res) => res.statusCode)).toEqual([200, 200]);
+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
+ expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deps.unsetConfigField).not.toHaveBeenCalled();
+ });
+
+ it('refuses a Turnstile tombstone under its AppConfig name and removes a stored one', async () => {
+ const { handlers, deps } = createHandlers({
+ unsetConfigField: jest.fn().mockResolvedValue({ _id: 'c1', overrides: {}, tombstones: [] }),
+ });
+ const params = { principalType: 'role', principalId: '__base__' };
+ const tombstoneRes = mockRes();
+ const deleteRes = mockRes();
+
+ await handlers.tombstoneConfigField(
+ mockReq({ params, body: { fieldPath: 'turnstileConfig' } }),
+ tombstoneRes,
+ );
+ await handlers.deleteConfigField(
+ mockReq({ params, query: { fieldPath: 'turnstileConfig.siteKey' } }),
+ deleteRes,
+ );
+
+ expect(tombstoneRes.statusCode).toBe(400);
+ expect(tombstoneRes.body).toEqual({
+ error: 'Unknown config section',
+ code: 'UNKNOWN_SECTION',
+ });
+ expect(deps.tombstoneConfigField).not.toHaveBeenCalled();
+ expect(deleteRes.statusCode).toBe(200);
+ expect(deps.unsetConfigField).toHaveBeenCalledWith(
+ 'role',
+ '__base__',
+ ['turnstileConfig.siteKey'],
+ undefined,
+ { expectedRevision: undefined },
+ );
+ });
+
it('rejects a patch that addresses a custom endpoint by index', async () => {
const { handlers, deps } = createHandlers();
const req = mockReq({
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
index 35a05c5d2b..26a6670156 100644
--- a/packages/api/src/admin/meta.spec.ts
+++ b/packages/api/src/admin/meta.spec.ts
@@ -3,10 +3,12 @@ import mongoose from 'mongoose';
import { readFileSync } from 'fs';
import mongoSanitize from 'express-mongo-sanitize';
import {
+ AppService,
loadWebSearchConfig,
mergeConfigOverrides,
createConfigOperations,
getConfigOverrideIssues,
+ BASE_CONFIG_PRINCIPAL_ID,
isConfigOverrideStateEmpty,
} from '@librechat/data-schemas';
import {
@@ -28,6 +30,7 @@ import {
} from 'librechat-data-provider';
import type {
AdminConfigFeatureFlag,
+ ConfigOverrideLayer,
AdminConfigMeta,
ConfigRecord,
ConfigStore,
@@ -39,6 +42,7 @@ import type { Request, Response } from 'express';
import type { ServerRequest } from '~/types/http';
import type { AdminConfigDeps } from './config';
import { createRequestSanitizer, rejectUnsafeConfigKeys } from '~/middleware/sanitize';
+import { resolvePreAuthAppConfig, resolvePreLoginAppConfig } from '~/app/resolve';
import { redactConfigSecrets, encryptConfigSecretFields } from './secrets';
import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';
import { createMCPPolicyResolver } from '~/mcp/registry/policy';
@@ -214,6 +218,7 @@ describe('GET /api/admin/config/meta', () => {
'changesBatch',
'dottedKeys',
'expectedRevision',
+ 'preAuthBaseOverrides',
'prunesEmptyParents',
'readFilteredWriteResponses',
'sectionAllowlist',
@@ -248,6 +253,7 @@ describe('GET /api/admin/config/meta', () => {
dottedKeys: true,
sectionAllowlist: true,
readFilteredWriteResponses: true,
+ preAuthBaseOverrides: true,
webSearchStoredKeys: true,
expectedRevision: true,
prunesEmptyParents: true,
@@ -487,6 +493,43 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
);
});
},
+ async preAuthBaseOverrides() {
+ const store = new Map<string, unknown>();
+ const base: ConfigOverrideLayer = {
+ principalType: PrincipalType.ROLE,
+ principalId: BASE_CONFIG_PRINCIPAL_ID,
+ priority: 0,
+ overrides: {
+ registration: { socialLogins: ['github'] },
+ turnstile: { siteKey: 'base-site-key' },
+ },
+ };
+ const { getAppConfig } = createAppConfigService({
+ loadBaseConfig: () =>
+ AppService({
+ config: {
+ registration: { socialLogins: ['openid'] },
+ turnstile: { siteKey: 'yaml-site-key' },
+ },
+ }),
+ setCachedTools: async () => undefined,
+ getCache: () => ({
+ get: async (key: string) => store.get(key),
+ set: async (key: string, value: unknown) => store.set(key, value),
+ delete: async (key: string) => store.delete(key),
+ }),
+ cacheKeys: { APP_CONFIG: 'app_config' },
+ getApplicableConfigs: jest.fn().mockResolvedValue([base]),
+ getUserPrincipals: jest.fn().mockResolvedValue([]),
+ });
+ const signedOut = await resolvePreLoginAppConfig(getAppConfig);
+ const preAuth = await resolvePreAuthAppConfig(getAppConfig);
+ return [signedOut, preAuth].every(
+ (config) =>
+ config.registration?.socialLogins?.join() === 'github' &&
+ config.turnstileConfig?.siteKey === 'yaml-site-key',
+ );
+ },
async webSearchStoredKeys() {
const keys = {
'webSearch.serperApiKey': 'serper-admin-secret',
diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.ts
index 7817cb6f5b..1998f46d7a 100644
--- a/packages/api/src/admin/meta.ts
+++ b/packages/api/src/admin/meta.ts
@@ -23,6 +23,7 @@ export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
dottedKeys: true,
sectionAllowlist: true,
readFilteredWriteResponses: true,
+ preAuthBaseOverrides: true,
webSearchStoredKeys: true,
expectedRevision: true,
prunesEmptyParents: true,
diff --git a/packages/api/src/app/__fixtures__/links/contact.yaml b/packages/api/src/app/__fixtures__/links/contact.yaml
new file mode 100644
index 0000000000..2fcab16fbd
--- /dev/null
+++ b/packages/api/src/app/__fixtures__/links/contact.yaml
@@ -0,0 +1,7 @@
+version: 1.3.17
+cache: true
+interface:
+ privacyPolicy:
+ externalUrl: 'mailto:[email protected]'
+ termsOfService:
+ externalUrl: 'https://example.com/terms'
diff --git a/packages/api/src/app/__fixtures__/links/unsafe.yaml b/packages/api/src/app/__fixtures__/links/unsafe.yaml
new file mode 100644
index 0000000000..b71cc4a447
--- /dev/null
+++ b/packages/api/src/app/__fixtures__/links/unsafe.yaml
@@ -0,0 +1,10 @@
+version: 1.3.17
+cache: true
+interface:
+ modelSelect: true
+ privacyPolicy:
+ externalUrl: 'javascript:alert(document.domain)'
+ openNewTab: true
+ termsOfService:
+ externalUrl: 'htps://example.com/terms'
+ modalAcceptance: true
diff --git a/packages/api/src/app/index.ts b/packages/api/src/app/index.ts
index 9198f02baa..a88e7d7437 100644
--- a/packages/api/src/app/index.ts
+++ b/packages/api/src/app/index.ts
@@ -14,4 +14,4 @@ export * from './origin';
export * from './agents';
export { resolveBuildInfo } from './build';
export type { BuildInfo } from './build';
-export { buildPreLoginInterface } from './interface';
+export { buildPreLoginInterface, withSafePolicyLinks } from './interface';
diff --git a/packages/api/src/app/interface.spec.ts b/packages/api/src/app/interface.spec.ts
index a0038fdd1c..1dee8aa4bb 100644
--- a/packages/api/src/app/interface.spec.ts
+++ b/packages/api/src/app/interface.spec.ts
@@ -1,4 +1,5 @@
-import { buildPreLoginInterface } from './interface';
+import type { AppConfig } from '@librechat/data-schemas';
+import { buildPreLoginInterface, checkConfigPolicyLinks, withSafePolicyLinks } from './interface';
describe('buildPreLoginInterface', () => {
it('omits the interface when nothing public is configured', () => {
@@ -22,6 +23,20 @@ describe('buildPreLoginInterface', () => {
});
});
+ it('drops a policy link that would run script, keeping the safe link and the rest', () => {
+ expect(
+ buildPreLoginInterface({
+ privacyPolicy: { externalUrl: 'javascript:alert(document.domain)', openNewTab: true },
+ termsOfService: { externalUrl: '/terms' },
+ buildInfo: false,
+ }),
+ ).toEqual({
+ privacyPolicy: { openNewTab: true },
+ termsOfService: { externalUrl: '/terms' },
+ buildInfo: false,
+ });
+ });
+
it('carries a bundled theme name', () => {
expect(buildPreLoginInterface({ theme: 'clickhouse', modelSelect: true })).toEqual({
theme: 'clickhouse',
@@ -37,3 +52,93 @@ describe('buildPreLoginInterface', () => {
expect(buildPreLoginInterface({ theme })).toEqual({ theme });
});
});
+
+describe('withSafePolicyLinks', () => {
+ it('returns the same config when every policy link is http(s), mailto:, relative or blank', () => {
+ const contact = { privacyPolicy: { externalUrl: 'mailto:[email protected]' } };
+ expect(withSafePolicyLinks(contact)).toBe(contact);
+ const interfaceConfig = {
+ privacyPolicy: { externalUrl: 'https://example.com/privacy' },
+ termsOfService: { externalUrl: '', modalAcceptance: true },
+ modelSelect: true,
+ };
+ const withoutLinks: AppConfig['interfaceConfig'] = { modelSelect: false };
+ expect(withSafePolicyLinks(interfaceConfig)).toBe(interfaceConfig);
+ expect(withSafePolicyLinks(withoutLinks)).toBe(withoutLinks);
+ expect(withSafePolicyLinks(undefined)).toBeUndefined();
+ expect(withSafePolicyLinks(null)).toBeNull();
+ });
+
+ it.each([
+ 'javascript:alert(1)',
+ ' JAVASCRIPT:alert(1)',
+ 'data:text/html,hi',
+ 'vbscript:x',
+ '\u00a0javascript:alert(document.domain)',
+ '\ufeffjavascript:alert(document.domain)',
+ '\u2028javascript:alert(document.domain)',
+ '\u3000javascript:alert(document.domain)',
+ ])('removes %j from both links without touching the other settings', (externalUrl) => {
+ const interfaceConfig = {
+ privacyPolicy: { externalUrl, openNewTab: true },
+ termsOfService: { externalUrl, modalAcceptance: true, modalTitle: 'Terms' },
+ modelSelect: true,
+ };
+
+ const safe = withSafePolicyLinks(interfaceConfig);
+
+ expect(JSON.parse(JSON.stringify(safe))).toEqual({
+ privacyPolicy: { openNewTab: true },
+ termsOfService: { modalAcceptance: true, modalTitle: 'Terms' },
+ modelSelect: true,
+ });
+ expect(interfaceConfig.privacyPolicy.externalUrl).toBe(externalUrl);
+ });
+
+ it('removes a stored value that is not a string at all', () => {
+ const privacyPolicy = { externalUrl: 42 } as unknown as { externalUrl?: string };
+ expect(withSafePolicyLinks({ privacyPolicy }).privacyPolicy).toEqual({
+ externalUrl: undefined,
+ });
+ });
+});
+
+describe('checkConfigPolicyLinks', () => {
+ it('returns the same config when there is nothing to drop', () => {
+ const safe = {
+ interface: {
+ privacyPolicy: { externalUrl: 'tel:+15555550100' },
+ termsOfService: { externalUrl: '/terms' },
+ },
+ };
+ const notStrings = { interface: { privacyPolicy: { externalUrl: 42 } } };
+ for (const config of [safe, notStrings, { version: '1.3.17' }, null, 'yaml']) {
+ expect(checkConfigPolicyLinks(config)).toEqual({ config, dropped: [] });
+ expect(checkConfigPolicyLinks(config).config).toBe(config);
+ }
+ });
+
+ it('drops only the unsafe URL, leaving the link settings and the input untouched', () => {
+ const config = {
+ cache: true,
+ interface: {
+ modelSelect: true,
+ privacyPolicy: { externalUrl: '\ufeffjavascript:alert(1)', openNewTab: true },
+ termsOfService: { externalUrl: 'https://example.com/terms' },
+ },
+ };
+
+ expect(checkConfigPolicyLinks(config)).toEqual({
+ config: {
+ cache: true,
+ interface: {
+ modelSelect: true,
+ privacyPolicy: { openNewTab: true },
+ termsOfService: { externalUrl: 'https://example.com/terms' },
+ },
+ },
+ dropped: ['interface.privacyPolicy.externalUrl'],
+ });
+ expect(config.interface.privacyPolicy.externalUrl).toBe('\ufeffjavascript:alert(1)');
+ });
+});
diff --git a/packages/api/src/app/interface.ts b/packages/api/src/app/interface.ts
index de3d5fb704..b49c4c6163 100644
--- a/packages/api/src/app/interface.ts
+++ b/packages/api/src/app/interface.ts
@@ -1,23 +1,117 @@
-import type { TInterfaceConfig } from 'librechat-data-provider';
+import { isSafeLinkUrl } from 'librechat-data-provider';
+import type { TTermsOfService } from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
+
+type InterfaceConfig = NonNullable<AppConfig['interfaceConfig']>;
type PreLoginInterface = Pick<
- TInterfaceConfig,
+ InterfaceConfig,
'privacyPolicy' | 'termsOfService' | 'buildInfo' | 'theme'
>;
+type PolicyLinks = Pick<InterfaceConfig, 'privacyPolicy' | 'termsOfService'>;
+
+const POLICY_LINK_FIELDS = ['privacyPolicy', 'termsOfService'] as const;
+
+type YamlNode = { [key: string]: YamlValue };
+type YamlValue = string | number | boolean | null | undefined | YamlNode | YamlValue[];
+
+export interface ConfigPolicyLinkCheck {
+ /** The config to validate and return: the input itself unless a link had to be dropped. */
+ config: unknown;
+ /** The `externalUrl` paths that were dropped. */
+ dropped: string[];
+}
+
+function isYamlNode(value: unknown): value is YamlNode {
+ return value != null && typeof value === 'object' && !Array.isArray(value);
+}
+
+/** The policy link without its `externalUrl` when `isSafeLinkUrl` refuses it. */
+function withSafeExternalUrl<T extends Pick<TTermsOfService, 'externalUrl'>>(
+ link: T | undefined,
+): T | undefined {
+ if (!link) {
+ return link;
+ }
+ const externalUrl: unknown = link.externalUrl;
+ if (externalUrl == null || (typeof externalUrl === 'string' && isSafeLinkUrl(externalUrl))) {
+ return link;
+ }
+ return { ...link, externalUrl: undefined };
+}
+
+/**
+ * The interface config as a client may render it: a privacy policy or terms of service
+ * `externalUrl` that `isSafeLinkUrl` refuses (`javascript:`, `data:` and the like) is removed, so
+ * it never becomes an `href`. Admin writes already refuse such a value, the YAML loader drops one
+ * from librechat.yaml, and the merge drops one stored before that; this keeps every payload that
+ * carries the links (signed out, signed in, shared link) safe on its own, whatever key or path
+ * the value arrived by. Returns the same object when nothing is removed.
+ */
+export function withSafePolicyLinks<T extends PolicyLinks | null | undefined>(
+ interfaceConfig: T,
+): T {
+ if (!interfaceConfig) {
+ return interfaceConfig;
+ }
+ const privacyPolicy = withSafeExternalUrl(interfaceConfig.privacyPolicy);
+ const termsOfService = withSafeExternalUrl(interfaceConfig.termsOfService);
+ if (
+ privacyPolicy === interfaceConfig.privacyPolicy &&
+ termsOfService === interfaceConfig.termsOfService
+ ) {
+ return interfaceConfig;
+ }
+ return { ...interfaceConfig, privacyPolicy, termsOfService };
+}
+
+/**
+ * Drops a librechat.yaml policy link `externalUrl` that `isSafeLinkUrl` refuses, before the
+ * config is validated, so the deployment publishes no link for it and the rest of the config
+ * still loads, as an invalid `interface.theme` does. Admin writes of such a value are refused
+ * instead, and every payload removes one that reaches it another way. A config whose links are
+ * all safe is returned as the same object.
+ */
+export function checkConfigPolicyLinks(config: unknown): ConfigPolicyLinkCheck {
+ if (!isYamlNode(config) || !isYamlNode(config.interface)) {
+ return { config, dropped: [] };
+ }
+ const interfaceConfig = config.interface;
+ const dropped: string[] = [];
+ const checked: YamlNode = { ...interfaceConfig };
+ for (const field of POLICY_LINK_FIELDS) {
+ const link = interfaceConfig[field];
+ if (!isYamlNode(link) || typeof link.externalUrl !== 'string') {
+ continue;
+ }
+ if (isSafeLinkUrl(link.externalUrl)) {
+ continue;
+ }
+ const { externalUrl: _dropped, ...rest } = link;
+ checked[field] = rest;
+ dropped.push(`interface.${field}.externalUrl`);
+ }
+ if (dropped.length === 0) {
+ return { config, dropped };
+ }
+ return { config: { ...config, interface: checked }, dropped };
+}
+
/**
* Selects the interface fields a signed-out client may see: the legal links the
- * login page renders, a disabled build-info flag, and the deployment theme so the
- * login page paints it instead of switching after sign-in. Returns `undefined`
- * when none of them is configured, so the payload omits `interface` entirely.
+ * login page renders (safe links only), a disabled build-info flag,
+ * and the deployment theme so the login page paints it instead of switching after
+ * sign-in. Returns `undefined` when none of them is configured, so the payload
+ * omits `interface` entirely.
*/
export function buildPreLoginInterface(
- interfaceConfig?: Partial<TInterfaceConfig>,
+ interfaceConfig?: AppConfig['interfaceConfig'],
): PreLoginInterface | undefined {
if (!interfaceConfig) {
return undefined;
}
- const { privacyPolicy, termsOfService, buildInfo, theme } = interfaceConfig;
+ const { privacyPolicy, termsOfService, buildInfo, theme } = withSafePolicyLinks(interfaceConfig);
const selected: PreLoginInterface = {
...(privacyPolicy && { privacyPolicy }),
...(termsOfService && { termsOfService }),
diff --git a/packages/api/src/app/loader.spec.ts b/packages/api/src/app/loader.spec.ts
index da30bb27db..216fc257ac 100644
--- a/packages/api/src/app/loader.spec.ts
+++ b/packages/api/src/app/loader.spec.ts
@@ -182,3 +182,59 @@ describe('createCustomConfigLoader interface.theme', () => {
});
});
});
+
+describe('createCustomConfigLoader policy links', () => {
+ const originalConfigPath = process.env.CONFIG_PATH;
+ let warn: jest.SpyInstance;
+ let exit: jest.SpyInstance;
+
+ beforeEach(() => {
+ warn = jest.spyOn(logger, 'warn');
+ jest.spyOn(logger, 'error').mockImplementation(() => logger);
+ jest.spyOn(logger, 'info').mockImplementation(() => logger);
+ exit = jest.spyOn(process, 'exit').mockImplementation((code) => {
+ throw new Error(`process.exit(${code})`);
+ });
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ if (originalConfigPath === undefined) {
+ delete process.env.CONFIG_PATH;
+ } else {
+ process.env.CONFIG_PATH = originalConfigPath;
+ }
+ });
+
+ const load = async (name: string, mode: 'startup' | 'reload' = 'startup') => {
+ process.env.CONFIG_PATH = path.join(__dirname, '__fixtures__', 'links', `${name}.yaml`);
+ return createLoader()(false, { mode });
+ };
+
+ it.each(['startup', 'reload'] as const)(
+ 'drops a link that is not http(s), mailto:, tel: or relative and still loads on %s',
+ async (mode) => {
+ const config = await load('unsafe', mode);
+
+ expect(exit).not.toHaveBeenCalled();
+ expect(config?.interface).toEqual({
+ modelSelect: true,
+ privacyPolicy: { openNewTab: true },
+ termsOfService: { modalAcceptance: true },
+ });
+ expect(warnings(warn)).toContain('- interface.privacyPolicy.externalUrl');
+ expect(warnings(warn)).toContain('- interface.termsOfService.externalUrl');
+ expect(warnings(warn)).not.toContain('javascript');
+ },
+ );
+
+ it('keeps mailto: and http(s) links as written, without warnings', async () => {
+ const config = await load('contact');
+
+ expect(config?.interface).toEqual({
+ privacyPolicy: { externalUrl: 'mailto:[email protected]' },
+ termsOfService: { externalUrl: 'https://example.com/terms' },
+ });
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/app/loader.ts b/packages/api/src/app/loader.ts
index 80c3510113..23de375031 100644
--- a/packages/api/src/app/loader.ts
+++ b/packages/api/src/app/loader.ts
@@ -15,6 +15,7 @@ import {
import type { TCustomConfig, TEndpoint } from 'librechat-data-provider';
import type { ZodIssue } from 'zod';
import { isAgentInferenceExtension } from '../agents/inference';
+import { checkConfigPolicyLinks } from './interface';
import { checkConfigTheme } from './theme';
type CustomParams = NonNullable<TEndpoint['customParams']>;
@@ -156,6 +157,16 @@ function isRemoteConfigPath(configPath: string): boolean {
return /^https?:\/\//.test(configPath);
}
+function reportPolicyLinkCheck(configPath: string, dropped: string[]): void {
+ if (dropped.length === 0) {
+ return;
+ }
+ logger.warn(
+ `Ignoring policy links in ${configPath} that are not http(s), mailto:, tel: or relative URLs; no link is published for them:\n` +
+ dropped.map((path) => `- ${path}`).join('\n'),
+ );
+}
+
function reportThemeCheck(configPath: string, errors: string[], warnings: string[]): void {
if (errors.length > 0) {
logger.warn(
@@ -262,6 +273,9 @@ export function createCustomConfigLoader({
const themeCheck = checkConfigTheme(loadedConfig);
loadedConfig = themeCheck.config;
reportThemeCheck(configPath, themeCheck.errors, themeCheck.warnings);
+ const linkCheck = checkConfigPolicyLinks(loadedConfig);
+ loadedConfig = linkCheck.config;
+ reportPolicyLinkCheck(configPath, linkCheck.dropped);
setMaxSubagents(getConfiguredMaxSubagents(loadedConfig));
const result = configSchema.strict().safeParse(loadedConfig);
diff --git a/packages/api/src/app/resolve.integration.spec.ts b/packages/api/src/app/resolve.integration.spec.ts
new file mode 100644
index 0000000000..869535251c
--- /dev/null
+++ b/packages/api/src/app/resolve.integration.spec.ts
@@ -0,0 +1,341 @@
+import mongoose from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { SystemRoles, PrincipalModel, PrincipalType } from 'librechat-data-provider';
+import {
+ logger,
+ AppService,
+ createModels,
+ runAsSystem,
+ createMethods,
+ tenantStorage,
+ BASE_CONFIG_PRINCIPAL_ID,
+} from '@librechat/data-schemas';
+import type { TCustomConfig } from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
+import {
+ resolveAppConfigForUser,
+ resolvePreAuthAppConfig,
+ resolvePreLoginAppConfig,
+} from './resolve';
+import { isEmailDomainAllowed } from '~/auth/domain';
+import { buildPreLoginInterface } from './interface';
+import { createAppConfigService } from './service';
+import { createUserOnce } from '~/auth/provision';
+
+/**
+ * Pre-auth config resolution end to end: the real config service and the real config methods
+ * over MongoDB, with librechat.yaml stood in by `AppService` on a fixed config.
+ */
+
+type Methods = ReturnType<typeof createMethods>;
+type Overrides = Partial<TCustomConfig>;
+
+const YAML: Parameters<typeof AppService>[0] = {
+ config: {
+ registration: { socialLogins: ['github'] },
+ turnstile: { siteKey: 'yaml-site-key' },
+ interface: { privacyPolicy: { externalUrl: 'https://yaml.example/privacy' } },
+ },
+};
+
+let mongoServer: MongoMemoryServer;
+let methods: Methods;
+
+function createCache() {
+ const store = new Map<string, unknown>();
+ return {
+ get: async (key: string) => store.get(key),
+ set: async (key: string, value: unknown) => {
+ store.set(key, value);
+ return true;
+ },
+ delete: async (key: string) => store.delete(key),
+ };
+}
+
+/** A fresh service per test, so no merged config is served from an earlier test's cache. */
+function createService(getApplicableConfigs: Methods['getApplicableConfigs']) {
+ const cache = createCache();
+ return createAppConfigService({
+ loadBaseConfig: () => AppService(YAML),
+ setCachedTools: async () => undefined,
+ getCache: () => cache,
+ cacheKeys: { APP_CONFIG: 'app_config' },
+ getApplicableConfigs,
+ getUserPrincipals: methods.getUserPrincipals,
+ }).getAppConfig;
+}
+
+function storeOverrides(principalId: string, overrides: Overrides, priority = 10) {
+ return methods.upsertConfig(
+ PrincipalType.ROLE,
+ principalId,
+ PrincipalModel.ROLE,
+ overrides,
+ principalId === BASE_CONFIG_PRINCIPAL_ID ? 0 : priority,
+ );
+}
+
+const inTenant = <T>(tenantId: string, fn: () => Promise<T>): Promise<T> =>
+ tenantStorage.run({ tenantId }, fn);
+
+const domains = (config: AppConfig): string[] | undefined =>
+ config.registration?.allowedDomains ?? undefined;
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ /** Building every model's indexes is slow and none of these queries depends on one. */
+ await mongoose.connect(mongoServer.getUri(), { autoIndex: false });
+ createModels(mongoose);
+ methods = createMethods(mongoose);
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+beforeEach(async () => {
+ await Promise.all([mongoose.models.Config.deleteMany({}), mongoose.models.User.deleteMany({})]);
+ jest.spyOn(logger, 'error').mockReturnValue(logger);
+ jest.spyOn(logger, 'info').mockReturnValue(logger);
+});
+
+describe('pre-auth allowedDomains', () => {
+ beforeEach(async () => {
+ await storeOverrides(BASE_CONFIG_PRINCIPAL_ID, {
+ registration: { allowedDomains: ['corp.example', 'partner.example'] },
+ });
+ await inTenant('tenant-b', () =>
+ storeOverrides(BASE_CONFIG_PRINCIPAL_ID, {
+ registration: { allowedDomains: ['tenant-b.example'] },
+ }),
+ );
+ await storeOverrides('USER', { registration: { allowedDomains: ['corp.example'] } });
+ await inTenant('tenant-b', () =>
+ storeOverrides('USER', { registration: { allowedDomains: ['open.example'] } }),
+ );
+ });
+
+ it("applies the deployment's __base__ override before the user is known", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await resolvePreAuthAppConfig(getAppConfig);
+
+ expect(domains(config)).toEqual(['corp.example', 'partner.example']);
+ expect(isEmailDomainAllowed('[email protected]', domains(config))).toBe(false);
+ });
+
+ it("never merges another tenant's __base__ into the deployment's", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await resolvePreAuthAppConfig(getAppConfig);
+
+ expect(isEmailDomainAllowed('[email protected]', domains(config))).toBe(false);
+ });
+
+ it("applies the tenant's own __base__ inside a tenant", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await inTenant('tenant-b', () => resolvePreAuthAppConfig(getAppConfig));
+
+ expect(domains(config)).toEqual(['tenant-b.example']);
+ });
+
+ it('keeps each tenant and the deployment apart in one shared cache', async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const tenantB = await inTenant('tenant-b', () => resolvePreAuthAppConfig(getAppConfig));
+ const tenantA = await inTenant('tenant-a', () => resolvePreAuthAppConfig(getAppConfig));
+ const deployment = await resolvePreAuthAppConfig(getAppConfig);
+
+ expect(domains(tenantB)).toEqual(['tenant-b.example']);
+ expect(domains(tenantA)).toBeUndefined();
+ expect(domains(deployment)).toEqual(['corp.example', 'partner.example']);
+ });
+
+ it("reads only the deployment's __base__ under the system sentinel", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await runAsSystem(() => resolvePreAuthAppConfig(getAppConfig));
+
+ expect(domains(config)).toEqual(['corp.example', 'partner.example']);
+ });
+
+ it('narrows the list by role for a known user without a tenant', async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await resolveAppConfigForUser(getAppConfig, { role: 'USER' });
+
+ expect(domains(config)).toEqual(['corp.example']);
+ expect(isEmailDomainAllowed('[email protected]', domains(config))).toBe(false);
+ });
+
+ it("resolves a tenant user's role in that tenant only", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await resolveAppConfigForUser(getAppConfig, {
+ role: 'USER',
+ tenantId: 'tenant-b',
+ });
+
+ expect(domains(config)).toEqual(['open.example']);
+ });
+
+ describe('a first sign-in, under the role the new account is created with', () => {
+ function firstLogin(
+ getAppConfig: ReturnType<typeof createService>,
+ email: string,
+ role?: string,
+ ) {
+ return createUserOnce({
+ newUser: { provider: 'saml', samlId: email, email, username: email, role },
+ email,
+ getAppConfig,
+ getBalanceConfig: () => null,
+ lookup: async () => ({ user: await methods.findUser({ email }), error: null }),
+ strategyName: 'samlStrategy',
+ createUserIfAbsent: methods.createUserIfAbsent,
+ findBalanceByUser: methods.findBalanceByUser,
+ });
+ }
+
+ it("refuses a domain the USER role's list excludes, creating nothing", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const result = await firstLogin(getAppConfig, '[email protected]');
+
+ expect(result).toEqual({ user: null, error: 'Email domain not allowed', created: false });
+ expect(await mongoose.models.User.countDocuments()).toBe(0);
+ });
+
+ it("creates the account when the USER role's list admits the domain", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const result = await firstLogin(getAppConfig, '[email protected]');
+
+ expect(result.created).toBe(true);
+ expect(result.user && domains(result.appConfig)).toEqual(['corp.example']);
+ });
+
+ it("admits an ADMIN account under the ADMIN role's config", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const result = await firstLogin(getAppConfig, '[email protected]', SystemRoles.ADMIN);
+
+ expect(result.user).toEqual(expect.objectContaining({ role: SystemRoles.ADMIN }));
+ });
+ });
+
+ it('fails closed when overrides cannot be read', async () => {
+ const getApplicableConfigs = jest
+ .fn<
+ ReturnType<Methods['getApplicableConfigs']>,
+ Parameters<Methods['getApplicableConfigs']>
+ >()
+ .mockRejectedValue(new Error('override read failed'));
+ const getAppConfig = createService(getApplicableConfigs);
+
+ await expect(resolvePreAuthAppConfig(getAppConfig)).rejects.toThrow('override read failed');
+ await expect(resolveAppConfigForUser(getAppConfig, { role: 'USER' })).rejects.toThrow(
+ 'override read failed',
+ );
+ });
+});
+
+describe('signed-out startup config', () => {
+ beforeEach(async () => {
+ await storeOverrides(BASE_CONFIG_PRINCIPAL_ID, {
+ registration: { socialLogins: ['google', 'openid'] },
+ turnstile: { siteKey: 'stored-site-key' },
+ interface: { privacyPolicy: { externalUrl: 'https://base.example/privacy' } },
+ });
+ await inTenant('tenant-a', () =>
+ storeOverrides(BASE_CONFIG_PRINCIPAL_ID, {
+ registration: { socialLogins: ['discord'] },
+ turnstile: { siteKey: 'tenant-a-site-key' },
+ }),
+ );
+ await storeOverrides('USER', { registration: { socialLogins: ['facebook'] } });
+ });
+
+ it('serves the __base__ override, keeping Turnstile on librechat.yaml', async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await resolvePreLoginAppConfig(getAppConfig);
+
+ expect(config.registration?.socialLogins).toEqual(['google', 'openid']);
+ expect(config.interfaceConfig?.privacyPolicy?.externalUrl).toBe('https://base.example/privacy');
+ expect(config.turnstileConfig?.siteKey).toBe('yaml-site-key');
+ });
+
+ it("serves a tenant its own __base__, but Turnstile from librechat.yaml, not the tenant's", async () => {
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await inTenant('tenant-a', () => resolvePreLoginAppConfig(getAppConfig));
+
+ expect(config.registration?.socialLogins).toEqual(['discord']);
+ expect(config.turnstileConfig?.siteKey).toBe('yaml-site-key');
+ });
+
+ it('keeps Turnstile on librechat.yaml for a signed-in user too', async () => {
+ await storeOverrides('USER', { turnstile: { siteKey: 'role-site-key' } });
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await getAppConfig({ role: 'USER' });
+
+ expect(config.turnstileConfig?.siteKey).toBe('yaml-site-key');
+ });
+
+ it('drops a stored script URL from the policy links, keeping their other settings', async () => {
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ await storeOverrides(BASE_CONFIG_PRINCIPAL_ID, {
+ interface: {
+ privacyPolicy: { externalUrl: 'javascript:alert(document.domain)', openNewTab: true },
+ termsOfService: { externalUrl: 'https://base.example/terms' },
+ },
+ });
+ const getAppConfig = createService(methods.getApplicableConfigs);
+
+ const config = await resolvePreLoginAppConfig(getAppConfig);
+
+ expect(config.interfaceConfig?.privacyPolicy).toEqual({
+ externalUrl: 'https://yaml.example/privacy',
+ openNewTab: true,
+ });
+ expect(buildPreLoginInterface(config.interfaceConfig)).toEqual({
+ privacyPolicy: { externalUrl: 'https://yaml.example/privacy', openNewTab: true },
+ termsOfService: { externalUrl: 'https://base.example/terms' },
+ });
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('Ignoring invalid override "interface.privacyPolicy.externalUrl"'),
+ );
+ });
+
+ it('falls back to librechat.yaml when overrides cannot be read', async () => {
+ const getApplicableConfigs = jest
+ .fn<
+ ReturnType<Methods['getApplicableConfigs']>,
+ Parameters<Methods['getApplicableConfigs']>
+ >()
+ .mockRejectedValue(new Error('override read failed'));
+ const getAppConfig = createService(getApplicableConfigs);
+
+ const config = await resolvePreLoginAppConfig(getAppConfig);
+
+ expect(config.registration?.socialLogins).toEqual(['github']);
+ expect(config.turnstileConfig?.siteKey).toBe('yaml-site-key');
+ });
+
+ it('reads the overrides once per cache lifetime', async () => {
+ const getApplicableConfigs = jest.fn(methods.getApplicableConfigs);
+ const getAppConfig = createService(getApplicableConfigs);
+
+ await resolvePreLoginAppConfig(getAppConfig);
+ await resolvePreLoginAppConfig(getAppConfig);
+ await resolvePreAuthAppConfig(getAppConfig);
+
+ expect(getApplicableConfigs).toHaveBeenCalledTimes(1);
+ expect(getApplicableConfigs).toHaveBeenCalledWith([]);
+ });
+});
diff --git a/packages/api/src/app/resolve.spec.ts b/packages/api/src/app/resolve.spec.ts
index d7585198a0..f97c280d44 100644
--- a/packages/api/src/app/resolve.spec.ts
+++ b/packages/api/src/app/resolve.spec.ts
@@ -3,15 +3,75 @@ import type { AsyncLocalStorage } from 'async_hooks';
jest.mock('@librechat/data-schemas', () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { AsyncLocalStorage: ALS } = require('async_hooks');
- return { tenantStorage: new ALS() };
+ const tenantStorage = new ALS();
+ return { tenantStorage, getTenantId: () => tenantStorage.getStore()?.tenantId };
});
-import { resolveAppConfigForUser } from './resolve';
+import type { AppConfig } from '@librechat/data-schemas';
+import type { GetAppConfigOptions } from './service';
+import {
+ resolveAppConfigForUser,
+ resolvePreAuthAppConfig,
+ resolvePreLoginAppConfig,
+} from './resolve';
const { tenantStorage } = jest.requireMock('@librechat/data-schemas') as {
tenantStorage: AsyncLocalStorage<{ tenantId?: string }>;
};
+const PRE_AUTH = { skipRuntimeAugmentation: true, failClosed: true };
+
+describe('resolvePreAuthAppConfig', () => {
+ const mockGetAppConfig = jest.fn();
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockGetAppConfig.mockResolvedValue({ registration: {} });
+ });
+
+ it('reads the base principal only, without augmentation, failing closed', async () => {
+ await resolvePreAuthAppConfig(mockGetAppConfig);
+ expect(mockGetAppConfig).toHaveBeenCalledTimes(1);
+ expect(mockGetAppConfig).toHaveBeenCalledWith(PRE_AUTH);
+ });
+
+ it('propagates an override read failure instead of returning librechat.yaml', async () => {
+ mockGetAppConfig.mockRejectedValue(new Error('overrides unavailable'));
+ await expect(resolvePreAuthAppConfig(mockGetAppConfig)).rejects.toThrow(
+ 'overrides unavailable',
+ );
+ });
+});
+
+describe('resolvePreLoginAppConfig', () => {
+ const mergedConfig: Partial<AppConfig> = { registration: { socialLogins: ['google'] } };
+ const getAppConfig = jest.fn(async (_options: GetAppConfigOptions) => mergedConfig as AppConfig);
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('serves the base override in one read, with or without a tenant', async () => {
+ const outside = await resolvePreLoginAppConfig(getAppConfig);
+ const inside = await tenantStorage.run({ tenantId: 'tenant-a' }, () =>
+ resolvePreLoginAppConfig(getAppConfig),
+ );
+
+ expect(getAppConfig).toHaveBeenCalledTimes(2);
+ expect(getAppConfig).toHaveBeenNthCalledWith(1, { skipRuntimeAugmentation: true });
+ expect(getAppConfig).toHaveBeenNthCalledWith(2, { skipRuntimeAugmentation: true });
+ expect(outside.registration).toEqual({ socialLogins: ['google'] });
+ expect(inside).toBe(outside);
+ });
+
+ it('does not fail closed, so the sign-in page still renders from the YAML fallback', async () => {
+ await resolvePreLoginAppConfig(getAppConfig);
+ for (const [options] of getAppConfig.mock.calls) {
+ expect(options.failClosed).toBeUndefined();
+ }
+ });
+});
+
describe('resolveAppConfigForUser', () => {
const mockGetAppConfig = jest.fn();
@@ -20,24 +80,28 @@ describe('resolveAppConfigForUser', () => {
mockGetAppConfig.mockResolvedValue({ registration: {} });
});
- it('calls getAppConfig with baseOnly when user is null', async () => {
+ it('resolves the pre-auth config when user is null', async () => {
await resolveAppConfigForUser(mockGetAppConfig, null);
- expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(mockGetAppConfig).toHaveBeenCalledWith(PRE_AUTH);
});
- it('calls getAppConfig with baseOnly when user is undefined', async () => {
+ it('resolves the pre-auth config when user is undefined', async () => {
await resolveAppConfigForUser(mockGetAppConfig, undefined);
- expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(mockGetAppConfig).toHaveBeenCalledWith(PRE_AUTH);
});
- it('calls getAppConfig with baseOnly when user has no tenantId', async () => {
+ it('applies role overrides for a user without a tenant', async () => {
await resolveAppConfigForUser(mockGetAppConfig, { role: 'USER' });
- expect(mockGetAppConfig).toHaveBeenCalledWith({ baseOnly: true });
+ expect(mockGetAppConfig).toHaveBeenCalledWith({ ...PRE_AUTH, role: 'USER' });
});
it('calls getAppConfig with role and tenantId when user has tenantId', async () => {
await resolveAppConfigForUser(mockGetAppConfig, { tenantId: 'tenant-a', role: 'USER' });
- expect(mockGetAppConfig).toHaveBeenCalledWith({ role: 'USER', tenantId: 'tenant-a' });
+ expect(mockGetAppConfig).toHaveBeenCalledWith({
+ ...PRE_AUTH,
+ role: 'USER',
+ tenantId: 'tenant-a',
+ });
});
it('calls tenantStorage.run for tenant users but not for non-tenant users', async () => {
@@ -78,7 +142,11 @@ describe('resolveAppConfigForUser', () => {
it('calls getAppConfig with role undefined when user has tenantId but no role', async () => {
await resolveAppConfigForUser(mockGetAppConfig, { tenantId: 'tenant-e' });
- expect(mockGetAppConfig).toHaveBeenCalledWith({ role: undefined, tenantId: 'tenant-e' });
+ expect(mockGetAppConfig).toHaveBeenCalledWith({
+ ...PRE_AUTH,
+ role: undefined,
+ tenantId: 'tenant-e',
+ });
});
it('propagates rejection from getAppConfig for tenant users', async () => {
@@ -88,8 +156,11 @@ describe('resolveAppConfigForUser', () => {
).rejects.toThrow('config unavailable');
});
- it('propagates rejection from getAppConfig for baseOnly path', async () => {
+ it('propagates rejection from getAppConfig for users without a tenant', async () => {
mockGetAppConfig.mockRejectedValue(new Error('cache failure'));
+ await expect(resolveAppConfigForUser(mockGetAppConfig, { role: 'USER' })).rejects.toThrow(
+ 'cache failure',
+ );
await expect(resolveAppConfigForUser(mockGetAppConfig, null)).rejects.toThrow('cache failure');
});
});
diff --git a/packages/api/src/app/resolve.ts b/packages/api/src/app/resolve.ts
index 0810400222..4fcdfc12dd 100644
--- a/packages/api/src/app/resolve.ts
+++ b/packages/api/src/app/resolve.ts
@@ -1,20 +1,43 @@
import { tenantStorage } from '@librechat/data-schemas';
import type { AppConfig } from '@librechat/data-schemas';
+import type { GetAppConfigOptions } from './service';
interface UserForConfigResolution {
tenantId?: string;
role?: string;
}
-type GetAppConfig = (opts: {
- role?: string;
- tenantId?: string;
- baseOnly?: boolean;
-}) => Promise<AppConfig>;
+type GetAppConfig = (opts: GetAppConfigOptions) => Promise<AppConfig>;
+
+/**
+ * Config for a sign-in decision made before the user is known, such as the
+ * `registration.allowedDomains` check: librechat.yaml plus the `__base__` override of the
+ * request's tenant, or of the deployment outside a tenant (tenant from ALS). No principal is
+ * resolved, so nothing role-, group- or user-scoped is read.
+ *
+ * Fails closed: librechat.yaml alone can be broader than the policy an admin stored, so an
+ * override read failure must not decide sign-in on the YAML.
+ */
+export function resolvePreAuthAppConfig(getAppConfig: GetAppConfig): Promise<AppConfig> {
+ return getAppConfig({ skipRuntimeAugmentation: true, failClosed: true });
+}
+
+/**
+ * Config for the signed-out startup payload (`GET /api/config` without a session): the
+ * pre-auth config, falling back to librechat.yaml when overrides cannot be read, since it only
+ * renders the sign-in pages. Turnstile comes from librechat.yaml here as everywhere, because
+ * `turnstile` is a base-only section that no config document overrides.
+ */
+export function resolvePreLoginAppConfig(getAppConfig: GetAppConfig): Promise<AppConfig> {
+ return getAppConfig({ skipRuntimeAugmentation: true });
+}
/**
- * Resolves AppConfig scoped to the given user's tenant when available,
- * falling back to YAML-only base config for new users or non-tenant deployments.
+ * Resolves the config a sign-in continues under once the user is known: the pre-auth config
+ * plus the user's role overrides, in the user's tenant when it has one. An account about to be
+ * created is passed as its role alone and resolves in the request's tenant (ALS), the tenant it
+ * will be created in. Without a user it is the pre-auth config. Fails closed like
+ * `resolvePreAuthAppConfig`.
*
* Auth flows only apply role-level overrides (userId is not passed) because
* user/group principal resolution requires heavier DB work that is deferred
@@ -30,10 +53,17 @@ export async function resolveAppConfigForUser(
getAppConfig: GetAppConfig,
user: UserForConfigResolution | null | undefined,
): Promise<AppConfig> {
- if (user?.tenantId) {
- return tenantStorage.run({ tenantId: user.tenantId }, async () =>
- getAppConfig({ role: user.role, tenantId: user.tenantId }),
- );
+ if (!user) {
+ return resolvePreAuthAppConfig(getAppConfig);
+ }
+ const options: GetAppConfigOptions = {
+ role: user.role,
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ };
+ const { tenantId } = user;
+ if (tenantId) {
+ return tenantStorage.run({ tenantId }, async () => getAppConfig({ ...options, tenantId }));
}
- return getAppConfig({ baseOnly: true });
+ return getAppConfig(options);
}
diff --git a/packages/api/src/app/service.ts b/packages/api/src/app/service.ts
index 55aaac7e0a..e343eae98e 100644
--- a/packages/api/src/app/service.ts
+++ b/packages/api/src/app/service.ts
@@ -558,7 +558,8 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
*
* When `baseOnly` is true, returns the YAML-derived config without any DB queries.
* `role` and `userId` are ignored; tenantId still scopes YAML custom endpoints.
- * Use this for startup, auth strategies, and other pre-tenant code paths.
+ * Use this for startup and other paths that must not read overrides; sign-in decisions
+ * read the `__base__` override through `resolvePreAuthAppConfig`.
*/
async function getAppConfig(options: GetAppConfigOptions = {}): Promise<AppConfig> {
const {
@@ -604,9 +605,9 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
return scopedBaseConfig;
}
- // Strict isolation + no tenant anywhere (neither param nor ALS) is pathological: a
- // middleware bypass or an unauthenticated startup call. Pre-tenant calls should use
- // baseOnly:true and admin calls carry an explicit tenantId. Return the base config
+ // Strict isolation + no tenant anywhere (neither param nor ALS): a middleware bypass,
+ // or a signed-out request that named no tenant (strict mode refuses config reads without
+ // one). Admin calls carry an explicit tenantId. Return the base config
// without caching it under the shared `__default__` bucket. When ALS has a tenant,
// overrideCacheKey scopes the key to it, so we fall through and cache per-tenant.
if (principals.length === 0 && !tenantId && !getTenantId() && isStrictOverrideMode()) {
diff --git a/packages/api/src/auth/ldap.ts b/packages/api/src/auth/ldap.ts
index 678fd658a5..1c5ba5a5f9 100644
--- a/packages/api/src/auth/ldap.ts
+++ b/packages/api/src/auth/ldap.ts
@@ -31,9 +31,11 @@ export async function findLdapUser({
/**
* Resolves the account an LDAP login continues as, carrying the directory's values: LDAP manages
* these users' identity, so provider, `ldapId`, email, username and name are overwritten on every
- * login. Without an account, the user is created through `createUserOnce` (the deployment's first
- * user as ADMIN), and an account a concurrent first login created is admitted like a found account
- * and refreshed the same way. Returns the account with the config the login continues under.
+ * login. A found account continues under `appConfig`, its own config. Without an account, the
+ * user is created through `createUserOnce` (the deployment's first user as ADMIN), which admits
+ * it under that role's config, and an account a concurrent first login created is admitted like a
+ * found account and refreshed the same way. Returns the account with the config the login
+ * continues under.
*/
export async function provisionLdapUser({
user,
@@ -69,7 +71,6 @@ export async function provisionLdapUser({
const result = await createUserOnce({
newUser: { provider: 'ldap', ldapId, username, email, emailVerified: true, name, role },
email,
- appConfig,
getAppConfig,
getBalanceConfig,
strategyName: 'ldapStrategy',
diff --git a/packages/api/src/auth/openid.spec.ts b/packages/api/src/auth/openid.spec.ts
index 5548bba312..7e4fe4e84a 100644
--- a/packages/api/src/auth/openid.spec.ts
+++ b/packages/api/src/auth/openid.spec.ts
@@ -1,6 +1,6 @@
import mongoose, { Types } from 'mongoose';
-import { ErrorTypes } from 'librechat-data-provider';
import { MongoMemoryServer } from 'mongodb-memory-server';
+import { ErrorTypes, SystemRoles } from 'librechat-data-provider';
import { logger, tenantStorage, createMethods, createModels } from '@librechat/data-schemas';
import type { IUser, AppConfig, UserMethods } from '@librechat/data-schemas';
import type { CommandStartedEvent } from 'mongodb';
@@ -1035,14 +1035,15 @@ describe('createOpenIDUser', () => {
return { findUser: methods.findUser, email, openidId, openidIssuer: issuer };
}
- function firstLogin(
- balance?: { enabled: boolean; startBalance: number },
- overrides: Partial<Parameters<typeof createOpenIDUser>[0]> = {},
- ) {
+ /** Answers the new account's config read, then the read of the account a lookup recovers. */
+ function configsFor(newAccount: AppConfig, recovered: AppConfig): void {
+ getAppConfig.mockResolvedValueOnce(newAccount).mockResolvedValueOnce(recovered);
+ }
+
+ function firstLogin(overrides: Partial<Parameters<typeof createOpenIDUser>[0]> = {}) {
return createOpenIDUser({
lookup: getLookup(),
profile,
- appConfig: appConfigWith(balance),
getAppConfig,
getBalanceConfig: (config: AppConfig) => config.balance ?? null,
createUserIfAbsent: methods.createUserIfAbsent,
@@ -1066,6 +1067,7 @@ describe('createOpenIDUser', () => {
beforeEach(async () => {
jest.clearAllMocks();
+ getAppConfig.mockReset().mockResolvedValue(appConfigWith());
await mongoose.connection.dropDatabase();
await User.syncIndexes();
});
@@ -1092,7 +1094,7 @@ describe('createOpenIDUser', () => {
emailVerified: false,
};
- const { user } = await firstLogin(undefined, {
+ const { user } = await firstLogin({
lookup: { ...getLookup(), email: renamed.email },
profile: renamed,
});
@@ -1109,9 +1111,9 @@ describe('createOpenIDUser', () => {
});
it('credits the start balance once across concurrent first logins', async () => {
- const balance = { enabled: true, startBalance: 500 };
+ getAppConfig.mockResolvedValue(appConfigWith({ enabled: true, startBalance: 500 }));
- const [{ user }] = await Promise.all([firstLogin(balance), firstLogin(balance)]);
+ const [{ user }] = await Promise.all([firstLogin(), firstLogin()]);
const balances = await mongoose.models.Balance.find({ user: user._id }).lean<
Array<{ tokenCredits: number }>
@@ -1121,8 +1123,9 @@ describe('createOpenIDUser', () => {
it('fails the recovered login while the winner has not credited its start balance yet', async () => {
await User.create({ email, provider: 'openid', openidId, openidIssuer: issuer });
+ getAppConfig.mockResolvedValue(appConfigWith({ enabled: true, startBalance: 500 }));
- const login = firstLogin({ enabled: true, startBalance: 500 });
+ const login = firstLogin();
await expect(login).rejects.toThrow(ErrorTypes.AUTH_FAILED);
expect(await mongoose.models.Balance.countDocuments()).toBe(0);
@@ -1130,8 +1133,9 @@ describe('createOpenIDUser', () => {
it('recovers an account created without a balance when no start balance is configured', async () => {
await User.create({ email, provider: 'openid', openidId, openidIssuer: issuer });
+ getAppConfig.mockResolvedValue(appConfigWith({ enabled: true, startBalance: 0 }));
- const { user } = await firstLogin({ enabled: true, startBalance: 0 });
+ const { user } = await firstLogin();
expect(user).toEqual(expect.objectContaining({ openidId, email }));
});
@@ -1140,7 +1144,7 @@ describe('createOpenIDUser', () => {
await tenantStorage.run({ tenantId }, () =>
User.create({ email, provider: 'openid', openidId, openidIssuer: issuer }),
);
- getAppConfig.mockResolvedValueOnce(appConfigWith(undefined, ['other.example']));
+ configsFor(appConfigWith(), appConfigWith(undefined, ['other.example']));
const login = tenantStorage.run({ tenantId }, () => firstLogin());
@@ -1152,7 +1156,7 @@ describe('createOpenIDUser', () => {
await tenantStorage.run({ tenantId }, () =>
User.create({ email, provider: 'openid', openidId, openidIssuer: issuer }),
);
- getAppConfig.mockResolvedValueOnce(appConfigWith({ enabled: true, startBalance: 500 }));
+ configsFor(appConfigWith(), appConfigWith({ enabled: true, startBalance: 500 }));
const login = await tenantStorage.run({ tenantId }, () => firstLogin());
@@ -1163,12 +1167,13 @@ describe('createOpenIDUser', () => {
await tenantStorage.run({ tenantId }, () =>
User.create({ email, provider: 'openid', openidId, openidIssuer: issuer }),
);
- getAppConfig.mockResolvedValueOnce(appConfigWith({ enabled: false, startBalance: 0 }));
-
- const login = tenantStorage.run({ tenantId }, () =>
- firstLogin({ enabled: true, startBalance: 500 }),
+ configsFor(
+ appConfigWith({ enabled: true, startBalance: 500 }),
+ appConfigWith({ enabled: false, startBalance: 0 }),
);
+ const login = tenantStorage.run({ tenantId }, () => firstLogin());
+
await expect(login).rejects.toThrow(ErrorTypes.AUTH_FAILED);
});
@@ -1177,7 +1182,7 @@ describe('createOpenIDUser', () => {
User.create({ email, provider: 'openid', openidId, openidIssuer: issuer }),
);
const tenantConfig = appConfigWith(undefined, ['example.com']);
- getAppConfig.mockResolvedValueOnce(tenantConfig);
+ configsFor(appConfigWith(), tenantConfig);
const login = await tenantStorage.run({ tenantId }, () => firstLogin());
@@ -1185,6 +1190,50 @@ describe('createOpenIDUser', () => {
expect(login.user).toEqual(expect.objectContaining({ openidId, tenantId }));
});
+ it("refuses a first login the USER role's domain list excludes, creating nothing", async () => {
+ getAppConfig.mockResolvedValueOnce(appConfigWith(undefined, ['other.example']));
+
+ await expect(firstLogin()).rejects.toThrow('Email domain not allowed');
+ expect(getAppConfig).toHaveBeenCalledWith({
+ role: SystemRoles.USER,
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ });
+ expect(await User.countDocuments()).toBe(0);
+ });
+
+ it('creates the account in the USER role and reports that this call created it', async () => {
+ const login = await firstLogin({ claimedRole: SystemRoles.ADMIN });
+
+ expect(login.created).toBe(true);
+ expect(login.user).toEqual(expect.objectContaining({ role: SystemRoles.USER }));
+ expect(getAppConfig).toHaveBeenCalledWith({
+ role: SystemRoles.ADMIN,
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+ });
+ });
+
+ it('refuses a first login the role its claims assign excludes, creating nothing', async () => {
+ getAppConfig
+ .mockResolvedValueOnce(appConfigWith({ enabled: true, startBalance: 500 }))
+ .mockResolvedValueOnce(appConfigWith(undefined, ['other.example']));
+
+ await expect(firstLogin({ claimedRole: SystemRoles.ADMIN })).rejects.toThrow(
+ 'Email domain not allowed',
+ );
+ expect(await User.countDocuments()).toBe(0);
+ expect(await mongoose.models.Balance.countDocuments()).toBe(0);
+ });
+
+ it('reports a recovered account as not created by this call', async () => {
+ await firstLogin();
+
+ const login = await firstLogin();
+
+ expect(login.created).toBe(false);
+ });
+
it('fails the login when the email was taken by another provider in the meantime', async () => {
await User.create({ email, provider: 'local', username: 'local-user' });
@@ -1195,7 +1244,7 @@ describe('createOpenIDUser', () => {
it('throws when the lookup cannot account for the existing account', async () => {
await User.create({ email: '[email protected]', provider: 'openid', openidId: 'other-sub' });
- const login = firstLogin(undefined, {
+ const login = firstLogin({
lookup: { findUser: methods.findUser, openidId, openidIssuer: issuer },
profile: { ...profile, email: '[email protected]' },
});
@@ -1206,7 +1255,7 @@ describe('createOpenIDUser', () => {
it('rethrows other create failures without a second lookup', async () => {
const findUser = jest.fn(methods.findUser);
- const login = firstLogin(undefined, {
+ const login = firstLogin({
lookup: { ...getLookup(), findUser },
profile: { ...profile, email: 'not-an-email' },
});
diff --git a/packages/api/src/auth/openid.ts b/packages/api/src/auth/openid.ts
index 91a966f6a7..14e7ec6b48 100644
--- a/packages/api/src/auth/openid.ts
+++ b/packages/api/src/auth/openid.ts
@@ -1,5 +1,5 @@
import { logger } from '@librechat/data-schemas';
-import { ErrorTypes } from 'librechat-data-provider';
+import { ErrorTypes, SystemRoles } from 'librechat-data-provider';
import type { IUser, AppConfig, UserMethods, UserRecord } from '@librechat/data-schemas';
import type { FilterQuery } from 'mongoose';
import type {
@@ -337,17 +337,19 @@ export function applyOpenIDProfile<T extends UserRecord>(user: T, profile: OpenI
}
/**
- * Creates a first-login OpenID user through `createUserOnce`, which recovers a concurrent first
- * login by repeating `findOpenIDUser`, with its provider and issuer checks, once the winner
- * finished provisioning the account, and admits that account exactly as a found one (tenant
- * config and email-domain policy). The recovered account is refreshed with this callback's
- * claims like any account the lookup finds. Returns the account with the config the login
- * continues under (`appConfig` for a user this request created).
+ * Creates a first-login OpenID user, in the USER role, through `createUserOnce`, which admits it
+ * under the USER role's config and under `claimedRole`'s, the role this login's claims move it
+ * into, before creating it. It recovers a concurrent first login by repeating `findOpenIDUser`,
+ * with its provider and issuer checks, once the winner finished provisioning the account,
+ * admitting that account exactly as a found one (its own config and email-domain policy). The
+ * recovered account is refreshed with this callback's claims like any account the lookup finds.
+ * Returns the account with the config the login continues under, and whether this call
+ * created it.
*/
export async function createOpenIDUser({
lookup,
profile,
- appConfig,
+ claimedRole,
getAppConfig,
getBalanceConfig,
createUserIfAbsent,
@@ -355,16 +357,17 @@ export async function createOpenIDUser({
}: {
lookup: Parameters<typeof findOpenIDUser>[0];
profile: OpenIDProfile;
- appConfig: AppConfig;
+ claimedRole?: string;
getAppConfig: GetAppConfig;
getBalanceConfig: GetBalanceConfig;
createUserIfAbsent: CreateUserIfAbsent;
findBalanceByUser: FindBalanceByUser;
-}): Promise<{ user: UserRecord; appConfig: AppConfig }> {
+}): Promise<{ user: UserRecord; appConfig: AppConfig; created: boolean }> {
const result = await createUserOnce({
strategyName: lookup.strategyName ?? 'openid',
newUser: {
provider: 'openid',
+ role: SystemRoles.USER,
openidId: profile.openidId,
username: profile.username,
email: profile.email || '',
@@ -374,7 +377,7 @@ export async function createOpenIDUser({
openidIssuer: profile.openidIssuer,
},
email: profile.email ?? '',
- appConfig,
+ claimedRole,
getAppConfig,
getBalanceConfig,
lookup: () => findOpenIDUser(lookup),
@@ -385,5 +388,6 @@ export async function createOpenIDUser({
return {
user: result.created ? result.user : applyOpenIDProfile(result.user, profile),
appConfig: result.appConfig,
+ created: result.created,
};
}
diff --git a/packages/api/src/auth/provision.spec.ts b/packages/api/src/auth/provision.spec.ts
index 6ac83c8c7c..4c49b932b7 100644
--- a/packages/api/src/auth/provision.spec.ts
+++ b/packages/api/src/auth/provision.spec.ts
@@ -1,7 +1,7 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { ErrorTypes, SystemRoles } from 'librechat-data-provider';
-import { tenantStorage, createMethods, createModels } from '@librechat/data-schemas';
+import { getTenantId, tenantStorage, createMethods, createModels } from '@librechat/data-schemas';
import type { IUser, AppConfig, UserRecord } from '@librechat/data-schemas';
import type { LoginUserResolution } from './provision';
import { provisionSocialUser } from './social';
@@ -27,6 +27,7 @@ afterAll(async () => {
});
beforeEach(async () => {
+ getAppConfig.mockReset().mockResolvedValue(baseConfig);
await mongoose.connection.dropDatabase();
await User.syncIndexes();
});
@@ -43,9 +44,20 @@ function appConfigWith(
}
const baseConfig = appConfigWith();
+const startBalance = { enabled: true, startBalance: 500 };
const getAppConfig = jest.fn(async (): Promise<AppConfig> => baseConfig);
const getBalanceConfig = (config: AppConfig) => config.balance ?? null;
-const admission = { appConfig: baseConfig, getAppConfig, getBalanceConfig };
+const admission = { getAppConfig, getBalanceConfig };
+const roleConfigRead = (role: string) => ({
+ role,
+ skipRuntimeAugmentation: true,
+ failClosed: true,
+});
+
+/** Answers the new account's config read, then the read of the account a lookup recovers. */
+function configsFor(newAccount: AppConfig, recovered: AppConfig): void {
+ getAppConfig.mockResolvedValueOnce(newAccount).mockResolvedValueOnce(recovered);
+}
describe('createUserOnce', () => {
const email = '[email protected]';
@@ -71,6 +83,101 @@ describe('createUserOnce', () => {
});
}
+ it('creates the account under the config of the role it is created with', async () => {
+ const roleConfig = appConfigWith(['example.com'], startBalance);
+ getAppConfig.mockResolvedValueOnce(roleConfig);
+
+ const result = await firstLogin();
+
+ expect(result).toEqual(
+ expect.objectContaining({ created: true, error: null, appConfig: roleConfig }),
+ );
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead(SystemRoles.USER));
+ expect(await findBalanceByUser(result.user!._id.toString())).toEqual(
+ expect.objectContaining({ tokenCredits: 500 }),
+ );
+ });
+
+ it('refuses a new account whose role config excludes the domain, creating nothing', async () => {
+ getAppConfig.mockResolvedValueOnce(appConfigWith(['other.example']));
+ const createUserIfAbsent = jest.fn(methods.createUserIfAbsent);
+
+ const result = await firstLogin(lookupByEmail, { createUserIfAbsent });
+
+ expect(result).toEqual({ user: null, error: 'Email domain not allowed', created: false });
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ expect(await User.countDocuments()).toBe(0);
+ });
+
+ it('refuses a new account the role its login claims excludes, creating nothing', async () => {
+ getAppConfig
+ .mockResolvedValueOnce(baseConfig)
+ .mockResolvedValueOnce(appConfigWith(['other.example']));
+ const createUserIfAbsent = jest.fn(methods.createUserIfAbsent);
+
+ const result = await firstLogin(lookupByEmail, {
+ claimedRole: 'BASIC-USER',
+ createUserIfAbsent,
+ });
+
+ expect(result).toEqual({ user: null, error: 'Email domain not allowed', created: false });
+ expect(getAppConfig).toHaveBeenNthCalledWith(1, roleConfigRead(SystemRoles.USER));
+ expect(getAppConfig).toHaveBeenNthCalledWith(2, roleConfigRead('BASIC-USER'));
+ expect(createUserIfAbsent).not.toHaveBeenCalled();
+ expect(await User.countDocuments()).toBe(0);
+ });
+
+ it('creates the account under its own role config once the claimed role admits the email', async () => {
+ const roleConfig = appConfigWith(['example.com'], startBalance);
+ getAppConfig
+ .mockResolvedValueOnce(roleConfig)
+ .mockResolvedValueOnce(appConfigWith(['example.com']));
+
+ const result = await firstLogin(lookupByEmail, { claimedRole: SystemRoles.ADMIN });
+
+ expect(result).toEqual(
+ expect.objectContaining({ created: true, error: null, appConfig: roleConfig }),
+ );
+ expect(result.user).toEqual(expect.objectContaining({ role: SystemRoles.USER }));
+ expect(await findBalanceByUser(result.user!._id.toString())).toEqual(
+ expect.objectContaining({ tokenCredits: 500 }),
+ );
+ });
+
+ it('reads one config when the claimed role is the role the account is created with', async () => {
+ await firstLogin(lookupByEmail, { claimedRole: SystemRoles.USER });
+
+ expect(getAppConfig).toHaveBeenCalledTimes(1);
+ });
+
+ it("reads the config of the new account's own role", async () => {
+ await firstLogin(lookupByEmail, { newUser: { ...newUser, role: SystemRoles.ADMIN } });
+
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead(SystemRoles.ADMIN));
+ expect(getAppConfig).not.toHaveBeenCalledWith(roleConfigRead(SystemRoles.USER));
+ });
+
+ it("reads the new account's config in the request's tenant, where it is created", async () => {
+ const tenantId = 'tenant-a';
+ let readTenant: string | undefined;
+ getAppConfig.mockImplementationOnce(async () => {
+ readTenant = getTenantId();
+ return baseConfig;
+ });
+
+ const result = await tenantStorage.run({ tenantId }, () => firstLogin());
+
+ expect(readTenant).toBe(tenantId);
+ expect(result.user).toEqual(expect.objectContaining({ tenantId }));
+ });
+
+ it("fails without creating the account when the new account's config cannot be read", async () => {
+ getAppConfig.mockRejectedValueOnce(new Error('override read failed'));
+
+ await expect(firstLogin()).rejects.toThrow('override read failed');
+ expect(await User.countDocuments()).toBe(0);
+ });
+
it('creates once and resolves the concurrent login to the created account', async () => {
const results = await Promise.all([firstLogin(), firstLogin()]);
@@ -89,19 +196,18 @@ describe('createUserOnce', () => {
it('fails the recovered login while the winner has not credited its start balance yet', async () => {
await User.create(newUser);
+ getAppConfig.mockResolvedValue(appConfigWith(undefined, startBalance));
- const result = await firstLogin(lookupByEmail, {
- appConfig: appConfigWith(undefined, { enabled: true, startBalance: 500 }),
- });
+ const result = await firstLogin();
expect(result).toEqual({ user: null, error: ErrorTypes.AUTH_FAILED, created: false });
});
it('recovers once the winner has credited its start balance', async () => {
- const appConfig = appConfigWith(undefined, { enabled: true, startBalance: 500 });
- const winner = await firstLogin(lookupByEmail, { appConfig });
+ getAppConfig.mockResolvedValue(appConfigWith(undefined, startBalance));
+ const winner = await firstLogin();
- const loser = await firstLogin(lookupByEmail, { appConfig });
+ const loser = await firstLogin();
expect(loser.created).toBe(false);
expect(loser.user?._id.toString()).toBe(winner.user?._id.toString());
@@ -110,7 +216,7 @@ describe('createUserOnce', () => {
it("applies the recovered tenant account's email-domain policy", async () => {
const tenantId = 'tenant-a';
await tenantStorage.run({ tenantId }, () => User.create(newUser));
- getAppConfig.mockResolvedValueOnce(appConfigWith(['other.example']));
+ configsFor(baseConfig, appConfigWith(['other.example']));
const result = await tenantStorage.run({ tenantId }, () => firstLogin());
@@ -121,9 +227,7 @@ describe('createUserOnce', () => {
it("continues when only the recovered tenant account's config sets a start balance", async () => {
const tenantId = 'tenant-a';
await tenantStorage.run({ tenantId }, () => User.create(newUser));
- getAppConfig.mockResolvedValueOnce(
- appConfigWith(undefined, { enabled: true, startBalance: 500 }),
- );
+ configsFor(baseConfig, appConfigWith(undefined, startBalance));
const result = await tenantStorage.run({ tenantId }, () => firstLogin());
@@ -132,11 +236,12 @@ describe('createUserOnce', () => {
it('reads the tenant config and the start balance together', async () => {
const tenantId = 'tenant-a';
- const appConfig = appConfigWith(undefined, { enabled: true, startBalance: 500 });
- await tenantStorage.run({ tenantId }, () => firstLogin(lookupByEmail, { appConfig }));
+ const appConfig = appConfigWith(undefined, startBalance);
+ getAppConfig.mockResolvedValueOnce(appConfig);
+ await tenantStorage.run({ tenantId }, () => firstLogin());
let configResolved = false;
let balanceReadBeforeConfig = false;
- getAppConfig.mockImplementationOnce(async () => {
+ getAppConfig.mockResolvedValueOnce(appConfig).mockImplementationOnce(async () => {
await new Promise((resolve) => setTimeout(resolve, 20));
configResolved = true;
return baseConfig;
@@ -144,7 +249,6 @@ describe('createUserOnce', () => {
const result = await tenantStorage.run({ tenantId }, () =>
firstLogin(lookupByEmail, {
- appConfig,
findBalanceByUser: (userId) => {
balanceReadBeforeConfig = !configResolved;
return findBalanceByUser(userId);
@@ -160,7 +264,7 @@ describe('createUserOnce', () => {
const tenantId = 'tenant-a';
await tenantStorage.run({ tenantId }, () => User.create(newUser));
const tenantConfig = appConfigWith(['example.com']);
- getAppConfig.mockResolvedValueOnce(tenantConfig);
+ configsFor(baseConfig, tenantConfig);
const result = await tenantStorage.run({ tenantId }, () => firstLogin());
@@ -169,6 +273,28 @@ describe('createUserOnce', () => {
);
});
+ it("applies the recovered account's role policy without a tenant", async () => {
+ await User.create({ ...newUser, role: SystemRoles.USER });
+ configsFor(baseConfig, appConfigWith(['other.example']));
+
+ const result = await firstLogin();
+
+ expect(result).toEqual({ user: null, error: 'Email domain not allowed', created: false });
+ expect(getAppConfig).toHaveBeenLastCalledWith(roleConfigRead(SystemRoles.USER));
+ });
+
+ it("continues under the recovered account's role config without a tenant", async () => {
+ await User.create({ ...newUser, role: SystemRoles.USER });
+ const roleConfig = appConfigWith(['example.com']);
+ configsFor(baseConfig, roleConfig);
+
+ const result = await firstLogin();
+
+ expect(result).toEqual(
+ expect.objectContaining({ created: false, error: null, appConfig: roleConfig }),
+ );
+ });
+
it('throws when the lookup cannot account for the existing account', async () => {
await firstLogin();
@@ -201,6 +327,7 @@ describe('provisionSamlUser', () => {
email,
...profile,
...admission,
+ appConfig: baseConfig,
findUser: methods.findUser,
createUserIfAbsent: methods.createUserIfAbsent,
findBalanceByUser,
@@ -227,6 +354,16 @@ describe('provisionSamlUser', () => {
expect(result).toEqual({ user: null, error: ErrorTypes.AUTH_FAILED });
});
+
+ it("refuses a first login the USER role's domain list excludes, creating nothing", async () => {
+ getAppConfig.mockResolvedValueOnce(appConfigWith(['other.example']));
+
+ const result = await samlLogin(null);
+
+ expect(result).toEqual({ user: null, error: 'Email domain not allowed' });
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead(SystemRoles.USER));
+ expect(await User.countDocuments()).toBe(0);
+ });
});
describe('provisionLdapUser', () => {
@@ -242,6 +379,7 @@ describe('provisionLdapUser', () => {
name: 'Ldap User',
...values,
...admission,
+ appConfig: baseConfig,
findUser: methods.findUser,
countUsers: () => methods.countUsers(),
createUserIfAbsent: methods.createUserIfAbsent,
@@ -249,10 +387,22 @@ describe('provisionLdapUser', () => {
});
}
- it('creates the first deployment user as ADMIN', async () => {
+ it('creates the first deployment user as ADMIN, under the ADMIN role config', async () => {
const result = await ldapLogin(null);
expect(result.user).toEqual(expect.objectContaining({ ldapId, role: SystemRoles.ADMIN }));
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead(SystemRoles.ADMIN));
+ });
+
+ it("refuses a later first login the USER role's domain list excludes, creating nothing", async () => {
+ await User.create({ email: '[email protected]', provider: 'local', username: 'first' });
+ getAppConfig.mockResolvedValueOnce(appConfigWith(['other.example']));
+
+ const result = await ldapLogin(null);
+
+ expect(result).toEqual({ user: null, error: 'Email domain not allowed' });
+ expect(getAppConfig).toHaveBeenCalledWith(roleConfigRead(SystemRoles.USER));
+ expect(await User.countDocuments({ ldapId })).toBe(0);
});
it("carries this login's directory values onto the account a concurrent first login created", async () => {
@@ -278,7 +428,7 @@ describe('provisionSocialUser', () => {
const newUser = { email, provider: 'google', googleId: 'google-sub', username: 'social' };
function socialLogin() {
- const finishNewUser = jest.fn(async (user: UserRecord) => user);
+ const finishNewUser = jest.fn(async (user: UserRecord, _appConfig: AppConfig) => user);
const refreshExistingUser = jest.fn(async () => undefined);
const login = provisionSocialUser({
lookup: { findUser: methods.findUser, provider: 'google', providerId: 'google-sub', email },
@@ -301,6 +451,10 @@ describe('provisionSocialUser', () => {
expect(recovered._id.toString()).toBe(created._id.toString());
expect(winner.finishNewUser).toHaveBeenCalledTimes(1);
+ expect(winner.finishNewUser).toHaveBeenCalledWith(
+ expect.objectContaining({ _id: created._id }),
+ baseConfig,
+ );
expect(loser.finishNewUser).not.toHaveBeenCalled();
expect(loser.refreshExistingUser).toHaveBeenCalledWith(
expect.objectContaining({ _id: created._id }),
@@ -308,6 +462,19 @@ describe('provisionSocialUser', () => {
);
});
+ it("throws the email-domain error before creating an account the USER role's list excludes", async () => {
+ getAppConfig.mockResolvedValueOnce(appConfigWith(['other.example']));
+
+ const { login, finishNewUser } = socialLogin();
+
+ await expect(login).rejects.toMatchObject({
+ code: ErrorTypes.AUTH_FAILED,
+ message: 'Email domain not allowed',
+ });
+ expect(finishNewUser).not.toHaveBeenCalled();
+ expect(await User.countDocuments()).toBe(0);
+ });
+
it('throws the coded AUTH_FAILED error when another provider took the email', async () => {
await User.create({ email, provider: 'local', username: 'local-user' });
diff --git a/packages/api/src/auth/provision.ts b/packages/api/src/auth/provision.ts
index e55299e47e..3e6f735e28 100644
--- a/packages/api/src/auth/provision.ts
+++ b/packages/api/src/auth/provision.ts
@@ -1,5 +1,5 @@
import { logger } from '@librechat/data-schemas';
-import { ErrorTypes } from 'librechat-data-provider';
+import { ErrorTypes, SystemRoles } from 'librechat-data-provider';
import type {
AppConfig,
UserRecord,
@@ -48,18 +48,26 @@ function hasStartBalance(balanceConfig?: BalanceConfig | null): boolean {
}
/**
- * Inserts a first-login user. Concurrent first logins for one identity all miss the strategy's
- * lookup, and `createUserIfAbsent` reports `user_exists` for every insert but the first. A
- * rejected request repeats `lookup`, with the strategy's provider and identity checks, and
- * resolves to the account that won (`created: false`) admitted exactly as a found account: a
- * tenant account resolves its tenant config and that config's email-domain policy applies. The
- * caller then refreshes it like any account its lookup finds. A user this request created keeps
- * `appConfig`. A conflict the lookup cannot account for throws.
+ * Inserts a first-login user. The account is admitted before it exists exactly as a found account
+ * is: the config it is created under is its own (the overrides of the role it is created with, in
+ * the request's tenant if any), and a domain that config's `registration.allowedDomains` excludes
+ * fails the login without creating anything. `claimedRole` is the role the login moves the new
+ * account into once it exists (OpenID role claims); its config, read in parallel, must admit the
+ * email too, so a login that role would refuse creates nothing either.
+ *
+ * Concurrent first logins for one identity all miss the strategy's lookup, and
+ * `createUserIfAbsent` reports `user_exists` for every insert but the first. A rejected request
+ * repeats `lookup`, with the strategy's provider and identity checks, and resolves to the account
+ * that won (`created: false`) admitted exactly as a found account: the account resolves its own
+ * config (its role's overrides, in its tenant if any) and that config's email-domain policy
+ * applies. The caller then refreshes it like any account its lookup finds. A user this request
+ * created continues under the config it was created under. A conflict the lookup cannot account
+ * for throws.
*
* It resolves to the winner's account only once the winner finished provisioning it. When the
- * config new users are created under (`appConfig`) sets a start balance, the balance must
- * exist: `createUserIfAbsent` writes it before the user, but a winner on an earlier release adds
- * it with `$inc` after its insert, and login balance sync must not initialize it first; such a
+ * config new users are created under sets a start balance, the balance must exist:
+ * `createUserIfAbsent` writes it before the user, but a winner on an earlier release adds it
+ * with `$inc` after its insert, and login balance sync must not initialize it first; such a
* login fails as it did before recovery existed. A start balance only the account's tenant
* config sets is initialized by login balance sync with an insert-only write that cannot be
* added on top, so it does not hold the login back.
@@ -67,7 +75,7 @@ function hasStartBalance(balanceConfig?: BalanceConfig | null): boolean {
export async function createUserOnce({
newUser,
email,
- appConfig,
+ claimedRole,
getAppConfig,
getBalanceConfig,
lookup,
@@ -77,7 +85,7 @@ export async function createUserOnce({
}: {
newUser: NewUserData;
email: string;
- appConfig: AppConfig;
+ claimedRole?: string;
getAppConfig: GetAppConfig;
getBalanceConfig: GetBalanceConfig;
lookup: () => Promise<LoginUserResolution>;
@@ -85,6 +93,23 @@ export async function createUserOnce({
createUserIfAbsent: CreateUserIfAbsent;
findBalanceByUser: FindBalanceByUser;
}): Promise<FirstLoginResult> {
+ const role = newUser.role ?? SystemRoles.USER;
+ const roles = claimedRole && claimedRole !== role ? [role, claimedRole] : [role];
+ const configs = await Promise.all(
+ roles.map((admittedRole) => resolveAppConfigForUser(getAppConfig, { role: admittedRole })),
+ );
+ const refused = configs.findIndex(
+ (config) => !isEmailDomainAllowed(email, config?.registration?.allowedDomains),
+ );
+ if (refused !== -1) {
+ logger.error(
+ `[${strategyName}] Authentication blocked - email domain not allowed for a new account in the ${roles[refused]} role`,
+ );
+ return { user: null, error: EMAIL_DOMAIN_NOT_ALLOWED, created: false };
+ }
+
+ const appConfig = configs[0];
+
const created = await createUserIfAbsent(newUser, getBalanceConfig(appConfig) ?? undefined);
if (created.ok) return { user: created.value, appConfig, created: true, error: null };
@@ -99,7 +124,7 @@ export async function createUserOnce({
const userId = resolution.user._id.toString();
const requiresBalance = hasStartBalance(getBalanceConfig(appConfig));
const [accountConfig, balance] = await Promise.all([
- resolution.user.tenantId ? resolveAppConfigForUser(getAppConfig, resolution.user) : appConfig,
+ resolveAppConfigForUser(getAppConfig, resolution.user),
requiresBalance ? findBalanceByUser(userId) : null,
]);
if (!isEmailDomainAllowed(email, accountConfig?.registration?.allowedDomains)) {
diff --git a/packages/api/src/auth/saml.ts b/packages/api/src/auth/saml.ts
index ffa8c5e928..5af11df4e8 100644
--- a/packages/api/src/auth/saml.ts
+++ b/packages/api/src/auth/saml.ts
@@ -84,10 +84,11 @@ export async function findSamlUser({
/**
* Resolves the account a SAML login continues as once the strategy's policy checks pass. A
- * found account claims this login's NameID and profile atomically; without one, the user is
- * created through `createUserOnce`, and an account a concurrent first login created is admitted
- * like a found account and claimed the same way. Returns the account with the config the login
- * continues under.
+ * found account claims this login's NameID and profile atomically and continues under
+ * `appConfig`, its own config; without one, the user is created through `createUserOnce`, which
+ * admits it under the USER role's config, and an account a concurrent first login created is
+ * admitted like a found account and claimed the same way. Returns the account with the config
+ * the login continues under.
*/
export async function provisionSamlUser({
user,
@@ -126,7 +127,6 @@ export async function provisionSamlUser({
const result = await createUserOnce({
newUser: { provider: 'saml', samlId: nameID, username, email, emailVerified: true, name },
email,
- appConfig,
getAppConfig,
getBalanceConfig,
strategyName: 'samlStrategy',
diff --git a/packages/api/src/auth/social.ts b/packages/api/src/auth/social.ts
index 4fb7e17491..b548ec2ed1 100644
--- a/packages/api/src/auth/social.ts
+++ b/packages/api/src/auth/social.ts
@@ -50,17 +50,16 @@ export async function resolveSocialUser(lookup: SocialUserLookup): Promise<Login
}
/**
- * Creates a social first-login user through `createUserOnce`. A new account goes through
- * `finishNewUser`; an account a concurrent first login created is admitted like a found account
- * and goes through `refreshExistingUser` with the config its login continues under, as any
- * account the login finds does. A failure throws the coded `AUTH_FAILED` error `socialLogin`
- * hands to its passport callback, with the reason (`AUTH_FAILED` or the email-domain policy)
- * as its message.
+ * Creates a social first-login user through `createUserOnce`, which admits it under the config of
+ * the role it is created with. A new account goes through `finishNewUser` with that config; an
+ * account a concurrent first login created is admitted like a found account and goes through
+ * `refreshExistingUser` with the config its login continues under, as any account the login
+ * finds does. A failure throws the coded `AUTH_FAILED` error `socialLogin` hands to its passport
+ * callback, with the reason (`AUTH_FAILED` or the email-domain policy) as its message.
*/
export async function provisionSocialUser({
lookup,
newUser,
- appConfig,
getAppConfig,
getBalanceConfig,
createUserIfAbsent,
@@ -70,18 +69,16 @@ export async function provisionSocialUser({
}: {
lookup: SocialUserLookup;
newUser: NewUserData;
- appConfig: AppConfig;
getAppConfig: GetAppConfig;
getBalanceConfig: GetBalanceConfig;
createUserIfAbsent: CreateUserIfAbsent;
findBalanceByUser: FindBalanceByUser;
- finishNewUser: (user: UserRecord) => Promise<UserRecord>;
+ finishNewUser: (user: UserRecord, appConfig: AppConfig) => Promise<UserRecord>;
refreshExistingUser: (user: UserRecord, appConfig: AppConfig) => Promise<void>;
}): Promise<UserRecord> {
const result = await createUserOnce({
newUser,
email: newUser.email,
- appConfig,
getAppConfig,
getBalanceConfig,
strategyName: `${lookup.provider}Login`,
@@ -92,7 +89,7 @@ export async function provisionSocialUser({
if (result.error !== null) {
throw Object.assign(new Error(result.error), { code: ErrorTypes.AUTH_FAILED });
}
- if (result.created) return finishNewUser(result.user);
+ if (result.created) return finishNewUser(result.user, result.appConfig);
await refreshExistingUser(result.user, result.appConfig);
return result.user;
diff --git a/packages/api/src/shared-links/config.test.ts b/packages/api/src/shared-links/config.test.ts
index 356a55d8cd..2f85430098 100644
--- a/packages/api/src/shared-links/config.test.ts
+++ b/packages/api/src/shared-links/config.test.ts
@@ -182,6 +182,26 @@ describe('buildSharedLinkStartupPayload', () => {
});
});
+ it('never hands an anonymous share viewer a policy link that would run script', () => {
+ const payload = buildSharedLinkStartupPayload(
+ appConfig({
+ interfaceConfig: {
+ privacyPolicy: { externalUrl: 'javascript:alert(document.domain)' },
+ termsOfService: { externalUrl: 'https://example.com/tos', openNewTab: true },
+ },
+ }),
+ {},
+ );
+
+ expect(JSON.parse(JSON.stringify(payload))).toEqual({
+ appTitle: 'LibreChat',
+ interface: {
+ privacyPolicy: {},
+ termsOfService: { externalUrl: 'https://example.com/tos', openNewTab: true },
+ },
+ });
+ });
+
it.each<[string, TThemeDefinitionConfig | string]>([
['a bundled name', 'clickhouse'],
[
diff --git a/packages/api/src/shared-links/config.ts b/packages/api/src/shared-links/config.ts
index f65e81d963..e53206b545 100644
--- a/packages/api/src/shared-links/config.ts
+++ b/packages/api/src/shared-links/config.ts
@@ -4,6 +4,7 @@ import type { TSharedLinkStartupConfig } from 'librechat-data-provider';
import type { Request, Response, NextFunction } from 'express';
import type { AppConfig } from '@librechat/data-schemas';
import type { GetAppConfigOptions } from '../app/service';
+import { withSafePolicyLinks } from '~/app/interface';
import { isEnabled } from '~/utils';
type SharedLinkStartupEnv = NodeJS.ProcessEnv;
@@ -104,7 +105,7 @@ export function buildSharedLinkStartupPayload(
}
const { privacyPolicy, termsOfService, codeHighlightThrottleMs, artifactUndocking } =
- appConfig?.interfaceConfig ?? {};
+ withSafePolicyLinks(appConfig?.interfaceConfig) ?? {};
const parsedTheme = deploymentThemeSchema.safeParse(appConfig?.interfaceConfig?.theme);
const theme = parsedTheme.success ? parsedTheme.data : undefined;
/* A shared conversation shows the same artifacts pane, so it needs the same
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index c586916224..bcb68263df 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -30,6 +30,7 @@ import {
isTwoFactorPolicyProvider,
resolveEndpointType,
webSearchSchema,
+ isSafeLinkUrl,
} from './config';
describe('independent browser replay opt-in', () => {
@@ -2768,6 +2769,120 @@ describe('interface theme config', () => {
});
});
+describe('policy link URLs', () => {
+ const scriptUrls = [
+ 'javascript:alert(document.domain)',
+ 'JavaScript:alert(1)',
+ ' javascript:alert(1)',
+ '\u0001javascript:alert(1)',
+ 'java\tscript:alert(1)',
+ 'java\nscript:alert(1)',
+ 'data:text/html,<script>alert(1)</script>',
+ 'vbscript:msgbox(1)',
+ 'file:///etc/passwd',
+ 'blob:https://example.com/0b1c',
+ ];
+ /** Unicode white space the URL parser keeps but `String.prototype.trim()` strips. */
+ const trimmedScriptUrls = ['\u00a0', '\ufeff', '\u2028', '\u3000'].map(
+ (space) => `${space}javascript:alert(document.domain)${space}`,
+ );
+ const linkUrls = [
+ 'https://example.com/privacy',
+ 'HTTP://example.com/terms',
+ 'https://example.com/privacy policy',
+ '\u00a0https://example.com/privacy',
+ 'mailto:[email protected]',
+ 'tel:+15555550100',
+ '/privacy',
+ 'legal/terms.html',
+ './privacy',
+ '//example.com/privacy',
+ '#privacy',
+ '?doc=privacy',
+ '',
+ ' ',
+ '\u3000',
+ ];
+ const linkProtocols = new Set(['http:', 'https:', 'mailto:', 'tel:']);
+ const parseInterface = (value: Record<string, unknown>) =>
+ configSchema.safeParse({ version: '1.3.0', interface: value });
+
+ it.each([...scriptUrls, ...trimmedScriptUrls])(
+ 'refuses %j, which a browser would not open as a web page, mail or phone link',
+ (url) => {
+ expect(isSafeLinkUrl(url)).toBe(false);
+ },
+ );
+
+ it.each(linkUrls)('accepts %j, an http(s), mailto:, tel:, relative or blank link', (url) => {
+ expect(isSafeLinkUrl(url)).toBe(true);
+ });
+
+ it('keeps accepting a malformed http(s) link, which a browser does not open at all', () => {
+ expect(isSafeLinkUrl('https://exa mple.com')).toBe(true);
+ expect(isSafeLinkUrl('http://')).toBe(true);
+ });
+
+ it('reads the scheme the URL parser reads, before and after the trim a client applies', () => {
+ const base = 'https://chat.example.com/c/new';
+ for (const url of [...scriptUrls, ...trimmedScriptUrls, ...linkUrls]) {
+ const readable = [url, url.trim()].every((read) =>
+ linkProtocols.has(new URL(read, base).protocol),
+ );
+ expect([isSafeLinkUrl(url), url]).toEqual([readable, url]);
+ }
+ });
+
+ it('refuses a scheme behind any mix of control characters and Unicode white space', () => {
+ expect(isSafeLinkUrl('\u0001\u00a0javascript:alert(1)')).toBe(false);
+ expect(isSafeLinkUrl('\u00a0\t\u0001\ufeffJAVASCRIPT:alert(1)')).toBe(false);
+ });
+
+ it('judges a link with long white-space runs in time that grows linearly with its length', () => {
+ const run = 100_000;
+ const cases: [string, boolean][] = [
+ [`https://example.com/${' '.repeat(run)}x`, true],
+ [`https://example.com/${'\u00a0\t'.repeat(run / 2)}x`, true],
+ [`${' '.repeat(run)}x`, true],
+ [`${'\u3000'.repeat(run)}${'a'.repeat(run)}`, true],
+ [`${' \u00a0\u0001'.repeat(run / 3)}javascript:alert(1)${' '.repeat(run)}x`, false],
+ [`java${'\t'.repeat(run)}script:alert(1)`, false],
+ ];
+ for (const [url, safe] of cases) {
+ const started = performance.now();
+ const decision = isSafeLinkUrl(url);
+ const elapsed = performance.now() - started;
+ expect([decision, elapsed < 100]).toEqual([safe, true]);
+ }
+ });
+
+ it('rejects a script URL in either policy link and points at the field', () => {
+ for (const field of ['privacyPolicy', 'termsOfService']) {
+ const result = parseInterface({ [field]: { externalUrl: 'javascript:alert(1)' } });
+ expect(result.success).toBe(false);
+ expect(result.success ? [] : result.error.issues.map((issue) => issue.path)).toEqual([
+ ['interface', field, 'externalUrl'],
+ ]);
+ }
+ });
+
+ it('accepts http(s), mailto:, relative and blank policy links with their other settings', () => {
+ const result = parseInterface({
+ privacyPolicy: { externalUrl: 'https://example.com/privacy', openNewTab: true },
+ termsOfService: { externalUrl: '/terms', modalAcceptance: true, modalContent: '# Terms' },
+ });
+ expect(result.success).toBe(true);
+ expect(result.success && result.data.interface.privacyPolicy).toEqual({
+ externalUrl: 'https://example.com/privacy',
+ openNewTab: true,
+ });
+ expect(parseInterface({ privacyPolicy: { externalUrl: '' } }).success).toBe(true);
+ expect(
+ parseInterface({ privacyPolicy: { externalUrl: 'mailto:[email protected]' } }).success,
+ ).toBe(true);
+ });
+});
+
describe('built-in endpoint model lists', () => {
const parse = (endpoints: Record<string, unknown>) =>
configSchema.safeParse({ version: '1.0', endpoints });
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 8b410829dd..5921139122 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -113,7 +113,10 @@ export function isTwoFactorPolicyProvider(provider: string | null | undefined):
/** How long a started social login may take to return to its callback before its `state` expires. */
export const DEFAULT_OAUTH_STATE_TTL_MS = 10 * 60 * 1000;
-export const BASE_ONLY_CONFIG_SECTIONS = ['filters', 'mcpAppSandbox'] as const;
+/** Sections only librechat.yaml sets: no config document, Base included, can change or remove
+ * them. `turnstile` stays here until the server verifies Turnstile tokens: until then a stored
+ * site key adds no protection, and a wrong one locks users out of sign-in and registration. */
+export const BASE_ONLY_CONFIG_SECTIONS = ['filters', 'mcpAppSandbox', 'turnstile'] as const;
/** Sections that may be stored in the tenant's base config document but must
* not be overridden or tombstoned by role, group, or user config documents. */
export const BASE_PRINCIPAL_CONFIG_SECTIONS = ['langfuse'] as const;
@@ -2634,8 +2637,42 @@ export enum EImageOutputType {
JPEG = 'jpeg',
}
+/** Schemes a configured link may use: web pages, and the mail and phone links that run no script. */
+const LINK_SCHEMES = new Set(['http', 'https', 'mailto', 'tel']);
+/**
+ * A link's scheme as a reader finds it. It skips what either reader strips from the front: the
+ * WHATWG URL parser strips C0 controls and spaces, and `String.prototype.trim()` (which clients
+ * apply first) strips Unicode white space such as U+00A0, U+FEFF, U+2028 and U+3000; skipping
+ * both at once covers either reader, and either order. Inside the scheme it allows the tabs and
+ * newlines the URL parser removes. Only the front of a link decides its scheme, so the match is
+ * anchored there and ends with the scheme: the skipped characters cannot start a scheme, so a
+ * failed match gives each one back once, and nothing after the scheme is read at all.
+ */
+// eslint-disable-next-line no-control-regex
+const URL_SCHEME = /^[\u0000-\u0020\s]*([a-z][a-z\d+.\t\n\r-]*):/i;
+const URL_TAB_OR_NEWLINE = /[\t\n\r]/g;
+
+/**
+ * Whether a configured link, such as a privacy policy or terms of service `externalUrl`, may be
+ * rendered as an `href` on the app's pages, the signed-out sign-in page included: an http(s),
+ * `mailto:` or `tel:` URL, a URL relative to the app (which keeps the page's http(s) scheme),
+ * or a blank value, which publishes no link. The scheme is read the way the URL parser browsers
+ * use reads it, after the trimming clients apply, so letter case, white space (Unicode white
+ * space included) and control characters cannot disguise one that runs script, such as
+ * `javascript:` or `data:`. Only the scheme is judged: a malformed http(s) URL is not opened by
+ * a browser at all, so it stays accepted as it always was.
+ */
+export function isSafeLinkUrl(url: string): boolean {
+ const scheme = URL_SCHEME.exec(url)?.[1];
+ return scheme == null || LINK_SCHEMES.has(scheme.replace(URL_TAB_OR_NEWLINE, '').toLowerCase());
+}
+
+const linkUrlSchema = z
+ .string()
+ .refine(isSafeLinkUrl, { message: 'must be an http(s), mailto: or tel: URL, or a relative URL' });
+
const termsOfServiceSchema = z.object({
- externalUrl: z.string().optional(),
+ externalUrl: linkUrlSchema.optional(),
openNewTab: z.boolean().optional(),
modalAcceptance: z.boolean().optional(),
modalTitle: z.string().optional(),
@@ -2877,7 +2914,7 @@ export const interfaceSchema = z
theme: deploymentThemeSchema.optional(),
privacyPolicy: z
.object({
- externalUrl: z.string().optional(),
+ externalUrl: linkUrlSchema.optional(),
openNewTab: z.boolean().optional(),
})
.optional(),
diff --git a/packages/data-schemas/misc/ferretdb/tenantIsolation.ferretdb.spec.ts b/packages/data-schemas/misc/ferretdb/tenantIsolation.ferretdb.spec.ts
new file mode 100644
index 0000000000..ee8752744c
--- /dev/null
+++ b/packages/data-schemas/misc/ferretdb/tenantIsolation.ferretdb.spec.ts
@@ -0,0 +1,35 @@
+import { describeTenantIsolationConformance } from '~/tenant/conformance';
+import { createMongooseTenantHarness } from '~/tenant/harness';
+
+/**
+ * The portable tenant-isolation contract against a live engine: FerretDB (PostgreSQL +
+ * DocumentDB extension), or any MongoDB-compatible server for parity. It covers the
+ * single-partition reads that config resolution relies on, whose tenantless filter
+ * (`$exists: false`, `null` and `''`) must mean the same on every engine.
+ *
+ * Run against FerretDB (see docker-compose.ferretdb.yml):
+ * FERRETDB_URI="mongodb://ferretdb:[email protected]:27020/tenant_conformance" \
+ * npx jest --config misc/ferretdb/jest.ferretdb.config.mjs tenantIsolation.ferretdb
+ *
+ * Run against MongoDB (for parity):
+ * FERRETDB_URI="mongodb://127.0.0.1:27017/tenant_conformance" \
+ * npx jest --config misc/ferretdb/jest.ferretdb.config.mjs tenantIsolation.ferretdb
+ */
+
+const FERRETDB_URI = process.env.FERRETDB_URI;
+
+if (FERRETDB_URI) {
+ describeTenantIsolationConformance(
+ createMongooseTenantHarness({
+ name: `mongoose on ${new URL(FERRETDB_URI).host}`,
+ connect: async () => FERRETDB_URI,
+ release: async () => undefined,
+ }),
+ );
+} else {
+ describe.skip('tenant isolation conformance (set FERRETDB_URI to run)', () => {
+ it('runs against a live engine', () => {
+ expect(FERRETDB_URI).toBeDefined();
+ });
+ });
+}
diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts
index 66b1538123..f2dc5df306 100644
--- a/packages/data-schemas/src/app/resolution.spec.ts
+++ b/packages/data-schemas/src/app/resolution.spec.ts
@@ -159,6 +159,38 @@ describe('mergeConfigOverrides', () => {
expect(mergeConfigOverrides(base, configs).mcpAppSandbox).toEqual(base.mcpAppSandbox);
});
+ it('keeps Turnstile on librechat.yaml whatever Base or a role stores or tombstones', () => {
+ const base = { turnstileConfig: { siteKey: 'yaml-site-key' } } as unknown as AppConfig;
+ const configs = [
+ fakeConfig(
+ { turnstile: { siteKey: 'base-site-key' } },
+ 0,
+ ['turnstile.options'],
+ BASE_CONFIG_PRINCIPAL_ID,
+ ),
+ fakeConfig({ turnstile: { siteKey: 'role-site-key' } }, 10, ['turnstile.siteKey']),
+ ];
+
+ expect(mergeConfigOverrides(base, configs).turnstileConfig).toEqual({
+ siteKey: 'yaml-site-key',
+ });
+ });
+
+ it('keeps Turnstile on librechat.yaml when a document names it by its AppConfig key', () => {
+ const base = { turnstileConfig: { siteKey: 'yaml-site-key' } } as unknown as AppConfig;
+ const aliased = (overrides: Record<string, unknown>, tombstones?: string[]) =>
+ fakeConfig(overrides, 0, tombstones, BASE_CONFIG_PRINCIPAL_ID);
+
+ expect(
+ mergeConfigOverrides(base, [aliased({ turnstileConfig: { siteKey: 'stored-key' } })])
+ .turnstileConfig,
+ ).toEqual({ siteKey: 'yaml-site-key' });
+ expect(
+ mergeConfigOverrides(base, [aliased({}, ['turnstileConfig', 'turnstileConfig.siteKey'])])
+ .turnstileConfig,
+ ).toEqual({ siteKey: 'yaml-site-key' });
+ });
+
it('keeps the pull request host from the base config whatever an override does', () => {
const pullRequests = { host: 'ghe.example.com', allowedRepositories: ['acme/*'] };
const base = { endpoints: { agents: { pullRequests } } } as unknown as AppConfig;
@@ -619,11 +651,10 @@ describe('mergeConfigOverrides', () => {
expect(iface.parameters).toBe(true);
});
- it('remaps all renamed YAML keys (exhaustiveness check)', () => {
+ it('remaps all renamed YAML keys that overrides may set (exhaustiveness check)', () => {
const base = {
mcpConfig: null,
interfaceConfig: { modelSelect: true },
- turnstileConfig: {},
} as unknown as AppConfig;
const configs = [
@@ -631,7 +662,6 @@ describe('mergeConfigOverrides', () => {
{
mcpServers: { srv: { url: 'http://mcp' } },
interface: { modelSelect: false },
- turnstile: { siteKey: 'key-123' },
},
10,
),
@@ -640,11 +670,9 @@ describe('mergeConfigOverrides', () => {
expect(result.mcpConfig).toEqual({ srv: { url: 'http://mcp' } });
expect((result.interfaceConfig as Record<string, unknown>).modelSelect).toBe(false);
- expect((result.turnstileConfig as Record<string, unknown>).siteKey).toBe('key-123');
expect(result.mcpServers).toBeUndefined();
expect(result.interface).toBeUndefined();
- expect(result.turnstile).toBeUndefined();
});
it('strips interface permission fields from overrides', () => {
@@ -2109,6 +2137,103 @@ describe('getConfigOverrideIssues: items addressed by id', () => {
});
});
+describe('policy links in overrides', () => {
+ const scriptUrl = 'javascript:alert(document.domain)';
+ /** Script URLs behind Unicode white space, which a client's `trim()` strips before rendering. */
+ const trimmedScriptUrls = ['\u00a0', '\ufeff', '\u2028', '\u3000'].map(
+ (space) => `${space}${scriptUrl}`,
+ );
+
+ it('rejects a whole-document write whose policy link would run script', () => {
+ const issues = getConfigOverrideIssues({
+ interface: {
+ customWelcome: 'Hi',
+ privacyPolicy: { externalUrl: scriptUrl, openNewTab: true },
+ termsOfService: { externalUrl: 'data:text/html,<script>alert(1)</script>' },
+ },
+ });
+
+ expect(issues.map(({ path, code }) => ({ path, code }))).toEqual([
+ { path: 'interface.privacyPolicy.externalUrl', code: 'custom' },
+ { path: 'interface.termsOfService.externalUrl', code: 'custom' },
+ ]);
+ });
+
+ it.each(trimmedScriptUrls)('rejects %j in a document write and a field write', (url) => {
+ expect(
+ getConfigOverrideIssues({ interface: { privacyPolicy: { externalUrl: url } } }).map(
+ ({ path, code }) => ({ path, code }),
+ ),
+ ).toEqual([{ path: 'interface.privacyPolicy.externalUrl', code: 'custom' }]);
+ expect(
+ getConfigFieldIssues({ 'interface.termsOfService.externalUrl': url }).map(({ path }) => path),
+ ).toEqual(['interface.termsOfService.externalUrl']);
+ });
+
+ it('accepts http(s), mailto:, relative and blank policy links', () => {
+ expect(
+ getConfigOverrideIssues({
+ interface: {
+ privacyPolicy: { externalUrl: 'mailto:[email protected]' },
+ termsOfService: { externalUrl: 'https://example.com/terms' },
+ },
+ }),
+ ).toEqual([]);
+ expect(
+ getConfigOverrideIssues({
+ interface: {
+ privacyPolicy: { externalUrl: 'https://example.com/privacy' },
+ termsOfService: { externalUrl: '/terms', modalAcceptance: true },
+ },
+ }),
+ ).toEqual([]);
+ expect(getConfigOverrideIssues({ interface: { privacyPolicy: { externalUrl: '' } } })).toEqual(
+ [],
+ );
+ });
+
+ it('rejects a field write of a script URL, as a value or inside its object', () => {
+ expect(
+ getConfigFieldIssues({ 'interface.privacyPolicy.externalUrl': scriptUrl }).map(
+ ({ path }) => path,
+ ),
+ ).toEqual(['interface.privacyPolicy.externalUrl']);
+ expect(
+ getConfigFieldIssues({ 'interface.termsOfService': { externalUrl: scriptUrl } }).map(
+ ({ path }) => path,
+ ),
+ ).toEqual(['interface.termsOfService.externalUrl']);
+ });
+
+ it.each([scriptUrl, ...trimmedScriptUrls])(
+ 'drops %j stored before validation, keeping the rest of the document',
+ (storedUrl) => {
+ const base = {
+ interfaceConfig: { privacyPolicy: { externalUrl: 'https://yaml.example/privacy' } },
+ } as unknown as AppConfig;
+
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig(
+ {
+ interface: {
+ customWelcome: 'Hi',
+ privacyPolicy: { externalUrl: storedUrl, openNewTab: true },
+ },
+ },
+ 0,
+ undefined,
+ BASE_CONFIG_PRINCIPAL_ID,
+ ),
+ ]);
+
+ expect(merged.interfaceConfig).toEqual({
+ customWelcome: 'Hi',
+ privacyPolicy: { externalUrl: 'https://yaml.example/privacy', openNewTab: true },
+ });
+ },
+ );
+});
+
describe('applyConfigTombstones', () => {
it('removes tombstoned base paths except the ones a write clears', () => {
const base = {
diff --git a/packages/data-schemas/src/app/store.ts b/packages/data-schemas/src/app/store.ts
index fcf12caeb5..95262f07f4 100644
--- a/packages/data-schemas/src/app/store.ts
+++ b/packages/data-schemas/src/app/store.ts
@@ -23,6 +23,12 @@ import { parseFieldPath } from './paths';
* (`./mutations`) applied between a read and that write, so a second engine (PostgreSQL/JSONB)
* implements five operations and inherits the rest.
*
+ * Every engine also scopes documents to the caller's tenant as `~/tenant/conformance` requires,
+ * and keeps role documents (whose ids every tenant reuses) and every `listActive` read to one
+ * tenant partition (`tenantPartition`), so a merge never mixes tenants. Only a `list` that asks
+ * for `acrossTenants` reads every partition the caller's scope can see, for reports that name
+ * each document's tenant.
+ *
* `./conformance` is the suite an engine must pass.
*/
@@ -81,11 +87,20 @@ export type ConfigTombstones = Pick<
'principalType' | 'principalId' | 'tenantId' | 'tombstones'
>;
+/**
+ * Which documents a `list` returns: only active or inactive ones, and with `acrossTenants`, the
+ * role documents of every tenant partition the caller's scope can read instead of one partition's.
+ */
+export interface ConfigListFilter {
+ isActive?: boolean;
+ acrossTenants?: boolean;
+}
+
export interface ConfigStore {
/** The principal's document, active or not, or `null` when it has none. */
read(principal: ConfigPrincipal): Promise<ConfigRecord | null>;
- /** Every document (optionally only active or inactive ones), in {@link compareConfigRecords} order. */
- list(filter?: { isActive?: boolean }): Promise<ConfigRecord[]>;
+ /** Every document the filter selects, in {@link compareConfigRecords} order. */
+ list(filter?: ConfigListFilter): Promise<ConfigRecord[]>;
/** The active documents of exactly these principals, in {@link compareConfigRecords} order. */
listActive(principals: readonly ConfigPrincipal[]): Promise<ConfigRecord[]>;
/**
@@ -417,7 +432,7 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
*/
async function listTombstones(fieldPath: string): Promise<ConfigTombstones[]> {
const found: ConfigTombstones[] = [];
- for (const record of await store.list({ isActive: true })) {
+ for (const record of await store.list({ isActive: true, acrossTenants: true })) {
if (record.tombstones.some((path) => isPathOrDescendant(path, fieldPath))) {
found.push(toTombstones(record));
}
diff --git a/packages/data-schemas/src/methods/config.spec.ts b/packages/data-schemas/src/methods/config.spec.ts
index 4a918e0717..ac77550a99 100644
--- a/packages/data-schemas/src/methods/config.spec.ts
+++ b/packages/data-schemas/src/methods/config.spec.ts
@@ -2,9 +2,10 @@ import mongoose, { Types } from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { PrincipalType, PrincipalModel } from 'librechat-data-provider';
import type { ConfigRecord } from '~/app/store';
-import type { IConfig } from '~/types';
-import { createConfigMethods } from './config';
-import configSchema from '~/schema/config';
+import { tenantStorage, runAsSystem } from '~/config/tenantContext';
+import { createConfigMethods, createConfigStore } from './config';
+import { resetTenantStrictCache } from '~/tenant/policy';
+import { createConfigModel } from '~/models/config';
let mongoServer: MongoMemoryServer;
let methods: ReturnType<typeof createConfigMethods>;
@@ -12,10 +13,7 @@ let methods: ReturnType<typeof createConfigMethods>;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
await mongoose.connect(mongoServer.getUri());
- if (!mongoose.models.Config) {
- mongoose.model<IConfig>('Config', configSchema);
- }
- await mongoose.models.Config.init();
+ await createConfigModel(mongoose).init();
methods = createConfigMethods(mongoose);
});
@@ -314,6 +312,96 @@ describe('getApplicableConfigs', () => {
expect(configs).toHaveLength(1);
});
+
+ describe('tenant partition', () => {
+ const USER_ROLE = [{ principalType: PrincipalType.ROLE, principalId: 'USER' }];
+
+ /** Inserts documents directly so each one keeps exactly the `tenantId` form it is given. */
+ async function seed(
+ docs: Array<{ principalId: string; label: string; tenantId?: string | null }>,
+ ): Promise<void> {
+ await mongoose.connection.db!.collection('configs').insertMany(
+ docs.map(({ principalId, label, tenantId }, index) => ({
+ principalType: PrincipalType.ROLE,
+ principalId,
+ principalModel: PrincipalModel.ROLE,
+ priority: principalId === '__base__' ? 0 : 10 + index,
+ overrides: { registration: { allowedDomains: [label] } },
+ tombstones: [],
+ isActive: true,
+ configVersion: 1,
+ ...(tenantId !== undefined && { tenantId }),
+ })),
+ );
+ }
+
+ const labels = (configs: ConfigRecord[]): string[] =>
+ configs.map((config) => config.overrides.registration?.allowedDomains?.[0] ?? '');
+
+ beforeEach(async () => {
+ await seed([
+ { principalId: '__base__', label: 'deployment-base' },
+ { principalId: '__base__', label: 'a-base', tenantId: 'tenant-a' },
+ { principalId: '__base__', label: 'b-base', tenantId: 'tenant-b' },
+ { principalId: 'USER', label: 'deployment-user' },
+ { principalId: 'USER', label: 'a-user', tenantId: 'tenant-a' },
+ { principalId: 'USER', label: 'b-user', tenantId: 'tenant-b' },
+ ]);
+ });
+
+ afterEach(() => {
+ delete process.env.TENANT_ISOLATION_STRICT;
+ resetTenantStrictCache();
+ });
+
+ it('reads only tenantless documents outside a tenant', async () => {
+ expect(labels(await methods.getApplicableConfigs(USER_ROLE))).toEqual([
+ 'deployment-base',
+ 'deployment-user',
+ ]);
+ });
+
+ it('reads only tenantless documents under the system sentinel', async () => {
+ const configs = await runAsSystem(() => methods.getApplicableConfigs(USER_ROLE));
+ expect(labels(configs)).toEqual(['deployment-base', 'deployment-user']);
+ });
+
+ it("reads only the active tenant's documents", async () => {
+ const configs = await tenantStorage.run({ tenantId: 'tenant-a' }, () =>
+ methods.getApplicableConfigs(USER_ROLE),
+ );
+ expect(labels(configs)).toEqual(['a-base', 'a-user']);
+ });
+
+ it("never falls back to the deployment's documents inside a tenant", async () => {
+ const configs = await tenantStorage.run({ tenantId: 'tenant-c' }, () =>
+ methods.getApplicableConfigs(USER_ROLE),
+ );
+ expect(configs).toEqual([]);
+ });
+
+ it('treats a stored null or empty tenantId as tenantless', async () => {
+ await mongoose.models.Config.deleteMany({});
+ await seed([
+ { principalId: '__base__', label: 'null-base', tenantId: null },
+ { principalId: 'USER', label: 'empty-user', tenantId: '' },
+ { principalId: 'ADMIN', label: 'a-admin', tenantId: 'tenant-a' },
+ ]);
+
+ const configs = await methods.getApplicableConfigs([
+ ...USER_ROLE,
+ { principalType: PrincipalType.ROLE, principalId: 'ADMIN' },
+ ]);
+ expect(labels(configs)).toEqual(['null-base', 'empty-user']);
+ });
+
+ it('refuses a read with no tenant context in strict mode', async () => {
+ process.env.TENANT_ISOLATION_STRICT = 'true';
+ resetTenantStrictCache();
+
+ await expect(methods.getApplicableConfigs(USER_ROLE)).rejects.toThrow('[TenantIsolation]');
+ });
+ });
});
describe('patchConfigFields', () => {
@@ -816,6 +904,392 @@ describe('toggleConfigActiveTracked', () => {
const raw = () => mongoose.connection.db!.collection('configs');
+describe('role-addressed operations stay in one tenant partition', () => {
+ const BASE = '__base__';
+ const inTenantA = <T>(fn: () => Promise<T>): Promise<T> =>
+ tenantStorage.run({ tenantId: 'tenant-a' }, fn);
+ const revisionOf = (config: { _id: unknown; configVersion: number }) =>
+ `${String(config._id)}:${config.configVersion}`;
+
+ /** Inserts directly, so the document keeps exactly the `tenantId` form it is given. */
+ async function seedBase(label: string, tenantId?: string | null): Promise<void> {
+ await mongoose.connection.db!.collection('configs').insertOne({
+ principalType: PrincipalType.ROLE,
+ principalId: BASE,
+ principalModel: PrincipalModel.ROLE,
+ priority: 0,
+ overrides: { registration: { allowedDomains: [label] } },
+ tombstones: [],
+ isActive: true,
+ configVersion: 1,
+ ...(tenantId !== undefined && { tenantId }),
+ });
+ }
+
+ const stored = () =>
+ mongoose.connection
+ .db!.collection('configs')
+ .find({}, { projection: { _id: 0, tenantId: 1, overrides: 1, isActive: 1, tombstones: 1 } })
+ .sort({ tenantId: 1 })
+ .toArray();
+
+ afterEach(() => {
+ delete process.env.TENANT_ISOLATION_STRICT;
+ resetTenantStrictCache();
+ });
+
+ it("does not read a tenant's document as the deployment's", async () => {
+ await seedBase('a-base', 'tenant-a');
+
+ expect(await methods.findConfigByPrincipal(PrincipalType.ROLE, BASE)).toBeNull();
+ expect(await methods.listAllConfigs()).toEqual([]);
+ });
+
+ it('reads the tenantless document outside a tenant and the tenant document inside it', async () => {
+ await seedBase('a-base', 'tenant-a');
+ await seedBase('deployment-base');
+
+ const deployment = await methods.findConfigByPrincipal(PrincipalType.ROLE, BASE);
+ const tenant = await inTenantA(() => methods.findConfigByPrincipal(PrincipalType.ROLE, BASE));
+
+ expect(deployment?.overrides).toEqual({
+ registration: { allowedDomains: ['deployment-base'] },
+ });
+ expect(tenant?.overrides).toEqual({ registration: { allowedDomains: ['a-base'] } });
+ expect((await methods.listAllConfigs()).map((config) => config.tenantId)).toEqual([undefined]);
+ });
+
+ it("writes the deployment's own document instead of a tenant's", async () => {
+ await seedBase('a-base', 'tenant-a');
+
+ await methods.patchConfigFields(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ { 'registration.socialLogins': ['google'] },
+ 0,
+ );
+
+ expect(await stored()).toEqual([
+ expect.objectContaining({
+ overrides: { registration: { socialLogins: ['google'] } },
+ }),
+ expect.objectContaining({
+ tenantId: 'tenant-a',
+ overrides: { registration: { allowedDomains: ['a-base'] } },
+ }),
+ ]);
+ expect((await stored())[0]).not.toHaveProperty('tenantId');
+ });
+
+ it("writes a tenant's document inside the tenant, leaving the deployment's alone", async () => {
+ await seedBase('deployment-base');
+
+ await inTenantA(() =>
+ methods.upsertConfig(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ { registration: { allowedDomains: ['a-only'] } },
+ 0,
+ ),
+ );
+
+ expect(await stored()).toEqual([
+ expect.objectContaining({
+ overrides: { registration: { allowedDomains: ['deployment-base'] } },
+ }),
+ expect.objectContaining({
+ tenantId: 'tenant-a',
+ overrides: { registration: { allowedDomains: ['a-only'] } },
+ }),
+ ]);
+ });
+
+ it("replaces, tombstones, unsets, toggles and deletes only the deployment's document", async () => {
+ await seedBase('a-base', 'tenant-a');
+ await seedBase('deployment-base', null);
+
+ await methods.upsertConfig(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ { registration: { allowedDomains: ['replaced'] }, interface: { customWelcome: 'hi' } },
+ 0,
+ );
+ await methods.tombstoneConfigField(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ 'interface.theme',
+ 0,
+ );
+ await methods.unsetConfigField(PrincipalType.ROLE, BASE, 'registration.allowedDomains');
+ await methods.toggleConfigActive(PrincipalType.ROLE, BASE, false);
+ await methods.toggleConfigActiveTracked(PrincipalType.ROLE, BASE, false);
+
+ const [deployment, tenant] = await stored();
+ expect(deployment).toEqual({
+ tenantId: null,
+ overrides: { interface: { customWelcome: 'hi' } },
+ tombstones: ['interface.theme'],
+ isActive: false,
+ });
+ expect(tenant).toEqual({
+ tenantId: 'tenant-a',
+ overrides: { registration: { allowedDomains: ['a-base'] } },
+ tombstones: [],
+ isActive: true,
+ });
+
+ const deleted = await methods.deleteConfig(PrincipalType.ROLE, BASE);
+ expect(deleted?.overrides).toEqual({ interface: { customWelcome: 'hi' } });
+ expect(deleted).not.toHaveProperty('tenantId');
+ expect(await stored()).toEqual([expect.objectContaining({ tenantId: 'tenant-a' })]);
+ });
+
+ it("deletes nothing outside a tenant when only a tenant's document exists", async () => {
+ await seedBase('a-base', 'tenant-a');
+
+ expect(await methods.deleteConfig(PrincipalType.ROLE, BASE)).toBeNull();
+ expect(await stored()).toEqual([expect.objectContaining({ tenantId: 'tenant-a' })]);
+ });
+
+ it("refuses a store write or delete pinned to a tenant document's revision outside the tenant", async () => {
+ await seedBase('a-base', 'tenant-a');
+ const tenantDocument = await raw().findOne({ tenantId: 'tenant-a' });
+ const store = createConfigStore(mongoose);
+ const principal = { principalType: PrincipalType.ROLE, principalId: BASE };
+ const revision = revisionOf({ _id: tenantDocument!._id, configVersion: 1 });
+
+ await expect(
+ store.write(
+ principal,
+ {
+ principalModel: PrincipalModel.ROLE,
+ priority: 0,
+ overrides: { registration: { allowedDomains: ['stale'] } },
+ tombstones: [],
+ isActive: true,
+ },
+ revision,
+ ),
+ ).rejects.toMatchObject({ code: 'CONFIG_VERSION_CONFLICT' });
+ await expect(store.remove(principal, revision)).rejects.toMatchObject({
+ code: 'CONFIG_VERSION_CONFLICT',
+ });
+ expect(await stored()).toEqual([
+ {
+ tenantId: 'tenant-a',
+ overrides: { registration: { allowedDomains: ['a-base'] } },
+ tombstones: [],
+ isActive: true,
+ },
+ ]);
+ });
+
+ it('lists every tenant role document only when a listing asks for all tenants', async () => {
+ await seedBase('a-base', 'tenant-a');
+ await seedBase('deployment-base');
+ const store = createConfigStore(mongoose);
+ const tenants = (records: ConfigRecord[]) => records.map((record) => record.tenantId);
+
+ expect(tenants(await store.list())).toEqual([undefined]);
+ expect(tenants(await store.list({ acrossTenants: true })).sort()).toEqual([
+ 'tenant-a',
+ undefined,
+ ]);
+ expect(tenants(await inTenantA(() => store.list({ acrossTenants: true })))).toEqual([
+ 'tenant-a',
+ ]);
+ });
+
+ it("restores the deployment's document while a tenant's document exists", async () => {
+ await seedBase('a-base', 'tenant-a');
+ await seedBase('deployment-base');
+ const deleted = await methods.deleteConfig(PrincipalType.ROLE, BASE);
+
+ const restored = await methods.restoreConfig(deleted!);
+
+ expect(restored).toBe(true);
+ expect((await stored()).map((config) => config.overrides)).toEqual([
+ { registration: { allowedDomains: ['deployment-base'] } },
+ { registration: { allowedDomains: ['a-base'] } },
+ ]);
+ });
+
+ it("applies revision-conditioned writes to the deployment's document, never a tenant's", async () => {
+ await seedBase('a-base', 'tenant-a');
+ const tenantDocument = await raw().findOne({ tenantId: 'tenant-a' });
+
+ const created = await methods.patchConfigFields(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ { 'interface.customWelcome': 'deployment' },
+ 0,
+ undefined,
+ { expectedRevision: 'absent' },
+ );
+ const tombstoned = await methods.tombstoneConfigField(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ 'interface.theme',
+ 0,
+ undefined,
+ { expectedRevision: revisionOf(created) },
+ );
+ const unset = await methods.unsetConfigField(
+ PrincipalType.ROLE,
+ BASE,
+ 'interface.theme',
+ undefined,
+ { expectedRevision: revisionOf(tombstoned) },
+ );
+ const stale = methods.upsertConfig(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ { registration: { allowedDomains: ['stale'] } },
+ 0,
+ undefined,
+ { expectedRevision: revisionOf({ _id: tenantDocument!._id, configVersion: 1 }) },
+ );
+
+ expect([created, tombstoned, unset].map((config) => config?.configVersion)).toEqual([1, 2, 3]);
+ await expect(stale).rejects.toMatchObject({ code: 'CONFIG_VERSION_CONFLICT' });
+ const [deployment, tenant] = await stored();
+ expect(deployment).toEqual({
+ overrides: { interface: { customWelcome: 'deployment' } },
+ tombstones: [],
+ isActive: true,
+ });
+ expect(tenant).toEqual({
+ tenantId: 'tenant-a',
+ overrides: { registration: { allowedDomains: ['a-base'] } },
+ tombstones: [],
+ isActive: true,
+ });
+ });
+
+ it('refuses an unscoped write in strict mode', async () => {
+ process.env.TENANT_ISOLATION_STRICT = 'true';
+ resetTenantStrictCache();
+
+ await expect(
+ methods.patchConfigFields(
+ PrincipalType.ROLE,
+ BASE,
+ PrincipalModel.ROLE,
+ { 'registration.socialLogins': ['google'] },
+ 0,
+ ),
+ ).rejects.toThrow('[TenantIsolation]');
+ });
+});
+
+describe('group and user documents are addressed by id in any tenant', () => {
+ const groupId = new Types.ObjectId().toString();
+ const userId = new Types.ObjectId().toString();
+ const inTenant = <T>(tenantId: string, fn: () => Promise<T>): Promise<T> =>
+ tenantStorage.run({ tenantId }, fn);
+
+ async function seed(
+ principalType: PrincipalType,
+ principalId: string,
+ label: string,
+ tenantId?: string,
+ ): Promise<void> {
+ await mongoose.connection.db!.collection('configs').insertOne({
+ principalType,
+ principalId,
+ principalModel:
+ principalType === PrincipalType.GROUP ? PrincipalModel.GROUP : PrincipalModel.USER,
+ priority: 10,
+ overrides: { registration: { allowedDomains: [label] } },
+ tombstones: [],
+ isActive: true,
+ configVersion: 1,
+ ...(tenantId !== undefined && { tenantId }),
+ });
+ }
+
+ beforeEach(async () => {
+ await seed(PrincipalType.GROUP, groupId, 'a-group', 'tenant-a');
+ await seed(PrincipalType.USER, userId, 'a-user', 'tenant-a');
+ await seed(PrincipalType.ROLE, '__base__', 'a-base', 'tenant-a');
+ });
+
+ afterEach(() => {
+ delete process.env.TENANT_ISOLATION_STRICT;
+ resetTenantStrictCache();
+ });
+
+ it("reads and lists a tenant's group and user documents outside a tenant", async () => {
+ const group = await methods.findConfigByPrincipal(PrincipalType.GROUP, groupId);
+ const user = await methods.findConfigByPrincipal(PrincipalType.USER, userId);
+
+ expect(group?.tenantId).toBe('tenant-a');
+ expect(user?.tenantId).toBe('tenant-a');
+ expect((await methods.listAllConfigs()).map((config) => config.principalId).sort()).toEqual(
+ [groupId, userId].sort(),
+ );
+ });
+
+ it("updates and deletes a tenant's group document outside a tenant, as a group cascade does", async () => {
+ await methods.patchConfigFields(
+ PrincipalType.GROUP,
+ groupId,
+ PrincipalModel.GROUP,
+ { 'registration.socialLogins': ['google'] },
+ 10,
+ );
+ const deleted = await methods.deleteConfig(PrincipalType.GROUP, groupId);
+
+ expect(deleted?.tenantId).toBe('tenant-a');
+ expect(deleted?.overrides).toEqual({
+ registration: { allowedDomains: ['a-group'], socialLogins: ['google'] },
+ });
+ expect(await methods.deleteConfig(PrincipalType.USER, userId)).toEqual(
+ expect.objectContaining({ tenantId: 'tenant-a' }),
+ );
+ expect(await raw().countDocuments()).toBe(1);
+ });
+
+ it("does not reach another tenant's group or user document inside a tenant", async () => {
+ expect(
+ await inTenant('tenant-b', () => methods.findConfigByPrincipal(PrincipalType.GROUP, groupId)),
+ ).toBeNull();
+ expect(
+ await inTenant('tenant-b', () => methods.deleteConfig(PrincipalType.USER, userId)),
+ ).toBeNull();
+ expect(await inTenant('tenant-b', () => methods.listAllConfigs())).toEqual([]);
+ expect(await inTenant('tenant-a', () => methods.listAllConfigs())).toHaveLength(3);
+ });
+
+ it('keeps resolution in one partition for group and user principals', async () => {
+ const principals = [
+ { principalType: PrincipalType.GROUP, principalId: groupId },
+ { principalType: PrincipalType.USER, principalId: userId },
+ ];
+
+ expect(await methods.getApplicableConfigs(principals)).toEqual([]);
+ expect(await inTenant('tenant-a', () => methods.getApplicableConfigs(principals))).toHaveLength(
+ 3,
+ );
+ });
+
+ it('refuses an unscoped group read in strict mode', async () => {
+ process.env.TENANT_ISOLATION_STRICT = 'true';
+ resetTenantStrictCache();
+
+ await expect(methods.findConfigByPrincipal(PrincipalType.GROUP, groupId)).rejects.toThrow(
+ '[TenantIsolation]',
+ );
+ });
+});
+
function collectKeys(value: unknown, keys: string[] = []): string[] {
if (Array.isArray(value)) {
value.forEach((item) => collectKeys(item, keys));
diff --git a/packages/data-schemas/src/methods/config.ts b/packages/data-schemas/src/methods/config.ts
index 9f50ed3af5..98ec5a430c 100644
--- a/packages/data-schemas/src/methods/config.ts
+++ b/packages/data-schemas/src/methods/config.ts
@@ -1,5 +1,6 @@
import { Types } from 'mongoose';
-import type { PrincipalType, PrincipalModel, TCustomConfig } from 'librechat-data-provider';
+import { PrincipalType } from 'librechat-data-provider';
+import type { PrincipalModel, TCustomConfig } from 'librechat-data-provider';
import type { Model } from 'mongoose';
import type {
ConfigDraft,
@@ -7,11 +8,13 @@ import type {
ConfigRecord,
ConfigRevision,
ConfigPrincipal,
+ ConfigListFilter,
ConfigTombstones,
ConfigPathInputs,
ConfigWriteOptions,
ConfigLifecycleOptions,
} from '~/app/store';
+import type { TenantPartitionFilter } from '~/models/plugins/tenantIsolation';
import type { StoredKeyForm } from './encoding';
import type { IConfig } from '~/types';
import {
@@ -27,6 +30,7 @@ import {
getStoredKeyForms,
CONFIG_KEY_ENCODING_VERSION,
} from './encoding';
+import { tenantPartitionFilter } from '~/models/plugins/tenantIsolation';
import { isFieldNameRejection } from '~/utils/fields';
import logger from '~/config/winston';
@@ -75,10 +79,32 @@ function toRecord(document: StoredConfig): ConfigRecord {
return record;
}
-function principalFilter(principal: ConfigPrincipal): ConfigPrincipal {
+/** A principal's document in one tenant partition, as role documents are addressed. */
+type PrincipalFilter = ConfigPrincipal | (ConfigPrincipal & TenantPartitionFilter);
+
+function identityFilter(principal: ConfigPrincipal): ConfigPrincipal {
return { principalType: principal.principalType, principalId: principal.principalId };
}
+/**
+ * The filter that addresses one principal's document. A role's document, `__base__` included,
+ * is addressed in the active tenant partition (`tenantPartition`): role ids are names every
+ * tenant reuses and a document's identity includes its tenant (the unique index is principal
+ * plus `tenantId`), so without a tenant in context an unpartitioned filter would match
+ * whichever tenant's document comes first, and an unscoped admin write could land in a tenant's
+ * profile that the deployment's own resolution never reads. Group and user ids are unique across
+ * tenants, so their documents are addressed by id alone, like the groups and users themselves:
+ * inside a tenant the tenant plugin still scopes them, and outside one a group's or user's
+ * cleanup reaches its document whichever tenant holds it.
+ */
+function principalFilter(principal: ConfigPrincipal, operation: string): PrincipalFilter {
+ const filter = identityFilter(principal);
+ if (principal.principalType !== PrincipalType.ROLE) {
+ return filter;
+ }
+ return { ...filter, ...tenantPartitionFilter(operation) };
+}
+
/** A legacy document may predate `configVersion`; version 0 matches it too. */
function versionFilter(configVersion: number): number | { $in: Array<number | null> } {
return configVersion === 0 ? { $in: [0, null] } : configVersion;
@@ -99,13 +125,14 @@ function isDuplicateKeyError(error: unknown): boolean {
function revisionFilter(
principal: ConfigPrincipal,
revision: ConfigRevision,
+ operation: string,
): Record<string, unknown> | null {
const parsed = parseConfigRevision(revision);
if (!parsed || !Types.ObjectId.isValid(parsed.id)) {
return null;
}
return {
- ...principalFilter(principal),
+ ...principalFilter(principal, operation),
_id: new Types.ObjectId(parsed.id),
configVersion: versionFilter(parsed.configVersion),
};
@@ -121,7 +148,8 @@ interface StoredKeys {
* The Mongoose engine for the portable config store. Override keys are stored raw where the
* engine accepts them and encoded where it refuses them (see `./encoding`), and every read
* decodes them. Queries run through the `Config` model, so the tenant-isolation plugin scopes
- * every read and write.
+ * every read and write; role documents are also kept to one tenant partition (`principalFilter`),
+ * and `listActive`, which a merge reads, draws every document from one partition.
*/
export function createConfigStore(mongoose: typeof import('mongoose')): ConfigStore {
const model = () => mongoose.models.Config as Model<IConfig>;
@@ -155,25 +183,51 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
}
async function read(principal: ConfigPrincipal): Promise<ConfigRecord | null> {
- const document = await model().findOne(principalFilter(principal)).lean<StoredConfig>();
+ const document = await model()
+ .findOne(principalFilter(principal, 'configStore.read'))
+ .lean<StoredConfig>();
return document ? toRecord(document) : null;
}
- async function list(filter?: { isActive?: boolean }): Promise<ConfigRecord[]> {
- const where: { isActive?: boolean } = {};
- if (filter?.isActive !== undefined) {
- where.isActive = filter.isActive;
- }
+ /**
+ * Every document the caller can address by principal: the role documents of the active tenant
+ * partition, and the group and user documents the tenant plugin lets it see. `acrossTenants`
+ * drops the partition, so role documents of every tenant the plugin lets it see are listed too.
+ */
+ async function list(filter?: ConfigListFilter): Promise<ConfigRecord[]> {
+ const where = {
+ ...(filter?.acrossTenants
+ ? {}
+ : {
+ $or: [
+ { principalType: { $ne: PrincipalType.ROLE } },
+ { principalType: PrincipalType.ROLE, ...tenantPartitionFilter('configStore.list') },
+ ],
+ }),
+ ...(filter?.isActive !== undefined ? { isActive: filter.isActive } : {}),
+ };
const documents = await model().find(where).sort(STORE_ORDER).lean<StoredConfig[]>();
return documents.map(toRecord);
}
+ /**
+ * The active documents of `principals`, all from one tenant partition: the active tenant's, or
+ * the tenantless ones outside a tenant. Role ids are names shared across tenants, so an
+ * unpartitioned read would merge every tenant's `__base__` and same-named role documents into
+ * one config.
+ */
async function listActive(principals: readonly ConfigPrincipal[]): Promise<ConfigRecord[]> {
if (principals.length === 0) {
return [];
}
const documents = await model()
- .find({ $or: principals.map(principalFilter), isActive: true })
+ .find({
+ $and: [
+ { $or: principals.map(identityFilter) },
+ tenantPartitionFilter('configStore.listActive'),
+ ],
+ isActive: true,
+ })
.sort(STORE_ORDER)
.lean<StoredConfig[]>();
return documents.map(toRecord);
@@ -196,7 +250,7 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
try {
const document = await model()
.findOneAndUpdate(
- principalFilter(principal),
+ principalFilter(principal, 'configStore.write'),
{
$setOnInsert: { ...fields, _id, configVersion: 1, createdAt: now, updatedAt: now },
},
@@ -235,7 +289,7 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
if (expected === ABSENT_CONFIG_REVISION) {
return storeKeys(draft.overrides ?? {}, (keys) => create(principal, fields(keys)));
}
- const filter = revisionFilter(principal, expected);
+ const filter = revisionFilter(principal, expected, 'configStore.write');
if (!filter) {
throw new ConfigRevisionConflictError();
}
@@ -265,7 +319,7 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
): Promise<ConfigRecord | null> {
if (expected === undefined) {
const deleted = await model()
- .findOneAndDelete(principalFilter(principal))
+ .findOneAndDelete(principalFilter(principal, 'configStore.remove'))
.lean<StoredConfig>();
return deleted ? toRecord(deleted) : null;
}
@@ -276,7 +330,7 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
}
return null;
}
- const filter = revisionFilter(principal, expected);
+ const filter = revisionFilter(principal, expected, 'configStore.remove');
const deleted = filter ? await model().findOneAndDelete(filter).lean<StoredConfig>() : null;
if (!deleted) {
throw new ConfigRevisionConflictError();
@@ -290,7 +344,10 @@ export function createConfigStore(mongoose: typeof import('mongoose')): ConfigSt
const principalId = snapshot.principalId.toString();
const result = await storeKeys(overrides ?? {}, (keys) =>
model().updateOne(
- { principalType: snapshot.principalType, principalId },
+ principalFilter(
+ { principalType: snapshot.principalType, principalId },
+ 'configStore.restore',
+ ),
{
$setOnInsert: {
...rest,
diff --git a/packages/data-schemas/src/models/plugins/tenantIsolation.ts b/packages/data-schemas/src/models/plugins/tenantIsolation.ts
index e96083287d..04719ab148 100644
--- a/packages/data-schemas/src/models/plugins/tenantIsolation.ts
+++ b/packages/data-schemas/src/models/plugins/tenantIsolation.ts
@@ -2,6 +2,7 @@ import type { Schema, Query, Aggregate } from 'mongoose';
import type { TenantDocument, TenantUpdate } from '~/tenant/policy';
import {
tenantFilter,
+ tenantPartition,
scopeReplacement,
currentTenantScope,
resolveTenantScope,
@@ -27,6 +28,24 @@ export function _resetStrictCache(): void {
warnOnInvalidStrictSetting();
+/** Rows of exactly one tenant partition: the active tenant's, or the tenantless ones. */
+export type TenantPartitionFilter =
+ | { tenantId: string }
+ | { $or: [{ tenantId: { $exists: false } }, { tenantId: { $in: [null, ''] } }] };
+
+/**
+ * Mongoose binding of `tenantPartition`, for reads that merge several rows into one answer. The
+ * tenantless form spells out `$exists: false` so it does not lean on `null` also matching a
+ * missing field. Strict mode still refuses a read with no tenant context, as every query does.
+ */
+export function tenantPartitionFilter(operation: string): TenantPartitionFilter {
+ const tenantId = tenantPartition(resolveTenantScope(operation));
+ if (tenantId != null) {
+ return { tenantId };
+ }
+ return { $or: [{ tenantId: { $exists: false } }, { tenantId: { $in: [null, ''] } }] };
+}
+
const TENANT_ISOLATION_APPLIED = Symbol.for('librechat:tenantIsolation');
interface TenantWhereDocument {
diff --git a/packages/data-schemas/src/tenant/conformance.mongoose.spec.ts b/packages/data-schemas/src/tenant/conformance.mongoose.spec.ts
index 98f53b9ac4..520fca2164 100644
--- a/packages/data-schemas/src/tenant/conformance.mongoose.spec.ts
+++ b/packages/data-schemas/src/tenant/conformance.mongoose.spec.ts
@@ -1,8 +1,6 @@
-import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
-import type { TenantRow, TenantEngineHarness } from './conformance';
-import { applyTenantIsolation } from '~/models/plugins/tenantIsolation';
import { describeTenantIsolationConformance } from './conformance';
+import { createMongooseTenantHarness } from './harness';
/**
* The Mongoose binding's answer to the portable contract. A PostgreSQL engine
@@ -10,74 +8,17 @@ import { describeTenantIsolationConformance } from './conformance';
* the seam real rather than hypothetical.
*/
-interface ConformanceDocument {
- name: string;
- tenantId?: string;
-}
-
let server: MongoMemoryServer;
-let Model: mongoose.Model<ConformanceDocument>;
-
-/** Reads and writes that must not be tenant-scoped, for fixtures and assertions. */
-const raw = () => mongoose.connection.db!.collection<ConformanceDocument>('conformances');
-
-const harness: TenantEngineHarness = {
- name: 'mongoose',
-
- async setup() {
- server = await MongoMemoryServer.create();
- await mongoose.connect(server.getUri());
-
- const schema = new mongoose.Schema<ConformanceDocument>({
- name: String,
- tenantId: { type: String, index: true },
- });
- applyTenantIsolation(schema);
- Model = mongoose.model<ConformanceDocument>('Conformance', schema);
- },
-
- async teardown() {
- await mongoose.disconnect();
- await server.stop();
- },
-
- async reset() {
- await raw().deleteMany({});
- },
-
- async seed(rows) {
- await raw().insertMany(rows.map((row) => ({ ...row })));
- },
-
- async readAllUnscoped() {
- const rows = await raw().find({}).toArray();
- return rows.map((row): TenantRow => ({ name: row.name, tenantId: row.tenantId }));
- },
-
- async insert(row) {
- await Model.create({ ...row });
- },
-
- async findNames() {
- const rows = await Model.find({}).lean();
- return rows.map((row) => row.name);
- },
-
- async count() {
- return Model.countDocuments({});
- },
-
- async rename(from, to) {
- await Model.updateOne({ name: from }, { $set: { name: to } });
- },
-
- async renameAndReassign(from, to, tenantId) {
- await Model.updateOne({ name: from }, { $set: { name: to, tenantId } });
- },
-
- async remove(name) {
- await Model.deleteOne({ name });
- },
-};
-describeTenantIsolationConformance(harness);
+describeTenantIsolationConformance(
+ createMongooseTenantHarness({
+ name: 'mongoose',
+ async connect() {
+ server = await MongoMemoryServer.create();
+ return server.getUri();
+ },
+ async release() {
+ await server.stop();
+ },
+ }),
+);
diff --git a/packages/data-schemas/src/tenant/conformance.ts b/packages/data-schemas/src/tenant/conformance.ts
index 3d3dd9e1bb..042bd363e9 100644
--- a/packages/data-schemas/src/tenant/conformance.ts
+++ b/packages/data-schemas/src/tenant/conformance.ts
@@ -21,7 +21,8 @@ import { resetTenantStrictCache } from './policy';
/** A row as the engine stores it. */
export interface TenantRow {
readonly name: string;
- readonly tenantId?: string;
+ /** Absent, `null` or `''` marks a tenantless (deployment or pre-tenancy) row. */
+ readonly tenantId?: string | null;
}
/**
@@ -45,6 +46,8 @@ export interface TenantEngineHarness {
insert(row: TenantRow): Promise<void>;
findNames(): Promise<readonly string[]>;
+ /** Reads through the engine's binding of `tenantPartition`, as merged reads do. */
+ findNamesInPartition(): Promise<readonly string[]>;
count(): Promise<number>;
rename(from: string, to: string): Promise<void>;
/** Applies an update that also attempts to set `tenantId`. */
@@ -122,6 +125,49 @@ export function describeTenantIsolationConformance(harness: TenantEngineHarness)
});
});
+ /**
+ * A read that merges rows into one answer, such as config resolution, must never mix
+ * tenants: unlike plain reads, unscoped and system contexts see only tenantless rows.
+ */
+ describe('single-partition reads', () => {
+ const partitionRows: readonly TenantRow[] = [
+ { name: 'mine', tenantId: A },
+ { name: 'theirs', tenantId: B },
+ { name: 'deployment' },
+ { name: 'legacy-null', tenantId: null },
+ { name: 'legacy-empty', tenantId: '' },
+ ];
+ const tenantless = ['deployment', 'legacy-empty', 'legacy-null'];
+
+ it('sees only the active tenant when scoped', async () => {
+ await harness.seed(partitionRows);
+
+ expect(await asA(() => harness.findNamesInPartition())).toEqual(['mine']);
+ });
+
+ it('sees only tenantless rows with no context', async () => {
+ await harness.seed(partitionRows);
+
+ expect([...(await harness.findNamesInPartition())].sort()).toEqual(tenantless);
+ });
+
+ it('sees only tenantless rows under the system sentinel', async () => {
+ await harness.seed(partitionRows);
+
+ expect([...(await asSystem(() => harness.findNamesInPartition()))].sort()).toEqual(
+ tenantless,
+ );
+ });
+
+ it('refuses a read with no tenant context in strict mode', async () => {
+ await harness.seed(partitionRows);
+
+ await withStrict(true, async () => {
+ await expect(harness.findNamesInPartition()).rejects.toThrow('[TenantIsolation]');
+ });
+ });
+ });
+
describe('writes', () => {
it('stamps the active tenant onto an insert', async () => {
await asA(() => harness.insert({ name: 'fresh' }));
diff --git a/packages/data-schemas/src/tenant/harness.ts b/packages/data-schemas/src/tenant/harness.ts
new file mode 100644
index 0000000000..bf939dfbcd
--- /dev/null
+++ b/packages/data-schemas/src/tenant/harness.ts
@@ -0,0 +1,97 @@
+import mongoose from 'mongoose';
+import type { TenantRow, TenantEngineHarness } from './conformance';
+import { applyTenantIsolation, tenantPartitionFilter } from '~/models/plugins/tenantIsolation';
+
+/**
+ * The Mongoose binding's harness for the tenant-isolation contract, on whichever server
+ * `connect` provides: mongodb-memory-server in the unit suite, or a live engine such as
+ * FerretDB in `misc/ferretdb`. A PostgreSQL engine supplies its own harness instead.
+ */
+
+interface ConformanceDocument {
+ name: string;
+ tenantId?: string | null;
+}
+
+export interface MongooseTenantEngine {
+ readonly name: string;
+ /** Starts or locates the server and returns its connection URI. */
+ connect(): Promise<string>;
+ /** Releases the server once the suite has disconnected from it. */
+ release(): Promise<void>;
+}
+
+const COLLECTION = 'conformances';
+
+export function createMongooseTenantHarness(engine: MongooseTenantEngine): TenantEngineHarness {
+ let Model: mongoose.Model<ConformanceDocument>;
+
+ /** Reads and writes that must not be tenant-scoped, for fixtures and assertions. */
+ const raw = () => mongoose.connection.db!.collection<ConformanceDocument>(COLLECTION);
+
+ return {
+ name: engine.name,
+
+ async setup() {
+ await mongoose.connect(await engine.connect());
+
+ const schema = new mongoose.Schema<ConformanceDocument>({
+ name: String,
+ tenantId: { type: String, index: true },
+ });
+ applyTenantIsolation(schema);
+ Model = mongoose.model<ConformanceDocument>('Conformance', schema, COLLECTION);
+ },
+
+ async teardown() {
+ await raw()
+ .drop()
+ .catch(() => undefined);
+ await mongoose.disconnect();
+ await engine.release();
+ },
+
+ async reset() {
+ await raw().deleteMany({});
+ },
+
+ async seed(rows) {
+ await raw().insertMany(rows.map((row) => ({ ...row })));
+ },
+
+ async readAllUnscoped() {
+ const rows = await raw().find({}).toArray();
+ return rows.map((row): TenantRow => ({ name: row.name, tenantId: row.tenantId }));
+ },
+
+ async insert(row) {
+ await Model.create({ ...row });
+ },
+
+ async findNames() {
+ const rows = await Model.find({}).lean();
+ return rows.map((row) => row.name);
+ },
+
+ async findNamesInPartition() {
+ const rows = await Model.find(tenantPartitionFilter('conformance')).lean();
+ return rows.map((row) => row.name);
+ },
+
+ async count() {
+ return Model.countDocuments({});
+ },
+
+ async rename(from, to) {
+ await Model.updateOne({ name: from }, { $set: { name: to } });
+ },
+
+ async renameAndReassign(from, to, tenantId) {
+ await Model.updateOne({ name: from }, { $set: { name: to, tenantId } });
+ },
+
+ async remove(name) {
+ await Model.deleteOne({ name });
+ },
+ };
+}
diff --git a/packages/data-schemas/src/tenant/policy.spec.ts b/packages/data-schemas/src/tenant/policy.spec.ts
index dadc8384ad..5f039f608a 100644
--- a/packages/data-schemas/src/tenant/policy.spec.ts
+++ b/packages/data-schemas/src/tenant/policy.spec.ts
@@ -1,6 +1,7 @@
import type { TenantScope } from './policy';
import {
tenantFilter,
+ tenantPartition,
scopeReplacement,
currentTenantScope,
resolveTenantScope,
@@ -114,6 +115,17 @@ describe('tenantFilter', () => {
});
});
+describe('tenantPartition', () => {
+ it('names the active tenant when scoped', () => {
+ expect(tenantPartition(SCOPED)).toBe('tenant-a');
+ });
+
+ it('names the tenantless partition for system and unscoped reads', () => {
+ expect(tenantPartition(SYSTEM)).toBeNull();
+ expect(tenantPartition(UNSCOPED)).toBeNull();
+ });
+});
+
describe('sanitizeTenantMutation (guard mode)', () => {
it('refuses a cross-tenant $set', () => {
expect(() =>
diff --git a/packages/data-schemas/src/tenant/policy.ts b/packages/data-schemas/src/tenant/policy.ts
index 109a102be7..5cea7dba76 100644
--- a/packages/data-schemas/src/tenant/policy.ts
+++ b/packages/data-schemas/src/tenant/policy.ts
@@ -99,6 +99,19 @@ export function tenantFilter(scope: TenantScope): { tenantId: string } | undefin
return scope.kind === 'scoped' ? { tenantId: scope.tenantId } : undefined;
}
+/**
+ * The one partition a read may draw from when it merges several rows into a single answer, such
+ * as the config documents layered into an app config: the active tenant's rows when scoped, and
+ * otherwise only the deployment's own rows, which carry no tenant (absent, `null` or `''`, the
+ * same unclaimed forms `tenantWritePredicate` accepts). `tenantFilter` lets unscoped and system
+ * reads see every tenant, but an answer merged from several tenants' rows means nothing, so such
+ * reads stay in one partition. `null` names the tenantless partition, all three of those forms,
+ * which a SQL engine reads as `tenant_id IS NULL OR tenant_id = ''`.
+ */
+export function tenantPartition(scope: TenantScope): string | null {
+ return scope.kind === 'scoped' ? scope.tenantId : null;
+}
+
/** Result of sanitizing an update payload against the active scope. */
export interface TenantMutationResult {
/** The payload to send to the engine — the input itself when nothing changed. */
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index fc84674a68..64c9397876 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -243,6 +243,11 @@ export type AdminConfigChangeErrorResponse = {
* - `sectionAllowlist`: writes to a top-level key `configSchema` does not define are rejected,
* and stored ones are ignored at merge.
* - `readFilteredWriteResponses`: write responses are filtered by the caller's read access.
+ * - `preAuthBaseOverrides`: Base (`__base__`) overrides apply before sign-in: the signed-out
+ * `GET /api/config` serves Base `registration.socialLogins` and the pre-login interface fields,
+ * and Base `registration.allowedDomains` gates email registration, password reset and LDAP,
+ * OpenID, SAML and social sign-in (a role profile's list then applies to that role's accounts,
+ * new ones included). Turnstile stays on librechat.yaml (`turnstile` is base-only).
* - `webSearchStoredKeys`: web search uses a key stored in config (encrypted by the admin API,
* or a `librechat.yaml` literal) at runtime, not only a `${VAR}` reference, and stores
* `webSearch.keenableApiKey` encrypted like the other web search keys. A stored key reaches a
@@ -281,6 +286,7 @@ export type AdminConfigFeatureFlag =
| 'dottedKeys'
| 'sectionAllowlist'
| 'readFilteredWriteResponses'
+ | 'preAuthBaseOverrides'
| 'webSearchStoredKeys'
| 'expectedRevision'
| 'prunesEmptyParents'