From a28d25ff5900aa363802df0ed4a57eb119066e7a Mon Sep 17 00:00:00 2001 From: rflavien Date: Fri, 29 May 2026 17:29:35 +0200 Subject: [PATCH 1/2] fix(masker): close audit leak vectors, secure by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remediates the audit findings on real-world leak paths: - H1: traverse objects (JsonSerializable / Stringable / public props) with cycle protection — secrets carried by objects no longer leak. - H2: mask the log message (on by default). - M1: scan integer values, not just strings. - M2: SegmentKeyMatcher catches compound keys (db_password, userToken, x-api-key) while avoiding false positives like "tokenizer". - M3: sub-string masking via ValueMatcherInterface::redact() — only the matched token is masked, surrounding text is preserved. - M4: CreditCardMatcher with Luhn validation replaces the broad digit-run regex; added AWS / Google / PEM patterns. Behaviour is now secure by default (segment keys, message masking, object traversal); opt out via matchKeysExactly(), maskMessage(false), traverseObjects(false). Minimum PHP bumped to 8.2 (required by the property-test tooling). Quality gates kept green: PHPStan max, 100% coverage, Infection MSI 100%, black-box property suite. Docs and CHANGELOG updated. Co-Authored-By: Claude Opus 4.8 (1M context) --- CHANGELOG.md | 37 +++++ README.md | 48 ++++-- composer.json | 10 ++ infection.json.dist | 14 +- src/Config/DefaultValuePatterns.php | 16 +- src/Masker/Masker.php | 116 ++++++++++++--- src/Masker/MaskerInterface.php | 5 + src/MaskerBuilder.php | 80 ++++++++-- src/Matcher/ChainValueMatcher.php | 45 ++++++ src/Matcher/CreditCardMatcher.php | 75 ++++++++++ src/Matcher/RegexValueMatcher.php | 18 +++ src/Matcher/SegmentKeyMatcher.php | 107 ++++++++++++++ src/Matcher/ValueMatcherInterface.php | 12 ++ src/Processor/MaskingProcessor.php | 9 +- tests/Masker/MaskerTest.php | 181 ++++++++++++++++++++++- tests/MaskerBuilderTest.php | 111 +++++++++++++- tests/Matcher/ChainValueMatcherTest.php | 46 ++++++ tests/Matcher/CreditCardMatcherTest.php | 78 ++++++++++ tests/Matcher/RegexValueMatcherTest.php | 26 +++- tests/Matcher/SegmentKeyMatcherTest.php | 100 +++++++++++++ tests/Processor/MaskingProcessorTest.php | 37 +++++ tests/Property/Generators.php | 15 +- tests/Property/MaskerPropertyTest.php | 23 ++- tests/Property/MatcherPropertyTest.php | 42 +++++- 24 files changed, 1182 insertions(+), 69 deletions(-) create mode 100644 CHANGELOG.md create mode 100644 src/Matcher/ChainValueMatcher.php create mode 100644 src/Matcher/CreditCardMatcher.php create mode 100644 src/Matcher/SegmentKeyMatcher.php create mode 100644 tests/Matcher/ChainValueMatcherTest.php create mode 100644 tests/Matcher/CreditCardMatcherTest.php create mode 100644 tests/Matcher/SegmentKeyMatcherTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..0914857 --- /dev/null +++ b/CHANGELOG.md @@ -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). diff --git a/README.md b/README.md index 7401410..ae76415 100644 --- a/README.md +++ b/README.md @@ -31,24 +31,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 @@ -72,7 +78,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 @@ -89,12 +110,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 diff --git a/composer.json b/composer.json index 54efd1d..69a6f79 100644 --- a/composer.json +++ b/composer.json @@ -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/ManakinCubber" + } + ], + "support": { + "issues": "https://github.com/ManakinCubber/monolog-masker/issues", + "source": "https://github.com/ManakinCubber/monolog-masker" + }, "require": { "php": ">=8.2", "monolog/monolog": "^3.0" diff --git a/infection.json.dist b/infection.json.dist index 3d38063..b9d3436 100644 --- a/infection.json.dist +++ b/infection.json.dist @@ -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" diff --git a/src/Config/DefaultValuePatterns.php b/src/Config/DefaultValuePatterns.php index e59754b..60da0b5 100644 --- a/src/Config/DefaultValuePatterns.php +++ b/src/Config/DefaultValuePatterns.php @@ -24,16 +24,26 @@ final class DefaultValuePatterns // "Bearer " / "Basic " 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 */ diff --git a/src/Masker/Masker.php b/src/Masker/Masker.php index 1b5f62e..6282021 100644 --- a/src/Masker/Masker.php +++ b/src/Masker/Masker.php @@ -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 { @@ -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.'); @@ -38,42 +43,99 @@ public function __construct( public function mask(array $data): array { - return $this->process($data, 1); + return $this->processArray($data, 1, new \SplObjectStorage()); } /** - * @param array $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 $data + * @param \SplObjectStorage $seen * * @return array */ - 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 $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 $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 { @@ -81,8 +143,16 @@ private function maskLeaf(mixed $value): mixed 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; diff --git a/src/Masker/MaskerInterface.php b/src/Masker/MaskerInterface.php index d1907ef..063c689 100644 --- a/src/Masker/MaskerInterface.php +++ b/src/Masker/MaskerInterface.php @@ -17,4 +17,9 @@ interface MaskerInterface * @return array */ public function mask(array $data): array; + + /** + * Masks sensitive tokens inside a standalone string (e.g. a log message). + */ + public function maskString(string $value): string; } diff --git a/src/MaskerBuilder.php b/src/MaskerBuilder.php index a479692..b164854 100644 --- a/src/MaskerBuilder.php +++ b/src/MaskerBuilder.php @@ -5,22 +5,27 @@ namespace Tiime\MonologMasker; use Tiime\MonologMasker\Masker\Masker; +use Tiime\MonologMasker\Matcher\ChainValueMatcher; +use Tiime\MonologMasker\Matcher\CreditCardMatcher; use Tiime\MonologMasker\Matcher\KeyListMatcher; use Tiime\MonologMasker\Matcher\KeyMatcherInterface; use Tiime\MonologMasker\Matcher\RegexValueMatcher; +use Tiime\MonologMasker\Matcher\SegmentKeyMatcher; use Tiime\MonologMasker\Matcher\ValueMatcherInterface; use Tiime\MonologMasker\Processor\MaskingProcessor; use Tiime\MonologMasker\Strategy\FullMaskStrategy; use Tiime\MonologMasker\Strategy\MaskStrategyInterface; /** - * Fluent factory wiring matchers, strategy and engine together with sensible - * defaults, so the common case is a one-liner: + * Fluent factory wiring matchers, strategy and engine together with + * secure-by-default settings, so the common case is a one-liner: * * $logger->pushProcessor(MaskerBuilder::create()->buildProcessor()); * - * Every default can be overridden. Methods return a new instance — the builder - * is immutable. + * Defaults: segment-aware key matching (catches `db_password`, `userToken`…), + * value matching with Luhn-validated card detection, message masking ON and + * object traversal ON. Each can be overridden; methods return a new instance + * (the builder is immutable). */ final class MaskerBuilder { @@ -36,6 +41,9 @@ private function __construct( private readonly array $additionalKeys = [], private readonly array $additionalPatterns = [], private readonly bool $valueMatchingEnabled = true, + private readonly bool $exactKeys = false, + private readonly bool $maskMessage = true, + private readonly bool $traverseObjects = true, ) { } @@ -62,6 +70,15 @@ public function withKeyMatcher(KeyMatcherInterface $matcher): self return $this->cloneWith(keyMatcher: $matcher); } + /** + * Matches keys by whole-string equality instead of the default segment + * matching (no compound-key detection, fewer false positives). + */ + public function matchKeysExactly(): self + { + return $this->cloneWith(exactKeys: true); + } + /** * Adds value patterns to the default pattern list. * @@ -73,7 +90,8 @@ public function withValuePatterns(array $patterns): self } /** - * Replaces the value matcher entirely (ignores the default patterns). + * Replaces the value matcher entirely (ignores the default patterns and + * card detection). */ public function withValueMatcher(ValueMatcherInterface $matcher): self { @@ -81,7 +99,7 @@ public function withValueMatcher(ValueMatcherInterface $matcher): self } /** - * Disables value-based (regex) detection; only key-based masking remains. + * Disables value-based detection; only key-based masking remains. */ public function withoutValueMatching(): self { @@ -98,26 +116,52 @@ public function maxDepth(int $maxDepth): self return $this->cloneWith(maxDepth: $maxDepth); } - public function buildMasker(): Masker + /** + * Toggles masking of the log message itself (default: on). + */ + public function maskMessage(bool $enabled = true): self { - $keyMatcher = $this->keyMatcher ?? KeyListMatcher::withDefaults($this->additionalKeys); + return $this->cloneWith(maskMessage: $enabled); + } - $valueMatcher = null; - if ($this->valueMatchingEnabled) { - $valueMatcher = $this->valueMatcher ?? RegexValueMatcher::withDefaults($this->additionalPatterns); - } + /** + * Toggles recursion into objects found in the context (default: on). When + * off, objects are left untouched (and serialised as-is by Monolog). + */ + public function traverseObjects(bool $enabled = true): self + { + return $this->cloneWith(traverseObjects: $enabled); + } + public function buildMasker(): Masker + { return new Masker( - $keyMatcher, - $valueMatcher, + $this->keyMatcher ?? $this->defaultKeyMatcher(), + $this->valueMatchingEnabled ? ($this->valueMatcher ?? $this->defaultValueMatcher()) : null, $this->strategy ?? new FullMaskStrategy(), $this->maxDepth, + $this->traverseObjects, ); } public function buildProcessor(): MaskingProcessor { - return new MaskingProcessor($this->buildMasker()); + return new MaskingProcessor($this->buildMasker(), $this->maskMessage); + } + + private function defaultKeyMatcher(): KeyMatcherInterface + { + return $this->exactKeys + ? KeyListMatcher::withDefaults($this->additionalKeys) + : SegmentKeyMatcher::withDefaults($this->additionalKeys); + } + + private function defaultValueMatcher(): ValueMatcherInterface + { + return new ChainValueMatcher( + RegexValueMatcher::withDefaults($this->additionalPatterns), + new CreditCardMatcher(), + ); } /** @@ -132,6 +176,9 @@ private function cloneWith( ?array $additionalKeys = null, ?array $additionalPatterns = null, ?bool $valueMatchingEnabled = null, + ?bool $exactKeys = null, + ?bool $maskMessage = null, + ?bool $traverseObjects = null, ): self { return new self( $keyMatcher ?? $this->keyMatcher, @@ -141,6 +188,9 @@ private function cloneWith( $additionalKeys ?? $this->additionalKeys, $additionalPatterns ?? $this->additionalPatterns, $valueMatchingEnabled ?? $this->valueMatchingEnabled, + $exactKeys ?? $this->exactKeys, + $maskMessage ?? $this->maskMessage, + $traverseObjects ?? $this->traverseObjects, ); } } diff --git a/src/Matcher/ChainValueMatcher.php b/src/Matcher/ChainValueMatcher.php new file mode 100644 index 0000000..98bfca7 --- /dev/null +++ b/src/Matcher/ChainValueMatcher.php @@ -0,0 +1,45 @@ + + */ + private readonly array $matchers; + + public function __construct(ValueMatcherInterface ...$matchers) + { + $this->matchers = array_values($matchers); + } + + public function matches(string $value): bool + { + foreach ($this->matchers as $matcher) { + if ($matcher->matches($value)) { + return true; + } + } + + return false; + } + + public function redact(string $value, MaskStrategyInterface $strategy): string + { + foreach ($this->matchers as $matcher) { + $value = $matcher->redact($value, $strategy); + } + + return $value; + } +} diff --git a/src/Matcher/CreditCardMatcher.php b/src/Matcher/CreditCardMatcher.php new file mode 100644 index 0000000..d37d289 --- /dev/null +++ b/src/Matcher/CreditCardMatcher.php @@ -0,0 +1,75 @@ +isCardNumber($candidate)) { + return true; + } + } + + return false; + } + + public function redact(string $value, MaskStrategyInterface $strategy): string + { + if ('' === $value) { + return $value; + } + + return preg_replace_callback( + self::CANDIDATE, + fn (array $matches): string => $this->isCardNumber($matches[0]) + ? $strategy->mask($matches[0]) + : $matches[0], + $value, + ) ?? $value; + } + + private function isCardNumber(string $candidate): bool + { + // The candidate regex already constrains the run to 13–19 digits (only + // spaces/dashes as separators), so we just strip those and check Luhn. + return $this->passesLuhn(str_replace([' ', '-'], '', $candidate)); + } + + private function passesLuhn(string $digits): bool + { + $sum = 0; + $double = false; + + for ($i = \strlen($digits) - 1; $i >= 0; --$i) { + $digit = (int) $digits[$i]; + + if ($double) { + $digit *= 2; + if ($digit > 9) { + $digit -= 9; + } + } + + $sum += $digit; + $double = !$double; + } + + return 0 === $sum % 10; + } +} diff --git a/src/Matcher/RegexValueMatcher.php b/src/Matcher/RegexValueMatcher.php index eea78ae..bc72004 100644 --- a/src/Matcher/RegexValueMatcher.php +++ b/src/Matcher/RegexValueMatcher.php @@ -5,6 +5,7 @@ namespace Tiime\MonologMasker\Matcher; use Tiime\MonologMasker\Config\DefaultValuePatterns; +use Tiime\MonologMasker\Strategy\MaskStrategyInterface; /** * Matches a string value against a set of PCRE patterns. Patterns are validated @@ -58,4 +59,21 @@ public function matches(string $value): bool return false; } + + public function redact(string $value, MaskStrategyInterface $strategy): string + { + if ('' === $value) { + return $value; + } + + foreach ($this->patterns as $pattern) { + $value = preg_replace_callback( + $pattern, + static fn (array $matches): string => $strategy->mask($matches[0]), + $value, + ) ?? $value; + } + + return $value; + } } diff --git a/src/Matcher/SegmentKeyMatcher.php b/src/Matcher/SegmentKeyMatcher.php new file mode 100644 index 0000000..28bcb43 --- /dev/null +++ b/src/Matcher/SegmentKeyMatcher.php @@ -0,0 +1,107 @@ +> + */ + private readonly array $needles; + + /** + * @param list $keys + */ + public function __construct(array $keys) + { + $needles = []; + foreach ($keys as $key) { + $segments = self::segments($key); + if ([] !== $segments) { + $needles[] = $segments; + } + } + + $this->needles = $needles; + } + + /** + * @param list $additionalKeys + */ + public static function withDefaults(array $additionalKeys = []): self + { + return new self([...DefaultSensitiveKeys::all(), ...$additionalKeys]); + } + + public function matches(string|int $key): bool + { + if (\is_int($key)) { + return false; + } + + $haystack = self::segments($key); + if ([] === $haystack) { + return false; + } + + foreach ($this->needles as $needle) { + if (self::containsSequence($haystack, $needle)) { + return true; + } + } + + return false; + } + + /** + * @return list + */ + private static function segments(string $key): array + { + // Insert a space at camelCase boundaries (fooBar, XMLToken). + $spaced = preg_replace('/(?<=[a-z0-9])(?=[A-Z])/', ' ', $key) ?? $key; + $spaced = preg_replace('/(?<=[A-Z])(?=[A-Z][a-z])/', ' ', $spaced) ?? $spaced; + + $parts = preg_split('/[\s_\-.\/]+/', $spaced) ?: []; + + $segments = []; + foreach ($parts as $part) { + if ('' !== $part) { + $segments[] = mb_strtolower($part); + } + } + + return $segments; + } + + /** + * Whether $needle appears as a consecutive run inside $haystack. Both lists + * are joined with a delimiter so a plain substring search enforces the + * "whole segment, in order" rule (e.g. `token` matches `user/token` but not + * `tokenizer`). + * + * @param list $haystack + * @param list $needle + */ + private static function containsSequence(array $haystack, array $needle): bool + { + return str_contains( + '/'.implode('/', $haystack).'/', + '/'.implode('/', $needle).'/', + ); + } +} diff --git a/src/Matcher/ValueMatcherInterface.php b/src/Matcher/ValueMatcherInterface.php index bae15a1..6e2b3c2 100644 --- a/src/Matcher/ValueMatcherInterface.php +++ b/src/Matcher/ValueMatcherInterface.php @@ -4,11 +4,23 @@ namespace Tiime\MonologMasker\Matcher; +use Tiime\MonologMasker\Strategy\MaskStrategyInterface; + /** * Decides whether a scalar string value is sensitive on its own (e.g. it looks * like an email, a credit card number or a JWT), regardless of its key. */ interface ValueMatcherInterface { + /** + * Whether the value contains at least one sensitive token. + */ public function matches(string $value): bool; + + /** + * Returns the value with every sensitive token replaced by its masked + * form (sub-string masking). A value with no sensitive token is returned + * unchanged. + */ + public function redact(string $value, MaskStrategyInterface $strategy): string; } diff --git a/src/Processor/MaskingProcessor.php b/src/Processor/MaskingProcessor.php index 7f32027..bda31b7 100644 --- a/src/Processor/MaskingProcessor.php +++ b/src/Processor/MaskingProcessor.php @@ -10,7 +10,12 @@ /** * Thin Monolog adapter: runs the {@see MaskerInterface} over a record's - * `context` and `extra` before it reaches any handler. + * `context` and `extra` — and, when enabled (default), over the `message` + * itself — before it reaches any handler. + * + * Push this processor FIRST so Monolog runs it LAST: that way it also masks the + * `extra` data added by other processors (Monolog executes processors in + * reverse push order). * * LogRecord is immutable in Monolog 3, so a new record is returned via * {@see LogRecord::with()}. @@ -19,12 +24,14 @@ final class MaskingProcessor implements ProcessorInterface { public function __construct( private readonly MaskerInterface $masker, + private readonly bool $maskMessage = true, ) { } public function __invoke(LogRecord $record): LogRecord { return $record->with( + message: $this->maskMessage ? $this->masker->maskString($record->message) : $record->message, context: $this->masker->mask($record->context), extra: $this->masker->mask($record->extra), ); diff --git a/tests/Masker/MaskerTest.php b/tests/Masker/MaskerTest.php index 2640c5c..4c6ae81 100644 --- a/tests/Masker/MaskerTest.php +++ b/tests/Masker/MaskerTest.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\TestCase; use Tiime\MonologMasker\Masker\Masker; +use Tiime\MonologMasker\Matcher\CreditCardMatcher; use Tiime\MonologMasker\Matcher\KeyListMatcher; use Tiime\MonologMasker\Matcher\RegexValueMatcher; use Tiime\MonologMasker\Strategy\FullMaskStrategy; @@ -216,13 +217,183 @@ public function testMaxDepthOfOneTruncatesFirstNestedArray(): void self::assertSame(['a' => Masker::TRUNCATED], $result); } - public function testDoesNotMaskNonStringScalarValuesThatLookSensitive(): void + public function testLeavesScalarsNotRecognisedByTheMatcherUntouched(): void { - // Only string leaves are scanned by the value matcher: an integer that - // happens to look like a card number stays untouched. - $result = $this->masker()->mask(['card' => 4242424242424242]); + // This matcher (default regex patterns) does not recognise bare digit + // runs, so the integer passes through unchanged. + $result = $this->masker()->mask(['ref' => 4242424242424242]); - self::assertSame(['card' => 4242424242424242], $result); + self::assertSame(['ref' => 4242424242424242], $result); + } + + public function testMasksIntegerValueWhenTheMatcherRecognisesIt(): void + { + $masker = new Masker(new KeyListMatcher([]), new CreditCardMatcher(), new FullMaskStrategy(self::MASK)); + + self::assertSame(['card' => self::MASK], $masker->mask(['card' => 4242424242424242])); + } + + public function testMasksOnlyTheMatchedSubStringInAStringLeaf(): void + { + $result = $this->masker()->mask(['note' => 'mail john.doe@example.com ok']); + + self::assertSame(['note' => 'mail '.self::MASK.' ok'], $result); + } + + public function testTraversesObjectPublicProperties(): void + { + $object = new class { + public string $password = 'secret'; + public string $name = 'alice'; + }; + + self::assertSame( + ['u' => ['password' => self::MASK, 'name' => 'alice']], + $this->masker()->mask(['u' => $object]), + ); + } + + public function testTraversesJsonSerializableObjects(): void + { + $object = new class implements \JsonSerializable { + /** + * @return array + */ + public function jsonSerialize(): array + { + return ['token' => 'abc', 'x' => 1]; + } + }; + + self::assertSame( + ['o' => ['token' => self::MASK, 'x' => 1]], + $this->masker()->mask(['o' => $object]), + ); + } + + public function testMasksStringableObjectsByValue(): void + { + $object = new class implements \Stringable { + public function __toString(): string + { + return 'john.doe@example.com'; + } + }; + + self::assertSame(['o' => self::MASK], $this->masker()->mask(['o' => $object])); + } + + public function testGuardsAgainstObjectCycles(): void + { + $object = new class { + public string $name = 'loop'; + public ?object $self = null; + }; + $object->self = $object; + + self::assertSame( + ['o' => ['name' => 'loop', 'self' => Masker::TRUNCATED]], + $this->masker()->mask(['o' => $object]), + ); + } + + public function testDoesNotTraverseObjectsWhenDisabled(): void + { + $object = new \stdClass(); + $object->password = 'secret'; + $masker = new Masker( + new KeyListMatcher(['password']), + RegexValueMatcher::withDefaults(), + new FullMaskStrategy(self::MASK), + 16, + false, + ); + + self::assertSame($object, $masker->mask(['o' => $object])['o']); + } + + public function testMaskStringRedactsSensitiveTokens(): void + { + self::assertSame( + 'email '.self::MASK.' end', + $this->masker()->maskString('email john.doe@example.com end'), + ); + } + + public function testMaskStringReturnsValueUnchangedWithoutValueMatcher(): void + { + $masker = new Masker(new KeyListMatcher([]), null, new FullMaskStrategy(self::MASK)); + + self::assertSame('plain text', $masker->maskString('plain text')); + } + + public function testTruncatesObjectsBeyondMaxDepth(): void + { + $masker = new Masker(new KeyListMatcher([]), null, new FullMaskStrategy(self::MASK), 1); + + self::assertSame(['o' => Masker::TRUNCATED], $masker->mask(['o' => new \stdClass()])); + } + + public function testGuardsAgainstJsonSerializableCycles(): void + { + $object = new class implements \JsonSerializable { + /** + * @return array + */ + public function jsonSerialize(): array + { + return ['self' => $this]; + } + }; + + self::assertSame( + ['o' => ['self' => Masker::TRUNCATED]], + $this->masker()->mask(['o' => $object]), + ); + } + + public function testDetachesTraversedObjectsSoSiblingsAreNotTruncated(): void + { + $object = new class { + public string $name = 'ok'; + }; + + self::assertSame( + ['a' => ['name' => 'ok'], 'b' => ['name' => 'ok']], + $this->masker()->mask(['a' => $object, 'b' => $object]), + ); + } + + public function testDetachesJsonSerializableSoSiblingsAreNotTruncated(): void + { + $object = new class implements \JsonSerializable { + /** + * @return array + */ + public function jsonSerialize(): array + { + return ['token' => 'abc']; + } + }; + + self::assertSame( + ['a' => ['token' => self::MASK], 'b' => ['token' => self::MASK]], + $this->masker()->mask(['a' => $object, 'b' => $object]), + ); + } + + public function testCountsObjectDepthTowardsMaxDepth(): void + { + $object = new class { + /** @var array */ + public array $a = ['b' => ['c' => 'd']]; + }; + $masker = new Masker(new KeyListMatcher([]), null, new FullMaskStrategy(self::MASK), 3); + + self::assertSame( + ['root' => ['a' => ['b' => Masker::TRUNCATED]]], + $masker->mask(['root' => $object]), + ); } public function testDoesNotMutateNestedInput(): void diff --git a/tests/MaskerBuilderTest.php b/tests/MaskerBuilderTest.php index 9ba12c8..72ffecd 100644 --- a/tests/MaskerBuilderTest.php +++ b/tests/MaskerBuilderTest.php @@ -4,6 +4,8 @@ namespace Tiime\MonologMasker\Tests; +use Monolog\Level; +use Monolog\LogRecord; use PHPUnit\Framework\TestCase; use Tiime\MonologMasker\Masker\Masker; use Tiime\MonologMasker\MaskerBuilder; @@ -78,9 +80,10 @@ public function testWithValueMatcherReplacesDefaultPatterns(): void $result = $masker->mask(['a' => 'john.doe@example.com', 'b' => 'a secretword here']); - // Default email pattern is gone; only the custom pattern applies. + // Default email pattern is gone; only the custom pattern applies, and + // only the matched sub-string is masked. self::assertSame('john.doe@example.com', $result['a']); - self::assertSame('***', $result['b']); + self::assertSame('a *** here', $result['b']); } public function testWithValuePatternsAddsToDefaults(): void @@ -198,6 +201,110 @@ public function testLatestStrategyWins(): void self::assertSame(['password' => '***'], $result); } + public function testSegmentMatchingCatchesCompoundKeysByDefault(): void + { + $masker = MaskerBuilder::create() + ->withoutValueMatching() + ->withStrategy(new FullMaskStrategy('***')) + ->buildMasker(); + + $result = $masker->mask(['db_password' => 'x', 'userToken' => 'y', 'username' => 'z']); + + self::assertSame(['db_password' => '***', 'userToken' => '***', 'username' => 'z'], $result); + } + + public function testMatchKeysExactlyRestoresWholeStringMatching(): void + { + $masker = MaskerBuilder::create() + ->matchKeysExactly() + ->withoutValueMatching() + ->withStrategy(new FullMaskStrategy('***')) + ->buildMasker(); + + $result = $masker->mask(['db_password' => 'x', 'password' => 'y']); + + // Compound key no longer matched once exact matching is on. + self::assertSame(['db_password' => 'x', 'password' => '***'], $result); + } + + public function testDetectsLuhnValidCardByDefault(): void + { + $masker = MaskerBuilder::create()->withStrategy(new FullMaskStrategy('***'))->buildMasker(); + + self::assertSame(['ref' => '***'], $masker->mask(['ref' => '4242424242424242'])); + // A non-Luhn digit run is left alone. + self::assertSame(['ref' => '1234567890123'], $masker->mask(['ref' => '1234567890123'])); + } + + public function testObjectTraversalCanBeDisabled(): void + { + $object = new \stdClass(); + $object->password = 'secret'; + $masker = MaskerBuilder::create()->traverseObjects(false)->buildMasker(); + + self::assertSame($object, $masker->mask(['o' => $object])['o']); + } + + public function testMessageMaskingCanBeDisabledViaBuilder(): void + { + $processor = MaskerBuilder::create() + ->maskMessage(false) + ->withStrategy(new FullMaskStrategy('***')) + ->buildProcessor(); + + self::assertSame('mail john.doe@example.com', $processor($this->record())->message); + } + + public function testMasksMessageByDefaultViaBuilder(): void + { + $processor = MaskerBuilder::create()->withStrategy(new FullMaskStrategy('***'))->buildProcessor(); + + self::assertSame('mail ***', $processor($this->record())->message); + } + + public function testMessageMaskingCanBeReEnabledWithNoArgument(): void + { + $processor = MaskerBuilder::create() + ->maskMessage(false) + ->maskMessage() + ->withStrategy(new FullMaskStrategy('***')) + ->buildProcessor(); + + self::assertSame('mail ***', $processor($this->record())->message); + } + + public function testTraversesObjectsByDefaultViaBuilder(): void + { + $object = new \stdClass(); + $object->password = 'secret'; + $masker = MaskerBuilder::create()->withStrategy(new FullMaskStrategy('***'))->buildMasker(); + + self::assertSame(['o' => ['password' => '***']], $masker->mask(['o' => $object])); + } + + public function testObjectTraversalCanBeReEnabledWithNoArgument(): void + { + $object = new \stdClass(); + $object->password = 'secret'; + $masker = MaskerBuilder::create() + ->traverseObjects(false) + ->traverseObjects() + ->withStrategy(new FullMaskStrategy('***')) + ->buildMasker(); + + self::assertSame(['o' => ['password' => '***']], $masker->mask(['o' => $object])); + } + + private function record(): LogRecord + { + return new LogRecord( + datetime: new \DateTimeImmutable('@0'), + channel: 'app', + level: Level::Info, + message: 'mail john.doe@example.com', + ); + } + public function testDefaultMaxDepthIsSixteen(): void { $masker = MaskerBuilder::create()->buildMasker(); diff --git a/tests/Matcher/ChainValueMatcherTest.php b/tests/Matcher/ChainValueMatcherTest.php new file mode 100644 index 0000000..f7c7710 --- /dev/null +++ b/tests/Matcher/ChainValueMatcherTest.php @@ -0,0 +1,46 @@ +chain(); + + self::assertTrue($chain->matches('aaa')); + self::assertTrue($chain->matches('4242424242424242')); + self::assertFalse($chain->matches('zzz')); + } + + public function testRedactsWithEveryChildInTurn(): void + { + $masked = $this->chain()->redact('aaa and 4242424242424242', new FullMaskStrategy('***')); + + self::assertSame('*** and ***', $masked); + } + + public function testEmptyChainMatchesNothingAndRedactsNothing(): void + { + $chain = new ChainValueMatcher(); + + self::assertFalse($chain->matches('aaa')); + self::assertSame('aaa', $chain->redact('aaa', new FullMaskStrategy('***'))); + } +} diff --git a/tests/Matcher/CreditCardMatcherTest.php b/tests/Matcher/CreditCardMatcherTest.php new file mode 100644 index 0000000..bb0f148 --- /dev/null +++ b/tests/Matcher/CreditCardMatcherTest.php @@ -0,0 +1,78 @@ +matcher = new CreditCardMatcher(); + } + + /** + * @dataProvider validCards + */ + public function testMatchesLuhnValidCardNumbers(string $value): void + { + self::assertTrue($this->matcher->matches($value)); + } + + /** + * @return iterable + */ + public static function validCards(): iterable + { + yield 'visa' => ['4242424242424242']; + yield 'visa grouped (spaces)' => ['4242 4242 4242 4242']; + yield 'visa grouped (dashes)' => ['4242-4242-4242-4242']; + yield 'amex (15)' => ['378282246310005']; + yield 'mastercard' => ['5555555555554444']; + } + + /** + * @dataProvider nonCards + */ + public function testDoesNotMatchNonCards(string $value): void + { + self::assertFalse($this->matcher->matches($value)); + } + + /** + * @return iterable + */ + public static function nonCards(): iterable + { + yield 'wrong checksum' => ['4242424242424241']; + yield 'too short' => ['123456789012']; + yield 'too long' => ['12345678901234567890']; + yield 'not digits' => ['hello world']; + yield 'empty' => ['']; + } + + public function testRedactsOnlyTheCardSubString(): void + { + $masked = $this->matcher->redact('pay with 4242424242424242 now', new FullMaskStrategy('***')); + + self::assertSame('pay with *** now', $masked); + } + + public function testRedactLeavesNonLuhnDigitsUntouched(): void + { + $value = 'order 4242424242424241 placed'; + + self::assertSame($value, $this->matcher->redact($value, new FullMaskStrategy('***'))); + } + + public function testRedactReturnsEmptyStringUnchanged(): void + { + self::assertSame('', $this->matcher->redact('', new FullMaskStrategy('***'))); + } +} diff --git a/tests/Matcher/RegexValueMatcherTest.php b/tests/Matcher/RegexValueMatcherTest.php index bb9435d..d0d2610 100644 --- a/tests/Matcher/RegexValueMatcherTest.php +++ b/tests/Matcher/RegexValueMatcherTest.php @@ -6,6 +6,7 @@ use PHPUnit\Framework\TestCase; use Tiime\MonologMasker\Matcher\RegexValueMatcher; +use Tiime\MonologMasker\Strategy\FullMaskStrategy; final class RegexValueMatcherTest extends TestCase { @@ -25,8 +26,9 @@ public static function sensitiveValues(): iterable yield 'email' => ['john.doe@example.com']; yield 'jwt' => ['eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjMifQ.s5pVl0lK3a8xZ_q2cQ8m1Q']; yield 'bearer' => ['Bearer abc123.def-456_ghi']; - yield 'credit card' => ['4242 4242 4242 4242']; yield 'iban' => ['FR7630006000011234567890189']; + yield 'aws access key' => ['AKIAIOSFODNN7EXAMPLE']; + yield 'google api key' => ['AIzaSyA1234567890abcdefghijklmnopqrstuv']; yield 'stripe key' => ['sk_live_abcdef0123456789ABCDEF']; } @@ -82,4 +84,26 @@ public function testEmptyPatternSetMatchesNothing(): void self::assertFalse($matcher->matches('john.doe@example.com')); } + + public function testRedactReplacesOnlyTheMatchedSubString(): void + { + $masked = RegexValueMatcher::withDefaults()->redact( + 'contact john.doe@example.com please', + new FullMaskStrategy('***'), + ); + + self::assertSame('contact *** please', $masked); + } + + public function testRedactLeavesNonMatchingValueUntouched(): void + { + $value = 'nothing sensitive here'; + + self::assertSame($value, RegexValueMatcher::withDefaults()->redact($value, new FullMaskStrategy('***'))); + } + + public function testRedactReturnsEmptyStringUnchanged(): void + { + self::assertSame('', RegexValueMatcher::withDefaults()->redact('', new FullMaskStrategy('***'))); + } } diff --git a/tests/Matcher/SegmentKeyMatcherTest.php b/tests/Matcher/SegmentKeyMatcherTest.php new file mode 100644 index 0000000..5db9bbf --- /dev/null +++ b/tests/Matcher/SegmentKeyMatcherTest.php @@ -0,0 +1,100 @@ +matches($key)); + } + + /** + * @return iterable + */ + public static function sensitiveKeys(): iterable + { + yield 'exact' => ['password']; + yield 'snake prefix' => ['db_password']; + yield 'camelCase' => ['userToken']; + yield 'kebab multi-word' => ['x-api-key']; + yield 'camel multi-word' => ['apiKey']; + yield 'dotted' => ['request.authorization']; + yield 'upper' => ['DB_PASSWORD']; + yield 'XML camel boundary' => ['XMLAuthToken']; + } + + /** + * @dataProvider safeKeys + */ + public function testDoesNotMatchSafeKeys(string $key): void + { + self::assertFalse(SegmentKeyMatcher::withDefaults()->matches($key)); + } + + /** + * @return iterable + */ + public static function safeKeys(): iterable + { + // A sensitive word must appear as a whole segment, not a substring. + yield 'tokenizer' => ['tokenizer']; + yield 'author' => ['author']; + yield 'username' => ['username']; + yield 'passwordless is still a single segment' => ['passwordless']; + // A sensitive word as a suffix of a larger segment must not match. + yield 'mytoken' => ['mytoken']; + } + + public function testNeverMatchesIntegerKeys(): void + { + self::assertFalse(SegmentKeyMatcher::withDefaults()->matches(0)); + } + + public function testMultiWordEntryRequiresTheSequence(): void + { + $matcher = new SegmentKeyMatcher(['api_key']); + + self::assertTrue($matcher->matches('api_key')); + self::assertTrue($matcher->matches('publicApiKey')); + // 'key' alone is not the configured sequence. + self::assertFalse($matcher->matches('key')); + self::assertFalse($matcher->matches('api')); + } + + public function testEmptyAndSeparatorOnlyKeysNeverMatch(): void + { + $matcher = SegmentKeyMatcher::withDefaults(); + + self::assertFalse($matcher->matches('')); + self::assertFalse($matcher->matches('___')); + } + + public function testIgnoresEmptyConfiguredKeys(): void + { + $matcher = new SegmentKeyMatcher(['']); + + self::assertFalse($matcher->matches('password')); + } + + public function testSplitsUppercaseRunFollowedByLowercase(): void + { + // "APIToken" must split as API / Token (the XMLToken-style boundary). + self::assertTrue(SegmentKeyMatcher::withDefaults()->matches('APIToken')); + } + + public function testMatchesAccentedConfiguredKeysCaseInsensitively(): void + { + $matcher = new SegmentKeyMatcher(['café']); + + self::assertTrue($matcher->matches('CAFÉ')); + } +} diff --git a/tests/Processor/MaskingProcessorTest.php b/tests/Processor/MaskingProcessorTest.php index 92e28f4..91338d3 100644 --- a/tests/Processor/MaskingProcessorTest.php +++ b/tests/Processor/MaskingProcessorTest.php @@ -115,4 +115,41 @@ public function testHandlesEmptyContextAndExtra(): void self::assertSame([], $processed->context); self::assertSame([], $processed->extra); } + + public function testMasksTheMessageByDefault(): void + { + $processor = new MaskingProcessor($this->masker()); + + $processed = $processor($this->record('login from john.doe@example.com')); + + self::assertSame('login from ***', $processed->message); + } + + public function testMessageMaskingCanBeDisabled(): void + { + $processor = new MaskingProcessor($this->masker(), false); + + $processed = $processor($this->record('login from john.doe@example.com')); + + self::assertSame('login from john.doe@example.com', $processed->message); + } + + private function masker(): Masker + { + return new Masker( + new KeyListMatcher(['password']), + RegexValueMatcher::withDefaults(), + new FullMaskStrategy('***'), + ); + } + + private function record(string $message): LogRecord + { + return new LogRecord( + datetime: new \DateTimeImmutable('@0'), + channel: 'app', + level: Level::Info, + message: $message, + ); + } } diff --git a/tests/Property/Generators.php b/tests/Property/Generators.php index 7923025..6cf7655 100644 --- a/tests/Property/Generators.php +++ b/tests/Property/Generators.php @@ -6,7 +6,10 @@ use Innmind\BlackBox\Set; use Tiime\MonologMasker\Config\DefaultSensitiveKeys; +use Tiime\MonologMasker\Matcher\ChainValueMatcher; +use Tiime\MonologMasker\Matcher\CreditCardMatcher; use Tiime\MonologMasker\Matcher\RegexValueMatcher; +use Tiime\MonologMasker\Matcher\ValueMatcherInterface; /** * black-box {@see Set} generators shared by the property tests. @@ -39,9 +42,17 @@ public static function anyKey(): Set * Scalars guaranteed NOT to be flagged by the default value matcher: * small integers, booleans and short lower-case ASCII strings. */ + /** + * The same value matcher the builder uses by default (regex + Luhn card). + */ + public static function defaultValueMatcher(): ValueMatcherInterface + { + return new ChainValueMatcher(RegexValueMatcher::withDefaults(), new CreditCardMatcher()); + } + public static function safeScalars(): Set { - $matcher = RegexValueMatcher::withDefaults(); + $matcher = self::defaultValueMatcher(); return Set::either( Set::integers()->between(0, 9999), @@ -57,7 +68,7 @@ public static function safeScalars(): Set */ public static function sensitiveValues(): Set { - $matcher = RegexValueMatcher::withDefaults(); + $matcher = self::defaultValueMatcher(); return Set::either( Set::email(), diff --git a/tests/Property/MaskerPropertyTest.php b/tests/Property/MaskerPropertyTest.php index f84eb96..3c9a7d0 100644 --- a/tests/Property/MaskerPropertyTest.php +++ b/tests/Property/MaskerPropertyTest.php @@ -5,10 +5,11 @@ namespace Tiime\MonologMasker\Tests\Property; use Innmind\BlackBox\PHPUnit\BlackBox; +use Innmind\BlackBox\Set; use PHPUnit\Framework\TestCase; use Tiime\MonologMasker\Masker\Masker; use Tiime\MonologMasker\MaskerBuilder; -use Tiime\MonologMasker\Matcher\KeyListMatcher; +use Tiime\MonologMasker\Matcher\SegmentKeyMatcher; use Tiime\MonologMasker\Strategy\FullMaskStrategy; /** @@ -118,12 +119,30 @@ public function testLeavesSafeScalarUnderSafeKeyUntouched(): void }); } + public function testMasksSensitiveDataCarriedByObjects(): void + { + $this + ->forAll( + Set::of('password', 'token', 'secret', 'apikey', 'authorization'), + Generators::safeScalars(), + ) + ->then(function (string $property, mixed $value): void { + $object = new \stdClass(); + $object->{$property} = $value; + + $masked = $this->masker()->mask(['carrier' => $object]); + + // The object is traversed and its sensitive property masked. + $this->assertSame(self::MASK, $masked['carrier'][$property]); + }); + } + /** * @param array $output */ private function assertSensitiveKeysMasked(array $output): void { - $keyMatcher = KeyListMatcher::withDefaults(); + $keyMatcher = SegmentKeyMatcher::withDefaults(); foreach ($output as $key => $value) { if (\is_string($key) && $keyMatcher->matches($key)) { diff --git a/tests/Property/MatcherPropertyTest.php b/tests/Property/MatcherPropertyTest.php index a80380a..a9d3d79 100644 --- a/tests/Property/MatcherPropertyTest.php +++ b/tests/Property/MatcherPropertyTest.php @@ -7,6 +7,7 @@ use Innmind\BlackBox\PHPUnit\BlackBox; use Innmind\BlackBox\Set; use PHPUnit\Framework\TestCase; +use Tiime\MonologMasker\Matcher\CreditCardMatcher; use Tiime\MonologMasker\Matcher\KeyListMatcher; use Tiime\MonologMasker\Matcher\RegexValueMatcher; @@ -30,7 +31,7 @@ public function testSensitiveKeysMatchRegardlessOfCase(): void public function testCuratedSensitiveValuesAlwaysMatch(): void { - $matcher = RegexValueMatcher::withDefaults(); + $matcher = Generators::defaultValueMatcher(); $this ->forAll(Set::of( @@ -59,4 +60,43 @@ public function testLowerCaseAsciiStringsNeverMatch(): void $this->assertFalse($matcher->matches($value)); }); } + + public function testCreditCardDetectionAgreesWithLuhn(): void + { + $matcher = new CreditCardMatcher(); + + $this + ->forAll(Set::sequence(Set::integers()->between(0, 9))->between(13, 16)) + ->then(function (array $digits) use ($matcher): void { + $number = implode('', $digits); + + // The matcher flags a bare digit run iff it satisfies Luhn. + $this->assertSame($this->isLuhnValid($number), $matcher->matches($number)); + }); + } + + /** + * Independent Luhn implementation used to cross-check the matcher. + */ + private function isLuhnValid(string $digits): bool + { + $sum = 0; + $double = false; + + for ($i = \strlen($digits) - 1; $i >= 0; --$i) { + $value = (int) $digits[$i]; + + if ($double) { + $value *= 2; + if ($value > 9) { + $value -= 9; + } + } + + $sum += $value; + $double = !$double; + } + + return 0 === $sum % 10; + } } From fb06082e096a08b7b69676a35b90f21c7f95f035 Mon Sep 17 00:00:00 2001 From: rflavien Date: Fri, 29 May 2026 17:35:12 +0200 Subject: [PATCH 2/2] chore(meta): repository metadata and README header Point composer support/source to Tiime-Software/MonologMasker and add the Tiime header to the README. Co-Authored-By: Claude Opus 4.8 (1M context) --- README.md | 5 ++++- composer.json | 6 +++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ae76415..7671cd0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,7 @@ -# 🛡️ Monolog Masker +

+ logo Tiime
+Monolog Masker +

![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) diff --git a/composer.json b/composer.json index 69a6f79..541d2cf 100644 --- a/composer.json +++ b/composer.json @@ -7,12 +7,12 @@ "authors": [ { "name": "Tiime platform-dev", - "homepage": "https://github.com/ManakinCubber" + "homepage": "https://github.com/Tiime-Software" } ], "support": { - "issues": "https://github.com/ManakinCubber/monolog-masker/issues", - "source": "https://github.com/ManakinCubber/monolog-masker" + "issues": "https://github.com/Tiime-Software/MonologMasker/issues", + "source": "https://github.com/Tiime-Software/MonologMasker" }, "require": { "php": ">=8.2",