This commit is contained in:
Andrey Golanov 2026-11-01 21:27:56 +05:30 • committed by GitHub
commit 7221abd8cb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 504 additions and 3 deletions

View file

@ -30,6 +30,40 @@
> Per-repo read-only tools take an optional `repo` parameter. Omit it when only one repo is indexed, an MCP default is configured, or the GitNexus process cwd is inside a registered path without crossing into an unindexed nested Git checkout; otherwise pass it explicitly. Mutating tools require `repo` when multiple repos are indexed and no MCP default exists. Per-repo tools also take an optional `branch` for indexes pinned with `gitnexus analyze --branch`, except `read_file` and `grep`, which read the checkout and do not accept `branch`. Omitting `branch` queries the workspace index, which follows your checked-out working tree — switching branches and re-running `gitnexus analyze` updates it incrementally. `explain` and `pdg_query` need an index built with `gitnexus analyze --pdg`.
### AdonisJS taint coverage
The TypeScript/JavaScript model recognizes directly assigned or destructured results of `input`, `qs`,
`header`, `param`, `cookie`, `all`, `body`, `params`, `headers`, `only`, `except`,
and `validateUsing` calls on `req`, `request`, or `ctx.request`. The request call
must supply the entire assigned value; `await`, parentheses, and TypeScript
`as`, `satisfies`, and non-null assertions may wrap it. For example:
```ts
const name = request.input('name');
await db.rawQuery('select * from users where name = ' + name); // SQL injection finding
await db.rawQuery('select * from users where name = ?', [name]); // value binding
```
`rawQuery` consumes SQL at argument 0. The model recognizes `db`, `database`, and
`trx` receivers, plus aliases imported from `@adonisjs/lucid/services/db`.
`Model.query()` without arguments starts a query builder and is not itself a
SQL injection sink. `validateUsing()` remains a source: schema validation can
accept strings that are unsafe when concatenated into SQL or executable code.
Request receiver matching is conventional and exact; arbitrary aliases are not
modeled. The call-result rules also do not cover inline calls, concatenation,
template interpolation, method chains, `??` / `||` expressions, or wrapper calls
such as `String(request.input('name'))`, even when the containing expression is
assigned to a variable. For example, neither of these introduces a modeled source:
```ts
db.rawQuery(request.input('sql'));
const name = request.input('name', '').trim();
```
A zero-finding result does not establish safety. Re-run
`gitnexus analyze --pdg` after upgrading to rebuild findings with the new model.
### Resources for instant context
| Resource | Purpose |

View file

@ -356,6 +356,9 @@ const SPAWN_CLI = [
const WORKER_THREADS = [
// Native callback parsing and exact caller/summary ownership (#3489).
'test/integration/cfg/interproc-taint.test.ts',
// AdonisJS sources and Lucid sinks through a real parse worker, then the
// warm parse-cache and ParsedFile-store path (#2982).
'test/integration/cfg/adonis-taint.test.ts',
'test/integration/function-local-identity.test.ts',
'test/integration/java-imported-return-types.test.ts',
'test/integration/resolvers/java-overload-jls.test.ts',

View file

@ -449,9 +449,9 @@ export function matchFunctionSites(
for (const entry of spec.sources) {
if (!isCallResultSource(entry)) continue;
if (
resolved.path.length === 2 &&
entry.receivers.includes(resolved.path[0]) &&
entry.methods.includes(resolved.path[1])
resolved.path.length >= 2 &&
entry.receivers.includes(resolved.path.slice(0, -1).join('.')) &&
entry.methods.includes(resolved.path[resolved.path.length - 1])
) {
sources.push({
type: 'call-result',

View file

@ -119,6 +119,7 @@ export interface TaintMemberSourceEntry {
export interface TaintCallResultSourceEntry {
readonly type: 'call-result';
readonly kind: SourceKind;
/** Exact conventional receiver paths, e.g. `request` or `ctx.request`. */
readonly receivers: readonly string[];
readonly methods: readonly string[];
}

View file

@ -36,6 +36,29 @@ export const TS_JS_TAINT_MODEL: SourceSinkSanitizerSpec = {
objects: ['req', 'request'],
properties: ['body', 'query', 'params', 'headers', 'cookies'],
},
// AdonisJS reads request data through methods, including when the
// request is accessed through HttpContext rather than destructured.
// Schema validation can still allow arbitrary strings: validateUsing
// does not by itself neutralize SQL, shell, path, or markup injection.
{
type: 'call-result',
kind: 'remote-input',
receivers: ['req', 'request', 'ctx.request'],
methods: [
'input',
'qs',
'header',
'param',
'cookie',
'all',
'body',
'params',
'headers',
'only',
'except',
'validateUsing',
],
},
],
sinks: [
// Command execution — shell strings are arg 0; argv-form APIs also treat
@ -99,6 +122,16 @@ export const TS_JS_TAINT_MODEL: SourceSinkSanitizerSpec = {
receivers: ['db', 'database', 'conn', 'client', 'pool'],
},
{ name: 'raw', kind: 'sql-injection', args: [0], receivers: ['db', 'knex', 'sequelize'] },
// Lucid consumes SQL at argument 0; argument 1 contains value bindings.
// Preserve import provenance for aliases of the Adonis database service
// alongside conventional database/transaction handles.
{
name: 'rawQuery',
kind: 'sql-injection',
args: [0],
module: '@adonisjs/lucid/services/db',
},
{ name: 'rawQuery', kind: 'sql-injection', args: [0], receivers: ['db', 'database', 'trx'] },
// Reflected XSS — Express response writes, conventional receiver `res`.
{ name: 'send', kind: 'xss', args: [0], receivers: ['res'] },
{ name: 'write', kind: 'xss', args: [0], receivers: ['res'] },

View file

@ -0,0 +1,150 @@
import fs from 'node:fs';
import path from 'node:path';
import { assert, describe, expect, it } from 'vitest';
import { runPipelineFromRepo } from '../../../src/core/ingestion/pipeline.js';
import { decodeTaintPath } from '../../../src/core/ingestion/taint/path-codec.js';
import { loadParseCache, saveParseCache } from '../../../src/storage/parse-cache.js';
import {
getDurableParsedFileDir,
pruneAndSaveDurableParsedFileStore,
} from '../../../src/storage/parsedfile-store.js';
import type { PipelineResult } from '../../../src/types/pipeline.js';
import { createTempDirPool } from '../../helpers/temp-dir-pool.js';
import { runtimeParseIdentity } from '../../helpers/runtime-parse-identity.js';
const directories = createTempDirPool('gn-adonis-taint-');
const parseIdentity = await runtimeParseIdentity();
const workerOptions = {
workerPoolSize: 1,
workerThresholdsForTest: { minFiles: 1, minBytes: 1 },
} as const;
const controller = `import sqlClient from '@adonisjs/lucid/services/db';
import { runQuery } from './sink';
export default class UsersController {
async sqlFromInput({ request }) {
const name = request.input('name');
return sqlClient.rawQuery('select * from users where name = ' + name);
}
async sqlFromContext(ctx) {
const params = ctx.request.qs();
return sqlClient.rawQuery('select * from users where name = ' + params.name);
}
async sqlFromValidated({ request }) {
const payload = await request.validateUsing(searchValidator);
return sqlClient.rawQuery('select * from users where name = ' + payload.name);
}
async boundValue({ request }) {
const name = request.input('name');
return sqlClient.rawQuery('select * from users where name = ?', [name]);
}
async queryBuilder({ request }) {
const name = request.input('name');
return User.query().where('name', name);
}
async forward({ request }) {
const name = request.header('x-name');
return runQuery(name);
}
}
`;
const sink = `import db from '@adonisjs/lucid/services/db';
export function runQuery(sql) {
return db.rawQuery(sql);
}
`;
function findingOwners(result: PipelineResult) {
const ownerName = (id: string) => {
const node = result.graph.getNode(id);
assert(node !== undefined, `Expected taint endpoint ${id}`);
if (node.label !== 'BasicBlock') return node.properties.name;
// CFG line numbers are 1-based; Function/Method startLine is 0-based.
const functionStartLine = Number(node.id.split(':').at(-3));
const owner = [...result.graph.iterNodes()].find(
(candidate) =>
(candidate.label === 'Function' || candidate.label === 'Method') &&
candidate.properties.filePath === node.properties.filePath &&
candidate.properties.startLine === functionStartLine - 1,
);
assert(owner !== undefined, `Expected function owning ${id}`);
return owner.properties.name;
};
return [...result.graph.iterRelationships()]
.filter((edge) => edge.type === 'TAINTED' || edge.type === 'TAINT_PATH')
.map((edge) => {
const decoded = decodeTaintPath(edge.reason);
expect(decoded.ok).toBe(true);
return {
type: edge.type,
source: ownerName(edge.sourceId),
target: ownerName(edge.targetId),
kind: decoded.ok ? decoded.kind : undefined,
};
})
.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));
}
describe('AdonisJS taint through real workers (#2982)', () => {
it.each(['ts', 'js'])(
'preserves %s findings and safe SQL controls through cold and warm parsing',
async (extension) => {
const repo = directories.dir();
const storage = directories.dir();
fs.writeFileSync(path.join(repo, `controller.${extension}`), controller);
fs.writeFileSync(path.join(repo, `sink.${extension}`), sink);
const cache = await loadParseCache(storage, parseIdentity, storage);
const cold = await runPipelineFromRepo(repo, () => {}, {
...workerOptions,
pdg: true,
parseCache: cache,
});
expect(cold.usedWorkerPool).toBe(true);
expect(cold.reparsedFileCount).toBe(2);
expect(cold.scopeExtractionFailures).toEqual([]);
expect(findingOwners(cold)).toEqual([
{ type: 'TAINT_PATH', source: 'forward', target: 'runQuery', kind: 'sql-injection' },
{
type: 'TAINTED',
source: 'sqlFromContext',
target: 'sqlFromContext',
kind: 'sql-injection',
},
{ type: 'TAINTED', source: 'sqlFromInput', target: 'sqlFromInput', kind: 'sql-injection' },
{
type: 'TAINTED',
source: 'sqlFromValidated',
target: 'sqlFromValidated',
kind: 'sql-injection',
},
]);
const savedKeys = await saveParseCache(storage, cache);
expect(savedKeys.length).toBeGreaterThan(0);
await pruneAndSaveDurableParsedFileStore(
getDurableParsedFileDir(storage),
parseIdentity.base,
new Set(savedKeys),
);
const warm = await runPipelineFromRepo(repo, () => {}, {
...workerOptions,
pdg: true,
parseCache: await loadParseCache(storage, parseIdentity, storage),
});
expect(warm.usedWorkerPool).toBe(false);
expect(warm.reparsedFileCount).toBe(0);
expect(warm.parseCacheHitFileCount).toBe(2);
expect(findingOwners(warm)).toEqual(findingOwners(cold));
const off = await runPipelineFromRepo(repo, () => {}, { ...workerOptions });
expect(findingOwners(off)).toEqual([]);
},
);
});

View file

@ -643,6 +643,65 @@ withTestLbugDB(
},
);
withTestLbugDB(
'taint-explain-adonis',
(handle) => {
it('explain reports persisted AdonisJS input reaching rawQuery (#2982)', async () => {
const backend = (handle as typeof handle & { _backend: LocalBackend })._backend;
const unsafe = await backend.callTool('explain', { target: 'unsafeQuery' });
expect(unsafe).not.toHaveProperty('error');
expect(unsafe.totalFindings).toBe(1);
expect(unsafe.findings).toEqual([
expect.objectContaining({ sinkKind: 'sql-injection', file: 'controller.ts' }),
]);
const safe = await backend.callTool('explain', { target: 'boundQuery' });
expect(safe).not.toHaveProperty('error');
expect(safe.totalFindings).toBe(0);
});
},
{
poolAdapter: true,
beforeFTS: async (dbPath) => {
const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-adonis-explain-'));
try {
fs.writeFileSync(
path.join(repoDir, 'controller.ts'),
`import db from '@adonisjs/lucid/services/db';
export function unsafeQuery(ctx) {
const name = ctx.request.input('name');
return db.rawQuery('select * from users where name = ' + name);
}
export function boundQuery({ request }) {
const name = request.input('name');
return db.rawQuery('select * from users where name = ?', [name]);
}
`,
);
const result = await runPipelineFromRepo(repoDir, () => {}, { pdg: true });
const adapter = await import('../../src/core/lbug/lbug-adapter.js');
await adapter.loadGraphToLbug(result.graph, repoDir, path.dirname(dbPath));
} finally {
fs.rmSync(repoDir, { recursive: true, force: true });
}
},
afterSetup: async (handle) => {
vi.mocked(listRegisteredRepos).mockResolvedValue([
{
name: 'adonis-taint-repo',
path: '/adonis-taint/repo',
storagePath: handle.tmpHandle.dbPath,
indexedAt: new Date().toISOString(),
lastCommit: 'adonis001',
stats: { files: 1, nodes: 1, communities: 0, processes: 0 },
},
]);
const backend = new LocalBackend();
await backend.init();
(handle as typeof handle & { _backend: LocalBackend })._backend = backend;
},
},
);
// ─── Block 4: symbol-anchor window correctness (#2188 _explainImpl off-by-one) ──
//
// Hand-seeded with controlled line numbers (no parser dependency). `tailFn`

View file

@ -0,0 +1,221 @@
import { describe, expect, it } from 'vitest';
import { cfgOf, importsFor } from '../../helpers/ts-cfg-harness.js';
import { computeReachingDefs } from '../../../src/core/ingestion/cfg/reaching-defs.js';
import {
buildTaintImportIndex,
matchFunctionSites,
} from '../../../src/core/ingestion/taint/match.js';
import { computeTaintFlows } from '../../../src/core/ingestion/taint/propagate.js';
import { harvestFunctionSummary } from '../../../src/core/ingestion/taint/summary-harvest.js';
import { hasTaintSafeSites } from '../../../src/core/ingestion/taint/site-safety.js';
import type { SourceSinkSanitizerSpec } from '../../../src/core/ingestion/taint/source-sink-config.js';
import { TS_JS_TAINT_MODEL } from '../../../src/core/ingestion/taint/typescript-model.js';
function analyzeAdonis(code: string, spec: SourceSinkSanitizerSpec = TS_JS_TAINT_MODEL) {
const cfg = cfgOf(code);
expect(hasTaintSafeSites(cfg)).toBe(true);
const matches = matchFunctionSites(cfg, spec, buildTaintImportIndex(importsFor(code)));
const defUse = computeReachingDefs(cfg);
return {
matches,
flows: computeTaintFlows(cfg, defUse, matches),
summary: harvestFunctionSummary(cfg, defUse, matches).facts,
};
}
describe('AdonisJS request sources (#2982)', () => {
describe.each(['request', 'req', 'ctx.request'])('%s', (receiver) => {
it.each([
'input',
'qs',
'header',
'param',
'cookie',
'all',
'body',
'params',
'headers',
'only',
'except',
])('tracks the assigned result of %s() to a dangerous call', (method) => {
const { flows } = analyzeAdonis(`function controller(request, req, ctx) {
const value = ${receiver}.${method}('value');
eval(value);
}`);
expect(flows.status).toBe('computed');
expect(flows.findings).toHaveLength(1);
expect(flows.findings[0]).toMatchObject({
source: { type: 'call-result', calleeName: `${receiver}.${method}` },
sinkKind: 'code-injection',
sink: { entryName: 'eval', argIndex: 0 },
});
});
});
it('tracks a request destructured from HttpContext in a controller method', () => {
const { flows } = analyzeAdonis(`import type { HttpContext } from '@adonisjs/core/http';
export default class UsersController {
async index({ request }: HttpContext) {
const value = request.input('search');
eval(value);
}
}`);
expect(flows.findings).toHaveLength(1);
});
it('seeds an interprocedural flow from request.input() into a helper', () => {
const { summary } = analyzeAdonis(`function controller({ request }) {
const value = request.input('search');
runQuery(value);
}`);
expect(summary.sourceToCallArg).toEqual([
expect.objectContaining({
sourceKind: 'remote-input',
calleeName: 'runQuery',
argIndex: 0,
}),
]);
});
it('treats validateUsing output as input, without assuming schema validation escapes code', () => {
const { flows, matches } = analyzeAdonis(`async function controller({ request }) {
const payload = await request.validateUsing(searchValidator);
eval(payload.search);
}`);
expect(flows.findings).toHaveLength(1);
expect(flows.kills).toEqual([]);
expect(matches.statements.flatMap((statement) => statement.sanitizers)).toEqual([]);
});
it.each(['cache', 'ctx.response', 'other.request', 'ctx.request.extra'])(
'does not infer HTTP input from an unregistered receiver %s',
(receiver) => {
const { matches, flows } = analyzeAdonis(`function controller(cache, ctx, other) {
const value = ${receiver}.input('value');
eval(value);
}`);
expect(matches.hasSource).toBe(false);
expect(flows.findings).toEqual([]);
},
);
it('does not treat an uncalled request method as its result', () => {
const { matches } = analyzeAdonis(`function controller(request) {
const method = request.input;
eval(method);
}`);
expect(matches.hasSource).toBe(false);
});
it('tracks a request result destructured directly into a local binding', () => {
const { flows } = analyzeAdonis(`function controller({ request }, db) {
const { name } = request.only(['name']);
db.rawQuery('select * from users where name = ' + name);
}`);
expect(flows.findings).toHaveLength(1);
expect(flows.findings[0]).toMatchObject({
source: { type: 'call-result', calleeName: 'request.only' },
sinkKind: 'sql-injection',
});
});
// These are coverage gaps, not safe expressions. Keep the documented
// direct-assignment boundary explicit until inline sources are supported.
it.each([
['inline call', "db.rawQuery(request.input('sql'));"],
['concatenation', "const sql = 'select ' + request.input('name'); db.rawQuery(sql);"],
['method chain', "const name = request.input('name', '').trim(); db.rawQuery(name);"],
['nullish fallback', "const name = request.input('name') ?? ''; db.rawQuery(name);"],
['logical fallback', "const name = request.input('name') || ''; db.rawQuery(name);"],
['wrapper call', "const name = String(request.input('name')); db.rawQuery(name);"],
['template interpolation', "const sql = `select ${request.input('name')}`; db.rawQuery(sql);"],
])('documents the current source coverage gap for %s', (_name, body) => {
const { matches, flows } = analyzeAdonis(`function controller({ request }, db) {
${body}
}`);
expect(matches.hasSink).toBe(true);
expect(matches.hasSource).toBe(false);
expect(flows.findings).toEqual([]);
});
});
describe('Lucid SQL sinks (#2982)', () => {
it.each(['db', 'database', 'trx'])('tracks rawQuery SQL on %s', (receiver) => {
const { flows } = analyzeAdonis(`function controller(req, ${receiver}) {
const sql = req.body.sql;
${receiver}.rawQuery(sql);
}`);
expect(flows.findings).toHaveLength(1);
expect(flows.findings[0]).toMatchObject({
sinkKind: 'sql-injection',
sink: { entryName: 'rawQuery', argIndex: 0 },
});
});
it('resolves an aliased Lucid database service import', () => {
const { flows } = analyzeAdonis(`import sqlClient from '@adonisjs/lucid/services/db';
function controller(req) {
sqlClient.rawQuery(req.body.sql);
}`);
expect(flows.findings).toHaveLength(1);
expect(flows.findings[0].sinkKind).toBe('sql-injection');
});
it('does not flag input supplied only through SQL value bindings', () => {
const { flows } = analyzeAdonis(`function controller(req, db) {
const value = req.body.value;
db.rawQuery('select * from users where name = ?', [value]);
}`);
expect(flows.findings).toEqual([]);
});
it('does not flag the zero-argument Lucid query builder', () => {
const { flows } = analyzeAdonis(`function controller(req, User) {
const value = req.body.name;
User.query().where('name', value);
}`);
expect(flows.findings).toEqual([]);
});
it('does not flag an unrelated rawQuery method', () => {
const { matches } = analyzeAdonis(`function controller(req, cache) {
cache.rawQuery(req.body.value);
}`);
expect(matches.hasSink).toBe(false);
});
});
describe('call-result source receiver paths', () => {
const spec: SourceSinkSanitizerSpec = {
sources: [
{ type: 'call-result', kind: 'remote-input', receivers: ['ctx.request'], methods: ['input'] },
],
sinks: [{ name: 'eval', kind: 'code-injection', global: true, args: [0] }],
sanitizers: [],
};
it('matches a configured full receiver path rather than only its first segment', () => {
const { flows } = analyzeAdonis(
`function controller(ctx) {
const value = ctx.request.input('search');
eval(value);
}`,
spec,
);
expect(flows.findings).toHaveLength(1);
});
it.each(['request', 'other.request', 'ctx.other.request', 'ctx.request.extra'])(
'does not match %s as ctx.request',
(receiver) => {
const { matches } = analyzeAdonis(
`function controller(ctx, other, request) {
const value = ${receiver}.input('search');
eval(value);
}`,
spec,
);
expect(matches.hasSource).toBe(false);
},
);
});