From 56544940e606bec41d544c727955df63b2ce4817 Mon Sep 17 00:00:00 2001 From: Abhishek Chatterjee Date: Sun, 22 Nov 2026 23:50:28 +0530 Subject: [PATCH 1/2] bug(routes): #232: support query filters and ssp in delete api --- ross/.dockerignore | 15 +++ ross/docs/docs/application.md | 29 +++++ ross/docs/docs/database/models.md | 8 +- ross/e2e/delete-ssp.spec.ts | 187 ++++++++++++++++++++++++++++++ ross/src/routes/models/delete.ts | 48 +++++++- ross/tests/routes/delete.test.ts | 166 +++++++++++++++++++++++++- 6 files changed, 448 insertions(+), 5 deletions(-) create mode 100644 ross/.dockerignore create mode 100644 ross/e2e/delete-ssp.spec.ts diff --git a/ross/.dockerignore b/ross/.dockerignore new file mode 100644 index 00000000..38f3f195 --- /dev/null +++ b/ross/.dockerignore @@ -0,0 +1,15 @@ +node_modules +.git +.github +.husky +build +coverage +docs +e2e +examples +playwright-report +test-results +.ross +.migrations +*.db +*.log diff --git a/ross/docs/docs/application.md b/ross/docs/docs/application.md index 745ef46c..3403ff32 100644 --- a/ross/docs/docs/application.md +++ b/ross/docs/docs/application.md @@ -308,6 +308,35 @@ You reference a magic variable in your API configuration using double brackets: When a user calls `POST /api/v1/projects`, ROSS strips `orgId` and `tenantId` from client validation, automatically injects `"orgId": "acme-corp"` and `"tenantId": 42` into the request body on the server side, and saves them to the database. The client cannot spoof or override these fields. +#### Scoping DELETE and GET Operations with Query SSP + +To enforce multi-tenant isolation or ownership scoping on `GET` and `DELETE` operations, configure `serverSideParams` with `type: "query"` referencing filter operators such as `_eq`: + +```json +{ + "apis": { + "model:v1:todos:id:delete": { + "authorization": true, + "serverSideParams": [ + { + "name": "owner_id_eq", + "type": "query", + "value": "[[userId]]" + } + ] + } + } +} +``` + +When a user calls `DELETE /api/v1/todos/id/42`, ROSS injects `owner_id_eq` with the authenticated user's ID into the query filters. The executed SQL statement becomes: + +```sql +DELETE FROM "todos" WHERE "id" = 42 AND "owner_id" = ; +``` + +Even if a malicious user passes another user's record ID, the deletion query will not match any rows and the target record remains safe. + #### Built-in vs. Custom Magic Variables ROSS includes built-in magic variables derived from the authenticated session: diff --git a/ross/docs/docs/database/models.md b/ross/docs/docs/database/models.md index 2dd60db1..2788c78a 100644 --- a/ross/docs/docs/database/models.md +++ b/ross/docs/docs/database/models.md @@ -194,7 +194,13 @@ The `apis` array controls which field-specific REST endpoints ROSS generates: | `"index"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `GET /api/v1///:` | Look up records by this field's value. Returns a single object if unique, or a paginated array if non-unique. | | `"search"` | `string` | `GET /api/v1//search/?_search=` | Case-insensitive substring search matching text on this specific field. | | `"edit"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `PATCH` / `PUT /api/v1///:` | Update records matching the specified field parameter. | -| `"delete"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `DELETE /api/v1///:` | Delete records matching the specified field parameter. | +| `"delete"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `DELETE /api/v1///:` | Delete records matching the specified field parameter. Supports query filters (e.g. `?status_eq=inactive`) to further constrain targeted records. | + +:::info[DELETE Endpoints Support Query Filters] + +Like listing and edit endpoints, `DELETE /api/v1///:` supports standard query filters for any other field on the model that defines `query` operations (e.g., `DELETE /api/v1/todos/id/42?owner_id_eq=7`). This enables scoping deletions by state or enforcing row-level ownership validation via Server-Side Parameters (`serverSideParams`). + +::: :::info[Search Is Restricted to String Fields] diff --git a/ross/e2e/delete-ssp.spec.ts b/ross/e2e/delete-ssp.spec.ts new file mode 100644 index 00000000..cb3bc1ec --- /dev/null +++ b/ross/e2e/delete-ssp.spec.ts @@ -0,0 +1,187 @@ +import {expect, test} from '@playwright/test'; + +import {AppConfigInput} from '@/interfaces/config'; + +import {createE2EServer, E2EServer} from './helpers/server'; + +const deleteSspE2EConfig: AppConfigInput = { + application: { + name: 'Rocket E2E - Delete SSP', + logLevel: 'warn', + }, + infrastructure: { + database: { + engine: 'sqlite', + connection: { + url: './e2e/.data/test-delete-ssp.db', + }, + }, + }, + authentication: { + enabled: true, + jwtSecret: 'super-secret-jwt-key-for-delete-ssp-testing-32chars', + userModel: { + modelName: 'users', + idField: 'id', + providerField: 'provider', + }, + providers: [ + { + type: 'up-auth', + config: { + fields: { + usernameField: 'email', + passwordField: 'password', + }, + }, + }, + ], + }, + data: { + models: { + users: { + fields: { + id: { + type: 'integer', + primaryKey: true, + autoIncrement: true, + nullable: false, + }, + email: { + type: 'string', + unique: true, + nullable: false, + }, + password: { + type: 'string', + nullable: false, + secret: true, + }, + provider: { + type: 'string', + nullable: true, + }, + }, + }, + todos: { + fields: { + id: { + type: 'integer', + primaryKey: true, + autoIncrement: true, + nullable: false, + apis: ['delete', 'index'], + }, + title: { + type: 'string', + nullable: false, + }, + owner_id: { + type: 'integer', + nullable: false, + query: ['eq'], + }, + }, + }, + }, + }, + apis: { + 'model.v1.todos.id.delete': { + enabled: true, + authorization: true, + serverSideParams: [ + { + name: 'owner_id_eq', + type: 'query', + value: '[[userId]]', + }, + ], + }, + 'model.v1.todos.unknown.getAll': { + enabled: true, + authorization: true, + }, + }, +}; + +test.describe.serial('E2E: DELETE API with SSP ownership scoping', () => { + let server: E2EServer; + let user1Token: string; + let user2Token: string; + + test.beforeAll(async () => { + server = await createE2EServer(deleteSspE2EConfig); + + user1Token = server.app.jwt.sign({id: 1, email: 'user1@example.com'}); + user2Token = server.app.jwt.sign({id: 2, email: 'user2@example.com'}); + }); + + test.afterAll(async () => { + if (server) { + await server.cleanup(); + } + }); + + test.beforeEach(async () => { + await server.app.db.query('DELETE FROM todos;'); + await server.app.db.query( + 'INSERT INTO todos (id, title, owner_id) VALUES (?, ?, ?), (?, ?, ?)', + [1, 'User 1 Todo', 1, 2, 'User 2 Todo', 2], + ); + }); + + test('User 1 cannot delete User 2 todo (scoped by [[userId]])', async () => { + const res = await server.request.delete('/api/v1/todos/id/2', { + headers: { + authorization: `Bearer ${user1Token}`, + 'content-type': 'text/plain', + }, + }); + + expect(res.status()).toBe(204); + + // Todo 2 must still exist in the database because owner_id was scoped to 1 + const checkRes = await server.app.db.query<{id: number}>( + 'SELECT id FROM todos WHERE id = ?', + [2], + ); + expect(checkRes.rows.length).toBe(1); + expect(checkRes.rows[0].id).toBe(2); + }); + + test('User 1 can delete their own todo', async () => { + const res = await server.request.delete('/api/v1/todos/id/1', { + headers: { + authorization: `Bearer ${user1Token}`, + 'content-type': 'text/plain', + }, + }); + + expect(res.status()).toBe(204); + + // Todo 1 must be deleted from the database + const checkRes = await server.app.db.query<{id: number}>( + 'SELECT id FROM todos WHERE id = ?', + [1], + ); + expect(checkRes.rows.length).toBe(0); + }); + + test('User 2 can delete their own todo', async () => { + const res = await server.request.delete('/api/v1/todos/id/2', { + headers: { + authorization: `Bearer ${user2Token}`, + 'content-type': 'text/plain', + }, + }); + + expect(res.status()).toBe(204); + + // Todo 2 must be deleted from the database + const checkRes = await server.app.db.query<{id: number}>( + 'SELECT id FROM todos WHERE id = ?', + [2], + ); + expect(checkRes.rows.length).toBe(0); + }); +}); diff --git a/ross/src/routes/models/delete.ts b/ross/src/routes/models/delete.ts index 4515b097..ef7fb63a 100644 --- a/ross/src/routes/models/delete.ts +++ b/ross/src/routes/models/delete.ts @@ -1,12 +1,14 @@ import {FastifyInstance, FastifyReply, FastifyRequest} from 'fastify'; import {getApiRouteTargets, ResolvedApiPolicy} from '@/lib/config/api'; +import {buildFilterQueryProperties} from '@/lib/schema/query'; import { buildSecurityArray, getResponseStructureSchema, } from '@/lib/schema/response'; -import {mapDataTypeToJsonSchema} from '@/lib/schema/types'; +import {getPublicFields, mapDataTypeToJsonSchema} from '@/lib/schema/types'; import {buildPreValidation} from '@/lib/server/prevalidation'; +import {applyFilters} from '@/lib/sql/filters'; import { ModelConfig, @@ -94,16 +96,34 @@ function registerDeleteEndpoint( }, async (request: FastifyRequest, reply: FastifyReply) => { const {[fieldName]: value} = request.params as Record; + const queryParams = request.query as Record; const tableName = modelName; const columnName = fieldName; - const query = `DELETE FROM "${tableName}" WHERE "${columnName}" = $1;`; + const whereClauses: string[] = []; + const values: unknown[] = []; + let paramIndex = 1; + + whereClauses.push(`"${columnName}" = $${paramIndex++}`); + values.push(value); + + const { + whereClauses: filterClauses, + values: filterValues, + nextParamIndex, + } = applyFilters(queryParams, paramIndex, [fieldName]); + + whereClauses.push(...filterClauses); + values.push(...filterValues); + paramIndex = nextParamIndex; + + const query = `DELETE FROM "${tableName}" WHERE ${whereClauses.join(' AND ')};`; let tx; try { tx = await app.db.beginTransaction(); - await tx.query(query, [value]); + await tx.query(query, values); await tx.commit(); } catch (err) { if (tx) await tx.rollback().catch(() => {}); @@ -127,6 +147,20 @@ function generateSchema( ) { const paramSchema = mapDataTypeToJsonSchema(field.type); + const effectiveQueries = policy.supportedQueries; + const queryProperties: Record = {}; + const fields = policy.bypassSecret + ? Object.entries(model.fields) + : getPublicFields(model); + + for (const [fName, f] of fields) { + if (fName === fieldName) continue; + Object.assign( + queryProperties, + buildFilterQueryProperties(fName, f, effectiveQueries), + ); + } + const schema: Record = { summary: `Delete ${capitalizeFirstLetter(modelName)} records by ${fieldName}`, description: `Delete records from ${capitalizeFirstLetter(modelName)} table where ${fieldName} matches the provided value`, @@ -145,6 +179,14 @@ function generateSchema( response: getResponseStructureSchema([204], {}), }; + if (Object.keys(queryProperties).length > 0) { + schema.querystring = { + type: 'object', + properties: queryProperties, + additionalProperties: false, + }; + } + const security = buildSecurityArray(config, policy.authorization); if (security.length > 0) { diff --git a/ross/tests/routes/delete.test.ts b/ross/tests/routes/delete.test.ts index 2c20d508..db639d04 100644 --- a/ross/tests/routes/delete.test.ts +++ b/ross/tests/routes/delete.test.ts @@ -1,6 +1,10 @@ import {beforeEach, describe, expect, test} from 'vitest'; -import {AuthenticationConfig, ModelConfig} from '@/interfaces/config'; +import { + ApisConfig, + AuthenticationConfig, + ModelConfig, +} from '@/interfaces/config'; import {pgClientQueryMock, pgQueryMock} from '@tests/helpers/db-mocks'; import {createTestApp, pgConfig} from '@tests/helpers/test-app'; @@ -422,4 +426,164 @@ describe('test delete api', () => { await fastify.close(); }); }); + + describe('query filters and server-side params', () => { + const todosModel: Record = { + todos: { + fields: { + id: {type: 'integer', primaryKey: true, apis: ['delete']}, + title: {type: 'string'}, + status: {type: 'string', query: ['eq']}, + authorId: {type: 'integer', query: ['eq']}, + secretNote: {type: 'string', secret: true, query: ['eq']}, + }, + }, + }; + + const sspApis: ApisConfig = { + 'model.v1.todos.id.delete': { + enabled: true, + authorization: true, + serverSideParams: [ + {type: 'query', name: 'authorId_eq', value: '[[userId]]'}, + ], + }, + }; + + test('should apply query filter to delete query', async () => { + const fastify = await createTestApp(pgConfig, todosModel); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/id/42?status_eq=archived', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "id" = $1 AND "status" = $2;', + [42, 'archived'], + ); + + await fastify.close(); + }); + + test('should apply multiple query filters to delete query', async () => { + const fastify = await createTestApp(pgConfig, todosModel); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/id/42?authorId_eq=7&status_eq=archived', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "id" = $1 AND "authorId" = $2 AND "status" = $3;', + [42, 7, 'archived'], + ); + + await fastify.close(); + }); + + test('should ignore unknown query params that do not match filter patterns', async () => { + const fastify = await createTestApp(pgConfig, todosModel); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/id/42?unknown_param=foo', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "id" = $1;', + [42], + ); + + await fastify.close(); + }); + + test('should inject [userId] as a query filter via SSP', async () => { + const fastify = await createTestApp( + pgConfig, + todosModel, + sspApis, + undefined, + upAuthConfig, + ); + const token = fastify.jwt.sign({id: 7, email: 'alice@example.com'}); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/id/42', + headers: {authorization: `Bearer ${token}`}, + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "id" = $1 AND "authorId" = $2;', + [42, 7], + ); + + await fastify.close(); + }); + + test('should override client query value with server-side SSP', async () => { + const fastify = await createTestApp( + pgConfig, + todosModel, + sspApis, + undefined, + upAuthConfig, + ); + const token = fastify.jwt.sign({id: 7, email: 'alice@example.com'}); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/id/42?authorId_eq=999', + headers: {authorization: `Bearer ${token}`}, + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "id" = $1 AND "authorId" = $2;', + [42, 7], + ); + + await fastify.close(); + }); + + test('should reject invalid query param type with 400', async () => { + const fastify = await createTestApp(pgConfig, todosModel); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/id/42?authorId_eq=not-an-integer', + }); + + expect(response.statusCode).toBe(400); + expect(pgClientQueryMock).not.toHaveBeenCalled(); + + await fastify.close(); + }); + + test('should include secret fields in query filter when bypassSecret is true', async () => { + const fastify = await createTestApp(pgConfig, todosModel, { + 'model.v1.todos.id.delete': { + bypassSecret: true, + }, + }); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/id/42?secretNote_eq=foo', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "id" = $1 AND "secretNote" = $2;', + [42, 'foo'], + ); + + await fastify.close(); + }); + }); }); From 0d7bbe3ccb9250fd27df87172beee3968dfed60b Mon Sep 17 00:00:00 2001 From: Abhishek Chatterjee Date: Mon, 23 Nov 2026 00:22:52 +0530 Subject: [PATCH 2/2] bug(routes): #232: restrict delete query filters to non-unique fields --- ross/docs/docs/application.md | 10 ++--- ross/docs/docs/database/models.md | 15 +++---- ross/e2e/delete-ssp.spec.ts | 38 +++++++--------- ross/src/routes/models/delete.ts | 44 ++++++++++-------- ross/tests/routes/delete.test.ts | 75 +++++++++++++++++++------------ 5 files changed, 101 insertions(+), 81 deletions(-) diff --git a/ross/docs/docs/application.md b/ross/docs/docs/application.md index 3403ff32..0797eeeb 100644 --- a/ross/docs/docs/application.md +++ b/ross/docs/docs/application.md @@ -310,12 +310,12 @@ When a user calls `POST /api/v1/projects`, ROSS strips `orgId` and `tenantId` fr #### Scoping DELETE and GET Operations with Query SSP -To enforce multi-tenant isolation or ownership scoping on `GET` and `DELETE` operations, configure `serverSideParams` with `type: "query"` referencing filter operators such as `_eq`: +To enforce multi-tenant isolation or ownership scoping on `GET` and non-unique `DELETE` operations, configure `serverSideParams` with `type: "query"` referencing filter operators such as `_eq`: ```json { "apis": { - "model:v1:todos:id:delete": { + "model:v1:todos:status:delete": { "authorization": true, "serverSideParams": [ { @@ -329,13 +329,13 @@ To enforce multi-tenant isolation or ownership scoping on `GET` and `DELETE` ope } ``` -When a user calls `DELETE /api/v1/todos/id/42`, ROSS injects `owner_id_eq` with the authenticated user's ID into the query filters. The executed SQL statement becomes: +When a user calls `DELETE /api/v1/todos/status/archived`, ROSS injects `owner_id_eq` with the authenticated user's ID into the query filters. The executed SQL statement becomes: ```sql -DELETE FROM "todos" WHERE "id" = 42 AND "owner_id" = ; +DELETE FROM "todos" WHERE "status" = 'archived' AND "owner_id" = ; ``` -Even if a malicious user passes another user's record ID, the deletion query will not match any rows and the target record remains safe. +Even if a user attempts to purge records with that status, the deletion query only deletes rows belonging to the authenticated user. #### Built-in vs. Custom Magic Variables diff --git a/ross/docs/docs/database/models.md b/ross/docs/docs/database/models.md index 2788c78a..92b76d2d 100644 --- a/ross/docs/docs/database/models.md +++ b/ross/docs/docs/database/models.md @@ -194,13 +194,7 @@ The `apis` array controls which field-specific REST endpoints ROSS generates: | `"index"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `GET /api/v1///:` | Look up records by this field's value. Returns a single object if unique, or a paginated array if non-unique. | | `"search"` | `string` | `GET /api/v1//search/?_search=` | Case-insensitive substring search matching text on this specific field. | | `"edit"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `PATCH` / `PUT /api/v1///:` | Update records matching the specified field parameter. | -| `"delete"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `DELETE /api/v1///:` | Delete records matching the specified field parameter. Supports query filters (e.g. `?status_eq=inactive`) to further constrain targeted records. | - -:::info[DELETE Endpoints Support Query Filters] - -Like listing and edit endpoints, `DELETE /api/v1///:` supports standard query filters for any other field on the model that defines `query` operations (e.g., `DELETE /api/v1/todos/id/42?owner_id_eq=7`). This enables scoping deletions by state or enforcing row-level ownership validation via Server-Side Parameters (`serverSideParams`). - -::: +| `"delete"` | `integer`, `decimal`, `string`, `enum`, `uuid`, `ulid` | `DELETE /api/v1///:` | Delete records matching the specified field parameter. | :::info[Search Is Restricted to String Fields] @@ -462,8 +456,10 @@ For every model configured in `data.models`, ROSS automatically mounts the follo - **Method**: `PATCH` (partial update) or `PUT` (complete update) - **Path**: `/api/v1///:` - **Generated for**: Fields with `"edit"` in `apis`. +- **Query Parameters**: + - `_`: Any configured model query filter (e.g. `?status_eq=active`) to narrow which records are updated. Supported only when the route's target `` is non-unique; endpoints on unique or primary key fields do not accept query filters. - **Body**: JSON payload of fields to update. When using `PATCH`, body fields are optional; when using `PUT`, all model fields are required. -- **Behavior**: Automatically updates the `updated_at` column if `timestamps: true` is enabled. If the field is not unique, you can provide query filters to narrow the update target. +- **Behavior**: Automatically updates the `updated_at` column if `timestamps: true` is enabled. When updating by a non-unique ``, query filters restrict which matching records are modified. - **Response**: `200 OK` returning `{ code: 200, message: "...", data: { ... } }` with updated values. If no matching record was found to update, returns `404 Not Found`. ### 5. Delete Record @@ -471,6 +467,9 @@ For every model configured in `data.models`, ROSS automatically mounts the follo - **Method**: `DELETE` - **Path**: `/api/v1///:` - **Generated for**: Fields with `"delete"` in `apis`. +- **Query Parameters**: + - `_`: Any configured model query filter (e.g. `?status_eq=inactive`) to narrow which records are deleted. Supported only when the route's target `` is non-unique; endpoints on unique or primary key fields do not accept query filters. +- **Behavior**: Deletes records matching the specified `` parameter. When deleting by a non-unique ``, query filters restrict which matching records are deleted. - **Response**: `204 No Content` (empty response body). ### 6. Substring Search diff --git a/ross/e2e/delete-ssp.spec.ts b/ross/e2e/delete-ssp.spec.ts index cb3bc1ec..cecd3269 100644 --- a/ross/e2e/delete-ssp.spec.ts +++ b/ross/e2e/delete-ssp.spec.ts @@ -70,12 +70,18 @@ const deleteSspE2EConfig: AppConfigInput = { primaryKey: true, autoIncrement: true, nullable: false, - apis: ['delete', 'index'], + apis: ['index'], }, title: { type: 'string', nullable: false, }, + status: { + type: 'string', + nullable: false, + apis: ['delete'], + query: ['eq'], + }, owner_id: { type: 'integer', nullable: false, @@ -86,7 +92,7 @@ const deleteSspE2EConfig: AppConfigInput = { }, }, apis: { - 'model.v1.todos.id.delete': { + 'model.v1.todos.status.delete': { enabled: true, authorization: true, serverSideParams: [ @@ -104,7 +110,8 @@ const deleteSspE2EConfig: AppConfigInput = { }, }; -test.describe.serial('E2E: DELETE API with SSP ownership scoping', () => { +test.describe + .serial('E2E: DELETE API with SSP ownership scoping on non-unique field', () => { let server: E2EServer; let user1Token: string; let user2Token: string; @@ -125,13 +132,13 @@ test.describe.serial('E2E: DELETE API with SSP ownership scoping', () => { test.beforeEach(async () => { await server.app.db.query('DELETE FROM todos;'); await server.app.db.query( - 'INSERT INTO todos (id, title, owner_id) VALUES (?, ?, ?), (?, ?, ?)', - [1, 'User 1 Todo', 1, 2, 'User 2 Todo', 2], + 'INSERT INTO todos (id, title, status, owner_id) VALUES (?, ?, ?, ?), (?, ?, ?, ?)', + [1, 'User 1 Todo', 'active', 1, 2, 'User 2 Todo', 'active', 2], ); }); test('User 1 cannot delete User 2 todo (scoped by [[userId]])', async () => { - const res = await server.request.delete('/api/v1/todos/id/2', { + const res = await server.request.delete('/api/v1/todos/status/active', { headers: { authorization: `Bearer ${user1Token}`, 'content-type': 'text/plain', @@ -147,28 +154,17 @@ test.describe.serial('E2E: DELETE API with SSP ownership scoping', () => { ); expect(checkRes.rows.length).toBe(1); expect(checkRes.rows[0].id).toBe(2); - }); - test('User 1 can delete their own todo', async () => { - const res = await server.request.delete('/api/v1/todos/id/1', { - headers: { - authorization: `Bearer ${user1Token}`, - 'content-type': 'text/plain', - }, - }); - - expect(res.status()).toBe(204); - - // Todo 1 must be deleted from the database - const checkRes = await server.app.db.query<{id: number}>( + // Todo 1 must have been deleted + const checkTodo1 = await server.app.db.query<{id: number}>( 'SELECT id FROM todos WHERE id = ?', [1], ); - expect(checkRes.rows.length).toBe(0); + expect(checkTodo1.rows.length).toBe(0); }); test('User 2 can delete their own todo', async () => { - const res = await server.request.delete('/api/v1/todos/id/2', { + const res = await server.request.delete('/api/v1/todos/status/active', { headers: { authorization: `Bearer ${user2Token}`, 'content-type': 'text/plain', diff --git a/ross/src/routes/models/delete.ts b/ross/src/routes/models/delete.ts index ef7fb63a..5be0908e 100644 --- a/ross/src/routes/models/delete.ts +++ b/ross/src/routes/models/delete.ts @@ -65,6 +65,7 @@ function registerDeleteEndpoint( apiIdentifier: string, policy: ResolvedApiPolicy, ): void { + const isUnique = field.primaryKey || field.unique; const schema: Record = generateSchema( fieldName, field, @@ -72,6 +73,7 @@ function registerDeleteEndpoint( modelName, config, policy, + isUnique, ); const path = `/${variant}/${modelName}/${fieldName}/:${fieldName}`; @@ -108,15 +110,17 @@ function registerDeleteEndpoint( whereClauses.push(`"${columnName}" = $${paramIndex++}`); values.push(value); - const { - whereClauses: filterClauses, - values: filterValues, - nextParamIndex, - } = applyFilters(queryParams, paramIndex, [fieldName]); + if (!isUnique) { + const { + whereClauses: filterClauses, + values: filterValues, + nextParamIndex, + } = applyFilters(queryParams, paramIndex, [fieldName]); - whereClauses.push(...filterClauses); - values.push(...filterValues); - paramIndex = nextParamIndex; + whereClauses.push(...filterClauses); + values.push(...filterValues); + paramIndex = nextParamIndex; + } const query = `DELETE FROM "${tableName}" WHERE ${whereClauses.join(' AND ')};`; @@ -144,21 +148,25 @@ function generateSchema( modelName: string, config: ResolvedAppConfig, policy: ResolvedApiPolicy, + isUnique?: boolean, ) { const paramSchema = mapDataTypeToJsonSchema(field.type); const effectiveQueries = policy.supportedQueries; const queryProperties: Record = {}; - const fields = policy.bypassSecret - ? Object.entries(model.fields) - : getPublicFields(model); - - for (const [fName, f] of fields) { - if (fName === fieldName) continue; - Object.assign( - queryProperties, - buildFilterQueryProperties(fName, f, effectiveQueries), - ); + + if (!isUnique) { + const fields = policy.bypassSecret + ? Object.entries(model.fields) + : getPublicFields(model); + + for (const [fName, f] of fields) { + if (fName === fieldName) continue; + Object.assign( + queryProperties, + buildFilterQueryProperties(fName, f, effectiveQueries), + ); + } } const schema: Record = { diff --git a/ross/tests/routes/delete.test.ts b/ross/tests/routes/delete.test.ts index db639d04..8f2b1a82 100644 --- a/ross/tests/routes/delete.test.ts +++ b/ross/tests/routes/delete.test.ts @@ -427,13 +427,13 @@ describe('test delete api', () => { }); }); - describe('query filters and server-side params', () => { + describe('query filters and server-side params on non-unique delete routes', () => { const todosModel: Record = { todos: { fields: { id: {type: 'integer', primaryKey: true, apis: ['delete']}, - title: {type: 'string'}, - status: {type: 'string', query: ['eq']}, + title: {type: 'string', query: ['eq']}, + status: {type: 'string', apis: ['delete'], query: ['eq']}, authorId: {type: 'integer', query: ['eq']}, secretNote: {type: 'string', secret: true, query: ['eq']}, }, @@ -441,7 +441,7 @@ describe('test delete api', () => { }; const sspApis: ApisConfig = { - 'model.v1.todos.id.delete': { + 'model.v1.todos.status.delete': { enabled: true, authorization: true, serverSideParams: [ @@ -450,46 +450,46 @@ describe('test delete api', () => { }, }; - test('should apply query filter to delete query', async () => { + test('should apply query filter to delete query on non-unique field', async () => { const fastify = await createTestApp(pgConfig, todosModel); const response = await fastify.inject({ method: 'DELETE', - url: '/v1/todos/id/42?status_eq=archived', + url: '/v1/todos/status/archived?authorId_eq=7', }); expect(response.statusCode).toBe(204); expect(pgClientQueryMock).toHaveBeenCalledWith( - 'DELETE FROM "todos" WHERE "id" = $1 AND "status" = $2;', - [42, 'archived'], + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2;', + ['archived', 7], ); await fastify.close(); }); - test('should apply multiple query filters to delete query', async () => { + test('should apply multiple query filters to delete query on non-unique field', async () => { const fastify = await createTestApp(pgConfig, todosModel); const response = await fastify.inject({ method: 'DELETE', - url: '/v1/todos/id/42?authorId_eq=7&status_eq=archived', + url: '/v1/todos/status/archived?authorId_eq=7&title_eq=done', }); expect(response.statusCode).toBe(204); expect(pgClientQueryMock).toHaveBeenCalledWith( - 'DELETE FROM "todos" WHERE "id" = $1 AND "authorId" = $2 AND "status" = $3;', - [42, 7, 'archived'], + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2 AND "title" = $3;', + ['archived', 7, 'done'], ); await fastify.close(); }); - test('should ignore unknown query params that do not match filter patterns', async () => { + test('should not apply query filters when deleting by unique primary key field', async () => { const fastify = await createTestApp(pgConfig, todosModel); const response = await fastify.inject({ method: 'DELETE', - url: '/v1/todos/id/42?unknown_param=foo', + url: '/v1/todos/id/42?authorId_eq=7', }); expect(response.statusCode).toBe(204); @@ -501,7 +501,24 @@ describe('test delete api', () => { await fastify.close(); }); - test('should inject [userId] as a query filter via SSP', async () => { + test('should ignore unknown query params on non-unique field', async () => { + const fastify = await createTestApp(pgConfig, todosModel); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/status/archived?unknown_param=foo', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "status" = $1;', + ['archived'], + ); + + await fastify.close(); + }); + + test('should inject [userId] as a query filter via SSP on non-unique delete route', async () => { const fastify = await createTestApp( pgConfig, todosModel, @@ -513,20 +530,20 @@ describe('test delete api', () => { const response = await fastify.inject({ method: 'DELETE', - url: '/v1/todos/id/42', + url: '/v1/todos/status/archived', headers: {authorization: `Bearer ${token}`}, }); expect(response.statusCode).toBe(204); expect(pgClientQueryMock).toHaveBeenCalledWith( - 'DELETE FROM "todos" WHERE "id" = $1 AND "authorId" = $2;', - [42, 7], + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2;', + ['archived', 7], ); await fastify.close(); }); - test('should override client query value with server-side SSP', async () => { + test('should override client query value with server-side SSP on non-unique delete route', async () => { const fastify = await createTestApp( pgConfig, todosModel, @@ -538,25 +555,25 @@ describe('test delete api', () => { const response = await fastify.inject({ method: 'DELETE', - url: '/v1/todos/id/42?authorId_eq=999', + url: '/v1/todos/status/archived?authorId_eq=999', headers: {authorization: `Bearer ${token}`}, }); expect(response.statusCode).toBe(204); expect(pgClientQueryMock).toHaveBeenCalledWith( - 'DELETE FROM "todos" WHERE "id" = $1 AND "authorId" = $2;', - [42, 7], + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2;', + ['archived', 7], ); await fastify.close(); }); - test('should reject invalid query param type with 400', async () => { + test('should reject invalid query param type with 400 on non-unique field', async () => { const fastify = await createTestApp(pgConfig, todosModel); const response = await fastify.inject({ method: 'DELETE', - url: '/v1/todos/id/42?authorId_eq=not-an-integer', + url: '/v1/todos/status/archived?authorId_eq=not-an-integer', }); expect(response.statusCode).toBe(400); @@ -565,22 +582,22 @@ describe('test delete api', () => { await fastify.close(); }); - test('should include secret fields in query filter when bypassSecret is true', async () => { + test('should include secret fields in query filter when bypassSecret is true on non-unique route', async () => { const fastify = await createTestApp(pgConfig, todosModel, { - 'model.v1.todos.id.delete': { + 'model.v1.todos.status.delete': { bypassSecret: true, }, }); const response = await fastify.inject({ method: 'DELETE', - url: '/v1/todos/id/42?secretNote_eq=foo', + url: '/v1/todos/status/archived?secretNote_eq=foo', }); expect(response.statusCode).toBe(204); expect(pgClientQueryMock).toHaveBeenCalledWith( - 'DELETE FROM "todos" WHERE "id" = $1 AND "secretNote" = $2;', - [42, 'foo'], + 'DELETE FROM "todos" WHERE "status" = $1 AND "secretNote" = $2;', + ['archived', 'foo'], ); await fastify.close();