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
2 changes: 1 addition & 1 deletion .github/workflows/api-server-security.yml
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ jobs:
env:
NODE_OPTIONS: --experimental-vm-modules
working-directory: packages/api-server
run: pnpm exec jest --maxWorkers=12 --runTestsByPath __tests__/core/executor/query-executor/TiDBPlaygroundQueryExecutor.ts __tests__/worker/queue-worker.ts __tests__/core/email-rekey.ts __tests__/core/app-startup.ts __tests__/core/public-abuse.ts __tests__/core/named-query-budgets.ts __tests__/core/account-registration.ts
run: pnpm exec jest --maxWorkers=12 --runTestsByPath __tests__/core/executor/query-executor/TiDBPlaygroundQueryExecutor.ts __tests__/worker/queue-worker.ts __tests__/core/email-rekey.ts __tests__/core/app-startup.ts __tests__/core/public-abuse.ts __tests__/core/named-query-budgets.ts __tests__/core/account-registration.ts __tests__/core/request-log-retention.ts

containers:
runs-on: ubuntu-latest
Expand Down
3 changes: 2 additions & 1 deletion ops/request-statistics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,5 @@ this follow-up open until the database and relevant backups have been checked;
do not report that the historical-data risk is fixed by this code change.

See [access and historical cleanup](access-and-retention.md) for the tested
writer privilege boundary, deployment procedure and historical-data decision.
writer privilege boundary, deployment procedure, and bounded preview and cleanup
command for both request-log tables.
47 changes: 46 additions & 1 deletion ops/request-statistics/access-and-retention.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,52 @@ A reviewed cleanup should specify:
writes can reintroduce expired records; partition removal alone does not
prevent that. Check this before enabling a schedule.

No default retention period or cleanup scheduler is enabled by this change.
## Preview or prune one bounded batch

The maintenance command supports `stats_api_requests.finished_at` and the
legacy `access_logs.requested_at`. It needs an explicit table, expected schema
and approved UTC date. The operator supplies the cutoff separately for each
table. Verify timestamps are recorded in UTC. The statistics table must keep
at least the rolling calendar month used by collection counts. The data owner
can require a longer period for either table.

Before applying a cutoff, confirm recovery and aggregate/reporting needs,
legal and investigation holds, and backup expiry with the data owner. Skip
a table if a hold covers any row in the proposed range. The command applies
the cutoff to **every** earlier row in that table. It has no per-record hold
list. TiDB 8.5.1 requires table-level `SELECT` for the bounded preview.
Use a dedicated maintenance account with `SELECT` on the reviewed table,
adding `DELETE` only to run the cleanup. This account can read historical data.
Keep its credentials outside the API and analytics services.
Supply the connection URL through the private environment variable
`REQUEST_LOG_MAINTENANCE_URL`. Remote connections require verified TLS.

Build the API workspace and its dependencies, then run this from
`packages/api-server` against the expected schema. For the legacy table
substitute `access_logs` and its separately approved cutoff.

```sh
node dist/cmd/prune-request-logs.js --table stats_api_requests \
--database "$EXPECTED_SCHEMA" --before "$APPROVED_CUTOFF" --limit 250
```

The preview counts up to the specified limit using only the timestamp range.
An exact cutoff match stays in the table. The command verifies the schema,
database date and presence of a visible leading timestamp index. On large
installations inspect the deployed query plan and check latency and lock waits
before proceeding. Add `--apply` to commit one batch of at most 1,000 rows.
The receipt records the table, cutoff, limit and count. Save each receipt in
the private maintenance record. After an interrupted run, preview the same
cutoff again. Each run selects from the remaining rows, including older rows
inserted after a previous run. Duplicate timestamps need no pagination cursor.

Keep a fixed cutoff while draining a backlog, pace invocations, and stop if
load or lock contention exceeds the deployment's operating limits. A final
empty preview confirms the live table at that instant. Schedule further runs
only under the approved retention policy. The command leaves partitions,
retained legacy fields, aggregates, and backup expiry to their respective
maintenance procedures.

Keep the historical-data issue open until the approved live cleanup, retained
legacy rows, access restrictions and relevant backups have all been verified.
Use the deployed TiDB version's [partition documentation](https://docs.pingcap.com/tidb/stable/partitioned-table/)
Expand Down
58 changes: 58 additions & 0 deletions packages/api-server/__tests__/core/request-log-retention.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import {createHash} from 'node:crypto';
import {Connection, createConnection, RowDataPacket} from 'mysql2/promise';
import {bootstrapTestDatabase, releaseTestDatabase} from '../helpers/db';
import {prune, readOptions} from '../../src/cmd/prune-request-logs';

let conn: Connection;
let maintenance: Connection;
let schema: string;
let user: string;
beforeAll(async () => {
const fixture = await bootstrapTestDatabase();
schema = fixture.database;
conn = await createConnection(fixture.rootUrl());
await conn.query('USE ??', [schema]);
user = 'prune_' + createHash('sha256').update(schema).digest('hex').slice(0, 16);
await conn.query("CREATE USER ?@'%' IDENTIFIED BY 'fixture-only'", [user]);
for (const table of ['stats_api_requests', 'access_logs']) {
await conn.query("GRANT SELECT, DELETE ON ??.?? TO ?@'%'", [schema, table, user]);
}
maintenance = await createConnection({host: fixture.host, port: fixture.port, database: schema, user, password: 'fixture-only'});
});
afterAll(async () => {
await maintenance?.end();
if (conn && user) await conn.query("DROP USER IF EXISTS ?@'%'", [user]);
await conn?.end();
await releaseTestDatabase();
});

function options(table: string, ...extra: string[]) {
return readOptions(['--table', table, '--database', schema, '--before', '2020-02-01', '--limit', '2', ...extra]);
}

test.each(['stats_api_requests', 'access_logs'])('previews and prunes %s in resumable batches', async table => {
const statistics = table === 'stats_api_requests';
const stamp = statistics ? 'finished_at' : 'requested_at';
const insert = statistics
? "INSERT INTO stats_api_requests (method, finished_at) VALUES ('GET', ?)"
: 'INSERT INTO access_logs (requested_at) VALUES (?)';
for (const date of ['2020-01-01', '2020-01-01', '2020-01-01', '2020-02-01', '2020-03-01']) {
await conn.query(insert, [date]);
}
expect(await prune(maintenance, options(table))).toMatchObject({mode: 'preview', candidates: 2});
for (const expected of [2, 1, 0]) {
expect(await prune(maintenance, options(table, '--apply'))).toMatchObject({deleted: expected});
}
await conn.query(insert, ['2020-01-20']);
expect(await prune(maintenance, options(table, '--apply'))).toMatchObject({deleted: 1});
const [remaining] = await conn.query<RowDataPacket[]>('SELECT COUNT(*) AS n FROM ?? WHERE ?? IN (?, ?)', [table, stamp, '2020-02-01', '2020-03-01']);
expect(Number(remaining[0].n)).toBe(2);
});

test('refuses a different database, an unsafe cutoff, or a missing leading index', async () => {
await expect(prune(maintenance, {...options('access_logs'), database: 'different_schema'})).rejects.toThrow('schema or the cutoff');
const [today] = await conn.query<RowDataPacket[]>("SELECT DATE_FORMAT(UTC_DATE(), '%Y-%m-%d') AS day");
await expect(prune(maintenance, {...options('stats_api_requests'), before: today[0].day})).rejects.toThrow('schema or the cutoff');
await conn.query('ALTER TABLE access_logs DROP INDEX index_al_on_requested_at');
await expect(prune(maintenance, options('access_logs', '--apply'))).rejects.toThrow('leading timestamp index');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import {maintenanceURL, readOptions} from '../../src/cmd/prune-request-logs';

const args = ['--table', 'stats_api_requests', '--database', 'statistics', '--before', '2024-02-29'];

test('defaults to a single read-only preview and accepts an explicit bounded apply', () => {
expect(readOptions(args)).toEqual({table: 'stats_api_requests', database: 'statistics', before: '2024-02-29', limit: 250, apply: false});
expect(readOptions([...args, '--limit', '1000', '--apply'])).toMatchObject({limit: 1000, apply: true});
});
test.each(['0', '-1', '1.5', '1001'])('rejects invalid row limit %s', value => {
expect(() => readOptions([...args, '--limit', value])).toThrow();
});
test.each(['2025-02-29', '2024-13-01', '2024-02-30', '2024-01-01T10:00:00Z'])('rejects invalid cutoff %s', date => {
expect(() => readOptions([...args.slice(0, -1), date])).toThrow();
});
test('requires one known table and an expected schema', () => {
expect(() => readOptions(['--before', '2020-01-01'])).toThrow();
expect(() => readOptions(['--table', 'collections', ...args.slice(2)])).toThrow();
expect(() => readOptions(args.filter(value => !['--database', 'statistics'].includes(value)))).toThrow();
});
test('requires a dedicated account, verifies remote TLS and limits connection options', () => {
const url = 'mysql://maintenance:fixture@db.example.test/statistics';
expect(JSON.parse(new URL(maintenanceURL(url)).searchParams.get('ssl')!)).toMatchObject({verifyIdentity: true, rejectUnauthorized: true});
for (const invalid of ['', url.replace('maintenance', 'root'), url + '?debug=true', url + '?ssl=false']) {
expect(() => maintenanceURL(invalid)).toThrow();
}
});
93 changes: 93 additions & 0 deletions packages/api-server/src/cmd/prune-request-logs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import {parseArgs} from 'node:util';
import {secureDatabaseURL} from '@ossinsight/types';
import {Connection, createConnection, ResultSetHeader, RowDataPacket} from 'mysql2/promise';

class ConfigurationError extends Error {}

export function readOptions(args: string[]) {
const {values} = parseArgs({args, options: {
table: {type: 'string'}, database: {type: 'string'}, before: {type: 'string'},
limit: {type: 'string', default: '250'}, apply: {type: 'boolean', default: false},
}});
const {table, database, before} = values;
if (table !== 'stats_api_requests' && table !== 'access_logs') {
throw new ConfigurationError('Select stats_api_requests or access_logs with --table.');
}
if (!database || !/^[a-zA-Z0-9_]{1,64}$/.test(database)) {
throw new ConfigurationError('Specify the expected schema with --database.');
}
if (!before || !/^[1-9]\d{3}-\d{2}-\d{2}$/.test(before)
|| new Date(Date.parse(before)).toJSON()?.slice(0, 10) !== before) {
throw new ConfigurationError('Specify a valid UTC cutoff date with --before YYYY-MM-DD.');
}
if (!values.limit || !/^[1-9]\d{0,3}$/.test(values.limit) || Number(values.limit) > 1000) {
throw new ConfigurationError('The batch limit must be between 1 and 1000.');
}
return {table, database, before, limit: Number(values.limit), apply: values.apply === true} as const;
}

export function maintenanceURL(value: string) {
let url: URL;
try {
url = new URL(secureDatabaseURL(value, process.env.NODE_ENV === 'production'));
} catch {
throw new ConfigurationError('Set a valid REQUEST_LOG_MAINTENANCE_URL with verified TLS for remote access.');
}
if (!url.username || /(?:^|\.)root$/i.test(decodeURIComponent(url.username)) ||
[...url.searchParams.keys()].some(key => key !== 'ssl')) {
throw new ConfigurationError('Use a dedicated maintenance account. Only the ssl connection option is supported.');
}
return url.toString();
}

export async function prune(connection: Connection, options: ReturnType<typeof readOptions>) {
const {table, database, before, limit, apply} = options;
const statistics = table === 'stats_api_requests';
const column = statistics ? 'finished_at' : 'requested_at';
const latest = statistics ? 'DATE_SUB(UTC_DATE(), INTERVAL 1 MONTH)' : 'UTC_DATE()';
await connection.query("SET SESSION time_zone = '+00:00'");
const [context] = await connection.query<RowDataPacket[]>(
`SELECT DATABASE() AS db, CAST(? AS DATE) <= ${latest} AS allowed`, [before],
);
if (context[0]?.db !== database || Number(context[0]?.allowed) !== 1) {
throw new ConfigurationError('The connected schema or the cutoff is unsuitable for this table.');
}
const [indexes] = await connection.query<RowDataPacket[]>(
'SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE() AND table_name = ? ' +
'AND column_name = ? AND seq_in_index = 1 AND is_visible = \'YES\' LIMIT 1', [table, column],
);
if (!indexes.length) throw new ConfigurationError('The leading timestamp index is missing or invisible.');

const range = statistics
? 'FROM stats_api_requests WHERE finished_at < ? ORDER BY finished_at LIMIT ?'
: 'FROM access_logs WHERE requested_at < ? ORDER BY requested_at LIMIT ?';
if (!apply) {
const [counts] = await connection.query<RowDataPacket[]>(
`SELECT COUNT(*) AS candidates FROM (SELECT 1 ${range}) AS batch`, [before, limit],
);
return {table, before, limit, mode: 'preview', candidates: Number(counts[0].candidates)};
}
await connection.query('SET SESSION innodb_lock_wait_timeout = 5');
// One autocommit statement per invocation, including when timestamps are duplicated.
await connection.query('SET SESSION autocommit = 1');
const [result] = await connection.query<ResultSetHeader>(`DELETE ${range}`, [before, limit]);
return {table, before, limit, mode: 'apply', deleted: result.affectedRows};
}

async function main() {
const options = readOptions(process.argv.slice(2));
const connection = await createConnection(maintenanceURL(process.env.REQUEST_LOG_MAINTENANCE_URL || ''));
try {
console.log(JSON.stringify(await prune(connection, options)));
} finally {
await connection.end();
}
}

if (require.main === module) {
main().catch(error => {
// Driver errors can include SQL and connection details. Never dump them to operations logs.
console.error(error instanceof ConfigurationError ? error.message : 'Request-log maintenance did not complete. Preview again before retrying.');
process.exitCode = 1;
});
}
Loading