Skip to content

Backend frontend agent#1848

Merged
Artuomka merged 6 commits into
mainfrom
backend-frontend_agent
Jun 22, 2026
Merged

Backend frontend agent#1848
Artuomka merged 6 commits into
mainfrom
backend-frontend_agent

Conversation

@Artuomka

@Artuomka Artuomka commented Jun 22, 2026

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Added an AI-backed endpoint to list tables available from a connection, returning only the ones the user has permission to read.
    • Added an endpoint to fetch company subscription information.
    • Improved CORS handling for public /table/crud routes with safer origin reflection, credential support, and correct OPTIONS preflight responses.
  • Tests
    • Expanded E2E coverage for /table/crud CORS, including authenticated/unauthenticated behavior and edge cases for malformed Origin and request headers.

Copilot AI review requested due to automatic review settings June 22, 2026 11:04
@Artuomka Artuomka enabled auto-merge June 22, 2026 11:04
@Artuomka Artuomka disabled auto-merge June 22, 2026 11:04
@coderabbitai

coderabbitai Bot commented Jun 22, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 73211b53-296c-4e78-82b5-55aee68a6c76

📥 Commits

Reviewing files that changed from the base of the PR and between 3c7f82d and a0f985e.

📒 Files selected for processing (1)
  • backend/src/main.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/main.ts

📝 Walkthrough

Walkthrough

The PR adds two agents microservice endpoints—POST /ai/data/:connectionId/tables (returns permission-filtered table names) and POST /company/subscription-info (returns SaaS subscription metadata)—with full use-case, DI token, module, and controller wiring. It also introduces publicCrudCorsMiddleware, an Express middleware that reflects Origin with credential support on /table/crud routes, registered before global CORS, with E2E test coverage.

Changes

Agents Microservice: New Use-Cases and Endpoints

Layer / File(s) Summary
Response DTOs, request DS, interfaces, and DI token
backend/src/common/data-injection.tokens.ts, backend/src/microservices/agents-microservice/data-structures/agents-responses.ds.ts, backend/src/microservices/agents-microservice/data-structures/agents.ds.ts, backend/src/microservices/agents-microservice/dto/agents-company.dtos.ts, backend/src/microservices/agents-microservice/use-cases/agents-use-cases.interface.ts
AiConnectionTablesRO and CompanySubscriptionInfoRO response classes, GetCompanySubscriptionInfoDs/GetCompanySubscriptionInfoDto request shapes, IGetAiConnectionTables and IGetCompanySubscriptionInfo interfaces, and AGENTS_GET_AI_CONNECTION_TABLES DI token are defined.
Use-case implementations
backend/src/microservices/agents-microservice/use-cases/get-ai-connection-tables.use.case.ts, backend/src/microservices/agents-microservice/use-cases/get-company-subscription-info.use.case.ts
GetAiConnectionTablesUseCase establishes an AI connection, fetches tables, and filters by per-table Cedar read permissions. GetCompanySubscriptionInfoUseCase loads the user's company, handles non-SaaS/test shortcuts, throws NotFoundException if missing, and queries the SaaS gateway for subscription details.
Controller endpoints and module DI wiring
backend/src/microservices/agents-microservice/agents.controller.ts, backend/src/microservices/agents-microservice/agents.module.ts
AgentsController gains POST /ai/data/:connectionId/tables and POST /company/subscription-info handlers with constructor-injected use-cases. AgentsModule registers both use-cases as providers under their UseCaseType tokens.

Public CRUD CORS Middleware

Layer / File(s) Summary
Middleware implementation, bootstrap registration, and E2E tests
backend/src/middlewares/public-crud-cors.middleware.ts, backend/src/main.ts, backend/test/ava-tests/non-saas-tests/non-saas-table-pure-crud-operations-e2e.test.ts
publicCrudCorsMiddleware reflects Origin with credential support for /table/crud routes, validates origin and header input against strict regexes, returns 204 for OPTIONS preflight, and rejects malformed origins/headers. Registered in bootstrap() before app.enableCors(). E2E tests validate preflight, authenticated requests, absent-Origin behavior, non-matching route isolation, and edge cases for malformed input.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant AgentsController
  participant GetAiConnectionTablesUseCase
  participant setupAiConnection
  participant CedarPermissionsService

  Client->>AgentsController: POST /ai/data/:connectionId/tables
  AgentsController->>GetAiConnectionTablesUseCase: execute({ connectionId, userId, masterPassword })
  GetAiConnectionTablesUseCase->>setupAiConnection: create/access connection
  setupAiConnection-->>GetAiConnectionTablesUseCase: dataAccessObject, foundConnection
  GetAiConnectionTablesUseCase->>setupAiConnection: getTablesFromDB()
  setupAiConnection-->>GetAiConnectionTablesUseCase: raw table names
  loop for each table name
    GetAiConnectionTablesUseCase->>CedarPermissionsService: improvedCheckTableRead(userId, connectionId, tableName)
    CedarPermissionsService-->>GetAiConnectionTablesUseCase: allowed: boolean
  end
  GetAiConnectionTablesUseCase-->>AgentsController: { tables: readableTableNames }
  AgentsController-->>Client: AiConnectionTablesRO
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • rocket-admin/rocketadmin#1841: Creates the agents microservice scaffold (AgentsController, AgentsModule, UseCaseType agent entries) that this PR extends with two new endpoints and use-cases.

Suggested reviewers

  • gugu
  • lyubov-voloshko

🐇 Two new paths for the agents to roam,
Tables and subscriptions—now they have a home.
CORS stands guard on the CRUD little gate,
Reflecting your Origin—credentials await!
With preflight returning a tidy 204,
This bunny hops onward, then bounds out the door! 🚀

🚥 Pre-merge checks | ✅ 4 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Backend frontend agent' is vague and does not clearly convey the specific changes made in this pull request. Use a more descriptive title that captures the main objective, such as 'Add agent endpoints for AI connections and subscription info' or 'Implement CORS middleware and agent use cases for table operations'.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Security Check ✅ Passed PR implements security best practices: JWT authentication via SaaSAuthMiddleware, Cedar permission checks for table access, CORS header injection protection with strict regex validation, UUID input...

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch backend-frontend_agent

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR extends the backend to support (1) wildcard CORS handling for the public /table/crud endpoints and (2) new “agents microservice” endpoints/use-cases for AI table discovery and company subscription metadata, aligning the backend API with agent-driven workflows.

Changes:

  • Added an Express middleware to reflect arbitrary origins for /table/crud routes and short-circuit OPTIONS preflights.
  • Expanded the agents microservice with new endpoints/use-cases to list readable tables for a connection and to fetch company subscription metadata.
  • Added/updated AVA e2e coverage to validate the new CORS behavior on /table/crud routes.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
backend/test/ava-tests/non-saas-tests/non-saas-table-pure-crud-operations-e2e.test.ts Registers the new CORS middleware in test app setup and adds e2e assertions for preflight + credentialed requests.
backend/src/middlewares/public-crud-cors.middleware.ts Implements wildcard/reflected-origin CORS handling specifically for /table/crud (including OPTIONS short-circuit).
backend/src/main.ts Registers the new CORS middleware before global enableCors() so /table/crud can accept arbitrary origins.
backend/src/common/data-injection.tokens.ts Adds new DI tokens for the agents microservice use-cases.
backend/src/microservices/agents-microservice/agents.module.ts Wires new use-cases into the agents module providers.
backend/src/microservices/agents-microservice/agents.controller.ts Adds endpoints for connection table listing and company subscription info.
backend/src/microservices/agents-microservice/use-cases/get-ai-connection-tables.use.case.ts New use-case to list tables and filter them by Cedar read permission.
backend/src/microservices/agents-microservice/use-cases/get-company-subscription-info.use.case.ts New use-case to resolve subscription metadata via the SaaS gateway.
backend/src/microservices/agents-microservice/use-cases/agents-use-cases.interface.ts Adds interfaces for the new use-cases.
backend/src/microservices/agents-microservice/dto/agents-company.dtos.ts Adds DTO for subscription info request.
backend/src/microservices/agents-microservice/data-structures/agents.ds.ts Adds DS for subscription info input.
backend/src/microservices/agents-microservice/data-structures/agents-responses.ds.ts Adds response models for AI table list and subscription info.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +27 to +35
const { foundConnection, dataAccessObject } = await setupAiConnection(
this._dbContext,
connectionId,
masterPassword,
userId,
);

const tables = await dataAccessObject.getTablesFromDB();
const tableNames = tables.map((table) => table.tableName?.trim()).filter((name): name is string => Boolean(name));
Comment on lines +37 to +41
const readableFlags = await Promise.all(
tableNames.map((tableName) =>
this.cedarPermissions.improvedCheckTableRead(userId, foundConnection.id, tableName),
),
);
Comment on lines +56 to +57
@ApiPropertyOptional({ nullable: true, description: 'FREE_PLAN | TEAM_PLAN | ENTERPRISE_PLAN | ANNUAL_* | null' })
subscriptionLevel: string | null;

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
backend/src/middlewares/public-crud-cors.middleware.ts (1)

24-24: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Handle potential string array from header value.

The type assertion as string doesn't account for the fact that req.headers['access-control-request-headers'] could be string[] if the header is sent multiple times. While uncommon for this specific header, defensive handling would be more robust.

♻️ Proposed refactor to handle array values
 res.header(
 	'Access-Control-Allow-Headers',
-	(req.headers['access-control-request-headers'] as string) ??
+	(Array.isArray(req.headers['access-control-request-headers']) 
+		? req.headers['access-control-request-headers'][0] 
+		: req.headers['access-control-request-headers']) ??
 		'Content-Type, Authorization, x-api-key, masterpwd',
 );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@backend/src/middlewares/public-crud-cors.middleware.ts` at line 24, The type
assertion `as string` on the access-control-request-headers value does not
account for the possibility that req.headers values can be either string or
string[]. Modify the handling to check whether the value is an array and handle
both cases appropriately, either by joining array elements with a comma or by
selecting the appropriate value before using it as a string. This defensive
approach will prevent potential runtime issues when the header is sent multiple
times.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@backend/src/microservices/agents-microservice/use-cases/get-company-subscription-info.use.case.ts`:
- Around line 40-43: In the get-company-subscription-info.use.case.ts file,
locate the null check for the company variable returned from
this._dbContext.companyInfoRepository.findCompanyInfoByUserId(userId). The
current implementation throws HttpStatus.FORBIDDEN when company is not found,
but this should be changed to HttpStatus.NOT_FOUND since the error message is
Messages.COMPANY_NOT_FOUND, which represents missing data rather than an
authorization issue. Replace HttpStatus.FORBIDDEN with HttpStatus.NOT_FOUND in
the throw statement within the if (!company) block.

In `@backend/src/middlewares/public-crud-cors.middleware.ts`:
- Around line 22-26: The Access-Control-Allow-Headers response header in the
public-crud-cors.middleware.ts file reflects the access-control-request-headers
value from the request without sanitization, creating an HTTP Response Splitting
vulnerability. Sanitize the reflected header value by removing CRLF characters
(\r and \n) before using it in the res.header call. Apply a sanitization
function or string replacement to strip these characters from the
req.headers['access-control-request-headers'] value to prevent header injection
attacks.

---

Nitpick comments:
In `@backend/src/middlewares/public-crud-cors.middleware.ts`:
- Line 24: The type assertion `as string` on the access-control-request-headers
value does not account for the possibility that req.headers values can be either
string or string[]. Modify the handling to check whether the value is an array
and handle both cases appropriately, either by joining array elements with a
comma or by selecting the appropriate value before using it as a string. This
defensive approach will prevent potential runtime issues when the header is sent
multiple times.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: f6172f7a-8af9-4b9d-ac5a-404367beb3b8

📥 Commits

Reviewing files that changed from the base of the PR and between 6c46258 and 10dbf69.

📒 Files selected for processing (12)
  • backend/src/common/data-injection.tokens.ts
  • backend/src/main.ts
  • backend/src/microservices/agents-microservice/agents.controller.ts
  • backend/src/microservices/agents-microservice/agents.module.ts
  • backend/src/microservices/agents-microservice/data-structures/agents-responses.ds.ts
  • backend/src/microservices/agents-microservice/data-structures/agents.ds.ts
  • backend/src/microservices/agents-microservice/dto/agents-company.dtos.ts
  • backend/src/microservices/agents-microservice/use-cases/agents-use-cases.interface.ts
  • backend/src/microservices/agents-microservice/use-cases/get-ai-connection-tables.use.case.ts
  • backend/src/microservices/agents-microservice/use-cases/get-company-subscription-info.use.case.ts
  • backend/src/middlewares/public-crud-cors.middleware.ts
  • backend/test/ava-tests/non-saas-tests/non-saas-table-pure-crud-operations-e2e.test.ts

Comment thread backend/src/middlewares/public-crud-cors.middleware.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@backend/test/ava-tests/non-saas-tests/non-saas-table-pure-crud-operations-e2e.test.ts`:
- Around line 750-762: The test callback parameters in the test.serial function
for "a malformed Origin is not reflected back (header-injection guard)" and the
other test at line 766 are missing required TypeScript type annotations. Add the
type annotation `ExecutionContext` to the `t` parameter and add the return type
`: Promise<void>` to the async callback function signature in both test.serial
calls to comply with TypeScript coding guidelines.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0c692645-1b89-40c2-9808-d07636a0d680

📥 Commits

Reviewing files that changed from the base of the PR and between 10dbf69 and 3c7f82d.

📒 Files selected for processing (3)
  • backend/src/microservices/agents-microservice/use-cases/get-company-subscription-info.use.case.ts
  • backend/src/middlewares/public-crud-cors.middleware.ts
  • backend/test/ava-tests/non-saas-tests/non-saas-table-pure-crud-operations-e2e.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/src/microservices/agents-microservice/use-cases/get-company-subscription-info.use.case.ts
  • backend/src/middlewares/public-crud-cors.middleware.ts

Comment on lines +750 to +762
test.serial(`${currentTest} a malformed Origin is not reflected back (header-injection guard)`, async (t) => {
const malformedOrigin = 'https://evil.example.com/path with spaces';

const res = await request(app.getHttpServer())
.options(`/table/crud/${faker.string.uuid()}?tableName=whatever`)
.set('Origin', malformedOrigin)
.set('Access-Control-Request-Method', 'POST');

// Still answered as a preflight, but a value that does not match a valid origin is dropped, not echoed.
t.is(res.status, 204);
t.is(res.headers['access-control-allow-origin'], undefined);
t.is(res.headers['access-control-allow-credentials'], undefined);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify untyped AVA async callback params in TS tests
rg -nP --type=ts 'test\.serial\([^)]*,\s*async\s*\(\s*[a-zA-Z_]\w*\s*\)\s*=>'

Repository: rocket-admin/rocketadmin

Length of output: 50381


Add type annotations to AVA test callback parameters.

The test callbacks at lines 750 and 766 lack required TypeScript type annotations. Add t: ExecutionContext and : Promise<void> to each callback signature per the TypeScript coding guidelines.

Suggested fix
-import test from 'ava';
+import test, { type ExecutionContext } from 'ava';

-test.serial(`${currentTest} a malformed Origin is not reflected back (header-injection guard)`, async (t) => {
+test.serial(
+	`${currentTest} a malformed Origin is not reflected back (header-injection guard)`,
+	async (t: ExecutionContext): Promise<void> => {

Apply the same annotations to both test callbacks in the file.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@backend/test/ava-tests/non-saas-tests/non-saas-table-pure-crud-operations-e2e.test.ts`
around lines 750 - 762, The test callback parameters in the test.serial function
for "a malformed Origin is not reflected back (header-injection guard)" and the
other test at line 766 are missing required TypeScript type annotations. Add the
type annotation `ExecutionContext` to the `t` parameter and add the return type
`: Promise<void>` to the async callback function signature in both test.serial
calls to comply with TypeScript coding guidelines.

Source: Coding guidelines

@Artuomka Artuomka enabled auto-merge June 22, 2026 11:36
@Artuomka Artuomka merged commit 8d22503 into main Jun 22, 2026
16 of 17 checks passed
@Artuomka Artuomka deleted the backend-frontend_agent branch June 22, 2026 11:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants