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
18 changes: 12 additions & 6 deletions configs/pipelines/calc_collection_visits/process.sql
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
WITH collections_with_past_month_visits AS (
SELECT
/*+ READ_FROM_STORAGE(TIFLASH[sar]) */
CAST(JSON_EXTRACT(query, '$.collectionId') AS SIGNED) AS collection_id,
JSON_UNQUOTE(JSON_EXTRACT(query, '$.collectionId')) AS collection_id,
COUNT(*) AS past_month_visit
FROM stats_api_requests sar
WHERE
path LIKE '/q/collection-%'
AND method = 'GET'
AND status_code >= 200 AND status_code < 300
AND error = 0
AND is_dev = 0
AND finished_at > DATE_SUB(NOW(), INTERVAL 1 MONTH)
AND finished_at <= NOW()
AND JSON_UNQUOTE(JSON_EXTRACT(query, '$.collectionId')) REGEXP '^[1-9][0-9]{0,18}$'
GROUP BY collection_id
)
UPDATE
collections c, collections_with_past_month_visits cv
collections c
-- Compare canonical strings: malformed legacy IDs must not coerce to an ID.
LEFT JOIN collections_with_past_month_visits cv ON CAST(c.id AS CHAR) = cv.collection_id
SET
c.past_month_visits = cv.past_month_visit
WHERE
c.id = cv.collection_id
;
c.past_month_visits = COALESCE(cv.past_month_visit, 0)
;
43 changes: 43 additions & 0 deletions ops/request-statistics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Request statistics and collection activity

`stats_api_requests` is a usage-statistics table. New records keep the final
method, registered resource shape, outcome, duration and development flag.
Resource segments and query parameters use the reviewed `requestAuditContext`
allowlist in `@ossinsight/types`; arbitrary query values, request bodies and
unknown paths are not stored. The legacy `client_ip` and `client_origin` columns
remain compatible with the existing schema but receive empty strings.

Operational `api_request` security events remain separate, with request IDs,
authenticated actors, outcomes and the source IP established by the configured
proxy trust chain. This change does not remove or alter those events.

## Collection activity

`calc_collection_visits` counts successful (2xx), non-error, production GET
requests to collection queries over the past month. It accepts canonical
positive collection IDs without numeric coercion and resets collections with
no qualifying requests to zero. Both legacy string IDs and new numeric JSON
IDs work. Prefetch executes queries directly and does not generate HTTP request
statistics.

The existing `past_month_visits` field is a request-activity signal, not unique
visitors or page views. A page can make several requests. Successful automated
requests can still contribute; the public request quota remains necessary but
does not establish that a visitor is human. Do not present this count as a
verified popularity or anti-fraud metric.

## Rollout and historical data

Deploy the API recorder and the pipeline configuration together. Verify recent
new-row metadata without exporting request contents, then run the normal
collection task and confirm completion. The recorder requires no schema or
permission change. The aggregation intentionally corrects existing stale
counts and can be rerun safely.

This change only minimizes **future writes**. Existing rows may contain raw
visitor identifiers and sensitive parameters. Before deleting or rewriting
them, inventory external reporting consumers, incident-investigation needs,
database/back-up access and retention obligations. Record an approved retention
period and verify recovery before applying a bounded historical cleanup. Keep
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.
55 changes: 50 additions & 5 deletions packages/api-server/__tests__/core/public-abuse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import Fastify from 'fastify';
import fp from 'fastify-plugin';
import urlData from '@fastify/url-data';
import mysqlPlugin from '@fastify/mysql';
import {createPool, Pool} from 'mysql2/promise';
import {createConnection, createPool, Pool} from 'mysql2/promise';
import pino from 'pino';
import {bootstrapTestDatabase, getTestDatabase, releaseTestDatabase} from '../helpers/db';
import {BatchLoader} from '../../src/core/db/batch-loader';
import recorder from '../../src/plugins/stats/api-request-recorder';
import {literalLikePrefix} from '../../../../apps/web/lib/server/search-keyword';
import {readFile} from 'node:fs/promises';
import {resolve} from 'node:path';

let pool: Pool;
beforeAll(async () => {await bootstrapTestDatabase();pool = createPool(getTestDatabase().url());});
Expand All @@ -30,25 +32,68 @@ test('strict TiDB preserves 99 good audit rows when one oversized origin poisons
} finally {await loader.destroy();}
});

test('real recorder writes bounded inputs and one final error row into the production-shaped schema', async () => {
test('real recorder minimizes stored inputs and preserves one final response in the production-shaped schema', async () => {
const app = Fastify();
await app.register(mysqlPlugin, {promise: true, uri: getTestDatabase().url(), connectionLimit: 2});
await app.register(fp(async () => {}, {name: '@fastify/env'}));
await app.register(fp(async () => {}, {name: '@ossinsight/tidb'}));
await app.register(urlData);await app.register(recorder);
app.get('/recorder-error', async () => {throw new Error('fixture');});
app.get('/q/:query', async () => ({ok: true}));
app.get('/healthy', async () => ({healthy: true}));
app.get('/metrics', async () => 'fixture metrics');
const requestPath = '/recorder-long-' + 'a'.repeat(500);
try {
await app.inject({url: requestPath, headers: {origin: 'https://' + 'a'.repeat(500)}});
await app.inject('/recorder-error');
await app.inject({url: '/q/collection-issues-history?collectionId=10001&token=synthetic-secret&sql=private-input&limit=5',
remoteAddress: '192.0.2.123', headers: {origin: 'https://private-fixture.invalid', authorization: 'Bearer synthetic-secret'}});
await app.inject('/healthy?token=synthetic-secret');
await app.inject('/metrics?collectionId=10001');
await app.apiRequestRecorder.flush();
const [rows]: any = await pool.query("SELECT path,OCTET_LENGTH(client_origin) AS originBytes,OCTET_LENGTH(path) AS pathBytes,error,status_code FROM stats_api_requests WHERE path LIKE '/recorder-%' ORDER BY path");
expect(rows).toHaveLength(2);
expect(rows.every((row: any) => row.originBytes <= 255 && row.pathBytes <= 255)).toBe(true);
const [rows]: any = await pool.query("SELECT client_ip,client_origin,path,query,error,status_code FROM stats_api_requests WHERE path NOT LIKE '/fixture-%' ORDER BY path");
expect(rows).toHaveLength(3);
expect(rows.every((row: any) => row.client_ip === '' && row.client_origin === '' && Buffer.byteLength(row.path) <= 255)).toBe(true);
expect(rows.find((row: any) => row.path === 'unmatched')).toMatchObject({error: 1, status_code: 404});
expect(rows.find((row: any) => row.path === '/recorder-error')).toMatchObject({error: 1, status_code: 500});
const collection = rows.find((row: any) => row.path === '/q/collection-issues-history');
expect(typeof collection.query === 'string' ? JSON.parse(collection.query) : collection.query).toEqual({collectionId: 10001, limit: 5});
expect(JSON.stringify(rows)).not.toMatch(/synthetic-secret|private-input|private-fixture|192\.0\.2\.123|recorder-long/);
} finally {await app.close();}
});

test('actual collection pipeline counts successful production GETs and clears stale totals without coercing IDs', async () => {
// The public API account intentionally cannot change collections. This
// pipeline fixture uses only the disposable test container's own schema.
const database = getTestDatabase();
const pipeline = await createConnection(`${database.rootUrl()}/${database.database}`);
try {
await pool.query('DELETE FROM stats_api_requests');
const ids = [71001, 71002, 71003];
await pipeline.query('INSERT INTO collections(id,name,past_month_visits) VALUES ?',
[ids.map(id => [id, `activity-fixture-${id}`, 99])]);
const rows: any[][] = [];
function record(collectionId: unknown, overrides: {path?: string, method?: string, status?: number, error?: number, dev?: number, ageDays?: number} = {}) {
rows.push([overrides.path ?? '/q/collection-issues-history', overrides.method ?? 'GET', JSON.stringify({collectionId}),
overrides.status ?? 200, overrides.error ?? 0, overrides.dev ?? 0, new Date(Date.now() - (overrides.ageDays ?? 1) * 86400000)]);
}
record(ids[0]);record(String(ids[0]), {status: 204});
for (const status of [301, 400, 401, 403, 404, 429, 500, 503]) record(ids[0], {status, error: status >= 400 ? 1 : 0});
record(ids[0], {error: 1});record(ids[0], {dev: 1});record(ids[0], {ageDays: 40});record(ids[0], {ageDays: -1});
for (const method of ['POST', 'OPTIONS', 'HEAD']) record(ids[0], {method});
record(ids[0], {path: '/q/events-total'});
for (const value of ['71001junk', '071001', '71001.0', '7.1001e4', '71001\n', '-71001', '9223372036854775808', null, [71001], {id: 71001}]) record(value);
record(ids[1], {status: 429, error: 1});record(ids[2], {ageDays: 40});
await pool.query('INSERT INTO stats_api_requests(path,method,query,status_code,error,is_dev,finished_at) VALUES ?', [rows]);
const sql = await readFile(resolve(__dirname, '../../../../configs/pipelines/calc_collection_visits/process.sql'), 'utf8');
for (let run = 0; run < 2; run++) {
await pipeline.query(sql);
const [actual]: any = await pool.query('SELECT id,past_month_visits FROM collections WHERE id IN (?) ORDER BY id', [ids]);
expect(actual).toEqual(ids.map((id, index) => ({id, past_month_visits: index === 0 ? 2 : 0})));
}
} finally {await pipeline.end();}
});

test.each(['', 'NO_BACKSLASH_ESCAPES'])('literal LIKE prefixes remain literal under SQL mode %s', async extraMode => {
const connection = await pool.getConnection();
try {
Expand Down
43 changes: 43 additions & 0 deletions packages/api-server/__tests__/security/request-statistics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import Fastify from 'fastify';
import fp from 'fastify-plugin';
import recorder from '../../src/plugins/stats/api-request-recorder';

test('statistics retain useful collection dimensions without visitor identifiers or arbitrary input', async () => {
const app = Fastify();
const rows: any[][] = [];
app.decorate('mysql', {query: async (_sql: string, [batch]: [any[][]]) => {
rows.push(...batch);return [{affectedRows: batch.length}];
}});
await app.register(fp(async () => {}, {name: '@fastify/env'}));
await app.register(fp(async () => {}, {name: '@ossinsight/tidb'}));
await app.register(recorder);
app.get('/q/:query', async (_request, reply) => reply.code(200).send({ok: true}));
app.get('/documents/:name', async () => ({ok: true}));
app.get('/failure', async () => {throw new Error('synthetic-private-error');});
app.get('/healthy', async () => ({healthy: true}));
app.get('/metrics', async () => 'synthetic metrics');
try {
await app.inject({url: '/q/collection-issues-history?collectionId=10001&limit=10&period=month&token=synthetic-private-token&sql=synthetic-private-sql',
remoteAddress: '192.0.2.123', headers: {origin: 'https://synthetic-private-origin.invalid', authorization: 'Bearer synthetic-private-token'}});
await app.inject('/q/collection-issues-history?collectionId=10001&collectionId=10002&limit=not-a-number');
await app.inject('/q/synthetic-private-query-name?token=synthetic-private-token');
await app.inject('/documents/synthetic-private-document?name=synthetic-private-name');
await app.inject('/synthetic-private-unknown-path?collectionId=10001');
await app.inject('/failure?token=synthetic-private-token');
await app.inject('/healthy?token=synthetic-private-token');
await app.inject('/metrics?collectionId=10001');
await app.apiRequestRecorder.flush();
expect(rows).toHaveLength(6);
expect(rows.every(row => row[0] === '' && row[1] === '')).toBe(true);
expect(rows[0][3]).toBe('/q/collection-issues-history');
expect(JSON.parse(rows[0][4])).toEqual({collectionId: 10001, limit: 10, period: 'month'});
expect(JSON.parse(rows[1][4])).toEqual({});
expect(rows[2][3]).toBe('/q/[redacted]');
expect(rows[3][3]).toBe('/documents/[redacted]');
expect(rows[4][3]).toBe('unmatched');
expect(rows[4][5]).toBe(true);expect(rows[4][6]).toBe(404);
expect(rows[5][3]).toBe('/failure');
expect(rows[5][5]).toBe(true);expect(rows[5][6]).toBe(500);
expect(JSON.stringify(rows)).not.toMatch(/synthetic-private|192\.0\.2\.123/);
} finally {await app.close();}
});
17 changes: 9 additions & 8 deletions packages/api-server/src/plugins/stats/api-request-recorder.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import fp from "fastify-plugin";
import {Pool} from "mysql2/promise";
import pino from "pino";
import {requestAuditContext} from '@ossinsight/types';

import {BatchLoader} from "../../core/db/batch-loader";
import {getRealClientIP} from "../../utils/http/forwared";
import Logger = pino.Logger;

// Bound bytes as well as characters, without cutting a UTF-8 code point.
Expand All @@ -30,20 +30,21 @@ export default fp(async (app) => {

app.decorate('apiRequestRecorder', apiRequestRecorder);
app.addHook('onResponse', function (req, reply, done) {
// Skip metrics request.
if (req.url === '/metrics' || req.url === '/healthy') {
const route = req.routeOptions.url || 'unmatched';
// Query strings must not turn health/metrics checks into visitor statistics.
if (route === '/metrics' || route === '/healthy') {
done();
return;
}

// Record the final response once, including errors and their final status.
const clientIP = boundedAuditText(getRealClientIP(req), 128);
const clientOrigin = boundedAuditText(req.headers.origin ?? '', 255);
const { method, query } = req;
const { path } = req.urlData();
// This table is long-lived usage statistics, not the security-event log.
// Keep its legacy columns compatible without copying visitor identifiers,
// arbitrary URL segments or unreviewed query values into the database.
const {resource, parameters} = requestAuditContext(route, req.raw.url);
const isDev = process.env.NODE_ENV === 'development';
void this.apiRequestRecorder.insert([
clientIP, clientOrigin, method, boundedAuditText(path ?? '', 255), JSON.stringify(query),
'', '', req.method, boundedAuditText(resource, 255), JSON.stringify(parameters),
reply.statusCode >= 400, reply.statusCode, reply.elapsedTime, isDev
]);
done();
Expand Down
Loading