π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(openapi): keep /users/me reachable by restricted API keys (#18063)
Rdmclin2b0fbd5f185cd
diff --git a/packages/openapi/src/controllers/user.controller.test.ts b/packages/openapi/src/controllers/user.controller.test.tsnew file mode 100644index 00000000000..c67f8bfc939--- /dev/null+++ b/packages/openapi/src/controllers/user.controller.test.ts@@ -0,0 +1,122 @@+import type { Context } from 'hono';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const getCurrentUser = vi.hoisted(() => vi.fn());++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn().mockResolvedValue({}) }));+vi.mock('@/database/models/rbac', () => ({ RbacModel: class {} }));+vi.mock('../services', () => ({+ UserService: class {+ getCurrentUser = getCurrentUser;+ },+}));++const { UserController } = await import('./user.controller');++/**+ * `/me` is open to any authenticated caller so a key can resolve its own+ * identity (LOBE-12934), which makes `messageCount` the one field on it that+ * still needs gating β it is chat-usage metadata, not identity.+ */+describe('UserController.getCurrentUser', () => {+ const contextFor = (auth: { authType?: string; scopes?: string[] | null }, query = '') => {+ const values: Record<string, unknown> = {+ apiKeyScopes: auth.scopes,+ authType: auth.authType,+ userId: 'user-1',+ };++ return {+ get: (key: string) => values[key],+ json: (body: unknown) => new Response(JSON.stringify(body)),+ req: { query: (key: string) => new URLSearchParams(query).get(key) ?? undefined },+ } as unknown as Context;+ };++ const FULL_PROFILE = {+ email: '[email protected]',+ fullName: 'Someone',+ id: 'user-1',+ messageCount: 42,+ phone: '+100000000',+ preference: { language: 'zh-CN' },+ roles: [{ id: 'role-1', name: 'admin' }],+ };++ const bodyOf = async (res: Response) => (await res.json()).data;++ beforeEach(() => {+ getCurrentUser.mockReset();+ getCurrentUser.mockResolvedValue(FULL_PROFILE);+ });++ describe('profile projection', () => {+ it('narrows the response to the id for a key without user:read', async () => {+ const res = await new UserController().getCurrentUser(+ contextFor({ authType: 'apikey', scopes: ['model:invoke'] }),+ );++ await expect(bodyOf(res)).resolves.toEqual({ id: 'user-1' });+ });++ it('returns the full profile to a key holding user:read', async () => {+ const res = await new UserController().getCurrentUser(+ contextFor({ authType: 'apikey', scopes: ['user:read'] }),+ );++ await expect(bodyOf(res)).resolves.toMatchObject({+ email: FULL_PROFILE.email,+ roles: FULL_PROFILE.roles,+ });+ });++ it('returns the full profile to full-access keys and session callers', async () => {+ for (const auth of [+ { authType: 'apikey', scopes: ['*'] },+ { authType: 'apikey', scopes: null },+ { authType: 'oidc' },+ ]) {+ const res = await new UserController().getCurrentUser(contextFor(auth));++ await expect(bodyOf(res)).resolves.toMatchObject({ email: FULL_PROFILE.email });+ }+ });+ });++ it('withholds the count from a restricted key without chat:read, without failing', async () => {+ const res = await new UserController().getCurrentUser(+ contextFor({+ authType: 'apikey',+ scopes: ['agent:read'],+ }),+ );++ expect(res.status).toBe(200);+ expect(getCurrentUser).toHaveBeenCalledWith(false);+ });++ it('returns the count to a restricted key holding chat:read', async () => {+ await new UserController().getCurrentUser(+ contextFor({ authType: 'apikey', scopes: ['chat:read'] }),+ );++ expect(getCurrentUser).toHaveBeenCalledWith(true);+ });++ it('returns the count to full-access keys and session callers', async () => {+ await new UserController().getCurrentUser(contextFor({ authType: 'apikey', scopes: ['*'] }));+ expect(getCurrentUser).toHaveBeenLastCalledWith(true);++ await new UserController().getCurrentUser(contextFor({ authType: 'apikey', scopes: null }));+ expect(getCurrentUser).toHaveBeenLastCalledWith(true);++ await new UserController().getCurrentUser(contextFor({ authType: 'oidc' }));+ expect(getCurrentUser).toHaveBeenLastCalledWith(true);+ });++ it('still honours an explicit includeCount=0 for permitted callers', async () => {+ await new UserController().getCurrentUser(contextFor({ authType: 'oidc' }, 'includeCount=0'));++ expect(getCurrentUser).toHaveBeenCalledWith(false);+ });+});diff --git a/packages/openapi/src/controllers/user.controller.ts b/packages/openapi/src/controllers/user.controller.tsindex 6a8bc240014..499b715e03d 100644--- a/packages/openapi/src/controllers/user.controller.ts+++ b/packages/openapi/src/controllers/user.controller.ts@@ -1,5 +1,7 @@import type { Context } from 'hono';+import { type ApiKeyScope, hasApiKeyScope, isFullAccessApiKey } from '@/const/apiKeyScope';+import { BaseController } from '../common/base.controller';import { UserService } from '../services';import type {@@ -14,22 +16,44 @@ import type {* Handles user-related HTTP requests and responses*/export class UserController extends BaseController {+ /** Session / OIDC callers and full-access keys hold every scope implicitly. */+ private callerHasScope(c: Context, scope: ApiKeyScope): boolean {+ if (c.get('authType') !== 'apikey') return true;++ const scopes = c.get('apiKeyScopes') as string[] | null | undefined;+ return isFullAccessApiKey(scopes) || hasApiKeyScope(scopes, scope);+ }+/**- * Retrieves the currently logged-in user's information- * @param c Hono Context- * @returns User public information response+ * `/me` is reachable by every authenticated caller so a key can resolve its+ * own identity β `lh login` depends on it (LOBE-12934). What it *returns*+ * is still scoped, because identity bootstrap needs an id, not a profile:+ *+ * - without `user:read` the response is narrowed to the id, keeping the+ * caller's email, phone, preferences and role names out of a key that was+ * only granted, say, `model:invoke`+ * - `messageCount` is chat-usage metadata and additionally needs `chat:read`+ *+ * Narrowed rather than rejected throughout: `includeCount` defaults to true,+ * so answering with 403 would make identity resolution depend on a query+ * parameter β the exact trap this endpoint just came out of.*/async getCurrentUser(c: Context): Promise<Response> {try {const includeCountQuery = c.req.query('includeCount');- const includeCount = includeCountQuery !== '0' && includeCountQuery !== 'false';+ const countRequested = includeCountQuery !== '0' && includeCountQuery !== 'false';+ const includeCount = countRequested && this.callerHasScope(c, 'chat:read');// Get database connection and create service instanceconst db = await this.getDatabase();const userService = new UserService(db, this.getUserId(c), this.getWorkspaceId(c));const userInfo = await userService.getCurrentUser(includeCount);- return this.success(c, userInfo, 'User info retrieved successfully');+ return this.success(+ c,+ this.callerHasScope(c, 'user:read') ? userInfo : { id: userInfo?.id },+ 'User info retrieved successfully',+ );} catch (error) {return this.handleError(c, error);}diff --git a/packages/openapi/src/routes/users.route.test.ts b/packages/openapi/src/routes/users.route.test.tsnew file mode 100644index 00000000000..15aa314cd38--- /dev/null+++ b/packages/openapi/src/routes/users.route.test.ts@@ -0,0 +1,54 @@+import { Hono } from 'hono';+import { describe, expect, it, vi } from 'vitest';++// the route module pulls in the db graph (via `requirePermission`) and the+// better-auth graph (via `requireAuth`) at import time; this test is only+// about which gates the route itself declares+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/rbac', () => ({ RbacModel: class {} }));+vi.mock('../middleware/auth', () => ({+ requireAuth: async (_c: any, next: any) => next(),+}));+vi.mock('../controllers', () => ({+ UserController: class {+ getCurrentUser(c: any) {+ return c.json({ data: { id: 'user-1' }, success: true });+ }+ },+}));++const { default: UserRoutes } = await import('./users.route');++/**+ * A key minted with narrow scopes still has to be able to identify itself, or+ * `lh login` cannot resolve a userId from it. Guarding this route on+ * `user:read` stranded such keys outside the product β see LOBE-12934.+ */+describe('GET /users/me', () => {+ const requestAs = (apiKeyScopes: string[]) => {+ const app = new Hono();++ app.use('*', async (c, next) => {+ c.set('userId' as never, 'user-1' as never);+ c.set('authType' as never, 'apikey' as never);+ c.set('apiKeyScopes' as never, apiKeyScopes as never);+ await next();+ });+ app.route('/', UserRoutes);++ return app.request('/me');+ };++ it('is reachable by a restricted API key that holds no user scope', async () => {+ const res = await requestAs(['agent:read']);++ expect(res.status).toBe(200);+ await expect(res.json()).resolves.toMatchObject({ data: { id: 'user-1' } });+ });++ it('is reachable by a key holding unrelated scopes only', async () => {+ const res = await requestAs(['model:invoke']);++ expect(res.status).toBe(200);+ });+});diff --git a/packages/openapi/src/routes/users.route.ts b/packages/openapi/src/routes/users.route.tsindex 82338d8a4b5..794970b2003 100644--- a/packages/openapi/src/routes/users.route.ts+++ b/packages/openapi/src/routes/users.route.ts@@ -6,7 +6,7 @@ import { getAllScopePermissions, getScopePermissions } from '@/utils/rbac';import { zValidator } from '../common/validator';import { UserController } from '../controllers';import { requireAuth } from '../middleware/auth';-import { requireAnyPermission, requireApiKeyScope } from '../middleware/permission-check';+import { requireAnyPermission } from '../middleware/permission-check';import {CreateUserRequestSchema,UpdateUserRequestSchema,@@ -26,8 +26,17 @@ UserRoutes.get('/me',describeRoute({ summary: 'Get current authenticated user', tags: ['users'] }),requireAuth,- // no RBAC permission, but restricted API keys still need the user domain- requireApiKeyScope('user:read'),+ // Deliberately reachable by every authenticated caller, including restricted+ // API keys holding no `user:read` β please do not add a scope gate here.+ // This is how `lh login` resolves a userId from a freshly minted key+ // (`apps/cli/src/auth/apiKey.ts`); gating the route strands the holder of a+ // valid key outside the product with a scope error, same reason GitHub keeps+ // `/user` open to any token.+ //+ // Reachability is not disclosure: the payload is scoped inside+ // `UserController.getCurrentUser` β a key without `user:read` receives only+ // `{ id }`, and `messageCount` additionally needs `chat:read`. Widen there,+ // under a scope check, rather than by gating the route. See LOBE-12934.async (c) => {const userController = new UserController();return await userController.getCurrentUser(c);diff --git a/packages/openapi/vitest.config.mts b/packages/openapi/vitest.config.mtsindex 7f44f70f149..7e32a721d33 100644--- a/packages/openapi/vitest.config.mts+++ b/packages/openapi/vitest.config.mts@@ -8,6 +8,7 @@ export default defineConfig({// mirror the root tsconfig paths: package sources first, app src as fallback'@/const/': resolve(__dirname, '../const/src') + '/','@/database/': resolve(__dirname, '../database/src') + '/',+ '@/envs/': resolve(__dirname, '../env/src') + '/','@/': resolve(__dirname, '../../src') + '/',},},