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: 2 additions & 0 deletions packages/api-server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ as trusted. Public clients cannot choose their quota identity with IP headers.

Set the same private `SUPPRESSED_GITHUB_ACCOUNTS` list on the web and API runtimes and restart both when the list changes. Public named queries and v1 results apply it after data retrieval, including cache hits. The policy handles account IDs and logins, repository owners, and grouped contributor and participant logins. Historical aggregate counts can still include past activity. When a new query returns an account under a different column name, add its identity mapping and a response test.

The authenticated `POST /q/playground` route applies configured account removals to the five public analytics sources before aggregates, joins or aliases are evaluated. The API and its shadow database reader need SELECT on repository metadata when filtering events, topics or trending repositories. Topics without resolvable repository ownership are omitted while removals are configured. The response contains the scoped SQL submitted for execution and never includes the private bind values. Database operators should restrict access to statement diagnostics, including any logging of bound parameters.

Collection-bearing catalog results retain their configured cache and prefetch-only
policy. Before returning cached trending/collection results, the API refreshes
public collection names and memberships with bounded metadata lookups; revoked
Expand Down
81 changes: 81 additions & 0 deletions packages/api-server/__tests__/core/playground-account-filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import Fastify from 'fastify';
import playground from '../../src/routes/q/playground';
import {registerRequestAudit} from '../../src/utils/http/request-audit';
import {createConnection, createPool} from 'mysql2/promise';
import {TiDBPlaygroundQueryExecutor} from '../../src/core/executor/query-executor/TiDBPlaygroundQueryExecutor';
import {SqlParser} from '../../src/core/playground/playground';
import {SQLRunner} from '../../src/core/runner/sql/SQLRunner';
import {bootstrapTestDatabase, getTestDatabase, releaseTestDatabase} from '../helpers/db';
import {testLogger} from '../helpers/log';

beforeAll(bootstrapTestDatabase);
afterAll(releaseTestDatabase);

test('custom projections, joins and aggregates use visible rows in the selected scope', async () => {
const db = getTestDatabase();
const setup = await createConnection({uri: db.rootUrl(), database: db.database});
try {
await setup.query(`INSERT INTO github_users (id, login, stars_total) VALUES
(42, 'renamed-fixture', 0), (7, 'visible', 0), (81, 'WITHDRAWN', 0)`);
await setup.query(`INSERT INTO github_repos (repo_id, repo_name, owner_id, owner_login, owner_is_org) VALUES
(42, 'visible/project', 7, 'visible', 0), (77, 'renamed-fixture/other', 42, 'renamed-fixture', 0)`);
await setup.query("INSERT INTO github_repo_topics VALUES (42, 'visible-topic'), (77, 'private-topic')");
await setup.query("INSERT INTO trending_repos (id, repo_name) VALUES (42, 'visible/project'), (77, 'renamed-fixture/other'), (80, 'WITHDRAWN/old')");
await setup.query(`INSERT INTO github_events
(id, repo_id, repo_name, actor_id, org_login, creator_user_id, event_day, event_month, event_year) VALUES
(1, 42, 'visible/project', 7, '', 0, '2024-01-01', '2024-01-01', 2024),
(2, 42, 'visible/project', 42, '', 0, '2024-01-01', '2024-01-01', 2024),
(3, 42, 'visible/project', 7, 'WITHDRAWN', 0, '2024-01-01', '2024-01-01', 2024),
(4, 42, 'visible/project', 7, '', 42, '2024-01-01', '2024-01-01', 2024),
(5, 77, 'historic/project', 7, '', 0, '2024-01-01', '2024-01-01', 2024)`);
} finally {
await setup.end();
}

const pool = createPool(db.analyticsUrl());
const original = process.env.SUPPRESSED_GITHUB_ACCOUNTS;
try {
process.env.SUPPRESSED_GITHUB_ACCOUNTS = 'withdrawn:42';
const runner = new SQLRunner(new TiDBPlaygroundQueryExecutor(pool, null, testLogger));
const run = async (input: string, id = '42') => {
const sql = new SqlParser('repo', id, input).sqlify();
const result = await runner.run(sql);
expect(result.sql).toBe(sql);
for (const field of result.fields) expect(['ids', 'logins']).not.toContain(field.name);
return result.data;
};
expect(await run('SELECT github_users.login AS handle FROM github_users')).toEqual([{handle: 'visible'}]);
expect(await run('WITH activity AS (SELECT actor_id FROM github_events) SELECT COUNT(*) AS activity_count FROM activity'))
.toEqual([{activity_count: 1}]);
expect(await run('SELECT COUNT(*) AS activity_count FROM github_events', '77')).toEqual([{activity_count: 0}]);
expect(await run('SELECT t.topic FROM github_repo_topics AS t JOIN github_repos AS r ON r.repo_id = t.repo_id'))
.toEqual([{topic: 'visible-topic'}]);
expect(await run('SELECT id, repo_name FROM trending_repos')).toEqual([{id: 42, repo_name: 'visible/project'}]);
const rows = await run('SELECT repo_name FROM github_repos UNION ALL SELECT repo_name FROM trending_repos');
expect(rows).toEqual([{repo_name: 'visible/project'}, {repo_name: 'visible/project'}]);
expect(await run('WITH ossinsight_visible_github_users AS (SELECT login FROM github_users) SELECT login FROM ossinsight_visible_github_users'))
.toEqual([{login: 'visible'}]);
expect(await run("SELECT '?' AS punctuation")).toEqual([{punctuation: '?'}]);

const app = Fastify();
try {
app.decorate('authenticate', async () => {});
app.decorate('userService', {checkAccountStatus: async () => {}} as any);
app.decorate('sqlRunner', runner);
registerRequestAudit(app);
await app.register(playground, {prefix: '/q/playground'});
const response = await app.inject({method: 'POST', url: '/q/playground',
payload: {type: 'repo', id: '42', sql: 'SELECT COUNT(*) AS total FROM github_events'}});
expect(response.statusCode).toBe(200);
expect(response.headers['cache-control']).toBe('no-store');
expect(response.json().data).toEqual([{total: 1}]);
expect(response.body).not.toMatch(/withdrawn|ossinsight_visible_/i);
} finally {
await app.close();
}
} finally {
if (original === undefined) delete process.env.SUPPRESSED_GITHUB_ACCOUNTS;
else process.env.SUPPRESSED_GITHUB_ACCOUNTS = original;
await pool.end();
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {enforceSQLPolicy, preparePlaygroundSQL} from '../../src/core/playground/sql-policy';
import {SqlParser} from '../../src/core/playground/playground';

const accounts = [{id: 12345, login: 'private-fixture'}];

test('a repeated source uses a single filtered relation and keeps the scope and original aliases', () => {
const scoped = new SqlParser('repo', '77', 'SELECT x.id FROM github_events x JOIN github_events y ON x.id = y.id').sqlify();
const {sql, values} = preparePlaygroundSQL(scoped, accounts);
expect(sql.match(/ossinsight_visible_github_events AS \(SELECT/g)).toHaveLength(1);
expect(sql).toContain('77');
expect(sql).not.toMatch(/private-fixture|12345/);
expect(values).toEqual(['12345', 'private-fixture']);
});

test('the empty list preserves ordinary SQL and a constant query needs no private bindings', () => {
const query = 'SELECT github_users.login FROM github_users';
expect(preparePlaygroundSQL(query, [])).toEqual({sql: enforceSQLPolicy(query), values: []});
expect(preparePlaygroundSQL("SELECT '?' AS punctuation", accounts).values).toEqual([]);
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import {Connection, Pool, QueryOptions} from "mysql2/promise";
import {Counter, Histogram} from 'prom-client';
import {Fields, Rows, Values} from './QueryExecutor';
import {enforceSQLPolicy} from '../../playground/sql-policy';
import {parseSuppressedAccounts} from '@ossinsight/types';
import {enforceSQLPolicy, preparePlaygroundSQL} from '../../playground/sql-policy';
import pino from "pino";
import { TiDBQueryExecutor } from "./TiDBQueryExecutor";
import { decoratePoolConnections } from "../../db/pool-decorator";
Expand All @@ -10,17 +11,22 @@ import {DEFAULT_PLAYGROUND_QUERY_TIMEOUT, validatePlaygroundQueryTimeout} from '
export class TiDBPlaygroundQueryExecutor extends TiDBQueryExecutor {
protected readonly logger: pino.Logger = this.pLogger.child({ module: 'tidb-query-executor' });

private readonly suppressedAccounts = parseSuppressedAccounts(process.env.SUPPRESSED_GITHUB_ACCOUNTS);

// All entry points (including queued jobs, EXPLAIN and shadow execution) pass
// here. A caller cannot bypass policy by invoking executeWithConn directly.
async executeWithConnInternal<T extends Rows>(
timer: Histogram, counter: Counter, conn: Connection,
queryKey: string, input: string | QueryOptions, values?: Values,
): Promise<[T, Fields]> {
const sql = enforceSQLPolicy(typeof input === 'string' ? input : input.sql);
const statement = typeof input === 'string' ? input : input.sql;
const prepared = queryKey === 'playground-sql' && this.suppressedAccounts.length
? preparePlaygroundSQL(statement, this.suppressedAccounts)
: {sql: enforceSQLPolicy(statement), values: typeof input === 'string' ? values : input.values};
const requested = typeof input === 'string' ? undefined : input.timeout;
const timeout = Number.isSafeInteger(requested) && requested! > 0
? Math.min(requested!, this.statementTimeoutMs) : this.statementTimeoutMs;
const safeInput = {...(typeof input === 'string' ? {values} : input), sql, timeout};
const safeInput = {...(typeof input === 'string' ? {} : input), ...prepared, timeout};
try {
// Also enforce the budget for externally supplied/reused connections and
// smaller per-query budgets. The AST serializer strips caller SQL hints.
Expand Down
5 changes: 5 additions & 0 deletions packages/api-server/src/core/playground/sql-policy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
enforceSQLPolicy as enforce,
preparePlaygroundSQL as prepare,
positiveId as parsePositiveId,
SQLPolicyError,
SQLPolicy,
Expand All @@ -25,3 +26,7 @@ export function positiveId(value: unknown): number {
export function enforceSQLPolicy(sql: string, policy: SQLPolicy = {}): string {
return apiPolicy(() => enforce(sql, policy));
}

export function preparePlaygroundSQL(sql: string, accounts: Parameters<typeof prepare>[1]) {
return apiPolicy(() => prepare(sql, accounts));
}
70 changes: 70 additions & 0 deletions packages/sql-policy/src/account-row-filter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
export interface FilterAccount {
readonly id: number;
readonly login: string;
}

const hasId = (column: string) => `FIND_IN_SET(COALESCE(CAST(${column} AS CHAR), ''), policy.ids) > 0`;
const hasLogin = (column: string) => `FIND_IN_SET(LOWER(COALESCE(${column}, '')), policy.logins) > 0`;
const repoOwner = (table: string) => hasLogin(`SUBSTRING_INDEX(${table}.repo_name, '/', 1)`);
const excludedRepo = (table: string) =>
`(${hasId(table + '.owner_id')} OR ${hasLogin(table + '.owner_login')} OR ${repoOwner(table)})`;

// Trending IDs identify observations, not repositories. Resolve topic ownership
// by repository ID and trending ownership by name. Events also carry historical
// actor, creator, organization and repository names independently of the catalog.
const predicates: Readonly<Record<string, string>> = {
github_users: `NOT (${hasId('src.id')} OR ${hasLogin('src.login')})`,
github_repos: `NOT ${excludedRepo('src')}`,
github_repo_topics: `EXISTS (SELECT 1 FROM github_repos AS repo
WHERE repo.repo_id = src.repo_id AND NOT ${excludedRepo('repo')})`,
trending_repos: `NOT (${repoOwner('src')}) AND NOT EXISTS (SELECT 1 FROM github_repos AS repo
WHERE repo.repo_name = src.repo_name AND ${excludedRepo('repo')})`,
github_events: `NOT (${hasId('src.actor_id')} OR ${hasLogin('src.actor_login')}
OR ${hasId('src.org_id')} OR ${hasLogin('src.org_login')}
OR ${hasId('src.creator_user_id')} OR ${hasLogin('src.creator_user_login')} OR ${repoOwner('src')})
AND NOT EXISTS (SELECT 1 FROM github_repos AS repo
WHERE repo.repo_id = src.repo_id AND ${excludedRepo('repo')})`,
};

export class AccountRowFilter {
private readonly sources = new Set<string>();

private readonly prefix: string;

constructor(private readonly accounts: ReadonlyArray<FilterAccount>, query: string) {
// User-defined CTEs and aliases retain their original names.
const used = new Set(query.toLowerCase().match(/ossinsight_visible\d*_/g) || []);
let prefix = 'ossinsight_visible_';
for (let suffix = 1; used.has(prefix); suffix++) {
prefix = `ossinsight_visible${suffix}_`;
}
this.prefix = prefix;
}

isReserved(name: string) {
return name.startsWith(this.prefix);
}

source(table: string) {
if (!Object.prototype.hasOwnProperty.call(predicates, table)) throw new Error('Unsupported privacy filter source');
this.sources.add(table);
return this.prefix + table;
}

prepare(query: string) {
if (!this.sources.size) return {sql: query, values: [] as string[]};
const ids = this.accounts.map(account => String(account.id)).join(',');
const logins = this.accounts.map(account => account.login.toLowerCase()).join(',');
const values: string[] = [];
const relations = Array.from(this.sources, table => {
values.push(ids, logins);
// These bound parameters precede all caller SQL. Only the physical
// table's own columns are projected into the authorized query.
return `${this.prefix}${table} AS (SELECT src.* FROM ${table} AS src
CROSS JOIN (SELECT ? AS ids, ? AS logins) AS policy WHERE ${predicates[table]})`;
});
const withClause = /^WITH\s+/i;
const separator = withClause.test(query) ? ', ' : ' ';
return {sql: 'WITH ' + relations.join(', ') + separator + query.replace(withClause, ''), values};
}
}
32 changes: 28 additions & 4 deletions packages/sql-policy/src/sql-policy.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {AccountRowFilter, FilterAccount} from './account-row-filter';
import { Parser } from 'node-sql-parser/build/mysql';
export class SQLPolicyError extends Error {}

Expand Down Expand Up @@ -32,11 +33,27 @@ export function positiveId(value: unknown): number {
return Number(value);
}

/** Parse, authorize, and serialize. Never execute the original input on failure. */
export function enforceSQLPolicy(sql: string, policy: SQLPolicy = {}): string {
if (typeof sql !== 'string' || !sql.trim() || sql.length > 32000) {
function checkedStatement(sql: string): string {
if (typeof sql !== 'string' || sql.length > 32000 || !sql.trim()) {
reject('A non-empty SQL statement of at most 32000 characters is required');
}
return sql;
}

/** Parse, authorize, and serialize. Never execute the original input on failure. */
export function enforceSQLPolicy(sql: string, policy: SQLPolicy = {}): string {
return authorizeSQL(checkedStatement(sql), policy);
}

/** Prepare the authenticated playground statement at its final execution boundary. */
export function preparePlaygroundSQL(sql: string, accounts: ReadonlyArray<FilterAccount>) {
if (!accounts.length) return {sql: enforceSQLPolicy(sql), values: [] as string[]};
const statement = checkedStatement(sql);
const filter = new AccountRowFilter(accounts, statement);
return filter.prepare(authorizeSQL(statement, {}, filter));
}

function authorizeSQL(sql: string, policy: SQLPolicy, filter?: AccountRowFilter): string {
const parser = new Parser();
let ast: any;
try {
Expand Down Expand Up @@ -64,6 +81,9 @@ export function enforceSQLPolicy(sql: string, policy: SQLPolicy = {}): string {
node.forEach(item => visit(item, ctes));
return;
}
if (filter && node.type === 'origin' && node.value === '?') {
reject('The playground accepts fully specified queries without bind parameters');
}
if (node.type === 'param') {
const name = node.value;
const identity = policy.identity;
Expand Down Expand Up @@ -97,7 +117,7 @@ export function enforceSQLPolicy(sql: string, policy: SQLPolicy = {}): string {
ctes = new Set(ctes);
for (const cte of node.with ?? []) {
const name = cte.name?.value?.toLowerCase();
if (!name || cte.recursive || PUBLIC_ANALYTICS_TABLES.has(name) || ctes.has(name)) {
if (!name || cte.recursive || PUBLIC_ANALYTICS_TABLES.has(name) || filter?.isReserved(name) || ctes.has(name)) {
reject('Invalid or shadowed common table expression');
}
// A CTE can reference earlier CTEs, not itself or a later CTE. Treating
Expand All @@ -111,6 +131,10 @@ export function enforceSQLPolicy(sql: string, policy: SQLPolicy = {}): string {
if (!PUBLIC_ANALYTICS_TABLES.has(name) && !ctes.has(name)) {
reject('Only public analytics tables are allowed');
}
if (filter && PUBLIC_ANALYTICS_TABLES.has(name)) {
from.as = from.as || from.table;
from.table = filter.source(name);
}
} else if (!from.expr?.ast) {
reject('Unsupported SQL data source');
}
Expand Down
Loading