π€― 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(db): treat a blank workspace id as personal instead of writing it through (#20564)
Arvin Xu7570096ba71a
diff --git a/packages/database/src/utils/workspace.test.ts b/packages/database/src/utils/workspace.test.tsindex 21c3f8d0059..117d80f3943 100644--- a/packages/database/src/utils/workspace.test.ts+++ b/packages/database/src/utils/workspace.test.ts@@ -18,6 +18,20 @@ describe('workspace utils', () => {expect(built.params).toStrictEqual(['user-1']);});+ it('treats a blank workspace id as personal scope rather than as a workspace', () => {+ // Reads already collapsed `''` because it is falsy. Pinning it keeps a+ // future refactor of the predicate from turning a blank scope into+ // `workspace_id = ''`, which matches nothing.+ const condition = buildWorkspaceWhere(+ { includeTrashed: true, userId: 'user-1', workspaceId: '' },+ agents,+ );+ const built = new PgDialect().sqlToQuery(condition);++ expect(built.sql).toBe('("agents"."user_id" = $1 and "agents"."workspace_id" is null)');+ expect(built.params).toStrictEqual(['user-1']);+ });+it('scopes workspace reads with visibility filter when the column is present', () => {const condition = buildWorkspaceWhere({ includeTrashed: true, userId: 'user-1', workspaceId: 'ws-1' },@@ -209,5 +223,45 @@ describe('workspace utils', () => {workspaceId: 'ws-1',});});++ /**+ * @example A caller hands over a scope it "resolved" into `''`.+ */+ it('treats a blank workspace id as personal instead of writing a scope that cannot exist', () => {+ // ROOT CAUSE:+ //+ // An empty scope is not a workspace. Whatever turns "no workspace" into+ // `''` β an empty header, an env var that is present but blank, a `?? ''`+ // on the way through a caller β the payload was written as+ // `workspace_id: ''`, which the foreign key to `workspaces` rejects. The+ // statement then fails whole, so nothing in that batch is persisted.+ //+ // Before: `''` was written through verbatim.+ // After: blank collapses to `null`, i.e. personal data.+ const personal = { title: 'Personal agent', userId: 'user-1', workspaceId: null };++ expect(+ buildWorkspacePayload({ userId: 'user-1', workspaceId: '' }, { title: 'Personal agent' }),+ ).toEqual(personal);+ expect(+ buildWorkspacePayload(+ { userId: 'user-1', workspaceId: ' ' },+ { title: 'Personal agent' },+ ),+ ).toEqual(personal);+ expect(+ buildWorkspacePayload({ userId: 'user-1', workspaceId: null }, { title: 'Personal agent' }),+ ).toEqual(personal);+ });++ it('trims a padded workspace id rather than writing it unreadable', () => {+ expect(+ buildWorkspacePayload({ userId: 'user-1', workspaceId: ' ws-1 ' }, { title: 'Team agent' }),+ ).toEqual({+ title: 'Team agent',+ userId: 'user-1',+ workspaceId: 'ws-1',+ });+ });});});diff --git a/packages/database/src/utils/workspace.ts b/packages/database/src/utils/workspace.tsindex 33b6053d48e..9cca68fc6f1 100644--- a/packages/database/src/utils/workspace.ts+++ b/packages/database/src/utils/workspace.ts@@ -119,19 +119,39 @@ export function buildWorkspaceWhere(return and(base, notTrashed(cols.isDeleted)) as SQL;}+/**+ * The workspace scope a write may carry: a real workspace id, or `null` for+ * personal data.+ *+ * An empty string is not a workspace. It shows up whenever a scope gets+ * "resolved" into a placeholder β an empty `X-Workspace-Id`, an env var that is+ * present but blank, a `?? ''` on the way through a caller β and every such+ * value lands in `workspace_id`, where the foreign key to `workspaces` rejects+ * it and takes the whole statement down with it. Collapse it (and+ * whitespace-only values) here, so no producer can persist a scope that cannot+ * exist.+ */+export const normalizeWorkspaceId = (value?: string | null): string | null => {+ const trimmed = value?.trim();++ return trimmed || null;+};+function buildScopeWhere(ctx: {callerAgentVisibility?: 'private' | 'public' | null;userId: string;- workspaceId?: string;+ workspaceId?: string | null;},cols: { userId: AnyPgColumn; visibility?: AnyPgColumn; workspaceId: AnyPgColumn },): SQL {- if (!ctx.workspaceId) {+ const workspaceId = normalizeWorkspaceId(ctx.workspaceId);++ if (!workspaceId) {return and(eq(cols.userId, ctx.userId), isNull(cols.workspaceId)) as SQL;}- const workspaceMatch = eq(cols.workspaceId, ctx.workspaceId);+ const workspaceMatch = eq(cols.workspaceId, workspaceId);if (!cols.visibility) return workspaceMatch;// Public agent gate: drop the "creator's own private rows" branch so a@@ -158,7 +178,9 @@ function buildScopeWhere(* Companion to `buildWorkspaceWhere` for INSERT payloads.** Always sets `userId` (the creator) and `workspaceId` (nullable). Personal-mode- * writes get `workspaceId: null`; team-mode writes get the workspace id.+ * writes get `workspaceId: null`; team-mode writes get the workspace id. A+ * blank scope is treated as personal rather than written through β see+ * {@link normalizeWorkspaceId}.** @example* ```ts@@ -171,12 +193,12 @@ function buildScopeWhere(* ```*/export function buildWorkspacePayload<T extends object>(- ctx: { userId: string; workspaceId?: string },+ ctx: { userId: string; workspaceId?: string | null },base: T,): T & { userId: string; workspaceId: string | null } {return {...base,userId: ctx.userId,- workspaceId: ctx.workspaceId ?? null,+ workspaceId: normalizeWorkspaceId(ctx.workspaceId),};}diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.tsindex 7be83e577fb..e408846b2e4 100644--- a/packages/trpc/src/lambda/context.test.ts+++ b/packages/trpc/src/lambda/context.test.ts@@ -389,6 +389,36 @@ describe('createLambdaContext', () => {expect(mockCanUseWorkspaceApiKeys).toHaveBeenCalledWith('ws-1');});+ it('should collapse a blank workspace scope instead of carrying it into every model', async () => {+ // ROOT CAUSE:+ //+ // `''` is not a workspace. When a caller resolves "no workspace" into a+ // blank string, every model built from this context writes+ // `workspace_id = ''`, which the foreign key to `workspaces` rejects β the+ // whole statement fails, so not even a single chat message could be+ // persisted. This context is the funnel every lambda request passes+ // through, so the collapse belongs here rather than at each of the ~90+ // model constructors.+ //+ // Before: `ctx.workspaceId` was `''`.+ // After: it is `undefined`, which is how the context already spells+ // "personal" (see the API-key assertions above).+ expect(+ (await createContextInner({ userId: 'user-1', workspaceId: '' })).workspaceId,+ ).toBeUndefined();+ expect(+ (await createContextInner({ userId: 'user-1', workspaceId: ' ' })).workspaceId,+ ).toBeUndefined();+ expect(+ (await createContextInner({ userId: 'user-1', workspaceId: null })).workspaceId,+ ).toBeUndefined();++ // A real scope still comes through, trimmed.+ expect(+ (await createContextInner({ userId: 'user-1', workspaceId: ' ws-1 ' })).workspaceId,+ ).toBe('ws-1');+ });+it('should accept a workspace API key with a matching workspace header', async () => {vi.mocked(ApiKeyModel.findByKey).mockResolvedValue(makeApiKeyRecord('ws-1'));diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.tsindex f4f95b6633c..454a08e7803 100644--- a/packages/trpc/src/lambda/context.ts+++ b/packages/trpc/src/lambda/context.ts@@ -11,6 +11,7 @@ import { canUseWorkspaceApiKeys } from '@/business/server/workspaceApiKey';import { getServerDB } from '@/database/core/db-adaptor';import { ApiKeyModel } from '@/database/models/apiKey';import { hasActiveWorkspaceMembership } from '@/database/models/workspace';+import { normalizeWorkspaceId } from '@/database/utils/workspace';import { authEnv, LOBE_CHAT_OIDC_AUTH_HEADER } from '@/envs/auth';import { extractTraceContext } from '@/libs/observability/traceparent';import { assertOIDCUserActive, isOIDCUserInactiveError } from '@/libs/oidc-provider/access-control';@@ -156,7 +157,12 @@ export const createContextInner = async (params?: {traceContext: params?.traceContext,userAgent: params?.userAgent,userId: params?.userId,- workspaceId: params?.workspaceId,+ // A blank scope is not a workspace. Callers that "resolve" one (an empty+ // header, a blank env var, a `?? ''` on the way through) would otherwise+ // hand `''` to every model, and each write would fail on the `workspaces`+ // foreign key instead of landing in personal data. `undefined` is how the+ // rest of the context already spells "no workspace".+ workspaceId: normalizeWorkspaceId(params?.workspaceId) ?? undefined,};};