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..0797eeeb 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 non-unique `DELETE` operations, configure `serverSideParams` with `type: "query"` referencing filter operators such as `_eq`: + +```json +{ + "apis": { + "model:v1:todos:status:delete": { + "authorization": true, + "serverSideParams": [ + { + "name": "owner_id_eq", + "type": "query", + "value": "[[userId]]" + } + ] + } + } +} +``` + +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 "status" = 'archived' AND "owner_id" = ; +``` + +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 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..92b76d2d 100644 --- a/ross/docs/docs/database/models.md +++ b/ross/docs/docs/database/models.md @@ -456,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 @@ -465,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 new file mode 100644 index 00000000..cecd3269 --- /dev/null +++ b/ross/e2e/delete-ssp.spec.ts @@ -0,0 +1,183 @@ +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: ['index'], + }, + title: { + type: 'string', + nullable: false, + }, + status: { + type: 'string', + nullable: false, + apis: ['delete'], + query: ['eq'], + }, + owner_id: { + type: 'integer', + nullable: false, + query: ['eq'], + }, + }, + }, + }, + }, + apis: { + 'model.v1.todos.status.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 on non-unique field', () => { + 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, 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/status/active', { + 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); + + // Todo 1 must have been deleted + const checkTodo1 = await server.app.db.query<{id: number}>( + 'SELECT id FROM todos WHERE id = ?', + [1], + ); + expect(checkTodo1.rows.length).toBe(0); + }); + + test('User 2 can delete their own todo', async () => { + const res = await server.request.delete('/api/v1/todos/status/active', { + 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..5be0908e 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, @@ -63,6 +65,7 @@ function registerDeleteEndpoint( apiIdentifier: string, policy: ResolvedApiPolicy, ): void { + const isUnique = field.primaryKey || field.unique; const schema: Record = generateSchema( fieldName, field, @@ -70,6 +73,7 @@ function registerDeleteEndpoint( modelName, config, policy, + isUnique, ); const path = `/${variant}/${modelName}/${fieldName}/:${fieldName}`; @@ -94,16 +98,36 @@ 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); + + if (!isUnique) { + 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(() => {}); @@ -124,9 +148,27 @@ function generateSchema( modelName: string, config: ResolvedAppConfig, policy: ResolvedApiPolicy, + isUnique?: boolean, ) { const paramSchema = mapDataTypeToJsonSchema(field.type); + const effectiveQueries = policy.supportedQueries; + const queryProperties: Record = {}; + + 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 = { summary: `Delete ${capitalizeFirstLetter(modelName)} records by ${fieldName}`, description: `Delete records from ${capitalizeFirstLetter(modelName)} table where ${fieldName} matches the provided value`, @@ -145,6 +187,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..8f2b1a82 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,181 @@ describe('test delete api', () => { await fastify.close(); }); }); + + 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', query: ['eq']}, + status: {type: 'string', apis: ['delete'], query: ['eq']}, + authorId: {type: 'integer', query: ['eq']}, + secretNote: {type: 'string', secret: true, query: ['eq']}, + }, + }, + }; + + const sspApis: ApisConfig = { + 'model.v1.todos.status.delete': { + enabled: true, + authorization: true, + serverSideParams: [ + {type: 'query', name: 'authorId_eq', value: '[[userId]]'}, + ], + }, + }; + + 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/status/archived?authorId_eq=7', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2;', + ['archived', 7], + ); + + await fastify.close(); + }); + + 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/status/archived?authorId_eq=7&title_eq=done', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2 AND "title" = $3;', + ['archived', 7, 'done'], + ); + + await fastify.close(); + }); + + 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?authorId_eq=7', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "id" = $1;', + [42], + ); + + await fastify.close(); + }); + + 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, + sspApis, + undefined, + upAuthConfig, + ); + const token = fastify.jwt.sign({id: 7, email: 'alice@example.com'}); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/status/archived', + headers: {authorization: `Bearer ${token}`}, + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2;', + ['archived', 7], + ); + + await fastify.close(); + }); + + test('should override client query value with server-side SSP on non-unique delete route', 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/status/archived?authorId_eq=999', + headers: {authorization: `Bearer ${token}`}, + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "status" = $1 AND "authorId" = $2;', + ['archived', 7], + ); + + await fastify.close(); + }); + + 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/status/archived?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 on non-unique route', async () => { + const fastify = await createTestApp(pgConfig, todosModel, { + 'model.v1.todos.status.delete': { + bypassSecret: true, + }, + }); + + const response = await fastify.inject({ + method: 'DELETE', + url: '/v1/todos/status/archived?secretNote_eq=foo', + }); + + expect(response.statusCode).toBe(204); + expect(pgClientQueryMock).toHaveBeenCalledWith( + 'DELETE FROM "todos" WHERE "status" = $1 AND "secretNote" = $2;', + ['archived', 'foo'], + ); + + await fastify.close(); + }); + }); });