#!/usr/bin/env node /** * Runs the security tests against this working tree. * * The tests are not in this repository. They live in a private one, which this repository includes * as the git submodule `security-tests`: requests and scripts written to get past a check are kept * out of public view. Maintainers check it out with `git submodule update --init security-tests`. * * yarn test:security the security specs of every project * node scripts/security-tests.mjs --specs [sdk|auth|plugin-codecall ...] [-- ] * * --summary print totals only (see below) * --if-present exit with 0 instead of 2 where the submodule is not checked out * --fingerprint print a hash of the specs (an Nx input, so a cached test run is not replayed * after the specs changed) * * --summary is for logs that are public, such as the CI of this repository. Nothing a test prints * reaches the output: every project runs as a child process whose output is discarded, and reports * through a result file. What is printed is a count per project. No name, no request, no value, no path. */ import { spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'; import { createRequire } from 'node:module'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const submodule = path.join(root, 'security-tests'); const specs = path.join(submodule, 'specs'); const scratch = path.join(root, 'tmp', 'security-tests'); const rootRequire = createRequire(path.join(root, 'package.json')); /** Projects whose security specs run under Jest, with the project's own Jest configuration. */ const PROJECTS = { sdk: { directory: 'libs/sdk', config: 'jest.config.ts', nodeArguments: ['--no-sparkplug'] }, auth: { directory: 'libs/auth', config: 'jest.config.cts' }, utils: { directory: 'libs/utils', config: 'jest.config.ts' }, 'storage-sqlite': { directory: 'libs/storage-sqlite', config: 'jest.config.ts' }, cli: { directory: 'libs/cli', config: 'jest.config.ts' }, 'plugin-codecall': { directory: 'plugins/plugin-codecall', config: 'jest.config.ts' }, 'plugin-cache': { directory: 'plugins/plugin-cache', config: 'jest.config.ts' }, 'plugin-remember': { directory: 'plugins/plugin-remember', config: 'jest.config.ts' }, 'plugin-result-handles': { directory: 'plugins/plugin-result-handles', config: 'jest.config.ts' }, 'plugin-skilled-openapi': { directory: 'plugins/plugin-skilled-openapi', config: 'jest.config.ts' }, 'plugin-approval': { directory: 'plugins/plugin-approval', config: 'jest.config.ts' }, 'plugin-feature-flags': { directory: 'plugins/plugin-feature-flags', config: 'jest.config.ts' }, 'plugin-dashboard': { directory: 'plugins/plugin-dashboard', config: 'jest.config.ts' }, adapters: { directory: 'libs/adapters', config: 'jest.config.ts' }, uipack: { directory: 'libs/uipack', config: 'jest.config.ts' }, }; const argv = process.argv.slice(2); const separator = argv.indexOf('--'); const own = separator < 0 ? argv : argv.slice(0, separator); const forwarded = separator < 0 ? [] : argv.slice(separator + 1); const has = (name) => own.includes(name); const summary = has('--summary'); const optional = has('--if-present'); function say(line) { process.stdout.write(`${line}\n`); } /** Runs a project's specs as a child process. In summary mode nothing it writes reaches this process's output. */ function run(args, { cwd = root, env = {} } = {}) { const result = spawnSync(process.execPath, args, { cwd, env: { ...process.env, ...env }, stdio: summary ? ['ignore', 'ignore', 'ignore'] : 'inherit', }); return result.status ?? 1; } function readJson(file) { try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return undefined; } } function resultFile(name) { mkdirSync(scratch, { recursive: true }); const file = path.join(scratch, name); rmSync(file, { force: true }); return file; } const isSpec = (name) => /\.spec\.tsx?$/.test(name); function holdsSpecs(directory) { if (!existsSync(directory)) return false; return readdirSync(directory, { withFileTypes: true }).some((entry) => entry.isDirectory() ? holdsSpecs(path.join(directory, entry.name)) : isSpec(entry.name), ); } const HOW_TO_REPRODUCE = 'Details are not written to this log. Run it locally with the private submodule checked out:\n' + ' git submodule update --init security-tests && yarn test:security'; function runSpecs(projects, named) { let exitCode = 0; let ran = 0; for (const project of projects) { const settings = PROJECTS[project]; const directory = path.join(specs, project); const label = `security specs (${project})`; if (!settings || !holdsSpecs(directory)) { // Asked for by name, a project without specs is a mistake; in a run of everything it is skipped. if (named) { say(`${label}: there are no specs for this project`); exitCode = 1; } continue; } ran += 1; const projectDirectory = path.join(root, settings.directory); // Named by this process, so two runs at once do not read each other's result const report = resultFile(`specs-${project}-${process.pid}.json`); const args = [ ...(settings.nodeArguments ?? []), rootRequire.resolve('jest/bin/jest'), '--config', path.join(projectDirectory, settings.config), // Only the private specs: the project's public ones run in `nx test `. '--roots', directory, // The counts are read in both modes: an exit code of 0 also means "nothing failed because // nothing ran" (every test skipped, or a name filter that matches none). '--json', '--outputFile', report, '--coverage=false', ]; if (summary) args.push('--silent'); const code = run([...args, ...forwarded], { cwd: projectDirectory }); if (code !== 0) exitCode = 1; const json = readJson(report); rmSync(report, { force: true }); if (!json || typeof json.numTotalTestSuites !== 'number') { say(`${label}: the run did not produce a result (exit code ${code})`); exitCode = 1; } else if (json.numTotalTestSuites === 0) { say(`${label}: no spec was found`); exitCode = 1; } else { // Jest counts a suite that could not be loaded among the failed ones. const failedSuites = json.numFailedTestSuites; if (summary) { say( `${label}: ${json.numPassedTestSuites} of ${json.numTotalTestSuites} suites passed` + (failedSuites > 0 ? `, ${failedSuites} failed` : '') + `; ${json.numTotalTests} tests: ${json.numPassedTests} passed, ${json.numFailedTests} failed, ` + `${json.numPendingTests + (json.numTodoTests ?? 0)} skipped`, ); } if (failedSuites > 0 || json.numFailedTests > 0) exitCode = 1; // A run in which no test passed has checked nothing, whatever its exit code. if (!(json.numPassedTests > 0)) { say(`${label}: no test passed`); exitCode = 1; } } } if (ran === 0 && !named) { say('security specs: the submodule holds no spec'); exitCode = 1; } return exitCode; } /** A hash of every spec in the submodule, or `absent`. */ function fingerprint() { if (!existsSync(specs)) return 'absent'; const hash = createHash('sha256'); const walk = (directory) => { for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) { const file = path.join(directory, entry.name); if (entry.isDirectory()) walk(file); else if (entry.isFile()) hash.update(path.relative(specs, file)).update('\0').update(readFileSync(file)).update('\0'); } }; walk(specs); return hash.digest('hex'); } if (has('--fingerprint')) { say(fingerprint()); process.exit(0); } if (!existsSync(specs)) { console.error( 'The security tests are not checked out.\n\n' + 'They live in a private repository (agentfront/frontmcp-security-tests), included here as the\n' + 'git submodule `security-tests`. With access to it:\n\n' + ' git submodule update --init security-tests\n', ); process.exit(optional ? 0 : 2); } const named = own.filter((arg) => !arg.startsWith('--')); const exitCode = runSpecs(named.length > 0 ? named : Object.keys(PROJECTS), named.length > 0); if (summary && exitCode !== 0) say(HOW_TO_REPRODUCE); process.exit(exitCode);