danilovl / page-audit-bundle
Symfony bundle that opens every page, form and API endpoint of the application on a copy of the database and reports response time, SQL, memory and size like the profiler
Package info
github.com/danilovl/page-audit-bundle
Type:symfony-bundle
pkg:composer/danilovl/page-audit-bundle
Requires
- php: ^8.5
- ext-dom: *
- ext-zlib: *
- doctrine/dbal: ^4.0
- doctrine/doctrine-bundle: ^3.0
- doctrine/orm: ^3.0
- symfony/asset: ^8.0
- symfony/console: ^8.0
- symfony/framework-bundle: ^8.0
- symfony/http-client: ^8.0
- symfony/mime: ^8.0
- symfony/process: ^8.0
- symfony/security-bundle: ^8.0
- symfony/serializer: ^8.0
- symfony/translation: ^8.0
- symfony/twig-bundle: ^8.0
Requires (Dev)
- aws/aws-sdk-php: ^3.279
- danilovl/hashids-bundle: ^2.0
- danilovl/phpstan-rules: ^0.0.4
- friendsofphp/php-cs-fixer: ^3.92.5
- lexik/jwt-authentication-bundle: ^3.1
- phpstan/extension-installer: ^1.4.3
- phpstan/phpstan: ^2.1.33
- phpstan/phpstan-doctrine: ^2.0
- phpstan/phpstan-phpunit: ^2.0
- phpstan/phpstan-symfony: ^2.0.9
- phpunit/phpunit: ^12.0
- ruflin/elastica: ^8.0 || ^9.0
- sqids/sqids: ^0.5
- symfony/browser-kit: ^8.0
- symfony/css-selector: ^8.0
- symfony/filesystem: ^8.0
- symfony/form: ^8.0
- symfony/mailer: ^8.0
- symfony/mercure: ^0.6 || ^0.10
- symfony/messenger: ^8.0
- symfony/validator: ^8.0
- symfony/yaml: ^8.0
Suggests
- aws/aws-sdk-php: S3 writes of audited requests are simulated
- danilovl/hashids-bundle: Hashids route parameters are encoded automatically
- friendsofsymfony/elastica-bundle: Elasticsearch indexes are copied for the audit
- lexik/jwt-authentication-bundle: JSON requests are sent with a JWT, so endpoints that skip CSRF for Bearer tokens work without a token from the page
- sqids/sqids: Sqids route parameters are encoded automatically
- symfony/form: Form errors of submitted forms are reported and fixed automatically
- symfony/mailer: E-mails of audited requests are recorded instead of being sent
- symfony/mercure: Mercure updates of audited requests are recorded instead of being published
- symfony/messenger: Audits run in a Messenger worker when one is running; without it they run in a background console process
Provides
None
Conflicts
None
Replaces
None
README
Opens every page, form and API endpoint of a Symfony application as a chosen user on a copy of the database and builds a report like the profiler, but for all pages at once: full time, TTFB, server time (bootstrap / routing and security / controller), SQL (count, time, N+1, slowest query), memory, response size, HTML size and external HTTP calls.
Nothing has to be described by hand: routes, parameters, form values, query parameters and request bodies are discovered automatically. Only endpoints that cannot be discovered need a scenario.
Requirements
- PHP 8.5+, Symfony 8, Doctrine ORM 3, DBAL 4
- MySQL / MariaDB, PostgreSQL or SQLite (see «Databases»)
- Nothing else is required: without Messenger the run goes to a background console process (see «Where the run is executed»)
- Optional:
symfony/messenger(runs in a Messenger worker and isolates messages of audited requests),symfony/form(form errors are reported and fixed),lexik/jwt-authentication-bundle(JSON requests carry a JWT),symfony/mailer,symfony/mercure,aws/aws-sdk-php, Elastica, Hashids, Sqids (isolated or encoded automatically when installed)
Screenshots
Installation
composer require danilovl/page-audit-bundle
// config/bundles.php Danilovl\PageAuditBundle\PageAuditBundle::class => ['all' => true],
# config/routes/page_audit.yaml page_audit: resource: '@PageAuditBundle/config/routes.yaml' prefix: /page-audit
bin/console assets:install
That is the whole setup. Open /page-audit/ as a user with ROLE_ADMIN and press Start audit, or run bin/console page-audit:run --user=<username>.
Minimal setup: what is required and what is optional
| Needed | Why | |
|---|---|---|
Bundle, route, assets:install |
required | the page and the console commands |
A user with ROLE_ADMIN |
required | only admins open /page-audit/ (the console needs --user) |
| A database to copy | required | by default the application database is copied to <name>_page_audit, the original is only read; set simulation.databases to copy another one (e.g. the test database) |
| Writable cache pool | required | reports and the run state live there (cache.app by default, page_audit.cache_pool) |
| A way to execute the run | required, one is always there | a Messenger worker, otherwise a background console process (bin/console page-audit:process, needs proc_open and PHP CLI), otherwise the open report page |
symfony/messenger and a worker |
optional | the worker is supervised and continues a run after a crash, works where processes cannot be started, can run on another machine; the bundle also keeps messages of audited requests out of the real queues, which matters only when the application itself uses Messenger |
page_audit.yaml |
optional | every setting has a default; needed only to change base_url, databases, skipped routes, scenarios, isolation or heuristics |
symfony/form |
optional | form errors of submitted forms are reported and fixed |
| OpenAPI document | optional | request bodies and query values of API endpoints; without it they are taken from the controller code |
lexik/jwt-authentication-bundle |
optional | JSON requests carry a JWT |
| Mailer, Mercure, AWS SDK, Elastica, Hashids, Sqids | optional | isolated or encoded automatically when installed |
The «Checks» panel of the start form shows the same: every row is marked required or optional.
How it works
- Sandbox. The chosen source database is copied into the sandbox (or an existing allowed database is used without a copy). Every request of the audit carries a signed
X-Page-Auditheader with the database name; the server switches the Doctrine connection of that request to it only if the name is in the allowed list. - Login. The signed header also carries the user. Before the firewall runs, the bundle writes a security token into the session (stateful firewalls) or into the token storage (stateless firewalls). No login form, password or JWT is needed. The user gets a random password in the sandbox, so forms that ask for the current password pass.
- Read. All GET routes without parameters, then links found on pages (
href, URLs in attributes and inline scripts, redirects), then routes with parameters. Entity parameters are taken from the database (#[MapEntity], argument types,xxxIdnames), your own records first; the owner relation is detected from the user class. 404 and 403 try the next record. - Learn. Query strings,
data-*attributes, JSON in attributes, JSON responses and CSRF tokens are remembered and reused as values of parameters with the same name. - Query parameters. Required query parameters come from OpenAPI (found automatically: NelmioApiDoc, API Platform or any
/doc.json-like route). When a GET answers 400, 422 or 500, it is repeated once with all parameters the controller reads:#[MapQueryParameter],#[MapQueryString]and$request->query->get*('name')in the controller and the services it calls (enum values are used forgetEnum()). - Write. Every form found on the pages is submitted with its own values; empty required fields get test values by type and name; autocomplete selects get ids from the database. POST/PATCH/PUT routes without a form get a JSON body from OpenAPI, or a body from
#[MapRequestPayload]/$request->request->get*()/getPayload(). Rejected requests (form errors,errors, RFC 7807violations) are fixed and repeated. Deleting routes go last. - External HTTP. During an audited request the
http_clienttransport is wrapped: outgoing requests are blocked and reported (block_external_http). - Report. Besides the numbers of every request the report shows:
- Coverage — the share of routes that really passed: a route passes only when none of its requests failed or was rejected. Routes whose form or API call was rejected by validation are shown as «Not tested», failed and not opened routes with the reason; routes closed for the role of the run are not counted.
- What to fix — problems grouped by cause, worst first, with an advice and example requests: one row per exception class and place in the application code, per HTTP error, per SQL query repeated in a loop (N+1) or slow, per GET that writes to the database (INSERT, UPDATE, DELETE), per external host and per action the audit could not pass because of validation (not tested).
Parallel requests
concurrency (or the field on the start form, or --concurrency) sends GET requests in parallel through Symfony HttpClient; forms and POST requests are always sent one by one. Every parallel lane has its own session. Parallel mode measures throughput: each request runs under load, so single-request times are higher than in a sequential run.
Databases
Databases are listed in the config and offered in the selects of the start form. Under the chosen database the page shows whether it is connected or why it cannot be used (no connection, no right to create databases, the copy does not exist yet); Start is disabled until a usable database is chosen.
page_audit: simulation: database_pattern: '~test~' # optional safety net: every used name must match databases: app_test: ~ # key = name, copy target app_test_page_audit app_perf: existing: true # may be used without a copy reports: name: reports_test url: 'mysql://audit:secret@db2:3306/reports_test' # own connection, default is the application connection copy: false existing: true
| Option | Default | Meaning |
|---|---|---|
name |
key | database name (SQLite: file path) |
url |
application connection | DSN (mysql://, postgresql://, sqlite:///path) — another host, port or user; the driver must be the same as the application connection |
copy |
true |
offered as a source of «Copy into a sandbox» |
sandbox |
<name>_page_audit |
name of the copy |
existing |
false |
offered in «Use an existing database» |
elasticsearch_prefix |
'' |
FOSElastica: source indexes of this database are <prefix><index name> (for example test_ when the database is the test one) |
Without databases the database of the application connection is offered as the only copy source.
The start form (and page-audit:run) has two modes:
- Copy into a sandbox (
--source=<key>) — the sandbox of the chosen entry is deleted and created again from it; the user gets a random password in the copy. - Use an existing database (
--database=<name>or--database=copy:<key>for the last copy) — no copy is made; forms and POST requests change the database; the password is not changed. The list contains entries withexisting: true, copies that already exist and, whendatabase_patternis set, every database on the server of the application connection that matches it. Withoutdatabase_patternonly configured databases are offered.
Only the reference (db:<key> / copy:<key>) travels in the signed X-Page-Audit header; the server resolves it from the config and refuses anything else with 503.
| Platform | How the copy is made | Right that is checked |
|---|---|---|
| MySQL / MariaDB | CREATE DATABASE + SHOW CREATE TABLE + INSERT … SELECT + ANALYZE TABLE |
global CREATE and DROP (SHOW GRANTS) |
| PostgreSQL 13+ | DROP DATABASE … WITH (FORCE) + CREATE DATABASE … TEMPLATE from the postgres database; nobody may be connected to the source |
CREATEDB or superuser |
| SQLite | copy of the file with -wal/-shm |
writable directory |
Other platforms: implement Danilovl\PageAuditBundle\Sandbox\PageAuditSandboxDriverInterface (supports(), isValidName(), canCreate(), copy()); the service is picked up automatically.
Shared services (isolation)
A copy of the database is not enough for a bigger application: caches, queues, search and file storage are shared with the real environment. While an audited request runs, the bundle detects them and keeps them unchanged — nothing to configure, the start form lists what was found («What is copied, isolated and simulated»):
| Service | What happens during an audited request |
|---|---|
| Doctrine result cache and second-level cache | replaced by an in-memory cache, so the copy never reaches the shared cache (Redis etc.) |
| Messenger | messages are not sent to transports (RabbitMQ, Doctrine…), they are handled right away against the copy |
| Mailer | e-mails are not sent, they are recorded |
| Mercure | updates are not published, they are recorded |
| AWS SDK clients (S3…) | write commands (Put*, Delete*, Copy*, Create*, Upload*…) are simulated, reads go to the real storage |
| FOSElastica | every index is copied to <index>_page_audit while the run is prepared (settings, mapping, documents); audited requests read and write only the copies |
| HttpClient | external requests are blocked (block_external_http) |
sandbox_request_attributes |
request attributes set for audited requests (for example to switch off a response cache) |
Recorded side effects are shown on the request page («Simulated side effects»).
Auto and manual isolation
The start form (step 4) and page-audit:run --isolation=auto|manual choose how services are handled:
- Auto — the behaviour from the table above for every detected service.
- Manual — every service gets the mode chosen in the «Isolation» card (or
--set=<service>=<mode>); defaults come from the config:
page_audit: isolation: mode: auto # default of the start form services: # manual defaults; every service can be sent to your own host doctrine_cache: dsn # memory | dsn | shared doctrine_cache_dsn: 'redis://redis-test:6379/15' elasticsearch: url # copy | url | shared elasticsearch_url: 'http://user:password@elasticsearch-test:9200' messenger: dsn # sandbox | drop | transport | dsn | real messenger_transport: audit # existing transport for mode «transport» messenger_dsn: 'amqp://guest:guest@rabbitmq-test:5672/%2f/audit' mailer: dsn # record | dsn | real mailer_dsn: 'smtp://mailpit:1025' mercure: url # record | url | real mercure_url: 'http://mercure-test/.well-known/mercure' mercure_jwt: '...' aws: endpoint # simulate_writes | block | endpoint | real aws_endpoint: 'http://minio-test:9000' # path-style; reads and writes go there http: block # block | allow http_allow_hosts: [mercure, minio] http_rewrite: 'api.example.com=mock:8080' # requests to a host go to another host:port profiles: # prepared environments, chosen on the start form or with --env-profile test_stack: label: 'Test stack (.env.test)' headers: # sent with every audit request, e.g. a header the application uses to load another env file X-E2E-TEST: '1' services: mailer: dsn mailer_dsn: 'smtp://mailpit:1025'
A profile applies its headers and service modes in both modes; in manual mode the values chosen on the form win. The report shows the mode, the profile and every service that differs from the auto behaviour.
Users and roles
«Run as» on the start form (or --user, --role=ROLE_A,ROLE_B, --all-roles):
- Me — the logged-in user, looked up in the audit database by the identifier.
- A role — the bundle looks into the audit database and picks an active user with this role (the role hierarchy is applied) who has the most related records (rows that reference the user through Doctrine associations), so the pages of the role are not empty.
- Every role one by one — one report per role; the runs wait for each other. Roles come from
security.role_hierarchyand the users table.
The user entity is found from Doctrine metadata (the class supported by the user provider that has the most associations), the identifier from username/login/email, roles from roles.
Encoded route parameters
When a value from the database does not match the requirement of the route parameter (for example id: '%hashid%'), the bundle tries the parameter encoders and uses the first result that matches the requirement:
danilovl/hashids-bundle(HashidsServiceInterface) and Sqids (Sqids\SqidsInterface, used by sqids bundles) — when the service exists.- Any Twig filter or function of the application that encodes ids (
hashids_encode,sqids_encode,encode_id,obfuscate_id, …) — templates build links with it, so the same logic is reused without configuration. - Own logic: implement
Danilovl\PageAuditBundle\Encoder\PageAuditParameterEncoderInterface(encode(string $value): ?string), the service is picked up automatically.
Where the run is executed
A transport is optional. The start form (step 5 «Checks») picks where the run goes, in this order:
- Messenger worker — a worker that reported itself in the last 90 seconds (every worker writes a heartbeat to the cache pool every 10 seconds on
WorkerRunningEvent; workers started before the bundle was installed or updated report nothing until they are restarted). No config is needed: withoutpage_audit.transportthe bundle takes a running worker of a transport fromheuristics.worker_transports(defaultasync), so dedicated workers of the application (mail, logs) are not used by accident; an empty list allows any transport except those matchingheuristics.worker_transport_exclude_pattern(failed,sync,scheduler_*). Setpage_audit.transportonly to pin one transport. - Background console process — otherwise the bundle starts
bin/console page-audit:process <run id>withnohupin the background (the same PHP CLI found byPhpExecutableFinder, the same environment). The page can be closed. Needsproc_openand a Unix-like system; another console path can be set withpage_audit.console_path. - This page — when processes cannot be started: the open report page calls the
tickendpoint and must stay open.
When no worker is running, «Details» in the form lists what to do: the Messenger transport to add if the application has none, the messenger:consume command to start, then reload the page. The bundle itself needs no config file at all.
The cache pool (page_audit.cache_pool) must be writable, otherwise the run cannot start. The chosen way is stored in the run; «Resume» checks again, so a run whose worker or process is gone continues in the next available way.
Scenarios (only for what cannot be discovered)
The bundle knows nothing about the application: routes, parameters, form values and request bodies are discovered automatically. When a value cannot be discovered, the application describes the request in its own code — there is no scenario section in the bundle config.
Simple, static values — attribute on the controller method (or class):
use Danilovl\PageAuditBundle\Attribute\PageAudit; #[PageAudit(form: ['key' => ''], bearer: true)] public function dismissAlert(): Response {} #[PageAudit(skip: true)] public function sendNewsletter(): Response {} #[PageAudit(skip: true)] class PaymentController {} // every route of the controller is skipped, GET and POST/PATCH/DELETE
An attribute on a method wins over the attribute on its class.
Keys: params, query, form, json, files (paths), method, formId (a form without action that JavaScript sends to this route), bearer, skip. Values may use placeholders: {date:+1 day}, {datetime:…}, {month:…}, {password}, {user_id}, {sql:…}.
Values that need code or data — a service implementing PageAuditScenarioInterface (autoconfigured with the page_audit.scenario tag, so it only has to live in the application's src):
use Danilovl\PageAuditBundle\Scenario\{ PageAuditScenarioContext, PageAuditScenarioFile, PageAuditScenarioInterface, PageAuditScenarioRequest }; readonly class ActivityImportPageAuditScenario implements PageAuditScenarioInterface { public function __construct(private ActivityFacade $activityFacade) {} public function getRoute(): string { return 'activity_import'; } public function create(PageAuditScenarioContext $context): ?PageAuditScenarioRequest { $csv = $this->activityFacade->createExampleCsv(); $files = [ 'activity_import[file]' => new PageAuditScenarioFile('ACTIVITY_example.csv', $csv) ]; return new PageAuditScenarioRequest(files: $files); } }
create()runs right before the request, inside the sandbox: the Doctrine connection points to the copy of the database for the duration of the call, so repositories and facades of the application read the copy, never the original.PageAuditScenarioContextcarries the route, the user of the run (username,userId,role) and the sandboxpassword.PageAuditScenarioRequesthas the same fields as the attribute; files are given by name and content (PageAuditScenarioFile) and are written to a temporary directory — nothing is stored in the project.- Returning
nullskips the route as «no records». - The attribute wins when a route has both.
Heuristics (nothing project specific in the code)
Everything the bundle «guesses» comes from page_audit.heuristics; the defaults are in config/defaults.php of the bundle and can be replaced in your config (a list or a map replaces the default as a whole):
| Key | What it controls |
|---|---|
skip_routes, delete_routes |
routes that are never opened / are opened last (delete phase); page_audit.skip_routes and simulation.delete_routes are added to them |
api_path_prefixes |
paths reported as API |
owner_associations |
association names that point to the record owner |
user.identifier_fields, role_fields, enabled_fields, password_fields, service_roles, role_pattern |
how the user entity and its roles are read |
csrf_headers |
headers that carry a CSRF token |
openapi.route_names, openapi.path_pattern |
how the OpenAPI document is found |
ajax.route_name_pattern, ajax.path_pattern |
how an AJAX route finds the form of its page |
route_names.ignored_tokens, action_tokens |
how route names are split into entity families |
html_form_error_pattern, html_form_error_message_pattern |
how form errors are found in HTML |
twig_encoder_pattern |
Twig filters/functions used to encode ids |
aws_write_command_pattern |
AWS commands treated as writes |
read_write_ignore_table_pattern |
tables a GET request may write to without a «GET changes data» warning (sessions, Messenger, cache, locks) |
retry.query_statuses, retry.record_statuses |
statuses that make the crawler retry with query values / the next record |
parallel_options |
values of «Parallel» on the start form |
values.* |
values guessed by field name: dates, date formats, formats, numbers, texts ({unique} placeholder), locale, search, passwords, amounts, default text |
Configuration
page_audit: base_url: null # default: current request / framework.router.default_uri base_urls: [] # quick choices under the Base URL field of the start form, e.g. http://nginx; any http(s) address without query, fragment or credentials can also be typed role: ROLE_ADMIN layout: '@PageAudit/layout.html.twig' # a template with block page_audit_content cache_pool: cache.app # runs and metrics are kept here, no tables; data of deleted runs is removed automatically (registry page_audit_registry, «Stored data» on the list page with «Delete all» and «Reset all» — everything the audit keeps in the cache) transport: null concurrency: 1 block_external_http: true max_pages: 800 max_urls_per_route: 1 skip_routes: [] # added to built-in: _profiler, _wdt, page_audit_*, logout, login, token generation, password reset by e-mail link, Vite dev-server proxy, API Platform internal routes sandbox_request_attributes: {} simulation: databases: {} # see «Databases» database_pattern: null openapi: [] # list of sources, merged; default: detected from routes (/api/doc.json) # /api/doc.json — URL of the application # https://…/openapi.json — external URL # config/openapi/api.yaml — file (JSON or YAML, relative to the project) # config/openapi — folder: every *.json, *.yaml, *.yml inside, recursively # config/openapi/*.yaml — glob pattern guess_attempts: 5 fix_attempts: 4 skip_routes: [] delete_routes: ['~(^|_)(delete|remove|destroy|revoke|reset|clear|purge)(_|$)~'] scenarios: {} thresholds: { time_warning_ms: 500, time_critical_ms: 1500, query_warning: 30, query_critical: 100, … }
The web server and the crawler must share the cache pool (same environment), because the server writes the metrics of each request there.
Tests
tests/Functional/App is a small Symfony application with typical situations: attribute routes, plain AbstractControllers, an entity in the route, required query parameters that are not linked anywhere, #[MapQueryParameter] with an enum, a JSON API with #[MapRequestPayload] and getPayload(), a Symfony Form with CSRF, edit and delete, a service that reads $request->request, a session firewall with a login form and a stateless /api firewall, an external HTTP call, an exception, SQLite. It has no OpenAPI, except one endpoint whose allowed values exist only in openapi/.
tests/Integration/PageAuditRunTest.php prepares the application (schema, seed), starts it with php -S, makes a full audit with page-audit:run and checks every route, the not opened routes and that the source database is not changed — once without OpenAPI (api_stats must be reported as not opened) and once with the openapi/ folder (every route must pass).
composer install composer cs-fixer-check composer phpstan composer tests
The same checks run in GitHub Actions (.github/workflows/phpunit.yml) and Bitbucket Pipelines.
License
The PageAuditBundle is open-sourced software licensed under the MIT license.






