Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions ross/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
node_modules
.git
.github
.husky
build
coverage
docs
e2e
examples
playwright-report
test-results
.ross
.migrations
*.db
*.log
29 changes: 29 additions & 0 deletions ross/docs/docs/application.md
Original file line number Diff line number Diff line change
Expand Up @@ -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" = <authenticated_user_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:
Expand Down
7 changes: 6 additions & 1 deletion ross/docs/docs/database/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,15 +456,20 @@ For every model configured in `data.models`, ROSS automatically mounts the follo
- **Method**: `PATCH` (partial update) or `PUT` (complete update)
- **Path**: `/api/v1/<model>/<field>/:<field>`
- **Generated for**: Fields with `"edit"` in `apis`.
- **Query Parameters**:
- `<filter_field>_<operator>`: Any configured model query filter (e.g. `?status_eq=active`) to narrow which records are updated. Supported only when the route's target `<field>` 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 `<field>`, 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

- **Method**: `DELETE`
- **Path**: `/api/v1/<model>/<field>/:<field>`
- **Generated for**: Fields with `"delete"` in `apis`.
- **Query Parameters**:
- `<filter_field>_<operator>`: Any configured model query filter (e.g. `?status_eq=inactive`) to narrow which records are deleted. Supported only when the route's target `<field>` is non-unique; endpoints on unique or primary key fields do not accept query filters.
- **Behavior**: Deletes records matching the specified `<field>` parameter. When deleting by a non-unique `<field>`, query filters restrict which matching records are deleted.
- **Response**: `204 No Content` (empty response body).

### 6. Substring Search
Expand Down
183 changes: 183 additions & 0 deletions ross/e2e/delete-ssp.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
56 changes: 53 additions & 3 deletions ross/src/routes/models/delete.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -63,13 +65,15 @@ function registerDeleteEndpoint(
apiIdentifier: string,
policy: ResolvedApiPolicy,
): void {
const isUnique = field.primaryKey || field.unique;
const schema: Record<string, unknown> = generateSchema(
fieldName,
field,
model,
modelName,
config,
policy,
isUnique,
);

const path = `/${variant}/${modelName}/${fieldName}/:${fieldName}`;
Expand All @@ -94,16 +98,36 @@ function registerDeleteEndpoint(
},
async (request: FastifyRequest, reply: FastifyReply) => {
const {[fieldName]: value} = request.params as Record<string, unknown>;
const queryParams = request.query as Record<string, unknown>;

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(() => {});
Expand All @@ -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<string, object> = {};

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<string, unknown> = {
summary: `Delete ${capitalizeFirstLetter(modelName)} records by ${fieldName}`,
description: `Delete records from ${capitalizeFirstLetter(modelName)} table where ${fieldName} matches the provided value`,
Expand All @@ -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) {
Expand Down
Loading
Loading