feat(twenty-orm): introduce WorkspaceScopedRepository for core/metadata workspace-scoped entities (#20953)
## Summary Adds a third tenancy enforcement layer for entities that live in shared schemas (`core`, `metadata`) and carry a `workspaceId` column — previously the only safeguard at this layer was developer discipline (remembering to put `workspaceId` in every WHERE clause). ### The three layers, after this PR | Layer | Scope | How it's enforced | |---|---|---| | 1. Workspace data | per-workspace schema (companies, people, custom objects) | `twentyORMManager.getRepository(workspace, E)` — physical isolation (own data source) | | 2. Metadata | shared `metadata` schema (objectMetadata, fieldMetadata, views, roles…) | Flat-entity-maps cache — workspace-scoped in-memory map, lookups by id within it | | 3. Core (new) | shared `core` schema (agent threads/turns/messages, app tokens, etc.) | `WorkspaceScopedRepository<T>` — `workspaceId` is a required positional argument on every read/write | ## What's in the PR ### The wrapper (`packages/twenty-server/src/engine/twenty-orm/workspace-scoped-repository/`) - `WorkspaceScopedRepository<T extends WorkspaceScopedEntity>` — wraps a TypeORM `Repository<T>`, requires `workspaceId` on every `find`/`findOne`/`findOneOrFail`/`update`/`delete`/`softDelete`/`insert`/`save`/`count` call, merging it into the WHERE or stamping it on the entity. `createQueryBuilder` is an explicit escape hatch (caller scopes manually). - Provided via Nest DI with `@InjectWorkspaceScopedRepository(EntityClass)` and the `provideWorkspaceScopedRepository(EntityClass)` provider factory. - 19 unit tests cover the merge behavior, override-on-conflict, and the array-where (OR) case. ### Lint enforcement (`packages/twenty-oxlint-rules/rules/prefer-workspace-scoped-repository.ts`) - New `twenty/prefer-workspace-scoped-repository` rule (level: **error**). - Blacklist of entity names: raw `@InjectRepository(E)` is rejected if `E` is on the list. - Initial list: `AgentTurnEntity`, `AgentMessageEntity`, `AgentMessagePartEntity`, `AgentChatThreadEntity`, `AgentTurnEvaluationEntity`, `AgentEntity`. - Designed to grow over time as more consumers are migrated. - 5 rule tests. ### Migration in this PR All consumers of the six blacklisted entities, including: - AI agent / chat / monitor resolvers, services, and jobs - `AgentService`, `AiAgentRoleService`, `AiAgentWorkflowAction`, `ApplicationService`, `WorkspaceFlatAgentMapCacheService` - Admin-panel chat (migrated where the lookup is workspace-known; one documented `eslint-disable` on the threadId-discovery lookup that necessarily precedes the `allowImpersonation` permission check) - `AiAgentRoleService` unit spec updated to mock the scoped wrapper ## Future work (deliberately not in this PR) A standalone audit identified ~14 additional `core`/`metadata` entities with `workspaceId` that currently use raw `@InjectRepository` and could be added to the blacklist. Notable candidates: `UserWorkspaceEntity` (42 sites), `AppTokenEntity` (10), `FileEntity` (7), `BillingCustomerEntity`/`BillingSubscriptionEntity` (~22 combined). Each should be its own PR — the migration is mechanical but the surface is wide. ## Test plan - [x] `npx nx typecheck twenty-server` — clean - [x] `npx nx lint twenty-server` — 0 warnings, 0 errors - [x] `npx jest workspace-scoped-repository` — 19/19 pass - [x] `npx nx test twenty-oxlint-rules` — 215/215 pass - [x] `npx jest src/engine/metadata-modules/ai` — 44/44 pass - [ ] Manual smoke: end-to-end AI agent chat send/receive (reviewer) - [ ] Manual smoke: AI agent monitor — list turns, run evaluation (reviewer) - [ ] Manual smoke: admin-panel chat thread inspection (reviewer)
This commit is contained in:
@@ -46,7 +46,7 @@ import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.ent
|
||||
import { AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
|
||||
import { AgentChatThreadEntity } from 'src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity';
|
||||
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
|
||||
|
||||
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([
|
||||
@@ -98,6 +98,9 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi
|
||||
WorkerHealthIndicator,
|
||||
ConnectedAccountHealth,
|
||||
AppHealthIndicator,
|
||||
provideWorkspaceScopedRepository(AgentMessageEntity),
|
||||
provideWorkspaceScopedRepository(FeatureFlagEntity),
|
||||
provideWorkspaceScopedRepository(BillingCustomerEntity),
|
||||
],
|
||||
exports: [
|
||||
AdminPanelUserLookupService,
|
||||
|
||||
+5
-4
@@ -9,7 +9,8 @@ import { BillingPriceEntity } from 'src/engine/core-modules/billing/entities/bil
|
||||
import { BillingPlanKey } from 'src/engine/core-modules/billing/enums/billing-plan-key.enum';
|
||||
import { BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';
|
||||
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
|
||||
|
||||
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
|
||||
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
|
||||
const CREDIT_BALANCE_MICRO_UNIT = 1_000_000;
|
||||
|
||||
const KNOWN_PLAN_KEYS: ReadonlySet<string> = new Set(
|
||||
@@ -19,8 +20,8 @@ const KNOWN_PLAN_KEYS: ReadonlySet<string> = new Set(
|
||||
@Injectable()
|
||||
export class AdminPanelBillingService {
|
||||
constructor(
|
||||
@InjectRepository(BillingCustomerEntity)
|
||||
private readonly billingCustomerRepository: Repository<BillingCustomerEntity>,
|
||||
@InjectWorkspaceScopedRepository(BillingCustomerEntity)
|
||||
private readonly billingCustomerRepository: WorkspaceScopedRepository<BillingCustomerEntity>,
|
||||
@InjectRepository(BillingPriceEntity)
|
||||
private readonly billingPriceRepository: Repository<BillingPriceEntity>,
|
||||
private readonly billingSubscriptionService: BillingSubscriptionService,
|
||||
@@ -35,7 +36,7 @@ export class AdminPanelBillingService {
|
||||
}
|
||||
|
||||
const [customer, subscription] = await Promise.all([
|
||||
this.billingCustomerRepository.findOne({ where: { workspaceId } }),
|
||||
this.billingCustomerRepository.findOne(workspaceId, { where: {} }),
|
||||
this.billingSubscriptionService.getCurrentBillingSubscription({
|
||||
workspaceId,
|
||||
}),
|
||||
|
||||
+16
-9
@@ -7,18 +7,22 @@ import { type AdminChatMessageDTO } from 'src/engine/core-modules/admin-panel/dt
|
||||
import { type AdminWorkspaceChatThreadDTO } from 'src/engine/core-modules/admin-panel/dtos/admin-workspace-chat-thread.dto';
|
||||
import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
import { AgentChatThreadEntity } from 'src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity';
|
||||
import { AgentMessageEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';
|
||||
|
||||
import { AgentChatThreadEntity } from 'src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity';
|
||||
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
|
||||
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
|
||||
@Injectable()
|
||||
export class AdminPanelChatService {
|
||||
constructor(
|
||||
@InjectRepository(WorkspaceEntity)
|
||||
private readonly workspaceRepository: Repository<WorkspaceEntity>,
|
||||
// Thread lookup is by id alone; the admin does not know the workspaceId
|
||||
// upfront. assertWorkspaceAllowsImpersonation gates every other read.
|
||||
// eslint-disable-next-line twenty/prefer-workspace-scoped-repository
|
||||
@InjectRepository(AgentChatThreadEntity)
|
||||
private readonly agentChatThreadRepository: Repository<AgentChatThreadEntity>,
|
||||
@InjectRepository(AgentMessageEntity)
|
||||
private readonly agentMessageRepository: Repository<AgentMessageEntity>,
|
||||
@InjectWorkspaceScopedRepository(AgentMessageEntity)
|
||||
private readonly agentMessageRepository: WorkspaceScopedRepository<AgentMessageEntity>,
|
||||
) {}
|
||||
|
||||
private async assertWorkspaceAllowsImpersonation(
|
||||
@@ -74,11 +78,14 @@ export class AdminPanelChatService {
|
||||
|
||||
await this.assertWorkspaceAllowsImpersonation(thread.workspaceId);
|
||||
|
||||
const messages = await this.agentMessageRepository.find({
|
||||
where: { threadId },
|
||||
relations: { parts: true },
|
||||
order: { createdAt: 'ASC' },
|
||||
});
|
||||
const messages = await this.agentMessageRepository.find(
|
||||
thread.workspaceId,
|
||||
{
|
||||
where: { threadId },
|
||||
relations: { parts: true },
|
||||
order: { createdAt: 'ASC' },
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
thread: {
|
||||
|
||||
+5
-6
@@ -19,7 +19,8 @@ import { UserService } from 'src/engine/core-modules/user/services/user.service'
|
||||
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
|
||||
import { userValidator } from 'src/engine/core-modules/user/user.validate';
|
||||
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
|
||||
|
||||
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
|
||||
import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
|
||||
@Injectable()
|
||||
export class AdminPanelUserLookupService {
|
||||
constructor(
|
||||
@@ -32,8 +33,8 @@ export class AdminPanelUserLookupService {
|
||||
private readonly workspaceRepository: Repository<WorkspaceEntity>,
|
||||
@InjectRepository(UserWorkspaceEntity)
|
||||
private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
|
||||
@InjectRepository(FeatureFlagEntity)
|
||||
private readonly featureFlagRepository: Repository<FeatureFlagEntity>,
|
||||
@InjectWorkspaceScopedRepository(FeatureFlagEntity)
|
||||
private readonly featureFlagRepository: WorkspaceScopedRepository<FeatureFlagEntity>,
|
||||
) {}
|
||||
|
||||
private buildFallbackAvatarUrlsByUserId(
|
||||
@@ -160,9 +161,7 @@ export class AdminPanelUserLookupService {
|
||||
where: { workspaceId },
|
||||
relations: { user: true },
|
||||
}),
|
||||
this.featureFlagRepository.find({
|
||||
where: { workspaceId },
|
||||
}),
|
||||
this.featureFlagRepository.find(workspaceId),
|
||||
]);
|
||||
|
||||
const allFeatureFlagKeys = Object.values(FeatureFlagKey);
|
||||
|
||||
Reference in New Issue
Block a user