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(creds): route a member's own workspace-listed credential to the personal endpoint (#18992)

LiJian39a9a117a269
diff --git a/src/features/Settings/creds/features/CredsList.tsx b/src/features/Settings/creds/features/CredsList.tsx
index 2ceccd0dc8f..58602d79d8b 100644
--- a/src/features/Settings/creds/features/CredsList.tsx
+++ b/src/features/Settings/creds/features/CredsList.tsx
@@ -16,9 +16,10 @@ import ListSkeleton from '@/components/ListSkeleton';
import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
+import { credsApiForRow, isActionableCredRow } from './credAccess';
import CredItem from './CredItem';
import { createEditCredModal } from './EditCredModal';
-import { useCredsApi } from './useCredsApi';
+import { defaultCredsApi, useCredsApi } from './useCredsApi';
import { createViewCredModal } from './ViewCredModal';
const styles = createStaticStyles(({ css }) => ({
@@ -44,36 +45,46 @@ const styles = createStaticStyles(({ css }) => ({
const CredsList: FC = () => {
const { t } = useTranslation('setting');
- const { isAuthenticated, isLoading: isAuthLoading, signIn } = useMarketAuth();
+ const { isAuthenticated, isLoading: isAuthLoading, session, signIn } = useMarketAuth();
const { allowed: canManageCredentials } = usePermission('manage_provider_key');
const credsApi = useCredsApi();
+ const myAccountId = session?.userInfo?.accountId;
const { data, error, isLoading, refetch } = credsApi.query.list.useQuery(undefined, {
enabled: isAuthenticated,
});
+ const credentials = data?.data ?? [];
+
+ // See credAccess.ts for the ownership/routing rules this applies.
+ const isActionable = (cred: UserCredSummary) => isActionableCredRow(cred, myAccountId);
+ const apiFor = (cred: UserCredSummary) =>
+ credsApiForRow(cred, myAccountId, credsApi, defaultCredsApi);
+
const deleteMutation = useMutation({
mutationFn: async (id: number) => {
if (!canManageCredentials) return;
- await credsApi.client.delete.mutate({ id });
+ const cred = credentials.find((c) => c.id === id);
+ if (!cred || !isActionable(cred)) return;
+ await apiFor(cred).client.delete.mutate({ id });
},
onSuccess: () => {
refetch();
},
});
- const credentials = data?.data ?? [];
-
const handleEdit = (cred: UserCredSummary) => {
+ if (!isActionable(cred)) return;
createEditCredModal({
cred,
- credsApi,
+ credsApi: apiFor(cred),
onSuccess: () => refetch(),
});
};
const handleView = (cred: UserCredSummary) => {
- createViewCredModal({ cred, credsApi });
+ if (!isActionable(cred)) return;
+ createViewCredModal({ cred, credsApi: apiFor(cred) });
};
if (isAuthLoading) {
@@ -113,18 +124,23 @@ const CredsList: FC = () => {
onRetry={() => refetch()}
>
<Flexbox gap={0}>
- {credentials.map((cred) => (
- <CredItem
- cred={cred}
- key={cred.id}
- onDelete={(id) => deleteMutation.mutate(id)}
- onView={handleView}
- onEdit={(cred) => {
- if (!canManageCredentials) return;
- handleEdit(cred);
- }}
- />
- ))}
+ {credentials.map((cred) => {
+ // Another member's shared row: no endpoint this UI can reach for
+ // it (see the isActionable doc comment above) β€” omit the action
+ // handlers entirely so CredItem renders the row with no "..."
+ // menu / view button, instead of a menu whose actions silently
+ // no-op.
+ const actionable = isActionable(cred);
+ return (
+ <CredItem
+ cred={cred}
+ key={cred.id}
+ onDelete={actionable ? (id) => deleteMutation.mutate(id) : undefined}
+ onEdit={actionable && canManageCredentials ? (cred) => handleEdit(cred) : undefined}
+ onView={actionable ? handleView : undefined}
+ />
+ );
+ })}
</Flexbox>
</AsyncBoundary>
</div>
diff --git a/src/features/Settings/creds/features/credAccess.test.ts b/src/features/Settings/creds/features/credAccess.test.ts
new file mode 100644
index 00000000000..f23821b81b7
--- /dev/null
+++ b/src/features/Settings/creds/features/credAccess.test.ts
@@ -0,0 +1,88 @@
+import { type UserCredSummary } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { credsApiForRow, isActionableCredRow, isOwnCredRow } from './credAccess';
+
+const baseCred = {
+ createdAt: '2024-01-01T00:00:00.000Z',
+ id: 1,
+ key: 'GITHUB_TOKEN',
+ name: 'GitHub',
+ type: 'kv-env' as const,
+ updatedAt: '2024-01-01T00:00:00.000Z',
+};
+
+const orgOwnedRow: UserCredSummary = {
+ ...baseCred,
+ ownerAccountId: 100,
+ ownerType: 'organization',
+};
+
+const myOwnRow: UserCredSummary = {
+ ...baseCred,
+ ownerAccountId: 42,
+ ownerType: 'user',
+};
+
+const anotherMembersRow: UserCredSummary = {
+ ...baseCred,
+ ownerAccountId: 99,
+ ownerType: 'user',
+};
+
+const myAccountId = 42;
+
+describe('isOwnCredRow', () => {
+ it('is true for a "user"-owned row whose ownerAccountId matches the signed-in account', () => {
+ expect(isOwnCredRow(myOwnRow, myAccountId)).toBe(true);
+ });
+
+ it("is false for another member's row even though ownerType is also 'user'", () => {
+ expect(isOwnCredRow(anotherMembersRow, myAccountId)).toBe(false);
+ });
+
+ it('is false for an org-owned row', () => {
+ expect(isOwnCredRow(orgOwnedRow, myAccountId)).toBe(false);
+ });
+
+ it('is false when the signed-in account id is unknown (not yet loaded)', () => {
+ expect(isOwnCredRow(myOwnRow, undefined)).toBe(false);
+ });
+});
+
+describe('isActionableCredRow', () => {
+ it('is true for an org-owned row', () => {
+ expect(isActionableCredRow(orgOwnedRow, myAccountId)).toBe(true);
+ });
+
+ it("is true for the signed-in member's own row", () => {
+ expect(isActionableCredRow(myOwnRow, myAccountId)).toBe(true);
+ });
+
+ it("is false for another member's row β€” no endpoint can reach it", () => {
+ expect(isActionableCredRow(anotherMembersRow, myAccountId)).toBe(false);
+ });
+});
+
+describe('credsApiForRow', () => {
+ const contextApi = 'workspaceCreds' as const;
+ const personalApi = 'marketCreds' as const;
+
+ it('routes an org-owned row to the context (workspace) API', () => {
+ expect(credsApiForRow(orgOwnedRow, myAccountId, contextApi, personalApi)).toBe(contextApi);
+ });
+
+ it("routes the signed-in member's own row to the personal API", () => {
+ expect(credsApiForRow(myOwnRow, myAccountId, contextApi, personalApi)).toBe(personalApi);
+ });
+
+ it("routes another member's row to the context API, not the personal one β€” the caller must gate on isActionableCredRow first and never call this for such a row in practice", () => {
+ // credsApiForRow has no "no valid endpoint" return value, so this
+ // documents the fallback rather than endorsing it: CredsList only calls
+ // apiFor() after confirming isActionable(cred), so this branch is never
+ // reached for another member's row in the real component.
+ expect(credsApiForRow(anotherMembersRow, myAccountId, contextApi, personalApi)).toBe(
+ contextApi,
+ );
+ });
+});
diff --git a/src/features/Settings/creds/features/credAccess.ts b/src/features/Settings/creds/features/credAccess.ts
new file mode 100644
index 00000000000..2eddaa2b2df
--- /dev/null
+++ b/src/features/Settings/creds/features/credAccess.ts
@@ -0,0 +1,50 @@
+import { type UserCredSummary } from '@lobechat/types';
+
+/**
+ * Ownership routing for a row from an org-scoped credential list
+ * (`workspaceCreds.list`). Extracted from {@link CredsList} as plain,
+ * dependency-free functions so the routing decision has direct unit
+ * coverage independent of React/tRPC test scaffolding β€” see
+ * `credAccess.test.ts`.
+ *
+ * A row can be:
+ * - the org's own credential (`ownerType: 'organization'`);
+ * - the SIGNED-IN member's own credential, published/draft-linked into the
+ * org (`ownerType: 'user'` AND `ownerAccountId === myAccountId`);
+ * - ANOTHER member's published credential (`ownerType: 'user'` AND
+ * `ownerAccountId !== myAccountId`) β€” `ownerType` alone conflates this
+ * with the previous case.
+ *
+ * Market's org-scoped write endpoints (`/organizations/:orgId/creds/:id`
+ * PATCH/DELETE/GET?decrypt) resolve ownership by the *org's* account id
+ * only β€” they 404 (or refuse to decrypt) on ANY member-owned row, mine or
+ * someone else's. So:
+ * - org-owned β†’ the workspace API (context-bound) is correct;
+ * - my own row β†’ must go through my personal `market.creds` endpoint
+ * instead, which is scoped to my own account;
+ * - another member's row β†’ no endpoint this UI can reach at all; actions
+ * for it must be hidden rather than misrouted (routing to my personal API
+ * would 404 too, since that row isn't mine).
+ */
+type CredRowOwnership = Pick<UserCredSummary, 'ownerAccountId' | 'ownerType'>;
+
+export const isOwnCredRow = (cred: CredRowOwnership, myAccountId: number | undefined): boolean =>
+ cred.ownerType === 'user' && cred.ownerAccountId === myAccountId;
+
+export const isActionableCredRow = (
+ cred: CredRowOwnership,
+ myAccountId: number | undefined,
+): boolean => cred.ownerType !== 'user' || isOwnCredRow(cred, myAccountId);
+
+/**
+ * Which API binding (`personalApi` vs `contextApi`) a row's mutations should
+ * go through. Only meaningful for an {@link isActionableCredRow} row β€” the
+ * caller must gate on that first, since another member's row has no correct
+ * binding to return here.
+ */
+export const credsApiForRow = <T>(
+ cred: CredRowOwnership,
+ myAccountId: number | undefined,
+ contextApi: T,
+ personalApi: T,
+): T => (isOwnCredRow(cred, myAccountId) ? personalApi : contextApi);
diff --git a/src/features/Settings/creds/features/useCredsApi.ts b/src/features/Settings/creds/features/useCredsApi.ts
index 7e0be64ee3d..37464b9cfd0 100644
--- a/src/features/Settings/creds/features/useCredsApi.ts
+++ b/src/features/Settings/creds/features/useCredsApi.ts
@@ -21,7 +21,14 @@ export interface CredsApi {
query: typeof lambdaQuery.market.creds;
}
-const defaultCredsApi: CredsApi = {
+/**
+ * The personal `market.creds` binding, exported so callers that need it
+ * regardless of ambient context can use it explicitly β€” e.g. {@link CredsList}
+ * routing a merged workspace-view row back to the personal API when its
+ * `ownerType` is `'user'` (the row is a member's own credential, not the
+ * org's), since only the owner's personal endpoint can write to it.
+ */
+export const defaultCredsApi: CredsApi = {
client: lambdaClient.market.creds,
query: lambdaQuery.market.creds,
};