Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Changelog

All notable changes to this project are documented here. The format is based on
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## [Unreleased]

### Added
- Object traversal in the masking engine (`JsonSerializable`, `Stringable`, public
properties), with object-cycle protection — secrets carried by objects in the
context are no longer leaked.
- Log **message** masking in `MaskingProcessor` (on by default).
- `SegmentKeyMatcher`: segment-aware key matching that catches compound/nested
keys (`db_password`, `userToken`, `x-api-key`) without false positives like
`tokenizer`.
- `CreditCardMatcher`: Luhn-validated card detection (replaces the broad
digit-run regex, removing false positives on timestamps/identifiers).
- `ChainValueMatcher` to compose value matchers.
- `ValueMatcherInterface::redact()` for sub-string masking (only the matched
token is masked, surrounding text is preserved).
- Integer values are now scanned by the value matcher.
- Builder options: `matchKeysExactly()`, `maskMessage()`, `traverseObjects()`.
- Default value patterns for AWS access keys, Google API keys and PEM private-key
blocks.

### Changed
- **BREAKING**: minimum PHP version is now **8.2** (was 8.1).
- **BREAKING (defaults)**: secure-by-default — segment key matching, message
masking and object traversal are now on by default; value matching masks only
the matched sub-string instead of the whole value. Use `matchKeysExactly()`,
`maskMessage(false)` and `traverseObjects(false)` to opt out.
- `ValueMatcherInterface` gained the `redact()` method (affects custom
implementations).

### Security
- Closes leak vectors found in audit: objects in context (H1), unmasked log
message (H2), unmatched non-string scalars (M1), compound key names (M2).
53 changes: 39 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
# 🛡️ Monolog Masker
<p align="center">
<img src="https://assets.tiime.fr/auth0-universal-login/apps/logo_tiime.svg" height="40px" alt="logo Tiime"><br>
Monolog Masker
</p>

![PHP Version](https://img.shields.io/badge/PHP-8.2%2B-777BB4.svg?style=flat-square)
![Monolog Version](https://img.shields.io/badge/Monolog-3.x-blue.svg?style=flat-square)
Expand Down Expand Up @@ -31,24 +34,30 @@ use Monolog\Logger;
use Tiime\MonologMasker\MaskerBuilder;

$logger = new Logger('app');
// Push FIRST so Monolog runs it LAST — see "Processor ordering" below.
$logger->pushProcessor(MaskerBuilder::create()->buildProcessor());

$logger->info('payment', [
'db_password' => 'super-secret',
'card_number' => '4242 4242 4242 4242',
'token' => 'super-secret',
'amount' => 1000,
]);
// context becomes:
// ['card_number' => '████████', 'token' => '████████', 'amount' => 1000]
// ['db_password' => '████████', 'card_number' => '████████', 'amount' => 1000]
```

The processor walks `context` and `extra` recursively and masks two things:
The processor walks `message`, `context` and `extra` and masks, **secure by default**:

- **Sensitive keys** — values whose key matches a known sensitive name
(`password`, `token`, `api_key`, `authorization`, …). The whole sub-tree under
a sensitive key is collapsed, so nested secrets cannot slip through.
- **Sensitive values** — leaf strings that *look* like a secret or PII (email,
credit card, IBAN, JWT, `Bearer …`, Stripe-style keys), regardless of their key.
- **Sensitive keys** — values whose key contains a known sensitive *segment*
(`password`, `token`, `api_key`, `authorization`, …). Matching is segment-aware,
so compound names like `db_password`, `userToken` or `x-api-key` are caught too
(but not `tokenizer`). The whole sub-tree under a sensitive key is collapsed.
- **Sensitive values** — tokens that *look* like a secret or PII (email, IBAN, JWT,
`Bearer …`, AWS/Google keys, PEM blocks, and **Luhn-validated** card numbers),
wherever they appear — including the log **message**. Only the matched
sub-string is masked, so surrounding text is preserved.
- **Objects** in the context are traversed too (`JsonSerializable`, `Stringable`,
or public properties), so secrets carried by DTOs don't slip through unmasked.

## ⚙️ Configuration

Expand All @@ -72,7 +81,22 @@ Other knobs:

- `withKeyMatcher()` / `withValueMatcher()` — replace detection entirely with
your own `KeyMatcherInterface` / `ValueMatcherInterface`.
- `withoutValueMatching()` — key-based masking only (skip the regex pass).
- `withoutValueMatching()` — key-based masking only (skip value detection).
- `matchKeysExactly()` — whole-string key matching instead of segment-aware
(no compound-key detection, fewer false positives).
- `maskMessage(false)` — stop masking the log message.
- `traverseObjects(false)` — leave objects untouched.

### Processor ordering

Monolog runs processors in **reverse** of their push order. To also mask the
`extra` data added by other processors (e.g. `WebProcessor`), push the masker
**first** so it runs **last**.

### Depth limit

Recursion is bounded by `maxDepth` (default 16); anything deeper — and any object
cycle — is replaced with `[TRUNCATED]` rather than traversed.

### Masking strategies

Expand All @@ -89,12 +113,13 @@ you can implement `MaskStrategyInterface` for anything else.
The masking engine is decoupled from Monolog so it can be tested and reused on
its own:

- `Masker` — recursive, immutable engine (never mutates its input; bounded by a
configurable max depth that also guards against self-referential arrays).
- `Masker` — recursive, immutable engine (never mutates its input; traverses
arrays and objects; bounded by a max depth that also guards against cycles).
- `MaskingProcessor` — thin Monolog adapter (`ProcessorInterface`).
- `Matcher\*` — pluggable key/value detection (`KeyListMatcher`, `RegexValueMatcher`).
- `Matcher\*` — pluggable detection: keys (`KeyListMatcher`, `SegmentKeyMatcher`)
and values (`RegexValueMatcher`, `CreditCardMatcher`, `ChainValueMatcher`).
- `Strategy\*` — pluggable masking (`FullMaskStrategy`, `PartialMaskStrategy`).
- `MaskerBuilder` — fluent factory tying it all together with sane defaults.
- `MaskerBuilder` — fluent factory tying it all together with secure defaults.

## ✅ Development

Expand Down
10 changes: 10 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@
"type": "library",
"license": "MIT",
"keywords": ["monolog", "logging", "security", "gdpr", "masking", "pii", "secrets"],
"authors": [
{
"name": "Tiime platform-dev",
"homepage": "https://github.com/Tiime-Software"
}
],
"support": {
"issues": "https://github.com/Tiime-Software/MonologMasker/issues",
"source": "https://github.com/Tiime-Software/MonologMasker"
},
"require": {
"php": ">=8.2",
"monolog/monolog": "^3.0"
Expand Down
14 changes: 13 additions & 1 deletion infection.json.dist
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,19 @@
"directories": ["src"]
},
"mutators": {
"@default": true
"@default": true,
"CastInt": {
"ignore": ["Tiime\\MonologMasker\\Matcher\\CreditCardMatcher::passesLuhn"]
},
"GreaterThan": {
"ignore": ["Tiime\\MonologMasker\\Matcher\\CreditCardMatcher::passesLuhn"]
},
"PlusEqual": {
"ignore": ["Tiime\\MonologMasker\\Matcher\\CreditCardMatcher::passesLuhn"]
},
"UnwrapArrayValues": {
"ignore": ["Tiime\\MonologMasker\\Matcher\\ChainValueMatcher::__construct"]
}
},
"logs": {
"text": "build/infection.log"
Expand Down
16 changes: 13 additions & 3 deletions src/Config/DefaultValuePatterns.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,26 @@ final class DefaultValuePatterns
// "Bearer <token>" / "Basic <token>" authorization values.
'bearer' => '/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+\/\-]+=*/i',

// 13-to-16 digit card numbers, optionally grouped by spaces or dashes.
'credit_card' => '/\b(?:\d[ \-]?){12,18}\d\b/',

// IBAN (2 letters + 2 check digits + up to 30 alphanumerics).
'iban' => '/\b[A-Z]{2}\d{2}[A-Z0-9]{11,30}\b/',

// Stripe-style secret/restricted keys.
'api_secret_key' => '/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b/',

// AWS access key id.
'aws_access_key' => '/\bAKIA[0-9A-Z]{16}\b/',

// Google API key.
'google_api_key' => '/\bAIza[0-9A-Za-z_\-]{35}\b/',

// PEM-encoded private key block header.
'pem_private_key' => '/-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/',
];

// Card numbers are detected separately (with a Luhn check) by
// {@see \Tiime\MonologMasker\Matcher\CreditCardMatcher} to avoid the false
// positives a plain digit-run regex would cause.

/**
* @return array<string, string>
*/
Expand Down
116 changes: 93 additions & 23 deletions src/Masker/Masker.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,21 @@
use Tiime\MonologMasker\Strategy\MaskStrategyInterface;

/**
* Framework-agnostic masking engine. It walks an array recursively and masks:
* Framework-agnostic masking engine. It walks a structure recursively and masks:
*
* - any value whose key is flagged sensitive by the {@see KeyMatcherInterface}
* (the whole sub-tree is replaced, so nested secrets cannot leak);
* - any leaf string flagged sensitive by the optional {@see ValueMatcherInterface}.
* - any sensitive token inside a leaf string/number flagged by the optional
* {@see ValueMatcherInterface} (sub-string masking, the rest is preserved).
*
* The input array is never mutated — {@see mask()} returns a fresh copy.
* Objects are traversed too (unless disabled): {@see \JsonSerializable} via its
* serialized form, {@see \Stringable} via its string form, and plain objects via
* their public properties — matching how Monolog would otherwise serialise them,
* so secrets they carry cannot slip through unmasked.
*
* Recursion is bounded by a configurable maximum depth; branches deeper than
* that are replaced with a truncation marker rather than traversed, which also
* protects against self-referential arrays.
* The input is never mutated — {@see mask()} returns a fresh copy. Recursion is
* bounded by a configurable maximum depth (branches beyond it become a
* truncation marker), and object cycles are tracked to avoid infinite loops.
*/
final class Masker implements MaskerInterface
{
Expand All @@ -30,6 +34,7 @@ public function __construct(
private readonly ?ValueMatcherInterface $valueMatcher,
private readonly MaskStrategyInterface $strategy,
private readonly int $maxDepth = 16,
private readonly bool $traverseObjects = true,
) {
if ($maxDepth < 1) {
throw new \InvalidArgumentException('The maximum depth must be at least 1.');
Expand All @@ -38,51 +43,116 @@ public function __construct(

public function mask(array $data): array
{
return $this->process($data, 1);
return $this->processArray($data, 1, new \SplObjectStorage());
}

/**
* @param array<array-key, mixed> $data
* Masks every sensitive token inside a standalone string (e.g. a log
* message). Returns it unchanged when value matching is disabled.
*/
public function maskString(string $value): string
{
return $this->valueMatcher?->redact($value, $this->strategy) ?? $value;
}

/**
* @param array<array-key, mixed> $data
* @param \SplObjectStorage<object, mixed> $seen
*
* @return array<array-key, mixed>
*/
private function process(array $data, int $depth): array
private function processArray(array $data, int $depth, \SplObjectStorage $seen): array
{
$masked = [];

foreach ($data as $key => $value) {
if ($this->keyMatcher->matches($key)) {
$masked[$key] = $this->maskValue($value);
$masked[$key] = $this->keyMatcher->matches($key)
? $this->maskValue($value)
: $this->processValue($value, $depth, $seen);
}

continue;
}
return $masked;
}

if (\is_array($value)) {
$masked[$key] = $depth >= $this->maxDepth
? self::TRUNCATED
: $this->process($value, $depth + 1);
/**
* @param \SplObjectStorage<object, mixed> $seen
*/
private function processValue(mixed $value, int $depth, \SplObjectStorage $seen): mixed
{
if (\is_array($value)) {
return $depth >= $this->maxDepth
? self::TRUNCATED
: $this->processArray($value, $depth + 1, $seen);
}

if (\is_object($value)) {
return $this->processObject($value, $depth, $seen);
}

continue;
return $this->maskLeaf($value);
}

/**
* @param \SplObjectStorage<object, mixed> $seen
*/
private function processObject(object $value, int $depth, \SplObjectStorage $seen): mixed
{
if (!$this->traverseObjects) {
return $value;
}

if ($value instanceof \JsonSerializable) {
if ($seen->contains($value)) {
return self::TRUNCATED;
}

$masked[$key] = $this->maskLeaf($value);
$seen->attach($value);
$masked = $this->processValue($value->jsonSerialize(), $depth, $seen);
$seen->detach($value);

return $masked;
}

if ($value instanceof \Stringable) {
return $this->maskLeaf((string) $value);
}

if ($seen->contains($value)) {
return self::TRUNCATED;
}

if ($depth >= $this->maxDepth) {
return self::TRUNCATED;
}

$seen->attach($value);
$masked = $this->processArray(get_object_vars($value), $depth + 1, $seen);
$seen->detach($value);

return $masked;
}

/**
* Masks a leaf (non-array) value when it is a string flagged by the value
* matcher; otherwise returns it untouched.
* Masks sensitive tokens inside a leaf: sub-string masking for strings, and
* whole-value masking for an integer the matcher recognises. Other values
* are returned untouched.
*/
private function maskLeaf(mixed $value): mixed
{
if (null === $this->valueMatcher) {
return $value;
}

if (\is_string($value) && $this->valueMatcher->matches($value)) {
return $this->strategy->mask($value);
if (\is_string($value)) {
return $this->valueMatcher->redact($value, $this->strategy);
}

if (\is_int($value)) {
$string = (string) $value;

return $this->valueMatcher->matches($string)
? $this->strategy->mask($string)
: $value;
}

return $value;
Expand Down
5 changes: 5 additions & 0 deletions src/Masker/MaskerInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,9 @@ interface MaskerInterface
* @return array<array-key, mixed>
*/
public function mask(array $data): array;

/**
* Masks sensitive tokens inside a standalone string (e.g. a log message).
*/
public function maskString(string $value): string;
}
Loading
Loading