Skip to content

🀯 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.

πŸ› fix(knowledge-base): let agents read No-access KBs a browser mounted (#22956)

Rdmclin21f2060db5e84
diff --git a/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts
index 35d0711e21e..a0d7748991c 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/knowledgeContentAccess.integration.test.ts
@@ -746,4 +746,75 @@ describe('knowledge content read boundaries', () => {
(await contents(owner, ['docs_content_workspace'], 'content-workspace'))[0].content,
).toBe('restricted text');
});
+
+ it('lets an agent read a No-access knowledge base a browser mounted, never a self-mount', async () => {
+ const workspaceId = 'content-workspace';
+ await db
+ .insert(schema.workspaceMembers)
+ .values([owner, viewer].map((userId) => ({ userId, workspaceId })));
+ await db.insert(schema.agents).values(
+ ['agt_content_mounted', 'agt_content_self_mounted', 'agt_content_unmounted'].map((id) => ({
+ id,
+ userId: id === 'agt_content_self_mounted' ? viewer : owner,
+ workspaceId,
+ })),
+ );
+ await db.insert(schema.agentsKnowledgeBases).values(
+ [
+ // Mounted by the knowledge base's creator, who may browse it.
+ { agentId: 'agt_content_mounted', userId: owner },
+ // Mounted by the No-access member on their own agent.
+ { agentId: 'agt_content_self_mounted', userId: viewer },
+ ].map((mount) => ({ ...mount, knowledgeBaseId: 'content-kb-workspace', workspaceId })),
+ );
+ await db
+ .insert(schema.projects)
+ .values({ id: 'project_content', name: 'Project', userId: owner, workspaceId });
+ await db.insert(schema.projectKnowledgeBases).values({
+ addedByUserId: owner,
+ knowledgeBaseId: 'content-kb-workspace',
+ projectId: 'project_content',
+ workspaceId,
+ });
+
+ const readAs = async (scope: { agentId?: string; projectId?: string }) => {
+ const runtime = (await knowledgeBaseRuntime.factory({
+ ...scope,
+ serverDB: db,
+ userId: viewer,
+ workspaceId,
+ } as any)) as any;
+ return runtime.readKnowledge({
+ fileIds: ['file_content_workspace', 'docs_content_workspace'],
+ });
+ };
+
+ for (const scope of [{ agentId: 'agt_content_mounted' }, { projectId: 'project_content' }]) {
+ const read = await readAs(scope);
+ expect(read.success).toBe(true);
+ expect(read.content).toContain('restricted text');
+ }
+
+ for (const agentId of ['agt_content_self_mounted', 'agt_content_unmounted']) {
+ const read = await readAs({ agentId });
+ expect(read.success).toBe(false);
+ expect(read.content).toContain('Only knowledge base managers');
+ }
+
+ // A creator who left the workspace no longer vouches for their mount.
+ await db
+ .update(schema.workspaceMembers)
+ .set({ deletedAt: new Date() })
+ .where(eq(schema.workspaceMembers.userId, owner));
+ expect((await readAs({ agentId: 'agt_content_mounted' })).success).toBe(false);
+ await db
+ .update(schema.workspaceMembers)
+ .set({ deletedAt: null })
+ .where(eq(schema.workspaceMembers.userId, owner));
+
+ // The member's own direct read stays manager-only.
+ await expect(contents(viewer, ['file_content_workspace'], workspaceId)).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ });
});
diff --git a/apps/server/src/services/knowledgeBase/index.ts b/apps/server/src/services/knowledgeBase/index.ts
index 1cfece43954..94408eb60d5 100644
--- a/apps/server/src/services/knowledgeBase/index.ts
+++ b/apps/server/src/services/knowledgeBase/index.ts
@@ -22,7 +22,10 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
import { DocumentService } from '@/server/services/document';
import { resolveEnterpriseContentScopes } from '@/server/services/enterpriseKnowledge/contentAccess';
import { createFtsSearchRepo } from '@/server/services/ftsSearch';
-import { assertContentsNotInRestrictedKnowledgeBase } from '@/server/services/knowledgeBaseAccess';
+import {
+ assertContentsNotInRestrictedKnowledgeBase,
+ type UsableKnowledgeBaseResolver,
+} from '@/server/services/knowledgeBaseAccess';
export interface FileContentResult {
content: string;
@@ -232,7 +235,15 @@ export class KnowledgeBaseSearchService {
};
}
- async getFileContents(ids: string[]): Promise<FileContentResult[]> {
+ /**
+ * @param options.resolveUsableKnowledgeBaseIds Only agent tool runtimes pass it, so a
+ * member's "No access" knowledge base stays readable by the agents it is mounted on while
+ * direct reads keep the manager-only rule.
+ */
+ async getFileContents(
+ ids: string[],
+ options: { resolveUsableKnowledgeBaseIds?: UsableKnowledgeBaseResolver } = {},
+ ): Promise<FileContentResult[]> {
await assertContentsNotInRestrictedKnowledgeBase(
{
serverDB: this.serverDB,
@@ -240,6 +251,7 @@ export class KnowledgeBaseSearchService {
workspaceId: this.workspaceId,
},
ids,
+ options,
);
const scopes = await resolveEnterpriseContentScopes(
{ serverDB: this.serverDB, userId: this.askerId, workspaceId: this.workspaceId },
diff --git a/apps/server/src/services/knowledgeBaseAccess/index.ts b/apps/server/src/services/knowledgeBaseAccess/index.ts
index cf0c5a92783..e69e7abb5f2 100644
--- a/apps/server/src/services/knowledgeBaseAccess/index.ts
+++ b/apps/server/src/services/knowledgeBaseAccess/index.ts
@@ -1,12 +1,17 @@
import { TRPCError } from '@trpc/server';
import { and, eq, inArray, isNull, ne, or } from 'drizzle-orm';
+import pMap from 'p-map';
import { ResourcePermissionModel } from '@/database/models/resourcePermission';
import {
+ agentsKnowledgeBases,
documents,
knowledgeBaseFiles,
knowledgeBases,
+ projectKnowledgeBases,
resourcePermissions,
+ tasks,
+ workspaceMembers,
} from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import {
@@ -164,21 +169,144 @@ export const assertFileNotInRestrictedKnowledgeBase = async (
}
};
+/** Picks, from the caller's restricted knowledge base ids, the ones a read may still use. */
+export type UsableKnowledgeBaseResolver = (restrictedIds: string[]) => Promise<string[]>;
+
+/**
+ * Of `knowledgeBaseIds`, the ones mounted on the agent (or on its project,
+ * directly or through the task) by a user who may browse them.
+ *
+ * "No access" keeps a knowledge base usable on the agents it is mounted on, so
+ * an agent may read its full content for a member who cannot browse it. The
+ * mount must come from someone who can browse the knowledge base (its
+ * creator, a curator or a collaborator): a member mounting a knowledge base
+ * they cannot browse on their own agent must not unlock it.
+ */
+export const getKnowledgeBaseIdsMountedByBrowsers = async (
+ ctx: Pick<KnowledgeBaseAccessCtx, 'serverDB' | 'workspaceId'>,
+ scope: { agentId?: string; projectId?: string; taskId?: string },
+ knowledgeBaseIds: string[],
+): Promise<string[]> => {
+ const { serverDB: db, workspaceId } = ctx;
+ if (!workspaceId || knowledgeBaseIds.length === 0) return [];
+
+ let projectId = scope.projectId;
+ if (!projectId && scope.taskId) {
+ const [task] = await db
+ .select({ projectId: tasks.projectId })
+ .from(tasks)
+ .where(and(eq(tasks.id, scope.taskId), eq(tasks.workspaceId, workspaceId)))
+ .limit(1);
+ projectId = task?.projectId ?? undefined;
+ }
+
+ const [agentMounts, projectMounts] = await Promise.all([
+ scope.agentId
+ ? db
+ .select({
+ knowledgeBaseId: agentsKnowledgeBases.knowledgeBaseId,
+ mountedBy: agentsKnowledgeBases.userId,
+ })
+ .from(agentsKnowledgeBases)
+ .where(
+ and(
+ eq(agentsKnowledgeBases.agentId, scope.agentId),
+ eq(agentsKnowledgeBases.workspaceId, workspaceId),
+ eq(agentsKnowledgeBases.enabled, true),
+ inArray(agentsKnowledgeBases.knowledgeBaseId, knowledgeBaseIds),
+ ),
+ )
+ : [],
+ projectId
+ ? db
+ .select({
+ knowledgeBaseId: projectKnowledgeBases.knowledgeBaseId,
+ mountedBy: projectKnowledgeBases.addedByUserId,
+ })
+ .from(projectKnowledgeBases)
+ .where(
+ and(
+ eq(projectKnowledgeBases.projectId, projectId),
+ eq(projectKnowledgeBases.workspaceId, workspaceId),
+ eq(projectKnowledgeBases.enabled, true),
+ inArray(projectKnowledgeBases.knowledgeBaseId, knowledgeBaseIds),
+ ),
+ )
+ : [],
+ ]);
+
+ const mounts = [...agentMounts, ...projectMounts];
+ const mountAuthors = [
+ ...new Set(mounts.flatMap(({ mountedBy }) => (mountedBy ? [mountedBy] : []))),
+ ];
+ if (mountAuthors.length === 0) return [];
+
+ // Only current members vouch for a mount: a removed member keeps their rows
+ // (membership is soft-deleted) and, as a creator, would otherwise still pass
+ // the creator exemption in `getRestrictedKnowledgeBaseIds`.
+ const activeMembers = await db
+ .select({ userId: workspaceMembers.userId })
+ .from(workspaceMembers)
+ .where(
+ and(
+ eq(workspaceMembers.workspaceId, workspaceId),
+ inArray(workspaceMembers.userId, mountAuthors),
+ isNull(workspaceMembers.deletedAt),
+ ),
+ );
+ const mounters = activeMembers.map(({ userId }) => userId);
+ const restrictedByMounter = new Map(
+ await pMap(
+ mounters,
+ async (userId) =>
+ [
+ userId,
+ new Set(await getRestrictedKnowledgeBaseIds({ serverDB: db, userId, workspaceId })),
+ ] as const,
+ { concurrency: 5 },
+ ),
+ );
+
+ return [
+ ...new Set(
+ mounts
+ .filter(
+ ({ knowledgeBaseId, mountedBy }) =>
+ !!mountedBy &&
+ restrictedByMounter.has(mountedBy) &&
+ !restrictedByMounter.get(mountedBy)!.has(knowledgeBaseId),
+ )
+ .map(({ knowledgeBaseId }) => knowledgeBaseId),
+ ),
+ ];
+};
+
/**
* Assert a full-content batch read (`chunk.getFileContents`) does not leak a
* restricted knowledge base's content. Accepts the mixed id list the endpoint
* takes: `file_*` ids resolve through `knowledge_base_files`, `docs_*` ids
* through `documents.knowledge_base_id`. The member-facing "No access" level
- * only promises attached agents continued retrieval (semantic search) β€” full
+ * keeps the knowledge base usable by the agents it is mounted on β€” direct
* document dumps stay manager-only, matching the browse restriction.
+ *
+ * `resolveUsableKnowledgeBaseIds` lets an agent tool read exempt the restricted
+ * knowledge bases mounted on the running agent (see
+ * `getKnowledgeBaseIdsMountedByBrowsers`). It only runs when the caller has
+ * restricted knowledge bases. A file that is also in another restricted
+ * knowledge base stays blocked.
*/
export const assertContentsNotInRestrictedKnowledgeBase = async (
ctx: KnowledgeBaseAccessCtx,
ids: string[],
+ options: { resolveUsableKnowledgeBaseIds?: UsableKnowledgeBaseResolver } = {},
): Promise<void> => {
if (!ctx.workspaceId || ids.length === 0) return;
- const restricted = await getRestrictedKnowledgeBaseIds(ctx);
+ let restricted = await getRestrictedKnowledgeBaseIds(ctx);
+ if (restricted.length > 0 && options.resolveUsableKnowledgeBaseIds) {
+ const usable = new Set(await options.resolveUsableKnowledgeBaseIds(restricted));
+ restricted = restricted.filter((id) => !usable.has(id));
+ }
if (restricted.length === 0) return;
const documentIds = ids.filter((id) => id.startsWith('docs_'));
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
index ae5b13c8c29..86961607354 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts
@@ -10,6 +10,7 @@ import { DocumentService } from '@/server/services/document';
import { resolveDocumentWrite } from '@/server/services/document/editorData';
import { FileService } from '@/server/services/file';
import { KnowledgeBaseSearchService } from '@/server/services/knowledgeBase';
+import { getKnowledgeBaseIdsMountedByBrowsers } from '@/server/services/knowledgeBaseAccess';
import { type ServerRuntimeRegistration } from './types';
@@ -59,7 +60,18 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {
return new KnowledgeBaseExecutionRuntime(
{
- getFileContents: (fileIds) => searchService.getFileContents(fileIds),
+ getFileContents: (fileIds) =>
+ searchService.getFileContents(fileIds, {
+ // "No access" keeps a knowledge base usable on the agents it is mounted on.
+ resolveUsableKnowledgeBaseIds: async (restrictedIds) => {
+ const mounted = new Set(await resolveAgentKnowledgeBaseIds());
+ return getKnowledgeBaseIdsMountedByBrowsers(
+ { serverDB, workspaceId },
+ { agentId, projectId, taskId },
+ restrictedIds.filter((id) => mounted.has(id)),
+ );
+ },
+ }),
semanticSearchForChat: async ({ knowledgeIds, query, topK }) => {
const effectiveKnowledgeIds = await resolveAgentKnowledgeBaseIds(knowledgeIds);
// No enabled KB in scope (none attached, or all turned off) β†’ both search paths would return nothing (BM25 is