mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-08-27 04:07:05 +00:00
🔑 feat: Refresh-Capable Google Admin OAuth Sessions (#13832)
* 🔑 feat: Refresh-Capable Google Admin OAuth Sessions Google admin sessions cannot be refreshed today. Three gaps add up to that: passport.authenticate('googleAdmin', ...) in api/server/routes/admin/auth.js never sets access_type=offline, so Google omits the refresh_token from its token response; createOAuthHandler in api/server/controllers/auth/oauth.js only forwards a refresh token into the admin exchange payload when the user's provider is 'openid' AND OPENID_REUSE_TOKENS is enabled; and /api/admin/oauth/refresh is openid-only, calling openid-client.refreshTokenGrant against the configured OIDC issuer. OpenID admins refresh transparently because all three are in place for them. This PR closes all three. The googleAdmin authenticate call now passes accessType: 'offline' and prompt: 'consent' so Google issues a refresh token on consent; the chat-side googleLogin is untouched. The shared socialLogin verify callback now passes the IdP refreshToken through as passport's third argument (info), landing on req.authInfo, with the two-argument call shape preserved when no refresh token is present so existing strategy tests stay valid. createOAuthHandler reads req.authInfo?.refreshToken for non-OpenID admin providers and forwards it into the exchange code; the OpenID branch and its OPENID_REUSE_TOKENS gate are unchanged. /api/admin/oauth/refresh now accepts an optional provider field ('openid' | 'google', default 'openid'). The new Google branch POSTs grant_type=refresh_token to https://oauth2.googleapis.com/token, decodes the returned id_token for the sub claim, looks up the admin user by googleId, enforces tenant scope and ACCESS_ADMIN, and mints a fresh LibreChat JWT in the same response shape /oauth/exchange returns. It is gated on GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET being set (returns 503 GOOGLE_NOT_CONFIGURED otherwise); unknown provider values return 400 INVALID_PROVIDER. * 🔁 fix: Harden Google admin refresh against bot review findings Five validated findings from the initial bot pass: socialLogin.js: mirror the OpenID migrate-or-reject pattern on the email fallback. When an existing user is found by email and the stored provider id is empty, persist the refreshed sub so the refresh path can later bind to it. When the stored id is present and differs, reject as AUTH_FAILED to prevent identity-swap, matching the existing OpenID behavior in packages/api/src/auth/openid.ts. oauth.js: scope the non-OpenID admin refresh-token forwarding to provider === 'google'. The previous else branch would have forwarded a Discord refresh token (passport-discord supplies one) into the admin exchange payload even though /api/admin/oauth/refresh only accepts openid or google, leaving the admin client with a token it could not refresh. admin/auth.js (refreshGoogleAdminSession): drop id_token from the mandatory-fields check. Google's OAuth refresh response is documented to include id_token only conditionally, so the previous mandatory check broke refresh whenever Google omitted it. Decode id_token when present (fast path); when absent, call Google's userinfo endpoint with the access token to read sub. Wrap tokenResponse.json() in try/catch and return IDP_INCOMPLETE on parse failure instead of a generic 500. Tighten access_token to a typeof string check. admin/auth.js (refreshGoogleAdminSession): reuse serializeUserForExchange for the response user so the Google refresh shape matches /oauth/exchange and the OpenID branch exactly (full _id, id, email, name, username, role, avatar, provider, openidId). The previous Google-specific subset dropped fields the admin client relies on for later provider-specific refreshes and disambiguation. Tests cover each fix: socialLogin's migration and rejection cases, the oauth.js Discord-gating case, the userinfo fallback path on missing id_token, CLAIMS_INCOMPLETE when both id_token and userinfo are absent, IDP_INCOMPLETE on a non-JSON token body, and the full response shape on the happy path. * 🧪 fix: Add updateUser to appleStrategy test mock for socialLogin migration The shared socialLogin verify callback now invokes `updateUser` when the email-fallback path discovers a same-provider user with an empty provider id, persisting the refreshed sub. The Apple strategy test's `~/models` mock did not stub `updateUser`, so the migration path hit `TypeError: updateUser is not a function` and failed the `should handle existing user and update avatarUrl` case in CI shard 1/3. * 🧹 refactor: Move Google admin refresh into TypeScript @librechat/api helper Per repo guidance (CLAUDE.md): all new backend code must be TypeScript in /packages/api, and /api is a thin JS wrapper. The previous commit landed the Google admin refresh flow as ~120 lines of new JS inside api/server/routes/admin/auth.js, which violates that. This commit extracts the flow into a new TS helper at packages/api/src/auth/googleRefresh.ts and reduces the route handler to a thin dep-wiring wrapper. The helper exports applyGoogleAdminRefresh(deps, options) with the same shape as the OpenID applyAdminRefresh: callers pass findUsers, getUserById, canAccessAdmin, and mintToken as deps so the package stays free of /api model imports and capability/session helpers. The route handler now builds those deps from the existing model + capability + token modules and calls the helper, mapping AdminRefreshError to the documented HTTP responses. While moving the code, the helper now guards getUserById with Types.ObjectId.isValid before the direct-lookup branch, matching the OpenID admin path at packages/api/src/auth/refresh.ts. Without this guard a malformed user_id from the admin client would hit Mongoose findById's CastError and surface as a 500 INTERNAL_ERROR instead of falling through to the documented sub-based lookup. Tests move with the code: packages/api/src/auth/googleRefresh.spec.ts now owns the helper's behavior (token endpoint, userinfo fallback, ObjectId guard, USER_ID_MISMATCH/TENANT_MISMATCH/USER_NOT_FOUND/FORBIDDEN, rotated refresh-token pass-through, GOOGLE_NOT_CONFIGURED, IDP_INCOMPLETE on non-JSON body, CLAIMS_INCOMPLETE when both id_token and userinfo miss). The route-level api/server/routes/admin/auth.refresh.test.js drops the duplicated end-to-end Google cases and keeps a smaller surface: route delegates to applyGoogleAdminRefresh with the right deps + options, maps AdminRefreshError to HTTP status/code, falls through to 500 for unknown errors, and rejects unknown providers with INVALID_PROVIDER. * 🔁 fix: Tighten Google admin refresh and limit social-login changes Brutal-review findings on top of the upstream feature work. socialLogin.js: the migrate-or-reject pattern from the previous commit applied to every provider's chat-side verify callback, not just the admin flow. Gate both branches on `options.existingUsersOnly` so the chat-side googleLogin / facebookLogin / etc. keep their pre-existing email-fallback behavior unchanged. Tests follow: restore the original `should fallback to finding user by email` chat-side case and re-add the migration and mismatch-reject cases as admin-only by passing `{ existingUsersOnly: true }` to socialLogin in those tests. googleRefresh.ts: add a defense-in-depth `isEmailAllowed(user)` dep that the helper invokes before `canAccessAdmin`. Mirrors the `isEmailDomainAllowed` check the initial Google admin login already runs, so a deployment that removes a domain from `registration.allowedDomains` after issuance can no longer mint fresh JWTs for that admin via refresh. The route handler wires it up with `resolveAppConfigForUser` + `isEmailDomainAllowed`, falling back to `baseOnly` config for users without a tenantId. googleRefresh.ts: drop the unreachable `?? ''` defensive coalescing in `fetchGoogleTokenset`. The `GOOGLE_NOT_CONFIGURED` guard upstream already narrows `clientId`/`clientSecret` to non-empty strings; the function takes a narrowed `GoogleAdminRefreshConfiguredOptions` shape and `applyGoogleAdminRefresh` constructs that shape after the guard. * 🔒 fix: Apply brutal-review hardening to Google admin refresh Tighten the Google OAuth refresh flow against all outstanding code review findings: enforce JWT aud claim verification against the configured clientId (ISSUER_MISMATCH on mismatch), reject ambiguous googleId matches (limit:2 in findUsers, USER_ID_MISMATCH when multiple rows match), scope the authInfo refresh-token carrier to the Google provider only, add TOCTOU re-read defense after the admin googleId migration write in socialLogin, deduplicate canAccessAdmin/mintToken closures via buildAdminRefreshClosures shared by both OpenID and Google refresh paths, document rotation semantics on AdminExchangeResponse.refreshToken, standardise all log prefixes to [admin/oauth/refresh], and expand test coverage for all new paths. * 🔒 fix: Reject refresh for users migrated off the Google provider The interactive Google admin login path in socialLogin.js already rejects a user whose provider field is not 'google', returning AUTH_FAILED. Without a matching guard in the refresh path, a user migrated to OpenID could use an unexpired Google refresh token to keep minting admin JWTs indefinitely. Add a PROVIDER_MISMATCH check after resolving the user in both the direct getUserById branch and the findUsers fallback branch of resolveAdminUser, mirroring the provider gate the interactive path enforces. * 🔒 fix: Add ban check and fix domain allowlist on admin OAuth refresh Two gaps in the /api/admin/oauth/refresh route: Add middleware.checkBan to the route chain before preAuthTenantMiddleware, matching the gate that /login/local and createOAuthHandler already apply. Without it a banned admin could keep minting JWTs until their IdP refresh token expired. Replace getAppConfig({ baseOnly: true }) in the non-tenant isEmailAllowed closure with getAppConfig({ role: user.role }), which includes DB-layer overrides from the admin panel. baseOnly returns only YAML-derived config, so any allowedDomains list maintained entirely through the admin panel was silently inert on this path. Extract isEmailAllowedForUser as a shared helper, move it into buildAdminRefreshClosures so both Google and OpenID refresh paths enforce domain policy consistently, and add isEmailAllowed to AdminRefreshDeps in the TS package so applyAdminRefresh can invoke it. * 🔒 fix: Harden admin OAuth refresh against user bans, tenant scope gaps, and cross-tenant migration Post-identity-resolution ban check: the initial checkBan middleware fires before the refresh token is exchanged and req.user is populated, so it can only evaluate IP bans. After applyGoogleAdminRefresh/applyAdminRefresh resolves the user identity, we now synthesize req.user and re-run checkBan against the resolved user's id before emitting the JWT, so a user-level ban is enforced even from a fresh IP. Domain allowlist now includes userId: the getAppConfig call in isEmailAllowedForUser was passing only role, missing user and group-level allowedDomains overrides that the initial OAuth callback's checkDomainAllowed enforces via userId. Both branches now pass userId so buildPrincipals takes the full user+group+role resolution path. The tenant branch is also inlined (replacing resolveAppConfigForUser) to accept userId, wrapped in tenantStorage.run for correct Mongoose scoping and cache-key resolution. Cross-tenant email-fallback migration: the Passport verify callback fires before tenantContextMiddleware, so findUser({email}) is unscoped and can return a same-email user from another tenant. Writing googleId onto that document permanently corrupts the other tenant's account. Migration is now blocked for users with a tenantId; single-tenant users are unaffected. --------- Co-authored-by: Danny Avila <danny@librechat.ai>
This commit is contained in:
parent
e3b8e30327
commit
6d2f29266c
12 changed files with 1405 additions and 177 deletions
|
|
@ -43,11 +43,15 @@ function createOAuthHandler(redirectUri = domains.client) {
|
|||
const sessionExpiry = Number(process.env.SESSION_EXPIRY) || DEFAULT_SESSION_EXPIRY;
|
||||
const token = await generateToken(req.user, sessionExpiry);
|
||||
|
||||
/** Get refresh token from tokenset for OpenID users */
|
||||
const refreshToken =
|
||||
req.user.provider === 'openid' && isEnabled(process.env.OPENID_REUSE_TOKENS) === true
|
||||
? req.user.tokenset?.refresh_token || req.user.federatedTokens?.refresh_token
|
||||
: undefined;
|
||||
let refreshToken;
|
||||
if (req.user.provider === 'openid') {
|
||||
if (isEnabled(process.env.OPENID_REUSE_TOKENS) === true) {
|
||||
refreshToken =
|
||||
req.user.tokenset?.refresh_token || req.user.federatedTokens?.refresh_token;
|
||||
}
|
||||
} else if (req.user.provider === 'google') {
|
||||
refreshToken = req.authInfo?.refreshToken;
|
||||
}
|
||||
const expiresAt = Date.now() + sessionExpiry;
|
||||
|
||||
const callbackUrl = new URL(redirectUri);
|
||||
|
|
|
|||
|
|
@ -148,4 +148,69 @@ describe('createOAuthHandler', () => {
|
|||
expect(mockSetAuthTokens).not.toHaveBeenCalled();
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('forwards the refresh token from req.authInfo for non-openid admin providers', async () => {
|
||||
const handler = createOAuthHandler('http://admin.example.com/auth/google/callback');
|
||||
const req = buildReq({
|
||||
user: { _id: 'user-9', email: 'g@example.com', provider: 'google' },
|
||||
authInfo: { refreshToken: 'google-refresh-token' },
|
||||
});
|
||||
const res = buildRes();
|
||||
const next = jest.fn();
|
||||
|
||||
await handler(req, res, next);
|
||||
|
||||
expect(mockGenerateAdminExchangeCode).toHaveBeenCalledWith(
|
||||
{},
|
||||
req.user,
|
||||
'jwt-token',
|
||||
'google-refresh-token',
|
||||
'http://admin.example.com',
|
||||
'pkce-challenge',
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it('omits the refresh token when a non-openid admin login has no authInfo', async () => {
|
||||
const handler = createOAuthHandler('http://admin.example.com/auth/google/callback');
|
||||
const req = buildReq({
|
||||
user: { _id: 'user-9', email: 'g@example.com', provider: 'google' },
|
||||
});
|
||||
const res = buildRes();
|
||||
const next = jest.fn();
|
||||
|
||||
await handler(req, res, next);
|
||||
|
||||
expect(mockGenerateAdminExchangeCode).toHaveBeenCalledWith(
|
||||
{},
|
||||
req.user,
|
||||
'jwt-token',
|
||||
undefined,
|
||||
'http://admin.example.com',
|
||||
'pkce-challenge',
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
|
||||
it('does not forward refresh tokens for admin providers other than google or openid', async () => {
|
||||
const handler = createOAuthHandler('http://admin.example.com/auth/discord/callback');
|
||||
const req = buildReq({
|
||||
user: { _id: 'user-9', email: 'd@example.com', provider: 'discord' },
|
||||
authInfo: { refreshToken: 'discord-refresh-token' },
|
||||
});
|
||||
const res = buildRes();
|
||||
const next = jest.fn();
|
||||
|
||||
await handler(req, res, next);
|
||||
|
||||
expect(mockGenerateAdminExchangeCode).toHaveBeenCalledWith(
|
||||
{},
|
||||
req.user,
|
||||
'jwt-token',
|
||||
undefined,
|
||||
'http://admin.example.com',
|
||||
'pkce-challenge',
|
||||
expect.any(Number),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ const {
|
|||
DEFAULT_SESSION_EXPIRY,
|
||||
SystemCapabilities,
|
||||
getTenantId,
|
||||
tenantStorage,
|
||||
} = require('@librechat/data-schemas');
|
||||
const {
|
||||
isEnabled,
|
||||
|
|
@ -18,8 +19,10 @@ const {
|
|||
tenantContextMiddleware,
|
||||
preAuthTenantMiddleware,
|
||||
applyAdminRefresh,
|
||||
applyGoogleAdminRefresh,
|
||||
AdminRefreshError,
|
||||
buildOpenIDRefreshParams,
|
||||
isEmailDomainAllowed,
|
||||
} = require('@librechat/api');
|
||||
const { loginController } = require('~/server/controllers/auth/LoginController');
|
||||
const { hasCapability, requireCapability } = require('~/server/middleware/roles/capabilities');
|
||||
|
|
@ -101,6 +104,55 @@ function resolveRequestOrigin(req) {
|
|||
}
|
||||
}
|
||||
|
||||
async function isEmailAllowedForUser(user) {
|
||||
if (!user?.email) return false;
|
||||
try {
|
||||
const userId = user.id ?? user._id?.toString();
|
||||
const appConfig = user.tenantId
|
||||
? await tenantStorage.run({ tenantId: user.tenantId }, () =>
|
||||
getAppConfig({ role: user.role ?? '', userId, tenantId: user.tenantId }),
|
||||
)
|
||||
: await getAppConfig({ role: user.role ?? '', userId });
|
||||
return isEmailDomainAllowed(user.email, appConfig?.registration?.allowedDomains);
|
||||
} catch (err) {
|
||||
logger.warn(`[admin/oauth/refresh] domain allowlist check failed, denying: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function buildAdminRefreshClosures(sessionExpiry) {
|
||||
return {
|
||||
canAccessAdmin: async (user) => {
|
||||
try {
|
||||
return await hasCapability(
|
||||
{
|
||||
id: user.id ?? user._id?.toString(),
|
||||
role: user.role ?? '',
|
||||
tenantId: user.tenantId,
|
||||
},
|
||||
SystemCapabilities.ACCESS_ADMIN,
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn(`[admin/oauth/refresh] capability check failed, denying: ${err?.message}`);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
isEmailAllowed: isEmailAllowedForUser,
|
||||
mintToken: async (user) => ({
|
||||
token: await generateToken(user, sessionExpiry),
|
||||
expiresAt: Date.now() + sessionExpiry,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildGoogleAdminRefreshDeps(sessionExpiry) {
|
||||
return {
|
||||
findUsers,
|
||||
getUserById,
|
||||
...buildAdminRefreshClosures(sessionExpiry),
|
||||
};
|
||||
}
|
||||
|
||||
router.post(
|
||||
'/login/local',
|
||||
middleware.logHeaders,
|
||||
|
|
@ -275,6 +327,8 @@ router.get(
|
|||
scope: ['openid', 'profile', 'email'],
|
||||
session: false,
|
||||
state,
|
||||
accessType: 'offline',
|
||||
prompt: 'consent',
|
||||
})(req, res, next);
|
||||
},
|
||||
);
|
||||
|
|
@ -548,30 +602,37 @@ router.post('/oauth/exchange', middleware.loginLimiter, async (req, res) => {
|
|||
* `/api/admin/oauth/exchange`.
|
||||
*
|
||||
* POST /api/admin/oauth/refresh
|
||||
* Body: { refresh_token: string, user_id?: string }
|
||||
* Body: { refresh_token: string, user_id?: string, provider?: 'openid' | 'google' }
|
||||
* Response: { token: string, refreshToken?: string, user: object, expiresAt: number }
|
||||
*
|
||||
* Errors (all responses are `{ error: string, error_code: string }`):
|
||||
* 400 MISSING_REFRESH_TOKEN — refresh_token absent or empty
|
||||
* 400 INVALID_PROVIDER — provider value not one of 'openid' | 'google'
|
||||
* 401 REFRESH_FAILED — IdP rejected the refresh grant
|
||||
* 401 USER_NOT_FOUND — no LibreChat user matches the refreshed sub
|
||||
* 401 USER_ID_MISMATCH — supplied user_id resolves to a user with a different openidId
|
||||
* 401 USER_ID_MISMATCH — supplied user_id resolves to a different provider id
|
||||
* 401 ISSUER_MISMATCH — refreshed tokenset was issued by an unexpected issuer
|
||||
* 401 TENANT_MISMATCH — resolved user belongs to a different tenant than the request
|
||||
* 403 FORBIDDEN — resolved user no longer holds ACCESS_ADMIN
|
||||
* 403 TOKEN_REUSE_DISABLED — OPENID_REUSE_TOKENS is not enabled on the server
|
||||
* 502 IDP_INCOMPLETE — IdP returned a tokenset missing access_token
|
||||
* 403 TOKEN_REUSE_DISABLED — OPENID_REUSE_TOKENS is not enabled (openid provider only)
|
||||
* 502 IDP_INCOMPLETE — IdP returned a tokenset missing access_token / id_token
|
||||
* 502 CLAIMS_INCOMPLETE — IdP tokenset has no readable claims or no sub
|
||||
* 503 OPENID_NOT_CONFIGURED — OpenID is not configured on this server
|
||||
* 503 GOOGLE_NOT_CONFIGURED — Google admin OAuth is not configured on this server
|
||||
* 500 INTERNAL_ERROR — anything else (logged server-side)
|
||||
*/
|
||||
router.post(
|
||||
'/oauth/refresh',
|
||||
middleware.loginLimiter,
|
||||
middleware.checkBan,
|
||||
preAuthTenantMiddleware,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { refresh_token: refreshToken, user_id: userId } = req.body ?? {};
|
||||
const {
|
||||
refresh_token: refreshToken,
|
||||
user_id: userId,
|
||||
provider: rawProvider,
|
||||
} = req.body ?? {};
|
||||
if (typeof refreshToken !== 'string' || refreshToken.length === 0) {
|
||||
return res.status(400).json({
|
||||
error: 'Missing refresh_token',
|
||||
|
|
@ -579,6 +640,40 @@ router.post(
|
|||
});
|
||||
}
|
||||
|
||||
const provider =
|
||||
typeof rawProvider === 'string' && rawProvider.length > 0 ? rawProvider : 'openid';
|
||||
if (provider !== 'openid' && provider !== 'google') {
|
||||
return res.status(400).json({
|
||||
error: 'Unsupported provider',
|
||||
error_code: 'INVALID_PROVIDER',
|
||||
});
|
||||
}
|
||||
|
||||
const sessionExpiry = Number(process.env.SESSION_EXPIRY) || DEFAULT_SESSION_EXPIRY;
|
||||
const normalizedUserId = typeof userId === 'string' && userId.length > 0 ? userId : undefined;
|
||||
const tenantId = getTenantId();
|
||||
|
||||
if (provider === 'google') {
|
||||
try {
|
||||
const result = await applyGoogleAdminRefresh(buildGoogleAdminRefreshDeps(sessionExpiry), {
|
||||
refreshToken,
|
||||
userId: normalizedUserId,
|
||||
tenantId,
|
||||
clientId: process.env.GOOGLE_CLIENT_ID,
|
||||
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
|
||||
});
|
||||
req.user = { id: result.user._id };
|
||||
await middleware.checkBan(req, res, () => {});
|
||||
if (req.banned || res.headersSent) return;
|
||||
return res.json(result);
|
||||
} catch (err) {
|
||||
if (err instanceof AdminRefreshError) {
|
||||
return res.status(err.status).json({ error: err.message, error_code: err.code });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isEnabled(process.env.OPENID_REUSE_TOKENS)) {
|
||||
return res.status(403).json({
|
||||
error: 'OpenID token reuse is not enabled',
|
||||
|
|
@ -621,7 +716,6 @@ router.post(
|
|||
});
|
||||
}
|
||||
|
||||
const sessionExpiry = Number(process.env.SESSION_EXPIRY) || DEFAULT_SESSION_EXPIRY;
|
||||
const expectedIssuer = openIdConfig.serverMetadata?.()?.issuer;
|
||||
|
||||
try {
|
||||
|
|
@ -630,35 +724,18 @@ router.post(
|
|||
{
|
||||
findUsers,
|
||||
getUserById,
|
||||
canAccessAdmin: async (user) => {
|
||||
try {
|
||||
return await hasCapability(
|
||||
{
|
||||
id: user.id ?? user._id?.toString(),
|
||||
role: user.role ?? '',
|
||||
tenantId: user.tenantId,
|
||||
},
|
||||
SystemCapabilities.ACCESS_ADMIN,
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn(
|
||||
`[admin/oauth/refresh] capability check failed, denying: ${err?.message}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
mintToken: async (user) => ({
|
||||
token: await generateToken(user, sessionExpiry),
|
||||
expiresAt: Date.now() + sessionExpiry,
|
||||
}),
|
||||
...buildAdminRefreshClosures(sessionExpiry),
|
||||
},
|
||||
{
|
||||
userId: typeof userId === 'string' && userId.length > 0 ? userId : undefined,
|
||||
userId: normalizedUserId,
|
||||
previousRefreshToken: refreshToken,
|
||||
expectedIssuer,
|
||||
tenantId: getTenantId(),
|
||||
tenantId,
|
||||
},
|
||||
);
|
||||
req.user = { id: result.user._id };
|
||||
await middleware.checkBan(req, res, () => {});
|
||||
if (req.banned || res.headersSent) return;
|
||||
return res.json(result);
|
||||
} catch (err) {
|
||||
if (err instanceof AdminRefreshError) {
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ jest.mock('@librechat/data-schemas', () => ({
|
|||
DEFAULT_SESSION_EXPIRY: 60000,
|
||||
SystemCapabilities: { ACCESS_ADMIN: 'ACCESS_ADMIN' },
|
||||
getTenantId: jest.fn(() => undefined),
|
||||
tenantStorage: { run: jest.fn((ctx, fn) => fn()) },
|
||||
}));
|
||||
|
||||
jest.mock('@librechat/api', () => {
|
||||
|
|
@ -44,6 +45,7 @@ jest.mock('@librechat/api', () => {
|
|||
tenantContextMiddleware: jest.fn((req, res, next) => next()),
|
||||
preAuthTenantMiddleware: jest.fn((req, res, next) => next()),
|
||||
applyAdminRefresh: jest.fn(),
|
||||
applyGoogleAdminRefresh: jest.fn(),
|
||||
AdminRefreshError,
|
||||
buildOpenIDRefreshParams: jest.fn(() => {
|
||||
const params = {};
|
||||
|
|
@ -110,6 +112,7 @@ const { logger } = require('@librechat/data-schemas');
|
|||
const {
|
||||
isEnabled,
|
||||
applyAdminRefresh,
|
||||
applyGoogleAdminRefresh,
|
||||
storeAndStripChallenge,
|
||||
buildOpenIDRefreshParams,
|
||||
} = require('@librechat/api');
|
||||
|
|
@ -121,146 +124,6 @@ const ORIGINAL_OPENID_SCOPE = process.env.OPENID_SCOPE;
|
|||
const ORIGINAL_OPENID_REFRESH_AUDIENCE = process.env.OPENID_REFRESH_AUDIENCE;
|
||||
const ORIGINAL_SESSION_EXPIRY = process.env.SESSION_EXPIRY;
|
||||
|
||||
describe('admin auth OpenID route availability', () => {
|
||||
let app;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin', adminAuthRouter);
|
||||
});
|
||||
|
||||
it('returns not configured for the OpenID availability check when config lookup throws', async () => {
|
||||
getOpenIdConfig.mockImplementation(() => {
|
||||
throw new Error('OpenID client is not initialized. Please call setupOpenId first.');
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/admin/oauth/openid/check');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: 'OpenID configuration not found',
|
||||
error_code: 'OPENID_NOT_CONFIGURED',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not start OpenID admin login when config lookup throws', async () => {
|
||||
getOpenIdConfig.mockImplementation(() => {
|
||||
throw new Error('OpenID client is not initialized. Please call setupOpenId first.');
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/admin/oauth/openid');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: 'OpenID configuration not found',
|
||||
error_code: 'OPENID_NOT_CONFIGURED',
|
||||
});
|
||||
expect(storeAndStripChallenge).not.toHaveBeenCalled();
|
||||
expect(passport.authenticate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not run OpenID admin callback auth when config lookup throws', async () => {
|
||||
getOpenIdConfig.mockImplementation(() => {
|
||||
throw new Error('OpenID client is not initialized. Please call setupOpenId first.');
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/admin/oauth/openid/callback?state=state');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: 'OpenID configuration not found',
|
||||
error_code: 'OPENID_NOT_CONFIGURED',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin auth social route availability', () => {
|
||||
let app;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
passport._strategy.mockReturnValue(undefined);
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin', adminAuthRouter);
|
||||
});
|
||||
|
||||
const startRoutes = [
|
||||
['saml', 'SAML'],
|
||||
['google', 'Google'],
|
||||
['github', 'GitHub'],
|
||||
['discord', 'Discord'],
|
||||
['facebook', 'Facebook'],
|
||||
['apple', 'Apple'],
|
||||
];
|
||||
|
||||
it.each(startRoutes)(
|
||||
'does not start %s admin login when the strategy is not registered',
|
||||
async (path, provider) => {
|
||||
const response = await request(app).get(`/api/admin/oauth/${path}`);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: `${provider} configuration not found`,
|
||||
error_code: `${provider.toUpperCase()}_NOT_CONFIGURED`,
|
||||
});
|
||||
expect(storeAndStripChallenge).not.toHaveBeenCalled();
|
||||
expect(passport.authenticate).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
const callbackRoutes = [
|
||||
[
|
||||
'saml',
|
||||
'SAML',
|
||||
(agent) => agent.post('/api/admin/oauth/saml/callback').send({ RelayState: 'state' }),
|
||||
],
|
||||
['google', 'Google', (agent) => agent.get('/api/admin/oauth/google/callback?state=state')],
|
||||
['github', 'GitHub', (agent) => agent.get('/api/admin/oauth/github/callback?state=state')],
|
||||
['discord', 'Discord', (agent) => agent.get('/api/admin/oauth/discord/callback?state=state')],
|
||||
[
|
||||
'facebook',
|
||||
'Facebook',
|
||||
(agent) => agent.get('/api/admin/oauth/facebook/callback?state=state'),
|
||||
],
|
||||
[
|
||||
'apple',
|
||||
'Apple',
|
||||
(agent) => agent.post('/api/admin/oauth/apple/callback').send({ state: 'state' }),
|
||||
],
|
||||
];
|
||||
|
||||
it.each(callbackRoutes)(
|
||||
'does not run %s admin callback auth when the strategy is not registered',
|
||||
async (path, provider, makeRequest) => {
|
||||
const response = await makeRequest(request(app));
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: `${provider} configuration not found`,
|
||||
error_code: `${provider.toUpperCase()}_NOT_CONFIGURED`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('starts admin login when the strategy is registered', async () => {
|
||||
passport._strategy.mockReturnValue({ name: 'googleAdmin' });
|
||||
storeAndStripChallenge.mockResolvedValue(true);
|
||||
|
||||
await request(app).get('/api/admin/oauth/google');
|
||||
|
||||
expect(storeAndStripChallenge).toHaveBeenCalledTimes(1);
|
||||
expect(passport.authenticate).toHaveBeenCalledWith(
|
||||
'googleAdmin',
|
||||
expect.objectContaining({ session: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin auth OpenID refresh route', () => {
|
||||
const openIdConfig = {
|
||||
serverMetadata: jest.fn(() => ({ issuer: 'https://issuer.example.com' })),
|
||||
|
|
@ -398,6 +261,326 @@ describe('admin auth OpenID refresh route', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('admin auth Google refresh route', () => {
|
||||
let app;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
delete process.env.SESSION_EXPIRY;
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin', adminAuthRouter);
|
||||
|
||||
process.env.GOOGLE_CLIENT_ID = 'google-client-id';
|
||||
process.env.GOOGLE_CLIENT_SECRET = 'google-client-secret';
|
||||
|
||||
applyGoogleAdminRefresh.mockResolvedValue({
|
||||
token: 'admin-jwt',
|
||||
refreshToken: 'rotated-refresh',
|
||||
user: {
|
||||
_id: 'user-id',
|
||||
id: 'user-id',
|
||||
email: 'admin@example.com',
|
||||
name: 'Admin',
|
||||
username: 'admin',
|
||||
role: 'ADMIN',
|
||||
provider: 'google',
|
||||
},
|
||||
expiresAt: 1234567890,
|
||||
});
|
||||
});
|
||||
|
||||
it('delegates to applyGoogleAdminRefresh with route-supplied deps and options', async () => {
|
||||
const response = await request(app).post('/api/admin/oauth/refresh').send({
|
||||
refresh_token: 'incoming-google-refresh',
|
||||
user_id: '6a343eb8b5025a84b6ca2767',
|
||||
provider: 'google',
|
||||
});
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toEqual({
|
||||
token: 'admin-jwt',
|
||||
refreshToken: 'rotated-refresh',
|
||||
user: expect.objectContaining({
|
||||
_id: 'user-id',
|
||||
id: 'user-id',
|
||||
email: 'admin@example.com',
|
||||
name: 'Admin',
|
||||
username: 'admin',
|
||||
role: 'ADMIN',
|
||||
provider: 'google',
|
||||
}),
|
||||
expiresAt: 1234567890,
|
||||
});
|
||||
expect(applyGoogleAdminRefresh).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
findUsers: expect.any(Function),
|
||||
getUserById: expect.any(Function),
|
||||
canAccessAdmin: expect.any(Function),
|
||||
mintToken: expect.any(Function),
|
||||
}),
|
||||
{
|
||||
refreshToken: 'incoming-google-refresh',
|
||||
userId: '6a343eb8b5025a84b6ca2767',
|
||||
tenantId: undefined,
|
||||
clientId: 'google-client-id',
|
||||
clientSecret: 'google-client-secret',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('forwards the tenant id from getTenantId() to the helper', async () => {
|
||||
const { getTenantId } = require('@librechat/data-schemas');
|
||||
getTenantId.mockReturnValueOnce('tenant-x');
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-google-refresh', provider: 'google' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(applyGoogleAdminRefresh).toHaveBeenCalledWith(
|
||||
expect.any(Object),
|
||||
expect.objectContaining({ tenantId: 'tenant-x' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('canAccessAdmin closure calls hasCapability with the normalized user id', async () => {
|
||||
const { hasCapability } = require('~/server/middleware/roles/capabilities');
|
||||
let capturedDeps;
|
||||
applyGoogleAdminRefresh.mockImplementationOnce(async (deps) => {
|
||||
capturedDeps = deps;
|
||||
return {
|
||||
token: 'jwt',
|
||||
refreshToken: 'r',
|
||||
user: { id: 'u', _id: 'u', email: 'e@e.com', name: '', username: '', role: 'ADMIN' },
|
||||
expiresAt: 0,
|
||||
};
|
||||
});
|
||||
|
||||
await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'google-refresh', provider: 'google' });
|
||||
|
||||
await capturedDeps.canAccessAdmin({ id: 'user-1', role: 'ADMIN', tenantId: 'tenant-a' });
|
||||
expect(hasCapability).toHaveBeenCalledWith(
|
||||
{ id: 'user-1', role: 'ADMIN', tenantId: 'tenant-a' },
|
||||
'ACCESS_ADMIN',
|
||||
);
|
||||
});
|
||||
|
||||
it('does not require OPENID_REUSE_TOKENS for the google provider', async () => {
|
||||
isEnabled.mockReturnValue(false);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-google-refresh', provider: 'google' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
});
|
||||
|
||||
it('maps AdminRefreshError thrown by the helper to the documented status and code', async () => {
|
||||
const { AdminRefreshError } = require('@librechat/api');
|
||||
applyGoogleAdminRefresh.mockRejectedValueOnce(
|
||||
new AdminRefreshError('GOOGLE_NOT_CONFIGURED', 503, 'Google admin OAuth is not configured'),
|
||||
);
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-google-refresh', provider: 'google' });
|
||||
|
||||
expect(response.status).toBe(503);
|
||||
expect(response.body).toEqual({
|
||||
error: 'Google admin OAuth is not configured',
|
||||
error_code: 'GOOGLE_NOT_CONFIGURED',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns 500 INTERNAL_ERROR when the helper throws a non-AdminRefreshError', async () => {
|
||||
applyGoogleAdminRefresh.mockRejectedValueOnce(new Error('boom'));
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-google-refresh', provider: 'google' });
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
expect(response.body.error_code).toBe('INTERNAL_ERROR');
|
||||
});
|
||||
|
||||
it('rejects unknown provider values with INVALID_PROVIDER before calling either helper', async () => {
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-refresh', provider: 'github' });
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
expect(response.body.error_code).toBe('INVALID_PROVIDER');
|
||||
expect(applyGoogleAdminRefresh).not.toHaveBeenCalled();
|
||||
expect(applyAdminRefresh).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('re-runs checkBan with the resolved user identity and blocks a banned user', async () => {
|
||||
const middleware = require('~/server/middleware');
|
||||
let banCheckCalls = 0;
|
||||
middleware.checkBan.mockImplementation((req, res, next) => {
|
||||
banCheckCalls++;
|
||||
if (banCheckCalls >= 2 && req.user) {
|
||||
req.banned = true;
|
||||
return res.status(403).json({ message: 'banned' });
|
||||
}
|
||||
return next();
|
||||
});
|
||||
|
||||
const response = await request(app)
|
||||
.post('/api/admin/oauth/refresh')
|
||||
.send({ refresh_token: 'incoming-google-refresh', provider: 'google' });
|
||||
|
||||
expect(response.status).toBe(403);
|
||||
expect(middleware.checkBan).toHaveBeenCalledTimes(2);
|
||||
expect(middleware.checkBan.mock.calls[1][0].user).toEqual({ id: 'user-id' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin auth OpenID route availability', () => {
|
||||
let app;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
middleware.checkBan.mockImplementation((req, res, next) => next());
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin', adminAuthRouter);
|
||||
});
|
||||
|
||||
it('returns not configured for the OpenID availability check when config lookup throws', async () => {
|
||||
getOpenIdConfig.mockImplementation(() => {
|
||||
throw new Error('OpenID client is not initialized. Please call setupOpenId first.');
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/admin/oauth/openid/check');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: 'OpenID configuration not found',
|
||||
error_code: 'OPENID_NOT_CONFIGURED',
|
||||
});
|
||||
});
|
||||
|
||||
it('does not start OpenID admin login when config lookup throws', async () => {
|
||||
getOpenIdConfig.mockImplementation(() => {
|
||||
throw new Error('OpenID client is not initialized. Please call setupOpenId first.');
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/admin/oauth/openid');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: 'OpenID configuration not found',
|
||||
error_code: 'OPENID_NOT_CONFIGURED',
|
||||
});
|
||||
expect(storeAndStripChallenge).not.toHaveBeenCalled();
|
||||
expect(passport.authenticate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not run OpenID admin callback auth when config lookup throws', async () => {
|
||||
getOpenIdConfig.mockImplementation(() => {
|
||||
throw new Error('OpenID client is not initialized. Please call setupOpenId first.');
|
||||
});
|
||||
|
||||
const response = await request(app).get('/api/admin/oauth/openid/callback?state=state');
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: 'OpenID configuration not found',
|
||||
error_code: 'OPENID_NOT_CONFIGURED',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin auth social route availability', () => {
|
||||
let app;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
passport._strategy.mockReturnValue(undefined);
|
||||
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api/admin', adminAuthRouter);
|
||||
});
|
||||
|
||||
const startRoutes = [
|
||||
['saml', 'SAML'],
|
||||
['google', 'Google'],
|
||||
['github', 'GitHub'],
|
||||
['discord', 'Discord'],
|
||||
['facebook', 'Facebook'],
|
||||
['apple', 'Apple'],
|
||||
];
|
||||
|
||||
it.each(startRoutes)(
|
||||
'does not start %s admin login when the strategy is not registered',
|
||||
async (path, provider) => {
|
||||
const response = await request(app).get(`/api/admin/oauth/${path}`);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: `${provider} configuration not found`,
|
||||
error_code: `${provider.toUpperCase()}_NOT_CONFIGURED`,
|
||||
});
|
||||
expect(storeAndStripChallenge).not.toHaveBeenCalled();
|
||||
expect(passport.authenticate).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
const callbackRoutes = [
|
||||
[
|
||||
'saml',
|
||||
'SAML',
|
||||
(agent) => agent.post('/api/admin/oauth/saml/callback').send({ RelayState: 'state' }),
|
||||
],
|
||||
['google', 'Google', (agent) => agent.get('/api/admin/oauth/google/callback?state=state')],
|
||||
['github', 'GitHub', (agent) => agent.get('/api/admin/oauth/github/callback?state=state')],
|
||||
['discord', 'Discord', (agent) => agent.get('/api/admin/oauth/discord/callback?state=state')],
|
||||
[
|
||||
'facebook',
|
||||
'Facebook',
|
||||
(agent) => agent.get('/api/admin/oauth/facebook/callback?state=state'),
|
||||
],
|
||||
[
|
||||
'apple',
|
||||
'Apple',
|
||||
(agent) => agent.post('/api/admin/oauth/apple/callback').send({ state: 'state' }),
|
||||
],
|
||||
];
|
||||
|
||||
it.each(callbackRoutes)(
|
||||
'does not run %s admin callback auth when the strategy is not registered',
|
||||
async (path, provider, makeRequest) => {
|
||||
const response = await makeRequest(request(app));
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
expect(response.body).toEqual({
|
||||
error: `${provider} configuration not found`,
|
||||
error_code: `${provider.toUpperCase()}_NOT_CONFIGURED`,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('starts admin login when the strategy is registered', async () => {
|
||||
passport._strategy.mockReturnValue({ name: 'googleAdmin' });
|
||||
storeAndStripChallenge.mockResolvedValue(true);
|
||||
|
||||
await request(app).get('/api/admin/oauth/google');
|
||||
|
||||
expect(storeAndStripChallenge).toHaveBeenCalledTimes(1);
|
||||
expect(passport.authenticate).toHaveBeenCalledWith(
|
||||
'googleAdmin',
|
||||
expect.objectContaining({ session: false }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('admin local login route', () => {
|
||||
let app;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue