diff --git a/npm/secfoo-sensor/index.js b/npm/secfoo-sensor/index.js index 3e25116..fdc7860 100644 --- a/npm/secfoo-sensor/index.js +++ b/npm/secfoo-sensor/index.js @@ -9,9 +9,14 @@ const { sanitizeRouteTemplate, } = require("./lib/context"); const { expressMiddleware, fastifyPlugin } = require("./lib/middleware"); +const { SensorProbe, startFromEnv } = require("./lib/probe"); + +// Inert unless SECFOO_SENSOR=1; safe to load via `node --require @rakfortltd/secfoo-sensor`. +startFromEnv(); module.exports = { NodeHitCollector, + SensorProbe, detectAuthState, expressMiddleware, fastifyPlugin, @@ -19,4 +24,5 @@ module.exports = { runWithJob, runWithRequest, sanitizeRouteTemplate, + startFromEnv, }; diff --git a/npm/secfoo-sensor/lib/coverage.js b/npm/secfoo-sensor/lib/coverage.js new file mode 100644 index 0000000..71a0de6 --- /dev/null +++ b/npm/secfoo-sensor/lib/coverage.js @@ -0,0 +1,86 @@ +"use strict"; + +const inspector = require("node:inspector"); +const path = require("node:path"); +const { fileURLToPath } = require("node:url"); + +/** + * Optional low-overhead V8 coverage tracker using `inspector` + * (`callCount: false, detailed: false`) to populate `app_functions` / + * `functions_executed` in #53 `session` events (#56). + */ +class V8CoverageTracker { + constructor(appRoot = process.cwd(), sensorDir = path.resolve(__dirname)) { + this.appRoot = path.resolve(appRoot); + this.sensorDir = path.resolve(sensorDir); + this._session = null; + this._enabled = false; + } + + start() { + if (this._enabled) return; + try { + const s = new inspector.Session(); + s.connect(); + s.post("Profiler.enable"); + s.post("Profiler.startPreciseCoverage", { callCount: false, detailed: false }); + this._session = s; + this._enabled = true; + } catch { + this.stop(); + } + } + + _isAppUrl(rawUrl) { + if (!rawUrl || !rawUrl.startsWith("file://")) return false; + let filePath; + try { + filePath = path.resolve(fileURLToPath(rawUrl)); + } catch { + return false; + } + if (filePath.includes(`${path.sep}node_modules${path.sep}`)) return false; + if (filePath.startsWith(this.sensorDir)) return false; + return filePath.startsWith(this.appRoot); + } + + collect() { + if (!this._enabled || !this._session) return { app_functions: null, functions_executed: null }; + let totalFuncs = 0; + let executedFuncs = 0; + try { + this._session.post("Profiler.takePreciseCoverage", (err, res) => { + if (err || !res || !Array.isArray(res.result)) return; + for (const script of res.result) { + if (!this._isAppUrl(script.url) || !Array.isArray(script.functions)) continue; + for (const fn of script.functions) { + totalFuncs += 1; + if (Array.isArray(fn.ranges) && fn.ranges.some((r) => r.count > 0)) { + executedFuncs += 1; + } + } + } + }); + } catch { + return { app_functions: null, functions_executed: null }; + } + if (totalFuncs === 0) return { app_functions: null, functions_executed: null }; + return { app_functions: totalFuncs, functions_executed: executedFuncs }; + } + + stop() { + if (this._session) { + try { + this._session.post("Profiler.stopPreciseCoverage"); + this._session.post("Profiler.disable"); + this._session.disconnect(); + } catch { + // Ignore teardown failures + } + } + this._session = null; + this._enabled = false; + } +} + +module.exports = { V8CoverageTracker }; diff --git a/npm/secfoo-sensor/lib/esm_loader.mjs b/npm/secfoo-sensor/lib/esm_loader.mjs new file mode 100644 index 0000000..1f73ad3 --- /dev/null +++ b/npm/secfoo-sensor/lib/esm_loader.mjs @@ -0,0 +1,140 @@ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const SELF_DIR = path.dirname(fileURLToPath(import.meta.url)); +const PROBE_URL = pathToFileURL(path.join(SELF_DIR, "probe.js")).href; + +let watchedPackages = null; + +function loadWatchedPackages() { + if (process.env.SECFOO_SENSOR !== "1") return new Map(); + if (watchedPackages !== null) return watchedPackages; + const map = new Map(); + const wlPath = process.env.SECFOO_WATCHLIST; + if (!wlPath) { + watchedPackages = map; + return map; + } + try { + const doc = JSON.parse(fs.readFileSync(wlPath, "utf-8")); + for (const entry of doc.entries || []) { + if (entry.ecosystem && entry.ecosystem !== "npm") continue; + for (const sym of entry.symbols || []) { + const idx = String(sym).indexOf("#"); + if (idx > 0) { + const pkg = sym.slice(0, idx); + const mem = sym.slice(idx + 1); + const set = map.get(pkg) || new Set(); + set.add(mem); + map.set(pkg, set); + } + } + } + } catch { + // Watchlist unreadable; stay passive + } + watchedPackages = map; + return map; +} + +function findMatchingPkg(urlStr) { + if (!urlStr.startsWith("file://")) return null; + const map = loadWatchedPackages(); + if (map.size === 0) return null; + let fsPath; + try { + fsPath = fileURLToPath(urlStr); + } catch { + return null; + } + let dir = path.dirname(fsPath); + for (let i = 0; i < 6; i += 1) { + const pj = path.join(dir, "package.json"); + if (fs.existsSync(pj)) { + try { + const meta = JSON.parse(fs.readFileSync(pj, "utf-8")); + if (meta && meta.name && map.has(meta.name)) return meta.name; + } catch { + break; + } + break; + } + const parent = path.dirname(dir); + if (parent === dir) break; + dir = parent; + } + const stem = path.basename(fsPath, path.extname(fsPath)); + if (map.has(stem)) return stem; + return null; +} + +function extractNamedExports(src) { + const names = new Set(); + let hasDefault = false; + // Strip single-line and block comments cleanly enough for ESM export declarations. + const clean = src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, ""); + for (const m of clean.matchAll(/^\s*export\s+(?:async\s+)?function\s*\*?\s+([A-Za-z_$][\w$]*)/gm)) { + names.add(m[1]); + } + for (const m of clean.matchAll(/^\s*export\s+class\s+([A-Za-z_$][\w$]*)/gm)) { + names.add(m[1]); + } + for (const m of clean.matchAll(/^\s*export\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)/gm)) { + names.add(m[1]); + } + for (const m of clean.matchAll(/^\s*export\s*\{([^}]+)\}/gm)) { + for (const part of m[1].split(",")) { + const asMatch = part.trim().split(/\s+as\s+/); + const exported = (asMatch[1] || asMatch[0] || "").trim(); + if (exported === "default") hasDefault = true; + else if (exported) names.add(exported); + } + } + if (/^\s*export\s+default\b/m.test(clean)) hasDefault = true; + return { names: Array.from(names), hasDefault }; +} + +export async function load(url, context, nextLoad) { + if (process.env.SECFOO_SENSOR !== "1") return nextLoad(url, context); + const parsed = new URL(url); + if (parsed.searchParams.get("__secfoo_raw") === "1") { + parsed.searchParams.delete("__secfoo_raw"); + return nextLoad(parsed.href, context); + } + const pkgName = findMatchingPkg(url); + if (!pkgName || url === PROBE_URL || url.startsWith(pathToFileURL(SELF_DIR).href)) { + return nextLoad(url, context); + } + const result = await nextLoad(url, context); + if (result.format !== "module" || !result.source) return result; + const srcText = typeof result.source === "string" ? result.source : Buffer.from(result.source).toString("utf-8"); + const { names, hasDefault } = extractNamedExports(srcText); + if (names.length === 0 && !hasDefault) return result; + + const rawUrl = new URL(url); + rawUrl.searchParams.set("__secfoo_raw", "1"); + + const lines = [ + `import * as _raw from ${JSON.stringify(rawUrl.href)};`, + `import { createRequire } from "node:module";`, + `const _req = createRequire(import.meta.url);`, + `const { wrapNamespaceExport } = _req(${JSON.stringify(path.join(SELF_DIR, "probe.js"))});`, + ]; + for (const name of names) { + lines.push( + `export const ${name} = wrapNamespaceExport(${JSON.stringify(pkgName)}, ${JSON.stringify(name)}, _raw[${JSON.stringify(name)}], ${JSON.stringify(url)});`, + ); + } + if (hasDefault) { + lines.push( + `const _def = wrapNamespaceExport(${JSON.stringify(pkgName)}, "default", _raw.default, ${JSON.stringify(url)});`, + `export default _def;`, + ); + } + return { + format: "module", + shortCircuit: true, + source: lines.join("\n") + "\n", + }; +} diff --git a/npm/secfoo-sensor/lib/hooks.js b/npm/secfoo-sensor/lib/hooks.js new file mode 100644 index 0000000..9d69ff9 --- /dev/null +++ b/npm/secfoo-sensor/lib/hooks.js @@ -0,0 +1,150 @@ +"use strict"; + +const Module = require("node:module"); +const path = require("node:path"); +const { packageNameFromRequest } = require("./inventory"); + +const wrappedTargets = new WeakSet(); +const moduleCacheRecords = []; // { pkgName, resolvedFile, exportsObj, getContainer? } +let installed = false; +let originalLoad = null; + +/** + * Wrap `fn` with a transparent Proxy so `this`, arguments, return values, + * thrown errors, `new` construction (`instanceof`), and static properties stay + * completely intact (#56). + */ +function createFunctionWrapper(fn, target, onHit) { + if (typeof fn !== "function" || wrappedTargets.has(fn)) return fn; + const wrapped = new Proxy(fn, { + apply(inner, thisArg, args) { + try { + onHit(target); + } catch { + // Observe-only, fail-open + } + return Reflect.apply(inner, thisArg, args); + }, + construct(inner, args, newTarget) { + try { + onHit(target); + } catch { + // Observe-only, fail-open + } + return Reflect.construct(inner, args, newTarget); + }, + }); + wrappedTargets.add(fn); + wrappedTargets.add(wrapped); + return wrapped; +} + +function applyTargetsToExports(exportsObj, targets, onHit) { + if (!exportsObj || (typeof exportsObj !== "object" && typeof exportsObj !== "function")) { + return exportsObj; + } + for (const target of targets) { + if (target.granularity !== "symbol" || !Array.isArray(target.memberPath) || target.memberPath.length === 0) { + continue; + } + let owner = exportsObj; + const parts = target.memberPath; + for (let i = 0; i < parts.length - 1; i += 1) { + const next = owner ? owner[parts[i]] : undefined; + if (!next || (typeof next !== "object" && typeof next !== "function")) { + owner = null; + break; + } + owner = next; + } + if (!owner) continue; + const leaf = parts[parts.length - 1]; + let current; + try { + current = owner[leaf]; + } catch { + continue; + } + if (typeof current !== "function" || wrappedTargets.has(current)) continue; + const desc = Object.getOwnPropertyDescriptor(owner, leaf); + if (desc && !desc.configurable && !desc.writable) continue; + const wrapped = createFunctionWrapper(current, target, onHit); + try { + owner[leaf] = wrapped; + } catch { + // Ignore frozen / non-writable exports + } + } + return exportsObj; +} + +function resolveFileQuiet(request, parent) { + try { + return Module._resolveFilename(request, parent, false); + } catch { + return null; + } +} + +function installCjsHook({ watchlist, inventory, onHit }) { + if (installed) return; + installed = true; + originalLoad = Module._load; + + Module._load = function secfooWrappedLoad(request, parent, isMain) { + const loaded = originalLoad.apply(this, arguments); + try { + if (typeof request === "string" && !request.startsWith("node:") && !Module.builtinModules.includes(request)) { + const resolved = resolveFileQuiet(request, parent); + const inv = inventory.recordModule(resolved || request, request); + const pkgName = (inv && inv.package) || packageNameFromRequest(request); + const candidates = []; + if (pkgName) candidates.push(pkgName); + if (resolved) { + // Allow matching base filename when watched package name equals local sample file stem. + const stem = path.basename(resolved, path.extname(resolved)); + if (stem && !candidates.includes(stem)) candidates.push(stem); + } + for (const cand of candidates) { + const targets = watchlist.targetsForPackage(cand); + if (targets.length > 0) { + applyTargetsToExports(loaded, targets, onHit); + } + } + if (loaded && (typeof loaded === "object" || typeof loaded === "function") && candidates.length > 0) { + moduleCacheRecords.push({ candidates, exportsObj: loaded }); + } + } + } catch { + // Never interfere with app module loading + } + return loaded; + }; +} + +function applyWatchlistReload({ watchlist, onHit }) { + for (const rec of moduleCacheRecords) { + for (const cand of rec.candidates) { + const targets = watchlist.targetsForPackage(cand); + if (targets.length > 0) { + applyTargetsToExports(rec.exportsObj, targets, onHit); + } + } + } +} + +function uninstallCjsHook() { + if (installed && originalLoad) { + Module._load = originalLoad; + originalLoad = null; + installed = false; + } +} + +module.exports = { + applyTargetsToExports, + applyWatchlistReload, + createFunctionWrapper, + installCjsHook, + uninstallCjsHook, +}; diff --git a/npm/secfoo-sensor/lib/inventory.js b/npm/secfoo-sensor/lib/inventory.js new file mode 100644 index 0000000..0fe1f9d --- /dev/null +++ b/npm/secfoo-sensor/lib/inventory.js @@ -0,0 +1,120 @@ +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); + +/** Extract npm package name (`lodash` or `@scope/pkg`) from an import specifier. */ +function packageNameFromRequest(request) { + if (typeof request !== "string" || !request) return null; + if (request.startsWith("node:") || request.startsWith(".") || path.isAbsolute(request)) { + return null; + } + const parts = request.split("/"); + if (request.startsWith("@") && parts.length >= 2) { + return `${parts[0]}/${parts[1]}`; + } + return parts[0] || null; +} + +/** Walk up from a resolved JS file path to locate its nearest `package.json`. */ +function findPackageMetadata(filePath, cache = new Map()) { + if (!filePath || typeof filePath !== "string") return null; + let cleanPath = filePath.startsWith("file://") ? decodeURIComponent(new URL(filePath).pathname) : filePath; + if (process.platform === "win32" && /^\/[A-Za-z]:/.test(cleanPath)) cleanPath = cleanPath.slice(1); + let dir = path.dirname(path.resolve(cleanPath)); + const visited = []; + + for (let depth = 0; depth < 12; depth += 1) { + if (cache.has(dir)) { + const hit = cache.get(dir); + for (const d of visited) cache.set(d, hit); + return hit; + } + visited.push(dir); + const pkgPath = path.join(dir, "package.json"); + if (fs.existsSync(pkgPath)) { + try { + const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8")); + const meta = + pkg && typeof pkg.name === "string" && pkg.name.trim() + ? { + name: pkg.name.trim(), + version: typeof pkg.version === "string" && pkg.version.trim() ? pkg.version.trim() : "unknown", + rootDir: dir, + } + : null; + for (const d of visited) cache.set(d, meta); + return meta; + } catch { + for (const d of visited) cache.set(d, null); + return null; + } + } + const parent = path.dirname(dir); + if (parent === dir) break; + dir = parent; + } + + for (const d of visited) cache.set(d, null); + return null; +} + +class InventoryTracker { + constructor(sessionId, appRoot = null) { + this.sessionId = sessionId; + this.appRoot = appRoot ? path.resolve(appRoot) : null; + this._dirCache = new Map(); + this._seen = new Set(); + this._events = []; + } + + recordModule(resolvedFile, request = null) { + if (!resolvedFile || typeof resolvedFile !== "string") return null; + const reqPkg = packageNameFromRequest(request); + // Do not emit inventory events for Secfoo's own sensor package. + if (reqPkg === "@rakfortltd/secfoo-sensor") return null; + + const meta = findPackageMetadata(resolvedFile, this._dirCache); + let pkgName = meta ? meta.name : null; + let version = meta ? meta.version : "unknown"; + + if (!pkgName && reqPkg) { + pkgName = reqPkg; + } + if (!pkgName || pkgName === "@rakfortltd/secfoo-sensor") return null; + + // If this module is the app itself inside appRoot (not under node_modules), + // treat it as app package only when explicitly watched, else skip polluting npm inventory. + const normalized = path.resolve(resolvedFile); + const inNodeModules = normalized.includes(`${path.sep}node_modules${path.sep}`); + if (!inNodeModules && !reqPkg && this.appRoot && normalized.startsWith(this.appRoot)) { + // Allow conformance fixtures named explicitly via `package.json`, skip unnamed scripts. + if (!meta) return null; + } + + const key = `${pkgName}\0${version}`; + if (this._seen.has(key)) return null; + this._seen.add(key); + + const ev = { + type: "load", + session: this.sessionId, + ecosystem: "npm", + package: pkgName, + version, + first_seen: new Date().toISOString(), + }; + this._events.push(ev); + return ev; + } + + snapshot() { + return this._events.slice(); + } +} + +module.exports = { + InventoryTracker, + findPackageMetadata, + packageNameFromRequest, +}; diff --git a/npm/secfoo-sensor/lib/probe.js b/npm/secfoo-sensor/lib/probe.js new file mode 100644 index 0000000..2a90671 --- /dev/null +++ b/npm/secfoo-sensor/lib/probe.js @@ -0,0 +1,275 @@ +"use strict"; + +const crypto = require("node:crypto"); +const path = require("node:path"); +const { getContext } = require("./context"); +const { V8CoverageTracker } = require("./coverage"); +const { applyTargetsToExports, applyWatchlistReload, createFunctionWrapper, installCjsHook, uninstallCjsHook } = require("./hooks"); +const { InventoryTracker } = require("./inventory"); +const { clampFlushSeconds, createTransportFromEnv } = require("./transport"); +const { WatchlistManager } = require("./watchlist"); + +const MAX_STACK_FRAMES = 10; +const SENSOR_DIR = path.resolve(__dirname); +const FORBIDDEN_FRAME_RE = /:\/\/|[?#]/; + +function extractAppStackFrames(appRoot = null) { + const stack = String(new Error().stack || ""); + const lines = stack.split("\n").slice(1); + const frames = []; + const root = appRoot ? path.resolve(appRoot) : null; + + for (const rawLine of lines) { + const trimmed = rawLine.trim(); + if (!trimmed.startsWith("at ")) continue; + let loc = trimmed.slice(3); + const parenOpen = loc.lastIndexOf("("); + const parenClose = loc.lastIndexOf(")"); + if (parenOpen >= 0 && parenClose > parenOpen) { + loc = loc.slice(parenOpen + 1, parenClose); + } + if (loc.startsWith("node:") || loc.startsWith("internal/")) continue; + if (loc.startsWith("file://")) { + try { + let p = decodeURIComponent(new URL(loc).pathname); + if (process.platform === "win32" && /^\/[A-Za-z]:/.test(p)) p = p.slice(1); + loc = p; + } catch { + continue; + } + } + // Strip trailing `:line:col` -> `file:line` + const match = /^(.*):(\d+):(\d+)$/.exec(loc); + if (!match) continue; + let filePath = match[1].trim(); + const lineNo = match[2]; + if (!filePath || filePath.startsWith(SENSOR_DIR) || filePath.includes(`${path.sep}node_modules${path.sep}`)) { + continue; + } + if (root && filePath.startsWith(root + path.sep)) { + filePath = filePath.slice(root.length + 1); + } + const candidate = `${filePath.replace(/\\/g, "/")}:${lineNo}`; + if (!candidate.includes(" ") && !FORBIDDEN_FRAME_RE.test(candidate)) { + frames.push(candidate); + if (frames.length >= MAX_STACK_FRAMES) break; + } + } + return frames; +} + +class SensorProbe { + constructor() { + this.started = false; + this.sessionId = crypto.randomUUID(); + this.startedAt = new Date().toISOString(); + this.appRoot = process.env.SECFOO_APP_ROOT || process.cwd(); + this.watchlist = null; + this.inventory = null; + this.transport = null; + this.coverage = null; + this.flushSeconds = 10.0; + this._sampleEvery = 1; + this._callOrdinal = 0; + this._hits = new Map(); // compositeKey -> { fingerprint, symbol, route, auth, count, first_seen, last_seen, stack_sample } + this._timer = null; + this._stopping = false; + } + + start() { + if (this.started) return this; + this.started = true; + + this.flushSeconds = clampFlushSeconds(Number(process.env.SECFOO_FLUSH_INTERVAL || 10.0)) || 10.0; + this.watchlist = new WatchlistManager(process.env.SECFOO_WATCHLIST || null); + this.watchlist.refreshIfNeeded(true); + this.inventory = new InventoryTracker(this.sessionId, this.appRoot); + + this.transport = createTransportFromEnv(process.env, { + onControl: (msg) => { + if (msg && msg.type === "welcome") { + const next = clampFlushSeconds(msg.flush_interval); + if (next !== null && next !== this.flushSeconds) { + this.flushSeconds = next; + this._rescheduleTimer(); + } + } else if (msg && msg.type === "slow") { + const n = Number(msg.sample_every); + if (Number.isInteger(n) && n >= 1) this._sampleEvery = n; + } + }, + }); + + if (process.env.SECFOO_V8_COVERAGE !== "0") { + this.coverage = new V8CoverageTracker(this.appRoot, SENSOR_DIR); + this.coverage.start(); + } + + installCjsHook({ + watchlist: this.watchlist, + inventory: this.inventory, + onHit: (target) => this.recordHit(target), + }); + + this._rescheduleTimer(); + this._installExitHooks(); + return this; + } + + _rescheduleTimer() { + if (this._timer) clearInterval(this._timer); + if (!this.started || this._stopping) return; + this._timer = setInterval(() => { + try { + if (this.watchlist && this.watchlist.refreshIfNeeded(false)) { + applyWatchlistReload({ watchlist: this.watchlist, onHit: (t) => this.recordHit(t) }); + } + this.flush(); + } catch { + // Observe-only, fail-open + } + }, Math.max(50, Math.round(this.flushSeconds * 1000))); + if (typeof this._timer.unref === "function") this._timer.unref(); + } + + _installExitHooks() { + const onBeforeExit = () => { + if (this._stopping) return; + this.stop().catch(() => {}); + }; + const onSignal = () => { + this.stop().catch(() => {}); + }; + process.once("beforeExit", onBeforeExit); + process.once("SIGTERM", onSignal); + process.once("SIGINT", onSignal); + } + + recordHit(target) { + if (!this.started) return; + if (this._sampleEvery > 1) { + this._callOrdinal += 1; + if (this._callOrdinal % this._sampleEvery !== 0) return; + } + const ctx = getContext(); + const route = ctx.route || "unknown"; + const auth = ctx.auth || "unknown"; + const key = `${target.fingerprint}\0${target.symbol}\0${route}\0${auth}`; + const now = new Date().toISOString(); + let entry = this._hits.get(key); + if (!entry) { + entry = { + fingerprint: target.fingerprint, + symbol: target.symbol, + route, + auth, + count: 1, + first_seen: now, + last_seen: now, + stack_sample: extractAppStackFrames(this.appRoot), + }; + this._hits.set(key, entry); + } else { + entry.count += 1; + entry.last_seen = now; + } + } + + buildBatch() { + const cov = this.coverage ? this.coverage.collect() : { app_functions: null, functions_executed: null }; + const session = { + type: "session", + id: this.sessionId, + language: "node", + runtime: process.versions.node, + source: "sensor", + started_at: this.startedAt, + last_seen: new Date().toISOString(), + }; + if (process.env.SECFOO_APP) session.app = String(process.env.SECFOO_APP).trim(); + if (process.env.SECFOO_ENV) session.env = String(process.env.SECFOO_ENV).trim(); + if (cov.app_functions !== null) session.app_functions = cov.app_functions; + if (cov.functions_executed !== null) session.functions_executed = cov.functions_executed; + + const loads = this.inventory ? this.inventory.snapshot() : []; + const hits = []; + for (const entry of this._hits.values()) { + const h = { + type: "hit", + session: this.sessionId, + finding_fingerprint: entry.fingerprint, + symbol: entry.symbol, + route: entry.route, + auth: entry.auth, + count: entry.count, + first_seen: entry.first_seen, + last_seen: entry.last_seen, + }; + if (Array.isArray(entry.stack_sample) && entry.stack_sample.length > 0) { + h.stack_sample = entry.stack_sample; + } + hits.push(h); + } + return [session, ...loads, ...hits]; + } + + flush() { + if (!this.started || !this.transport) return false; + return this.transport.send(this.buildBatch()); + } + + async stop() { + if (!this.started || this._stopping) return; + this._stopping = true; + if (this._timer) { + clearInterval(this._timer); + this._timer = null; + } + try { + this.flush(); + if (this.transport) await this.transport.close(); + } catch { + // Never fail app teardown + } finally { + if (this.coverage) this.coverage.stop(); + uninstallCjsHook(); + } + } +} + +let singleton = null; + +function startFromEnv() { + if (process.env.SECFOO_SENSOR !== "1") return null; + if (!singleton) { + singleton = new SensorProbe().start(); + } + return singleton; +} + +function wrapNamespaceExport(pkgName, exportName, value, moduleUrl = null) { + const probe = startFromEnv(); + if (!probe || !probe.watchlist) return value; + if (probe.inventory && moduleUrl) { + probe.inventory.recordModule(moduleUrl, pkgName); + } + const targets = probe.watchlist.targetsForPackage(pkgName); + if (targets.length === 0) return value; + for (const target of targets) { + if (target.granularity !== "symbol" || !Array.isArray(target.memberPath)) continue; + if (target.memberPath.length === 1 && target.memberPath[0] === exportName && typeof value === "function") { + return createFunctionWrapper(value, target, (t) => probe.recordHit(t)); + } + if (target.memberPath.length > 1 && target.memberPath[0] === exportName && value && typeof value === "object") { + applyTargetsToExports({ [exportName]: value }, [target], (t) => probe.recordHit(t)); + } + } + return value; +} + +module.exports = { + SensorProbe, + extractAppStackFrames, + startFromEnv, + wrapNamespaceExport, +}; diff --git a/npm/secfoo-sensor/lib/transport.js b/npm/secfoo-sensor/lib/transport.js new file mode 100644 index 0000000..2d29e6d --- /dev/null +++ b/npm/secfoo-sensor/lib/transport.js @@ -0,0 +1,357 @@ +"use strict"; + +const fs = require("node:fs"); +const https = require("node:https"); +const net = require("node:net"); +const os = require("node:os"); +const zlib = require("node:zlib"); + +const PROTOCOL_VERSION = 1; +const PROBE_VERSION = "0.1.0"; +const DIRECT_TIMEOUT_MS = 200; +const MAX_QUEUED_BATCHES = 500; +const CLOSE_DRAIN_MS = 200; + +function isLoopbackHost(host) { + const clean = String(host || "").trim().toLowerCase(); + if (clean === "localhost" || clean === "127.0.0.1" || clean === "::1" || clean === "[::1]") return true; + const kind = net.isIP(clean); + if (kind === 4) return clean.startsWith("127."); + if (kind === 6) return clean === "::1"; + return false; +} + +function clampFlushSeconds(val) { + if (typeof val !== "number" || !Number.isFinite(val)) return null; + return Math.min(Math.max(val, 0.05), 3600); +} + +function buildHello() { + return { + type: "hello", + protocol: PROTOCOL_VERSION, + runtime: "node", + runtime_version: process.versions.node, + probe_version: PROBE_VERSION, + pid: process.pid, + host: process.env.HOSTNAME || os.hostname() || "node-host", + }; +} + +function encodeLines(events) { + return events.map((e) => JSON.stringify(e)).join("\n") + "\n"; +} + +class FileTransport { + constructor(template) { + this.template = template; + this.path = template.replace(/\{pid\}/g, String(process.pid)); + } + + send(events) { + if (!events || events.length === 0) return true; + try { + fs.appendFileSync(this.path, encodeLines(events), { encoding: "utf-8", mode: 0o600 }); + return true; + } catch { + return false; + } + } + + close() { + return Promise.resolve(); + } +} + +class StreamTransport { + constructor(address, opts = {}) { + this.address = address; + this.onControl = typeof opts.onControl === "function" ? opts.onControl : () => {}; + this._parsed = StreamTransport.parseAddress(address); + this._sock = null; + this._connecting = false; + this._closed = false; + this._queue = []; // bounded array of JSON-lines strings + this._helloSent = false; + this._readBuf = ""; + } + + static parseAddress(address) { + const parsed = new URL(address); + const scheme = parsed.protocol.replace(":", "").toLowerCase(); + if (scheme === "tcp") { + const host = parsed.hostname; + const port = Number(parsed.port); + if (!isLoopbackHost(host) || !Number.isInteger(port) || port <= 0) { + throw new Error(`tcp:// SECFOO_SENSOR_ADDR must be loopback with a port, got ${address}`); + } + return { scheme: "tcp", host, port }; + } + if (scheme === "unix") { + const p = decodeURIComponent(parsed.pathname || ""); + if (!p) throw new Error(`unix:// address missing path: ${address}`); + return { scheme: "unix", path: p }; + } + if (scheme === "npipe") { + const prefix = "npipe:////"; + if (!address.startsWith(prefix)) throw new Error(`Invalid npipe:// address: ${address}`); + const p = "\\\\" + address.slice(prefix.length).replace(/\//g, "\\"); + return { scheme: "npipe", path: p }; + } + throw new Error(`Unsupported stream transport ${scheme}`); + } + + _enqueue(payloadStr) { + if (this._queue.length >= MAX_QUEUED_BATCHES) { + this._queue.shift(); // Drop oldest on overflow + } + this._queue.push(payloadStr); + } + + _ensureSocket() { + if (this._closed || this._sock || this._connecting) return; + this._connecting = true; + this._helloSent = false; + + const connectOpts = + this._parsed.scheme === "tcp" + ? { host: this._parsed.host, port: this._parsed.port } + : { path: this._parsed.path }; + + let sock; + try { + sock = net.connect(connectOpts); + } catch { + this._connecting = false; + this._sock = null; + return; + } + + // Never hold the Node event loop open if the app is idle/exiting. + if (typeof sock.unref === "function") sock.unref(); + this._sock = sock; + + sock.on("connect", () => { + this._connecting = false; + this._sendHandshakeAndQueue(); + }); + + sock.on("data", (chunk) => { + this._readBuf += chunk.toString("utf-8"); + const lines = this._readBuf.split("\n"); + this._readBuf = lines.pop() || ""; + for (const raw of lines) { + if (!raw.trim()) continue; + try { + const msg = JSON.parse(raw); + this.onControl(msg); + } catch { + // Ignore malformed sensor control frames + } + } + }); + + sock.on("error", () => { + this._connecting = false; + this._dropSocket(); + }); + + sock.on("close", () => { + this._connecting = false; + if (this._sock === sock) { + this._sock = null; + this._helloSent = false; + } + }); + } + + _sendHandshakeAndQueue() { + if (!this._sock || this._sock.destroyed || this._sock.writableEnded) return; + try { + if (!this._helloSent) { + const preface = [buildHello()]; + const key = process.env.SECFOO_SENSOR_KEY; + if (key && this._parsed.scheme === "tcp") { + preface.push({ type: "auth", key }); + } + this._sock.write(encodeLines(preface)); + this._helloSent = true; + } + while (this._queue.length > 0 && this._sock && !this._sock.destroyed) { + const batch = this._queue.shift(); + this._sock.write(batch); + } + } catch { + this._dropSocket(); + } + } + + _dropSocket() { + const s = this._sock; + this._sock = null; + this._helloSent = false; + if (s && !s.destroyed) { + try { + s.destroy(); + } catch { + // fail open + } + } + } + + send(events) { + if (this._closed || !events || events.length === 0) return false; + const payload = encodeLines(events); + if (this._sock && !this._sock.destroyed && !this._connecting && this._helloSent) { + try { + this._sock.write(payload); + return true; + } catch { + this._dropSocket(); + this._enqueue(payload); + return false; + } + } + this._enqueue(payload); + this._ensureSocket(); + return true; + } + + close() { + this._closed = true; + const s = this._sock; + if (!s || s.destroyed) { + this._queue.length = 0; + return Promise.resolve(); + } + return new Promise((resolve) => { + let settled = false; + const done = () => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (s && !s.destroyed) { + try { + s.destroy(); + } catch { + // Ignore close failure + } + } + resolve(); + }; + const timer = setTimeout(done, CLOSE_DRAIN_MS); + if (typeof timer.unref === "function") timer.unref(); + try { + if (typeof s.ref === "function") s.ref(); + if (this._connecting) { + s.once("connect", () => { + this._sendHandshakeAndQueue(); + s.end(); + }); + } else { + this._sendHandshakeAndQueue(); + s.end(); + } + s.once("close", done); + } catch { + done(); + } + }); + } +} + +class DirectHttpsTransport { + constructor(address) { + const keyFile = (process.env.SECFOO_API_KEY_FILE || "").trim(); + const apiKey = keyFile + ? fs.readFileSync(keyFile, "utf-8").trim() + : (process.env.SECFOO_API_KEY || "").trim(); + const project = (process.env.SECFOO_PROJECT || "").trim(); + if (!apiKey || !project) { + throw new Error("Direct HTTPS transport requires SECFOO_API_KEY[_FILE] and SECFOO_PROJECT"); + } + const base = new URL(address); + const params = new URLSearchParams({ project }); + if (process.env.SECFOO_APP) params.set("app", process.env.SECFOO_APP.trim()); + if (process.env.SECFOO_ENV) params.set("env", process.env.SECFOO_ENV.trim()); + this.endpoint = new URL(`/api/runtime/v1/events?${params.toString()}`, base.origin); + this.apiKey = apiKey; + } + + send(events) { + if (!events || events.length === 0) return false; + try { + const gz = zlib.gzipSync(Buffer.from(encodeLines(events), "utf-8")); + const req = https.request( + this.endpoint, + { + method: "POST", + timeout: DIRECT_TIMEOUT_MS, + headers: { + Authorization: `Bearer ${this.apiKey}`, + "Content-Encoding": "gzip", + "Content-Type": "application/x-ndjson", + "Content-Length": gz.length, + }, + }, + (res) => { + res.resume(); + }, + ); + req.on("error", () => {}); + req.on("timeout", () => req.destroy()); + if (req.socket && typeof req.socket.unref === "function") req.socket.unref(); + req.end(gz); + return true; + } catch { + return false; + } + } + + close() { + return Promise.resolve(); + } +} + +class NullTransport { + send() { + return false; + } + close() { + return Promise.resolve(); + } +} + +function createTransportFromEnv(env = process.env, opts = {}) { + const addr = String(env.SECFOO_SENSOR_ADDR || "").trim(); + if (!addr) { + const out = String(env.SECFOO_EVENTS_OUT || "").trim(); + return out ? new FileTransport(out) : new NullTransport(); + } + if (addr.startsWith("file://")) { + let p = decodeURIComponent(new URL(addr).pathname); + if (process.platform === "win32" && /^\/[A-Za-z]:/.test(p)) p = p.slice(1); + return new FileTransport(p); + } + if (addr.startsWith("https://")) { + return new DirectHttpsTransport(addr); + } + if (addr.startsWith("tcp://") || addr.startsWith("unix://") || addr.startsWith("npipe://")) { + return new StreamTransport(addr, opts); + } + throw new Error(`Unsupported SECFOO_SENSOR_ADDR: ${addr}`); +} + +module.exports = { + CLOSE_DRAIN_MS, + DirectHttpsTransport, + FileTransport, + NullTransport, + PROTOCOL_VERSION, + PROBE_VERSION, + StreamTransport, + buildHello, + clampFlushSeconds, + createTransportFromEnv, + encodeLines, +}; diff --git a/npm/secfoo-sensor/lib/watchlist.js b/npm/secfoo-sensor/lib/watchlist.js new file mode 100644 index 0000000..296412f --- /dev/null +++ b/npm/secfoo-sensor/lib/watchlist.js @@ -0,0 +1,118 @@ +"use strict"; + +const fs = require("node:fs"); + +const RECHECK_MS = 30_000; + +/** + * Parse `#52` npm symbol notation (`pkg#export` or `@scope/pkg#Class.method`) + * into `{ packageName, memberPath }`. + */ +function parseNpmSymbol(symbol) { + if (typeof symbol !== "string") return null; + const hashIdx = symbol.indexOf("#"); + if (hashIdx <= 0 || hashIdx === symbol.length - 1) return null; + const packageName = symbol.slice(0, hashIdx).trim(); + const memberRaw = symbol.slice(hashIdx + 1).trim(); + if (!packageName || !memberRaw) return null; + const memberPath = memberRaw.split(".").filter(Boolean); + if (memberPath.length === 0) return null; + return { packageName, memberPath }; +} + +class WatchlistManager { + constructor(filePath = null) { + this.filePath = filePath ? String(filePath).trim() || null : null; + this._lastCheckMs = 0; + this._lastMtimeMs = -1; + this._byPackage = new Map(); // packageName -> Array<{ fingerprint, symbol, memberPath, granularity }> + this._allTargets = []; + } + + _loadFromDisk() { + if (!this.filePath) return false; + let stat; + try { + stat = fs.statSync(this.filePath); + } catch { + return false; + } + if (stat.mtimeMs === this._lastMtimeMs) return false; + + let doc; + try { + doc = JSON.parse(fs.readFileSync(this.filePath, "utf-8")); + } catch { + return false; + } + this._lastMtimeMs = stat.mtimeMs; + + const byPkg = new Map(); + const targets = []; + const entries = Array.isArray(doc && doc.entries) ? doc.entries : []; + for (const entry of entries) { + if (!entry || typeof entry !== "object") continue; + if (entry.ecosystem && entry.ecosystem !== "npm") continue; + const fp = String(entry.finding_fingerprint || "").trim(); + const pkg = String(entry.package || "").trim(); + const granularity = entry.granularity === "package" ? "package" : "symbol"; + const syms = Array.isArray(entry.symbols) ? entry.symbols : []; + + if (!pkg && syms.length === 0) continue; + if (granularity === "package" || syms.length === 0) { + if (!pkg) continue; + const list = byPkg.get(pkg) || []; + list.push({ fingerprint: fp, symbol: pkg, packageName: pkg, memberPath: [], granularity: "package" }); + byPkg.set(pkg, list); + continue; + } + + for (const sym of syms) { + const parsed = parseNpmSymbol(sym); + const packageName = parsed ? parsed.packageName : pkg; + const memberPath = parsed ? parsed.memberPath : []; + if (!packageName || memberPath.length === 0) continue; + const item = { + fingerprint: fp, + symbol: sym, + packageName, + memberPath, + granularity: "symbol", + }; + const list = byPkg.get(packageName) || []; + list.push(item); + byPkg.set(packageName, list); + targets.push(item); + } + } + + this._byPackage = byPkg; + this._allTargets = targets; + return true; + } + + refreshIfNeeded(force = false) { + const now = Date.now(); + if (!force && now - this._lastCheckMs < RECHECK_MS) return false; + this._lastCheckMs = now; + return this._loadFromDisk(); + } + + targetsForPackage(packageName) { + return this._byPackage.get(packageName) || []; + } + + watchedPackages() { + return Array.from(this._byPackage.keys()); + } + + allSymbolTargets() { + return this._allTargets; + } +} + +module.exports = { + RECHECK_MS, + WatchlistManager, + parseNpmSymbol, +}; diff --git a/npm/secfoo-sensor/package.json b/npm/secfoo-sensor/package.json index 43dc69d..35bf1ac 100644 --- a/npm/secfoo-sensor/package.json +++ b/npm/secfoo-sensor/package.json @@ -1,10 +1,14 @@ { "name": "@rakfortltd/secfoo-sensor", "version": "0.1.0", - "description": "In-process Node.js request, job, and auth attribution middleware for Secfoo runtime reachability (#69).", + "description": "In-process Node.js live sensor (--require / --import) and request attribution middleware for Secfoo runtime reachability (#56, #69).", "main": "index.js", + "exports": { + ".": "./index.js", + "./register": "./register.mjs" + }, "scripts": { - "test": "node --test test/middleware.test.js" + "test": "node --test test/middleware.test.js test/probe_cjs.test.js test/probe_esm.test.mjs" }, "engines": { "node": ">=18" diff --git a/npm/secfoo-sensor/register.mjs b/npm/secfoo-sensor/register.mjs new file mode 100644 index 0000000..b6e6c41 --- /dev/null +++ b/npm/secfoo-sensor/register.mjs @@ -0,0 +1,9 @@ +import { register } from "node:module"; +import { createRequire } from "node:module"; + +if (process.env.SECFOO_SENSOR === "1") { + register("./lib/esm_loader.mjs", import.meta.url); + const require = createRequire(import.meta.url); + const { startFromEnv } = require("./lib/probe"); + startFromEnv(); +} diff --git a/npm/secfoo-sensor/test/benchmark.js b/npm/secfoo-sensor/test/benchmark.js new file mode 100644 index 0000000..ce55ec0 --- /dev/null +++ b/npm/secfoo-sensor/test/benchmark.js @@ -0,0 +1,74 @@ +"use strict"; + +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); + +const SENSOR_INDEX = path.resolve(__dirname, "..", "index.js"); + +function runBench() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "secfoo-node-bench-")); + try { + const modDir = path.join(dir, "node_modules", "bench-pkg"); + fs.mkdirSync(modDir, { recursive: true }); + fs.writeFileSync(path.join(modDir, "package.json"), JSON.stringify({ name: "bench-pkg", version: "1.0.0" })); + fs.writeFileSync(path.join(modDir, "index.js"), "exports.work = function work(x) { return (x * 3 + 1) | 0; };\n"); + const watchlist = path.join(dir, "watchlist.json"); + fs.writeFileSync( + watchlist, + JSON.stringify({ + version: 1, + entries: [{ finding_fingerprint: "fp-b", ecosystem: "npm", package: "bench-pkg", granularity: "symbol", symbols: ["bench-pkg#work"] }], + }), + ); + const app = path.join(dir, "bench.js"); + fs.writeFileSync( + app, + [ + "const { work } = require('bench-pkg');", + "const n = Number(process.env.BENCH_N || 200000);", + "let acc = 0;", + "const t0 = process.hrtime.bigint();", + "for (let i = 0; i < n; i += 1) acc = (acc + work(i)) | 0;", + "const elapsedMs = Number(process.hrtime.bigint() - t0) / 1e6;", + "console.log(JSON.stringify({ acc, elapsedMs }));", + ].join("\n"), + ); + + const nSmall = 200_000; + const nLarge = 1_000_000; + const execOne = (n, probed) => { + const args = probed ? ["--require", SENSOR_INDEX, app] : [app]; + const out = spawnSync(process.execPath, args, { + cwd: dir, + env: { + ...process.env, + BENCH_N: String(n), + SECFOO_SENSOR: probed ? "1" : "", + SECFOO_WATCHLIST: watchlist, + SECFOO_EVENTS_OUT: path.join(dir, "events.ndjson"), + SECFOO_V8_COVERAGE: "0", + }, + encoding: "utf-8", + }); + if (out.status !== 0) throw new Error(out.stderr); + return JSON.parse(out.stdout.trim()).elapsedMs; + }; + + const barePerCallUs = ((execOne(nLarge, false) - execOne(nSmall, false)) * 1000) / (nLarge - nSmall); + const probedPerCallUs = ((execOne(nLarge, true) - execOne(nSmall, true)) * 1000) / (nLarge - nSmall); + const overheadUs = probedPerCallUs - barePerCallUs; + console.log( + JSON.stringify({ + bare_per_call_us: Number(barePerCallUs.toFixed(4)), + probed_per_call_us: Number(probedPerCallUs.toFixed(4)), + marginal_overhead_us: Number(overheadUs.toFixed(4)), + }), + ); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +runBench(); diff --git a/npm/secfoo-sensor/test/probe_cjs.test.js b/npm/secfoo-sensor/test/probe_cjs.test.js new file mode 100644 index 0000000..9e2bfa0 --- /dev/null +++ b/npm/secfoo-sensor/test/probe_cjs.test.js @@ -0,0 +1,126 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { spawnSync } = require("node:child_process"); +const test = require("node:test"); + +const SENSOR_INDEX = path.resolve(__dirname, "..", "index.js"); + +test("inert when SECFOO_SENSOR is unset", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "secfoo-node-inert-")); + try { + const outFile = path.join(dir, "events.ndjson"); + const appFile = path.join(dir, "app.js"); + fs.writeFileSync(appFile, "console.log('ok');\n"); + const res = spawnSync(process.execPath, ["--require", SENSOR_INDEX, appFile], { + env: { ...process.env, SECFOO_EVENTS_OUT: outFile, SECFOO_SENSOR: "" }, + encoding: "utf-8", + }); + assert.equal(res.status, 0); + assert.equal(fs.existsSync(outFile), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("CJS hook preserves this, args, return, errors, instanceof, and reloads watchlist", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "secfoo-node-cjs-")); + try { + const modDir = path.join(dir, "node_modules", "vuln-lib"); + fs.mkdirSync(modDir, { recursive: true }); + fs.writeFileSync(path.join(modDir, "package.json"), JSON.stringify({ name: "vuln-lib", version: "1.2.3" })); + fs.writeFileSync( + path.join(modDir, "index.js"), + [ + "function add(a, b) { return this.offset + a + b; }", + "function boom(msg) { throw new TypeError(msg); }", + "function lateFn(x) { return x * 2; }", + "class Widget { constructor(v) { this.v = v; } }", + "Widget.kind = 'ui';", + "module.exports = { add, boom, lateFn, Widget };", + ].join("\n"), + ); + + const watchlist = path.join(dir, "watchlist.json"); + fs.writeFileSync( + watchlist, + JSON.stringify({ + version: 1, + entries: [ + { + finding_fingerprint: "fp-node-1", + ecosystem: "npm", + package: "vuln-lib", + version: "1.2.3", + granularity: "symbol", + symbols: ["vuln-lib#add", "vuln-lib#boom", "vuln-lib#Widget"], + }, + ], + }), + ); + + const outFile = path.join(dir, "events.ndjson"); + const runnerFile = path.join(dir, "app.js"); + fs.writeFileSync( + runnerFile, + [ + "const assert = require('node:assert/strict');", + "const fs = require('node:fs');", + `const { runWithRequest, startFromEnv } = require(${JSON.stringify(SENSOR_INDEX)});`, + "const lib = require('vuln-lib');", + "const ctx = { offset: 10 };", + "runWithRequest(() => {", + " assert.equal(lib.add.call(ctx, 2, 3), 15);", + " assert.throws(() => lib.boom('bad-input-SECRET'), TypeError);", + " const w = new lib.Widget(7);", + " assert.equal(w instanceof lib.Widget, true);", + " assert.equal(w.v, 7);", + " assert.equal(lib.Widget.kind, 'ui');", + "}, { route: 'POST /orders', auth: 'authenticated' });", + "// Mutate watchlist and trigger reload on already-loaded cached module:", + "const wlPath = process.env.SECFOO_WATCHLIST;", + "const doc = JSON.parse(fs.readFileSync(wlPath, 'utf-8'));", + "doc.entries[0].symbols.push('vuln-lib#lateFn');", + "fs.writeFileSync(wlPath, JSON.stringify(doc));", + "const now = new Date(Date.now() + 2000);", + "fs.utimesSync(wlPath, now, now);", + "const probe = startFromEnv();", + "probe.watchlist.refreshIfNeeded(true);", + "const { applyWatchlistReload } = require(" + JSON.stringify(path.resolve(__dirname, "..", "lib", "hooks.js")) + ");", + "applyWatchlistReload({ watchlist: probe.watchlist, onHit: (t) => probe.recordHit(t) });", + "assert.equal(lib.lateFn(21), 42);", + ].join("\n"), + ); + + const res = spawnSync(process.execPath, ["--require", SENSOR_INDEX, runnerFile], { + cwd: dir, + env: { + ...process.env, + SECFOO_SENSOR: "1", + SECFOO_WATCHLIST: watchlist, + SECFOO_EVENTS_OUT: outFile, + SECFOO_FLUSH_INTERVAL: "0.05", + }, + encoding: "utf-8", + }); + assert.equal(res.status, 0, res.stderr); + const events = fs + .readFileSync(outFile, "utf-8") + .trim() + .split("\n") + .map((l) => JSON.parse(l)); + const loads = events.filter((e) => e.type === "load" && e.package === "vuln-lib"); + assert.equal(loads.length >= 1, true); + assert.equal(loads[0].version, "1.2.3"); + const hits = events.filter((e) => e.type === "hit"); + assert.equal(hits.some((h) => h.symbol === "vuln-lib#add" && h.route === "POST /orders" && h.auth === "authenticated"), true); + assert.equal(hits.some((h) => h.symbol === "vuln-lib#Widget"), true); + assert.equal(hits.some((h) => h.symbol === "vuln-lib#lateFn"), true); + assert.equal(JSON.stringify(events).includes("bad-input-SECRET"), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/npm/secfoo-sensor/test/probe_esm.test.mjs b/npm/secfoo-sensor/test/probe_esm.test.mjs new file mode 100644 index 0000000..c875cb5 --- /dev/null +++ b/npm/secfoo-sensor/test/probe_esm.test.mjs @@ -0,0 +1,85 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import test from "node:test"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const TEST_DIR = path.dirname(fileURLToPath(import.meta.url)); +const REGISTER_URL = pathToFileURL(path.resolve(TEST_DIR, "..", "register.mjs")).href; + +test("ESM module.register wraps watched named exports and preserves default class instanceof", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "secfoo-node-esm-")); + try { + const modDir = path.join(dir, "node_modules", "esm-vuln"); + fs.mkdirSync(modDir, { recursive: true }); + fs.writeFileSync( + path.join(modDir, "package.json"), + JSON.stringify({ name: "esm-vuln", version: "2.0.1", type: "module", main: "./index.mjs" }), + ); + fs.writeFileSync( + path.join(modDir, "index.mjs"), + [ + "export function danger(x) { return `out:${x}`; }", + "export default class Client { constructor(id) { this.id = id; } }", + ].join("\n"), + ); + + const watchlist = path.join(dir, "watchlist.json"); + fs.writeFileSync( + watchlist, + JSON.stringify({ + version: 1, + entries: [ + { + finding_fingerprint: "fp-esm-1", + ecosystem: "npm", + package: "esm-vuln", + version: "2.0.1", + granularity: "symbol", + symbols: ["esm-vuln#danger", "esm-vuln#default"], + }, + ], + }), + ); + + const outFile = path.join(dir, "events.ndjson"); + const appFile = path.join(dir, "app.mjs"); + fs.writeFileSync( + appFile, + [ + "import assert from 'node:assert/strict';", + "import Client, { danger } from 'esm-vuln';", + "assert.equal(danger('arg-SECRET'), 'out:arg-SECRET');", + "const c = new Client(99);", + "assert.equal(c instanceof Client, true);", + "assert.equal(c.id, 99);", + ].join("\n"), + ); + + const res = spawnSync(process.execPath, ["--import", REGISTER_URL, appFile], { + cwd: dir, + env: { + ...process.env, + SECFOO_SENSOR: "1", + SECFOO_WATCHLIST: watchlist, + SECFOO_EVENTS_OUT: outFile, + SECFOO_FLUSH_INTERVAL: "0.05", + }, + encoding: "utf-8", + }); + assert.equal(res.status, 0, res.stderr); + const lines = fs + .readFileSync(outFile, "utf-8") + .trim() + .split("\n") + .map((l) => JSON.parse(l)); + assert.equal(lines.some((e) => e.type === "load" && e.package === "esm-vuln" && e.version === "2.0.1"), true); + assert.equal(lines.some((e) => e.type === "hit" && e.symbol === "esm-vuln#danger" && e.count === 1), true); + assert.equal(lines.some((e) => e.type === "hit" && e.symbol === "esm-vuln#default" && e.count === 1), true); + assert.equal(JSON.stringify(lines).includes("arg-SECRET"), false); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/tests/test_sensor/test_node_probe.py b/tests/test_sensor/test_node_probe.py new file mode 100644 index 0000000..3b22d2d --- /dev/null +++ b/tests/test_sensor/test_node_probe.py @@ -0,0 +1,120 @@ +"""Cross-language tests and #73 conformance verification for Node.js live sensor (#56).""" + +from __future__ import annotations + +import json +import shutil +import subprocess # nosec B404 -- runs node test/conformance binaries on test fixtures +from pathlib import Path + +import pytest + +from secfoo.runtime.conformance.kit import SENTINEL, run_kit + +ROOT = Path(__file__).resolve().parents[2] +NPM_SENSOR = ROOT / "npm" / "secfoo-sensor" +NODE_BIN = shutil.which("node") +NPM_BIN = shutil.which("npm") + + +@pytest.mark.skipif(not NODE_BIN, reason="node runtime not installed") +def test_node_sensor_npm_unit_and_esm_tests(): + # Run directly via `node --test` cleanly on Windows and POSIX without shell=True. + res = subprocess.run( # nosec B603 + [ + NODE_BIN, + "--test", + str(NPM_SENSOR / "test" / "middleware.test.js"), + str(NPM_SENSOR / "test" / "probe_cjs.test.js"), + str(NPM_SENSOR / "test" / "probe_esm.test.mjs"), + ], + cwd=str(NPM_SENSOR), + capture_output=True, + text=True, + check=False, + ) + assert res.returncode == 0, res.stdout + "\n" + res.stderr + + +@pytest.mark.skipif(not NODE_BIN, reason="node runtime not installed") +def test_node_cjs_probe_passes_conformance_kit(tmp_path): + mod_dir = tmp_path / "node_modules" / "conformance" + mod_dir.mkdir(parents=True) + (mod_dir / "package.json").write_text('{"name":"conformance","version":"1.0.0"}\n', encoding="utf-8") + (mod_dir / "index.js").write_text("exports.parse = function parse(text) { return String(text).length; };\n", encoding="utf-8") + + app_js = tmp_path / "sample_app.js" + app_js.write_text( + ( + "const { runWithRequest } = require(" + json.dumps(str(NPM_SENSOR / "index.js")) + ");\n" + "const { parse } = require(" + json.dumps(str(mod_dir / "index.js")) + ");\n" + "const step = process.env.SECFOO_CONFORMANCE_STEP;\n" + "if (step === 'call') {\n" + " for (let i = 0; i < 3; i += 1) parse('payload-' + i);\n" + "} else if (step === 'request') {\n" + f" runWithRequest(() => parse({json.dumps(SENTINEL)}), {{ route: 'POST /orders', auth: 'authenticated' }});\n" + "} else if (step === 'slow') {\n" + " parse('one');\n" + " setTimeout(() => { console.log('ok'); }, 150);\n" + "} else if (step === 'loop') {\n" + " const n = Number(process.env.SECFOO_CONFORMANCE_N || 200000);\n" + " let total = 0;\n" + " for (let i = 0; i < n; i += 1) total += parse('x');\n" + " if (total < 0) process.exit(1);\n" + "}\n" + ), + encoding="utf-8", + ) + + results = run_kit( + [NODE_BIN, "--require", str(NPM_SENSOR / "index.js"), str(app_js)], + symbol="conformance#parse", + ecosystem="npm", + max_call_overhead_us=50.0, + loop_calls=200_000, + ) + failed = [f"{r.name}: {r.detail}" for r in results if not r.passed] + assert not failed, "\n".join(failed) + + +@pytest.mark.skipif(not NODE_BIN, reason="node runtime not installed") +def test_node_esm_probe_passes_conformance_kit(tmp_path): + mod_dir = tmp_path / "node_modules" / "conformance" + mod_dir.mkdir(parents=True) + (mod_dir / "package.json").write_text('{"name":"conformance","version":"1.0.0","type":"module","main":"./index.mjs"}\n', encoding="utf-8") + (mod_dir / "index.mjs").write_text("export function parse(text) { return String(text).length; }\n", encoding="utf-8") + + app_mjs = tmp_path / "sample_app.mjs" + register_url = (NPM_SENSOR / "register.mjs").resolve().as_uri() + app_mjs.write_text( + ( + "import { createRequire } from 'node:module';\n" + f"const req = createRequire(import.meta.url);\n" + f"const {{ runWithRequest }} = req({json.dumps(str(NPM_SENSOR / 'index.js'))});\n" + "import { parse } from 'conformance';\n" + "const step = process.env.SECFOO_CONFORMANCE_STEP;\n" + "if (step === 'call') {\n" + " for (let i = 0; i < 3; i += 1) parse('payload-' + i);\n" + "} else if (step === 'request') {\n" + f" runWithRequest(() => parse({json.dumps(SENTINEL)}), {{ route: 'GET /items/{{id}}', auth: 'anonymous' }});\n" + "} else if (step === 'slow') {\n" + " parse('one');\n" + " setTimeout(() => { console.log('ok'); }, 150);\n" + "} else if (step === 'loop') {\n" + " const n = Number(process.env.SECFOO_CONFORMANCE_N || 200000);\n" + " let total = 0;\n" + " for (let i = 0; i < n; i += 1) total += parse('x');\n" + " if (total < 0) process.exit(1);\n" + "}\n" + ), + encoding="utf-8", + ) + results = run_kit( + [NODE_BIN, "--import", register_url, str(app_mjs)], + symbol="conformance#parse", + ecosystem="npm", + max_call_overhead_us=50.0, + loop_calls=200_000, + ) + failed = [f"{r.name}: {r.detail}" for r in results if not r.passed] + assert not failed, "\n".join(failed)