Scrubbing sensitive data
QuietGuard\Monitor\Support\Scrubber masks sensitive values by name before anything leaves the process. It is framework-agnostic. It walks arrays and, from version 0.3.1, also opens the strings that carry named values of their own: JSON written as a string, a URL.
Configuring keys
Pass the terms you want masked to the constructor. They are stored lower-cased, and a key matches as soon as its name contains one of them, case-insensitively:
use QuietGuard\Monitor\Support\Scrubber;
$scrubber = new Scrubber(['password', 'authorization', 'api_key', 'secret']);How it works
scrub(array $data): array walks the array recursively. When a key (a string key) contains one of the configured terms, its whole value is replaced with the mask constant; otherwise nested arrays are scrubbed in turn and, from version 0.3.1, a string value is read as well (see Strings that carry values).
$clean = $scrubber->scrub([
'user_id' => 42,
'password' => 'hunter2',
'headers' => [
'Authorization' => 'Bearer abc',
'Accept' => 'application/json',
],
]);
// [
// 'user_id' => 42,
// 'password' => '[scrubbed]',
// 'headers' => [
// 'Authorization' => '[scrubbed]', // matched case-insensitively
// 'Accept' => 'application/json',
// ],
// ]Notes on the behaviour:
- The mask is the public constant
Scrubber::MASK, which is'[scrubbed]'. - Matching is on names, never on the shape of a value: the name of a key and, from version 0.3.1, the name of a query parameter or of a JSON key found inside a string. The one exception is the token-shaped URL path segment described below. Recognising a value by its shape is the job of the other half.
- Matching is a case-insensitive substring check: the key name only has to contain a configured term, so a configured
passwordalso masksuser_passwordandPASSWORD_CONFIRMATION. - From version 0.3.1, a hyphen and an underscore count as the same character. Symfony's request, which Laravel uses too, names every header lower-cased with hyphens: the password of an HTTP Basic authentication arrives there as
php-auth-pwand an API key asx-api-key, whichphp_auth_pwandapi_keynow mask. - From version 0.3.1, a term that carries a hyphen or an underscore between two of its characters is also looked for without them, in a name stripped of its own:
api_keytherefore masksapikey(the header of Supabase and Kong),apiKey(a form field),x-apikeyandX-API-KEY. A term with no separator is compared as before, and a term that starts or ends with a separator, such as WordPress'sdb_, keeps its spelling: without it,dbwould maskfeedback. The cost is accepted: thelogged_inof the WordPress list also masksisLoggedInandloggedInAt. - A matched key has its entire value masked, whether that value is a scalar or a nested array.
- Numeric/list keys are never treated as sensitive; only string keys are compared.
Strings that carry values
From version 0.3.1, three kinds of string are opened, because they carry named values that no key of the array names.
A JSON object or array written as a string, such as the snapshot a Livewire component sends back with every request, is decoded, masked by key like any array, then written back. When nothing inside was masked, it goes out byte for byte as it came; when it held a secret and cannot be written back, it is replaced whole with the mask. When it does not decode, because it is cut short or because a mask by shape took the place of a number in it ([redacted:card]), it is replaced whole with the mask as soon as a quoted name followed by a : in it matches ("password":), compared as a key is, including after a stray quote that shifts the pairs; otherwise it goes out as it came.
A string that starts with an absolute URL, http or https, leading whitespace included, goes through scrubUrl(string $url): string, which you can also call directly:
- the value of every query-string parameter whose name matches is masked, and so is the value of every
name=valuepair of a fragment whose name matches (#access_token=...). The mask is encoded there,%5Bscrubbed%5D, so that the address stays an address; - from version 0.3.1, four parameter names are masked whatever the list holds, because an address carrying one is itself a credential until it expires:
hash(Symfony's login link, besideuserandexpires),_hash(the signature of Symfony'sUriSigner, beside_expiration),sig(Azure's shared access signature, SAS) andsignature. The name must be exact, compared decoded and regardless of case:hashtagorcontent_hashstay. The rule holds in an address only: an array key, a JSON key and a source line callinghash('sha256', ...)are not affected. The list is theScrubber::URL_CREDENTIALSconstant; - every path segment made of forty letters or digits in a row, or more, is masked outright, whatever the list says: that is where Laravel's password reset link (Breeze, Fortify, Jetstream) carries its token,
/reset-password/{token}. A number, a slug, a UUID or a ULID stays, since the path is what says where the application broke; - the scheme, the host, the port and the user of a
user:password@travel as they came; its password is masked (user:%5Bscrubbed%5D@), since a URL typed into a form field or a webhook setting carries it there. A credential written in place of the user (https://ghp_...@github.com) therefore stays, with the user. A password that contains an unencoded/,?or#is not recognised, since the address ends before it: write it percent-encoded (%2F,%3F,%23), as a URL requires; - the URL ends at the first whitespace, and the text after it is handed back as it came, except a pair opened by
&,?or#whose name matches: an address written by hand with an unencoded space (?q=hello world&token=abc) pushes the rest of its own query string there; - a relative address (
/reset?token=...), or a URL that does not open the string, is not reached.
$scrubber = new Scrubber(['token', 'signature']);
$scrubber->scrubUrl('https://shop.test/reset-password/'.$token.'?email=alex%40example.com');
// https://shop.test/reset-password/%5Bscrubbed%5D?email=alex%40example.com
$scrubber->scrubUrl('https://shop.test/reset?email=alex%40example.com&token=abc123&signature=9f8e7d');
// https://shop.test/reset?email=alex%40example.com&token=%5Bscrubbed%5D&signature=%5Bscrubbed%5DA string that starts with an address of another scheme, most often a DSN (mysql://root:secret@db/app, redis://:secret@cache:6379), leading whitespace included, has the password of its user:password@ masked the same way, and so is the value of every query-string parameter whose name matches, since a DSN writes its options there, a password among them (tcp://127.0.0.1:6379?password=..., which Predis reads). The token-shaped path segment rule stays the web's: a DSN's path is a database name or a file.
Source code lines
scrubLines(array $lines): array masks the lines of a code snippet, and scrubSnippets(array $frames): array applies it to the snippet (code.lines) each frame may carry. A line is replaced whole with the mask when an identifier containing a term of the list, or a word of Scrubber::LINE_NEEDLES (key, auth, credential, salt, private, dsn, bearer, sk_, pk_), is given a value:
- an assignment or a key separator:
=,=>or a single:($secret = '...','api_key' => '...'); - from version 0.3.1, an array index named in quotes and followed by
=($headers['Authorization'] = '...'); - a quoted name before a comma (
define('API_KEY', '...')); - a call whose first argument is a literal (
setApiKey('sk_live_...')).
A comparison by == or === with the name on the left counts as a value, for a variable as for an index (if ($token == $expected), if ($config['password'] === '...')): its other side may be the secret itself, written into the code. !=, !== and a comparison with the name on the right (if ('...' === $token)) do not count, and the line travels. A line that only uses the name stays: Hash::check($password, $hash), return csrf_token();, return $headers['Authorization'];. From version 0.3.1, :: is a scope and not a separator, so Auth::user() or TokenMismatchException::expired() stay too; version 0.3.0 masked those lines, the line of the throw included. From the same version, a term is also tried in its other spelling when a hyphen or an underscore inside it sits between two letters or digits, php_auth_pw and php-auth-pw, so that a hardcoded 'php-auth-pw' => '...' goes out masked. The line itself is never rewritten, and a term that starts or ends with a separator, such as WordPress's db_ or the words sk_ and pk_, keeps its one spelling: the other one starts or ends an ordinary word ('db-new', 'disk-usage' => 90).
From version 0.6.0, a line also goes whole when it hands a string literal to one of the calls of Scrubber::CREDENTIAL_CALLS, whose arguments are credentials whatever they are called: new PDO(...), new mysqli(...), mysqli_connect(...), mysqli_real_connect(...), mysql_connect(...), pg_connect(...), pg_pconnect(...), oci_connect(...), ldap_bind(...), ftp_login(...), imap_open(...), ssh2_auth_password(...), PHP 8.4's static factories PDO::connect(...) and Pdo\Mysql::connect(...), Pdo\Pgsql::connect(...), Pdo\Sqlite::connect(...) (and Odbc, Dblib, Firebird), and the ->real_connect(...) method. The password of a new PDO($dsn, 'root', 'hunter2') is a positional argument no list of names ever sees, and only the call says what it is. The literal has to be an argument of the call itself: new PDO($dsn, $user, $password) stays readable, as does new PDO($dsn, $user, env('DB_PASSWORD')), whose literal names a variable and not a secret. The arguments are read on the line of the call only; a call whose arguments continue on the next lines is read there alone.
Any other shape travels as it is: a literal that names none of these words, or an assignment through an index that is not in quotes ($data[$key] = '...').
Where it is applied
The Reporter runs the scrubber automatically:
reportException()scrubs the exception context and the snippet lines of its trace (scrubSnippets()) before sending.sendLogs()scrubs the logs array before sending. From version 0.3.1, the strings in it are opened like anywhere else, the message included: when it starts with a URL or is JSON, the values it carries are masked by the same rules, and the rest of its text is kept.sendDependencies()does not scrub: a dependency manifest contains package names and versions, not secrets.
If you build payloads yourself, call scrub() on the relevant array before handing it to a transport.
The other half: masking by shape
A key name never sees an address written into the free text of an error message, into a URL segment, or into a field somebody called reference. Support\ValueRedactor reads the value instead, and the Reporter runs it over the whole payload as the last thing before the wire, exceptions and logs alike.
It ships on, with every shape of ValueRedactor::PATTERNS. The personal data first: email, iban, nir, card and phone. Shapes carrying a check digit are verified rather than merely matched, so a sixteen digit order reference is not taken for a card number, and each mask names what it hid ([redacted:email]) so the message stays readable. Configure it through Config: redact selects the shapes, customRedactions adds your own.
From version 0.6.0, credentials, grouped in ValueRedactor::CREDENTIALS and recognised by the prefix their issuer stamps on them: stripe (sk_live_, sk_test_, rk_live_, rk_test_, whsec_), aws (an access key id: AKIA or ASIA followed by sixteen upper-case letters or digits) and aws_secret (the secret key, forty base64 characters with no prefix at all: alone it has the shape of any hash, so it is masked only within the eighty characters after an id just masked, or after the name aws_secret_access_key / aws_secret_key; the anchor stays, the forty characters go), github (ghp_, gho_, ghu_, ghs_, ghr_, github_pat_), gitlab (glpat-, glrt-, gldt-, gloas-, glptt-, glffct-, glimt-, glagent-, glcbt-, glsoat-, every prefix GitLab documents for a token it issues), slack (xox?-, xapp-, and the address of an incoming webhook https://hooks.slack.com/services/..., whose path is the secret: the host and /services/ stay, the three segments go), jwt (three base64url segments whose header decodes to JSON), private_key (a -----BEGIN ... PRIVATE KEY----- block, PGP block included, to its end or to the end of the text when it was cut), app_key (a Laravel APP_KEY, base64: and forty-four characters), project_key (a Quiet Guard project key, lm_ and forty characters) and aws_presigned (the signature of a presigned storage address, X-Amz-Signature= followed by sixty-four hex digits: the name, the host, the path and X-Amz-Credential stay readable, only the signature digits go; since version 0.8.0). The group runs before the personal shapes, because a token that starts with digits used to come out as [redacted:phone]. And url_password: the password of a user:password@host written into an address of any scheme, wherever it sits in the text (Connection to redis://u:[redacted:password]@cache:6379 failed), the scheme, the user and the host staying readable; the scrubber only read an address that opens the string, and an exception message never goes through it. A token written as a password keeps its own label. An ordinary word, a class name, a git hash or a UUID carries none of these prefixes and travels. The Quiet Guard server masks this same group on arrival, with this same code, on what an older client sends in clear. The slashes of the :// separator and of an application key may arrive escaped (\/), as json_encode() writes them; the user of an address may carry an @ (a mailer DSN's postmaster@domain) and is read up to the first :; the password may carry an @ or a / and runs to the last @ of the authority, each candidate @ having to be followed by a host and then a delimiter. The exact list every client shipped before version 0.6.0, ['email', 'iban', 'nir', 'card', 'phone'] in that order (ValueRedactor::LEGACY_DEFAULT), is read as the default it was: every published configuration carries it, and read literally it would have switched every credential shape off for everyone who followed the installation page.
From the same version, a percent-encoded value is read decoded. Laravel's fullUrl() and Symfony's getUri() rewrite the query string in RFC 3986 form, so an email typed into ?email= travels as jeanne.martin%40example.fr and a number written with spaces as 06%2012%2034%2056%2078: read as written, neither is the shape its pattern knows, and before version 0.6.0 they left in clear in the reported URL, as did a DSN or an application key passed as a parameter. The credentials are read as written first, then the text decoded where it is encoded, by every pattern, then the personal shapes as written: a token that follows %3D fails its own boundary check as written, and the phone shape would otherwise bite into its digits. An address passed as a parameter (next=, return_to=) has its own query encoded a second time (%2540 is an @ encoded twice), so the decoded text is decoded in turn, up to three levels. When a pattern matches, only the value is rewritten, the mask unencoded (?email=[redacted:email]) and every other byte as it was written, so the address keeps its keys, their order and its spelling, and a second pass changes nothing. A + stays a +: a form body quoted in a message with + for its spaces (phone=06+12+34+56+78) is not recognised. The server's credential net reads the same way. A card is looked for in every run of digit groups: the whole run when it holds thirteen to nineteen digits, failing that a span laid out as a card (groups of four, American Express 4-6-5, Diners 4-6-4), so a card followed by its expiry or preceded by a phone number is still found. The password of an address ends before the punctuation a sentence puts around it (), ,, ;, >, a backquote, a final .), and runs no longer than 256 characters.
From the same version, a masking failure withholds the field rather than sending it as it came. A value the PCRE engine could not read (a backtrack or recursion limit hit, bytes that are not the UTF-8 a pattern asked for) is replaced whole by ValueRedactor::UNSCANNABLE, [redacted:unscannable]: "could not read" and "nothing to mask" are not the same verdict, and the old behaviour handed back precisely the value nothing had read. A string over 64 KB (ValueRedactor::CHUNK_BYTES), formerly skipped whole, is read in pieces cut on the last line break of the window, failing that on the last space, failing that on the last byte outside the token alphabet; no one-line shape straddles a cut, and the key block, the one shape that spans lines, is read on the whole text first. A customRedactions pattern that does not compile is dropped at construction: that is a configuration error, not an unreadable value, and the field is read by every other pattern. A cut never falls between the bytes of one character, or a pattern written with /u failed on the piece.
The bound also comes BEFORE masking, softly (Cut::before(), which the Reporter applies): a message cut hard at its limit before masking let the first half of a token straddling the cut leave in clear, since a cut token no longer has its minimum length. Cut::soft() cuts on the first whitespace past the limit (within the 4096 characters after it, Cut::SLACK), masking reads whole tokens, and Cut::payload() then cuts hard on text already masked. A context whose JSON encoding exceeds the 65 535 bytes the server keeps (Cut::LIMITS['context']) is replaced before masking by the marker the server would write, environment, release and occurred_at kept: scanning several megabytes the server will drop costs the failing request for nothing, and replacing the whole cuts through no value.
You are reading the PHP Core v1.0 documentation.