diff --git a/npm/secfoo-sensor/index.js b/npm/secfoo-sensor/index.js new file mode 100644 index 0000000..3e25116 --- /dev/null +++ b/npm/secfoo-sensor/index.js @@ -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, +}; diff --git a/npm/secfoo-sensor/lib/context.js b/npm/secfoo-sensor/lib/context.js new file mode 100644 index 0000000..5cc90f9 --- /dev/null +++ b/npm/secfoo-sensor/lib/context.js @@ -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, +}; diff --git a/npm/secfoo-sensor/lib/middleware.js b/npm/secfoo-sensor/lib/middleware.js new file mode 100644 index 0000000..9d75873 --- /dev/null +++ b/npm/secfoo-sensor/lib/middleware.js @@ -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, +}; diff --git a/npm/secfoo-sensor/package.json b/npm/secfoo-sensor/package.json new file mode 100644 index 0000000..43dc69d --- /dev/null +++ b/npm/secfoo-sensor/package.json @@ -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" + ] +} diff --git a/npm/secfoo-sensor/test/middleware.test.js b/npm/secfoo-sensor/test/middleware.test.js new file mode 100644 index 0000000..ee37e3c --- /dev/null +++ b/npm/secfoo-sensor/test/middleware.test.js @@ -0,0 +1,130 @@ +"use strict"; + +const assert = require("node:assert/strict"); +const { describe, it } = require("node:test"); + +const { + NodeHitCollector, + expressMiddleware, + fastifyPlugin, + getContext, + runWithJob, + sanitizeRouteTemplate, +} = require("../index"); + +describe("Node AsyncLocalStorage route and auth attribution (#69)", () => { + it("normalizes templates and rejects concrete URLs/query strings cleanly", () => { + assert.equal(sanitizeRouteTemplate("get", "/users/:id"), "GET /users/{id}"); + assert.equal(sanitizeRouteTemplate("POST", "/upload"), "POST /upload"); + assert.equal(sanitizeRouteTemplate("GET", "/users/8675309?token=s3cr3t"), "unknown"); + assert.equal(sanitizeRouteTemplate("GET", "https://example.com/a"), "unknown"); + assert.equal(sanitizeRouteTemplate("GET", null), "unknown"); + }); + + it("extracts Express req.route.path, auth state, and route counts without leaking params", async () => { + const collector = new NodeHitCollector(); + const mw = expressMiddleware(collector); + const SENTINEL = "s3cr3t-SENTINEL-73"; + + async function invokeExpress({ method, rawUrl, headers, matchedRoutePath, baseUrl = "", user = null }) { + const finishHandlers = []; + const req = { + method, + url: rawUrl, + originalUrl: rawUrl, + baseUrl, + headers, + user, + route: null, + }; + const res = { + on(ev, cb) { + if (ev === "finish") finishHandlers.push(cb); + }, + }; + await new Promise((resolve) => { + mw(req, res, async () => { + // Simulate Express setting req.route during router dispatch before handler runs + req.route = matchedRoutePath ? { path: matchedRoutePath } : null; + await new Promise((r) => setTimeout(r, 5)); + collector.recordHit("fp-express-1", "yaml.load"); + for (const h of finishHandlers) h(); + resolve(); + }); + }); + } + + // Concurrent anonymous + authenticated requests stay isolated inside AsyncLocalStorage + await Promise.all([ + invokeExpress({ + method: "GET", + rawUrl: `/users/8675309?token=${SENTINEL}`, + headers: {}, + matchedRoutePath: "/users/:id", + }), + invokeExpress({ + method: "POST", + rawUrl: "/orders/99?debug=1", + baseUrl: "/api", + headers: { authorization: `Bearer ${SENTINEL}` }, + matchedRoutePath: "/orders/:orderId", + }), + ]); + + const events = collector.snapshot(); + const serialized = JSON.stringify(events); + assert.equal(serialized.includes(SENTINEL), false); + assert.equal(serialized.includes("8675309"), false); + + const session = events.find((e) => e.type === "session"); + assert.deepEqual(session.routes_seen, { + "GET /users/{id}": 1, + "POST /api/orders/{orderId}": 1, + }); + + const hits = events.filter((e) => e.type === "hit"); + const anon = hits.find((h) => h.route === "GET /users/{id}"); + const authed = hits.find((h) => h.route === "POST /api/orders/{orderId}"); + assert.equal(anon.auth, "anonymous"); + assert.equal(authed.auth, "authenticated"); + }); + + it("extracts Fastify routeOptions.url and session cookie auth cleanly", () => { + const collector = new NodeHitCollector(); + const hooks = {}; + const fakeFastify = { + addHook(name, fn) { + hooks[name] = fn; + }, + }; + fastifyPlugin(fakeFastify, { collector }, () => {}); + + const request = { + method: "POST", + url: "/items/42?secret=abc", + routeOptions: { method: "POST", url: "/items/:itemId" }, + headers: { cookie: "theme=dark; sessionid=secret-cookie-value" }, + }; + hooks.onRequest(request, {}, () => { + collector.recordHit("fp-fastify-1", "lodash.template"); + }); + hooks.onResponse(request, {}, () => {}); + + const events = collector.snapshot(); + const hit = events.find((e) => e.type === "hit"); + assert.equal(hit.route, "POST /items/{itemId}"); + assert.equal(hit.auth, "authenticated"); + assert.equal(JSON.stringify(events).includes("secret-cookie-value"), false); + }); + + it("tags background jobs with job: outside HTTP requests", () => { + const collector = new NodeHitCollector(); + assert.deepEqual(getContext(), { route: "unknown", auth: "unknown" }); + runWithJob("nightly-sync", () => { + collector.recordHit("fp-job", "tar.extract"); + }); + const hit = collector.snapshot().find((e) => e.type === "hit"); + assert.equal(hit.route, "job:nightly-sync"); + assert.equal(hit.auth, undefined); + }); +}); diff --git a/src/secfoo/runtime/evidence.py b/src/secfoo/runtime/evidence.py index 02200b2..46dd4e7 100644 --- a/src/secfoo/runtime/evidence.py +++ b/src/secfoo/runtime/evidence.py @@ -42,7 +42,7 @@ LANGUAGES = frozenset({"python", "node", "jvm", "dotnet", "go", "rust", "ruby", "php", "native"}) SOURCES = frozenset({"sensor", "coverage"}) -AUTH_STATES = frozenset({"anonymous", "authenticated"}) +AUTH_STATES = frozenset({"anonymous", "authenticated", "unknown"}) MAX_LINE_BYTES = 64 * 1024 MAX_TEXT = 1024 @@ -129,6 +129,24 @@ def _frame(value: object, key: str) -> str: return value +def _routes_seen(value: object) -> dict[str, int] | None: + if value is None: + return None + if not isinstance(value, dict): + raise EvidenceError("'routes_seen' must be an object mapping route templates to counts") + cleaned: dict[str, int] = {} + for raw_route, raw_count in value.items(): + if not isinstance(raw_route, str) or not raw_route.strip() or len(raw_route) > MAX_TEXT: + raise EvidenceError("'routes_seen' keys must be non-empty route templates") + _require_utf8(raw_route, "routes_seen") + if _CONCRETE_URL_RE.search(raw_route): + raise EvidenceError("'routes_seen' keys must be templates like 'GET /users/{id}', not concrete URLs") + if isinstance(raw_count, bool) or not isinstance(raw_count, int) or raw_count < 1 or raw_count > MAX_COUNT: + raise EvidenceError(f"'routes_seen' counts must be integers between 1 and {MAX_COUNT}") + cleaned[raw_route] = raw_count + return cleaned + + def validate_event(event: object) -> dict: """The stored fields of one event, or EvidenceError. Unknown fields are dropped here, so nothing outside the contract can reach the database.""" @@ -160,6 +178,7 @@ def validate_event(event: object) -> dict: "ended_at": _timestamp(event, "ended_at"), "app_functions_total": total, "app_functions_executed": executed, + "routes_seen": _routes_seen(event.get("routes_seen")), } if kind == "load": return { @@ -177,7 +196,7 @@ def validate_event(event: object) -> dict: raise EvidenceError("'route' must be a template like 'POST /upload', not a concrete URL") auth = _text(event, "auth") if auth is not None and auth not in AUTH_STATES: - raise EvidenceError("'auth' must be 'anonymous' or 'authenticated'") + raise EvidenceError("'auth' must be 'anonymous', 'authenticated' or 'unknown'") stack = event.get("stack_sample") if stack is not None: if not isinstance(stack, list) or len(stack) > MAX_STACK_FRAMES: @@ -243,23 +262,27 @@ def _session_id(conn: sqlite3.Connection, project_id: int, session_uuid: str) -> def _store_session(conn: sqlite3.Connection, project_id: int, event: dict) -> int: + routes_seen = event.get("routes_seen") + routes_seen_json = json.dumps(routes_seen, sort_keys=True) if routes_seen else None conn.execute( """ INSERT INTO runtime_sessions ( project_id, session_uuid, language, runtime, source, app, env, instance, sensor_version, - started_at, ended_at, app_functions_total, app_functions_executed, ingested_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + started_at, ended_at, app_functions_total, app_functions_executed, routes_seen_json, ingested_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (project_id, session_uuid) DO UPDATE SET language = excluded.language, runtime = excluded.runtime, source = excluded.source, app = excluded.app, env = excluded.env, instance = excluded.instance, sensor_version = excluded.sensor_version, started_at = excluded.started_at, ended_at = excluded.ended_at, app_functions_total = excluded.app_functions_total, - app_functions_executed = excluded.app_functions_executed, ingested_at = excluded.ingested_at + app_functions_executed = excluded.app_functions_executed, + routes_seen_json = COALESCE(excluded.routes_seen_json, runtime_sessions.routes_seen_json), + ingested_at = excluded.ingested_at """, ( project_id, event["id"], event["language"], event["runtime"], event["source"], event["app"], event["env"], event["instance"], event["sensor_version"], event["started_at"], event["ended_at"], - event["app_functions_total"], event["app_functions_executed"], _now(), + event["app_functions_total"], event["app_functions_executed"], routes_seen_json, _now(), ), ) session_id = _session_id(conn, project_id, event["id"]) @@ -300,8 +323,16 @@ def _store_hit(conn: sqlite3.Connection, project_id: int, session_id: int, event stack_sample = COALESCE(excluded.stack_sample, runtime_evidence.stack_sample) """, ( - project_id, session_id, event["finding_fingerprint"], event["symbol"], event["route"], event["auth"], - event["count"], event["first_seen"], event["last_seen"], event["entry_frame"], + project_id, + session_id, + event["finding_fingerprint"], + event["symbol"], + event["route"], + None if event["auth"] in (None, "unknown") else event["auth"], + event["count"], + event["first_seen"], + event["last_seen"], + event["entry_frame"], None if event["stack_sample"] is None else json.dumps(event["stack_sample"]), ), ) diff --git a/src/secfoo/runtime/evidence.schema.json b/src/secfoo/runtime/evidence.schema.json index 6e9aa5b..6d8cc7c 100644 --- a/src/secfoo/runtime/evidence.schema.json +++ b/src/secfoo/runtime/evidence.schema.json @@ -33,7 +33,12 @@ "started_at": {"$ref": "#/$defs/timestamp"}, "ended_at": {"$ref": "#/$defs/timestamp"}, "app_functions_total": {"type": "integer", "minimum": 0}, - "app_functions_executed": {"type": "integer", "minimum": 0} + "app_functions_executed": {"type": "integer", "minimum": 0}, + "routes_seen": { + "description": "Requests counted per sanitized route template during this session (#69).", + "type": "object", + "additionalProperties": {"type": "integer", "minimum": 1} + } } }, "load": { @@ -62,7 +67,7 @@ "type": "string", "minLength": 1, "maxLength": 1024, "pattern": "^[^?#]*$", "not": {"pattern": "://"} }, - "auth": {"enum": ["anonymous", "authenticated"]}, + "auth": {"enum": ["anonymous", "authenticated", "unknown"]}, "count": {"type": "integer", "minimum": 1, "description": "The session's running total for this (fingerprint, symbol, route)."}, "first_seen": {"$ref": "#/$defs/timestamp"}, "last_seen": {"$ref": "#/$defs/timestamp"}, diff --git a/src/secfoo/sensor/__init__.py b/src/secfoo/sensor/__init__.py index e07b81b..29be556 100644 --- a/src/secfoo/sensor/__init__.py +++ b/src/secfoo/sensor/__init__.py @@ -13,6 +13,27 @@ import os import sys +from secfoo.sensor.context import ( + SecfooASGIMiddleware, + SecfooDjangoMiddleware, + SecfooWSGIMiddleware, + install_flask, + job_context, + request_context, +) + +__all__ = [ + "SecfooASGIMiddleware", + "SecfooDjangoMiddleware", + "SecfooWSGIMiddleware", + "current_probe", + "enabled", + "install_flask", + "job_context", + "request_context", + "start_from_env", +] + _probe = None diff --git a/src/secfoo/sensor/context.py b/src/secfoo/sensor/context.py new file mode 100644 index 0000000..a3782ac --- /dev/null +++ b/src/secfoo/sensor/context.py @@ -0,0 +1,451 @@ +"""Request, job, and auth attribution for the Python runtime probe (#69). + +Uses `contextvars.ContextVar` so async tasks and sync threads each keep their own +request context with negligible per-call overhead. Strictly observes privacy: +never reads or records concrete paths, query strings, header/cookie values, +client IPs, user IDs, or request bodies. +""" + +from __future__ import annotations + +import contextvars +import re +import sys +from collections.abc import Callable, Iterable, Mapping +from contextlib import contextmanager +from dataclasses import dataclass + +_HTTP_METHODS = frozenset({"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "TRACE"}) +_AUTH_HEADER = b"authorization" +_COOKIE_HEADER = b"cookie" +# Presence of these session-like cookie names implies an authenticated browser session. +# Cookie values themselves are never stored or logged. +_SESSION_COOKIE_NAMES = frozenset( + { + "session", + "sessionid", + "session_id", + "sid", + "connect.sid", + "phpsessid", + "jsessionid", + "auth", + "auth_token", + "access_token", + "jwt", + "_session", + } +) +_ANGLE_PARAM_RE = re.compile(r"<(?:[A-Za-z_]\w*:)?([A-Za-z_]\w*)>") +_UNSAFE_ROUTE_RE = re.compile(r"://|[?#\r\n\t]") +_JOB_SAFE_RE = re.compile(r"[^A-Za-z0-9._:/-]+") + +FRAMEWORK_HOOK_MODULES = frozenset( + { + "starlette.applications", + "flask.app", + "django.core.handlers.base", + } +) + + +@dataclass +class _RequestState: + route: str = "unknown" + auth: str = "unknown" + resolver: Callable[[], tuple[str, str]] | None = None + resolved: bool = False + + +_current: contextvars.ContextVar[_RequestState | None] = contextvars.ContextVar( + "secfoo_request_context", default=None +) +_route_counter: Callable[[str], None] | None = None + + +def set_route_recorder(recorder: Callable[[str], None] | None) -> None: + """Register the active probe callback used to count distinct requests per route template.""" + global _route_counter + _route_counter = recorder + + +def _record_route(route: str) -> None: + recorder = _route_counter + if recorder is not None and route and route not in {"unknown", "startup"} and not route.startswith("job:"): + recorder(route) + + +def _norm_method(method: str | None) -> str: + if not isinstance(method, str): + return "" + up = method.strip().upper() + return up if up in _HTTP_METHODS else "" + + +def sanitize_route_template(method: str | None, template: str | None) -> str: + """Build a safe `"METHOD /template"` string or `"unknown"` when no template is available. + + Normalizes Flask/Django `` converters to `{id}` and rejects concrete URL + artifacts (`://`, `?`, `#`, whitespace, or excessively long paths). + """ + if not isinstance(template, str): + return "unknown" + raw = template.strip() + if not raw or len(raw) > 512 or _UNSAFE_ROUTE_RE.search(raw): + return "unknown" + normalized = _ANGLE_PARAM_RE.sub(r"{\1}", raw) + if not normalized.startswith("/"): + normalized = "/" + normalized.lstrip("/") + if normalized != "/" and normalized.endswith("/"): + normalized = normalized.rstrip("/") + if " " in normalized: + return "unknown" + verb = _norm_method(method) + return f"{verb} {normalized}" if verb else normalized + + +def _cookie_names_from_header(raw_cookie: bytes | str) -> set[str]: + text = raw_cookie.decode("latin-1", errors="ignore") if isinstance(raw_cookie, (bytes, bytearray)) else str(raw_cookie) + names: set[str] = set() + for part in text.split(";"): + name, sep, val = part.partition("=") + if sep and val.strip(): + cleaned = name.strip().lower() + if cleaned: + names.add(cleaned) + return names + + +def _has_session_cookie_name(names: Iterable[str]) -> bool: + for name in names: + low = str(name).strip().lower() + if low in _SESSION_COOKIE_NAMES or "session" in low: + return True + return False + + +def detect_auth_state( + *, + framework_authenticated: bool | None = None, + headers: Iterable[tuple[bytes | str, bytes | str]] | Mapping[str, str] | None = None, + cookie_names: Iterable[str] | None = None, + has_authorization: bool | None = None, +) -> str: + """Classify request auth as `"authenticated"`, `"anonymous"`, or `"unknown"`. + + Never inspects or persists bearer tokens, session values, claims, or user IDs. + """ + if framework_authenticated is True: + return "authenticated" + + auth_seen = bool(has_authorization) + session_cookie_seen = _has_session_cookie_name(cookie_names) if cookie_names else False + + if headers is not None and not (auth_seen and session_cookie_seen): + items = headers.items() if isinstance(headers, Mapping) else headers + for k, v in items: + key = k.lower() if isinstance(k, bytes) else str(k).lower().encode("latin-1", errors="ignore") + val_nonempty = bool(v.strip() if isinstance(v, (bytes, bytearray, str)) else v) + if key == _AUTH_HEADER and val_nonempty: + auth_seen = True + break + if ( + key == _COOKIE_HEADER + and val_nonempty + and _has_session_cookie_name(_cookie_names_from_header(v)) + ): + session_cookie_seen = True + + if auth_seen or session_cookie_seen: + return "authenticated" + if framework_authenticated is False or headers is not None or cookie_names is not None or has_authorization is not None: + return "anonymous" + return "unknown" + + +def resolve_hit_context(*, default_route: str = "unknown") -> tuple[str, str]: + """Return `(route, auth)` for the active Task/thread without raising.""" + state = _current.get() + if state is None: + return default_route, "unknown" + if not state.resolved and state.resolver is not None: + route, auth = state.resolver() + state.route = route + state.auth = auth + if route != "unknown": + state.resolved = True + return state.route, state.auth + + +@contextmanager +def request_context( + route: str = "unknown", + auth: str | None = None, + *, + resolver: Callable[[], tuple[str, str]] | None = None, +): + """Attach an HTTP request's sanitized template and auth posture cleanly via ContextVar.""" + safe_route = route if route in {"unknown", "startup"} or route.startswith("job:") else _clean_preformatted(route) + safe_auth = auth if auth in {"anonymous", "authenticated", "unknown"} else "unknown" + state = _RequestState(route=safe_route, auth=safe_auth, resolver=resolver, resolved=resolver is None) + token = _current.set(state) + try: + yield state + finally: + try: + final_route, _ = resolve_hit_context() + _record_route(final_route) + finally: + _current.reset(token) + + +def _clean_preformatted(route: str) -> str: + method, _, rest = route.strip().partition(" ") + if not rest and method.startswith("/"): + return sanitize_route_template(None, method) + if rest: + return sanitize_route_template(method, rest) + return "unknown" + + +@contextmanager +def job_context(name: str): + """Mark background / scheduled execution context cleanly as `job:`.""" + cleaned = _JOB_SAFE_RE.sub("-", (name or "").strip()).strip("-/") or "unknown" + state = _RequestState(route=f"job:{cleaned[:200]}", auth="unknown", resolved=True) + token = _current.set(state) + try: + yield state + finally: + _current.reset(token) + + +def _starlette_route_template(scope: Mapping[str, object]) -> str: + route_obj = scope.get("route") + if route_obj is None: + return "unknown" + pattern = getattr(route_obj, "path_format", None) or getattr(route_obj, "path", None) + if not isinstance(pattern, str) or not pattern: + return "unknown" + root_path = scope.get("root_path") + if isinstance(root_path, str) and root_path and not pattern.startswith(root_path): + pattern = root_path.rstrip("/") + "/" + pattern.lstrip("/") + return sanitize_route_template(scope.get("method"), pattern) # type: ignore[arg-type] + + +def _starlette_auth(scope: Mapping[str, object]) -> str: + user = scope.get("user") + framework_auth: bool | None = None + if user is not None: + is_auth = getattr(user, "is_authenticated", None) + if isinstance(is_auth, bool): + framework_auth = is_auth + return detect_auth_state(framework_authenticated=framework_auth, headers=scope.get("headers")) # type: ignore[arg-type] + + +class SecfooASGIMiddleware: + """ASGI middleware capturing route template and auth state for FastAPI/Starlette.""" + + def __init__(self, app) -> None: + self.app = app + + async def __call__(self, scope, receive, send): + if scope.get("type") != "http": + return await self.app(scope, receive, send) + state = _RequestState( + resolver=lambda: (_starlette_route_template(scope), _starlette_auth(scope)), + resolved=False, + ) + token = _current.set(state) + try: + return await self.app(scope, receive, send) + finally: + try: + if _route_counter is not None: + final_route = state.route if state.resolved else _starlette_route_template(scope) + _record_route(final_route) + finally: + _current.reset(token) + + +class SecfooWSGIMiddleware: + """WSGI middleware tagging requests using matched templates (or custom extractor, else `"unknown"`).""" + + def __init__( + self, + app, + *, + route_extractor: Callable[[Mapping[str, object]], str | None] | None = None, + auth_extractor: Callable[[Mapping[str, object]], bool | None] | None = None, + ) -> None: + self.app = app + self._route_extractor = route_extractor + self._auth_extractor = auth_extractor + + def __call__(self, environ, start_response): + def _resolve() -> tuple[str, str]: + method = environ.get("REQUEST_METHOD") + template = self._route_extractor(environ) if self._route_extractor is not None else None + route = sanitize_route_template(method, template) + fw_auth = self._auth_extractor(environ) if self._auth_extractor is not None else None + auth_hdr = environ.get("HTTP_AUTHORIZATION") + cookie_hdr = environ.get("HTTP_COOKIE") + hdrs: list[tuple[bytes, bytes]] = [] + if auth_hdr: + hdrs.append((_AUTH_HEADER, b"present")) + if cookie_hdr: + hdrs.append((_COOKIE_HEADER, cookie_hdr.encode("latin-1", errors="ignore"))) + return route, detect_auth_state(framework_authenticated=fw_auth, headers=hdrs) + + with request_context(resolver=_resolve): + return self.app(environ, start_response) + + +def _flask_extract_route(request_obj) -> str | None: + rule = getattr(request_obj, "url_rule", None) + return getattr(rule, "rule", None) if rule is not None else None + + +def _flask_extract_auth(environ: Mapping[str, object]) -> bool | None: + try: + flask_login = sys.modules.get("flask_login") + if flask_login is not None: + current_user = getattr(flask_login, "current_user", None) + if current_user is not None: + is_auth = getattr(current_user, "is_authenticated", None) + if isinstance(is_auth, bool): + return is_auth + except Exception: # noqa: BLE001, S110 # nosec B110 -- fail-open auth helper + pass + return None + + +def install_flask(app) -> None: + """Wrap a Flask `app` cleanly (idempotent) to attribute hits via `request.url_rule`.""" + if getattr(app, "_secfoo_wrapped", False): + return + orig_wsgi = app.wsgi_app + + def _wrapped_wsgi(environ, start_response): + def _route_getter(_env: Mapping[str, object]) -> str | None: + flask_mod = sys.modules.get("flask") + req = getattr(flask_mod, "request", None) if flask_mod is not None else None + return _flask_extract_route(req) if req is not None else None + + mw = SecfooWSGIMiddleware(orig_wsgi, route_extractor=_route_getter, auth_extractor=_flask_extract_auth) + return mw(environ, start_response) + + app.wsgi_app = _wrapped_wsgi + app._secfoo_wrapped = True + + +def _django_extract(request) -> tuple[str, str]: + resolver_match = getattr(request, "resolver_match", None) + pattern = getattr(resolver_match, "route", None) if resolver_match is not None else None + route = sanitize_route_template(getattr(request, "method", None), pattern) + user = getattr(request, "user", None) + fw_auth: bool | None = None + if user is not None: + is_auth = getattr(user, "is_authenticated", None) + if isinstance(is_auth, bool): + fw_auth = is_auth + meta = getattr(request, "META", {}) or {} + cookies = getattr(request, "COOKIES", {}) or {} + cookie_names = list(cookies.keys()) if isinstance(cookies, Mapping) else [] + auth = detect_auth_state( + framework_authenticated=fw_auth, + cookie_names=cookie_names, + has_authorization=bool(meta.get("HTTP_AUTHORIZATION")), + ) + return route, auth + + +class SecfooDjangoMiddleware: + """Django middleware tagging requests via `request.resolver_match.route` and `request.user`.""" + + def __init__(self, get_response) -> None: + self.get_response = get_response + + def __call__(self, request): + with request_context(resolver=lambda: _django_extract(request)): + return self.get_response(request) + + +def install_framework_hooks(module_name: str | None = None) -> None: + """Idempotently attach zero-code request attribution hooks to imported web frameworks.""" + targets = (module_name,) if module_name else tuple(FRAMEWORK_HOOK_MODULES) + for name in targets: + try: + if name == "starlette.applications" and "starlette.applications" in sys.modules: + _patch_starlette(sys.modules["starlette.applications"]) + elif name == "flask.app" and "flask.app" in sys.modules: + _patch_flask(sys.modules["flask.app"]) + elif name == "django.core.handlers.base" and "django.core.handlers.base" in sys.modules: + _patch_django(sys.modules["django.core.handlers.base"]) + except Exception: # noqa: BLE001, S110 # nosec B110 -- never break framework imports + pass + + +def _patch_starlette(module) -> None: + starlette_cls = getattr(module, "Starlette", None) + if starlette_cls is None or getattr(starlette_cls, "_secfoo_hooked", False): + return + orig_call = starlette_cls.__call__ + + async def _secfoo_asgi_call(self, scope, receive, send): + if scope.get("type") != "http": + return await orig_call(self, scope, receive, send) + state = _RequestState( + resolver=lambda: (_starlette_route_template(scope), _starlette_auth(scope)), + resolved=False, + ) + token = _current.set(state) + try: + return await orig_call(self, scope, receive, send) + finally: + try: + if _route_counter is not None: + final_route = state.route if state.resolved else _starlette_route_template(scope) + _record_route(final_route) + finally: + _current.reset(token) + + starlette_cls.__call__ = _secfoo_asgi_call + starlette_cls._secfoo_hooked = True + + +def _patch_flask(module) -> None: + flask_cls = getattr(module, "Flask", None) + if flask_cls is None or getattr(flask_cls, "_secfoo_hooked", False): + return + orig_wsgi_app = flask_cls.wsgi_app + + def _secfoo_flask_wsgi(self, environ, start_response): + def _route_getter(_env: Mapping[str, object]) -> str | None: + flask_mod = sys.modules.get("flask") + req = getattr(flask_mod, "request", None) if flask_mod is not None else None + return _flask_extract_route(req) if req is not None else None + + mw = SecfooWSGIMiddleware( + lambda e, sr: orig_wsgi_app(self, e, sr), + route_extractor=_route_getter, + auth_extractor=_flask_extract_auth, + ) + return mw(environ, start_response) + + flask_cls.wsgi_app = _secfoo_flask_wsgi + flask_cls._secfoo_hooked = True + + +def _patch_django(module) -> None: + handler_cls = getattr(module, "BaseHandler", None) + if handler_cls is None or getattr(handler_cls, "_secfoo_hooked", False): + return + orig_get_response = handler_cls._get_response + + def _secfoo_django_get_response(self, request): + with request_context(resolver=lambda: _django_extract(request)): + return orig_get_response(self, request) + + handler_cls._get_response = _secfoo_django_get_response + handler_cls._secfoo_hooked = True diff --git a/src/secfoo/sensor/probe.py b/src/secfoo/sensor/probe.py index 8351b1e..313496c 100644 --- a/src/secfoo/sensor/probe.py +++ b/src/secfoo/sensor/probe.py @@ -33,6 +33,13 @@ from datetime import datetime, timezone from pathlib import Path +from secfoo.sensor.context import ( + FRAMEWORK_HOOK_MODULES, + install_framework_hooks, + resolve_hit_context, + set_route_recorder, +) + PROBE_VERSION = "0.1.0" DEFAULT_FLUSH_SECONDS = 10.0 WATCHLIST_RECHECK_SECONDS = 30.0 @@ -101,13 +108,23 @@ def __init__(self, *, watchlist_path: str | None, transport, app_root: str | Non def _reset_session(self) -> None: self.session_id = str(uuid.uuid4()) self.started_at = _now() - self._hits: dict[tuple, dict] = {} # (fingerprint, symbol) -> aggregate + self._hits: dict[tuple, list] = {} # (fingerprint, symbol, route, auth) -> aggregate + self._routes_seen: dict[str, int] = {} self._seen_app_code = set() self.dropped = 0 + def record_route(self, route: str) -> None: + """Increment request counter for a sanitized route template.""" + if not self._active or self._broken: + return + with self._lock: + self._routes_seen[route] = self._routes_seen.get(route, 0) + 1 + def start(self) -> None: try: self._load_watchlist(force=True) + install_framework_hooks() + set_route_recorder(self.record_route) if self.backend == "monitoring": self._start_monitoring() else: @@ -146,6 +163,7 @@ def stop(self) -> None: if was_active and locked and not self._broken: self._flush_now() self._active = False + set_route_recorder(None) try: if self._watcher is not None: if self._watcher in sys.meta_path: @@ -306,16 +324,18 @@ def _is_app_code(self, filename: str) -> bool: return path.startswith(self.app_root) and not path.startswith(self._excluded_dirs) def _record_hit(self, code, watched) -> None: - """The hot path: one dict lookup and two stores per watched call. + """The hot path: ContextVar lookup + dict increment per watched call. Timestamps stay raw floats until flush. No lock: under the GIL a lost increment between threads is possible but rare, and a running total that's off by one is an acceptable price for not serialising the app's threads on every call.""" symbol, fingerprints = watched + route, auth = resolve_hit_context(default_route="unknown") now = time.time() hits = self._hits for fingerprint in fingerprints: - agg = hits.get((fingerprint, symbol)) + key = (fingerprint, symbol, route, auth) + agg = hits.get(key) if agg is not None: agg[0] += 1 agg[2] = now @@ -324,7 +344,7 @@ def _record_hit(self, code, watched) -> None: # stack[0] is the watched function itself; the entry frame is the # app code that called it. [count, first_seen, last_seen, stack, entry] with self._lock: - hits.setdefault((fingerprint, symbol), [1, now, now, stack, stack[1] if len(stack) > 1 else None]) + hits.setdefault(key, [1, now, now, stack, stack[1] if len(stack) > 1 else None]) def _stack_sample(self) -> list[str]: """file:line of app frames only (plus nothing else): no locals, no args.""" @@ -344,6 +364,7 @@ def snapshot(self) -> list[dict]: """The session's running totals as #53 events.""" with self._lock: hits = {k: list(v) for k, v in self._hits.items()} + routes_seen = dict(sorted(self._routes_seen.items())) executed = len(self._seen_app_code) session = { "type": "session", "id": self.session_id, "language": "python", @@ -351,16 +372,20 @@ def snapshot(self) -> list[dict]: "started_at": self.started_at, "ended_at": _now(), "sensor_version": PROBE_VERSION, "instance": os.environ.get("HOSTNAME") or os.environ.get("COMPUTERNAME") or None, } + if routes_seen: + session["routes_seen"] = routes_seen if self.backend == "monitoring": total = _count_app_functions(self) session["app_functions_total"] = max(total, executed) session["app_functions_executed"] = executed session = {k: v for k, v in session.items() if v is not None} events = [session, *self._loads()] - for (fingerprint, symbol), (count, first, last, stack, entry) in sorted(hits.items()): + for (fingerprint, symbol, route, auth), (count, first, last, stack, entry) in sorted(hits.items()): hit = {"type": "hit", "session": self.session_id, "finding_fingerprint": fingerprint, - "symbol": symbol, "route": "unknown", "count": count, "first_seen": _iso(first), + "symbol": symbol, "route": route, "count": count, "first_seen": _iso(first), "last_seen": _iso(last), "stack_sample": stack, "entry_frame": entry} + if auth in {"anonymous", "authenticated"}: + hit["auth"] = auth events.append({k: v for k, v in hit.items() if v not in (None, [])}) return events @@ -514,9 +539,10 @@ def __init__(self, probe: Probe) -> None: self._busy = threading.local() def find_spec(self, fullname, path=None, target=None): - if getattr(self._busy, "on", False) or not self.probe._pending_symbols: + is_fw = fullname in FRAMEWORK_HOOK_MODULES + if getattr(self._busy, "on", False) or (not is_fw and not self.probe._pending_symbols): return None - if not any(s == fullname or s.startswith(fullname + ".") for s in self.probe._pending_symbols): + if not is_fw and not any(s == fullname or s.startswith(fullname + ".") for s in self.probe._pending_symbols): return None self._busy.on = True try: @@ -535,7 +561,10 @@ def find_spec(self, fullname, path=None, target=None): def exec_module(module): original(module) try: - probe._resolve_pending() + if is_fw: + install_framework_hooks(fullname) + else: + probe._resolve_pending() except Exception as exc: # noqa: BLE001 probe._disable(exc) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 59cd087..a441896 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -125,6 +125,10 @@ def use_db_path(path: Path): "locations": "ALTER TABLE secret_findings ADD COLUMN locations TEXT", } +_RUNTIME_SESSIONS_MIGRATIONS = { + "routes_seen_json": "ALTER TABLE runtime_sessions ADD COLUMN routes_seen_json TEXT", +} + SAST_REVIEW_STATUSES = ("confirmed", "false_positive", "accepted_risk") # Skill id -> its per-finding lifecycle table. Every one of these tables @@ -229,6 +233,12 @@ def _migrate(self) -> None: for column, ddl in _SECRET_FINDINGS_MIGRATIONS.items(): if column not in existing_secret_cols: self._add_column(ddl) + existing_session_cols = { + row["name"] for row in self._conn.execute("PRAGMA table_info(runtime_sessions)").fetchall() + } + for column, ddl in _RUNTIME_SESSIONS_MIGRATIONS.items(): + if column not in existing_session_cols: + self._add_column(ddl) self._conn.commit() self._backfill_locations() self._backfill_responsible_ai_ratings() diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 35d4786..3b2c702 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -407,6 +407,7 @@ CREATE TABLE IF NOT EXISTS runtime_sessions ( ended_at TEXT, app_functions_total INTEGER, -- with _executed, the coverage behind any "not observed" app_functions_executed INTEGER, + routes_seen_json TEXT, -- JSON map of sanitized route template -> request count (#69) ingested_at TEXT NOT NULL, UNIQUE (project_id, session_uuid) ); diff --git a/src/secfoo/web/sca_runtime.py b/src/secfoo/web/sca_runtime.py index c6c5e2e..3be47a8 100644 --- a/src/secfoo/web/sca_runtime.py +++ b/src/secfoo/web/sca_runtime.py @@ -62,6 +62,7 @@ class Coverage: functions_total: int = 0 functions_executed: int = 0 observed_hours: float = 0.0 + routes_seen_total: int = 0 @property def percent(self) -> int | None: @@ -106,7 +107,9 @@ def summary(self) -> str: top = self.routes[0] more = f" +{len(self.routes) - 1} more" if len(self.routes) > 1 else "" auth = f" ({top['auth']})" if top["auth"] else "" - return f"Reached · {top['route']}{auth} · {top['count']:,}{more}" + total_routes = max(cov.routes_seen_total, len(self.routes)) if cov.routes_seen_total else 0 + routes_note = f" · reached on {len(self.routes)} of {total_routes} routes seen" if total_routes else "" + return f"Reached · {top['route']}{auth} · {top['count']:,}{more}{routes_note}" if self.state == "executed": return f"Executed · {self.hits:,} hits" + (f" · last {self.last_seen[:10]}" if self.last_seen else "") if self.state == "loaded": @@ -119,23 +122,34 @@ def summary(self) -> str: def _coverage(conn, project_id: int) -> tuple[Coverage, list[str], bool]: rows = conn.execute( - "SELECT source, started_at, ended_at, app_functions_total, app_functions_executed, " + "SELECT source, started_at, ended_at, app_functions_total, app_functions_executed, routes_seen_json, " "EXISTS (SELECT 1 FROM runtime_packages p WHERE p.session_id = s.id) AS has_inventory " "FROM runtime_sessions s WHERE project_id = ?", (project_id,), ).fetchall() cov = Coverage(sessions=len(rows)) sources: set[str] = set() + distinct_routes: set[str] = set() has_inventory = False - for source, started, ended, total, executed, inventory in rows: + for source, started, ended, total, executed, routes_seen_json, inventory in rows: sources.add(source) has_inventory = has_inventory or bool(inventory) if total and executed is not None: cov.functions_total += total cov.functions_executed += executed + if routes_seen_json: + try: + parsed_routes = json.loads(routes_seen_json) + if isinstance(parsed_routes, dict): + distinct_routes.update(str(k) for k in parsed_routes) + except ValueError: + # A corrupt routes_seen_json only loses the "of N routes seen" + # note; coverage from the other columns still renders. + pass start, end = _parse(started), _parse(ended) if start and end and end > start: cov.observed_hours += (end - start).total_seconds() / 3600 + cov.routes_seen_total = len(distinct_routes) return cov, sorted(sources), has_inventory diff --git a/tests/test_runtime/test_evidence.py b/tests/test_runtime/test_evidence.py index 4cb7601..2af0d0f 100644 --- a/tests/test_runtime/test_evidence.py +++ b/tests/test_runtime/test_evidence.py @@ -82,6 +82,18 @@ def test_valid_file_stores_session_load_and_hit(repo, project_id): assert json.loads(hit["stack_sample"]) == HIT_LINE["stack_sample"] +def test_session_routes_seen_stored_and_validated(repo, project_id): + line = {**SESSION_LINE, "routes_seen": {"POST /upload": 12, "GET /health": 41}} + report = ingest_events(repo.connection, project_id, _lines(line, HIT_LINE)) + assert report.skipped == [] + [session] = _rows(repo, "runtime_sessions") + assert json.loads(session["routes_seen_json"]) == {"GET /health": 41, "POST /upload": 12} + with pytest.raises(EvidenceError, match="routes_seen"): + validate_event({**SESSION_LINE, "routes_seen": {"GET /users/1?tok=secret": 1}}) + with pytest.raises(EvidenceError, match="routes_seen"): + validate_event({**SESSION_LINE, "routes_seen": {"GET /users/{id}": 0}}) + + def test_optional_fields_can_be_left_out(repo, project_id): minimal = _lines( {"type": "session", "id": "s1", "language": "node", "source": "coverage", "started_at": "2026-11-08T10:00:00"}, diff --git a/tests/test_sensor/test_route_auth_attribution.py b/tests/test_sensor/test_route_auth_attribution.py new file mode 100644 index 0000000..4c8f0bf --- /dev/null +++ b/tests/test_sensor/test_route_auth_attribution.py @@ -0,0 +1,365 @@ +"""#69: Attribute runtime hits to live traffic (route template, auth state, job context).""" +from __future__ import annotations + +import json +import shutil +import subprocess +import types +from pathlib import Path + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from secfoo.runtime.evidence import ingest_events, validate_event +from secfoo.runtime.protocol import FORBIDDEN_PATTERNS, SENTINEL +from secfoo.sensor.context import ( + SecfooASGIMiddleware, + SecfooDjangoMiddleware, + SecfooWSGIMiddleware, + detect_auth_state, + install_flask, + install_framework_hooks, + job_context, + request_context, + resolve_hit_context, + sanitize_route_template, +) +from secfoo.sensor.probe import Probe +from secfoo.storage.repository import RunRepository +from secfoo.web import sca_runtime + + +class _MemoryTransport: + def __init__(self) -> None: + self.batches: list[list[dict]] = [] + + def send(self, events: list[dict]) -> bool: + self.batches.append(events) + return True + + def close(self) -> None: + pass + + def reopen(self): + return self + + +def _make_watchlist(tmp_path: Path, *, module_name: str, func_name: str, fp: str = "fp-vuln-1") -> Path: + path = tmp_path / "watchlist.json" + path.write_text( + json.dumps( + { + "version": 1, + "generated_at": "2026-11-30T00:00:00Z", + "entries": [ + { + "finding_fingerprint": fp, + "advisory": "GHSA-test-69", + "ecosystem": "PyPI", + "package": "demo-vuln", + "version": "1.0.0", + "granularity": "symbol", + "symbols": [f"{module_name}.{func_name}"], + "source": "osv", + } + ], + } + ), + encoding="utf-8", + ) + return path + + +def test_sanitize_route_template_and_privacy(): + assert sanitize_route_template("get", "/users/{id}") == "GET /users/{id}" + assert sanitize_route_template("POST", "/users//") == "POST /users/{user_id}" + assert sanitize_route_template("GET", "users/") == "GET /users/{name}" + assert sanitize_route_template("GET", "/users/8675309?token=secret") == "unknown" + assert sanitize_route_template("GET", "https://example.com/users/1") == "unknown" + assert sanitize_route_template("GET", "/a#frag") == "unknown" + assert sanitize_route_template("GET", "/a b") == "unknown" + assert sanitize_route_template("GET", None) == "unknown" + + +def test_detect_auth_state_uses_presence_not_values(): + assert detect_auth_state(headers=[(b"authorization", b"Bearer secret")]) == "authenticated" + assert detect_auth_state(headers={"Cookie": "theme=dark; sessionid=abc123"}) == "authenticated" + assert detect_auth_state(headers={"Cookie": "theme=dark"}) == "anonymous" + assert detect_auth_state(framework_authenticated=True) == "authenticated" + assert detect_auth_state(framework_authenticated=False) == "anonymous" + assert detect_auth_state() == "unknown" + + +def test_fastapi_auto_hook_attributes_route_auth_jobs_and_no_privacy_leaks(tmp_path, monkeypatch): + mod = types.ModuleType("demo_fastapi_vuln_69") + + def sink(value: str) -> str: + return value.upper() + + mod.sink = sink + monkeypatch.setitem(__import__("sys").modules, "demo_fastapi_vuln_69", mod) + + app = FastAPI() + + @app.get("/users/{user_id}") + def read_user(user_id: str, token: str = ""): + return {"res": mod.sink(f"{user_id}:{token}")} + + @app.post("/orders/{order_id}") + def create_order(order_id: str): + return {"res": mod.sink(order_id)} + + @app.get("/health") + def health(): + return {"ok": True} + + watchlist = _make_watchlist(tmp_path, module_name="demo_fastapi_vuln_69", func_name="sink", fp="fp-fastapi-1") + transport = _MemoryTransport() + probe = Probe(watchlist_path=str(watchlist), transport=transport, app_root=str(tmp_path), flush_seconds=60.0) + probe.start() + try: + client = TestClient(app) + # Concrete ID + query secret + bearer secret must NEVER leak into evidence + r1 = client.get(f"/users/8675309?token={SENTINEL}") + assert r1.status_code == 200 + r2 = client.post("/orders/42", headers={"Authorization": f"Bearer {SENTINEL}"}) + assert r2.status_code == 200 + r3 = client.get("/health", headers={"Cookie": f"sessionid={SENTINEL}"}) + assert r3.status_code == 200 + + with job_context("nightly sync"): + mod.sink("background-job") + # Unmatched call outside any request -> unknown + mod.sink("cli-startup") + finally: + probe.stop() + + assert transport.batches + events = transport.batches[-1] + dumped = "\n".join(json.dumps(e) for e in events) + assert SENTINEL not in dumped + assert "8675309" not in dumped + for pat in FORBIDDEN_PATTERNS: + assert pat.search(dumped) is None + + for event in events: + validate_event(event) + + [session] = [e for e in events if e["type"] == "session"] + assert session["routes_seen"] == { + "GET /health": 1, + "GET /users/{user_id}": 1, + "POST /orders/{order_id}": 1, + } + + hits = {(h["route"], h.get("auth")): h["count"] for h in events if h.get("type") == "hit"} + assert hits[("GET /users/{user_id}", "anonymous")] == 1 + assert hits[("POST /orders/{order_id}", "authenticated")] == 1 + assert hits[("job:nightly-sync", None)] == 1 + assert hits[("unknown", None)] == 1 + + # End-to-end ingest + SCA runtime summary ('reached on X of Y routes seen') + db_path = tmp_path / "db.sqlite" + with RunRepository(db_path=db_path) as repo: + pid = repo.upsert_project("https://github.com/acme/demo", "demo", "github") + run_id = repo.get_run( + repo.create_run(project_id=pid, skill_id="sca-reachability", skill_name="SCA", agent_id="claude", confluence_urls=[]) + ).id + repo.upsert_sca_finding( + project_id=pid, + fingerprint="fp-fastapi-1", + run_id=run_id, + current_ref="D1", + package="demo-vuln", + severity="High", + version="1.0.0", + ecosystem="PyPI", + reachability="Not reachable", + ) + rep = ingest_events(repo.connection, pid, [json.dumps(e) for e in events]) + assert rep.skipped == [] + status = sca_runtime.status_for( + repo.connection, + project_id=pid, + fingerprint="fp-fastapi-1", + package="demo-vuln", + ecosystem="PyPI", + scanned_version="1.0.0", + ) + assert status.state == "reached" + assert status.coverage.routes_seen_total == 3 + assert "reached on 2 of 3 routes seen" in status.summary + + +def e_is_hit(event: dict) -> bool: + return event.get("type") == "hit" + + +def test_explicit_asgi_wsgi_flask_and_django_middlewares(monkeypatch): + # Flask WSGI adapter with rule template + fake_flask = types.SimpleNamespace( + request=types.SimpleNamespace(url_rule=types.SimpleNamespace(rule="/items/")) + ) + monkeypatch.setitem(__import__("sys").modules, "flask", fake_flask) + seen: list[tuple[str, str]] = [] + + class DummyFlaskApp: + def wsgi_app(self, environ, start_response): + seen.append(resolve_hit_context()) + start_response("200 OK", []) + return [b"ok"] + + flask_app = DummyFlaskApp() + install_flask(flask_app) + flask_app.wsgi_app( + { + "REQUEST_METHOD": "DELETE", + "PATH_INFO": "/items/999", + "QUERY_STRING": f"token={SENTINEL}", + "HTTP_COOKIE": f"session={SENTINEL}", + }, + lambda *_args: None, + ) + assert seen == [("DELETE /items/{item_id}", "authenticated")] + + # Generic WSGI middleware with unrouted request stays "unknown" (never leaks PATH_INFO) + seen.clear() + + def bare_wsgi(environ, start_response): + seen.append(resolve_hit_context()) + start_response("200 OK", []) + return [b"ok"] + + wrapped_wsgi = SecfooWSGIMiddleware(bare_wsgi) + wrapped_wsgi({"REQUEST_METHOD": "GET", "PATH_INFO": f"/secret/{SENTINEL}"}, lambda *_args: None) + assert seen == [("unknown", "anonymous")] + + # Django middleware reads resolver_match.route + user.is_authenticated + seen.clear() + django_mw = SecfooDjangoMiddleware(lambda req: seen.append(resolve_hit_context()) or "resp") + req_anon = types.SimpleNamespace( + method="GET", + path=f"/reports/8675309?x={SENTINEL}", + resolver_match=types.SimpleNamespace(route="reports//"), + user=types.SimpleNamespace(is_authenticated=False), + META={}, + COOKIES={}, + ) + django_mw(req_anon) + assert seen[-1] == ("GET /reports/{report_id}", "anonymous") + + +def test_node_async_local_storage_and_schema_compatibility(): + node = shutil.which("node") + if node is None: + pytest.skip("node binary not available") + pkg_dir = Path(__file__).resolve().parents[2] / "npm" / "secfoo-sensor" + proc = subprocess.run([node, "--test", "test/middleware.test.js"], cwd=pkg_dir, capture_output=True, text=True, check=False) + assert proc.returncode == 0, proc.stdout + "\n" + proc.stderr + + # Emit events from Node Express + Fastify hooks and validate every line with Python #53 validator + script = ( + "const { NodeHitCollector, expressMiddleware, runWithJob } = require('./index');\n" + "const c = new NodeHitCollector();\n" + "const mw = expressMiddleware(c);\n" + "const req = { method: 'GET', url: '/users/8675309?k=v', headers: { authorization: 'Bearer tok' }, route: { path: '/users/:id' } };\n" + "const res = { on(ev, cb) { if (ev === 'finish') cb(); } };\n" + "mw(req, res, () => { c.recordHit('conformance-fp', 'lodash.template'); });\n" + "runWithJob('export', () => c.recordHit('conformance-fp', 'lodash.template'));\n" + "console.log(JSON.stringify(c.snapshot()));\n" + ) + out = subprocess.run([node, "-e", script], cwd=pkg_dir, capture_output=True, text=True, check=True) + events = json.loads(out.stdout) + assert len(events) == 3 + for event in events: + validate_event(event) + assert any(e.get("route") == "GET /users/{id}" and e.get("auth") == "authenticated" for e in events) + assert any(e.get("route") == "job:export" for e in events) + + +def test_asgi_framework_patches_and_preformatted_contexts(monkeypatch): + import asyncio + import sys + + # Preformatted request_context variants + with request_context("POST /items/{id}", auth="authenticated"): + assert resolve_hit_context() == ("POST /items/{id}", "authenticated") + with request_context("/only-path"): + assert resolve_hit_context() == ("/only-path", "unknown") + with request_context("bad-no-slash"): + assert resolve_hit_context() == ("unknown", "unknown") + + # Explicit SecfooASGIMiddleware: non-HTTP passthrough, root_path prefix, user.is_authenticated + seen_asgi: list[tuple[str, str]] = [] + + async def inner_asgi(scope, _receive, _send): + seen_asgi.append(resolve_hit_context()) + + mw = SecfooASGIMiddleware(inner_asgi) + asyncio.run(mw({"type": "websocket"}, None, None)) + assert seen_asgi[-1] == ("unknown", "unknown") + + asyncio.run( + mw( + { + "type": "http", + "method": "PUT", + "root_path": "/v2", + "route": types.SimpleNamespace(path="/accounts/{id}"), + "user": types.SimpleNamespace(is_authenticated=True), + "headers": [], + }, + None, + None, + ) + ) + assert seen_asgi[-1] == ("PUT /v2/accounts/{id}", "authenticated") + + # Auto-hook patching for Flask (with flask_login + HTTP_AUTHORIZATION) & Django BaseHandler + fake_flask_app_mod = types.ModuleType("flask.app") + + class FakeFlask: + def wsgi_app(self, environ, start_response): + seen_asgi.append(resolve_hit_context()) + start_response("200 OK", []) + return [b"ok"] + + fake_flask_app_mod.Flask = FakeFlask + fake_flask_mod = types.ModuleType("flask") + fake_flask_mod.request = types.SimpleNamespace(url_rule=types.SimpleNamespace(rule="/v1/tokens")) + fake_flask_login = types.ModuleType("flask_login") + fake_flask_login.current_user = types.SimpleNamespace(is_authenticated=False) + monkeypatch.setitem(sys.modules, "flask.app", fake_flask_app_mod) + monkeypatch.setitem(sys.modules, "flask", fake_flask_mod) + monkeypatch.setitem(sys.modules, "flask_login", fake_flask_login) + + fake_django_mod = types.ModuleType("django.core.handlers.base") + + class FakeBaseHandler: + def _get_response(self, request): + seen_asgi.append(resolve_hit_context()) + return "ok" + + fake_django_mod.BaseHandler = FakeBaseHandler + monkeypatch.setitem(sys.modules, "django.core.handlers.base", fake_django_mod) + + install_framework_hooks("flask.app") + install_framework_hooks("django.core.handlers.base") + + FakeFlask().wsgi_app( + {"REQUEST_METHOD": "POST", "HTTP_AUTHORIZATION": f"Bearer {SENTINEL}"}, + lambda *_a: None, + ) + assert seen_asgi[-1] == ("POST /v1/tokens", "authenticated") + + FakeBaseHandler()._get_response( + types.SimpleNamespace( + method="GET", + resolver_match=types.SimpleNamespace(route="admin/users//"), + user=types.SimpleNamespace(is_authenticated=True), + META={}, + COOKIES={}, + ) + ) + assert seen_asgi[-1] == ("GET /admin/users/{id}", "authenticated")