mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-25 14:43:05 +09:00
* fix: critical security & performance fixes across 6 packages Addresses 11 vulnerabilities from security audit + 5 additional issues found during devil's advocate review, plus test suite fixes across memory, security, and swarm packages. ## Security Fixes (Critical) - CRIT-01: SQL injection in embeddings search — replaced string interpolation with parameterized queries (db.prepare/bind) - CRIT-02: Command injection in 4 files — replaced execSync template literals with execFileSync + input validation regex: - ruvector/import.ts (docker container name) - init.ts (embedding model name, 2 locations) - agent-browser-adapter.ts (CLI args) - CRIT-03: Browser eval hardening — 12 dangerous patterns blocked, configurable 20KB length limit via CLAUDE_FLOW_MAX_EVAL_SCRIPT_LENGTH ## Security Fixes (High) - HIGH-01: ESLint rules restricting child_process imports (both import and require) with overrides for safe-executor/daemon/mcp-server - HIGH-02: Hive-mind truthiness fix (=== true vs !== false) - HIGH-03: Prototype pollution prevention — safeJsonParse with JSON reviver stripping __proto__/constructor/prototype in 3 memory backends - HIGH-04: Plugin sandbox warning on unsandboxed plugin load - HIGH-05: HNSW hash collision fix — dual-hash (djb2+sdbm) producing 53-bit values with bidirectional map and linear probing ## Security Fixes (DA Review) - DA-CRIT-1: Local json-security.ts to avoid cross-package imports - DA-CRIT-2: PostgreSQL schema name validation (validateSchemaName) added to all 6 ruvector commands via pg-utils.ts - DA-CRIT-3: PID injection prevention in mcp-server — /proc read + execFileSync replacing execSync with PID interpolation - DA-HIGH-3: Timestamp validation (validateTimestamp) in ruvector import - DA-HIGH-4: 4 additional browser eval bypass patterns (globalThis, .constructor, Reflect, eval()) - DA-HIGH-5: ESLint no-restricted-modules for require() coverage ## Performance Fixes - PERF-01: BoundedSet<T> for gossip seenMessages — Map-based LRU eviction capped at 100K entries, prevents unbounded memory growth - PERF-02: Bulk operations use Promise.allSettled with batch size 50, logging partial failures instead of aborting - PERF-03: CLI lazy loading — reduced sync imports from 37 to 10 core commands, async getCommandsByCategory() for help display ## Test Suite Fixes - Fixed 11 broken import paths in security tests (../../security/ → ../src/ and ../../helpers/ → ../helpers/) - Added vitest.config.ts for security package (was inheriting root config with missing setup.ts reference) - Added allowedDirectories to SecurityConfig test fixture - Fixed sanitizePath test expectation (leading slash removal) - Fixed hardcoded /workspaces/claude-flow path in memory tests - Fixed semanticRouter controller test (auto-enables with agentdb) - Fixed database-provider count test (namespace-scoped assertion) - Fixed swarm latency tests (toBeGreaterThanOrEqual for sub-ms mocks) - Added TypeScript as dev dependency for build verification ## Verification - 22 automated security verification tests in security-verification.test.ts covering all 10 user-facing scenarios - All 5 packages type-check clean (0 errors) - memory: 9/9 suites, 353/353 tests pass - swarm: 4/4 suites, 172/172 tests pass - security: 13/13 suites, 444/444 tests pass - CLI help displays all 35 commands correctly with lazy loading ## New Files - v3/@claude-flow/cli/src/commands/ruvector/pg-utils.ts - v3/@claude-flow/cli/.eslintrc.json - v3/@claude-flow/cli/__tests__/security-verification.test.ts - v3/@claude-flow/memory/src/json-security.ts - v3/@claude-flow/security/vitest.config.ts Co-Authored-By: claude-flow <ruv@ruv.net> * fix: address Sherlock review findings for PR #1558 Finding 2 (MUST FIX): Add formatEmbedding array-element validation - Validate each embedding value is typeof number && Number.isFinite() - Prevents SQL injection via crafted JSON arrays with string payloads - Throws descriptive error with index for debugging Finding 1: Reclassify CRIT-03 eval blocklist as defense-in-depth - Add comment clarifying pattern blocklist is best-effort, not a sandbox - Primary defense is the browser sandbox itself - Update test description to reflect defense-in-depth classification Finding 3: Add behavioral tests alongside source-guards - Add formatEmbedding behavioral test with hostile inputs (NaN, Infinity, strings) - Add CRIT-02 behavioral test verifying execFileSync array argument pattern - Categorize existing tests as source-guard vs behavioral in comments Finding 4: Flag HIGH-02 as behavior change - Add comment explaining === true vs !== false semantic difference - Documents that undefined/null no longer treated as "skip permissions" Finding 6: Export BoundedSet, fix test semantics - Export BoundedSet from gossip.ts for reuse - Fix test to use FIFO semantics matching production (not LRU) - Add FIFO-specific test: re-adding doesn't refresh position Finding 7: Fix BoundedSet comment math - Remove speculative throughput time estimate - Use factual memory calculation: 100K × ~40B IDs ≈ 4MB Finding 5: No change (false positive — Math.abs in manhattanDistance is correct) Co-Authored-By: claude-flow <ruv@ruv.net> --------- Co-authored-by: claude-flow <ruv@ruv.net>
377 lines
11 KiB
TypeScript
377 lines
11 KiB
TypeScript
/**
|
|
* Database Provider Tests - Cross-Platform Compatibility
|
|
*
|
|
* Tests for platform-aware database selection and fallback mechanisms
|
|
*/
|
|
|
|
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
|
import { createDatabase, getPlatformInfo, getAvailableProviders } from './database-provider.js';
|
|
import { generateMemoryId, createDefaultEntry } from './types.js';
|
|
import { unlinkSync, existsSync } from 'node:fs';
|
|
|
|
describe('DatabaseProvider', () => {
|
|
const testDbPath = './test-database-provider.db';
|
|
|
|
beforeEach(() => {
|
|
// Ensure clean state before each test
|
|
if (existsSync(testDbPath)) {
|
|
try {
|
|
unlinkSync(testDbPath);
|
|
} catch {
|
|
// Ignore cleanup errors
|
|
}
|
|
}
|
|
});
|
|
|
|
afterEach(() => {
|
|
// Cleanup test database
|
|
if (existsSync(testDbPath)) {
|
|
try {
|
|
unlinkSync(testDbPath);
|
|
} catch {
|
|
// Ignore cleanup errors
|
|
}
|
|
}
|
|
});
|
|
|
|
describe('Platform Detection', () => {
|
|
it('should detect platform information', () => {
|
|
const info = getPlatformInfo();
|
|
|
|
expect(info).toHaveProperty('os');
|
|
expect(info).toHaveProperty('isWindows');
|
|
expect(info).toHaveProperty('isMacOS');
|
|
expect(info).toHaveProperty('isLinux');
|
|
expect(info).toHaveProperty('recommendedProvider');
|
|
|
|
// Should recommend sql.js on Windows, better-sqlite3 on Unix
|
|
if (info.isWindows) {
|
|
expect(info.recommendedProvider).toBe('sql.js');
|
|
} else {
|
|
expect(info.recommendedProvider).toBe('better-sqlite3');
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('Provider Availability', () => {
|
|
it('should check available providers', async () => {
|
|
const available = await getAvailableProviders();
|
|
|
|
expect(available).toHaveProperty('betterSqlite3');
|
|
expect(available).toHaveProperty('sqlJs');
|
|
expect(available).toHaveProperty('json');
|
|
|
|
// JSON backend should always be available
|
|
expect(available.json).toBe(true);
|
|
});
|
|
});
|
|
|
|
describe('Automatic Provider Selection', () => {
|
|
it('should create database with auto provider selection', async () => {
|
|
const db = await createDatabase(':memory:');
|
|
|
|
expect(db).toBeDefined();
|
|
await expect(db.count()).resolves.toBe(0);
|
|
|
|
await db.shutdown();
|
|
});
|
|
|
|
it('should create persistent database with auto provider', async () => {
|
|
const db = await createDatabase(testDbPath);
|
|
|
|
expect(db).toBeDefined();
|
|
|
|
// Store test entry
|
|
const entry = createDefaultEntry({
|
|
key: 'test-key',
|
|
content: 'test content',
|
|
namespace: 'test',
|
|
});
|
|
|
|
const countBefore = await db.count('test');
|
|
await db.store(entry);
|
|
await expect(db.count('test')).resolves.toBe(countBefore + 1);
|
|
|
|
await db.shutdown();
|
|
});
|
|
});
|
|
|
|
describe('Explicit Provider Selection', () => {
|
|
it('should create database with sql.js provider', async () => {
|
|
const available = await getAvailableProviders();
|
|
|
|
if (!available.sqlJs) {
|
|
console.log('sql.js not available, skipping test');
|
|
return;
|
|
}
|
|
|
|
const db = await createDatabase(':memory:', {
|
|
provider: 'sql.js',
|
|
verbose: false,
|
|
});
|
|
|
|
expect(db).toBeDefined();
|
|
|
|
// Test basic operations
|
|
const entry = createDefaultEntry({
|
|
key: 'sqljs-test',
|
|
content: 'testing sql.js backend',
|
|
namespace: 'test',
|
|
});
|
|
|
|
await db.store(entry);
|
|
await expect(db.count()).resolves.toBe(1);
|
|
|
|
const retrieved = await db.get(entry.id);
|
|
expect(retrieved).toBeDefined();
|
|
expect(retrieved?.key).toBe('sqljs-test');
|
|
|
|
await db.shutdown();
|
|
});
|
|
|
|
it('should create database with better-sqlite3 provider', async () => {
|
|
const available = await getAvailableProviders();
|
|
|
|
if (!available.betterSqlite3) {
|
|
console.log('better-sqlite3 not available, skipping test');
|
|
return;
|
|
}
|
|
|
|
const db = await createDatabase(':memory:', {
|
|
provider: 'better-sqlite3',
|
|
verbose: false,
|
|
});
|
|
|
|
expect(db).toBeDefined();
|
|
|
|
// Test basic operations
|
|
const entry = createDefaultEntry({
|
|
key: 'sqlite-test',
|
|
content: 'testing better-sqlite3 backend',
|
|
namespace: 'test',
|
|
});
|
|
|
|
await db.store(entry);
|
|
await expect(db.count()).resolves.toBe(1);
|
|
|
|
const retrieved = await db.get(entry.id);
|
|
expect(retrieved).toBeDefined();
|
|
expect(retrieved?.key).toBe('sqlite-test');
|
|
|
|
await db.shutdown();
|
|
});
|
|
|
|
it('should create database with JSON provider', async () => {
|
|
const db = await createDatabase(testDbPath, {
|
|
provider: 'json',
|
|
verbose: false,
|
|
});
|
|
|
|
expect(db).toBeDefined();
|
|
|
|
// Test basic operations
|
|
const entry = createDefaultEntry({
|
|
key: 'json-test',
|
|
content: 'testing JSON backend',
|
|
namespace: 'test',
|
|
});
|
|
|
|
await db.store(entry);
|
|
await expect(db.count()).resolves.toBe(1);
|
|
|
|
const retrieved = await db.get(entry.id);
|
|
expect(retrieved).toBeDefined();
|
|
expect(retrieved?.key).toBe('json-test');
|
|
|
|
await db.shutdown();
|
|
});
|
|
});
|
|
|
|
describe('Cross-Platform Functionality', () => {
|
|
it('should handle CRUD operations consistently across providers', async () => {
|
|
const available = await getAvailableProviders();
|
|
const providers: Array<'better-sqlite3' | 'sql.js' | 'json'> = [];
|
|
|
|
if (available.betterSqlite3) providers.push('better-sqlite3');
|
|
if (available.sqlJs) providers.push('sql.js');
|
|
providers.push('json'); // Always available
|
|
|
|
for (const provider of providers) {
|
|
const db = await createDatabase(':memory:', { provider });
|
|
|
|
// Create
|
|
const entry = createDefaultEntry({
|
|
key: `test-${provider}`,
|
|
content: `testing ${provider}`,
|
|
namespace: 'cross-platform',
|
|
tags: ['test', provider],
|
|
});
|
|
|
|
await db.store(entry);
|
|
|
|
// Read
|
|
const retrieved = await db.get(entry.id);
|
|
expect(retrieved).toBeDefined();
|
|
expect(retrieved?.key).toBe(`test-${provider}`);
|
|
expect(retrieved?.tags).toContain(provider);
|
|
|
|
// Update
|
|
const updated = await db.update(entry.id, {
|
|
content: `updated ${provider}`,
|
|
});
|
|
expect(updated).toBeDefined();
|
|
expect(updated?.content).toBe(`updated ${provider}`);
|
|
|
|
// Query
|
|
const results = await db.query({
|
|
type: 'hybrid',
|
|
namespace: 'cross-platform',
|
|
limit: 10,
|
|
});
|
|
expect(results.length).toBe(1);
|
|
expect(results[0].key).toBe(`test-${provider}`);
|
|
|
|
// Delete
|
|
const deleted = await db.delete(entry.id);
|
|
expect(deleted).toBe(true);
|
|
|
|
await expect(db.count()).resolves.toBe(0);
|
|
|
|
await db.shutdown();
|
|
}
|
|
});
|
|
|
|
it('should handle namespace operations across providers', async () => {
|
|
const db = await createDatabase(':memory:');
|
|
|
|
// Create entries in different namespaces
|
|
const entries = [
|
|
createDefaultEntry({ key: 'entry1', content: 'content1', namespace: 'ns1' }),
|
|
createDefaultEntry({ key: 'entry2', content: 'content2', namespace: 'ns1' }),
|
|
createDefaultEntry({ key: 'entry3', content: 'content3', namespace: 'ns2' }),
|
|
];
|
|
|
|
for (const entry of entries) {
|
|
await db.store(entry);
|
|
}
|
|
|
|
// List namespaces
|
|
const namespaces = await db.listNamespaces();
|
|
expect(namespaces).toContain('ns1');
|
|
expect(namespaces).toContain('ns2');
|
|
|
|
// Count by namespace
|
|
await expect(db.count('ns1')).resolves.toBe(2);
|
|
await expect(db.count('ns2')).resolves.toBe(1);
|
|
|
|
// Clear namespace
|
|
const cleared = await db.clearNamespace('ns1');
|
|
expect(cleared).toBe(2);
|
|
await expect(db.count('ns1')).resolves.toBe(0);
|
|
await expect(db.count('ns2')).resolves.toBe(1);
|
|
|
|
await db.shutdown();
|
|
});
|
|
|
|
it('should handle bulk operations across providers', async () => {
|
|
const db = await createDatabase(':memory:');
|
|
|
|
// Bulk insert
|
|
const entries = Array.from({ length: 10 }, (_, i) =>
|
|
createDefaultEntry({
|
|
key: `bulk-${i}`,
|
|
content: `content ${i}`,
|
|
namespace: 'bulk-test',
|
|
})
|
|
);
|
|
|
|
await db.bulkInsert(entries);
|
|
await expect(db.count('bulk-test')).resolves.toBe(10);
|
|
|
|
// Bulk delete
|
|
const idsToDelete = entries.slice(0, 5).map((e) => e.id);
|
|
const deletedCount = await db.bulkDelete(idsToDelete);
|
|
expect(deletedCount).toBe(5);
|
|
await expect(db.count('bulk-test')).resolves.toBe(5);
|
|
|
|
await db.shutdown();
|
|
});
|
|
});
|
|
|
|
describe('Health Check', () => {
|
|
it('should perform health check', async () => {
|
|
const db = await createDatabase(':memory:');
|
|
|
|
const health = await db.healthCheck();
|
|
|
|
expect(health).toHaveProperty('status');
|
|
expect(health).toHaveProperty('components');
|
|
expect(health).toHaveProperty('timestamp');
|
|
expect(health).toHaveProperty('issues');
|
|
expect(health).toHaveProperty('recommendations');
|
|
|
|
expect(health.components).toHaveProperty('storage');
|
|
expect(health.components).toHaveProperty('index');
|
|
expect(health.components).toHaveProperty('cache');
|
|
|
|
await db.shutdown();
|
|
});
|
|
});
|
|
|
|
describe('Statistics', () => {
|
|
it('should provide backend statistics', async () => {
|
|
const db = await createDatabase(':memory:');
|
|
|
|
// Add some test data
|
|
const entries = [
|
|
createDefaultEntry({ key: 'stat1', content: 'content1', namespace: 'stats', type: 'semantic' }),
|
|
createDefaultEntry({ key: 'stat2', content: 'content2', namespace: 'stats', type: 'episodic' }),
|
|
createDefaultEntry({ key: 'stat3', content: 'content3', namespace: 'stats', type: 'semantic' }),
|
|
];
|
|
|
|
for (const entry of entries) {
|
|
await db.store(entry);
|
|
}
|
|
|
|
const stats = await db.getStats();
|
|
|
|
expect(stats).toHaveProperty('totalEntries');
|
|
expect(stats).toHaveProperty('entriesByNamespace');
|
|
expect(stats).toHaveProperty('entriesByType');
|
|
expect(stats).toHaveProperty('memoryUsage');
|
|
expect(stats).toHaveProperty('avgQueryTime');
|
|
|
|
expect(stats.totalEntries).toBe(3);
|
|
|
|
await db.shutdown();
|
|
});
|
|
});
|
|
|
|
describe('Error Handling', () => {
|
|
it('should handle missing entries gracefully', async () => {
|
|
const db = await createDatabase(':memory:');
|
|
|
|
const entry = await db.get('non-existent-id');
|
|
expect(entry).toBeNull();
|
|
|
|
const byKey = await db.getByKey('non-existent-ns', 'non-existent-key');
|
|
expect(byKey).toBeNull();
|
|
|
|
await db.shutdown();
|
|
});
|
|
|
|
it('should handle empty queries', async () => {
|
|
const db = await createDatabase(':memory:');
|
|
|
|
const results = await db.query({
|
|
type: 'hybrid',
|
|
limit: 10,
|
|
});
|
|
|
|
expect(results).toEqual([]);
|
|
|
|
await db.shutdown();
|
|
});
|
|
});
|
|
});
|