Environment scoping added to create/update integration routes but not the sibling mutations
Tier 2 hard typescript · cross-file · real merged PR from novuhq/novu #11083
Ground-truth defects
The PR added API-key environment scoping to only the create and update integration routes. The sibling mutations removeIntegration, setIntegrationAsPrimary, and autoConfigureIntegration on the same controller were left unscoped, so an API key from one environment can delete, re-prioritize, or auto-configure integrations in another environment of the same org (cross-environment IDOR).
The change under review
diff
@@ -4,7 +4,6 @@ import { SubscriberPayloadDto } from '@novu/api/src/models/components/subscriber import { ClickHouseService, DetailEnum, QueryBuilder, Trace, TraceLogRepository } from '@novu/application-generic'; import { CommunityOrganizationRepository, - EnvironmentRepository, ExecutionDetailsRepository, IntegrationRepository, JobRepository, @@ -61,7 +60,6 @@ describe('Trigger event - /v1/events/trigger (POST) #novu-v2', () => { const integrationRepository = new IntegrationRepository(); const jobRepository = new JobRepository(); const executionDetailsRepository = new ExecutionDetailsRepository(); - const environmentRepository = new EnvironmentRepository(); const tenantRepository = new TenantRepository(); let novuClient: Novu; @@ -2701,16 +2699,10 @@ describe('Trigger event - /v1/events/trigger (POST) #novu-v2', () => { expect(messages.length).to.be.equal(1); expect(messages[0].providerId).to.be.equal(EmailProviderIdEnum.SendGrid); - const prodEnv = await environmentRepository.findOne({ - name: 'Production', - _organizationId: session.organization._id, - }); - const payload: CreateIntegrationRequestDto = { providerId: EmailProviderIdEnum.Mailgun, channel: 'email', credentials: { apiKey: '123', secretKey: 'abc' }, - environmentId: prodEnv?._id, active: true, check: false, }; @@ -648,6 +648,63 @@ describe('Create Integration - /integration (POST) #novu-v2', () => { ); process.env.NOVU_SMS_INTEGRATION_ACCOUNT_SID = oldNovuSmsIntegrationAccountSid; }); + + describe('API key authentication is scoped to the key environment', () => { + it('should forbid creating with a different `_environmentId` when authenticated via API key', async () => { + const prodEnv = await envRepository.findOne({ name: 'Production', _organizationId: session.organization._id }); + expect(prodEnv?._id, 'Expected Production environment fixture').to.exist; + + const payload = { + providerId: EmailProviderIdEnum.SendGrid, + channel: ChannelTypeEnum.EMAIL, + _environmentId: prodEnv!._id, + check: false, + }; + + const { body } = await session.testAgent + .post('/v1/integrations') + .set('authorization', `ApiKey ${session.apiKey}`) + .send(payload); + + expect(body.statusCode).to.equal(403); + expect(body.message).to.contain('API key authentication is scoped to a single environment'); + }); + + it('should allow creating without `_environmentId` (defaults to API key environment) via API key', async () => { + const payload = { + providerId: EmailProviderIdEnum.SendGrid, + channel: ChannelTypeEnum.EMAIL, + check: false, + }; + + const { + body: { data }, + } = await session.testAgent + .post('/v1/integrations') + .set('authorization', `ApiKey ${session.apiKey}`) + .send(payload); + + expect(data._environmentId).to.equal(session.environment._id); + }); + + it('should allow creating with the same `_environmentId` as the API key environment', async () => { + const payload = { + providerId: EmailProviderIdEnum.SendGrid, + channel: ChannelTypeEnum.EMAIL, + _environmentId: session.environment._id, + check: false, + }; + + const { + body: { data }, + } = await session.testAgent + .post('/v1/integrations') + .set('authorization', `ApiKey ${session.apiKey}`) + .send(payload); + + expect(data._environmentId).to.equal(session.environment._id); + }); + }); }); async function insertIntegrationTwice( @@ -1020,4 +1020,127 @@ describe('Update Integration - /integrations/:integrationId (PUT) #novu-v2', () expect(second.active).to.equal(true); expect(second.priority).to.equal(1); }); + + describe('API key authentication is scoped to the key environment', () => { + it('should forbid updating with a different `_environmentId` when authenticated via API key', async () => { + const integrationOne = await integrationRepository.create({ + name: 'Test', + identifier: 'identifier-api-key-other-env', + providerId: EmailProviderIdEnum.SendGrid, + channel: ChannelTypeEnum.EMAIL, + active: false, + _organizationId: session.organization._id, + _environmentId: session.environment._id, + }); + const prodEnv = await envRepository.findOne({ name: 'Production', _organizationId: session.organization._id }); + expect(prodEnv?._id, 'Expected Production environment fixture').to.exist; + + const payload = { + _environmentId: prodEnv!._id, + check: false, + }; + + const { body } = await session.testAgent + .put(`/v1/integrations/${integrationOne._id}`) + .set('authorization', `ApiKey ${session.apiKey}`) + .send(payload); + + expect(body.statusCode).to.equal(403); + expect(body.message).to.contain('API key authentication is scoped to a single environment'); + + const untouched = await integrationRepository.findOne({ + _id: integrationOne._id, + _environmentId: session.environment._id, + }); + expect(untouched?._environmentId).to.equal(session.environment._id); + }); + + it('should allow updating with the same `_environmentId` as the API key environment', async () => { + const integrationOne = await integrationRepository.create({ + name: 'Test', + identifier: 'identifier-api-key-same-env', + providerId: EmailProviderIdEnum.SendGrid, + channel: ChannelTypeEnum.EMAIL, + active: false, + _organizationId: session.organization._id, + _environmentId: session.environment._id, + }); + + const payload = { + _environmentId: session.environment._id, + name: 'Renamed via API key', + check: false, + }; + + const { + body: { data }, + } = await session.testAgent + .put(`/v1/integrations/${integrationOne._id}`) + .set('authorization', `ApiKey ${session.apiKey}`) + .send(payload); + + expect(data.name).to.equal('Renamed via API key'); + expect(data._environmentId).to.equal(session.environment._id); + }); + + it('should forbid updating an integration that lives in a different environment when authenticated via API key', async () => { + const prodEnv = await envRepository.findOne({ name: 'Production', _organizationId: session.organization._id }); + expect(prodEnv?._id, 'Expected Production environment fixture').to.exist; + const otherEnvironmentIntegration = await integrationRepository.create({ + name: 'OtherEnv', + identifier: 'other-env-update-api-key', + providerId: EmailProviderIdEnum.SendGrid, + channel: ChannelTypeEnum.EMAIL, + active: false, + _organizationId: session.organization._id, + _environmentId: prodEnv!._id, + }); + + const payload = { + name: 'Should not change', + check: false, + }; + + const { body } = await session.testAgent + .put(`/v1/integrations/${otherEnvironmentIntegration._id}`) + .set('authorization', `ApiKey ${session.apiKey}`) + .send(payload); + + expect(body.statusCode).to.equal(403); + expect(body.message).to.contain('API key authentication is scoped to a single environment'); + + const untouched = await integrationRepository.findOne({ + _id: otherEnvironmentIntegration._id, + _environmentId: prodEnv!._id, + }); + expect(untouched?.name).to.equal('OtherEnv'); + }); + + it('should still allow JWT-authenticated requests to update integrations in another environment', async () => { + const prodEnv = await envRepository.findOne({ name: 'Production', _organizationId: session.organization._id }); + expect(prodEnv?._id, 'Expected Production environment fixture').to.exist; + const otherEnvironmentIntegration = await integrationRepository.create({ + name: 'OtherEnv', + identifier: 'other-env-update-jwt', + providerId: EmailProviderIdEnum.SendGrid, + channel: ChannelTypeEnum.EMAIL, + active: false, + _organizationId: session.organization._id, + _environmentId: prodEnv!._id, + }); + + const payload = { + _environmentId: prodEnv!._id, + name: 'Renamed via JWT', + check: false, + }; + + const { + body: { data }, + } = await session.testAgent.put(`/v1/integrations/${otherEnvironmentIntegration._id}`).send(payload); + + expect(data.name).to.equal('Renamed via JWT'); + expect(data._environmentId).to.equal(prodEnv!._id); + }); + }); }); @@ -4,6 +4,7 @@ import { ClassSerializerInterceptor, Controller, Delete, + ForbiddenException, Get, Param, Post, @@ -27,6 +28,7 @@ import { } from '@novu/application-generic'; import { CommunityOrganizationRepository } from '@novu/dal'; import { + ApiAuthSchemeEnum, ApiServiceLevelEnum, ChannelTypeEnum, FeatureFlagsKeysEnum, @@ -227,6 +229,8 @@ export class IntegrationsController { @Body() body: CreateIntegrationRequestDto ): Promise<IntegrationResponseDto> { try { + this.assertEnvironmentScopedForApiKey(user, body._environmentId); + const canAccessCredentials = await this.canUserAccessCredentials(user); const integration = await this.createIntegrationUsecase.execute( CreateIntegrationCommand.create({ @@ -280,6 +284,8 @@ export class IntegrationsController { @Body() body: UpdateIntegrationRequestDto ): Promise<IntegrationResponseDto> { try { + this.assertEnvironmentScopedForApiKey(user, body._environmentId); + const canAccessCredentials = await this.canUserAccessCredentials(user); const integration = await this.updateIntegrationUsecase.execute( UpdateIntegrationCommand.create({ @@ -295,6 +301,7 @@ export class IntegrationsController { check: body.check ?? false, conditions: body.conditions, configurations: body.configurations, + restrictToUserEnvironment: user.scheme === ApiAuthSchemeEnum.API_KEY, }) ); @@ -823,6 +830,19 @@ export class IntegrationsController { ); } + private assertEnvironmentScopedForApiKey(user: UserSessionData, requestedEnvironmentId?: string): void { + if (user.scheme !== ApiAuthSchemeEnum.API_KEY) { + return; + } + + if (requestedEnvironmentId && requestedEnvironmentId !== user.environmentId) { + throw new ForbiddenException( + 'API key authentication is scoped to a single environment and cannot target a different `_environmentId`. ' + + 'Use an API key from the target environment, or authenticate with a session token.' + ); + } + } + private async canUserAccessCredentials(user: UserSessionData): Promise<boolean> { const organization = await this.organizationRepository.findOne({ _id: user.organizationId, @@ -1,6 +1,15 @@ import { MessageFilter } from '@novu/application-generic'; import { IConfigurations, ICredentialsDto } from '@novu/shared'; -import { IsArray, IsDefined, IsMongoId, IsObject, IsOptional, IsString, ValidateNested } from 'class-validator'; +import { + IsArray, + IsBoolean, + IsDefined, + IsMongoId, + IsObject, + IsOptional, + IsString, + ValidateNested, +} from 'class-validator'; import { OrganizationCommand } from '../../../shared/commands/organization.command'; @@ -41,4 +50,14 @@ export class UpdateIntegrationCommand extends OrganizationCommand { @IsOptional() @IsObject() configurations?: IConfigurations; + + /** + * When true, the existing integration must belong to `userEnvironmentId` for the + * update to succeed. Used when the request is authenticated with an API key, since + * an API key is bound to a single environment and must not be able to mutate + * integrations that live in a different environment of the same organization. + */ + @IsOptional() + @IsBoolean() + restrictToUserEnvironment?: boolean; } @@ -1,4 +1,11 @@ -import { BadRequestException, ConflictException, Inject, Injectable, NotFoundException } from '@nestjs/common'; +import { + BadRequestException, + ConflictException, + ForbiddenException, + Inject, + Injectable, + NotFoundException, +} from '@nestjs/common'; import { AnalyticsService, decryptCredentials, encryptCredentials, PinoLogger } from '@novu/application-generic'; import { EnvironmentRepository, IntegrationEntity, IntegrationRepository } from '@novu/dal'; import { CHANNELS_WITH_PRIMARY } from '@novu/shared'; @@ -102,6 +109,14 @@ export class UpdateIntegration { throw new NotFoundException(`Entity with id ${command.integrationId} not found`); } + if (command.restrictToUserEnvironment && existingIntegration._environmentId !== command.userEnvironmentId) { + throw new ForbiddenException( + 'API key authentication is scoped to a single environment and cannot update an integration ' + + "that belongs to a different environment. Use an API key from the integration's environment, " + + 'or authenticate with a session token.' + ); + } + if (command.environmentId && command.environmentId !== existingIntegration._environmentId) { const targetEnvironment = await this.environmentRepository.findByIdAndOrganization( command.environmentId,
Leaderboard for this case
hard · 2 of 9 bots fully caught it (22% solve rate) · 22% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Drape (Deep Review) | solved | 1/1 | 100.0% | 3 | 0 |
| 2 | Drape (Review) | solved | 1/1 | 100.0% | 3 | 0 |
| 3 | Claude Code (Opus 5.5) | miss | 0/1 | 0.0% | 0 | 0 |
| 4 | Cubic | miss | 0/1 | 0.0% | 2 | 0 |
| 5 | cursor | miss | 0/1 | 0.0% | 0 | 0 |
| 6 | greptile | miss | 0/1 | 0.0% | 0 | 0 |
| 7 | Mjolnir (Opus 5.5) | miss | 0/1 | 0.0% | 0 | 0 |
| 8 | Mjolnir (Sonnet 5.5) | miss | 0/1 | 0.0% | 0 | 0 |
| 9 | qodo | miss | 0/1 | 0.0% | 0 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
The finding asks for an extra post-condition assertion in the test; it does not claim the code misbehaves. The guard runs before the create usecase, so no integration is created today. [grounded: diff] [consensus 5/5: minor=5]
This only asks to deduplicate test setup with helpers. It is a style/refactor suggestion, not a behavior defect. [grounded: diff] [consensus 5/5: minor=5]
raw comments (3)
<!-- cubic:v=6d88831c-ae74-408d-a6b5-f9b15e8d15e1 -->
<!-- cubic:review-run=e5b32904-1842-5c6f-af02-8fe1e7a91f67 -->
<!-- metadata:{"confidence":7} -->
P2: The "should forbid creating with a different `_environmentId`" test asserts only the 403 status and message, but not the post-condition that no integration was created in the production environment. The sibling update-integration.e2e.ts tests for the same API-key scoping rule also verify the target resource stayed untouched, so a regression in the guard's sequencing (assert later, create earlier) could slip through here. Capture the SendGrid integration count in the prod environment before the request and assert it is unchanged afterwards.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/app/integrations/e2e/create-integration.e2e.ts, line 669:
<comment>The "should forbid creating with a different `_environmentId`" test asserts only the 403 status and message, but not the post-condition that no integration was created in the production environment. The sibling update-integration.e2e.ts tests for the same API-key scoping rule also verify the target resource stayed untouched, so a regression in the guard's sequencing (assert later, create earlier) could slip through here. Capture the SendGrid integration count in the prod environment before the request and assert it is unchanged afterwards.</comment>
<file context>
@@ -648,6 +648,63 @@ describe('Create Integration - /integration (POST) #novu-v2', () => {
+ .set('authorization', `ApiKey ${session.apiKey}`)
+ .send(payload);
+
+ expect(body.statusCode).to.equal(403);
+ expect(body.message).to.contain('API key authentication is scoped to a single environment');
+ });
</file context>
```
</details>
<!-- cubic:v=30a7f5f0-48ab-40b2-b4f4-4a5cdcd37424 -->
<!-- cubic:review-run=e5b32904-1842-5c6f-af02-8fe1e7a91f67 -->
<!-- metadata:{"confidence":6} -->
P3: The four new tests repeat the same setup: the `prodEnv` look-up with `expect(prodEnv?._id).to.exist` appears three times, and the SendGrid integration creation block (same provider/channel/active flags, differing only in identifier and name) is duplicated four times. Extract a small helper (e.g. `createIntegration(name, identifier, environmentId)` and a `getProductionEnv()`) used by all four tests to cut ~60 duplicated lines and make each test's intent clearer.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/api/src/app/integrations/e2e/update-integration.e2e.ts, line 1035:
<comment>The four new tests repeat the same setup: the `prodEnv` look-up with `expect(prodEnv?._id).to.exist` appears three times, and the SendGrid integration creation block (same provider/channel/active flags, differing only in identifier and name) is duplicated four times. Extract a small helper (e.g. `createIntegration(name, identifier, environmentId)` and a `getProductionEnv()`) used by all four tests to cut ~60 duplicated lines and make each test's intent clearer.</comment>
<file context>
@@ -1020,4 +1020,127 @@ describe('Update Integration - /integrations/:integrationId (PUT) #novu-v2', ()
+ _organizationId: session.organization._id,
+ _environmentId: session.environment._id,
+ });
+ const prodEnv = await envRepository.findOne({ name: 'Production', _organizationId: session.organization._id });
+ expect(prodEnv?._id, 'Expected Production environment fixture').to.exist;
+
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**2 issues found** across 6 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/api/src/app/integrations/e2e/update-integration.e2e.ts">
<violation number="1" location="apps/api/src/app/integrations/e2e/update-integration.e2e.ts:1035">
P3: The four new tests repeat the same setup: the `prodEnv` look-up with `expect(prodEnv?._id).to.exist` appears three times, and the SendGrid integration creation block (same provider/channel/active flags, differing only in identifier and name) is duplicated four times. Extract a small helper (e.g. `createIntegration(name, identifier, environmentId)` and a `getProductionEnv()`) used by all four tests to cut ~60 duplicated lines and make each test's intent clearer.</violation>
</file>
<file name="apps/api/src/app/integrations/e2e/create-integration.e2e.ts">
<violation number="1" location="apps/api/src/app/integrations/e2e/create-integration.e2e.ts:669">
P2: The "should forbid creating with a different `_environmentId`" test asserts only the 403 status and message, but not the post-condition that no integration was created in the production environment. The sibling update-integration.e2e.ts tests for the same API-key scoping rule also verify the target resource stayed untouched, so a regression in the guard's sequencing (assert later, create earlier) could slip through here. Capture the SendGrid integration count in the prod environment before the request and assert it is unchanged afterwards.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/65/ai_pr_review_github_delivery_90b1fbe622aa1047a0533563572edb7f98dc528b045251c6d9d1e299dbbb7853?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F65)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_90b1fbe622aa1047a0533563572edb7f98dc528b045251c6d9d1e299dbbb7853:4f1ac94d53e50d76e510744363fb83cf42a88b3b:e5b32904-1842-5c6f-af02-8fe1e7a91f67 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The change adds API-key environment scoping to create and update but leaves the sibling set-primary mutation, which looks up the integration by id and organization only. So an API key can still change the primary integration in another environment. This is an incomplete application of the new scoping. [grounded: tree apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts] [consensus 3/3: valid=3]
The auto-configure endpoint is ExternalApiAccessible, has no environment check and looks up the integration only by id and org. So an API key from one environment can still rewrite another environment's configurations. The change's scoping for mutations doesn't cover this peer. [grounded: tree apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts] [consensus 3/3: valid=3]
raw comments (3)
**API key can still delete other environments' integrations**
The new environment scoping covers only update, but `RemoveIntegration` looks up the integration by id and organization only. So a Development API key can delete a Production integration in the same org. Pass the API-key restriction to RemoveIntegration and reject when the integration's `_environmentId` differs from `user.environmentId`.
```
apps/api/src/app/integrations/integrations.controller.ts:304 restrictToUserEnvironment: user.scheme === ApiAuthSchemeEnum.API_KEY,
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:112 if (command.restrictToUserEnvironment && existingIntegration._environmentId !== command.userEnvironmentId) {
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:113 throw new ForbiddenException(
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:114 'API key authentication is scoped to a single environment and cannot update an integration ' +
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:15 const existingIntegration = await this.integrationRepository.findOne({
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:16 _id: command.integrationId,
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:17 _organizationId: command.organizationId,
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:18 });
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:19 if (!existingIntegration) {
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:20 throw new NotFoundException(`Entity with id ${command.integrationId} not found`);
```
**API key can set primary in another environment**
`SetIntegrationAsPrimary` finds the integration by id and organization only, and the new API-key scoping isn't applied there. A key from one environment can therefore change which provider is primary in another environment. Reject API-key requests when the integration's `_environmentId` differs from `user.environmentId`.
```
apps/api/src/app/integrations/integrations.controller.ts:304 restrictToUserEnvironment: user.scheme === ApiAuthSchemeEnum.API_KEY,
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:112 if (command.restrictToUserEnvironment && existingIntegration._environmentId !== command.userEnvironmentId) {
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:113 throw new ForbiddenException(
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:114 'API key authentication is scoped to a single environment and cannot update an integration ' +
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:53 const existingIntegration = await this.integrationRepository.findOne({
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:54 _id: command.integrationId,
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:55 _organizationId: command.organizationId,
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:56 });
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:57 if (!existingIntegration) {
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:58 throw new NotFoundException(`Integration with id ${command.integrationId} not found`);
```
**API key can auto-configure another environment's integration**
`AutoConfigureIntegration` gets no environment at all and looks up the integration by id and organization only. A key from one environment can therefore rewrite another environment's webhook configuration, which the new update scoping is meant to prevent. Pass `user.environmentId` and the API-key flag through, and reject a mismatched integration environment.
```
apps/api/src/app/integrations/integrations.controller.ts:304 restrictToUserEnvironment: user.scheme === ApiAuthSchemeEnum.API_KEY,
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:112 if (command.restrictToUserEnvironment && existingIntegration._environmentId !== command.userEnvironmentId) {
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:113 throw new ForbiddenException(
apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts:114 'API key authentication is scoped to a single environment and cannot update an integration ' +
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:20 const encryptedIntegration = await this.integrationRepository.findOne({
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:21 _id: command.integrationId,
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:22 _organizationId: command.organizationId,
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:23 });
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:46 await this.integrationRepository.update(
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:47 {
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The PR scopes API-key callers to their own environment for create and update, but leaves the sibling mutating endpoint auto-configure unscoped. Its usecase looks up the integration by id and organization only, then updates its configurations. This is an incomplete-change gap in the same security boundary. [grounded: tree apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts] [consensus 3/3: valid=3]
The set-primary usecase receives environmentId but never uses it in the lookup, so an API key from one environment can change primary/priority in another. The PR now blocks this for PUT but not for this sibling endpoint, which makes it an incomplete change. [grounded: tree apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts] [consensus 3/3: valid=3]
raw comments (3)
**Auto-configure still crosses environments with API key**
`autoConfigureIntegration` passes only `organizationId`, and its usecase finds the integration by id and organization. So an API key from one environment can still modify an integration in another, which the PUT change now blocks. Pass the environment and API-key restriction into the command and filter the lookup by `_environmentId`.
```
apps/api/src/app/integrations/integrations.controller.ts:287 this.assertEnvironmentScopedForApiKey(user, body._environmentId);
apps/api/src/app/integrations/integrations.controller.ts:289 const canAccessCredentials = await this.canUserAccessCredentials(user);
apps/api/src/app/integrations/integrations.controller.ts:290 const integration = await this.updateIntegrationUsecase.execute(
apps/api/src/app/integrations/integrations.controller.ts:291 UpdateIntegrationCommand.create({
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:20 const encryptedIntegration = await this.integrationRepository.findOne({
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:21 _id: command.integrationId,
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:22 _organizationId: command.organizationId,
apps/api/src/app/integrations/usecases/auto-configure-integration/auto-configure-integration.usecase.ts:23 });
```
**Set-primary still crosses environments with API key**
`setIntegrationAsPrimary` passes `user.environmentId`, but the usecase ignores it and finds the integration by id and organization only. An API key from one environment can change primary and priority in another, which PUT now blocks. Filter the lookup by `command.environmentId` for API-key callers, or reject on mismatch.
```
apps/api/src/app/integrations/integrations.controller.ts:287 this.assertEnvironmentScopedForApiKey(user, body._environmentId);
apps/api/src/app/integrations/integrations.controller.ts:289 const canAccessCredentials = await this.canUserAccessCredentials(user);
apps/api/src/app/integrations/integrations.controller.ts:290 const integration = await this.updateIntegrationUsecase.execute(
apps/api/src/app/integrations/integrations.controller.ts:291 UpdateIntegrationCommand.create({
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:53 const existingIntegration = await this.integrationRepository.findOne({
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:54 _id: command.integrationId,
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:55 _organizationId: command.organizationId,
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:56 });
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:57 if (!existingIntegration) {
apps/api/src/app/integrations/usecases/set-integration-as-primary/set-integration-as-primary.usecase.ts:58 throw new NotFoundException(`Integration with id ${command.integrationId} not found`);
```
**Delete integration ignores API key environment scope**
`removeIntegration` still finds and deletes the integration by organization only. An API key from one environment can delete an integration in another environment, which the change now blocks for update. Restrict removal to the API key's environment, the way update now does.
```
apps/api/src/app/integrations/integrations.controller.ts:830 );
apps/api/src/app/integrations/integrations.controller.ts:831 }
apps/api/src/app/integrations/integrations.controller.ts:833 private assertEnvironmentScopedForApiKey(user: UserSessionData, requestedEnvironmentId?: string): void {
apps/api/src/app/integrations/integrations.controller.ts:834 if (user.scheme !== ApiAuthSchemeEnum.API_KEY) {
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:15 const existingIntegration = await this.integrationRepository.findOne({
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:16 _id: command.integrationId,
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:17 _organizationId: command.organizationId,
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:18 });
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:19 if (!existingIntegration) {
apps/api/src/app/integrations/usecases/remove-integration/remove-integration.usecase.ts:20 throw new NotFoundException(`Entity with id ${command.integrationId} not found`);
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
raw comments (1)
<h3>Greptile Summary</h3>
This PR prevents environment-scoped API keys from creating or updating integrations in another environment while retaining cross-environment behavior for session-token authentication.
- Validates explicitly requested environments at the integrations controller boundary.
- Verifies an existing integration belongs to the API key’s environment before mutation.
- Adds end-to-end coverage for allowed and forbidden create/update scenarios.
- Updates the trigger-event test to rely on the authenticated environment default.
<h3>Confidence Score: 5/5</h3>
The PR appears safe to merge; the environment-scope checks are applied before mutation and are covered by focused end-to-end tests.
No actionable failures remain: API-key requests are reliably identified, explicit and implicit environment selection is correctly constrained, and existing integration ownership is checked before update side effects.
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| apps/api/src/app/integrations/integrations.controller.ts | Adds controller-level API-key environment validation and enables ownership enforcement for updates. |
| apps/api/src/app/integrations/usecases/update-integration/update-integration.command.ts | Adds a validated flag indicating that an update must remain within the authenticated environment. |
| apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts | Rejects API-key updates of integrations belonging to another environment before any mutation occurs. |
| apps/api/src/app/integrations/e2e/create-integration.e2e.ts | Covers rejected cross-environment creation and accepted same/default-environment creation. |
| apps/api/src/app/integrations/e2e/update-integration.e2e.ts | Covers API-key ownership restrictions and preserves session-token cross-environment updates. |
| apps/api/src/app/events/e2e/trigger-event.e2e.ts | Removes an irrelevant Production environment lookup and lets integration creation default to the authenticated Development environment. |
</details>
<details open><summary><h3>Flowchart</h3></summary>
```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Integration create or update request] --> B{Authentication scheme}
B -->|API key| C{Requested environment matches key environment?}
C -->|No| D[Return 403 Forbidden]
C -->|Yes or omitted| E{Updating existing integration?}
E -->|Yes| F{Integration belongs to key environment?}
F -->|No| D
F -->|Yes| G[Perform operation]
E -->|No| G
B -->|Session token| G
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update apps/api/src/app/events/e2e/trigg..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/89f248bc73662500a4d9eb4545dfbdfc32c4808e) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64289000)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
raw comments (2)
<h3>PR Summary by Qodo</h3>
Enforce environment scoping for API key integration mutations
<code>🐞 Bug fix</code> <code>🧪 Tests</code> <code>🕐 20-40 Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Prevent API keys from creating or moving integrations into another environment.
>• Block updates to integrations outside the API key’s bound environment.
>• Preserve cross-environment updates for session authentication and add end-to-end coverage.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
sequenceDiagram
actor Client as API Client
participant Controller as Integrations Controller
participant Create as Create Use Case
participant Update as Update Use Case
participant Repo as Integration Repository
Client->>Controller: Create or update
alt API key targets another environment
Controller-->>Client: 403 Forbidden
else Requested environment allowed
alt Create integration
Controller->>Create: Key-scoped command
Create->>Repo: Persist integration
Repo-->>Create: Created integration
Create-->>Controller: Integration
else Update integration
Controller->>Update: Scoped update command
Update->>Repo: Load integration
Repo-->>Update: Existing integration
alt Existing environment differs
Update-->>Controller: 403 Forbidden
else Environment matches or JWT
Update->>Repo: Persist changes
Repo-->>Update: Updated integration
Update-->>Controller: Integration
end
end
Controller-->>Client: Integration response
end
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Reusable environment-scope guard</b></summary>
<dl>
<dd>
- ➕ Centralizes API-key environment authorization across endpoints
- ➕ Reduces the chance of inconsistent checks in future controllers
- ➖ Resource updates still require loading the integration to validate its stored environment
- ➖ Introduces broader authentication infrastructure changes for a focused fix
</dd>
</dl>
</details>
<details>
<summary><b>2. Environment-scoped repository lookup</b></summary>
<dl>
<dd>
- ➕ Restricts API-key updates directly through repository query criteria
- ➕ Can avoid passing an authorization boolean into the use case
- ➖ Typically returns 404 instead of the explicit 403 contract
- ➖ Still requires separate validation when the payload requests another environment
</dd>
</dl>
</details>
>**Recommendation:** Keep the PR’s layered approach for this focused security fix: controller validation blocks explicit cross-environment targets, while the use case protects integrations already stored elsewhere. Consider extracting a reusable environment-scope policy if the same authorization rule expands to additional resources.
</dd>
</dl>
</details>
<details>
<summary> Files changed (6) <code> +236 / -10 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Bug fix (3) <code> +56 / -2 </code></summary>
<dl>
<dd>
<details>
<summary>integrations.controller.ts<code>Reject cross-environment integration mutations from API keys</code> <code>+20/-0</code></summary>
<br/>
>Reject cross-environment integration mutations from API keys
>
><pre>
>• Validates requested environment IDs against the environment bound to API-key authentication for create and update requests. Update commands now indicate when stored integration ownership must also be restricted.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/97/files#diff-f5bf225ee35dfe8f6a033aa141337bd3d5394076cfd2cb27a0015568c70867c3'>apps/api/src/app/integrations/integrations.controller.ts</a>
</details>
<details>
<summary>update-integration.command.ts<code>Add API-key environment restriction to update commands</code> <code>+20/-1</code></summary>
<br/>
>Add API-key environment restriction to update commands
>
><pre>
>• Introduces an optional validated boolean that instructs the update use case to enforce the authenticated user environment against the existing integration.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/97/files#diff-51e74902d26f0ca18c46f58579b95f4d972f8f2cb747d5d9ff0864a04d6e3df7'>apps/api/src/app/integrations/usecases/update-integration/update-integration.command.ts</a>
</details>
<details>
<summary>update-integration.usecase.ts<code>Protect stored integrations from cross-environment API-key updates</code> <code>+16/-1</code></summary>
<br/>
>Protect stored integrations from cross-environment API-key updates
>
><pre>
>• Checks the existing integration’s environment before applying a restricted update. Returns an explicit forbidden response when an API key attempts to mutate an integration belonging to another environment.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/97/files#diff-12b817183e64eb3c166b832f4b66f95bc6e89c25d6ef9ab6cdc6e56d2b0ea929'>apps/api/src/app/integrations/usecases/update-integration/update-integration.usecase.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Tests (3) <code> +180 / -8 </code></summary>
<dl>
<dd>
<details>
<summary>trigger-event.e2e.ts<code>Keep integration override test within the API key environment</code> <code>+0/-8</code></summary>
<br/>
>Keep integration override test within the API key environment
>
><pre>
>• Removes the Production environment lookup and explicit environment target when creating the Mailgun integration. The client now defaults creation to the environment bound to its API key.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/97/files#diff-4856797a94a026549b0543a31180fba737d626f993351ffec41b44b3d150dc04'>apps/api/src/app/events/e2e/trigger-event.e2e.ts</a>
</details>
<details>
<summary>create-integration.e2e.ts<code>Cover API-key environment scoping during integration creation</code> <code>+57/-0</code></summary>
<br/>
>Cover API-key environment scoping during integration creation
>
><pre>
>• Adds end-to-end cases proving that API keys cannot create integrations in another environment. Also verifies omitted and matching environment IDs resolve successfully to the key’s environment.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/97/files#diff-956aee22bb9ff788d51d58d369545e245437bdbe2246a0d563612a3993285684'>apps/api/src/app/integrations/e2e/create-integration.e2e.ts</a>
</details>
<details>
<summary>update-integration.e2e.ts<code>Cover API-key environment scoping during integration updates</code> <code>+123/-0</code></summary>
<br/>
>Cover API-key environment scoping during integration updates
>
><pre>
>• Adds coverage for rejected cross-environment targets and rejected updates to integrations stored outside the API key environment. Confirms same-environment API-key updates and cross-environment session-authenticated updates remain allowed.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/97/files#diff-fb953e3752bcae04b6b41cbfa8b0e1cbf89fef5b298745c947b8773b9ecb2d8b'>apps/api/src/app/integrations/e2e/update-integration.e2e.ts</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<h3>Code Review by Qodo</h3>
<code>🐞 Bugs (0)</code> <code>📘 Rule violations (0)</code> <code>📎 Requirement gaps (0)</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<img src="https://www.qodo.ai/wp-content/uploads/2025/06/qodo-anteater.svg" width="20%">
<h3>Great, no issues found!</h3>
Qodo reviewed your code and found no material issues that require review
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:start -->
<details>
<summary><strong>Tip of the day</strong></summary>
<br/>
<pre>💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper</pre>
<a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:end -->
<!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/bf9d919bb581b856b1934b5babcbc69cf35d6f53 -->
<a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>