Enterprise Middleware
Audit Log Middleware
Signed, structured records of who did what, when and from where in your Kipchak API, with personal data redacted, written to Kafka, OpenSearch, NATS JetStream or the log.
Introduction
Note: This middleware is only available with Kipchak Enterprise.
Keeps an audit trail of your API: who did what, to what, when, from where, and whether it worked. SOC 2, ISO 27001, HIPAA and PCI DSS all ask for one, and an API without it is hard to sell to the organisations that have to pass those audits.
- Every change, recorded:
POST,PUT,PATCHandDELETErequests by default, with any route able to record a read (viewing a patient's record, say) or leave a request out. - Who, verified: the consumer and tenant come from Consumer Identity after authentication, so a record names the client the token was issued to. Refused requests (401, 403) are recorded too.
- What, in your terms: a controller adds the action (
order.refund), the target (order42) and details; the method, route pattern, arguments, query and body are recorded without being asked. - Personal data redacted: bodies, query strings, details and error messages go through the PII Redaction rules before they are written.
- Signed: each record can carry an HMAC-SHA256 signature over its contents, which anyone holding the key can check. An edited record shows. A deleted record does not, as each is signed alone.
- Delivered where your security team looks: Kafka, OpenSearch, NATS JetStream and the log, at once if you like. A sink that fails never fails the request, and its records are logged in full so none is lost.
Installation
To install this middleware, you need access to the Enterprise Composer repository at https://php.pkgs.1x.ax/.
composer require kipchak/middleware-audit
It depends on PII Redaction, which Composer installs with it. Add the driver for each sink you use (Kafka, OpenSearch or NATS) to drivers/drivers.php.
Copy the sample config to config/kipchak.audit.php and add the middleware in middlewares/middlewares.php after the authentication middlewares, before PII Redaction:
use Kipchak\Middleware\Audit\Audit;
use Kipchak\Middleware\Redaction\Redaction;
Error::initialise($app);
// The authentication middlewares, e.g. JWKS::initialise($app);
Audit::initialise($app);
Redaction::initialise($app);
Error::initialise($app); // last: answers exceptions from the middleware above
Slim runs the last-added middleware first, so the recorder runs before authentication and sees refused requests as well. To see who a request is really from, it also hooks the routes' invocation strategy, which runs after every middleware, route-level authentication included: the consumer recorded is the one the verified token names, and an exception is recorded before the Error middleware turns it into a 500.
Configuration
<?php
use function Kipchak\Core\env;
return [
'enabled' => true,
'methods' => ['POST', 'PUT', 'PATCH', 'DELETE'],
'paths' => ['*'],
'except_paths' => ['/health'],
'record' => [
'request_body' => true,
'response_body' => false,
'query' => true,
'headers' => ['x-request-id', 'user-agent'],
'max_body_bytes' => 64 * 1024,
],
// PII Redaction's 'logs' rules (field rules and detectors), 'responses', or false.
'redaction' => 'logs',
// At least 32 characters, kept secret; empty for unsigned records.
'signing_key' => env('AUDIT_SIGNING_KEY', ''),
'sinks' => [
['type' => 'kafka', 'connection' => 'default', 'topic' => 'audit'],
['type' => 'opensearch', 'connection' => 'default', 'index' => 'audit-{Y.m}', 'timeout' => 2],
['type' => 'nats', 'connection' => 'default', 'subject' => 'audit.{service}'],
// ['type' => 'sql', 'connection' => 'audit', 'table' => 'audit_log'], // a Doctrine driver connection; readable with Sql\AuditLog
['type' => 'log', 'level' => 'info'],
],
];
The config, and that each sink's driver connection exists, are checked when the worker starts.
The record
{
"id": "01a19201-4903-740b-8b62-c313668591e2",
"time": "2026-10-31T12:42:03.743691Z",
"service": "orders-api",
"action": "order.refund",
"outcome": "success",
"actor": { "consumer": "acme", "tenant": "org-1", "ip": "203.0.113.9", "user_agent": "pos/1.0" },
"target": { "type": "order", "id": "42" },
"request": {
"id": "req-7f3a",
"method": "POST",
"path": "/v1/orders/42/refund",
"route": "/v1/orders/{id}/refund",
"route_name": null,
"arguments": { "id": "42" },
"query": { "reason": "damaged" },
"headers": { "x-request-id": "req-7f3a", "user-agent": "pos/1.0" },
"body": { "amount": 25, "email": "j***@example.com", "card_number": "************4242" }
},
"response": { "status": 200, "duration_ms": 12.48, "body": null },
"error": null,
"details": { "amount": 25.0 },
"signature": "hmac-sha256:5c1f..."
}
idis a UUID version 7, so records sort by time. Sinks use it to make retries idempotent.outcomeissuccess(below 400),denied(401 or 403),failure(other 4xx) orerror(5xx, or an exception).actiondefaults to the method and route pattern, such asPOST /v1/orders/{id}/refund.actor.consumerandactor.tenantare the verified identity where the route ran. For a request refused before that, they are whatever the request itself carries (an API key or a header); a JWT that was refused names no one.actor.ipis the connecting address. With Subashi Pro installed,client_ip(the same settings Subashi Pro takes) reads forwarding headers from trusted proxies.errorholds the exception's class and redacted message.
Describing what happened
use Kipchak\Middleware\Audit\Entry;
public function refund(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
// ...
Entry::of($request)?->action('order.refund')->target('order', $args['id'])->detail('amount', $amount);
return Http\Response::json($response, $refund);
}
Entry::of($request)?->force()->action('patient.view')->target('patient', $id); // record a read
Entry::of($request)?->skip(); // leave this one out
Entry::of() returns null when the middleware is not running, hence the ?->.
Sinks
Every record goes to every sink.
| Sink | Settings | Delivery |
|---|---|---|
kafka | connection, topic | Queued in librdkafka and delivered in the background, so a slow cluster never slows a request. Keyed by consumer, so one consumer's records stay in order. |
opensearch | connection, index (a date in braces, PHP date() format, UTC: audit-{Y.m}), timeout (seconds, default 2) | One document per record, the record id as document id, written with op_type=create so it is never overwritten. |
nats | connection, subject (may contain {service}) | Published to JetStream and confirmed. The record id is the message id, so a retry is stored once. Needs a stream that captures the subject. |
sql | connection or service, table (default audit_log), create_table (default false), columns, busy_timeout (ms, default 5000) | One row per record, through Doctrine DBAL: indexed columns to filter by, and the record exactly as signed. A retried record is stored once. Read it back with Sql\AuditLog. |
log | level (default info) | Through the Logger driver, on the audit channel, under audit_record, for a log shipper to route. |
service | key | Your own container entry implementing Kipchak\Middleware\Audit\Sink\Sink. MemorySink is there for your tests. |
When a sink fails, the request carries on and the record is logged at error level, in full under audit_record, with the message Audit record was not delivered, so it can be found and replayed. The sink is then skipped for retry_after seconds (default 30, set per sink), its records going straight to the log, so an unreachable sink does not add a timeout to every request. Kafka reports a failure later, from its delivery report, and it is logged the same way.
For OpenSearch, map the record's string fields as keyword with an index template, so id, actor.consumer and target.id can be searched exactly, and use Index State Management to roll indices over and keep them read-only. Use kipchak/driver-opensearch 1.13 or later: earlier versions kept the OpenSearch client's default connection pool, which, in a long-lived worker, refused a node for 120 seconds to an hour after a single failure.
The SQL sink
For an API that reads its own audit trail back, such as an access log on an administrator's screen (kipchak/middleware-audit 1.5 and later, with kipchak/driver-doctrine 1.53 for SQLite):
// config/kipchak.doctrine.php
'dbal' => ['enabled' => true, 'connections' => [
'audit' => ['driver' => 'pdo_sqlite', 'path' => '/data/app.db'], // or PostgreSQL, MySQL, ...
]],
// config/kipchak.audit.php
'sinks' => [
['type' => 'sql', 'connection' => 'audit', 'table' => 'access_log', 'create_table' => true],
],
create_table creates the table and its indexes if they are absent, and adds any index that is missing from an existing table; it is safe when several workers start at once on a new database (since 1.7). It is off by default, so that nothing creates a schema in a server database unless asked; to create it in your own migrations, take its definition from Kipchak\Middleware\Audit\Sql\Table::schema('access_log'). service names a container entry returning a Doctrine\DBAL\Connection, instead of a Doctrine driver connection.
Each row has these columns, filled from the record, and record, the record as signed:
| Column | From the record |
|---|---|
at | time, as UTC text that sorts in time order (2026-11-07T10:15:30.123456Z) |
service | service |
subject | actor.consumer |
name, roles | details.name and details.roles (JSON), which your route adds: Entry::of($request)?->detail('name', $name)->detail('roles', $roles) |
action | action |
target | target, as type:id |
result | outcome |
status | response.status |
source | actor.ip |
columns fills a column from another field, as a dot path, or leaves it empty with null: 'columns' => ['subject' => 'details.user_id'].
With SQLite, the sink waits up to busy_timeout milliseconds for another writer instead of failing with "database is locked", and switches the file to write-ahead logging, so several PHP workers can write to one file at once.
Read the table back with AuditLog:
use Kipchak\Driver\Doctrine\Doctrine;
use Kipchak\Middleware\Audit\Sql\AuditLog;
$log = new AuditLog(Doctrine::get('dbal.audit'), 'access_log', $signingKey, Logger::get());
$page = $log->query(['subject' => 'user-42', 'result' => 'denied', 'from' => '2026-11-01'], limit: 50);
foreach ($page->records as $entry) {
$entry->columns; // at, subject, name, roles, action, ...
$entry->record; // the record as signed
$entry->verified; // true, false (with $entry->problem), or null without a signing key
}
$next = $log->query([...], limit: 50, before: $page->next); // the following page, null on the last
$log->get($recordId);
$log->prune(new DateTimeImmutable('-400 days')); // retention: returns how many were deleted
$log->prune(new DateTimeImmutable('-400 days'), batchSize: 10000);
By default, prune() is one delete, which holds writers up for as long as it takes. With a batchSize (from 1.6), rows go in batches that each commit, so writers get a turn between them, and on SQLite a checkpoint follows each. If a batch fails, Sql\PruneFailed is thrown: its deleted says how many went, and those stay deleted, so run it again to continue.
The filters are subject, action, result, service, target, status, source, from and to, newest first. Every record read is checked: its signature against the key, and its columns against the signed record, so a row edited in the database is reported. A record that fails is returned all the same, with verified false and the reason, counted in $page->failures and logged at warning: it is never left out. prune() is the only way rows are deleted; nothing updates them.
Refusing reads that cannot be recorded
Where access itself must be on the record, a report for instance, name the paths under require_recorded, from 1.6. It is off unless rules are listed, and nothing changes for any other path:
'require_recorded' => [
['paths' => ['/v1/reports', '/v1/reports/*'], 'methods' => ['GET'], 'sinks' => ['sql:audit']],
],
On those paths the response is served only if each named sink took the record:
- A write that fails replaces the response with a 503 in the standard error envelope, with
Retry-AfterandCache-Control: no-storeand nothing of the response it replaces. - While a named sink is being skipped after a failure, the route does not run, and the request gets the same 503.
- A record that cannot be built is refused in the same way.
- The record goes to the log at error level, as for any failed sink, and a second error says the response was refused.
A named path is recorded whatever methods and paths say, and a route cannot leave it out with Entry::skip(). Name a sink as type:connection, or service:key for a custom one, which must match exactly one configured sink. HEAD follows a rule for GET.
The API fails at boot for a rule that would not do what it says:
- A method other than GET and HEAD. The record is written after the route has run, so a refusal could not undo a change.
- The
logsink, because a log alone does not count as recorded, or thekafkasink, whose delivery is confirmed only after the response has been decided. Aservicesink is taken at its word:emit()must throw if the record is not stored. - A path that
except_pathsleaves out,enabled => false,record.response_bodyon, which would put the refused content in the log, or no Logger driver.
The skip is per worker, for each sink's retry_after seconds, so a worker that saw a failure refuses for that long after the sink recovers, while others may already be serving. Put this middleware outside anything that can answer without it, such as a response cache, or a cached response will be served with no record.
Verifying records
With a signing_key, each record's signature is an HMAC-SHA256 over its canonical JSON (keys sorted at every level). Checking a stored record:
use Kipchak\Middleware\Audit\Record\Signature;
Signature::verify($recordFromOpenSearch, $key); // the decoded record, or its JSON exactly as stored
A changed field, a removed field or a different key gives false. Keep the key out of the systems that store the records, so that whoever can change a record cannot re-sign it.
Limits
- The SQL sink detects an edited row, not a deleted one. Each record is signed on its own, and
prune()deletes rows by design, so a row removed from the table leaves no trace. Detecting deletion needs a chained or anchored log, which this sink does not provide; keep the log sink, or another sink, on beside it if records must also be held somewhere the database's administrators cannot reach. - The record is written after the route has run. If every sink fails, the action has still happened; the record is then only in the log.
require_recordedrefuses reads in that case, not changes. - Request bodies are taken from the parsed body (JSON and form bodies). Bodies over
max_body_bytesare noted with their size, not copied. - Before 1.2, routes that are
RequestHandlerInterfaceobjects bypassed the invocation strategy, and their records had only the identity the request itself carries. From 1.2 they are captured like any other route.
Performance
A record costs one JSON encoding, the redaction of the request body, and the sinks' own time: microseconds for the log and Kafka, a round trip for NATS and OpenSearch. In testing on the Kipchak Enterprise runtime in worker mode, 2,400 concurrent requests wrote 2,400 records to Kafka, OpenSearch and NATS at once: the same records in all three, each exactly once, every signature valid. With OpenSearch stopped mid-traffic, requests carried on at full speed and its records went to the log.
Git Repository
The source code is included in the package, which a Kipchak Enterprise licence installs from the Kipchak registry.