Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions npm/secfoo-sensor/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"use strict";

const {
NodeHitCollector,
detectAuthState,
getContext,
runWithJob,
runWithRequest,
sanitizeRouteTemplate,
} = require("./lib/context");
const { expressMiddleware, fastifyPlugin } = require("./lib/middleware");

module.exports = {
NodeHitCollector,
detectAuthState,
expressMiddleware,
fastifyPlugin,
getContext,
runWithJob,
runWithRequest,
sanitizeRouteTemplate,
};
224 changes: 224 additions & 0 deletions npm/secfoo-sensor/lib/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
"use strict";

const crypto = require("node:crypto");
const fs = require("node:fs");
const os = require("node:os");
const { AsyncLocalStorage } = require("node:async_hooks");

const HTTP_METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE"]);
const UNSAFE_ROUTE_RE = /:\/\/|[?#\r\n\t]/;
const JOB_SAFE_RE = /[^A-Za-z0-9._:/-]+/g;
const SESSION_COOKIE_NAMES = new Set([
"session",
"sessionid",
"session_id",
"sid",
"connect.sid",
"phpsessid",
"jsessionid",
"auth",
"auth_token",
"access_token",
"jwt",
"_session",
]);

const storage = new AsyncLocalStorage();

function sanitizeRouteTemplate(method, template) {
if (typeof template !== "string") return "unknown";
const raw = template.trim();
if (!raw || raw.length > 512 || UNSAFE_ROUTE_RE.test(raw)) return "unknown";
// Express uses :param; normalize cleanly to {param} unless already braced.
let normalized = raw.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, "{$1}");
if (!normalized.startsWith("/")) {
normalized = "/" + normalized.replace(/^\/+/, "");
}
if (normalized !== "/" && normalized.endsWith("/")) {
normalized = normalized.slice(0, -1);
}
if (normalized.includes(" ")) return "unknown";
const verb = typeof method === "string" ? method.trim().toUpperCase() : "";
return HTTP_METHODS.has(verb) ? `${verb} ${normalized}` : normalized;
}

function hasSessionCookie(rawCookie) {
if (typeof rawCookie !== "string" || !rawCookie) return false;
for (const part of rawCookie.split(";")) {
const eq = part.indexOf("=");
if (eq <= 0) continue;
const name = part.slice(0, eq).trim().toLowerCase();
const val = part.slice(eq + 1).trim();
if (!val) continue;
if (SESSION_COOKIE_NAMES.has(name) || name.includes("session")) return true;
}
return false;
}

function detectAuthState({ frameworkAuthenticated = null, headers = null } = {}) {
if (frameworkAuthenticated === true) return "authenticated";
let authSeen = false;
let sessionCookieSeen = false;
if (headers && typeof headers === "object") {
const authHeader = headers.authorization ?? headers.Authorization;
if (typeof authHeader === "string" && authHeader.trim().length > 0) {
authSeen = true;
}
const cookieHeader = headers.cookie ?? headers.Cookie;
if (typeof cookieHeader === "string" && hasSessionCookie(cookieHeader)) {
sessionCookieSeen = true;
}
}
if (authSeen || sessionCookieSeen) return "authenticated";
if (frameworkAuthenticated === false || headers !== null) return "anonymous";
return "unknown";
}

function getContext() {
const state = storage.getStore();
if (!state) return { route: "unknown", auth: "unknown" };
if (typeof state.resolve === "function" && !state.resolved) {
const { route, auth } = state.resolve();
state.route = route || "unknown";
state.auth = auth || "unknown";
if (state.route !== "unknown") state.resolved = true;
}
return { route: state.route, auth: state.auth };
}

function runWithRequest(fn, { route = "unknown", auth = "unknown", resolve = null, onRoute = null } = {}) {
const state = {
route,
auth,
resolve,
resolved: typeof resolve !== "function",
};
return storage.run(state, () => {
try {
const result = fn();
if (result && typeof result.finally === "function") {
return result.finally(() => {
const finalCtx = getContext();
if (onRoute && finalCtx.route && finalCtx.route !== "unknown") {
onRoute(finalCtx.route);
}
});
}
const finalCtx = getContext();
if (onRoute && finalCtx.route && finalCtx.route !== "unknown") {
onRoute(finalCtx.route);
}
return result;
} catch (err) {
const finalCtx = getContext();
if (onRoute && finalCtx.route && finalCtx.route !== "unknown") {
onRoute(finalCtx.route);
}
throw err;
}
});
}

// Index-based trim: a `/^[-/]+|[-/]+$/` regex is quadratic on long runs of
// '-' (CodeQL js/polynomial-redos), and job names come from library callers.
function trimDashesAndSlashes(text) {
let start = 0;
let end = text.length;
while (start < end && (text[start] === "-" || text[start] === "/")) start += 1;
while (end > start && (text[end - 1] === "-" || text[end - 1] === "/")) end -= 1;
return text.slice(start, end);
}

function runWithJob(name, fn) {
const cleaned = trimDashesAndSlashes(String(name || "").trim().replace(JOB_SAFE_RE, "-"));
const route = `job:${(cleaned || "unknown").slice(0, 200)}`;
return storage.run({ route, auth: "unknown", resolved: true }, fn);
}

class NodeHitCollector {
constructor() {
this.sessionId = crypto.randomUUID();
this.startedAt = new Date().toISOString();
this.hits = new Map();
this.routesSeen = new Map();
}

recordRoute(route) {
if (!route || route === "unknown" || route === "startup" || route.startsWith("job:")) return;
this.routesSeen.set(route, (this.routesSeen.get(route) || 0) + 1);
}

recordHit(fingerprint, symbol) {
const { route, auth } = getContext();
const key = `${fingerprint}\0${symbol}\0${route}\0${auth}`;
const now = Date.now();
const existing = this.hits.get(key);
if (existing) {
existing.count += 1;
existing.lastSeen = now;
return;
}
this.hits.set(key, {
fingerprint,
symbol,
route,
auth,
count: 1,
firstSeen: now,
lastSeen: now,
});
}

snapshot() {
const routesObj = {};
for (const [k, v] of Array.from(this.routesSeen.entries()).sort((a, b) => a[0].localeCompare(b[0]))) {
routesObj[k] = v;
}
const session = {
type: "session",
id: this.sessionId,
language: "node",
runtime: process.versions.node,
source: "sensor",
started_at: this.startedAt,
ended_at: new Date().toISOString(),
instance: os.hostname(),
};
if (Object.keys(routesObj).length > 0) {
session.routes_seen = routesObj;
}
const events = [session];
for (const item of this.hits.values()) {
const hit = {
type: "hit",
session: this.sessionId,
finding_fingerprint: item.fingerprint,
symbol: item.symbol,
route: item.route,
count: item.count,
first_seen: new Date(item.firstSeen).toISOString(),
last_seen: new Date(item.lastSeen).toISOString(),
};
if (item.auth === "anonymous" || item.auth === "authenticated") {
hit.auth = item.auth;
}
events.push(hit);
}
return events;
}

flushToFile(filePath) {
const target = String(filePath).replace("{pid}", String(process.pid));
const lines = this.snapshot().map((e) => JSON.stringify(e)).join("\n") + "\n";
fs.writeFileSync(target, lines, "utf8");
}
}

module.exports = {
NodeHitCollector,
detectAuthState,
getContext,
runWithJob,
runWithRequest,
sanitizeRouteTemplate,
};
87 changes: 87 additions & 0 deletions npm/secfoo-sensor/lib/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"use strict";

const { detectAuthState, getContext, runWithRequest, sanitizeRouteTemplate } = require("./context");

function _resolveExpressAuth(req) {
let fwAuth = null;
if (typeof req?.isAuthenticated === "function") {
try {
fwAuth = Boolean(req.isAuthenticated());
} catch {
fwAuth = null;
}
} else if (req?.user && typeof req.user === "object") {
fwAuth = true;
}
return detectAuthState({ frameworkAuthenticated: fwAuth, headers: req?.headers || null });
}

function _expressRouteTemplate(req) {
// Never read req.url or req.originalUrl: only use matched req.route.path (+ mount baseUrl).
const routePath = req?.route?.path;
if (typeof routePath !== "string" || !routePath) return "unknown";
const baseUrl = typeof req?.baseUrl === "string" ? req.baseUrl : "";
const combined = baseUrl ? `${baseUrl.replace(/\/+$/, "")}/${routePath.replace(/^\/+/, "")}` : routePath;
return sanitizeRouteTemplate(req?.method, combined);
}

function expressMiddleware(collector = null) {
return function secfooExpressMiddleware(req, res, next) {
return runWithRequest(
() => {
if (typeof res?.on === "function") {
res.on("finish", () => {
const ctx = getContext();
if (collector && ctx.route && ctx.route !== "unknown") {
collector.recordRoute(ctx.route);
}
});
}
return next();
},
{
resolve: () => ({
route: _expressRouteTemplate(req),
auth: _resolveExpressAuth(req),
}),
}
);
};
}

function _fastifyRouteTemplate(request) {
// Never read request.url or request.raw.url: read routeOptions.url (Fastify v4/v5) or routerPath.
const pattern = request?.routeOptions?.url || request?.routerPath;
const method = request?.routeOptions?.method || request?.method;
return sanitizeRouteTemplate(typeof method === "string" ? method : null, pattern);
}

function _resolveFastifyAuth(request) {
const fwAuth = request?.user && typeof request.user === "object" ? true : null;
return detectAuthState({ frameworkAuthenticated: fwAuth, headers: request?.headers || null });
}

function fastifyPlugin(fastify, opts = {}, done) {
const collector = opts.collector || null;
fastify.addHook("onRequest", (request, _reply, hookDone) => {
runWithRequest(() => hookDone(), {
resolve: () => ({
route: _fastifyRouteTemplate(request),
auth: _resolveFastifyAuth(request),
}),
});
});
fastify.addHook("onResponse", (request, _reply, hookDone) => {
if (collector) {
const route = _fastifyRouteTemplate(request);
if (route !== "unknown") collector.recordRoute(route);
}
hookDone();
});
if (typeof done === "function") done();
}

module.exports = {
expressMiddleware,
fastifyPlugin,
};
25 changes: 25 additions & 0 deletions npm/secfoo-sensor/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "@rakfortltd/secfoo-sensor",
"version": "0.1.0",
"description": "In-process Node.js request, job, and auth attribution middleware for Secfoo runtime reachability (#69).",
"main": "index.js",
"scripts": {
"test": "node --test test/middleware.test.js"
},
"engines": {
"node": ">=18"
},
"license": "Apache-2.0",
"homepage": "https://github.com/secfoo-com/secfoo",
"repository": {
"type": "git",
"url": "git+https://github.com/secfoo-com/secfoo.git"
},
"keywords": [
"security",
"runtime",
"sca",
"secfoo",
"reachability"
]
}
Loading
Loading