GitNexus/gitnexus/test/unit/security.test.ts
Abhigyan Patwari 60c93d7d4a
feat: upgrade @ladybugdb/core to 0.15.2 and remove segfault workarounds (#374)
* feat: upgrade @ladybugdb/core to 0.15.2 and remove segfault workarounds

The upstream fix (ladybug-nodejs#1) resolves the child QueryResult lifetime
segfault, making .close() safe on all platforms. This removes 6 workaround
sites:

- Remove `dangerouslyIgnoreUnhandledErrors` from vitest config
- Remove platform-conditional .close() guards in global-setup and test helper
- Delete test/setup.ts (process._getActiveHandles unref hack)
- Replace no-op cleanup in test-indexed-db.ts with real adapter close
- Fix pool adapter closeOne() to properly close connections with shared
  Database refcount guard and orphaned connection handling in checkin()
- Update segfault-related comments across the codebase

Also bumps @ladybugdb/wasm-core to ^0.15.2 in gitnexus-web for consistency.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: keep dangerouslyIgnoreUnhandledErrors for macOS N-API exit crash

The N-API destructor ordering crash during worker fork exit on macOS is
independent of the QueryResult lifetime fix in 0.15.2. Tests pass, but
the exit triggers a crash. Keep the flag with an updated comment
explaining the actual cause. Can be removed once LadybugDB fixes all
destructor ordering issues upstream.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* ci: unify test run for single-pass coverage

- Update `npm test` to run all tests (unit + integration + lbug-db)
  via `vitest run` instead of `vitest run test/unit`
- Add `test:unit` script for running unit tests only
- Remove `ci-integration.yml` — the per-file lbug-db process isolation
  is no longer needed with `dangerouslyIgnoreUnhandledErrors` and
  `fileParallelism: false` handling fork exit issues
- Update `ci-unit-tests.yml` to run all tests with build + coverage
- Simplify `ci.yml` gate (two jobs: quality + tests)
- Simplify `ci-report.yml` (single coverage artifact, no merge step)

* fix: update cli-commands test for renamed test:all → test:unit script

* fix: set USERPROFILE in setup-skills test for Windows compatibility

os.homedir() checks USERPROFILE on Windows, not HOME.

* fix: add isolate: false to lbug-db project to prevent fork crashes

On macOS, N-API destructors crash fork workers on exit. With
isolate: true (default), vitest recycles the fork between files,
triggering the crash after each file. After several crashes, the
remaining lbug-db files never execute.

isolate: false keeps all 8 lbug-db files in a single fork — the
fork only exits once after all files complete, and that single exit
crash is caught by dangerouslyIgnoreUnhandledErrors.

* fix: add unique sequence.groupOrder to vitest projects

Vitest v4 requires unique groupOrder when projects have different
maxWorkers (lbug-db has fileParallelism: false → maxWorkers: 1).

* fix: await async close() in global-setup and remove isolate: false

global-setup.ts called conn.close() and db.close() without await —
these return Promise<void> in @ladybugdb/core 0.15.2.  The setup
function returned before the DB was fully closed, so vitest forks
hit a stale file lock when opening the same DB path, crashing the
lbug-db worker before any test ran.

isolate: false caused native state corruption after 2-3 open/close
cycles in the same fork (vitest-specific, not reproducible in plain
Node.js).  Without it, each file gets its own module scope and the
N-API destructor crash at fork exit is caught by
dangerouslyIgnoreUnhandledErrors.

Also fixes fire-and-forget close() calls in the pool adapter —
try/catch around an async close() never catches rejections; changed
to .catch(() => {}) for proper unhandled-rejection prevention.

Before: 0/8 lbug-db files ran on macOS CI (fork crash).
After:  8/8 pass, 84 files, 3077 tests, zero errors.

* fix: update project index references in AGENTS.md and CLAUDE.md to reflect correct symbol counts and relationships

* feat: enhance lbug adapter with external database support and write operation validation

* feat: create ci-tests workflow for comprehensive test coverage across platforms

* ci: move PR report inline to ci.yml, delete ci-report.yml

The old ci-report.yml used workflow_run which always runs code from
the default branch (main). This meant the PR comment used main's
stale report template that still referenced the old unit/integration
split architecture — causing "Merge coverage reports" failures.

Moving the report inline to ci.yml means it runs from the PR branch
and uses the current report template. The report now shows:
- per-platform status (Ubuntu/Windows/macOS columns)
- unified test counts from the single vitest run
- coverage with base branch (main) delta comparison
- commit SHA for traceability

Also removes the save-pr-meta job since the report no longer needs
a separate workflow_run trigger.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergo Magyar <gergomagyar@icloud.com>
2026-03-19 08:25:43 +00:00

193 lines
7.3 KiB
TypeScript

/**
* P0 Unit Tests: Security Hardening
*
* Tests all security hardening in isolation:
* - Write blocking (CYPHER_WRITE_RE)
* - Relation type allowlist
* - Path traversal detection
* - isWriteQuery wrapper
* - isTestFilePath patterns
*/
import { describe, it, expect } from 'vitest';
import {
VALID_RELATION_TYPES,
VALID_NODE_LABELS,
isTestFilePath,
} from '../../src/mcp/local/local-backend.js';
import { CYPHER_WRITE_RE, isWriteQuery } from '../../src/mcp/core/lbug-adapter.js';
// ─── Write-operation blocking (CYPHER_WRITE_RE) ──────────────────────
describe('CYPHER_WRITE_RE', () => {
const writeKeywords = ['CREATE', 'DELETE', 'SET', 'MERGE', 'REMOVE', 'DROP', 'ALTER', 'COPY', 'DETACH'];
for (const keyword of writeKeywords) {
it(`matches "${keyword}" (uppercase)`, () => {
expect(CYPHER_WRITE_RE.test(`${keyword} (n:Node)`)).toBe(true);
});
it(`matches "${keyword.toLowerCase()}" (lowercase)`, () => {
expect(CYPHER_WRITE_RE.test(`${keyword.toLowerCase()} (n:Node)`)).toBe(true);
});
it(`matches "${keyword[0] + keyword.slice(1).toLowerCase()}" (mixed case)`, () => {
const mixed = keyword[0] + keyword.slice(1).toLowerCase();
expect(CYPHER_WRITE_RE.test(`${mixed} (n:Node)`)).toBe(true);
});
}
// Safe read queries should NOT be blocked
const safeQueries = [
'MATCH (n) RETURN n',
'MATCH (n:Function) WHERE n.name = "foo" RETURN n',
'MATCH (a)-[r]->(b) RETURN a, r, b',
'OPTIONAL MATCH (n)-[r]->(m) RETURN n, r, m',
'MATCH (n) WITH n RETURN n.name',
'UNWIND [1,2,3] AS x RETURN x',
'MATCH (n) RETURN count(n)',
'MATCH (n:Function) WHERE n.filePath CONTAINS "test" RETURN n',
];
for (const query of safeQueries) {
it(`does NOT block safe query: "${query.slice(0, 50)}..."`, () => {
expect(CYPHER_WRITE_RE.test(query)).toBe(false);
});
}
it('blocks write keyword within a longer query', () => {
expect(CYPHER_WRITE_RE.test('MATCH (n) DELETE n')).toBe(true);
expect(CYPHER_WRITE_RE.test('MATCH (n:Node) SET n.name = "x"')).toBe(true);
});
it('does not match partial word (e.g., "CREATED" should not match)', () => {
// \b ensures word boundary. "CREATED" starts with "CREATE" but has extra D
// Actually \b(CREATE) matches "CREATE" in "CREATED" since CREATE is followed by D
// which is a word char -> no boundary at E-D. Let's verify:
expect(CYPHER_WRITE_RE.test('CREATED_AT')).toBe(false);
});
});
// ─── isWriteQuery wrapper ─────────────────────────────────────────────
describe('isWriteQuery', () => {
it('returns true for write queries', () => {
expect(isWriteQuery('CREATE (n:Node)')).toBe(true);
expect(isWriteQuery('match (n) delete n')).toBe(true);
});
it('returns false for read queries', () => {
expect(isWriteQuery('MATCH (n) RETURN n')).toBe(false);
});
it('handles empty string', () => {
expect(isWriteQuery('')).toBe(false);
});
// Hardening: regex lastIndex not stuck (non-global regex, but verify)
it('works correctly on consecutive calls', () => {
expect(isWriteQuery('CREATE (n)')).toBe(true);
expect(isWriteQuery('MATCH (n) RETURN n')).toBe(false);
expect(isWriteQuery('DROP TABLE foo')).toBe(true);
expect(isWriteQuery('MATCH (n) RETURN n')).toBe(false);
});
});
// ─── Relation type allowlist ──────────────────────────────────────────
describe('VALID_RELATION_TYPES', () => {
it('contains exactly the expected 8 types', () => {
expect(VALID_RELATION_TYPES.size).toBe(8);
expect(VALID_RELATION_TYPES.has('CALLS')).toBe(true);
expect(VALID_RELATION_TYPES.has('IMPORTS')).toBe(true);
expect(VALID_RELATION_TYPES.has('EXTENDS')).toBe(true);
expect(VALID_RELATION_TYPES.has('IMPLEMENTS')).toBe(true);
expect(VALID_RELATION_TYPES.has('HAS_METHOD')).toBe(true);
expect(VALID_RELATION_TYPES.has('HAS_PROPERTY')).toBe(true);
expect(VALID_RELATION_TYPES.has('OVERRIDES')).toBe(true);
expect(VALID_RELATION_TYPES.has('ACCESSES')).toBe(true);
});
it('rejects invalid relation types', () => {
expect(VALID_RELATION_TYPES.has('CONTAINS')).toBe(false);
expect(VALID_RELATION_TYPES.has('USES')).toBe(false);
expect(VALID_RELATION_TYPES.has('calls')).toBe(false); // case-sensitive
expect(VALID_RELATION_TYPES.has('DROP_TABLE')).toBe(false);
});
});
// ─── Valid node labels ───────────────────────────────────────────────
describe('VALID_NODE_LABELS', () => {
it('contains core node types', () => {
for (const label of ['File', 'Folder', 'Function', 'Class', 'Interface', 'Method', 'CodeElement']) {
expect(VALID_NODE_LABELS.has(label)).toBe(true);
}
});
it('contains meta node types', () => {
for (const label of ['Community', 'Process']) {
expect(VALID_NODE_LABELS.has(label)).toBe(true);
}
});
it('contains multi-language node types', () => {
for (const label of ['Struct', 'Enum', 'Macro', 'Trait', 'Impl', 'Namespace']) {
expect(VALID_NODE_LABELS.has(label)).toBe(true);
}
});
it('rejects invalid labels', () => {
expect(VALID_NODE_LABELS.has('InvalidType')).toBe(false);
expect(VALID_NODE_LABELS.has('function')).toBe(false); // case-sensitive
});
});
// ─── Path traversal detection ────────────────────────────────────────
describe('path traversal (isTestFilePath as proxy for path handling)', () => {
it('isTestFilePath matches .test. files', () => {
expect(isTestFilePath('src/foo.test.ts')).toBe(true);
expect(isTestFilePath('src/foo.spec.ts')).toBe(true);
});
it('isTestFilePath matches __tests__ directory', () => {
expect(isTestFilePath('src/__tests__/foo.ts')).toBe(true);
});
it('isTestFilePath matches /test/ directory', () => {
expect(isTestFilePath('src/test/foo.ts')).toBe(true);
});
it('isTestFilePath handles Windows backslash paths', () => {
expect(isTestFilePath('src\\test\\foo.ts')).toBe(true);
expect(isTestFilePath('src\\__tests__\\bar.ts')).toBe(true);
});
it('isTestFilePath is case-insensitive', () => {
expect(isTestFilePath('SRC/TEST/Foo.ts')).toBe(true);
expect(isTestFilePath('SRC/Foo.Test.ts')).toBe(true);
});
it('isTestFilePath matches Go test files', () => {
expect(isTestFilePath('pkg/handler_test.go')).toBe(true);
});
it('isTestFilePath matches Python test files', () => {
expect(isTestFilePath('tests/test_handler.py')).toBe(true);
expect(isTestFilePath('pkg/handler_test.py')).toBe(true);
});
it('isTestFilePath returns false for non-test files', () => {
expect(isTestFilePath('src/main.ts')).toBe(false);
expect(isTestFilePath('src/utils/helper.ts')).toBe(false);
});
});
// ─── Static analysis: parameterized query patterns ────────────────────
describe('parameterized query patterns (static analysis)', () => {
it('CYPHER_WRITE_RE is not a global regex (no lastIndex issue)', () => {
// A global regex would have sticky lastIndex state
expect(CYPHER_WRITE_RE.global).toBe(false);
});
});