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.

13.9 KB
Raw Blame
// @vitest-environment node
import { MarketAPIError } from '@lobehub/market-sdk';
import { beforeEach, describe, expect, it, vi } from 'vitest';

interface MockOrgCredRow {
  id: number;
  key: string;
  ownerType?: string;
}

const {
  mockCredsInject,
  mockMarketSandboxProvider,
  mockResolveSandboxSessionConfig,
  mockOrgCredsList,
  mockPersonalCredsList,
  mockPersonalCredsShare,
  mockPersonalCredsPublish,
  mockPersonalCredsUnshare,
} = vi.hoisted(() => ({
  mockCredsInject: vi.fn(async () => ({ credentials: { env: {} }, success: true })),
  mockMarketSandboxProvider: vi.fn(function (this: any, options: any) {
    this.options = options;
    this.callTool = vi.fn(async () => ({ result: {}, success: true }));
  }),
  mockResolveSandboxSessionConfig: vi.fn(),
  mockOrgCredsList: vi.fn(async (): Promise<{ data: MockOrgCredRow[] }> => ({
    data: [{ id: 1, key: 'ORG_SECRET' }],
  })),
  mockPersonalCredsList: vi.fn(
    async (): Promise<{
      data: Array<{ id: number; key: string; shares?: Array<{ workspaceId?: string }> }>;
    }> => ({ data: [{ id: 2, key: 'PERSONAL_SECRET' }] }),
  ),
  mockPersonalCredsPublish: vi.fn(async (id: number) => ({ id, visibility: 'public' })),
  mockPersonalCredsShare: vi.fn(async (id: number) => ({ id, visibility: 'private' })),
  mockPersonalCredsUnshare: vi.fn(async (id: number) => ({ id, visibility: 'private' })),
}));

vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({
  withRbacPermission: vi.fn(function () {
    return (opts: any) => opts.next(opts);
  }),
}));

// Simulates the real `cloudWorkspaceAuth`: strips `workspaceId` off the
// context unless the caller is flagged as a workspace member.
vi.mock('@/business/server/trpc-middlewares/workspaceAuth', () => ({
  cloudWorkspaceAuth: vi.fn(function (opts: any) {
    return opts.next({
      ctx: {
        ...opts.ctx,
        workspaceId: opts.ctx.isWorkspaceMember ? opts.ctx.workspaceId : undefined,
      },
    });
  }),
}));

vi.mock('@/libs/trpc/lambda/middleware', () => ({
  marketUserInfo: vi.fn(function (opts: any) {
    return opts.next({
      ctx: {
        ...opts.ctx,
        marketUserInfo: { email: '[email protected]', name: 'Actor', userId: 'user-1' },
      },
    });
  }),
  requireMarketAuth: vi.fn(function (opts: any) {
    return opts.next(opts);
  }),
  serverDatabase: vi.fn(function (opts: any) {
    return opts.next(opts);
  }),
}));

vi.mock('@/server/services/market', () => ({
  MarketService: vi.fn(function () {
    return {
      market: {
        creds: {
          inject: mockCredsInject,
          list: mockPersonalCredsList,
          publish: mockPersonalCredsPublish,
          share: mockPersonalCredsShare,
          unshare: mockPersonalCredsUnshare,
        },
        organizations: {
          creds: vi.fn(function () {
            return { list: mockOrgCredsList };
          }),
        },
      },
    };
  }),
}));

vi.mock('@/server/services/sandbox', () => ({
  getSandboxProviderKind: () => 'market',
  MarketSandboxProvider: mockMarketSandboxProvider,
  resolveSandboxSessionConfig: mockResolveSandboxSessionConfig,
}));

describe('credsRouter is always personal-scoped', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  // `market.creds` is the personal-creds router used directly by the browser
  // (standalone /settings/credential page, and the workspace creds page's "your
  // personal credentials" section). `ctx.workspaceId` is ambient — set on
  // every request whenever the caller has *any* workspace selected elsewhere
  // in the app, regardless of which page/section made the call. Routing
  // `list` (or any other procedure here) off that ambient value previously
  // made this router silently return the active workspace's org creds
  // instead of the caller's own personal creds — indistinguishable from
  // `workspaceCreds.list`. This must never happen again: `list` always
  // returns personal creds data, with or without an active (even verified)
  // workspace.
  it('returns personal creds data, never the org list, when the caller is a verified workspace member', async () => {
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({
      isWorkspaceMember: true,
      userId: 'user-1',
      workspaceId: 'workspace-1',
    } as any);

    const result = await caller.list();

    expect(mockPersonalCredsList).toHaveBeenCalledTimes(1);
    expect(result.data?.map((c) => c.id)).toEqual([2]);
    expect(result.data?.every((c) => c.key !== 'ORG_SECRET')).toBe(true);
  });

  it('resolves personal creds outside any workspace context, without consulting the org list at all', async () => {
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({
      isWorkspaceMember: false,
      userId: 'user-1',
    } as any);

    const result = await caller.list();

    expect(mockPersonalCredsList).toHaveBeenCalledTimes(1);
    expect(mockOrgCredsList).not.toHaveBeenCalled();
    expect(result.data).toEqual([{ id: 2, key: 'PERSONAL_SECRET' }]);
  });
});

describe('credsRouter listForContext follows the runtime scope', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('lists the workspace organization creds for a verified workspace member', async () => {
    const { credsRouter } = await import('./creds');
    const caller = credsRouter.createCaller({
      isWorkspaceMember: true,
      userId: 'user-1',
      workspaceId: 'workspace-1',
    } as any);

    const result = await caller.listForContext();

    expect(mockOrgCredsList).toHaveBeenCalledTimes(1);
    expect(mockPersonalCredsList).not.toHaveBeenCalled();
    expect(result.data.map((c) => c.key)).toEqual(['ORG_SECRET']);
  });

  it('lists personal creds outside a workspace', async () => {
    const { credsRouter } = await import('./creds');
    const caller = credsRouter.createCaller({ isWorkspaceMember: false, userId: 'user-1' } as any);

    const result = await caller.listForContext();

    expect(mockPersonalCredsList).toHaveBeenCalledTimes(1);
    expect(mockOrgCredsList).not.toHaveBeenCalled();
    expect(result.data.map((c) => c.key)).toEqual(['PERSONAL_SECRET']);
  });
});

describe('credsRouter list scopes sharing to the active workspace', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  const listIn = async (workspaceId: string | undefined) => {
    const { credsRouter } = await import('./creds');
    return credsRouter
      .createCaller({ isWorkspaceMember: !!workspaceId, userId: 'user-1', workspaceId } as any)
      .list();
  };

  it("flags sharedToActiveWorkspace from the credential's own shares", async () => {
    mockPersonalCredsList.mockResolvedValueOnce({
      data: [
        { id: 2, key: 'HERE', shares: [{ workspaceId: 'other' }, { workspaceId: 'workspace-1' }] },
        { id: 3, key: 'ELSEWHERE', shares: [{ workspaceId: 'other' }] },
        { id: 4, key: 'UNSHARED', shares: [] },
      ],
    });

    const result = await listIn('workspace-1');

    expect(result.data?.map((c) => [c.key, c.sharedToActiveWorkspace])).toEqual([
      ['HERE', true],
      ['ELSEWHERE', false],
      ['UNSHARED', false],
    ]);
    expect(mockOrgCredsList).not.toHaveBeenCalled();
  });

  it('leaves the flag off outside a workspace', async () => {
    mockPersonalCredsList.mockResolvedValueOnce({
      data: [{ id: 2, key: 'HERE', shares: [{ workspaceId: 'workspace-1' }] }],
    });

    const result = await listIn(undefined);

    expect(result.data?.[0]).not.toHaveProperty('sharedToActiveWorkspace');
  });
});

describe('credsRouter share/publish/unshare', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('shares a personal credential into the caller-verified workspace, never a client-supplied org', async () => {
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({
      isWorkspaceMember: true,
      userId: 'user-1',
      workspaceId: 'workspace-1',
    } as any);

    await caller.share({ id: 42, visibility: 'private' });

    expect(mockPersonalCredsShare).toHaveBeenCalledWith(42, {
      orgId: 'workspace:workspace-1',
      visibility: 'private',
    });
  });

  it('rejects share when there is no active (verified) workspace context', async () => {
    const { credsRouter } = await import('./creds');

    // Simulates both the personal-mode case (no header) and the forged-header
    // case (cloudWorkspaceAuth already stripped workspaceId for a non-member).
    const caller = credsRouter.createCaller({
      isWorkspaceMember: false,
      userId: 'user-1',
    } as any);

    await expect(caller.share({ id: 42 })).rejects.toThrow(
      'Sharing a credential requires an active workspace context',
    );
    expect(mockPersonalCredsShare).not.toHaveBeenCalled();
  });

  it("publishes the credential's share into the caller-verified workspace", async () => {
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({
      isWorkspaceMember: true,
      userId: 'user-1',
      workspaceId: 'workspace-1',
    } as any);

    const result = await caller.publish({ id: 42 });

    expect(mockPersonalCredsPublish).toHaveBeenCalledWith(42, undefined, {
      orgId: 'workspace:workspace-1',
    });
    expect(result).toEqual({ id: 42, visibility: 'public' });
  });

  it('unshares a credential from the caller-verified workspace only', async () => {
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({
      isWorkspaceMember: true,
      userId: 'user-1',
      workspaceId: 'workspace-1',
    } as any);

    const result = await caller.unshare({ id: 42 });

    expect(mockPersonalCredsUnshare).toHaveBeenCalledWith(42, undefined, {
      orgId: 'workspace:workspace-1',
    });
    expect(result).toEqual({ id: 42, visibility: 'private' });
  });

  it('maps a Market 403 (not a member) to a tRPC FORBIDDEN error', async () => {
    mockPersonalCredsShare.mockRejectedValueOnce(
      new MarketAPIError(403, 'Forbidden', { error: 'Not a member of this organization' }),
    );
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({
      isWorkspaceMember: true,
      userId: 'user-1',
      workspaceId: 'workspace-1',
    } as any);

    await expect(caller.share({ id: 42 })).rejects.toMatchObject({
      code: 'FORBIDDEN',
      message: 'Not a member of this organization',
    });
  });
});

describe('credsRouter inject routes to the topic sandbox', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  // Regression: this route forwarded only keys/sandbox/topicId/userId and
  // signed no storage claim, so the client-executor path always injected into
  // a throwaway sandbox, never the topic's persistent environment or drive.
  it('resolves mode, instance and claim server-side and signs the claim', async () => {
    const { MarketService } = await import('@/server/services/market');
    mockResolveSandboxSessionConfig.mockResolvedValue({
      claim: { key: 'u-user-1' },
      drive: 'personal',
      environment: 'inst-1',
      mode: 'persistent',
    });
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({ userId: 'user-1' } as any);
    await caller.inject({ keys: ['FOO'], topicId: 'topic-1', userId: 'someone-else' });

    expect(mockResolveSandboxSessionConfig).toHaveBeenCalledWith(
      expect.objectContaining({ topicId: 'topic-1', userId: 'user-1' }),
    );
    expect(MarketService).toHaveBeenLastCalledWith(
      expect.objectContaining({
        userInfo: expect.objectContaining({
          sandboxStorage: { key: 'u-user-1' },
          userId: 'user-1',
        }),
      }),
    );
    expect(mockCredsInject).toHaveBeenCalledWith(
      expect.objectContaining({
        keys: ['FOO'],
        sandbox: true,
        sandboxInstanceId: 'inst-1',
        sandboxMode: 'persistent',
        topicId: 'topic-1',
        userId: 'user-1',
      }),
    );
  });

  // Market rewrites ~/.creds/env on every inject, so the route merges the
  // listing afterwards. That merge must run in the sandbox the credentials
  // were just written into: without the placement and the signed claim it
  // would open (or replace) a throwaway sandbox instead.
  it('merges ~/.creds/env in the same sandbox the credentials were injected into', async () => {
    const { MarketService } = await import('@/server/services/market');
    mockResolveSandboxSessionConfig.mockResolvedValue({
      claim: { key: 'u-user-1' },
      cwd: '/workspace/project',
      drive: 'personal',
      environment: 'inst-1',
      mode: 'persistent',
      workingDir: '/home/user/project',
    });
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({ userId: 'user-1' } as any);
    await caller.inject({ keys: ['FOO'], topicId: 'topic-1' });

    expect(mockMarketSandboxProvider).toHaveBeenCalledTimes(1);
    const { options, callTool } = mockMarketSandboxProvider.mock.instances[0] as any;
    expect(options).toMatchObject({
      sandboxCwd: '/workspace/project',
      sandboxInstanceId: 'inst-1',
      sandboxMode: 'persistent',
      sandboxWorkingDir: '/home/user/project',
      topicId: 'topic-1',
      userId: 'user-1',
    });
    // The claim-signed service, not the request's unsigned one.
    expect(options.marketService).toBe(vi.mocked(MarketService).mock.results.at(-1)?.value);
    expect(callTool).toHaveBeenCalledWith('runCommand', {
      command: expect.stringContaining('~/.creds/.env.ledger'),
    });
  });

  it('skips sandbox resolution when not injecting into a sandbox', async () => {
    const { credsRouter } = await import('./creds');

    const caller = credsRouter.createCaller({ userId: 'user-1' } as any);
    await caller.inject({ keys: ['FOO'], sandbox: false, topicId: 'topic-1' });

    expect(mockResolveSandboxSessionConfig).not.toHaveBeenCalled();
    expect(mockCredsInject).toHaveBeenCalledWith(
      expect.objectContaining({ sandbox: false, sandboxMode: undefined }),
    );
    expect(mockMarketSandboxProvider).not.toHaveBeenCalled();
  });
});