siberfx / laravel-risk-analyzer
Security scanner for Laravel 12 & 13, and standalone for Symfony, Yii2 and plain PHP: AST taint analysis of your code, React/Vue/Angular frontend, Docker, CI and shell script checks, checks of the booted app's config and routes, OSV dependency advisories, baselines and SARIF output.
Requires
- php: ~8.4.0|~8.5.0|~8.6.0
- composer/semver: ^3.4
- guzzlehttp/guzzle: ^7.9|^8.0
- illuminate/config: ^12.0|^13.0
- illuminate/console: ^12.0|^13.0
- illuminate/container: ^12.0|^13.0
- illuminate/contracts: ^12.0|^13.0
- illuminate/http: ^12.0|^13.0
- illuminate/routing: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
- nikic/php-parser: ^5.4
- symfony/process: ^7.2|^8.0
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.20
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^4.0|^5.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Risk Analyzer finds security problems in a Laravel application: in its code (PHP, Blade, and React, Vue and Angular frontends), its Dockerfiles, compose files, scripts and CI workflows, its running configuration and routes, its dependencies and its files.
It does not grep source text. It parses your PHP and follows request input through your code (taint analysis), so it can tell these apart:
DB::select("select * from users where id = $id"); // $id = $request->input('id') → critical DB::select("select * from {$this->table()}"); // runtime value, not input → medium DB::select('select * from users where id = ?', [$id]); // bindings → not reported
It also runs without Laravel, on Symfony, Yii2 and plain PHP projects or a frontend or deploy repository, with vendor/bin/risk-analyzer. See Without Laravel.
Runtime rules check the booted application instead of reading .env files. They look at the merged config and the real route table with middleware groups expanded. Dependency advisories come from the OSV.dev database, read straight from your lock files (Composer, npm, Yarn, pnpm and Bun) and from what is actually installed in vendor/ and node_modules/. Support dates for PHP, Laravel and Node.js come from endoflife.date and php.net.
- 48 rules across code, frontend code, Docker/CI/scripts, configuration and routes, dependencies and filesystem
- Taint tracking through variables, string building, helpers, closures and loops, with sanitizers (
(int),escapeshellarg,basename,in_arrayallow-lists,validated()...) - Severity reflects reachability: user input reaching a sink ranks higher than a runtime value
- Inline suppressions with reasons:
// risk-analyzer-ignore sql-injection -- table name comes from an enum - Baselines to adopt it on an existing project and only gate new findings
--changedto scan only the files a branch touches- Frontend checks for React, Vue and Angular in
resources/js, or a separate SPA folder with--frontend=client --frontendand--infrastructureto scan only the frontend, or only Docker/CI/scripts- Dockerfile, Docker Compose, shell script, Makefile and GitHub Actions checks
- Console, JSON, SARIF (GitHub code scanning) and Markdown (PR comments / job summaries) output
- A
Report::assertClean()helper to run the scan inside your own test suite - A standalone
vendor/bin/risk-analyzerandStandalone::scan()for Symfony, Yii2 and plain PHP - Custom rules: an AST rule takes about 15 lines
Requirements
| Package | Version |
|---|---|
| PHP | 8.4, 8.5, 8.6 |
| Laravel | 12.x, 13.x |
PHP 8.6 is tested with Laravel 13. Laravel 12 allows PHP 8.6 too, but its test tooling (Testbench 10) can't be installed on PHP 8.6 yet, so that combination is not covered by CI.
These are the requirements for running the scanner. Without Laravel it can scan projects on any framework and any PHP version; see Without Laravel.
Installation
composer require --dev siberfx/laravel-risk-analyzer php artisan risk-analyzer:scan
Publish the config if you want to change paths, thresholds or rules:
php artisan vendor:publish --tag=risk-analyzer-config
Without Laravel (Symfony, Yii2, plain PHP)
vendor/bin/risk-analyzer scans a project without booting Laravel:
composer require --dev siberfx/laravel-risk-analyzer # when the project's dependencies allow it vendor/bin/risk-analyzer scan composer global require siberfx/laravel-risk-analyzer # otherwise: install it once, outside the project risk-analyzer scan --project=/path/to/project
It has the scan, baseline and rules commands with the same options as the artisan commands, plus --project (default: the current directory) and --config. The scanner needs PHP 8.4+, but the project it scans can target any PHP version.
All rules run except the configuration & route rules, which need a booted Laravel app. The PHP rules recognise input and dangerous calls in Symfony (Request, Doctrine DBAL/DQL/QueryBuilder, RedirectResponse, Twig |raw), Yii2 (Yii::$app->request, createCommand, findBySql, string where(), redirect(), views) and plain PHP ($_GET/$_POST, PDO, mysqli, echo). Without a config file the whole project is scanned, minus vendor, var, runtime, web/assets, node_modules, tests and caches. Put a risk-analyzer.php (or config/risk-analyzer.php) in the project to change that; it has the same format as the Laravel config.
From PHPUnit or Pest:
use Siberfx\RiskAnalyzer\Standalone; public function test_no_security_findings(): void { Standalone::scan(__DIR__.'/..', offline: true)->assertClean('high'); }
Guides per framework, with install, config, CI and what is checked:
Keeping a published config up to date
New options added by a package update work even if your published config is older: the package defaults fill any key you don't set, also inside nested sections such as routes. Lists you set (paths, admin_patterns...) are used as they are, never merged with the defaults.
To also write the new options into your config/risk-analyzer.php, so you can see and change them:
php artisan risk-analyzer:config-sync # add missing options to config/risk-analyzer.php php artisan risk-analyzer:config-sync --dry-run # only list them php artisan risk-analyzer:config-sync --check # list them and exit 1 if any are missing (CI)
It only adds keys, copied with their comments from the package config. Your values, comments, env() calls and formatting are left untouched, and nothing is removed. To run it on every update, add it to your app's composer.json:
"scripts": { "post-update-cmd": [ "@php artisan risk-analyzer:config-sync" ] }
If you run config:cache, run it again after syncing.
Usage
php artisan risk-analyzer:scan # everything, fails on "high" and above php artisan risk-analyzer:scan --production # apply production checks (debug mode, cookies, dev tools...) php artisan risk-analyzer:scan --dev # skip production-only checks, even when APP_ENV=production php artisan risk-analyzer:scan --fail-on=medium php artisan risk-analyzer:scan --only=code # categories: code, frontend, infrastructure, runtime, dependencies, filesystem php artisan risk-analyzer:scan --only=sql-injection,ssrf --skip=xss-blade php artisan risk-analyzer:scan --changed=origin/main # code, frontend and infrastructure rules, on files changed since origin/main php artisan risk-analyzer:scan --frontend # only frontend checks (and npm advisories for it) php artisan risk-analyzer:scan --frontend=client # the same, for the frontend in client/ instead of resources/js php artisan risk-analyzer:scan --infrastructure # only Docker, compose, script and CI checks php artisan risk-analyzer:scan --offline # no network: skips the OSV lookup, built-in support dates php artisan risk-analyzer:scan --format=sarif --output=risk-analyzer.sarif php artisan risk-analyzer:scan --format=markdown >> "$GITHUB_STEP_SUMMARY" php artisan risk-analyzer:rules --details # what every rule looks for php artisan risk-analyzer:baseline # accept the current findings php artisan risk-analyzer:config-sync # add new package options to your published config
Sample output:
RISK ANALYZER 48 rules · production profile · 1.84s
CRITICAL sql-injection app/Http/Controllers/ReportController.php:22
Request input flows into raw SQL passed to DB::select().
│ $rows = DB::select("select * from reports where id = $id");
↳ Keep the SQL a literal and pass values as bindings: whereRaw('price > ?', [$price]).
HIGH unprotected-route
GET|HEAD admin/users looks like an admin route but has no authentication middleware.
↳ Put the route in a group with the auth middleware (and an authorization check such as can:).
1 critical · 1 high · 0 medium · 3 low · 0 info (4 baselined)
FAIL 2 finding(s) at or above "high".
Exit codes: 0 when nothing reaches the threshold, 1 when something does, 2 for invalid options.
Rules
Code (AST + taint analysis)
| Rule | Looks for |
|---|---|
sql-injection |
Raw SQL built from input or runtime strings: Laravel (DB::select, DB::raw, whereRaw, orderByRaw...), PDO/mysqli/pg_query, Doctrine (executeQuery, fetchAllAssociative, createQuery, QueryBuilder where("… " . $x)), Yii2 (createCommand, findBySql, string where()); user-chosen orderBy/groupBy/DB::table identifiers |
command-injection |
exec, shell_exec, system, backticks, string-form Process::run() built from input |
code-execution |
eval, include of input, call_user_func($request->...), $fn() |
insecure-deserialization |
unserialize() of input, or without allowed_classes |
path-traversal |
File functions, Storage/File, response()->download(), storeAs() with input paths or client file names |
ssrf |
Http::get(), Guzzle, curl, get_headers with input URLs |
open-redirect |
redirect(), ->away(), Redirect::to(), Symfony RedirectResponse/$this->redirect(), Yii2 redirect(), Location: headers with input targets |
xxe |
LIBXML_NOENT/LIBXML_DTDLOAD, substituteEntities, re-enabled entity loader |
mass-assignment |
create($request->all()), forceFill(...) of input, empty $guarded, #[Unguarded], Model::unguard() |
xss-blade |
{!! !!} echoes: input printed raw (high), other raw output to review (low) |
xss-echo |
echo, print and <?= ?> of request input without htmlspecialchars()/Html::encode() (plain PHP pages, Yii2 views) |
xss-twig |
Twig {{ …|raw }} in Laravel apps using TwigBridge (resources/views/*.twig) and Symfony: request data such as request('q'), old(), app.request.query (high), other raw output (low); {% autoescape false %} (medium) |
hardcoded-secret |
Provider token formats (AWS, Stripe, GitHub, Slack, OpenAI, Anthropic...), private keys, literal passwords, secret env() fallbacks |
weak-cryptography |
md5/sha1 of passwords, ECB/DES/RC4, mcrypt, == on signatures |
insecure-randomness |
Tokens, OTPs and passwords made with rand, mt_rand, uniqid, str_shuffle |
tls-verification-disabled |
withoutVerifying(), 'verify' => false, CURLOPT_SSL_VERIFYPEER off |
debug-leftover |
dd, dump, ray, var_dump, ->dd(), phpinfo() |
Frontend code (React, Vue, Angular)
| Rule | Looks for |
|---|---|
xss-frontend |
dangerouslySetInnerHTML, v-html, [innerHTML], bypassSecurityTrust*(), innerHTML/outerHTML/insertAdjacentHTML/document.write: URL or route input (high), other values to review (medium), DOMPurify-sanitised (low) |
frontend-secret |
Provider tokens and literal secrets in JS/TS/Vue (shipped to every visitor), and VITE_/MIX_/NG_APP_/REACT_APP_ env variables named like secrets, which the bundler copies into the build |
frontend-code-execution |
eval(), new Function(), setTimeout/setInterval with a string |
frontend-open-redirect |
location.href, location.assign/replace, window.open, href/src bindings set to URL or route input; javascript: URLs in templates |
frontend-postmessage |
postMessage(data, '*'), window message listeners that never check event.origin |
frontend-token-storage |
Auth tokens (low) and passwords or secrets (medium) in localStorage/sessionStorage |
frontend-debug |
debugger statements, console.log/debug/trace calls (one finding per file) |
Docker, CI & scripts
| Rule | Looks for |
|---|---|
dockerfile-hardening |
Secrets in ENV (high) or build ARGs (medium), COPY . without a .dockerignore that keeps .env out, ADD https://… without --checksum, untagged or :latest base images, a final stage running as root, and the shell checks below on RUN lines |
compose-hardening |
privileged: true and a mounted Docker socket (high), network_mode: host, cap_add: SYS_ADMIN/ALL, unconfined seccomp/AppArmor, literal secrets in environment:, MYSQL_ALLOW_EMPTY_PASSWORD, database/cache/search ports published on every interface (medium in *.prod.yml, low otherwise) |
shell-script-risks |
In .sh/.bash/.zsh, Makefiles and Envoy.blade.php: committed tokens and secrets, mysql -p<password>, credentials in URLs, curl … | sh, chmod 777, TLS checks turned off (curl -k, --no-check-certificate, sslVerify false), eval "$VAR", rm -rf "$DIR/" without ${DIR:?} |
ci-workflow-risks |
GitHub Actions: issue/PR titles, bodies, branch names or commit messages expanded inside run: or github-script (script injection, high), pull_request_target workflows that check out the PR's code (high), permissions: write-all, third-party actions not pinned to a commit SHA (low, one finding per workflow), and the shell checks on run: steps |
apt-hardening |
Dockerfiles, scripts and workflows that add APT sources marked trusted=yes (high), turn off repository or certificate checks (AllowInsecureRepositories, Verify-Peer false, high), or use plain http:// package mirrors (medium) |
Configuration & routes (booted application)
| Rule | Looks for |
|---|---|
debug-mode |
APP_DEBUG and debug log level in production |
encryption-key |
Missing/invalid APP_KEY, weak cipher, production key equal to .env.example |
session-cookies |
http_only off, secure off in production, SameSite=None without Secure, very long lifetimes |
csrf-exclusions |
Catch-all exclusions, and which real POST/PUT/DELETE web routes each exclusion unprotects |
unprotected-route |
Admin-looking routes without auth, login/password/OTP routes without throttle. OAuth/SSO callbacks and webhooks are checked for throttling/signatures instead, and SPA catch-alls (admin/{any?}) by whether the API they call is protected |
cors-policy |
Any origin with credentials, unescaped origin patterns |
password-hashing |
bcrypt rounds < 10, Argon2 below OWASP minimums |
dev-tools-exposed |
Debugbar/Clockwork/Ray in require, debug routes and Debugbar/Telescope enabled in production |
security-headers |
In production: no clickjacking protection (X-Frame-Options / CSP frame-ancestors), no or short Strict-Transport-Security, no X-Content-Type-Options, no CSP or one allowing 'unsafe-inline'/'unsafe-eval' scripts, no Referrer-Policy, version-revealing X-Powered-By/Server |
trusted-proxies |
TrustProxies trusting every proxy (*, **), which lets clients spoof their IP with X-Forwarded-For |
insecure-app-url |
APP_URL on http:// or URL::forceScheme('http') in production |
database-tls |
In production: MySQL/MariaDB connections to public hosts without an SSL CA, PostgreSQL with sslmode disable/allow/prefer |
php-configuration |
In production: allow_url_include, display_errors, display_startup_errors and expose_php on, log_errors off, zend.assertions 1, read from the php.ini files PHP-FPM uses (see below) |
Dependencies
| Rule | Looks for |
|---|---|
vulnerable-dependency |
Packages in composer.lock, package-lock.json, yarn.lock (v1 and Berry), pnpm-lock.yaml and bun.lock with OSV advisories, with the lowest fixing version. Lockfiles inside frontend folders (a separate SPA) are checked too, and so are the packages installed in vendor/ (vendor/composer/installed.json, following config.vendor-dir) and node_modules/ (node_modules/.package-lock.json) when they differ from the lockfile or there is none; turn that off with dependencies.installed |
abandoned-package |
Packages marked abandoned (from the lock file, offline) |
composer-hardening |
secure-http: false, HTTP repositories, allow-plugins: true, unlisted plugins, missing lock |
unsupported-runtime |
PHP, Laravel and Node.js versions past (or within 90 days of) end of security support; a PHP patch level missing security releases; a composer.json PHP constraint that allows an unsupported version; Node versions pinned in .nvmrc, .node-version, package.json, Dockerfiles, compose files and GitHub Actions; in production, the MySQL/MariaDB/PostgreSQL and Redis/Valkey servers the app uses; PHP base images (php:8.1-fpm, serversideup/php:8.2-…) in Dockerfiles and compose files |
Filesystem
| Rule | Looks for |
|---|---|
public-exposure |
.env, .git, dumps, keys, backups, phpinfo.php, logs inside public/, and PHP files, dumps, keys, logs and .htaccess in folders linked into it (storage:link); built source maps (*.js.map, low) |
secrets-in-git |
.env, OAuth keys, auth.json, private keys committed to git (asks git ls-files). Symfony's committed .env/.env.<env> only when they hold a real secret |
apt-configuration |
On a Debian or Ubuntu host (the machine running the scan), /etc/apt: plain http:// sources together with a non-zero Acquire::Retries (the setup described for CVE-2026-109518, medium; Debian 12 and Ubuntu 22.04 retry by default), and sources marked trusted=yes or with checks turned off (high). Skipped on other systems |
file-permissions |
.env, auth.json and the Passport key readable or writable by every user, storage/ and bootstrap/cache set to 777 (not on Windows) |
Frontend code
The frontend rules read .js, .jsx, .ts, .tsx, .mjs, .cjs, .vue and .html (Angular templates) files in frontend.paths, which defaults to resources/js and resources/ts. node_modules, dist, build, .angular, tests, *.min.js, *.d.ts and *.spec/*.test files are skipped.
A full scan includes the frontend rules. --frontend scans only the frontend: the frontend rules plus vulnerable-dependency for its JavaScript lockfiles, with no PHP, configuration, Composer or filesystem rules. Given folders, it scans those instead of frontend.paths, for example an Angular or React app in its own folder. Paths are relative to the project root or absolute, and the option can be repeated:
php artisan risk-analyzer:scan --frontend # resources/js and resources/ts php artisan risk-analyzer:scan --frontend=client php artisan risk-analyzer:scan --frontend=apps/admin --frontend=apps/shop php artisan risk-analyzer:scan --frontend=client --skip=frontend-debug # --only/--skip narrow the scope
A frontend folder with its own package-lock.json, yarn.lock, pnpm-lock.yaml or bun.lock has that lockfile checked, in full scans too. Folders without one, such as resources/js, use the project's root lockfile. --skip=frontend leaves the frontend rules out of a full scan.
The frontend rules match patterns; they don't run a JavaScript parser. Input is recognised when it is visible in the expression (location.search, URLSearchParams, useParams(), useSearchParams(), $route.query, route.snapshot, event.data...) or in a variable the same file assigns from it (const params = new URLSearchParams(location.search)). Values that reach a sink in other ways are reported as medium, to review. Inline suppressions work in JS (// risk-analyzer-ignore xss-frontend -- sanitised on the server) and in templates (<!-- risk-analyzer-ignore xss-frontend -->).
Docker, CI & scripts
The infrastructure rules search infrastructure.paths (default: the project root) for Dockerfiles (Dockerfile, Dockerfile.*, *.Dockerfile, Containerfile), compose files (docker-compose*.yml, compose*.yaml), shell scripts (.sh, .bash, .zsh), Makefiles (Makefile, *.mk), Envoy.blade.php and .github/workflows/*.yml. vendor, node_modules, storage, public, .git and worktree folders are skipped. Add a folder outside the project, such as a checkout of your deploy repository, to the list:
'infrastructure' => [ 'paths' => ['.', '/srv/deploy-scripts'], ],
--infrastructure scans only these files: the four rules above plus unsupported-runtime for the PHP and Node versions pinned in Dockerfiles, compose files and workflows (not the PHP running the scan). Given folders, it searches those instead of infrastructure.paths:
php artisan risk-analyzer:scan --infrastructure
php artisan risk-analyzer:scan --infrastructure=docker --infrastructure=deploy
php artisan risk-analyzer:scan --frontend --infrastructure # both scopes
Like the frontend rules they match patterns, and comments are ignored. Suppress a line with a # comment on it or the line above:
# risk-analyzer-ignore dockerfile-hardening -- internal mirror with a private CA RUN curl -k https://mirror.internal/tool.tar.gz | tar xz
Runtime versions
unsupported-runtime takes end-of-support dates from endoflife.date and PHP security releases from php.net, cached for a day. With --offline, or when those sites can't be reached, it uses the dates built into the package.
-
PHP: the running version, and its patch level.
8.4.3is reported as high when a newer8.4.xrelease fixed security issues, and as low when only bug-fix releases are newer. Distribution packages (Debian, Ubuntu, RHEL) sometimes backport fixes without changing the version; check your vendor's advisories in that case. -
composer.json:
require.phpandconfig.platform.phpwhose lowest allowed version is unsupported, e.g.^8.1. -
Node.js: every pinned version is reported with where it came from, e.g.
Node 20 (Dockerfile:1) stopped receiving security fixes on 2026-04-30.Aliases such aslts/*ornode:currentare skipped. Ifnodeis on thePATH, its version is checked too. -
Database and Redis servers (production only): the default database connection (MySQL, MariaDB or PostgreSQL) and, when the cache, session or queue uses Redis, that Redis or Valkey server are asked for their version, e.g.
MySQL 8.0 (connection 'mysql', 8.0.39) stopped receiving security fixes on 2026-04-30.Each check opens its own connection with a 5 second timeout and only reads the version; a server that cannot be reached is skipped.
'runtime' => [ 'node' => true, // check Node versions pinned in the project 'node_binary' => 'node', // false to skip asking the installed node 'services' => true, // false to skip asking the database and Redis servers ],
Security headers
security-headers requests one page and checks its response headers. By default it sends GET / through your app's HTTP kernel, so nothing goes over the network, but headers added by nginx, Apache or a CDN are not visible. Findings then say "The app does not set..." To check what browsers actually receive, point it at the live site:
'http' => [ 'probe_path' => '/', // false to skip the in-app request 'probe_url' => env('RISK_ANALYZER_PROBE_URL'), // e.g. https://example.com (skipped with --offline) ],
The in-app request runs that page's code like a browser visit would. If / needs a database or does more than render, point probe_path at a lighter page (/up) or set it to false. A page that fails is reported as info, not as missing headers.
php.ini
php-configuration reads settings from the php.ini files, not with ini_get(): the CLI that runs the scan forces display_errors on and often loads a different php.ini than PHP-FPM. It uses, in order:
- the files in
risk-analyzer.php.ini_fileswhen set, otherwise the CLI's php.ini andconf.dfiles, or the PHP-FPM ones next to them on Debian/Ubuntu (/etc/php/8.4/fpm/php.ini,conf.d,pool.d/*.conf, includingphp_admin_value[...]overrides); public/.user.iniandphp_flag/php_valuelines inpublic/.htaccesson top (for settings a directory can change).
Each finding names the file the value came from. When the scan runs where PHP-FPM is configured differently (a Docker image, a managed host), list its files:
'php' => ['ini_files' => ['/usr/local/etc/php/php.ini', '/usr/local/etc/php-fpm.d/www.conf']],
Production profile
Some issues only matter in production (debug mode, insecure cookies, enabled dev tools). These rules use their full severity when the app runs in an environment listed in risk-analyzer.production_environments, or when you pass --production. Run the scan on the server, or in CI with the production config cached, to check the configuration that actually ships.
--dev does the opposite: it forces the development profile even when APP_ENV is a production environment. Production-only checks (debug mode, cookies, headers, database TLS and versions, php.ini...) are skipped, so the scan makes no page requests or service connections; code, dependency, route and filesystem rules still run. risk-analyzer:baseline takes --production and --dev too, and passing both is an error.
Suppressing findings
Inline, on the line or the line above:
// risk-analyzer-ignore sql-injection -- $column is mapped from an enum above $query->orderByRaw("{$column} desc"); $token = md5(uniqid()); // risk-analyzer-ignore insecure-randomness -- cache-busting only, not a secret
{{-- risk-analyzer-ignore xss-blade -- sanitised with HTMLPurifier in the model --}} {!! $post->body_html !!}
{/* risk-analyzer-ignore xss-frontend -- HTML is sanitised by the API */} <div dangerouslySetInnerHTML={{ __html: post.bodyHtml }} />
risk-analyzer-ignore with no rule id ignores every rule on that line. Put the reason after --.
Routes have no source line to comment, so put the #[RiskAnalyzerIgnore] attribute on the route's closure, controller method, or controller class (covers all its routes). With no rule ids it skips every route rule:
use Siberfx\RiskAnalyzer\Attributes\RiskAnalyzerIgnore; Route::get('admin/status', #[RiskAnalyzerIgnore('unprotected-route', reason: 'public status page')] fn () => view('status')); final class GoogleCallbackController { #[RiskAnalyzerIgnore('unprotected-route', reason: 'OAuth callback')] public function __invoke() { /* ... */ } }
The attribute is safe in production even though the package is a dev dependency: PHP only loads an attribute's class when something asks for an instance of it, and only the scanner does. Your routes keep working after composer install --no-dev.
Or list URI / route-name patterns in config, e.g. for routes a package registers. An unused config file is just as safe without the package:
'routes' => ['ignore' => ['admin/oauth/*' => 'SSO entry points', 'admin.preview']],
Baseline: record the findings you accept and only fail on new ones:
php artisan risk-analyzer:baseline # writes risk-analyzer-baseline.json, commit it php artisan risk-analyzer:scan # baselined findings are listed as such but never fail php artisan risk-analyzer:scan --no-baseline
Fingerprints ignore line numbers, so a baselined finding stays baselined when code moves around the file.
Config: disable rules, change severities or allow known sample values:
'rules' => [ 'disabled' => ['debug-leftover'], 'severity' => ['xss-blade' => 'medium'], ], 'dependencies' => ['ignore' => ['GHSA-xxxx-xxxx-xxxx']], 'secrets' => ['allow' => ['sk_test_documented_example']],
Reviewing ignores
risk-analyzer:ignores lists every active ignore with its reason: routes.ignore and the other config ignores, #[RiskAnalyzerIgnore] on routes, and inline risk-analyzer-ignore comments in PHP, Blade, frontend and infrastructure files.
php artisan risk-analyzer:ignores
+--------------+-----------------------------------+-----------------------------------+-------------------------------+
| Kind | Where | Ignores | Reason |
+--------------+-----------------------------------+-----------------------------------+-------------------------------+
| route-config | risk-analyzer.php (routes.ignore) | admin/{any?} · unprotected-route | SPA shell, API has auth |
| inline | app/Http/Report.php:12 | sql-injection | (no reason) |
+--------------+-----------------------------------+-----------------------------------+-------------------------------+
2 active ignore(s), 1 without a reason.
Secret values from secrets.allow are masked in the output. Entries without a reason are the ones to fix first.
To stop new ignores slipping in unreviewed, commit a snapshot and check against it in CI:
php artisan risk-analyzer:ignores --json > .risk-analyzer-ignores.json
git add .risk-analyzer-ignores.json
- name: No unreviewed risk-analyzer ignores run: php artisan risk-analyzer:ignores --check=.risk-analyzer-ignores.json
--check fails only for ignores that are not in the snapshot. Removing an ignore does not fail it. The check compares what each ignore covers, not its line number, so moving code does not fail it; but the where field in the snapshot does change, so regenerate the file in the same commit as the ignore. Standalone projects can run the same command with vendor/bin/risk-analyzer ignores.
Admin areas and single-page apps
unprotected-route flags any route whose path looks like an admin area (admin_patterns: admin, dashboard, backoffice, panel, manage). Single-page apps (React, Vue, Angular, Inertia) add a catch-all such as admin/{any?} that serves the shell for every admin page, so the scanner also checks the API that shell calls. Four options cover the cases:
// config/risk-analyzer.php 'routes' => [ // Skip routes by URI or route name. Covers the SPA shell and its API routes too. 'ignore' => [ 'admin/{any?}' => 'React admin shell; its API is checked separately', 'admin/api/*' => 'protected by auth:sanctum and the admin.access gate', ], // [] turns admin detection off completely (sensitive login and OTP checks still run). 'admin_patterns' => ['admin', 'dashboard', 'backoffice', 'panel', 'manage'], ], 'frontend' => [ // Folders of the frontend code that are not scanned. 'exclude' => ['node_modules', 'dist', 'resources/js/admin'], ],
| Stack | What to ignore | How |
|---|---|---|
| Laravel routes | an admin route or group | routes.ignore, or #[RiskAnalyzerIgnore('unprotected-route')] on the closure or controller |
| React, Vue, Angular, Inertia | the admin shell catch-all | routes.ignore; the API it calls should be protected on the server |
| React, Vue, Angular source | an admin folder | frontend.exclude, or {/* risk-analyzer-ignore xss-frontend -- reason */} on one line |
| Node (Express, Nest, Fastify) | not read by the scanner | nothing to ignore here; review its routes with the Node tools you use |
Patterns match the URI (admin/*) or the route name (admin.users.*) with Str::is. Always give a reason: the reason is what someone reviewing the ignore list needs.
Middleware the scanner accepts as protection
A route counts as protected when its expanded middleware (groups and aliases included) matches one of these:
- By name, from
routes.auth_middleware(default:auth,auth.basic,can,signed,password.confirm,verified).authalso matchesauth:sanctumandauth:api, andcanmatchescan:access-admin. - By class name, when the name contains
Authorize,Authenticate,Gate,Admin,PermissionorRole. Package dashboards such as Telescope, Horizon, Pulse and Filament are accepted this way.
The class-name match is case-sensitive, so role:admin (lowercase alias) does not count, while EnsureAdminAccess, RoleMiddleware or an alias such as AdminOnly does. To add your own names, put them in routes.auth_middleware.
Better than ignoring: protect the endpoint on the server
A route hidden in a React, Vue or Angular router guard is not protected. Anyone can call the URL directly, so the server has to check the user. The finding's remediation says the same thing, and the fixes below remove most admin findings without an ignore entry:
- Group the admin routes once. Put them behind
auth, acan:gate or a policy, and an admin role check, so the route file shows the rule:Route::middleware(['auth', 'can:access-admin'])->prefix('admin')->group(function () { Route::get('users', [UserController::class, 'index']); });
- Name the guard for what it does. The scanner accepts middleware whose class name contains
Authorize,Authenticate,Gate,Admin,PermissionorRole, soEnsureAdminAccesscounts as protection. - Protect the API, not the shell. The admin shell is only HTML and JavaScript. Once every
admin/api/*route needsauth:sanctumand a gate, ignore the shell with a reason. - Check authorization in the controller too. Use
$this->authorize()or a policy, so a route that loses its middleware group still fails closed. - Keep admin off the public host. Serve it from its own subdomain, restrict it by IP or VPN, or put it behind SSO. Each layer makes a missed middleware less dangerous.
- Do not rely on a secret path. A random prefix like
/x7-ops/only hides the route from casual visitors; it is not a control. Use it as an extra layer, not the only one. - Review the ignore list. Each entry is a decision. Keep it short, keep the reasons, and check it when the baseline changes.
CI
GitHub Actions with code scanning annotations:
name: security on: [push, pull_request] jobs: risk-analyzer: runs-on: ubuntu-latest permissions: contents: read security-events: write steps: - uses: actions/checkout@v4 with: fetch-depth: 0 - uses: shivammathur/setup-php@v2 with: php-version: '8.4' - run: composer install --no-interaction --prefer-dist - run: cp .env.example .env && php artisan key:generate - run: php artisan risk-analyzer:scan --format=sarif --output=risk-analyzer.sarif - run: php artisan risk-analyzer:scan --format=markdown >> "$GITHUB_STEP_SUMMARY" if: always() - uses: github/codeql-action/upload-sarif@v3 if: always() with: sarif_file: risk-analyzer.sarif
For pull requests you can scan only the touched files: php artisan risk-analyzer:scan --changed=origin/${{ github.base_ref }}.
Inside your test suite
use Siberfx\RiskAnalyzer\Facades\RiskAnalyzer; it('has no security findings', function () { RiskAnalyzer::scan(only: ['code', 'runtime'], offline: true)->assertClean('high'); });
Outside Laravel, use Standalone::scan() instead of the facade; see Without Laravel.
Writing your own rules
Code rules receive every AST node (nikic/php-parser), with taint information for the enclosing function in $file->taint:
use PhpParser\Node; use Siberfx\RiskAnalyzer\Code\Ast; use Siberfx\RiskAnalyzer\Code\FileScope; use Siberfx\RiskAnalyzer\Rules\Code\AbstractCodeRule; use Siberfx\RiskAnalyzer\Severity; final class NoRawHtmlMail extends AbstractCodeRule { public function id(): string { return 'raw-html-mail'; } public function title(): string { return 'Raw HTML mail'; } public function description(): string { return 'Mail::html() with request input.'; } public function severity(): Severity { return Severity::High; } public function inspect(Node $node, FileScope $file): iterable { if ($node instanceof Node\Expr\StaticCall && Ast::className($node) === 'Mail' && Ast::methodName($node) === 'html' && $file->taint->isTainted(Ast::arg($node, 0))) { yield $this->report($file, $node, 'Request input is sent as raw HTML mail.'); } } }
Project rules (config, files, external services) implement Siberfx\RiskAnalyzer\Contracts\ProjectRule and receive a ScanContext. Register either kind in config/risk-analyzer.php (rules.extra) or from a service provider:
RiskAnalyzer::extend(NoRawHtmlMail::class);
Limits
Risk Analyzer is a static scanner with intra-procedural taint tracking. It follows input within a function, not across method calls or class properties. The frontend and infrastructure rules match patterns in JavaScript, TypeScript, templates, Dockerfiles, YAML and shell rather than parsing them. So treat a clean scan as "no known patterns found", not as proof of safety. It complements code review, dependency updates and a web application firewall; it doesn't replace them.
What the scanner does not read
- Node server code (Express, NestJS, Fastify, Koa): their routes, middleware and auth checks are not analysed. Only the frontend and infrastructure folders you configure are read, and the frontend rules are pattern matches, not a server model.
- Client-side routers and guards (React Router, Vue Router, Angular routes and
canActivate): route paths and guards are not analysed. A guard hides a page in the browser; it is not a control on the server. - GraphQL schemas and resolvers (
.graphql,schema.gql, resolver classes) and OpenAPI or Swagger specs: not read, so their operations are not checked for auth. - Authorization inside code: only route middleware is checked.
$this->authorize(),Gate::allows(), policies andabort_unless()checks in controllers are not verified. - Routes outside the route table: in standalone scans there is no route table, so the route rules are skipped. Routes registered at runtime from a database are only seen in a booted Laravel scan.
- Files outside the configured paths (
paths,frontend.paths,infrastructure.paths), the code of dependencies invendor/andnode_modules/(their installed versions are checked byvulnerable-dependency), and minified bundles.
Testing
composer test
composer analyse
composer format
License
MIT. See LICENSE.