🤯 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): stop denying resources that nobody owns (#18525)
LiJiane52dc85cfd29
diff --git a/packages/openapi/src/common/base.service.test.ts b/packages/openapi/src/common/base.service.test.tsindex c87f9e1b406..2bd1246e1ff 100644--- a/packages/openapi/src/common/base.service.test.ts+++ b/packages/openapi/src/common/base.service.test.ts@@ -215,3 +215,104 @@ describe('BaseService workspace helpers', () => {expect(findFirst).toHaveBeenCalledTimes(1);});});++/**+ * `getResourceBelongTo` answers `undefined` for two unrelated things — a row+ * that does not exist, and a row nobody owns. Collapsing them into "belongs to+ * someone else" made `POST /api/v1/chat` return 403 for every account that+ * held `ai_model:invoke:owner`, which is what personal accounts are given:+ * built-in models have no owner, so the ownership question had no true answer+ * and the absent answer was read as a denial.+ */+describe('BaseService.resolveOperationPermission ownership resolution', () => {+ const modelService = (owner: string | null | undefined) =>+ new TestService(+ {+ query: {+ aiModels: {+ findFirst: vi+ .fn()+ .mockResolvedValue(+ owner ? { userId: owner } : owner === null ? { userId: null } : undefined,+ ),+ },+ },+ } as unknown as LobeChatDatabase,+ 'user-1',+ );++ beforeEach(() => {+ vi.clearAllMocks();+ mockBuildWorkspaceWhere.mockReturnValue('workspace-where');+ // Distinguishable codes, so the grant below keys off WHICH scope was asked+ // for rather than the order the two checks happen to run in.+ mockGetScopePermissions.mockImplementation((key: string, scopes: string[]) => [+ `${key}:${scopes[0].toLowerCase()}`,+ ]);+ });++ const grants = ({ all = false, owner = false }) =>+ mockHasAnyPermission.mockImplementation(async (codes: string[]) =>+ codes.some((code) => (code.endsWith(':all') ? all : owner)),+ );++ it('lets an owner-scoped grant invoke a model nobody owns', async () => {+ grants({ owner: true });++ await expect(+ modelService(null).operationPermission('ai_model:invoke' as any, {+ targetModelId: 'builtin-model',+ }),+ ).resolves.toMatchObject({ condition: { userId: 'user-1' }, isPermitted: true });+ });++ it('pins the returned condition to the caller when no owner was resolved', async () => {+ grants({ owner: true });++ const result = await modelService(undefined).operationPermission('ai_model:invoke' as any, {+ targetModelId: 'missing-model',+ });++ // The condition scopes the follow-up query. An unresolved owner must never+ // widen it to "no filter" — that would hand back every user's rows.+ expect(result.condition).toEqual({ userId: 'user-1' });+ });++ it('still refuses a resource owned by somebody else', async () => {+ grants({ owner: true });++ await expect(+ modelService('user-2').operationPermission('ai_model:invoke' as any, {+ targetModelId: 'their-model',+ }),+ ).resolves.toMatchObject({ isPermitted: false });+ });++ it('still refuses an ALL-scope request without ALL permission', async () => {+ grants({ owner: true });++ await expect(+ modelService(null).operationPermission('ai_model:invoke' as any, 'all' as any),+ ).resolves.toMatchObject({ isPermitted: false });+ });++ it('refuses when the caller holds neither ALL nor OWNER', async () => {+ grants({});++ await expect(+ modelService(null).operationPermission('ai_model:invoke' as any, {+ targetModelId: 'builtin-model',+ }),+ ).resolves.toMatchObject({ isPermitted: false });+ });++ it('leaves the ALL-permission path untouched', async () => {+ grants({ all: true });++ await expect(+ modelService('user-2').operationPermission('ai_model:invoke' as any, {+ targetModelId: 'their-model',+ }),+ ).resolves.toMatchObject({ condition: { userId: 'user-2' }, isPermitted: true });+ });+});diff --git a/packages/openapi/src/common/base.service.ts b/packages/openapi/src/common/base.service.tsindex d832a5610e1..724084cc9e3 100644--- a/packages/openapi/src/common/base.service.ts+++ b/packages/openapi/src/common/base.service.ts@@ -431,16 +431,11 @@ export abstract class BaseService implements IBaseService {}/**- * When the user does not have ALL permission, the following scenarios are not allowed:- * 1. Querying all data- * 2. Querying a specific user's data, but the target resource does not belong to the current user+ * Asking for everyone's data. Without ALL permission there is nothing to+ * fall back to — an owner-scoped grant cannot answer an unscoped question.*/- if (!resourceBelongTo || resourceBelongTo !== this.userId) {- this.log(- 'warn',- 'Permission denied: current user has no ALL permission, or target resource does not belong to current user',- logContext,- );+ if (resourceInfo === ALL_SCOPE) {+ this.log('warn', 'Permission denied: ALL-scope request without ALL permission', logContext);return {isPermitted: false,message: `no permission,current user has no ALL permission,and resource not belong to current user`,@@ -448,37 +443,49 @@ export abstract class BaseService implements IBaseService {}/**- * When the target resource belongs to the current user, any permission allows the operation- * Since ALL permission was already checked above, only owner permission needs to be checked here+ * A named resource owned by somebody else. Owner permission is irrelevant+ * here — it grants access to your own rows, never to theirs.*/- if (resourceBelongTo === this.userId) {- // Check if the user has owner permission for the corresponding action- const hasOwnerAccess = await this.hasOwnerPermission(permissionKey);+ if (resourceBelongTo && resourceBelongTo !== this.userId) {+ this.log('warn', 'Permission denied: target resource belongs to another user', logContext);+ return {+ isPermitted: false,+ message: `no permission,current user has no ALL permission,and resource not belong to current user`,+ };+ }- if (hasOwnerAccess) {- this.log('info', 'Permission granted: current user has owner permission', logContext);- return {- condition: { userId: resourceBelongTo },- isPermitted: true,- };- }+ /**+ * Either the resource is the caller's, or no owner could be resolved for+ * it. Denying the second case alongside the one above is what made every+ * `POST /api/v1/chat` answer 403.+ *+ * `getResourceBelongTo` returns `undefined` for two unrelated situations:+ * a row that does not exist, and a row that has no per-user owner at all.+ * Built-in models are the latter — nobody owns them — so "does this model+ * belong to you" has no true answer, and treating the absent answer as+ * "it belongs to someone else" denied every caller holding+ * `ai_model:invoke:owner`, which is exactly what personal accounts get.+ *+ * The owner check below is still the gate, and the returned condition is+ * pinned to the caller either way, so an unowned resource cannot widen a+ * query past the caller's own rows. A row that genuinely does not exist+ * now reaches the service and surfaces as "not found" rather than as a+ * permission error — also the truthful answer.+ */+ const hasOwnerAccess = await this.hasOwnerPermission(permissionKey);- this.log(- 'warn',- 'Permission denied: target resource belongs to current user, but user has no owner permission for this operation',- logContext,- );+ if (hasOwnerAccess) {+ this.log('info', 'Permission granted: current user has owner permission', logContext);return {- isPermitted: false,- message: `no permission,resource belong to current user,but current user has no any ${permissionKey} permission`,+ condition: { userId: this.userId },+ isPermitted: true,};}- // If we reach here, apply fallback logic- this.log('info', `Fallback: no permission`, logContext);+ this.log('warn', 'Permission denied: no owner permission for this operation', logContext);return {isPermitted: false,- message: `permission validation error for: ${permissionKey}`,+ message: `no permission,resource belong to current user,but current user has no any ${permissionKey} permission`,};}diff --git a/packages/openapi/src/services/chat.service.test.ts b/packages/openapi/src/services/chat.service.test.tsindex d15e9556279..fc15ecea72b 100644--- a/packages/openapi/src/services/chat.service.test.ts+++ b/packages/openapi/src/services/chat.service.test.ts@@ -33,6 +33,21 @@ vi.mock('@/database/schemas', () => ({topics: {},}));vi.mock('@/utils/rbac', () => ({ getScopePermissions: () => [] }));+// Values a caller could not have supplied by accident, so the assertions below+// prove the service reads these constants rather than literals of its own.+//+// Mocked on `@lobechat/business-const`, which is where they are declared —+// mocking them onto `@/const/settings` instead made these tests pass while the+// build failed on `Export DEFAULT_PROVIDER doesn't exist in target module`:+// that barrel re-exports `DEFAULT_MODEL` only, and a factory mock happily+// invents any key asked of it.+const DEFAULT_MODEL = 'default-model-from-const';+const DEFAULT_PROVIDER = 'default-provider-from-const';++vi.mock('@lobechat/business-const', () => ({+ DEFAULT_MODEL: 'default-model-from-const',+ DEFAULT_PROVIDER: 'default-provider-from-const',+}));vi.mock('@/const/settings', () => ({DEFAULT_AGENT_CHAT_CONFIG: {},DEFAULT_SYSTEM_AGENT_CONFIG: {},@@ -98,3 +113,85 @@ describe('ChatService payload construction', () => {expect(chatMock.mock.calls[0][0]).toMatchObject({ temperature: 0.7 });});});++/**+ * A provider row whose `keyVaults` is null is the ordinary shape for a+ * deployment that supplies credentials through the environment: the row exists+ * so the provider can be enabled, and no per-user vault is ever written.+ *+ * `decrypt` splits its argument on `:` in its first statement, so handing that+ * null straight to it — which a `!` assertion used to allow — threw+ * `Cannot read properties of null (reading 'split')` out of every+ * `/api/v1/chat*` call, from inside a helper whose name gives no hint that a+ * credential lookup is what failed.+ */+/**+ * A request that names no model used to ask for `gpt-3.5-turbo` on `openai`,+ * hard-coded here and unreachable by any caller — `ChatServiceConfig` only+ * arrives through the constructor and the controller never passes one. On a+ * deployment that does not run OpenAI, that surfaced as a credential error+ * naming a provider the caller had never mentioned.+ */+describe('ChatService default model', () => {+ // `chatMock` accumulates across describes; without this the assertions below+ // read the first call of the whole file, which belongs to another test.+ beforeEach(() => vi.clearAllMocks());++ it('falls back to the product defaults, not to this service’s own literals', async () => {+ const service = new ChatService({} as LobeChatDatabase, 'user-1');+ (service as any).resolveOperationPermission = vi.fn().mockResolvedValue({ isPermitted: true });+ (service as any).getApiKey = vi.fn().mockResolvedValue(JSON.stringify({ apiKey: 'k' }));++ chatMock.mockResolvedValue(+ new Response(JSON.stringify({ choices: [{ message: { content: 'hi' } }] }), {+ headers: { 'content-type': 'application/json' },+ }),+ );+ initModelRuntimeWithUserPayloadMock.mockResolvedValue({ chat: chatMock });++ const result = await service.chat({ messages: [{ content: 'hi', role: 'user' }] } as any);++ expect(chatMock.mock.calls[0][0]).toMatchObject({ model: DEFAULT_MODEL });+ expect(initModelRuntimeWithUserPayloadMock.mock.calls[0][0]).toBe(DEFAULT_PROVIDER);+ expect(result).toMatchObject({ model: DEFAULT_MODEL, provider: DEFAULT_PROVIDER });+ });+});++describe('ChatService.getApiKey provider credentials', () => {+ const decrypt = vi.fn();++ const serviceWith = (rows: unknown[]) => {+ const service = new ChatService(+ { query: { aiProviders: { findMany: vi.fn().mockResolvedValue(rows) } } } as any,+ 'user-1',+ );+ (service as any).buildWorkspaceWhere = vi.fn();+ return service;+ };++ const apiKey = (service: ChatService) => (service as any).getApiKey('openai');++ beforeEach(async () => {+ vi.clearAllMocks();+ decrypt.mockResolvedValue({ plaintext: '{"apiKey":"from-vault"}' });+ const { KeyVaultsGateKeeper } = await import('@/server/modules/KeyVaultsEncrypt');+ (KeyVaultsGateKeeper.initWithEnvKey as any).mockResolvedValue({ decrypt });+ });++ it('falls back to an empty vault when the row stores no key', async () => {+ await expect(apiKey(serviceWith([{ id: 'openai', keyVaults: null }]))).resolves.toBe('{}');+ expect(decrypt).not.toHaveBeenCalled();+ });++ it('falls back to an empty vault when no row exists', async () => {+ await expect(apiKey(serviceWith([]))).resolves.toBe('{}');+ expect(decrypt).not.toHaveBeenCalled();+ });++ it('still decrypts a row that does store a key', async () => {+ await expect(apiKey(serviceWith([{ id: 'openai', keyVaults: 'iv:tag:data' }]))).resolves.toBe(+ '{"apiKey":"from-vault"}',+ );+ expect(decrypt).toHaveBeenCalledWith('iv:tag:data');+ });+});diff --git a/packages/openapi/src/services/chat.service.ts b/packages/openapi/src/services/chat.service.tsindex f10803459f3..75a068f11ff 100644--- a/packages/openapi/src/services/chat.service.ts+++ b/packages/openapi/src/services/chat.service.ts@@ -1,3 +1,4 @@+import { DEFAULT_MODEL, DEFAULT_PROVIDER } from '@lobechat/business-const';import type { ChatStreamPayload } from '@lobechat/model-runtime';import { mergeModelRuntimeHooks } from '@lobechat/model-runtime';import type { LobeAgentChatConfig, LobeAgentConfig, UserSystemAgentConfig } from '@lobechat/types';@@ -42,8 +43,24 @@ export class ChatService extends BaseService {super(db, userId, workspaceId);this.config = {- defaultModel: 'gpt-3.5-turbo',- defaultProvider: 'openai',+ /**+ * The product's own defaults, not literals of this file's own.+ *+ * These were `gpt-3.5-turbo` / `openai`, which no caller could change:+ * `ChatServiceConfig` is only reachable through the constructor and the+ * controller never passes one, so a request that named no model always+ * asked for OpenAI. Any deployment that does not run OpenAI — including+ * the default one, whose `DEFAULT_PROVIDER` is `deepseek` — answered+ * such a request with a credential error naming a provider the caller+ * never mentioned.+ *+ * `DEFAULT_MODEL` / `DEFAULT_PROVIDER` are what `DEFAULT_AGENT_CONFIG`+ * and the rest of the product already resolve to, so `/api/v1/chat`+ * without a model now behaves like the rest of the product instead of+ * disagreeing with it.+ */+ defaultModel: DEFAULT_MODEL,+ defaultProvider: DEFAULT_PROVIDER,timeout: 30_000,...serviceConfig,};@@ -186,8 +203,28 @@ export class ChatService extends BaseService {where: and(eq(aiProviders.id, provider), this.buildWorkspaceWhere(aiProviders)),});- if (!aiProviderConfigs || aiProviderConfigs.length === 0) {+ const providerConfig = aiProviderConfigs?.[0];++ /**+ * No row, or a row that stores no key of its own.+ *+ * The second case is the ordinary one for a deployment whose provider+ * credentials come from the environment rather than from per-user vaults:+ * the row exists so the provider can be enabled and ordered in the UI,+ * and `keyVaults` stays null. `decrypt` splits its argument on `:` as its+ * very first statement, so passing that null through — which the `!` below+ * used to assert away — threw `Cannot read properties of null (reading+ * 'split')` out of every `/api/v1/chat*` call, from inside a helper whose+ * name gives no hint that a credential lookup is what failed.+ *+ * Both cases mean the same thing to the caller: this provider has no+ * user-supplied key, so hand back an empty vault and let the model runtime+ * fall back to the environment, exactly as it already did when no row+ * existed at all.+ */+ if (!providerConfig?.keyVaults) {this.log('info', '未找到有效的AI Provider配置,使用兜底环境变量配置', {+ hasRow: !!providerConfig,provider,userId: this.userId,});@@ -195,8 +232,7 @@ export class ChatService extends BaseService {return '{}';}- const providerConfig = aiProviderConfigs[0];- const { plaintext } = await gateKeeper.decrypt(providerConfig.keyVaults!);+ const { plaintext } = await gateKeeper.decrypt(providerConfig.keyVaults);return plaintext;}@@ -448,17 +484,13 @@ export class ChatService extends BaseService {targetModelId: finalModel,});+ // Only `translate` carried a second, target-less retry here. It existed to+ // work around the gate treating an unowned model as somebody else's, which+ // `resolveOperationPermission` now distinguishes — so the retry can never+ // change the outcome, and keeping it would suggest the two sibling+ // endpoints in this file were simply missing it.if (!modelScopedPermission.isPermitted) {- const fallbackPermission = await this.resolveOperationPermission('AI_MODEL_INVOKE');- if (!fallbackPermission.isPermitted) {- throw this.createAuthorizationError(modelScopedPermission.message || '无权限操作');- }-- this.log('warn', '模型级权限校验失败,已回退到通用模型调用权限校验', {- model: finalModel,- provider: finalProvider,- userId: this.userId,- });+ throw this.createAuthorizationError(modelScopedPermission.message || '无权限操作');}this.log('info', '开始翻译文本', {diff --git a/packages/openapi/src/types/chat.type.ts b/packages/openapi/src/types/chat.type.tsindex 00d9065cfe2..93d7002bfe2 100644--- a/packages/openapi/src/types/chat.type.ts+++ b/packages/openapi/src/types/chat.type.ts@@ -137,7 +137,15 @@ export const MessageGenerationParamsSchema = z.object({// ==================== Configuration Types ====================/**- * Supported AI providers+ * A hand-written sample of provider ids, kept only because it is exported.+ *+ * It is not the set of providers this service accepts and never was: the+ * request field beside it is `provider?: string`, validated as+ * `z.string().max(64)`, and the runtime resolves whatever id arrives against+ * the `ai_providers` table — including custom providers, which by definition+ * cannot appear in any list written here.+ *+ * @deprecated Provider ids are open. Use `string`.*/export type AIProvider = 'openai' | 'anthropic' | 'google' | 'groq' | 'vertexai';@@ -146,6 +154,15 @@ export type AIProvider = 'openai' | 'anthropic' | 'google' | 'groq' | 'vertexai'*/export interface ChatServiceConfig {defaultModel?: string;- defaultProvider?: AIProvider;+ /**+ * Deliberately `string`, matching `ChatServiceParams['provider']`.+ *+ * Typing this as {@link AIProvider} said a request may name any provider+ * while the default may only be one of five built-ins — a distinction with+ * nothing behind it, since both end up in the same lookup. It also made+ * `DEFAULT_PROVIDER` unassignable: the product's own default is `deepseek`,+ * which that list never included.+ */+ defaultProvider?: string;timeout?: number;}