From 1c9c4a9c48610d9c17da38f26be580959bd0dcb9 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 18:29:05 +0200 Subject: [PATCH 01/13] Strip query string from REQUEST_URI and add log redaction hook (#1) Co-Authored-By: Claude Sonnet 5.5 --- .gitignore | 2 + CHANGELOG.md | 18 +++++ composer.json | 14 ++++ src/Logger.php | 130 +++++++++++++++++++++++++++++++++- tests/EndToEndLoggingTest.php | 60 ++++++++++++++++ tests/RedactionTest.php | 57 +++++++++++++++ tests/RequestUriTest.php | 53 ++++++++++++++ 7 files changed, 333 insertions(+), 1 deletion(-) create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 tests/EndToEndLoggingTest.php create mode 100644 tests/RedactionTest.php create mode 100644 tests/RequestUriTest.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d1502b0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +vendor/ +composer.lock diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a9163d0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,18 @@ +# Changelog + +## Unreleased + +### Changed (behaviour change) +- File-fallback log entries now record only the **path** of `REQUEST_URI` (no query string, no fragment). + Signatures, tokens and one-time codes in query strings are no longer written to log files. + Anything parsing the `server.REQUEST_URI` field will no longer see the query string. + To restore the old behaviour, opt in explicitly with `Logger::logFullRequestUri(true)` (off by default). +- CLI (no `REQUEST_URI`) still writes an empty string. + +### Added +- Redaction of secrets before anything is logged (Monolog and file-fallback paths): + - sensitive context keys (`password`, `token`, `secret`, `sig`, `authorization`, ...) are masked recursively; + - `key=value` secrets inside messages, exception messages and traces are scrubbed; + - `Logger::setSensitiveKeys([...])` replaces the key list, `Logger::setRedactor(callable)` adds a custom hook + that receives the full context. A throwing hook never breaks logging and never leaks the original context. +- Behaviour change: values under the default sensitive keys now appear as `***REDACTED***` in logs. diff --git a/composer.json b/composer.json index 4d0ad06..4983e7f 100644 --- a/composer.json +++ b/composer.json @@ -47,10 +47,24 @@ "psr/log": "^3.0", "monolog/monolog": "^3.9" }, + "require-dev": { + "phpunit/phpunit": "^11.0" + }, "autoload": { "psr-4": { "Maatify\\Logger\\": "src/", "Maatify\\Store\\File\\": "src/store/file/" } + }, + "autoload-dev": { + "psr-4": { + "Maatify\\Logger\\Tests\\": "tests/" + } + }, + "config": { + "sort-packages": true + }, + "scripts": { + "test": "phpunit tests" } } diff --git a/src/Logger.php b/src/Logger.php index d52e5b7..23b0113 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -18,6 +18,17 @@ class Logger implements LoggerInterface { private static string $extension = 'log'; + private static bool $logFullRequestUri = false; + + private const string REDACTED = '***REDACTED***'; + + /** Context keys (case-insensitive substring match) whose values are always masked. */ + private static array $sensitiveKeys = [ + 'password', 'passwd', 'secret', 'token', 'authorization', 'api_key', 'apikey', 'sig', 'signature', 'otp', 'cookie', + ]; + + /** @var null|callable(array): array */ + private static $redactor = null; private const string INTERNAL_ERROR_FILE = __DIR__ . '/../../error_logger.log'; private ?\Monolog\Logger $monolog = null; @@ -80,6 +91,11 @@ public function log($level, $message, array $context = []): void $message = 'Exception log entry'; } + $context = self::redactContext($context); + if (is_string($message)) { + $message = self::scrubString($message); + } + if ($this->monolog) { // ✅ Monolog backend $this->monolog->log($level, $message, $context); @@ -97,7 +113,7 @@ public function log($level, $message, array $context = []): void 'server' => [ 'REMOTE_ADDR' => $_SERVER['REMOTE_ADDR'] ?? 'CLI', 'HTTP_HOST' => $_SERVER['HTTP_HOST'] ?? '', - 'REQUEST_URI' => $_SERVER['REQUEST_URI'] ?? '', + 'REQUEST_URI' => self::sanitizeRequestUri($_SERVER['REQUEST_URI'] ?? ''), 'USER_AGENT' => $_SERVER['HTTP_USER_AGENT'] ?? '', ], 'message' => $message, @@ -139,7 +155,119 @@ public function log($level, $message, array $context = []): void } } + // --- Redaction --- + + /** + * Register an extra redaction hook, run after the built-in key masking. + * It receives the whole context (including the 'exception' entry) and must return the array to log. + * Pass null to remove it. If the hook throws, the context is replaced by a redaction-failed marker. + */ + public static function setRedactor(?callable $redactor): void + { + self::$redactor = $redactor; + } + + /** + * Replace the list of sensitive context keys (case-insensitive substring match). + * + * @param string[] $keys + */ + public static function setSensitiveKeys(array $keys): void + { + self::$sensitiveKeys = array_map('strtolower', $keys); + } + + public static function redactContext(array $context): array + { + try { + $context = self::maskKeys($context); + if (self::$redactor !== null) { + $context = (self::$redactor)($context); + } + return is_array($context) ? $context : ['redaction' => 'invalid redactor result']; + } catch (Throwable) { + return ['redaction' => 'failed']; + } + } + + private static function maskKeys(array $data): array + { + foreach ($data as $key => $value) { + if (is_string($key) && self::isSensitiveKey($key)) { + $data[$key] = self::REDACTED; + } elseif (is_array($value)) { + $data[$key] = self::maskKeys($value); + } elseif (is_string($value)) { + $data[$key] = self::scrubString($value); + } + } + return $data; + } + + private static function isSensitiveKey(string $key): bool + { + $key = strtolower($key); + foreach (self::$sensitiveKeys as $needle) { + if ($needle !== '' && str_contains($key, $needle)) { + return true; + } + } + return false; + } + + /** + * Mask "key=value" / "key: value" secrets embedded in free text (exception messages, traces, URLs). + */ + private static function scrubString(string $text): string + { + $names = implode('|', array_map(static fn(string $k) => preg_quote($k, '/'), self::$sensitiveKeys)); + if ($names === '') { + return $text; + } + $out = preg_replace( + '/((?:[\w-]*(?:' . $names . ')[\w-]*)\s*[=:]\s*)("[^"]*"|\'[^\']*\'|[^\s&,;"\')]+)/i', + '$1' . self::REDACTED, + $text + ); + return $out ?? $text; + } + // --- Helpers --- + + /** + * Reduce a request URI to its path only (no query string, no fragment) so that + * signatures, tokens and one-time codes never reach the log files. + * Never throws; anything unusable yields ''. + */ + public static function sanitizeRequestUri(mixed $uri): string + { + if (!is_string($uri) || $uri === '') { + return ''; + } + + if (self::$logFullRequestUri) { + return $uri; + } + + // Cut at the first '?' or '#' (also covers malformed URIs parse_url rejects) + $path = substr($uri, 0, strcspn($uri, '?#')); + + // "//host/path" would be read as an authority; collapse leading slashes to one + if (str_starts_with($path, '//')) { + $path = '/' . ltrim($path, '/'); + } + + return $path; + } + + /** + * Opt-in: log the full REQUEST_URI including the query string. Off by default. + */ + public static function logFullRequestUri(bool $enabled): void + { + self::$logFullRequestUri = $enabled; + } + private function buildFilePath(string $logFile): string { $dir = sprintf( diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php new file mode 100644 index 0000000..cdec01c --- /dev/null +++ b/tests/EndToEndLoggingTest.php @@ -0,0 +1,60 @@ +root = sys_get_temp_dir() . '/maatify-logger-e2e-' . bin2hex(random_bytes(4)); + $src = getenv('LOGGER_SRC') ?: dirname(__DIR__) . '/src'; + mkdir($this->root . '/vendor/maatify/logger/src', 0775, true); + copy($src . '/Logger.php', $this->root . '/vendor/maatify/logger/src/Logger.php'); + } + + protected function tearDown(): void + { + $it = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($this->root, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST + ); + foreach ($it as $f) { + $f->isDir() ? rmdir($f->getPathname()) : unlink($f->getPathname()); + } + rmdir($this->root); + } + + public function testSecretsNeverReachTheLogFile(): void + { + $script = $this->root . '/run.php'; + file_put_contents($script, 'root . '/vendor/maatify/logger/src/Logger.php', true) . '; +$l = new Maatify\Logger\Logger(); +$l->error("callback https://x/cb?sig=SECRET1 failed", ["password" => "SECRET2", "ok" => "visible"]); +$l->error(new RuntimeException("gateway said token=SECRET3")); +'); + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script) . ' 2>&1', $out, $code); + $this->assertSame(0, $code, implode("\n", $out)); + + $files = glob($this->root . '/logs/*/*/*/*/app_*.log'); + $this->assertNotEmpty($files, 'no log file written'); + $content = (string) file_get_contents($files[0]); + + $this->assertStringContainsString('visible', $content); + foreach (['SECRET1', 'SECRET2', 'SECRET3'] as $secret) { + $this->assertStringNotContainsString($secret, $content); + } + } +} diff --git a/tests/RedactionTest.php b/tests/RedactionTest.php new file mode 100644 index 0000000..1ea8bcb --- /dev/null +++ b/tests/RedactionTest.php @@ -0,0 +1,57 @@ + 'a', 'Password' => 'P1', 'nested' => ['api_token' => 'T1']]); + $this->assertSame('a', $out['user']); + $this->assertStringNotContainsString('P1', json_encode($out)); + $this->assertStringNotContainsString('T1', json_encode($out)); + } + + public function testSecretsInExceptionTextAreScrubbed(): void + { + $out = Logger::redactContext(['exception' => [ + 'message' => 'GET https://x/cb?sig=SECRET&ok=1 failed', + 'trace' => '#0 call(token=SECRET2)', + ]]); + $json = json_encode($out); + $this->assertStringNotContainsString('SECRET', $json); + $this->assertStringContainsString('ok=1', $json); + } + + public function testCustomRedactorRuns(): void + { + Logger::setRedactor(static fn(array $c) => $c + ['extra' => 'x'] + ['order' => 'masked']); + $this->assertSame('x', Logger::redactContext([])['extra']); + } + + public function testThrowingRedactorNeverLeaksOrThrows(): void + { + Logger::setRedactor(static function (array $c) { throw new \RuntimeException('boom'); }); + $out = Logger::redactContext(['note' => 'hello']); + $this->assertSame(['redaction' => 'failed'], $out); + } + + public function testCustomKeyList(): void + { + Logger::setSensitiveKeys(['iban']); + $out = Logger::redactContext(['my_iban' => 'EG123', 'password' => 'visible']); + $this->assertStringNotContainsString('EG123', json_encode($out)); + $this->assertSame('visible', $out['password']); + } +} diff --git a/tests/RequestUriTest.php b/tests/RequestUriTest.php new file mode 100644 index 0000000..d1032d5 --- /dev/null +++ b/tests/RequestUriTest.php @@ -0,0 +1,53 @@ +assertSame('/cb', $out); + $this->assertStringNotContainsString('SECRET', $out); + } + + public function testFragmentIsStripped(): void + { + $this->assertSame('/a/b', Logger::sanitizeRequestUri('/a/b#frag=SECRET')); + } + + public function testQueryOnlyOrMalformed(): void + { + $this->assertSame('', Logger::sanitizeRequestUri('?sig=SECRET')); + $this->assertSame('/x', Logger::sanitizeRequestUri('/x?a=%zz&b[=SECRET')); + } + + public function testMissingOrNonString(): void + { + $this->assertSame('', Logger::sanitizeRequestUri(null)); + $this->assertSame('', Logger::sanitizeRequestUri(['a'])); + $this->assertSame('', Logger::sanitizeRequestUri(123)); + $this->assertSame('', Logger::sanitizeRequestUri('')); + } + + public function testDoubleSlashPrefix(): void + { + $this->assertSame('/evil.com/p', Logger::sanitizeRequestUri('//evil.com/p?t=SECRET')); + } + + public function testOptInKeepsFullUri(): void + { + Logger::logFullRequestUri(true); + $this->assertSame('/cb?sig=1', Logger::sanitizeRequestUri('/cb?sig=1')); + } +} From ad99c737e593b7c5b39958079d176bac42bc2cd9 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 18:36:27 +0200 Subject: [PATCH 02/13] Fix redaction gaps: Throwable in context, Bearer tokens, depth limit; drop composer version (#2) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 6 ++++ composer.json | 1 - src/Logger.php | 56 ++++++++++++++++++++++++++++++----- tests/EndToEndLoggingTest.php | 6 +++- tests/RedactionTest.php | 33 +++++++++++++++++++++ 5 files changed, 93 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a9163d0..1d3953d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,3 +16,9 @@ - `Logger::setSensitiveKeys([...])` replaces the key list, `Logger::setRedactor(callable)` adds a custom hook that receives the full context. A throwing hook never breaks logging and never leaks the original context. - Behaviour change: values under the default sensitive keys now appear as `***REDACTED***` in logs. +- `Throwable` objects placed anywhere in the context are converted to a scrubbed array (class, message, code, file, line, trace, previous) before reaching Monolog. +- `Authorization: Bearer/Basic ` values are redacted from free text. +- Redaction is depth-limited (8 levels), so circular or very deep contexts cannot exhaust memory. + +### Removed +- The `version` field from `composer.json`; releases are identified by VCS tags. diff --git a/composer.json b/composer.json index 4983e7f..f9bf2c8 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,6 @@ { "name": "maatify/logger", "description": "maatify.dev logger, known by our team", - "version": "5.1.2", "type": "library", "keywords": [ "PHP", diff --git a/src/Logger.php b/src/Logger.php index 23b0113..967186b 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -21,6 +21,7 @@ class Logger implements LoggerInterface private static bool $logFullRequestUri = false; private const string REDACTED = '***REDACTED***'; + private const int MAX_REDACTION_DEPTH = 8; /** Context keys (case-insensitive substring match) whose values are always masked. */ private static array $sensitiveKeys = [ @@ -190,18 +191,56 @@ public static function redactContext(array $context): array } } - private static function maskKeys(array $data): array + private static function maskKeys(array $data, int $depth = 0): array { + if ($depth >= self::MAX_REDACTION_DEPTH) { + return ['truncated' => 'max depth reached']; + } + + $out = []; foreach ($data as $key => $value) { if (is_string($key) && self::isSensitiveKey($key)) { - $data[$key] = self::REDACTED; - } elseif (is_array($value)) { - $data[$key] = self::maskKeys($value); - } elseif (is_string($value)) { - $data[$key] = self::scrubString($value); + $out[$key] = self::REDACTED; + } else { + $out[$key] = self::maskValue($value, $depth + 1); } } - return $data; + return $out; + } + + private static function maskValue(mixed $value, int $depth): mixed + { + if (is_array($value)) { + return self::maskKeys($value, $depth); + } + if (is_string($value)) { + return self::scrubString($value); + } + if ($value instanceof Throwable) { + return self::describeThrowable($value, $depth); + } + return $value; + } + + /** + * Throwables are converted to a scrubbed array so their raw message never reaches the formatter. + */ + private static function describeThrowable(Throwable $e, int $depth): array + { + $info = [ + 'class' => $e::class, + 'message' => self::scrubString($e->getMessage()), + 'code' => $e->getCode(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), + 'trace' => self::scrubString($e->getTraceAsString()), + ]; + if ($e->getPrevious() !== null) { + $info['previous'] = $depth >= self::MAX_REDACTION_DEPTH + ? ['truncated' => 'max depth reached'] + : self::describeThrowable($e->getPrevious(), $depth + 1); + } + return $info; } private static function isSensitiveKey(string $key): bool @@ -224,6 +263,9 @@ private static function scrubString(string $text): string if ($names === '') { return $text; } + // Authorization schemes: "Bearer " / "Basic " + $text = preg_replace('/\b(Bearer|Basic)\s+[A-Za-z0-9._~+\/=-]+/i', '$1 ' . self::REDACTED, $text) ?? $text; + $out = preg_replace( '/((?:[\w-]*(?:' . $names . ')[\w-]*)\s*[=:]\s*)("[^"]*"|\'[^\']*\'|[^\s&,;"\')]+)/i', '$1' . self::REDACTED, diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php index cdec01c..3a666bf 100644 --- a/tests/EndToEndLoggingTest.php +++ b/tests/EndToEndLoggingTest.php @@ -44,6 +44,10 @@ public function testSecretsNeverReachTheLogFile(): void $l = new Maatify\Logger\Logger(); $l->error("callback https://x/cb?sig=SECRET1 failed", ["password" => "SECRET2", "ok" => "visible"]); $l->error(new RuntimeException("gateway said token=SECRET3")); +$l->error("pay failed", ["exception" => new RuntimeException("token=SECRET4")]); +$l->error("hdr Authorization: Bearer SECRET5"); +$loop = ["a" => 1]; $loop["self"] = &$loop; +$l->error("loop", ["data" => $loop]); '); exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script) . ' 2>&1', $out, $code); $this->assertSame(0, $code, implode("\n", $out)); @@ -53,7 +57,7 @@ public function testSecretsNeverReachTheLogFile(): void $content = (string) file_get_contents($files[0]); $this->assertStringContainsString('visible', $content); - foreach (['SECRET1', 'SECRET2', 'SECRET3'] as $secret) { + foreach (['SECRET1', 'SECRET2', 'SECRET3', 'SECRET4', 'SECRET5'] as $secret) { $this->assertStringNotContainsString($secret, $content); } } diff --git a/tests/RedactionTest.php b/tests/RedactionTest.php index 1ea8bcb..faf1420 100644 --- a/tests/RedactionTest.php +++ b/tests/RedactionTest.php @@ -54,4 +54,37 @@ public function testCustomKeyList(): void $this->assertStringNotContainsString('EG123', json_encode($out)); $this->assertSame('visible', $out['password']); } + + public function testThrowableInContextIsScrubbed(): void + { + $e = new \RuntimeException('token=SECRET123', 5, new \LogicException('password=SECRET9')); + $out = Logger::redactContext(['exception' => $e, 'nested' => ['deep' => $e]]); + $json = json_encode($out); + $this->assertStringNotContainsString('SECRET', $json); + $this->assertStringContainsString('RuntimeException', $json); + $this->assertSame('RuntimeException', $out['exception']['class']); + } + + public function testBearerTokensAreScrubbed(): void + { + foreach (['Authorization: Bearer eyJ-SECRET-TOKEN', 'authorization=Basic dXNlcjpTRUNSRVQ=', 'sent header Bearer abc.DEF-SECRET_1 ok'] as $text) { + $out = Logger::redactContext(['m' => $text, 'exception' => ['message' => $text]]); + $this->assertStringNotContainsString('SECRET', json_encode($out), $text); + $this->assertStringNotContainsString('dXNlcjpTRUNSRVQ', json_encode($out), $text); + } + } + + public function testCircularAndDeepContextDoesNotExhaustMemory(): void + { + $a = ['k' => 'v']; + $a['self'] = &$a; + $out = Logger::redactContext(['loop' => $a]); + $this->assertSame('v', $out['loop']['k']); + + $deep = ['x' => 'end']; + for ($i = 0; $i < 500; $i++) { + $deep = ['n' => $deep]; + } + $this->assertIsArray(Logger::redactContext($deep)); + } } From bc33b7fbc2d4858968c368ea44e62f4cc0995148 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 18:42:18 +0200 Subject: [PATCH 03/13] Add CI workflow, composer quality scripts, PHPStan max and PHP floor constraint (#2) Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 82 ++++++++++++++++++++++++++++++++ CHANGELOG.md | 6 +++ CONTRIBUTING.md | 23 +++++++++ composer.json | 27 +++++++++-- phpstan.neon | 5 ++ scripts/check-php-floors.php | 47 ++++++++++++++++++ scripts/check-whitespace.php | 30 ++++++++++++ scripts/lint-php.php | 30 ++++++++++++ scripts/lint-workflows.sh | 22 +++++++++ src/Logger.php | 89 +++++++++++++++++++++++++++++++---- src/LoggerService.php | 11 +++++ tests/EndToEndLoggingTest.php | 23 +++++---- tests/RedactionTest.php | 24 ++++++---- 13 files changed, 389 insertions(+), 30 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 CONTRIBUTING.md create mode 100644 phpstan.neon create mode 100644 scripts/check-php-floors.php create mode 100644 scripts/check-whitespace.php create mode 100644 scripts/lint-php.php create mode 100644 scripts/lint-workflows.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0e6596b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,82 @@ +name: CI + +on: + pull_request: + branches: [master] + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + verify: + name: PHP ${{ matrix.php }} (${{ matrix.deps }}) + runs-on: ubuntu-24.04 + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + include: + - { php: '8.4', deps: 'latest' } + - { php: '8.5', deps: 'latest' } + - { php: '8.4', deps: 'lowest' } + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: ${{ matrix.php }} + tools: composer:v2 + coverage: none + - name: Validate composer.json + run: composer validate --strict + - name: Resolve dependencies + run: | + if [ "${{ matrix.deps }}" = "lowest" ]; then + composer update --prefer-lowest --prefer-stable --no-interaction --prefer-dist --no-progress + else + composer update --no-interaction --prefer-dist --no-progress + fi + - name: Check platform requirements + run: composer check-platform-reqs + - name: PHP security patch floors + run: composer check:php-floors + - name: PHP syntax + run: composer lint:php + - name: Whitespace + run: composer lint:whitespace + - name: PHPStan + run: composer analyse + - name: Tests + run: composer test + - name: Composer audit + run: composer audit:deps + + workflow-lint: + name: Workflow lint + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: scripts/lint-workflows.sh + + gate: + name: CI gate + if: always() + needs: [verify, workflow-lint] + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Require every upstream job to succeed + run: | + echo "verify=${{ needs.verify.result }} workflow-lint=${{ needs.workflow-lint.result }}" + [ "${{ needs.verify.result }}" = "success" ] && [ "${{ needs.workflow-lint.result }}" = "success" ] diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d3953d..7dd821d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,3 +22,9 @@ ### Removed - The `version` field from `composer.json`; releases are identified by VCS tags. + +### CI and tooling +- GitHub Actions workflow (PHP 8.4/8.5 latest dependencies, PHP 8.4 lowest dependencies, workflow lint, stable `CI gate` job); actions pinned to commit SHAs, `contents: read` only. +- Composer scripts for every gate (`composer ci`), PHPStan level max without baseline, `CONTRIBUTING.md` mapping local commands to CI. +- **Breaking:** `require.php` is now `>=8.4.27 <8.5.0 || >=8.5.12 <8.6.0`. Previously no PHP constraint was declared (the code already required 8.3+ typed constants). +- `Logger::log()` now throws `Psr\Log\InvalidArgumentException` for a non-string or unknown level (previously an uncaught error from Monolog or `strtoupper`). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9360a2e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,23 @@ +# Contributing + +## Local quality gates and their CI mapping + +Every CI step runs the same Composer script a developer can run locally (`composer ci` runs them all except the workflow lint). + +| Gate | Local command | CI step | +|---|---|---| +| Composer manifest | `composer validate:strict` | `composer validate --strict` | +| Platform requirements | `composer check:platform` | `composer check-platform-reqs` | +| PHP security patch floors | `composer check:php-floors` | same | +| PHP syntax | `composer lint:php` | same | +| Whitespace | `composer lint:whitespace` | same | +| PHPStan (level max, no baseline) | `composer analyse` | same | +| Tests | `composer test` | same | +| Composer audit | `composer audit:deps` | same | +| Workflow lint (actionlint 1.7.12) | `composer lint:workflows` | `workflow-lint` job | + +CI (`.github/workflows/ci.yml`) runs PHP 8.4 and 8.5 with latest dependencies and PHP 8.4 with lowest dependencies, then a stable `CI gate` job that is the one to require in branch protection. `composer.lock` is not committed; CI resolves dependencies with `composer update`. + +Prerequisites: PHP matching `require.php`, Composer 2, and `actionlint` (or Linux x86_64, where `scripts/lint-workflows.sh` downloads a checksum-verified copy). `composer check:php-floors` fails on an interpreter below the security patch floor; that is intentional. + +Known gaps against the Maatify CI standard: no Consumer Verification Harness job and no Release Artifact Verification yet. diff --git a/composer.json b/composer.json index f9bf2c8..353c228 100644 --- a/composer.json +++ b/composer.json @@ -42,11 +42,14 @@ } ], "require": { + "php": ">=8.4.27 <8.5.0 || >=8.5.12 <8.6.0", "ext-json": "*", - "psr/log": "^3.0", - "monolog/monolog": "^3.9" + "monolog/monolog": "^3.9", + "psr/log": "^3.0" }, "require-dev": { + "composer/semver": "^3.4", + "phpstan/phpstan": "^2.1", "phpunit/phpunit": "^11.0" }, "autoload": { @@ -64,6 +67,24 @@ "sort-packages": true }, "scripts": { - "test": "phpunit tests" + "validate:strict": "composer validate --strict", + "check:platform": "composer check-platform-reqs", + "check:php-floors": "php scripts/check-php-floors.php", + "lint:php": "php scripts/lint-php.php", + "lint:whitespace": "php scripts/check-whitespace.php", + "lint:workflows": "scripts/lint-workflows.sh", + "analyse": "phpstan analyse --no-progress --memory-limit=512M", + "audit:deps": "composer audit --no-interaction --abandoned=fail", + "test": "phpunit tests", + "ci": [ + "@validate:strict", + "@check:platform", + "@check:php-floors", + "@lint:php", + "@lint:whitespace", + "@analyse", + "@test", + "@audit:deps" + ] } } diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..1494f51 --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,5 @@ +parameters: + level: max + paths: + - src + - tests diff --git a/scripts/check-php-floors.php b/scripts/check-php-floors.php new file mode 100644 index 0000000..4624cf1 --- /dev/null +++ b/scripts/check-php-floors.php @@ -0,0 +1,47 @@ + '8.4.27', '8.5' => '8.5.12']; + +$composer = json_decode((string) file_get_contents(dirname(__DIR__) . '/composer.json'), true, flags: JSON_THROW_ON_ERROR); +$constraint = (string) ($composer['require']['php'] ?? ''); +if ($constraint === '') { + fwrite(STDERR, "composer.json has no require.php\n"); + exit(1); +} + +$errors = []; +$minor = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION; +echo 'Installed PHP: ' . PHP_VERSION . "\n"; +if (isset(FLOORS[$minor]) && version_compare(PHP_VERSION, FLOORS[$minor], '<')) { + $errors[] = 'Interpreter ' . PHP_VERSION . ' is below the ' . $minor . ' floor ' . FLOORS[$minor]; +} + +foreach (FLOORS as $m => $floor) { + [$maj, $min] = array_map('intval', explode('.', $m)); + [, , $patch] = array_map('intval', explode('.', $floor)); + $below = "$maj.$min." . ($patch - 1); + $next = "$maj." . ($min + 1) . '.0'; + if (!Semver::satisfies($floor, $constraint)) { + $errors[] = "$floor must be accepted"; + } + if (Semver::satisfies($below, $constraint)) { + $errors[] = "$below must be rejected"; + } + if (Semver::satisfies($next, $constraint) && !isset(FLOORS["$maj." . ($min + 1)])) { + $errors[] = "$next (minor without floor) must be rejected"; + } +} + +if ($errors !== []) { + fwrite(STDERR, implode("\n", $errors) . "\n"); + exit(1); +} +echo "PHP floor checks OK for constraint: $constraint\n"; diff --git a/scripts/check-whitespace.php b/scripts/check-whitespace.php new file mode 100644 index 0000000..517f28c --- /dev/null +++ b/scripts/check-whitespace.php @@ -0,0 +1,30 @@ + $line) { + if (preg_match('/[ \t\r]+$/', $line) === 1) { + $bad[] = $path . ':' . ($i + 1); + } + } +} +if ($bad !== []) { + fwrite(STDERR, "Trailing whitespace found:\n" . implode("\n", $bad) . "\n"); + exit(1); +} +echo "Whitespace OK\n"; diff --git a/scripts/lint-php.php b/scripts/lint-php.php new file mode 100644 index 0000000..41a741a --- /dev/null +++ b/scripts/lint-php.php @@ -0,0 +1,30 @@ +getExtension() !== 'php') { + continue; + } + $count++; + exec(escapeshellarg(PHP_BINARY) . ' -l ' . escapeshellarg($file->getPathname()) . ' 2>&1', $out, $code); + if ($code !== 0) { + $failed++; + fwrite(STDERR, implode("\n", $out) . "\n"); + } + $out = []; + } +} + +if ($count === 0 || $failed > 0) { + fwrite(STDERR, "PHP syntax check failed ({$failed} failing, {$count} checked)\n"); + exit(1); +} +echo "PHP syntax OK ({$count} files)\n"; diff --git a/scripts/lint-workflows.sh b/scripts/lint-workflows.sh new file mode 100644 index 0000000..6ac4a8f --- /dev/null +++ b/scripts/lint-workflows.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Non-mutating workflow lint with a version-pinned, checksum-verified actionlint. +set -euo pipefail + +VERSION="1.7.12" +SHA256="8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8" # linux_amd64 tarball +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +if command -v actionlint >/dev/null 2>&1 && [ "$(actionlint -version | head -1)" = "$VERSION" ]; then + BIN="actionlint" +else + [ "$(uname -s)-$(uname -m)" = "Linux-x86_64" ] || { echo "actionlint $VERSION not installed (auto-install supports linux/amd64 only)" >&2; exit 1; } + TMP="$(mktemp -d)" + trap 'rm -rf "$TMP"' EXIT + curl -fsSL -o "$TMP/a.tgz" "https://github.com/rhysd/actionlint/releases/download/v${VERSION}/actionlint_${VERSION}_linux_amd64.tar.gz" + echo "${SHA256} $TMP/a.tgz" | sha256sum -c - + tar -xzf "$TMP/a.tgz" -C "$TMP" actionlint + BIN="$TMP/actionlint" +fi + +"$BIN" "$DIR"/.github/workflows/*.yml +echo "Workflow lint OK" diff --git a/src/Logger.php b/src/Logger.php index 967186b..06ad4eb 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -11,6 +11,7 @@ namespace Maatify\Logger; use Monolog\Handler\StreamHandler; +use Monolog\Level; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use Throwable; @@ -23,12 +24,16 @@ class Logger implements LoggerInterface private const string REDACTED = '***REDACTED***'; private const int MAX_REDACTION_DEPTH = 8; - /** Context keys (case-insensitive substring match) whose values are always masked. */ + /** + * Context keys (case-insensitive substring match) whose values are always masked. + * + * @var list + */ private static array $sensitiveKeys = [ 'password', 'passwd', 'secret', 'token', 'authorization', 'api_key', 'apikey', 'sig', 'signature', 'otp', 'cookie', ]; - /** @var null|callable(array): array */ + /** @var null|callable(array): array */ private static $redactor = null; private const string INTERNAL_ERROR_FILE = __DIR__ . '/../../error_logger.log'; @@ -53,6 +58,8 @@ public function __construct() /** * Legacy method + * + * @param string|array|Throwable $message */ public static function RecordLog( string|array|Throwable $message, @@ -63,20 +70,60 @@ public static function RecordLog( } // --- PSR-3 Methods --- + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function emergency($message, array $context = []): void { $this->log(LogLevel::EMERGENCY, $message, $context); } + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function alert($message, array $context = []): void { $this->log(LogLevel::ALERT, $message, $context); } + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function critical($message, array $context = []): void { $this->log(LogLevel::CRITICAL, $message, $context); } + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function error($message, array $context = []): void { $this->log(LogLevel::ERROR, $message, $context); } + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function warning($message, array $context = []): void { $this->log(LogLevel::WARNING, $message, $context); } + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function notice($message, array $context = []): void { $this->log(LogLevel::NOTICE, $message, $context); } + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function info($message, array $context = []): void { $this->log(LogLevel::INFO, $message, $context); } + /** + * @param string|\Stringable|array|Throwable $message + * @param array $context + */ public function debug($message, array $context = []): void { $this->log(LogLevel::DEBUG, $message, $context); } /** * Core logger + * + * @param mixed $level a PSR-3 level name + * @param string|\Stringable|array|Throwable $message + * @param array $context */ public function log($level, $message, array $context = []): void { + if (!is_string($level)) { + throw new \Psr\Log\InvalidArgumentException('Log level must be a string'); + } + // Wrap behavior → message لازم يكون string if (is_array($message)) { $context['data'] = $message; @@ -92,20 +139,31 @@ public function log($level, $message, array $context = []): void $message = 'Exception log entry'; } + $message = (string) $message; + $context = self::redactContext($context); - if (is_string($message)) { - $message = self::scrubString($message); - } + $message = self::scrubString($message); if ($this->monolog) { // ✅ Monolog backend - $this->monolog->log($level, $message, $context); + $monologLevel = match (strtolower($level)) { + 'debug' => Level::Debug, + 'info' => Level::Info, + 'notice' => Level::Notice, + 'warning' => Level::Warning, + 'error' => Level::Error, + 'critical' => Level::Critical, + 'alert' => Level::Alert, + 'emergency' => Level::Emergency, + default => throw new \Psr\Log\InvalidArgumentException('Unknown log level: ' . $level), + }; + $this->monolog->log($monologLevel, $message, $context); return; } // ❌ fallback → ملفات try { - $logFile = $context['logFile'] ?? 'app'; + $logFile = is_string($context['logFile'] ?? null) ? $context['logFile'] : 'app'; unset($context['logFile']); $payload = [ @@ -162,6 +220,8 @@ public function log($level, $message, array $context = []): void * Register an extra redaction hook, run after the built-in key masking. * It receives the whole context (including the 'exception' entry) and must return the array to log. * Pass null to remove it. If the hook throws, the context is replaced by a redaction-failed marker. + * + * @param null|callable(array): array $redactor */ public static function setRedactor(?callable $redactor): void { @@ -171,13 +231,17 @@ public static function setRedactor(?callable $redactor): void /** * Replace the list of sensitive context keys (case-insensitive substring match). * - * @param string[] $keys + * @param list $keys */ public static function setSensitiveKeys(array $keys): void { - self::$sensitiveKeys = array_map('strtolower', $keys); + self::$sensitiveKeys = array_map(static fn(string $k): string => strtolower($k), $keys); } + /** + * @param array $context + * @return array + */ public static function redactContext(array $context): array { try { @@ -185,12 +249,16 @@ public static function redactContext(array $context): array if (self::$redactor !== null) { $context = (self::$redactor)($context); } - return is_array($context) ? $context : ['redaction' => 'invalid redactor result']; + return $context; } catch (Throwable) { return ['redaction' => 'failed']; } } + /** + * @param array $data + * @return array + */ private static function maskKeys(array $data, int $depth = 0): array { if ($depth >= self::MAX_REDACTION_DEPTH) { @@ -225,6 +293,7 @@ private static function maskValue(mixed $value, int $depth): mixed /** * Throwables are converted to a scrubbed array so their raw message never reaches the formatter. */ + /** @return array */ private static function describeThrowable(Throwable $e, int $depth): array { $info = [ diff --git a/src/LoggerService.php b/src/LoggerService.php index 90b55e2..ced9355 100644 --- a/src/LoggerService.php +++ b/src/LoggerService.php @@ -31,47 +31,56 @@ private static function getLogger(): Logger /** * واجهة عامة (generic) */ + /** @param string|array|Throwable $message */ public static function log(string $level, string|array|Throwable $message, string $logFile = 'app'): void { self::getLogger()->log($level, $message, ['logFile' => $logFile]); } // --- Wrappers لكل مستوى PSR-3 --- + /** @param string|array|Throwable $message */ public static function emergency(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::EMERGENCY, $message, $logFile); } + /** @param string|array|Throwable $message */ public static function alert(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::ALERT, $message, $logFile); } + /** @param string|array|Throwable $message */ public static function critical(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::CRITICAL, $message, $logFile); } + /** @param string|array|Throwable $message */ public static function error(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::ERROR, $message, $logFile); } + /** @param string|array|Throwable $message */ public static function warning(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::WARNING, $message, $logFile); } + /** @param string|array|Throwable $message */ public static function notice(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::NOTICE, $message, $logFile); } + /** @param string|array|Throwable $message */ public static function info(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::INFO, $message, $logFile); } + /** @param string|array|Throwable $message */ public static function debug(string|array|Throwable $message, string $logFile = 'app'): void { self::log(LogLevel::DEBUG, $message, $logFile); @@ -83,6 +92,8 @@ public static function debug(string|array|Throwable $message, string $logFile = /** * ميثود مختصر للتعامل مع Exceptions/Throwables * يسمح بتمرير context إضافي (مثلاً userId, requestId, إلخ) + * + * @param array $context */ public static function logException( Throwable $e, diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php index 3a666bf..f3ad1e2 100644 --- a/tests/EndToEndLoggingTest.php +++ b/tests/EndToEndLoggingTest.php @@ -25,14 +25,19 @@ protected function setUp(): void protected function tearDown(): void { - $it = new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($this->root, \FilesystemIterator::SKIP_DOTS), - \RecursiveIteratorIterator::CHILD_FIRST - ); - foreach ($it as $f) { - $f->isDir() ? rmdir($f->getPathname()) : unlink($f->getPathname()); + self::removeTree($this->root); + } + + private static function removeTree(string $path): void + { + foreach (scandir($path) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + $full = $path . '/' . $entry; + is_dir($full) ? self::removeTree($full) : unlink($full); } - rmdir($this->root); + rmdir($path); } public function testSecretsNeverReachTheLogFile(): void @@ -52,9 +57,9 @@ public function testSecretsNeverReachTheLogFile(): void exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script) . ' 2>&1', $out, $code); $this->assertSame(0, $code, implode("\n", $out)); - $files = glob($this->root . '/logs/*/*/*/*/app_*.log'); + $files = glob($this->root . '/logs/*/*/*/*/app_*.log') ?: []; $this->assertNotEmpty($files, 'no log file written'); - $content = (string) file_get_contents($files[0]); + $content = (string) file_get_contents((string) reset($files)); $this->assertStringContainsString('visible', $content); foreach (['SECRET1', 'SECRET2', 'SECRET3', 'SECRET4', 'SECRET5'] as $secret) { diff --git a/tests/RedactionTest.php b/tests/RedactionTest.php index faf1420..123eaf8 100644 --- a/tests/RedactionTest.php +++ b/tests/RedactionTest.php @@ -9,6 +9,12 @@ final class RedactionTest extends TestCase { + /** @param array $data */ + private static function json(array $data): string + { + return json_encode($data, JSON_THROW_ON_ERROR); + } + protected function tearDown(): void { Logger::setRedactor(null); @@ -19,8 +25,8 @@ public function testSensitiveKeysAreMaskedRecursively(): void { $out = Logger::redactContext(['user' => 'a', 'Password' => 'P1', 'nested' => ['api_token' => 'T1']]); $this->assertSame('a', $out['user']); - $this->assertStringNotContainsString('P1', json_encode($out)); - $this->assertStringNotContainsString('T1', json_encode($out)); + $this->assertStringNotContainsString('P1', self::json($out)); + $this->assertStringNotContainsString('T1', self::json($out)); } public function testSecretsInExceptionTextAreScrubbed(): void @@ -29,7 +35,7 @@ public function testSecretsInExceptionTextAreScrubbed(): void 'message' => 'GET https://x/cb?sig=SECRET&ok=1 failed', 'trace' => '#0 call(token=SECRET2)', ]]); - $json = json_encode($out); + $json = self::json($out); $this->assertStringNotContainsString('SECRET', $json); $this->assertStringContainsString('ok=1', $json); } @@ -51,7 +57,7 @@ public function testCustomKeyList(): void { Logger::setSensitiveKeys(['iban']); $out = Logger::redactContext(['my_iban' => 'EG123', 'password' => 'visible']); - $this->assertStringNotContainsString('EG123', json_encode($out)); + $this->assertStringNotContainsString('EG123', self::json($out)); $this->assertSame('visible', $out['password']); } @@ -59,9 +65,10 @@ public function testThrowableInContextIsScrubbed(): void { $e = new \RuntimeException('token=SECRET123', 5, new \LogicException('password=SECRET9')); $out = Logger::redactContext(['exception' => $e, 'nested' => ['deep' => $e]]); - $json = json_encode($out); + $json = self::json($out); $this->assertStringNotContainsString('SECRET', $json); $this->assertStringContainsString('RuntimeException', $json); + $this->assertIsArray($out['exception']); $this->assertSame('RuntimeException', $out['exception']['class']); } @@ -69,8 +76,8 @@ public function testBearerTokensAreScrubbed(): void { foreach (['Authorization: Bearer eyJ-SECRET-TOKEN', 'authorization=Basic dXNlcjpTRUNSRVQ=', 'sent header Bearer abc.DEF-SECRET_1 ok'] as $text) { $out = Logger::redactContext(['m' => $text, 'exception' => ['message' => $text]]); - $this->assertStringNotContainsString('SECRET', json_encode($out), $text); - $this->assertStringNotContainsString('dXNlcjpTRUNSRVQ', json_encode($out), $text); + $this->assertStringNotContainsString('SECRET', self::json($out), $text); + $this->assertStringNotContainsString('dXNlcjpTRUNSRVQ', self::json($out), $text); } } @@ -79,12 +86,13 @@ public function testCircularAndDeepContextDoesNotExhaustMemory(): void $a = ['k' => 'v']; $a['self'] = &$a; $out = Logger::redactContext(['loop' => $a]); + $this->assertIsArray($out['loop']); $this->assertSame('v', $out['loop']['k']); $deep = ['x' => 'end']; for ($i = 0; $i < 500; $i++) { $deep = ['n' => $deep]; } - $this->assertIsArray(Logger::redactContext($deep)); + $this->assertNotEmpty(Logger::redactContext($deep)); } } From 9361ff30977ee6dbc2c4766c7c5f07b53393fbc3 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 18:51:32 +0200 Subject: [PATCH 04/13] Make lint-workflows.sh executable (#2) Co-Authored-By: Claude Sonnet 5.5 --- scripts/lint-workflows.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 scripts/lint-workflows.sh diff --git a/scripts/lint-workflows.sh b/scripts/lint-workflows.sh old mode 100644 new mode 100755 From bddb01b4dd7f81ba73713a9bb93190160a06440c Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 18:55:19 +0200 Subject: [PATCH 05/13] Add Consumer Verification Harness and Release Artifact Verification tooling (#2) Co-Authored-By: Claude Sonnet 5.5 --- .gitattributes | 6 ++ .github/workflows/ci.yml | 22 +++++- .github/workflows/release-verification.yml | 38 +++++++++ CHANGELOG.md | 2 +- CONTRIBUTING.md | 7 +- composer.json | 5 +- scripts/consumer-harness.sh | 92 ++++++++++++++++++++++ scripts/verify-release-artifact.php | 78 ++++++++++++++++++ 8 files changed, 244 insertions(+), 6 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/release-verification.yml create mode 100755 scripts/consumer-harness.sh create mode 100644 scripts/verify-release-artifact.php diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..85af592 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +/.github export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/phpstan.neon export-ignore +/scripts export-ignore +/tests export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e6596b..78fc840 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,6 +59,22 @@ jobs: - name: Composer audit run: composer audit:deps + consumer-harness: + name: Consumer Verification Harness + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.5' + tools: composer:v2 + coverage: none + - name: Harness (two clean consumer installs) + run: composer harness + workflow-lint: name: Workflow lint runs-on: ubuntu-24.04 @@ -72,11 +88,11 @@ jobs: gate: name: CI gate if: always() - needs: [verify, workflow-lint] + needs: [verify, consumer-harness, workflow-lint] runs-on: ubuntu-24.04 timeout-minutes: 5 steps: - name: Require every upstream job to succeed run: | - echo "verify=${{ needs.verify.result }} workflow-lint=${{ needs.workflow-lint.result }}" - [ "${{ needs.verify.result }}" = "success" ] && [ "${{ needs.workflow-lint.result }}" = "success" ] + echo "verify=${{ needs.verify.result }} consumer-harness=${{ needs.consumer-harness.result }} workflow-lint=${{ needs.workflow-lint.result }}" + [ "${{ needs.verify.result }}" = "success" ] && [ "${{ needs.consumer-harness.result }}" = "success" ] && [ "${{ needs.workflow-lint.result }}" = "success" ] diff --git a/.github/workflows/release-verification.yml b/.github/workflows/release-verification.yml new file mode 100644 index 0000000..e664967 --- /dev/null +++ b/.github/workflows/release-verification.yml @@ -0,0 +1,38 @@ +name: Release Artifact Verification + +# Manual gate for a candidate release SHA and exact target version (CI Workflow Standard §2.5). +on: + workflow_dispatch: + inputs: + target: + description: 'Exact SemVer release target, e.g. 5.2.0 or 1.0.0-rc.1' + required: true + type: string + +permissions: + contents: read + +concurrency: + group: release-verification-${{ github.ref }} + cancel-in-progress: false + +jobs: + verify-release-artifact: + name: Release Artifact Verification + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0 + with: + php-version: '8.5' + coverage: none + - name: Verify release artifact + env: + TARGET: ${{ inputs.target }} + run: | + set -euo pipefail + php scripts/verify-release-artifact.php "$TARGET" | tee verification.txt + { echo '### Release Artifact Verification'; echo '```'; cat verification.txt; echo '```'; } >> "$GITHUB_STEP_SUMMARY" diff --git a/CHANGELOG.md b/CHANGELOG.md index 7dd821d..5e87523 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## Unreleased +## [Unreleased] ### Changed (behaviour change) - File-fallback log entries now record only the **path** of `REQUEST_URI` (no query string, no fragment). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9360a2e..beff7cd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,10 +14,15 @@ Every CI step runs the same Composer script a developer can run locally (`compos | PHPStan (level max, no baseline) | `composer analyse` | same | | Tests | `composer test` | same | | Composer audit | `composer audit:deps` | same | +| Consumer Verification Harness | `composer harness` | `consumer-harness` job | | Workflow lint (actionlint 1.7.12) | `composer lint:workflows` | `workflow-lint` job | CI (`.github/workflows/ci.yml`) runs PHP 8.4 and 8.5 with latest dependencies and PHP 8.4 with lowest dependencies, then a stable `CI gate` job that is the one to require in branch protection. `composer.lock` is not committed; CI resolves dependencies with `composer update`. Prerequisites: PHP matching `require.php`, Composer 2, and `actionlint` (or Linux x86_64, where `scripts/lint-workflows.sh` downloads a checksum-verified copy). `composer check:php-floors` fails on an interpreter below the security patch floor; that is intentional. -Known gaps against the Maatify CI standard: no Consumer Verification Harness job and no Release Artifact Verification yet. +`composer harness` installs a `git archive` of the committed tree (plus tracked edits; honours `.gitattributes` `export-ignore`) into a clean consumer project twice, with `--no-dev` and production autoload, then exercises the public API and checks the consumer's log files. Locally, set `HARNESS_COMPOSER_FLAGS=--ignore-platform-req=php` if your PHP is below the patch floor (CI never does). + +## Release Artifact Verification + +`composer release:verify ` (CI: manual `Release Artifact Verification` workflow with the exact target) checks the archived tree of the candidate SHA for target `X`: manifest, required release-facing files, the undated `## [X]` CHANGELOG section, empty `[Unreleased]`, README install target, SECURITY identity badges and archive contents. It prints the target, SHA and every check outcome, and fails closed. It is **expected to fail today**: `SECURITY.md`, `CODE_OF_CONDUCT.md`, `LICENSE`, `llms.txt`, `docs/guides/USAGE_GUIDE.md` and `examples/` do not exist yet and need owner-approved content. README/SECURITY wording still needs the semantic review the standard requires. diff --git a/composer.json b/composer.json index 353c228..a91df1e 100644 --- a/composer.json +++ b/composer.json @@ -84,7 +84,10 @@ "@lint:whitespace", "@analyse", "@test", + "@harness", "@audit:deps" - ] + ], + "harness": "scripts/consumer-harness.sh", + "release:verify": "php scripts/verify-release-artifact.php" } } diff --git a/scripts/consumer-harness.sh b/scripts/consumer-harness.sh new file mode 100755 index 0000000..836cdc1 --- /dev/null +++ b/scripts/consumer-harness.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Consumer Verification Harness: installs the package through Composer into a clean, throw-away +# consumer project (production autoload, no dev dependencies, no test namespace) and exercises the +# public API. Runs twice from clean states. Fails closed. +# +# Local-only escape hatch: HARNESS_COMPOSER_FLAGS (e.g. --ignore-platform-req=php) for machines whose PHP +# is below the security patch floor. CI never sets it. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +FLAGS="${HARNESS_COMPOSER_FLAGS:-}" + +# The consumer installs what a distribution archive contains (honours .gitattributes export-ignore), +# built from the committed tree plus tracked working-tree edits (untracked files are not included). +SNAPSHOT="$(mktemp -d)" +trap 'rm -rf "$SNAPSHOT"' EXIT +TREE="$(git -C "$ROOT" stash create 2>/dev/null || true)" +git -C "$ROOT" archive "${TREE:-HEAD}" | tar -x -C "$SNAPSHOT" + +run_once() { + local run="$1" + local dir + dir="$(mktemp -d)" + + mkdir -p "$dir/consumer" + cat > "$dir/consumer/composer.json" < "$dir/consumer/app.php" <<'PHP' +error('callback https://x/cb?sig=SECRET_A failed', ['password' => 'SECRET_B', 'visible' => 'kept']); +$logger->info('Authorization: Bearer SECRET_C'); +LoggerService::logException(new RuntimeException('token=SECRET_D'), 'exceptions'); +LoggerService::error(['note' => 'array entry', 'api_key' => 'SECRET_E']); + +foreach (['Maatify\\Logger\\Tests\\RedactionTest', 'PHPUnit\\Framework\\TestCase'] as $devClass) { + if (class_exists($devClass)) { + fwrite(STDERR, "dev class autoloadable in consumer: $devClass\n"); + exit(2); + } +} +echo "ok\n"; +PHP + + echo "== Harness run $run: composer install (clean state)" + # shellcheck disable=SC2086 + (cd "$dir/consumer" && composer install --no-dev --no-interaction --prefer-dist --no-progress $FLAGS) + + local mode + mode="$(php -r '$i=json_decode(file_get_contents($argv[1]),true); foreach($i["packages"] as $p){ if($p["name"]==="maatify/logger"){ echo $p["installation-source"] ?? "unknown"; } }' "$dir/consumer/vendor/composer/installed.json")" + echo "installed maatify/logger via: $mode" + [ -d "$dir/consumer/vendor/maatify/logger/src" ] || { echo "package not installed" >&2; exit 1; } + [ ! -d "$dir/consumer/vendor/maatify/logger/tests" ] || { echo "tests directory leaked into consumer install" >&2; exit 1; } + + echo "== Harness run $run: public API workflow" + (cd "$dir/consumer" && php app.php) + + local logs + logs="$(find "$dir/consumer/logs" -name '*.log' -type f 2>/dev/null || true)" + [ -n "$logs" ] || { echo "no log files written under consumer root" >&2; exit 1; } + + if echo "$logs" | xargs grep -l -E 'SECRET_[A-E]' >/dev/null 2>&1; then + echo "secret leaked into consumer log files" >&2 + exit 1 + fi + echo "$logs" | xargs grep -q 'kept' || { echo "expected non-secret content missing" >&2; exit 1; } + rm -rf "$dir" + echo "== Harness run $run OK" +} + +run_once 1 +run_once 2 +echo "Consumer Verification Harness OK (2 clean runs)" diff --git a/scripts/verify-release-artifact.php b/scripts/verify-release-artifact.php new file mode 100644 index 0000000..4a08717 --- /dev/null +++ b/scripts/verify-release-artifact.php @@ -0,0 +1,78 @@ + e.g. 5.2.0 or 1.0.0-rc.1 + * Verifies the committed tree (git archive of HEAD), prints target, SHA and per-check outcome, fails closed. + * Deterministic structural facts only: README/SECURITY wording still needs the semantic review the standard requires. + */ + +$target = $argv[1] ?? ''; +if (preg_match('/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/', $target) !== 1) { + fwrite(STDERR, "Usage: verify-release-artifact.php \n"); + exit(2); +} + +$root = dirname(__DIR__); +$sha = trim((string) shell_exec('git -C ' . escapeshellarg($root) . ' rev-parse HEAD')); +echo "Target: $target\nCandidate SHA: $sha\n"; + +$tmp = sys_get_temp_dir() . '/maatify-release-' . bin2hex(random_bytes(4)); +mkdir($tmp); +exec('git -C ' . escapeshellarg($root) . ' archive HEAD | tar -x -C ' . escapeshellarg($tmp), $o, $code); +if ($code !== 0) { + fwrite(STDERR, "git archive failed\n"); + exit(1); +} + +$results = []; +$check = static function (string $name, bool $ok, string $detail = '') use (&$results): void { + $results[] = [$name, $ok, $detail]; + echo ($ok ? 'PASS' : 'FAIL') . " $name" . ($detail !== '' ? " — $detail" : '') . "\n"; +}; +$read = static fn(string $f): string => is_file("$tmp/$f") ? (string) file_get_contents("$tmp/$f") : ''; + +// Manifest +$composer = json_decode($read('composer.json'), true) ?: []; +$check('composer.json has no committed version field', !isset($composer['version'])); +$check('composer.json package name is maatify/logger', ($composer['name'] ?? '') === 'maatify/logger'); +$check('composer.lock is not distributed', !is_file("$tmp/composer.lock")); + +// Required release-facing files (LIBRARY_PRESENTATION_STANDARD §6) +foreach (['README.md', 'CHANGELOG.md', 'SECURITY.md', 'CONTRIBUTING.md', 'CODE_OF_CONDUCT.md', 'LICENSE', 'composer.json', 'llms.txt', 'docs/guides/USAGE_GUIDE.md'] as $f) { + $check("required file present: $f", is_file("$tmp/$f")); +} +$check('examples/ present and non-empty', is_dir("$tmp/examples") && (glob("$tmp/examples/*") ?: []) !== []); + +// CHANGELOG target allocation +$changelog = $read('CHANGELOG.md'); +$quoted = preg_quote($target, '/'); +$check('CHANGELOG has undated section for target', preg_match('/^## \[' . $quoted . '\]\s*$/m', $changelog) === 1); +$check('CHANGELOG target section is not dated', preg_match('/^## \[' . $quoted . '\] - /m', $changelog) !== 1); +$unreleased = preg_match('/^## \[Unreleased\]\s*\n(.*?)(?=^## \[|\z)/ms', $changelog, $m) === 1 ? trim($m[1]) : ''; +$check('[Unreleased] holds no target-allocated changes', $unreleased === '', $unreleased === '' ? '' : 'non-empty: move changes allocated to the target'); + +// README identity / install target +$readme = $read('README.md'); +$check('README names the exact install target', str_contains($readme, $target)); + +// SECURITY.md identity badges +$security = $read('SECURITY.md'); +$check('SECURITY.md has repository + ecosystem identity badges', str_contains($security, 'github.com/Maatify/Logger') && str_contains($security, 'https://github.com/Maatify)')); + +// Archive exclusions must not drop required files nor include secrets / dev artifacts +$bad = []; +foreach (['.env', 'vendor', 'logs', 'error_logger.log'] as $p) { + if (file_exists("$tmp/$p")) { + $bad[] = $p; + } +} +$check('archive contains no secrets/dev artifacts', $bad === [], implode(', ', $bad)); + +exec('rm -rf ' . escapeshellarg($tmp)); + +$failed = array_filter($results, static fn(array $r): bool => !$r[1]); +echo $failed === [] ? "Release Artifact Verification PASSED for $target @ $sha\n" : 'Release Artifact Verification FAILED (' . count($failed) . " check(s)) for $target @ $sha\n"; +exit($failed === [] ? 0 : 1); From ce87da153febf3ac3091a8e745ea5982f9a95033 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:01:24 +0200 Subject: [PATCH 06/13] Prepare release 7.0.0 artifact: docs, examples, llms.txt, security files, release verifier checks (#2) Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 2 + CHANGELOG.md | 7 + CODE_OF_CONDUCT.md | 16 +++ CONTRIBUTING.md | 37 ++++- LICENSE | 16 +++ LOGGER_PACKAGE_REFERENCE.md | 69 +++++++++ README.md | 210 ++++++++++++---------------- SECURITY.md | 18 +++ composer.json | 16 ++- docs/guides/USAGE_GUIDE.md | 32 +++++ examples/01-facade.php | 14 ++ examples/02-psr3.php | 23 +++ examples/03-exceptions.php | 16 +++ examples/04-redaction.php | 30 ++++ examples/_bootstrap.php | 11 ++ llms.txt | 18 +++ phpstan.neon | 1 + scripts/lint-php.php | 2 +- scripts/run-examples.sh | 41 ++++++ scripts/verify-release-artifact.php | 24 +++- 20 files changed, 470 insertions(+), 133 deletions(-) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 LICENSE create mode 100644 LOGGER_PACKAGE_REFERENCE.md create mode 100644 SECURITY.md create mode 100644 docs/guides/USAGE_GUIDE.md create mode 100644 examples/01-facade.php create mode 100644 examples/02-psr3.php create mode 100644 examples/03-exceptions.php create mode 100644 examples/04-redaction.php create mode 100644 examples/_bootstrap.php create mode 100644 llms.txt create mode 100644 scripts/run-examples.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 78fc840..18dbdaf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,6 +74,8 @@ jobs: coverage: none - name: Harness (two clean consumer installs) run: composer harness + - name: Examples smoke execution + run: composer examples workflow-lint: name: Workflow lint diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e87523..33cb4ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +## [7.0.0] + ### Changed (behaviour change) - File-fallback log entries now record only the **path** of `REQUEST_URI` (no query string, no fragment). Signatures, tokens and one-time codes in query strings are no longer written to log files. @@ -23,6 +25,11 @@ ### Removed - The `version` field from `composer.json`; releases are identified by VCS tags. +### Documentation +- README rewritten to the Maatify presentation standard; added `LOGGER_PACKAGE_REFERENCE.md`, `docs/guides/USAGE_GUIDE.md`, `examples/`, `llms.txt`, `SECURITY.md`, `CODE_OF_CONDUCT.md` and `LICENSE` (proprietary, unchanged). +- Documented that with Monolog (the required backend) every entry goes to the `app_*.log` file; the per-call log file name routes files only in the file fallback. +- `composer.json` metadata: description, keywords and homepage now describe this package. + ### CI and tooling - GitHub Actions workflow (PHP 8.4/8.5 latest dependencies, PHP 8.4 lowest dependencies, workflow lint, stable `CI gate` job); actions pinned to commit SHAs, `contents: read` only. - Composer scripts for every gate (`composer ci`), PHPStan level max without baseline, `CONTRIBUTING.md` mapping local commands to CI. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..21495c6 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,16 @@ +# Code of Conduct — maatify/logger + +[![Maatify Logger](https://img.shields.io/badge/Maatify-Logger-blue?style=for-the-badge)](https://github.com/Maatify/Logger) +[![Maatify Ecosystem](https://img.shields.io/badge/Maatify-Ecosystem-9C27B0?style=for-the-badge)](https://github.com/Maatify) + +## Participation + +Take part respectfully and professionally. Make room for good-faith technical disagreement, discuss ideas and evidence, and address people with courtesy. + +Harassment, discrimination, threats, doxing, intimidation, and abusive behavior are not acceptable. + +These expectations apply to repository issues, pull requests, reviews, discussions, and official project channels. + +## Reporting and moderation + +Report conduct concerns privately to [support@maatify.dev](mailto:support@maatify.dev). Maintainers may moderate or remove content and restrict participation when necessary to protect the community. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index beff7cd..5536011 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,24 @@ # Contributing -## Local quality gates and their CI mapping +## Package identity and boundaries -Every CI step runs the same Composer script a developer can run locally (`composer ci` runs them all except the workflow lint). +`maatify/logger` is a standalone PSR-3 logger package: logging, redaction of secrets and file output. Log shipping, rotation, retention and application-specific secret detection are out of scope. The supported contract is [LOGGER_PACKAGE_REFERENCE.md](LOGGER_PACKAGE_REFERENCE.md). + +## Ways to contribute + +Report bugs and propose changes through issues and pull requests. Discuss architecture-affecting changes (new public API, changed log format, changed redaction semantics, PHP constraint changes) in an issue before opening a pull request. Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md), never in a public issue. + +## Pull request expectations + +- Work on a branch and open a pull request against `master`; do not push to `master`. +- Keep the change focused; update `CHANGELOG.md` under the right section and call out behavior changes. +- A fixed defect needs a test that detects its recurrence; show it failing before the fix when the defect can be reproduced safely. +- Observable behavior needs a system-level test through the public API (see `tests/EndToEndLoggingTest.php`). +- All gates below must pass; the `CI gate` job is the required check. + +## Local verification commands and their CI mapping + +Every CI step runs the same Composer script a developer can run locally (`composer ci` runs all of them except the workflow lint). | Gate | Local command | CI step | |---|---|---| @@ -13,16 +29,25 @@ Every CI step runs the same Composer script a developer can run locally (`compos | Whitespace | `composer lint:whitespace` | same | | PHPStan (level max, no baseline) | `composer analyse` | same | | Tests | `composer test` | same | -| Composer audit | `composer audit:deps` | same | | Consumer Verification Harness | `composer harness` | `consumer-harness` job | +| Examples smoke execution | `composer examples` | `consumer-harness` job | +| Composer audit | `composer audit:deps` | same | | Workflow lint (actionlint 1.7.12) | `composer lint:workflows` | `workflow-lint` job | -CI (`.github/workflows/ci.yml`) runs PHP 8.4 and 8.5 with latest dependencies and PHP 8.4 with lowest dependencies, then a stable `CI gate` job that is the one to require in branch protection. `composer.lock` is not committed; CI resolves dependencies with `composer update`. +CI (`.github/workflows/ci.yml`) runs PHP 8.4 and 8.5 with latest dependencies and PHP 8.4 with lowest dependencies, then a stable `CI gate` job that is the one to require in branch protection. Prerequisites: PHP matching `require.php`, Composer 2, and `actionlint` (or Linux x86_64, where `scripts/lint-workflows.sh` downloads a checksum-verified copy). `composer check:php-floors` fails on an interpreter below the security patch floor; that is intentional. -`composer harness` installs a `git archive` of the committed tree (plus tracked edits; honours `.gitattributes` `export-ignore`) into a clean consumer project twice, with `--no-dev` and production autoload, then exercises the public API and checks the consumer's log files. Locally, set `HARNESS_COMPOSER_FLAGS=--ignore-platform-req=php` if your PHP is below the patch floor (CI never does). +`composer harness` and `composer examples` install a `git archive` of the committed tree (plus tracked working-tree edits; stage new files first; honours `.gitattributes` `export-ignore`) into a clean consumer project with `--no-dev` and production autoload. Locally, set `HARNESS_COMPOSER_FLAGS=--ignore-platform-req=php` if your PHP is below the patch floor (CI never does). + +## Test and integration requirements + +There is no database or service dependency, so no Integration infrastructure is needed. Unit tests are in `tests/`; the end-to-end test and the harness exercise the public API through a clean consumer root. + +## `composer.lock` policy + +`composer.lock` is not committed (reusable library); CI resolves dependencies with `composer update`. ## Release Artifact Verification -`composer release:verify ` (CI: manual `Release Artifact Verification` workflow with the exact target) checks the archived tree of the candidate SHA for target `X`: manifest, required release-facing files, the undated `## [X]` CHANGELOG section, empty `[Unreleased]`, README install target, SECURITY identity badges and archive contents. It prints the target, SHA and every check outcome, and fails closed. It is **expected to fail today**: `SECURITY.md`, `CODE_OF_CONDUCT.md`, `LICENSE`, `llms.txt`, `docs/guides/USAGE_GUIDE.md` and `examples/` do not exist yet and need owner-approved content. README/SECURITY wording still needs the semantic review the standard requires. +`composer release:verify ` (CI: the manual `Release Artifact Verification` workflow with the exact target) checks the archived tree of the candidate SHA for target `X`: manifest, required release-facing files, the undated `## [X]` CHANGELOG section, empty `[Unreleased]`, README install target, SECURITY identity badges, `llms.txt` structure and links, and archive contents. It prints the target, SHA and every check outcome, and fails closed. README and SECURITY wording still need the semantic review the standard requires. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3dd0549 --- /dev/null +++ b/LICENSE @@ -0,0 +1,16 @@ +Proprietary License + +Copyright (c) 2025 Maatify. All rights reserved. + +This software and its associated documentation are proprietary to Maatify. + +No rights or licenses are granted to use, copy, modify, merge, publish, +distribute, sublicense, sell, or otherwise transfer this software or any +substantial portion of it except under a separate written agreement or +with prior written permission from Maatify. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. + +For licensing inquiries, contact Maatify through its official channels. diff --git a/LOGGER_PACKAGE_REFERENCE.md b/LOGGER_PACKAGE_REFERENCE.md new file mode 100644 index 0000000..0d7b37a --- /dev/null +++ b/LOGGER_PACKAGE_REFERENCE.md @@ -0,0 +1,69 @@ +# Maatify Logger — Package Reference + +The canonical public, runtime and behavioral contract of `maatify/logger` and the complete Public Runtime API inventory. [README.md](README.md) gives the overview; [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md) gives walkthroughs. Package identity, PHP and dependency constraints are owned by [composer.json](composer.json). + +## 1. Public Runtime API + +Namespace `Maatify\Logger`. Anything not listed here is not part of the supported contract. + +### 1.1 `Logger` (implements `Psr\Log\LoggerInterface`) + +| Member | Contract | +|---|---| +| `new Logger()` | Creates the Monolog backend (channel `maatify`, one stream handler) when `Monolog\Logger` is loadable. | +| `emergency/alert/critical/error/warning/notice/info/debug($message, array $context = [])` | PSR-3 level methods; delegate to `log()`. | +| `log($level, $message, array $context = []): void` | Core call. `$level` must be a PSR-3 level name (case-insensitive); `$message` may be a string, `Stringable`, array or `Throwable`. | +| `static RecordLog(string\|array\|Throwable $message, string $level = 'info', string $logFile = 'app'): void` | Legacy entry point; creates a `Logger` and logs with `['logFile' => $logFile]`. | +| `LEVEL_INFO`, `LEVEL_ERROR`, `LEVEL_DEBUG` | Legacy level constants (PSR-3 level names). | +| `static setSensitiveKeys(array $keys): void` | Replaces the list of sensitive context keys (case-insensitive substring match). | +| `static setRedactor(?callable $redactor): void` | Registers (or with `null` removes) a hook `fn(array $context): array` run after built-in masking. | +| `static redactContext(array $context): array` | Applies built-in masking and the hook; never throws. | +| `static sanitizeRequestUri(mixed $uri): string` | Returns the path of a request URI without query string or fragment; `''` for missing or non-string input. | +| `static logFullRequestUri(bool $enabled): void` | Opt-in to keep the full URI in `sanitizeRequestUri()`. Default off. | + +### 1.2 `LoggerService` (final, static facade) + +| Member | Contract | +|---|---| +| `log(string $level, string\|array\|Throwable $message, string $logFile = 'app')` | Generic call. | +| `emergency/alert/critical/error/warning/notice/info/debug(string\|array\|Throwable $message, string $logFile = 'app')` | Level wrappers. | +| `logException(Throwable $e, string $logFile = 'exceptions', string $level = 'error', array $context = [])` | Logs `'Exception captured'` with the exception details and the extra context. | + +The constructor is private; the class holds one shared `Logger`. + +## 2. Behavior + +### 2.1 Messages +An array message is logged as `'Array log entry'` with the array under `context.data`. A `Throwable` message is logged as `'Exception log entry'` with its details under `context.exception`. + +### 2.2 Backends and files +- With Monolog loadable (always, when installed through Composer), entries are written to `logs/YYYY/MM/DD/HH/app_YYYY-MM-DD-HH.log` under the consumer project root (the directory four levels above the package `src/`, i.e. the project root for `vendor/maatify/logger`). The `logFile` argument is not used for routing; it is carried in the context. +- Only when Monolog is not loadable, the file fallback writes pretty-printed JSON entries to `logs/YYYY/MM/DD/HH/_YYYY-MM-DD-HH.log`; a `/` in `logFile` creates sub-folders. Each created folder receives an `index.php` that answers `404`. +- Fallback I/O failures are written to `error_logger.log` and never thrown. + +### 2.3 Fallback entry shape +`level`, `time`, `server` (`REMOTE_ADDR` or `CLI`, `HTTP_HOST`, `REQUEST_URI` path only, `USER_AGENT`), `message`, `context`. + +### 2.4 Redaction (both backends) +Applied to the message and context on every call, before any write: +1. Context keys containing a sensitive key (default: `password`, `passwd`, `secret`, `token`, `authorization`, `api_key`, `apikey`, `sig`, `signature`, `otp`, `cookie`) get the value `***REDACTED***`, recursively. +2. Strings are scrubbed of `key=value` / `key: value` secrets for those keys and of `Bearer ` / `Basic ` values. +3. `Throwable` objects anywhere in the context become arrays (`class`, `message`, `code`, `file`, `line`, `trace`, `previous`) with message and trace scrubbed. +4. Nesting deeper than 8 levels is truncated, so circular structures are safe. +5. The optional hook runs last. If it throws, the context becomes `['redaction' => 'failed']`. + +Matching is by substring: a key such as `design` also contains `sig` and is masked. + +## 3. Errors + +| Condition | Result | +|---|---| +| `log()` with a non-string or unknown level | `Psr\Log\InvalidArgumentException` | +| Redaction hook throws or returns a non-array | Context replaced by a failure marker; logging continues | +| Fallback write or folder failure | Recorded in `error_logger.log`; no exception | + +Exceptions raised by Monolog's own handlers are not caught by the package. + +## 4. Boundaries and non-goals + +No log rotation, retention, shipping or sampling; no per-call routing with Monolog; no guarantee that arbitrary application secrets are recognized (configure sensitive keys or a hook). diff --git a/README.md b/README.md index 33aef36..3c630f4 100644 --- a/README.md +++ b/README.md @@ -1,171 +1,145 @@ -[![Current version](https://img.shields.io/packagist/v/maatify/logger)](https://packagist.org/packages/maatify/logger) -[![Packagist PHP Version Support](https://img.shields.io/packagist/php-v/maatify/logger)](https://packagist.org/packages/maatify/logger) +
+ +# Maatify Logger + + + + + Maatify.dev + + +[![Status](https://img.shields.io/badge/Status-Release%20Preparation-blue)](CHANGELOG.md) +[![PHP](https://img.shields.io/badge/PHP-%3E%3D8.4.27-8892BF)](composer.json) +[![License](https://img.shields.io/badge/License-Proprietary-green)](LICENSE) +[![PHPStan](https://img.shields.io/badge/PHPStan-Level%20Max-4E8CAE)](phpstan.neon) + +[![Packagist](https://img.shields.io/badge/Packagist-Distribution-blue)](https://packagist.org/packages/maatify/logger) [![Monthly Downloads](https://img.shields.io/packagist/dm/maatify/logger)](https://packagist.org/packages/maatify/logger/stats) [![Total Downloads](https://img.shields.io/packagist/dt/maatify/logger)](https://packagist.org/packages/maatify/logger/stats) +[![Maatify Ecosystem](https://img.shields.io/badge/Maatify-Ecosystem-blueviolet)](https://github.com/Maatify) +[![Install](https://img.shields.io/badge/Install-7.0.0-blue)](#installation) + +[![Usage Guide](https://img.shields.io/badge/Docs-Usage%20Guide-informational)](docs/guides/USAGE_GUIDE.md) +[![Examples](https://img.shields.io/badge/Docs-Examples-informational)](examples/) +[![Package Reference](https://img.shields.io/badge/Docs-Package%20Reference-informational)](LOGGER_PACKAGE_REFERENCE.md) +[![Changelog](https://img.shields.io/badge/Docs-Changelog-informational)](CHANGELOG.md) +[![Security](https://img.shields.io/badge/Docs-Security-informational)](SECURITY.md) +[![Contributing](https://img.shields.io/badge/Docs-Contributing-informational)](CONTRIBUTING.md) -# 📜 Maatify Logger +`maatify/logger` is a PSR-3 compatible logger for PHP: a Monolog-backed `Logger`, a static `LoggerService` facade, a legacy `RecordLog` entry point, redaction of secrets before anything is written, and a JSON file fallback used only when Monolog is not loadable. -A lightweight PSR-3 compatible Logger with **Monolog integration** (if available) and **file fallback** (date/hour folders). -Supports **legacy logging**, **modern PSR-3 methods**, and a **facade service** for easy usage. +Release Target: `7.0.0` · Release Preparation: active · Publication State of `7.0.0` at qualification: not published. + +
--- -## ✨ Features +## Key Features -- ✅ **PSR-3 compliant** (`LoggerInterface`, `LogLevel`). -- ✅ **Monolog integration** (if installed) – automatic backend. -- ✅ **File fallback** if Monolog is not available (organized by `year/month/day/hour`). -- ✅ **Structured JSON logs** (server info + message + context). -- ✅ **Facade service** (`LoggerService`) with static methods for quick usage. -- ✅ **Exception logging** via `logException()`. -- ✅ **Legacy support** (`RecordLog`) for old codebases. +- **PSR-3 logger:** `Maatify\Logger\Logger` implements `Psr\Log\LoggerInterface`. +- **Facade and legacy entry points:** static `LoggerService` methods and `Logger::RecordLog()` for existing code. +- **Secrets are redacted before they are written:** sensitive context keys, `key=value` secrets, `Authorization: Bearer/Basic` values and `Throwable` messages and traces are masked. The list and a custom hook are configurable. +- **Request path only:** the file fallback records `REQUEST_URI` without its query string or fragment; the full URI is an explicit opt-in. +- **Time-partitioned files:** `logs/YYYY/MM/DD/HH/` with a `404` `index.php` guard in each created folder. +- **Never throws on I/O failure in the fallback:** write problems go to an internal error file instead. ---- +## Requirements -## 📦 Installation +[composer.json](composer.json) is the source of truth for requirements and dependencies; this table reflects it. -```bash -composer require maatify/logger -```` +| Requirement | Constraint | +|---|---| +| PHP | `>=8.4.27 <8.5.0 \|\| >=8.5.12 <8.6.0` | +| Extensions | `ext-json` | +| `monolog/monolog` | `^3.9` | +| `psr/log` | `^3.0` | -If you also want Monolog support: +## Installation + +Install the exact release target: ```bash -composer require monolog/monolog +composer require maatify/logger:7.0.0 ``` ---- - -## 🔧 Usage +The command resolves through Packagist only after this exact version is published; the existence of this source tree does not publish it. -### 1. Using the Facade (`LoggerService`) +## Quick Usage ```php use Maatify\Logger\LoggerService; -// Info log -LoggerService::info("User login successful", "auth/logs"); +LoggerService::info('User login successful', 'auth/logs'); -// Error log with Exception try { - throw new RuntimeException("DB connection failed"); + throw new RuntimeException('DB connection failed'); } catch (Throwable $e) { - LoggerService::logException($e, "system/errors"); + LoggerService::logException($e, 'system/errors', context: ['requestId' => 'abc123']); } - -// Debug log with context -LoggerService::debug("Payment request", "payments/debug", [ - 'userId' => 123, - 'amount' => 99.99, -]); ``` ---- +Complete, runnable examples: [examples/](examples/). Walkthroughs: [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md). -### 2. Generic Logger Method +## Public Runtime API -```php -use Maatify\Logger\LoggerService; -use Psr\Log\LogLevel; +An overview only. The complete inventory (signatures, behavior, errors) is [LOGGER_PACKAGE_REFERENCE.md](LOGGER_PACKAGE_REFERENCE.md). -LoggerService::log(LogLevel::CRITICAL, "Out of memory!", "system/critical"); -``` +| Area | Types | +|---|---| +| PSR-3 logger | `Logger` (`emergency()` … `debug()`, `log()`) | +| Facade | `LoggerService` (static `log()`, level methods, `logException()`) | +| Legacy | `Logger::RecordLog()`, `Logger::LEVEL_*` constants | +| Redaction | `Logger::setSensitiveKeys()`, `Logger::setRedactor()`, `Logger::redactContext()` | +| Request URI policy | `Logger::sanitizeRequestUri()`, `Logger::logFullRequestUri()` | ---- +## Critical Runtime Behavior -### 3. Exception Logging with Extra Context +- **Monolog is the active backend:** because `monolog/monolog` is a required dependency, entries go to `logs/YYYY/MM/DD/HH/app_YYYY-MM-DD-HH.log`. The per-call log file name only routes files in the file fallback; with Monolog it is carried in the context. +- **Redaction runs first** on every call, in both backends, and never throws. +- **Invalid level:** a non-string or unknown level throws `Psr\Log\InvalidArgumentException`. -```php -try { - throw new RuntimeException("Unauthorized access"); -} catch (Throwable $e) { - LoggerService::logException( - $e, - "security/errors", - LogLevel::CRITICAL, - [ - 'userId' => 42, - 'requestId' => 'abc123', - 'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown', - ] - ); -} -``` - ---- - -### 4. Legacy Support +## Security and Trust Boundaries -For old codebases still using `RecordLog`: +The package masks well-known secret shapes; it cannot know every application secret. Add your own keys with `Logger::setSensitiveKeys()` or a hook with `Logger::setRedactor()`. `REMOTE_ADDR` and `USER_AGENT` are written by the file fallback unconditionally; apply your own retention policy to log files. See [SECURITY.md](SECURITY.md) for reporting. -```php -use Maatify\Logger\Logger; +## Examples -Logger::RecordLog("Old style log", Logger::LEVEL_INFO, "legacy/system"); -``` +Maintained, smoke-executed examples using only the Public Runtime API: [examples/](examples/). ---- +## Documentation -## 📂 Log Storage Structure +- [Usage Guide](docs/guides/USAGE_GUIDE.md) +- [Package Reference](LOGGER_PACKAGE_REFERENCE.md) +- [Changelog](CHANGELOG.md) +- [Security Policy](SECURITY.md) +- [Contributing](CONTRIBUTING.md) -When using fallback file logging (without Monolog), logs are stored under: +## Quality Status -``` -logs/YYYY/MM/DD/HH/_YYYY-MM-DD-HH.log -``` +PHPStan level max with no baseline, a PHPUnit suite, a Consumer Verification Harness (clean consumer install, production autoload) and smoke-executed examples run in [CI](.github/workflows/ci.yml); the `CI gate` job aggregates them. -Example: +## Development and Testing -``` -logs/2025/09/04/16/system_errors_2025-09-04-16.log +```bash +composer ci ``` -Each log entry is JSON formatted: - -```json -{ - "level": "ERROR", - "time": "2025-09-04 16:15:00", - "server": { - "REMOTE_ADDR": "127.0.0.1", - "HTTP_HOST": "example.com", - "REQUEST_URI": "/login", - "USER_AGENT": "Mozilla/5.0" - }, - "message": "Exception captured", - "context": { - "userId": 42, - "exception": { - "message": "Unauthorized access", - "file": "/var/www/app/login.php", - "line": 88, - "code": 0, - "trace": "stack trace..." - } - } -} -``` +Each gate and its CI mapping are listed in [CONTRIBUTING.md](CONTRIBUTING.md). ---- +## License -## ⚙️ Configuration +Proprietary. See [LICENSE](LICENSE). -* Default log path: `./logs` -* Default file extension: `.log` -* Default fallback log level: `info` -* Uses Monolog automatically if installed. +## 👤 Author ---- - -## 🛡️ License - -This project is proprietary ©2025 [Maatify.dev](https://maatify.dev) +Engineered by **Mohamed Abdulalim** ([@megyptm](https://github.com/megyptm))
+Backend Lead & Technical Architect
+[https://www.maatify.dev](https://www.maatify.dev) --- -## ✍️ Author - -**Mohamed Abdulalim** -[maatify.dev](https://maatify.dev) – [GitHub](https://github.com/Maatify) +
+[Built with ❤️ by Maatify.dev — Unified Ecosystem for Modern PHP Libraries](https://www.maatify.dev) +
diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..4a4f691 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,18 @@ +# Security Policy + +[![Maatify Logger](https://img.shields.io/badge/Maatify-Logger-blue?style=for-the-badge)](https://github.com/Maatify/Logger) +[![Maatify Ecosystem](https://img.shields.io/badge/Maatify-Ecosystem-9C27B0?style=for-the-badge)](https://github.com/Maatify) + +## Current Support State + +This tree is the release artifact for target `7.0.0`. It does not establish that `7.0.0` is published, and it does not define a supported release line; the supported release lines are recorded here only after a release is published and the maintainers have decided its support. + +## Reporting a Vulnerability + +Please report suspected package vulnerabilities privately to [support@maatify.dev](mailto:support@maatify.dev). Do not report a vulnerability in a public issue. + +Include the affected package or context, reproducible details, the potential impact, and the relevant environment, version, or commit when known. No response time is promised. + +## Scope + +This policy covers vulnerabilities in the package's logging, redaction and file-writing behavior. Host authentication, authorization, deployment, log retention and infrastructure defects belong with the owner of the relevant Host. diff --git a/composer.json b/composer.json index a91df1e..ee09872 100644 --- a/composer.json +++ b/composer.json @@ -1,13 +1,15 @@ { "name": "maatify/logger", - "description": "maatify.dev logger, known by our team", + "description": "PSR-3 compatible PHP logger with a Monolog backend, secret redaction and a JSON file fallback", "type": "library", "keywords": [ - "PHP", - "Logger", - "Handler" + "php", + "maatify", + "logger", + "psr-3", + "monolog" ], - "homepage": "https://github.com/Maatify/", + "homepage": "https://github.com/Maatify/Logger", "license": "proprietary", "authors": [ { @@ -85,9 +87,11 @@ "@analyse", "@test", "@harness", + "@examples", "@audit:deps" ], "harness": "scripts/consumer-harness.sh", - "release:verify": "php scripts/verify-release-artifact.php" + "release:verify": "php scripts/verify-release-artifact.php", + "examples": "scripts/run-examples.sh" } } diff --git a/docs/guides/USAGE_GUIDE.md b/docs/guides/USAGE_GUIDE.md new file mode 100644 index 0000000..98686d6 --- /dev/null +++ b/docs/guides/USAGE_GUIDE.md @@ -0,0 +1,32 @@ +# Maatify Logger — Usage Guide + +## Fit, requirements and non-goals + +Use `maatify/logger` when you want a PSR-3 logger that writes time-partitioned files and masks secrets before they are written. Requirements are in [README.md](../../README.md#requirements). It is not a log shipper, rotator or retention tool. The complete contract is [LOGGER_PACKAGE_REFERENCE.md](../../LOGGER_PACKAGE_REFERENCE.md). + +Logs are written under the root of the consuming project, in `logs/YYYY/MM/DD/HH/`. + +## Capability map + +| Capability | Walkthrough | Example | +|---|---|---| +| Log through the static facade | [1](#1-facade-logging) | [01-facade.php](../../examples/01-facade.php) | +| Use as a PSR-3 logger | [2](#2-psr-3-logger) | [02-psr3.php](../../examples/02-psr3.php) | +| Log exceptions with context | [3](#3-exceptions) | [03-exceptions.php](../../examples/03-exceptions.php) | +| Redact secrets and customize masking | [4](#4-redaction) | [04-redaction.php](../../examples/04-redaction.php) | + +## 1. Facade logging + +Input: a message (string, array or `Throwable`) and optional log file name. Public call: `LoggerService::info()` and the other level methods, or `LoggerService::log($level, ...)`. Result: one entry in the current hour's file. Boundary: with Monolog the file is always `app_...log`; the file name only routes in the fallback. + +## 2. PSR-3 logger + +Input: a PSR-3 level and message with context. Public call: `(new Logger())->error('...', [...])` or any PSR-3 consumer receiving a `Psr\Log\LoggerInterface`. Result: an entry with the context. Boundary: an unknown level throws `Psr\Log\InvalidArgumentException`. + +## 3. Exceptions + +Input: a `Throwable` and optional extra context. Public call: `LoggerService::logException($e, 'system/errors', 'error', ['requestId' => 'abc'])`. Result: an `'Exception captured'` entry with message, file, line, code and trace, scrubbed of secrets. Boundary: only the documented fields are logged. + +## 4. Redaction + +Input: context containing secrets. Public call: nothing extra for the defaults; `Logger::setSensitiveKeys([...])` replaces the key list and `Logger::setRedactor(fn (array $c): array => ...)` adds a hook. Result: `***REDACTED***` for sensitive keys and scrubbed strings. Boundary: only known shapes are masked; add your own keys for application-specific secrets. diff --git a/examples/01-facade.php b/examples/01-facade.php new file mode 100644 index 0000000..bebd7d4 --- /dev/null +++ b/examples/01-facade.php @@ -0,0 +1,14 @@ + 123, 'amount' => 99.99], 'payments/debug'); +LoggerService::log(LogLevel::CRITICAL, 'Out of memory!', 'system/critical'); + +echo "facade example ok\n"; diff --git a/examples/02-psr3.php b/examples/02-psr3.php new file mode 100644 index 0000000..a836bb9 --- /dev/null +++ b/examples/02-psr3.php @@ -0,0 +1,23 @@ +warning('Cache miss ratio high', ['ratio' => 0.42]); +} + +handle(new Logger()); + +try { + (new Logger())->log('not-a-level', 'x'); +} catch (Psr\Log\InvalidArgumentException $e) { + echo "unknown level rejected\n"; +} + +echo "psr3 example ok\n"; diff --git a/examples/03-exceptions.php b/examples/03-exceptions.php new file mode 100644 index 0000000..5d2b7e8 --- /dev/null +++ b/examples/03-exceptions.php @@ -0,0 +1,16 @@ + 'abc123']); +} + +echo "exceptions example ok\n"; diff --git a/examples/04-redaction.php b/examples/04-redaction.php new file mode 100644 index 0000000..5f32e66 --- /dev/null +++ b/examples/04-redaction.php @@ -0,0 +1,30 @@ + 'ali', + 'password' => 'hunter2', + 'iban' => 'EG00 0000', + 'internalNote' => 'drop me', + 'message' => 'callback failed token=abc123', +]); + +if (($masked['password'] ?? null) === 'hunter2' || str_contains(json_encode($masked, JSON_THROW_ON_ERROR), 'abc123')) { + fwrite(STDERR, "secret leaked\n"); + exit(1); +} + +(new Logger())->info('redaction example', $masked); + +echo "redaction example ok\n"; diff --git a/examples/_bootstrap.php b/examples/_bootstrap.php new file mode 100644 index 0000000..d1abd70 --- /dev/null +++ b/examples/_bootstrap.php @@ -0,0 +1,11 @@ + PSR-3 compatible PHP logger with a Monolog backend, a static facade, a legacy entry point, redaction of secrets before writing, and a JSON file fallback. Standalone Composer package; release target 7.0.0. + +This file is for an AI agent that consumes the package, not one that modifies it. The supported contract is what the linked consumer documents describe. Visible in the repository does not mean supported: do not treat `src/` internals, tests, fixtures, scripts, undocumented classes or methods, or internal engineering files as a consumer contract, and do not invent a contract the documents below do not state. + +## Start here + +- [README.md](README.md): overview, requirements, installation, quick usage, Public Runtime API overview. +- [LOGGER_PACKAGE_REFERENCE.md](LOGGER_PACKAGE_REFERENCE.md): the canonical public, runtime and behavioral contract and the complete Public Runtime API inventory. +- [docs/guides/USAGE_GUIDE.md](docs/guides/USAGE_GUIDE.md): integration walkthroughs and boundaries. +- [examples/](examples/): maintained, executable examples that use only the Public Runtime API. + +## Release and state + +- [CHANGELOG.md](CHANGELOG.md): release history and the `7.0.0` target section. +- [SECURITY.md](SECURITY.md): support state and private vulnerability reporting. +- [composer.json](composer.json): the only owner of package identity, PHP and extension requirements, dependencies and autoload. diff --git a/phpstan.neon b/phpstan.neon index 1494f51..efbd19a 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -3,3 +3,4 @@ parameters: paths: - src - tests + - examples diff --git a/scripts/lint-php.php b/scripts/lint-php.php index 41a741a..6fa714d 100644 --- a/scripts/lint-php.php +++ b/scripts/lint-php.php @@ -7,7 +7,7 @@ $failed = 0; $count = 0; -foreach (['src', 'tests', 'scripts'] as $dir) { +foreach (['src', 'tests', 'scripts', 'examples'] as $dir) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root . '/' . $dir, FilesystemIterator::SKIP_DOTS)); foreach ($it as $file) { if ($file->getExtension() !== 'php') { diff --git a/scripts/run-examples.sh b/scripts/run-examples.sh new file mode 100644 index 0000000..34c3830 --- /dev/null +++ b/scripts/run-examples.sh @@ -0,0 +1,41 @@ +#!/usr/bin/env bash +# Smoke-executes every example against a clean consumer install (production autoload, no dev dependencies), +# so example logs land in a throw-away consumer root. Fails closed. +# Local-only: HARNESS_COMPOSER_FLAGS (e.g. --ignore-platform-req=php) for PHP below the patch floor. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +FLAGS="${HARNESS_COMPOSER_FLAGS:-}" +WORK="$(mktemp -d)" +trap 'rm -rf "$WORK"' EXIT + +TREE="$(git -C "$ROOT" stash create 2>/dev/null || true)" +mkdir "$WORK/snapshot" "$WORK/consumer" +git -C "$ROOT" archive "${TREE:-HEAD}" | tar -x -C "$WORK/snapshot" + +cat > "$WORK/consumer/composer.json" <&2; exit 1; } +count=0 +for example in "$WORK"/snapshot/examples/[0-9]*.php; do + [ -e "$example" ] || { echo "no examples found" >&2; exit 1; } + echo "== $(basename "$example")" + (cd "$WORK/consumer" && MAATIFY_EXAMPLES_AUTOLOAD="$WORK/consumer/vendor/autoload.php" php "$example") + count=$((count + 1)) +done +echo "Examples OK ($count executed)" diff --git a/scripts/verify-release-artifact.php b/scripts/verify-release-artifact.php index 4a08717..aec8d84 100644 --- a/scripts/verify-release-artifact.php +++ b/scripts/verify-release-artifact.php @@ -41,7 +41,7 @@ $check('composer.lock is not distributed', !is_file("$tmp/composer.lock")); // Required release-facing files (LIBRARY_PRESENTATION_STANDARD §6) -foreach (['README.md', 'CHANGELOG.md', 'SECURITY.md', 'CONTRIBUTING.md', 'CODE_OF_CONDUCT.md', 'LICENSE', 'composer.json', 'llms.txt', 'docs/guides/USAGE_GUIDE.md'] as $f) { +foreach (['README.md', 'LOGGER_PACKAGE_REFERENCE.md', 'CHANGELOG.md', 'SECURITY.md', 'CONTRIBUTING.md', 'CODE_OF_CONDUCT.md', 'LICENSE', 'composer.json', 'llms.txt', 'docs/guides/USAGE_GUIDE.md'] as $f) { $check("required file present: $f", is_file("$tmp/$f")); } $check('examples/ present and non-empty', is_dir("$tmp/examples") && (glob("$tmp/examples/*") ?: []) !== []); @@ -56,12 +56,32 @@ // README identity / install target $readme = $read('README.md'); -$check('README names the exact install target', str_contains($readme, $target)); +$check('README shows the exact install command', str_contains($readme, 'composer require maatify/logger:' . $target)); +$check('README ends with the canonical Maatify footer', str_ends_with(rtrim($readme), "") && str_contains($readme, '[Built with ❤️ by Maatify.dev — Unified Ecosystem for Modern PHP Libraries](https://www.maatify.dev)')); +$check('README has the canonical Author block', str_contains($readme, 'Engineered by **Mohamed Abdulalim** ([@megyptm](https://github.com/megyptm))
')); +$check('README has a single H1 inside the header block', preg_match_all('/^# /m', $readme) === 1); // SECURITY.md identity badges $security = $read('SECURITY.md'); $check('SECURITY.md has repository + ecosystem identity badges', str_contains($security, 'github.com/Maatify/Logger') && str_contains($security, 'https://github.com/Maatify)')); +$check('SECURITY.md identifies the exact target', str_contains($security, $target)); + +// llms.txt structure and links (LIBRARY_PRESENTATION_STANDARD §10.3) +$llms = $read('llms.txt'); +$check('llms.txt has exactly one H1', preg_match_all('/^# /m', $llms) === 1); +$check('llms.txt has a blockquote summary', preg_match('/^> .+/m', $llms) === 1); +$badLinks = []; +if (preg_match_all('/\]\(([^)#]+)\)/', $llms, $links) > 0) { + foreach ($links[1] as $link) { + if (!preg_match('#^https?://#', $link) && !file_exists("$tmp/" . rtrim($link, '/'))) { + $badLinks[] = $link; + } + } +} +$check('llms.txt links resolve', $badLinks === [], implode(', ', $badLinks)); +$check('llms.txt links the Package Reference, Usage Guide and examples', str_contains($llms, '(LOGGER_PACKAGE_REFERENCE.md)') && str_contains($llms, '(docs/guides/USAGE_GUIDE.md)') && str_contains($llms, '(examples/)')); + // Archive exclusions must not drop required files nor include secrets / dev artifacts $bad = []; foreach (['.env', 'vendor', 'logs', 'error_logger.log'] as $p) { From 78faf386235c0216686dc8b06709df7ccdef05c8 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:04:47 +0200 Subject: [PATCH 07/13] Make run-examples.sh executable and verify script modes in release check (#2) Co-Authored-By: Claude Sonnet 5.5 --- scripts/run-examples.sh | 0 scripts/verify-release-artifact.php | 9 +++++++++ 2 files changed, 9 insertions(+) mode change 100644 => 100755 scripts/run-examples.sh diff --git a/scripts/run-examples.sh b/scripts/run-examples.sh old mode 100644 new mode 100755 diff --git a/scripts/verify-release-artifact.php b/scripts/verify-release-artifact.php index aec8d84..c5aa162 100644 --- a/scripts/verify-release-artifact.php +++ b/scripts/verify-release-artifact.php @@ -82,6 +82,15 @@ $check('llms.txt links resolve', $badLinks === [], implode(', ', $badLinks)); $check('llms.txt links the Package Reference, Usage Guide and examples', str_contains($llms, '(LOGGER_PACKAGE_REFERENCE.md)') && str_contains($llms, '(docs/guides/USAGE_GUIDE.md)') && str_contains($llms, '(examples/)')); +// Shell scripts must keep their executable bit in the committed tree +$nonExec = []; +foreach (explode("\n", trim((string) shell_exec('git -C ' . escapeshellarg($root) . ' ls-files -s -- "scripts/*.sh"'))) as $line) { + if ($line !== '' && !str_starts_with($line, '100755')) { + $nonExec[] = substr($line, strrpos($line, "\t") + 1); + } +} +$check('committed shell scripts are executable', $nonExec === [], implode(', ', $nonExec)); + // Archive exclusions must not drop required files nor include secrets / dev artifacts $bad = []; foreach (['.env', 'vendor', 'logs', 'error_logger.log'] as $p) { From ec42b350f6b2611b68a4d270bfcc5b47a3e0bbed Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:17:25 +0200 Subject: [PATCH 08/13] Mask secrets inside context objects, rescan redactor output, document cleanup service (#2) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + LOGGER_PACKAGE_REFERENCE.md | 23 +++++++++--- docs/guides/USAGE_GUIDE.md | 6 +++- src/Logger.php | 36 ++++++++++++++++++- tests/EndToEndLoggingTest.php | 6 +++- tests/RedactionTest.php | 67 +++++++++++++++++++++++++++++++++++ 6 files changed, 132 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 33cb4ee..41e46e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ - `Logger::setSensitiveKeys([...])` replaces the key list, `Logger::setRedactor(callable)` adds a custom hook that receives the full context. A throwing hook never breaks logging and never leaks the original context. - Behaviour change: values under the default sensitive keys now appear as `***REDACTED***` in logs. +- Objects in the context are expanded and masked before reaching any backend (`JsonSerializable` output, `Stringable` string, public properties); a redaction hook's output is masked again. Object entries now log as `['class' => ..., 'properties' => ...]` instead of Monolog's own object rendering. - `Throwable` objects placed anywhere in the context are converted to a scrubbed array (class, message, code, file, line, trace, previous) before reaching Monolog. - `Authorization: Bearer/Basic ` values are redacted from free text. - Redaction is depth-limited (8 levels), so circular or very deep contexts cannot exhaust memory. diff --git a/LOGGER_PACKAGE_REFERENCE.md b/LOGGER_PACKAGE_REFERENCE.md index 0d7b37a..99b0ac4 100644 --- a/LOGGER_PACKAGE_REFERENCE.md +++ b/LOGGER_PACKAGE_REFERENCE.md @@ -4,7 +4,7 @@ The canonical public, runtime and behavioral contract of `maatify/logger` and th ## 1. Public Runtime API -Namespace `Maatify\Logger`. Anything not listed here is not part of the supported contract. +Namespace `Maatify\Logger`. Anything not listed here is not part of the supported contract. This section is the complete inventory of the public classes. ### 1.1 `Logger` (implements `Psr\Log\LoggerInterface`) @@ -31,6 +31,20 @@ Namespace `Maatify\Logger`. Anything not listed here is not part of the supporte The constructor is private; the class holds one shared `Logger`. +### 1.3 `LoggerCleanupService` (final) + +| Member | Contract | +|---|---| +| `new LoggerCleanupService(?string $logBasePath = null)` | Directory to clean. **The default is `dirname(__DIR__, 2) . '/logs'`, which inside `vendor/maatify/logger` is `vendor/maatify/logs`, not the `logs/` folder the logger writes to. Always pass the log directory explicitly.** | +| `deleteOlderThanDays(int $days): void` | Deletes files under the directory whose modification time is older than the threshold, then removes empty sub-directories. | +| `deleteOlderThanHours(int $hours): void` | Same, with an hours threshold. | + +A missing directory is ignored; deletion errors are suppressed. The service deletes files permanently. + +### 1.4 `Maatify\Store\File\Path` (legacy helper) + +`new Path(string $path = '')` and `Get(): string` return the given path (default: the directory above the package namespace folder) followed by four `..` segments and a trailing separator. It is not used by `Logger` or `LoggerService` and is kept only for existing callers; new code should not depend on it. + ## 2. Behavior ### 2.1 Messages @@ -49,8 +63,9 @@ Applied to the message and context on every call, before any write: 1. Context keys containing a sensitive key (default: `password`, `passwd`, `secret`, `token`, `authorization`, `api_key`, `apikey`, `sig`, `signature`, `otp`, `cookie`) get the value `***REDACTED***`, recursively. 2. Strings are scrubbed of `key=value` / `key: value` secrets for those keys and of `Bearer ` / `Basic ` values. 3. `Throwable` objects anywhere in the context become arrays (`class`, `message`, `code`, `file`, `line`, `trace`, `previous`) with message and trace scrubbed. -4. Nesting deeper than 8 levels is truncated, so circular structures are safe. -5. The optional hook runs last. If it throws, the context becomes `['redaction' => 'failed']`. +4. Objects are expanded into what a formatter would serialize and then masked: `JsonSerializable` output, the string of a `Stringable`, otherwise `['class' => ..., 'properties' => ...]` from public properties. `DateTimeInterface` and enum values are kept as they are. An object whose serialization throws is replaced by `['class' => ..., 'unserializable' => true]`. +5. Nesting deeper than 8 levels is truncated, so circular structures (arrays or objects) are safe. +6. The optional hook runs last and its output is masked again with the same rules, so a hook cannot re-introduce a sensitive key or `key=value` secret. If the hook throws or returns a non-array, the context becomes `['redaction' => 'failed']`. Matching is by substring: a key such as `design` also contains `sig` and is masked. @@ -59,7 +74,7 @@ Matching is by substring: a key such as `design` also contains `sig` and is mask | Condition | Result | |---|---| | `log()` with a non-string or unknown level | `Psr\Log\InvalidArgumentException` | -| Redaction hook throws or returns a non-array | Context replaced by a failure marker; logging continues | +| Redaction hook throws or returns a non-array | Context replaced by `['redaction' => 'failed']`; logging continues | | Fallback write or folder failure | Recorded in `error_logger.log`; no exception | Exceptions raised by Monolog's own handlers are not caught by the package. diff --git a/docs/guides/USAGE_GUIDE.md b/docs/guides/USAGE_GUIDE.md index 98686d6..934757e 100644 --- a/docs/guides/USAGE_GUIDE.md +++ b/docs/guides/USAGE_GUIDE.md @@ -29,4 +29,8 @@ Input: a `Throwable` and optional extra context. Public call: `LoggerService::lo ## 4. Redaction -Input: context containing secrets. Public call: nothing extra for the defaults; `Logger::setSensitiveKeys([...])` replaces the key list and `Logger::setRedactor(fn (array $c): array => ...)` adds a hook. Result: `***REDACTED***` for sensitive keys and scrubbed strings. Boundary: only known shapes are masked; add your own keys for application-specific secrets. +Input: context containing secrets. Public call: nothing extra for the defaults; `Logger::setSensitiveKeys([...])` replaces the key list and `Logger::setRedactor(fn (array $c): array => ...)` adds a hook. Result: `***REDACTED***` for sensitive keys and scrubbed strings. Boundary: only known shapes are masked, including values reached through objects (`JsonSerializable`, `Stringable`, public properties); add your own keys for application-specific secrets. A hook's output is masked again, so it cannot re-introduce what the built-in rules mask. + +## Cleaning old logs + +`LoggerCleanupService` deletes files older than a number of days or hours. Pass the log directory explicitly (`new LoggerCleanupService('/path/to/project/logs')`); its default does not match where the logger writes. Deletion is permanent. diff --git a/src/Logger.php b/src/Logger.php index 06ad4eb..37ad688 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -247,7 +247,8 @@ public static function redactContext(array $context): array try { $context = self::maskKeys($context); if (self::$redactor !== null) { - $context = (self::$redactor)($context); + // The hook's output is re-scanned so it cannot re-introduce sensitive data. + $context = self::maskKeys((self::$redactor)($context)); } return $context; } catch (Throwable) { @@ -287,9 +288,42 @@ private static function maskValue(mixed $value, int $depth): mixed if ($value instanceof Throwable) { return self::describeThrowable($value, $depth); } + if (is_object($value)) { + return self::describeObject($value, $depth); + } return $value; } + /** + * Objects are expanded into the data a formatter would serialize (JsonSerializable output, __toString, + * public properties) and masked, so nothing sensitive reaches a backend through an object. + * Value objects without secrets (dates, enums) are kept as they are. + */ + private static function describeObject(object $value, int $depth): mixed + { + if ($value instanceof \DateTimeInterface || $value instanceof \UnitEnum) { + return $value; + } + if ($depth >= self::MAX_REDACTION_DEPTH) { + return ['truncated' => 'max depth reached']; + } + + try { + if ($value instanceof \JsonSerializable) { + return self::maskValue($value->jsonSerialize(), $depth + 1); + } + if ($value instanceof \Stringable) { + return self::scrubString((string) $value); + } + return [ + 'class' => $value::class, + 'properties' => self::maskKeys(get_object_vars($value), $depth + 1), + ]; + } catch (Throwable) { + return ['class' => $value::class, 'unserializable' => true]; + } + } + /** * Throwables are converted to a scrubbed array so their raw message never reaches the formatter. */ diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php index f3ad1e2..4d8081d 100644 --- a/tests/EndToEndLoggingTest.php +++ b/tests/EndToEndLoggingTest.php @@ -51,6 +51,10 @@ public function testSecretsNeverReachTheLogFile(): void $l->error(new RuntimeException("gateway said token=SECRET3")); $l->error("pay failed", ["exception" => new RuntimeException("token=SECRET4")]); $l->error("hdr Authorization: Bearer SECRET5"); +$l->error("obj", ["details" => new class implements JsonSerializable { public function jsonSerialize(): array { return ["password" => "SECRET6"]; } }]); +$l->error("str", ["s" => new class implements Stringable { public function __toString(): string { return "token=SECRET7"; } }]); +$plain = new stdClass(); $plain->password = "SECRET8"; +$l->error("plain", ["p" => $plain]); $loop = ["a" => 1]; $loop["self"] = &$loop; $l->error("loop", ["data" => $loop]); '); @@ -62,7 +66,7 @@ public function testSecretsNeverReachTheLogFile(): void $content = (string) file_get_contents((string) reset($files)); $this->assertStringContainsString('visible', $content); - foreach (['SECRET1', 'SECRET2', 'SECRET3', 'SECRET4', 'SECRET5'] as $secret) { + foreach (['SECRET1', 'SECRET2', 'SECRET3', 'SECRET4', 'SECRET5', 'SECRET6', 'SECRET7', 'SECRET8'] as $secret) { $this->assertStringNotContainsString($secret, $content); } } diff --git a/tests/RedactionTest.php b/tests/RedactionTest.php index 123eaf8..c413b82 100644 --- a/tests/RedactionTest.php +++ b/tests/RedactionTest.php @@ -95,4 +95,71 @@ public function testCircularAndDeepContextDoesNotExhaustMemory(): void } $this->assertNotEmpty(Logger::redactContext($deep)); } + + public function testJsonSerializableObjectsAreMasked(): void + { + $obj = new class implements \JsonSerializable { + /** @return array */ + public function jsonSerialize(): array + { + return ['password' => 'SECRET123', 'note' => 'token=SECRET124', 'ok' => 'visible']; + } + }; + $out = Logger::redactContext(['details' => $obj, 'nested' => ['deep' => $obj]]); + $json = self::json($out); + $this->assertStringNotContainsString('SECRET', $json); + $this->assertStringContainsString('visible', $json); + } + + public function testStringableObjectsAreScrubbed(): void + { + $obj = new class implements \Stringable { + public function __toString(): string + { + return 'failed with token=SECRET200'; + } + }; + $out = Logger::redactContext(['s' => $obj]); + $this->assertIsString($out['s']); + $this->assertStringNotContainsString('SECRET', $out['s']); + } + + public function testPlainObjectPublicPropertiesAreMasked(): void + { + $obj = new \stdClass(); + $obj->password = 'SECRET300'; + $obj->user = 'ali'; + $obj->child = new \stdClass(); + $obj->child->api_key = 'SECRET301'; + $json = self::json(Logger::redactContext(['o' => $obj])); + $this->assertStringNotContainsString('SECRET', $json); + $this->assertStringContainsString('ali', $json); + } + + public function testCircularAndThrowingObjectsNeverBreakLogging(): void + { + $a = new \stdClass(); + $a->self = $a; + $a->label = 'loop'; + $bad = new class implements \JsonSerializable { + public function jsonSerialize(): never + { + throw new \RuntimeException('boom token=SECRET400'); + } + }; + $badString = new class implements \Stringable { + public function __toString(): string + { + throw new \RuntimeException('boom'); + } + }; + $out = Logger::redactContext(['a' => $a, 'bad' => $bad, 'badString' => $badString]); + $this->assertStringNotContainsString('SECRET', self::json($out)); + } + + public function testRedactorOutputIsRescanned(): void + { + Logger::setRedactor(static fn(array $c): array => $c + ['password' => 'SECRET500', 'note' => 'token=SECRET501']); + $this->assertStringNotContainsString('SECRET', self::json(Logger::redactContext([]))); + } } From a4840fca8dad345c8b7ebd4f9faed6c717bdb902 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:18:46 +0200 Subject: [PATCH 09/13] Point LoggerCleanupService default at the logger's log directory (#2) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + LOGGER_PACKAGE_REFERENCE.md | 2 +- docs/guides/USAGE_GUIDE.md | 2 +- src/LoggerCleanupService.php | 2 +- tests/EndToEndLoggingTest.php | 23 ++++++++++++++++++++++- 5 files changed, 26 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 41e46e2..0254873 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ## [7.0.0] ### Changed (behaviour change) +- **Breaking:** `LoggerCleanupService` now defaults to the directory the logger writes to (`dirname(__DIR__, 4) . '/logs'`, the consumer project's `logs/`). Previously the default was `dirname(__DIR__, 2) . '/logs'`, which inside `vendor/` pointed at `vendor/maatify/logs` and cleaned nothing; callers relying on that default will now delete old files in the real log directory. - File-fallback log entries now record only the **path** of `REQUEST_URI` (no query string, no fragment). Signatures, tokens and one-time codes in query strings are no longer written to log files. Anything parsing the `server.REQUEST_URI` field will no longer see the query string. diff --git a/LOGGER_PACKAGE_REFERENCE.md b/LOGGER_PACKAGE_REFERENCE.md index 99b0ac4..0babb60 100644 --- a/LOGGER_PACKAGE_REFERENCE.md +++ b/LOGGER_PACKAGE_REFERENCE.md @@ -35,7 +35,7 @@ The constructor is private; the class holds one shared `Logger`. | Member | Contract | |---|---| -| `new LoggerCleanupService(?string $logBasePath = null)` | Directory to clean. **The default is `dirname(__DIR__, 2) . '/logs'`, which inside `vendor/maatify/logger` is `vendor/maatify/logs`, not the `logs/` folder the logger writes to. Always pass the log directory explicitly.** | +| `new LoggerCleanupService(?string $logBasePath = null)` | Directory to clean. The default is the same `logs/` directory the logger writes to (the consumer project root for `vendor/maatify/logger`). | | `deleteOlderThanDays(int $days): void` | Deletes files under the directory whose modification time is older than the threshold, then removes empty sub-directories. | | `deleteOlderThanHours(int $hours): void` | Same, with an hours threshold. | diff --git a/docs/guides/USAGE_GUIDE.md b/docs/guides/USAGE_GUIDE.md index 934757e..48d6a74 100644 --- a/docs/guides/USAGE_GUIDE.md +++ b/docs/guides/USAGE_GUIDE.md @@ -33,4 +33,4 @@ Input: context containing secrets. Public call: nothing extra for the defaults; ## Cleaning old logs -`LoggerCleanupService` deletes files older than a number of days or hours. Pass the log directory explicitly (`new LoggerCleanupService('/path/to/project/logs')`); its default does not match where the logger writes. Deletion is permanent. +`LoggerCleanupService` deletes files older than a number of days or hours. By default it cleans the same `logs/` directory the logger writes to; pass another directory with `new LoggerCleanupService('/path/to/logs')`. Deletion is permanent. diff --git a/src/LoggerCleanupService.php b/src/LoggerCleanupService.php index 824a967..0e27c2c 100644 --- a/src/LoggerCleanupService.php +++ b/src/LoggerCleanupService.php @@ -23,7 +23,7 @@ final class LoggerCleanupService public function __construct(?string $logBasePath = null) { - $this->logBasePath = $logBasePath ?? dirname(__DIR__, 2) . '/logs'; + $this->logBasePath = $logBasePath ?? dirname(__DIR__, 4) . '/logs'; } /** diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php index 4d8081d..1d4ad6b 100644 --- a/tests/EndToEndLoggingTest.php +++ b/tests/EndToEndLoggingTest.php @@ -20,7 +20,11 @@ protected function setUp(): void $this->root = sys_get_temp_dir() . '/maatify-logger-e2e-' . bin2hex(random_bytes(4)); $src = getenv('LOGGER_SRC') ?: dirname(__DIR__) . '/src'; mkdir($this->root . '/vendor/maatify/logger/src', 0775, true); - copy($src . '/Logger.php', $this->root . '/vendor/maatify/logger/src/Logger.php'); + foreach (['Logger.php', 'LoggerCleanupService.php'] as $file) { + if (is_file($src . '/' . $file)) { + copy($src . '/' . $file, $this->root . '/vendor/maatify/logger/src/' . $file); + } + } } protected function tearDown(): void @@ -70,4 +74,21 @@ public function testSecretsNeverReachTheLogFile(): void $this->assertStringNotContainsString($secret, $content); } } + + public function testCleanupServiceDefaultTargetsTheLoggerDirectory(): void + { + $script = $this->root . '/cleanup.php'; + file_put_contents($script, 'root . '/vendor/maatify/logger/src/Logger.php', true) . '; +require ' . var_export($this->root . '/vendor/maatify/logger/src/LoggerCleanupService.php', true) . '; +(new Maatify\\Logger\\Logger())->info("old entry"); +$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(' . var_export($this->root . '/logs', true) . ', FilesystemIterator::SKIP_DOTS)); +foreach ($it as $f) { if ($f->getExtension() === "log") { touch($f->getPathname(), time() - 2 * 86400); } } +(new Maatify\\Logger\\LoggerCleanupService())->deleteOlderThanDays(1); +'); + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script) . ' 2>&1', $out, $code); + $this->assertSame(0, $code, implode("\n", $out)); + $this->assertSame([], glob($this->root . '/logs/*/*/*/*/*.log') ?: [], 'old log files were not cleaned'); + } } From aba082444b1623229e676c50f8fd515f62a853e4 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:33:51 +0200 Subject: [PATCH 10/13] Strip authority from absolute URIs, keep cleanup guard file, validate level in both backends (#2) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 4 ++ LOGGER_PACKAGE_REFERENCE.md | 9 ++-- README.md | 2 +- docs/guides/USAGE_GUIDE.md | 2 +- src/Logger.php | 36 +++++++++------- src/LoggerCleanupService.php | 34 +++++++++++++-- tests/CleanupTest.php | 79 +++++++++++++++++++++++++++++++++++ tests/EndToEndLoggingTest.php | 38 +++++++++++++++++ tests/RequestUriTest.php | 25 ++++++++++- 9 files changed, 202 insertions(+), 27 deletions(-) create mode 100644 tests/CleanupTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 0254873..9a08790 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ ## [7.0.0] ### Changed (behaviour change) +- `sanitizeRequestUri()` also strips scheme, userinfo, host and port from absolute URLs and `//host/path` references (`https://user:pw@host/cb?x=1` is logged as `/cb`), and yields `''` for anything that is not an origin-form target. Previously `//host/path` was logged as `/host/path`. +- Both backends now reject an unknown log level with `Psr\Log\InvalidArgumentException`; the file fallback previously accepted any string. +- Monolog log folders now receive the same `index.php` guard file as the fallback folders. +- `LoggerCleanupService` no longer deletes `index.php` on age alone and removes a folder holding only an old guard file together with it. - **Breaking:** `LoggerCleanupService` now defaults to the directory the logger writes to (`dirname(__DIR__, 4) . '/logs'`, the consumer project's `logs/`). Previously the default was `dirname(__DIR__, 2) . '/logs'`, which inside `vendor/` pointed at `vendor/maatify/logs` and cleaned nothing; callers relying on that default will now delete old files in the real log directory. - File-fallback log entries now record only the **path** of `REQUEST_URI` (no query string, no fragment). Signatures, tokens and one-time codes in query strings are no longer written to log files. diff --git a/LOGGER_PACKAGE_REFERENCE.md b/LOGGER_PACKAGE_REFERENCE.md index 0babb60..d70e254 100644 --- a/LOGGER_PACKAGE_REFERENCE.md +++ b/LOGGER_PACKAGE_REFERENCE.md @@ -18,7 +18,7 @@ Namespace `Maatify\Logger`. Anything not listed here is not part of the supporte | `static setSensitiveKeys(array $keys): void` | Replaces the list of sensitive context keys (case-insensitive substring match). | | `static setRedactor(?callable $redactor): void` | Registers (or with `null` removes) a hook `fn(array $context): array` run after built-in masking. | | `static redactContext(array $context): array` | Applies built-in masking and the hook; never throws. | -| `static sanitizeRequestUri(mixed $uri): string` | Returns the path of a request URI without query string or fragment; `''` for missing or non-string input. | +| `static sanitizeRequestUri(mixed $uri): string` | Returns only the path of a request URI: no query string, fragment, scheme, userinfo, host or port. `https://user:pw@host/cb?x=1` becomes `/cb`; an absolute URL without a path becomes `/`. Anything that is not an origin-form target (missing or non-string input, `*`, `host:port`) yields `''`. | | `static logFullRequestUri(bool $enabled): void` | Opt-in to keep the full URI in `sanitizeRequestUri()`. Default off. | ### 1.2 `LoggerService` (final, static facade) @@ -39,7 +39,7 @@ The constructor is private; the class holds one shared `Logger`. | `deleteOlderThanDays(int $days): void` | Deletes files under the directory whose modification time is older than the threshold, then removes empty sub-directories. | | `deleteOlderThanHours(int $hours): void` | Same, with an hours threshold. | -A missing directory is ignored; deletion errors are suppressed. The service deletes files permanently. +Files named `index.php` (the logger's access-guard file) are never deleted on age alone. A folder that holds only an old-enough guard file is removed together with it; a folder that still holds newer logs keeps its guard. A missing directory is ignored; deletion errors are suppressed. The service deletes files permanently. ### 1.4 `Maatify\Store\File\Path` (legacy helper) @@ -51,8 +51,9 @@ A missing directory is ignored; deletion errors are suppressed. The service dele An array message is logged as `'Array log entry'` with the array under `context.data`. A `Throwable` message is logged as `'Exception log entry'` with its details under `context.exception`. ### 2.2 Backends and files +- Both backends validate the level first (see §3), then redact, then write. - With Monolog loadable (always, when installed through Composer), entries are written to `logs/YYYY/MM/DD/HH/app_YYYY-MM-DD-HH.log` under the consumer project root (the directory four levels above the package `src/`, i.e. the project root for `vendor/maatify/logger`). The `logFile` argument is not used for routing; it is carried in the context. -- Only when Monolog is not loadable, the file fallback writes pretty-printed JSON entries to `logs/YYYY/MM/DD/HH/_YYYY-MM-DD-HH.log`; a `/` in `logFile` creates sub-folders. Each created folder receives an `index.php` that answers `404`. +- Only when Monolog is not loadable, the file fallback writes pretty-printed JSON entries to `logs/YYYY/MM/DD/HH/_YYYY-MM-DD-HH.log`; a `/` in `logFile` creates sub-folders. Each created log folder (both backends) receives an `index.php` that answers `404`. That file does not prevent a web server from serving a known `.log` path: keep the log directory outside the web root or deny access to it in the server configuration. - Fallback I/O failures are written to `error_logger.log` and never thrown. ### 2.3 Fallback entry shape @@ -73,7 +74,7 @@ Matching is by substring: a key such as `design` also contains `sig` and is mask | Condition | Result | |---|---| -| `log()` with a non-string or unknown level | `Psr\Log\InvalidArgumentException` | +| `log()` with a non-string or unknown level (both backends) | `Psr\Log\InvalidArgumentException` | | Redaction hook throws or returns a non-array | Context replaced by `['redaction' => 'failed']`; logging continues | | Fallback write or folder failure | Recorded in `error_logger.log`; no exception | diff --git a/README.md b/README.md index 3c630f4..74256f6 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,7 @@ An overview only. The complete inventory (signatures, behavior, errors) is [LOGG ## Security and Trust Boundaries -The package masks well-known secret shapes; it cannot know every application secret. Add your own keys with `Logger::setSensitiveKeys()` or a hook with `Logger::setRedactor()`. `REMOTE_ADDR` and `USER_AGENT` are written by the file fallback unconditionally; apply your own retention policy to log files. See [SECURITY.md](SECURITY.md) for reporting. +The package masks well-known secret shapes; it cannot know every application secret. Add your own keys with `Logger::setSensitiveKeys()` or a hook with `Logger::setRedactor()`. Store logs outside the web root or deny access to them in your server configuration: the `index.php` guard in each log folder does not stop a web server from serving a known `.log` path. `REMOTE_ADDR` and `USER_AGENT` are written by the file fallback unconditionally; apply your own retention policy to log files. See [SECURITY.md](SECURITY.md) for reporting. ## Examples diff --git a/docs/guides/USAGE_GUIDE.md b/docs/guides/USAGE_GUIDE.md index 48d6a74..b506cca 100644 --- a/docs/guides/USAGE_GUIDE.md +++ b/docs/guides/USAGE_GUIDE.md @@ -4,7 +4,7 @@ Use `maatify/logger` when you want a PSR-3 logger that writes time-partitioned files and masks secrets before they are written. Requirements are in [README.md](../../README.md#requirements). It is not a log shipper, rotator or retention tool. The complete contract is [LOGGER_PACKAGE_REFERENCE.md](../../LOGGER_PACKAGE_REFERENCE.md). -Logs are written under the root of the consuming project, in `logs/YYYY/MM/DD/HH/`. +Logs are written under the root of the consuming project, in `logs/YYYY/MM/DD/HH/`. Keep that directory outside the web root, or deny access to it in your server configuration; the `index.php` guard in each folder does not stop a web server from serving a known `.log` path. ## Capability map diff --git a/src/Logger.php b/src/Logger.php index 37ad688..9ff9627 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -123,6 +123,17 @@ public function log($level, $message, array $context = []): void if (!is_string($level)) { throw new \Psr\Log\InvalidArgumentException('Log level must be a string'); } + $monologLevel = match (strtolower($level)) { + 'debug' => Level::Debug, + 'info' => Level::Info, + 'notice' => Level::Notice, + 'warning' => Level::Warning, + 'error' => Level::Error, + 'critical' => Level::Critical, + 'alert' => Level::Alert, + 'emergency' => Level::Emergency, + default => throw new \Psr\Log\InvalidArgumentException('Unknown log level: ' . $level), + }; // Wrap behavior → message لازم يكون string if (is_array($message)) { @@ -146,17 +157,6 @@ public function log($level, $message, array $context = []): void if ($this->monolog) { // ✅ Monolog backend - $monologLevel = match (strtolower($level)) { - 'debug' => Level::Debug, - 'info' => Level::Info, - 'notice' => Level::Notice, - 'warning' => Level::Warning, - 'error' => Level::Error, - 'critical' => Level::Critical, - 'alert' => Level::Alert, - 'emergency' => Level::Emergency, - default => throw new \Psr\Log\InvalidArgumentException('Unknown log level: ' . $level), - }; $this->monolog->log($monologLevel, $message, $context); return; } @@ -397,12 +397,16 @@ public static function sanitizeRequestUri(mixed $uri): string // Cut at the first '?' or '#' (also covers malformed URIs parse_url rejects) $path = substr($uri, 0, strcspn($uri, '?#')); - // "//host/path" would be read as an authority; collapse leading slashes to one - if (str_starts_with($path, '//')) { - $path = '/' . ltrim($path, '/'); + // Absolute URL ("scheme://user:pw@host/path") or network-path reference ("//host/path"): + // drop scheme, userinfo, host and port, keep only the path. + if (preg_match('#^(?:[A-Za-z][A-Za-z0-9+.-]*:)?//#', $path, $m) === 1) { + $rest = substr($path, strlen($m[0])); + $slash = strpos($rest, '/'); + $path = $slash === false ? '/' : substr($rest, $slash); } - return $path; + // Only origin-form targets ("/path") are logged; "*", "host:port" and the like yield '' + return str_starts_with($path, '/') ? $path : ''; } /** @@ -420,7 +424,7 @@ private function buildFilePath(string $logFile): string dirname(__DIR__, 4), date('Y'), date('m'), date('d'), date('H') ); - if (!is_dir($dir)) { @mkdir($dir, 0775, true); } + $this->createFolder($dir); return $dir . '/' . $logFile . '_' . date('Y-m-d-H') . '.' . self::$extension; } diff --git a/src/LoggerCleanupService.php b/src/LoggerCleanupService.php index 0e27c2c..49cdcbd 100644 --- a/src/LoggerCleanupService.php +++ b/src/LoggerCleanupService.php @@ -19,6 +19,8 @@ final class LoggerCleanupService { + private const string GUARD_FILE = 'index.php'; + private string $logBasePath; public function __construct(?string $logBasePath = null) @@ -57,14 +59,38 @@ private function cleanup(int $threshold): void foreach ($iterator as $file) { /** @var \SplFileInfo $file */ + $path = $file->getRealPath(); + if ($path === false) { + continue; + } if ($file->isFile()) { - if ($file->getMTime() < $threshold) { - @unlink($file->getRealPath()); + // The access-guard file is removed only together with its folder, never on age alone + if ($file->getFilename() !== self::GUARD_FILE && $file->getMTime() < $threshold) { + @unlink($path); } } elseif ($file->isDir()) { - // نحذف الفولدر لو فاضي - @rmdir($file->getRealPath()); + $this->removeIfEmpty($path, $threshold); + } + } + } + + /** + * A folder holding nothing but an old-enough guard file counts as empty; a fresh folder that the logger + * has just prepared is left alone. + */ + private function removeIfEmpty(string $dir, int $threshold): void + { + $entries = array_values(array_diff(scandir($dir) ?: [], ['.', '..'])); + if ($entries === [self::GUARD_FILE]) { + $guard = $dir . '/' . self::GUARD_FILE; + $mtime = @filemtime($guard); + if ($mtime !== false && $mtime < $threshold) { + @unlink($guard); + $entries = []; } } + if ($entries === []) { + @rmdir($dir); + } } } diff --git a/tests/CleanupTest.php b/tests/CleanupTest.php new file mode 100644 index 0000000..1e0b54d --- /dev/null +++ b/tests/CleanupTest.php @@ -0,0 +1,79 @@ +dir = sys_get_temp_dir() . '/maatify-cleanup-' . bin2hex(random_bytes(4)); + mkdir($this->dir . '/2025/01/01/01', 0775, true); + } + + protected function tearDown(): void + { + self::remove($this->dir); + } + + private static function remove(string $path): void + { + if (!is_dir($path)) { + return; + } + foreach (scandir($path) ?: [] as $entry) { + if ($entry !== '.' && $entry !== '..') { + is_dir($path . '/' . $entry) ? self::remove($path . '/' . $entry) : unlink($path . '/' . $entry); + } + } + rmdir($path); + } + + private function touchOld(string $file): void + { + touch($file, time() - 3 * 86400); + } + + public function testGuardFileIsKeptWhileRecentLogsRemain(): void + { + $leaf = $this->dir . '/2025/01/01/01'; + file_put_contents($leaf . '/index.php', 'touchOld($leaf . '/index.php'); + + (new LoggerCleanupService($this->dir))->deleteOlderThanDays(1); + + $this->assertFileExists($leaf . '/index.php'); + $this->assertFileExists($leaf . '/app_recent.log'); + } + + public function testOldLogsAndTheirGuardAreRemovedTogether(): void + { + $leaf = $this->dir . '/2025/01/01/01'; + file_put_contents($leaf . '/index.php', 'touchOld($leaf . '/app_old.log'); + $this->touchOld($leaf . '/index.php'); + + (new LoggerCleanupService($this->dir))->deleteOlderThanDays(1); + + $this->assertDirectoryDoesNotExist($leaf); + $this->assertDirectoryExists($this->dir); + } + + public function testFreshFolderWithOnlyItsGuardIsKept(): void + { + $leaf = $this->dir . '/2025/01/01/01'; + file_put_contents($leaf . '/index.php', 'dir))->deleteOlderThanDays(1); + + $this->assertFileExists($leaf . '/index.php'); + } +} diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php index 1d4ad6b..89e41fe 100644 --- a/tests/EndToEndLoggingTest.php +++ b/tests/EndToEndLoggingTest.php @@ -91,4 +91,42 @@ public function testCleanupServiceDefaultTargetsTheLoggerDirectory(): void $this->assertSame(0, $code, implode("\n", $out)); $this->assertSame([], glob($this->root . '/logs/*/*/*/*/*.log') ?: [], 'old log files were not cleaned'); } + + public function testMonologPathCreatesTheGuardFile(): void + { + $script = $this->root . '/guard.php'; + file_put_contents($script, 'root . '/vendor/maatify/logger/src/Logger.php', true) . '; +(new Maatify\\Logger\\Logger())->info("x"); +'); + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script) . ' 2>&1', $out, $code); + $this->assertSame(0, $code, implode("\n", $out)); + $this->assertNotEmpty(glob($this->root . '/logs/*/*/*/*/index.php') ?: [], 'guard index.php missing'); + } + + public function testFallbackPathValidatesLevelAndSanitizesUri(): void + { + $script = $this->root . '/fallback.php'; + file_put_contents($script, 'root . '/vendor/maatify/logger/src/Logger.php', true) . '; +$_SERVER["REQUEST_URI"] = "https://user:pass123@example.com/callback?sig=SECRET9"; +$l = new Maatify\\Logger\\Logger(); +$p = new ReflectionProperty($l, "monolog"); +$p->setValue($l, null); +try { $l->log("bogus-level", "x"); fwrite(STDERR, "unknown level accepted\n"); exit(3); } catch (Psr\\Log\\InvalidArgumentException) {} +$l->log("info", "fallback entry"); +'); + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script) . ' 2>&1', $out, $code); + $this->assertSame(0, $code, implode("\n", $out)); + $files = glob($this->root . '/logs/*/*/*/*/app_*.log') ?: []; + $this->assertNotEmpty($files, 'fallback wrote no file'); + $content = (string) file_get_contents((string) reset($files)); + $this->assertStringContainsString('/callback', $content); + foreach (['pass123', 'SECRET9', 'example.com'] as $leak) { + $this->assertStringNotContainsString($leak, $content); + } + $this->assertStringNotContainsString('bogus', $content); + } } diff --git a/tests/RequestUriTest.php b/tests/RequestUriTest.php index d1032d5..b75fc8d 100644 --- a/tests/RequestUriTest.php +++ b/tests/RequestUriTest.php @@ -42,7 +42,8 @@ public function testMissingOrNonString(): void public function testDoubleSlashPrefix(): void { - $this->assertSame('/evil.com/p', Logger::sanitizeRequestUri('//evil.com/p?t=SECRET')); + $this->assertSame('/p', Logger::sanitizeRequestUri('//evil.com/p?t=SECRET')); + $this->assertSame('/p', Logger::sanitizeRequestUri('//user:pass123@evil.com/p?t=SECRET')); } public function testOptInKeepsFullUri(): void @@ -50,4 +51,26 @@ public function testOptInKeepsFullUri(): void Logger::logFullRequestUri(true); $this->assertSame('/cb?sig=1', Logger::sanitizeRequestUri('/cb?sig=1')); } + + public function testAbsoluteUrisDropSchemeAuthorityAndUserinfo(): void + { + $cases = [ + 'https://user:pass123@example.com/callback?sig=SECRET456' => '/callback', + 'http://example.com:8080/a/b#frag' => '/a/b', + 'HTTPS://u:p@example.com' => '/', + 'https://user:pass123@example.com?x=SECRET' => '/', + 'ftp://u:p@h/p' => '/p', + ]; + foreach ($cases as $input => $expected) { + $out = Logger::sanitizeRequestUri($input); + $this->assertSame($expected, $out, $input); + $this->assertStringNotContainsString('pass123', $out); + } + } + + public function testNonOriginFormTargetsAreNotLogged(): void + { + $this->assertSame('', Logger::sanitizeRequestUri('user:pass123@example.com:443')); + $this->assertSame('', Logger::sanitizeRequestUri('*')); + } } From 0d79ec0006931b9b40f9af2f074c8f49d37e69ab Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:39:33 +0200 Subject: [PATCH 11/13] Reject empty-authority URLs and validate level without Monolog (#2) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 2 +- LOGGER_PACKAGE_REFERENCE.md | 4 ++-- src/Logger.php | 34 +++++++++++++++++++++++----------- tests/EndToEndLoggingTest.php | 26 ++++++++++++++++++++++++++ tests/RequestUriTest.php | 16 ++++++++++++++++ 5 files changed, 68 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a08790..d28e168 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ## [7.0.0] ### Changed (behaviour change) -- `sanitizeRequestUri()` also strips scheme, userinfo, host and port from absolute URLs and `//host/path` references (`https://user:pw@host/cb?x=1` is logged as `/cb`), and yields `''` for anything that is not an origin-form target. Previously `//host/path` was logged as `/host/path`. +- `sanitizeRequestUri()` also strips scheme, userinfo, host and port from absolute URLs and `//host/path` references (`https://user:pw@host/cb?x=1` is logged as `/cb`), and yields `''` for anything that is not an origin-form target or has an empty authority. Previously `//host/path` was logged as `/host/path`. - Both backends now reject an unknown log level with `Psr\Log\InvalidArgumentException`; the file fallback previously accepted any string. - Monolog log folders now receive the same `index.php` guard file as the fallback folders. - `LoggerCleanupService` no longer deletes `index.php` on age alone and removes a folder holding only an old guard file together with it. diff --git a/LOGGER_PACKAGE_REFERENCE.md b/LOGGER_PACKAGE_REFERENCE.md index d70e254..521fe6b 100644 --- a/LOGGER_PACKAGE_REFERENCE.md +++ b/LOGGER_PACKAGE_REFERENCE.md @@ -18,7 +18,7 @@ Namespace `Maatify\Logger`. Anything not listed here is not part of the supporte | `static setSensitiveKeys(array $keys): void` | Replaces the list of sensitive context keys (case-insensitive substring match). | | `static setRedactor(?callable $redactor): void` | Registers (or with `null` removes) a hook `fn(array $context): array` run after built-in masking. | | `static redactContext(array $context): array` | Applies built-in masking and the hook; never throws. | -| `static sanitizeRequestUri(mixed $uri): string` | Returns only the path of a request URI: no query string, fragment, scheme, userinfo, host or port. `https://user:pw@host/cb?x=1` becomes `/cb`; an absolute URL without a path becomes `/`. Anything that is not an origin-form target (missing or non-string input, `*`, `host:port`) yields `''`. | +| `static sanitizeRequestUri(mixed $uri): string` | Returns only the path of a request URI: no query string, fragment, scheme, userinfo, host or port. `https://user:pw@host/cb?x=1` becomes `/cb`; an absolute URL without a path becomes `/`. Anything that is not an origin-form target (missing or non-string input, `*`, `host:port`) and any absolute URL with an empty authority (such as `https:///user:pw@host/p`) yields `''`. | | `static logFullRequestUri(bool $enabled): void` | Opt-in to keep the full URI in `sanitizeRequestUri()`. Default off. | ### 1.2 `LoggerService` (final, static facade) @@ -51,7 +51,7 @@ Files named `index.php` (the logger's access-guard file) are never deleted on ag An array message is logged as `'Array log entry'` with the array under `context.data`. A `Throwable` message is logged as `'Exception log entry'` with its details under `context.exception`. ### 2.2 Backends and files -- Both backends validate the level first (see §3), then redact, then write. +- Both backends validate the level first (see §3), then redact, then write. Level validation does not depend on Monolog, so the file fallback works when Monolog is not installed. - With Monolog loadable (always, when installed through Composer), entries are written to `logs/YYYY/MM/DD/HH/app_YYYY-MM-DD-HH.log` under the consumer project root (the directory four levels above the package `src/`, i.e. the project root for `vendor/maatify/logger`). The `logFile` argument is not used for routing; it is carried in the context. - Only when Monolog is not loadable, the file fallback writes pretty-printed JSON entries to `logs/YYYY/MM/DD/HH/_YYYY-MM-DD-HH.log`; a `/` in `logFile` creates sub-folders. Each created log folder (both backends) receives an `index.php` that answers `404`. That file does not prevent a web server from serving a known `.log` path: keep the log directory outside the web root or deny access to it in the server configuration. - Fallback I/O failures are written to `error_logger.log` and never thrown. diff --git a/src/Logger.php b/src/Logger.php index 9ff9627..c7f6902 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -24,6 +24,12 @@ class Logger implements LoggerInterface private const string REDACTED = '***REDACTED***'; private const int MAX_REDACTION_DEPTH = 8; + /** PSR-3 level names accepted by log() (validated independently of Monolog). */ + private const array LEVELS = [ + LogLevel::EMERGENCY, LogLevel::ALERT, LogLevel::CRITICAL, LogLevel::ERROR, + LogLevel::WARNING, LogLevel::NOTICE, LogLevel::INFO, LogLevel::DEBUG, + ]; + /** * Context keys (case-insensitive substring match) whose values are always masked. * @@ -123,17 +129,9 @@ public function log($level, $message, array $context = []): void if (!is_string($level)) { throw new \Psr\Log\InvalidArgumentException('Log level must be a string'); } - $monologLevel = match (strtolower($level)) { - 'debug' => Level::Debug, - 'info' => Level::Info, - 'notice' => Level::Notice, - 'warning' => Level::Warning, - 'error' => Level::Error, - 'critical' => Level::Critical, - 'alert' => Level::Alert, - 'emergency' => Level::Emergency, - default => throw new \Psr\Log\InvalidArgumentException('Unknown log level: ' . $level), - }; + if (!in_array(strtolower($level), self::LEVELS, true)) { + throw new \Psr\Log\InvalidArgumentException('Unknown log level: ' . $level); + } // Wrap behavior → message لازم يكون string if (is_array($message)) { @@ -157,6 +155,17 @@ public function log($level, $message, array $context = []): void if ($this->monolog) { // ✅ Monolog backend + // Monolog\Level is only touched here, so the file fallback works without Monolog + $monologLevel = match (strtolower($level)) { + LogLevel::DEBUG => Level::Debug, + LogLevel::INFO => Level::Info, + LogLevel::NOTICE => Level::Notice, + LogLevel::WARNING => Level::Warning, + LogLevel::ERROR => Level::Error, + LogLevel::CRITICAL => Level::Critical, + LogLevel::ALERT => Level::Alert, + default => Level::Emergency, + }; $this->monolog->log($monologLevel, $message, $context); return; } @@ -401,6 +410,9 @@ public static function sanitizeRequestUri(mixed $uri): string // drop scheme, userinfo, host and port, keep only the path. if (preg_match('#^(?:[A-Za-z][A-Za-z0-9+.-]*:)?//#', $path, $m) === 1) { $rest = substr($path, strlen($m[0])); + if ($rest === '' || $rest[0] === '/') { + return ''; // empty authority: not a valid URL, refuse rather than guess what is userinfo + } $slash = strpos($rest, '/'); $path = $slash === false ? '/' : substr($rest, $slash); } diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php index 89e41fe..27d69e4 100644 --- a/tests/EndToEndLoggingTest.php +++ b/tests/EndToEndLoggingTest.php @@ -129,4 +129,30 @@ public function testFallbackPathValidatesLevelAndSanitizesUri(): void } $this->assertStringNotContainsString('bogus', $content); } + + public function testFallbackWorksWhenMonologIsReallyAbsent(): void + { + $psr = dirname(__DIR__) . '/vendor/psr/log/src/'; + $script = $this->root . '/nomonolog.php'; + file_put_contents($script, 'root . '/vendor/maatify/logger/src/Logger.php', true) . '; +if (class_exists("Monolog\\\\Logger")) { fwrite(STDERR, "monolog unexpectedly loadable\n"); exit(4); } +$l = new Maatify\\Logger\\Logger(); +$l->log("ERROR", "no monolog entry", ["password" => "SECRET11"]); +try { $l->log("bogus", "x"); fwrite(STDERR, "unknown level accepted\n"); exit(3); } catch (Psr\\Log\\InvalidArgumentException) {} +echo "ok"; +'); + exec(escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script) . ' 2>&1', $out, $code); + $this->assertSame(0, $code, implode("\n", $out)); + $files = glob($this->root . '/logs/*/*/*/*/app_*.log') ?: []; + $this->assertNotEmpty($files, 'fallback wrote no file'); + $content = (string) file_get_contents((string) reset($files)); + $this->assertStringContainsString('no monolog entry', $content); + $this->assertStringNotContainsString('SECRET11', $content); + } } diff --git a/tests/RequestUriTest.php b/tests/RequestUriTest.php index b75fc8d..0ad9973 100644 --- a/tests/RequestUriTest.php +++ b/tests/RequestUriTest.php @@ -73,4 +73,20 @@ public function testNonOriginFormTargetsAreNotLogged(): void $this->assertSame('', Logger::sanitizeRequestUri('user:pass123@example.com:443')); $this->assertSame('', Logger::sanitizeRequestUri('*')); } + + public function testMalformedAbsoluteUrisNeverExposeUserinfo(): void + { + $inputs = [ + 'https:///user:PASS123@host/path?sig=X', + 'http:////user:PASS456@host/path', + '///user:PASS789@host/path', + '////user:PASS790@host/p', + 'https:\\\\user:PASS791@host/p', + ]; + foreach ($inputs as $input) { + $out = Logger::sanitizeRequestUri($input); + $this->assertStringNotContainsString('PASS', $out, $input); + $this->assertStringNotContainsString('@', $out, $input); + } + } } From 27c62c4a1918cfeb0f98907f9d829331c42883ce Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:46:05 +0200 Subject: [PATCH 12/13] Never follow or delete symlinks in log cleanup (#2) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + LOGGER_PACKAGE_REFERENCE.md | 2 +- src/LoggerCleanupService.php | 5 +++-- tests/CleanupTest.php | 37 ++++++++++++++++++++++++++++++++++++ 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d28e168..7ab49e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - `sanitizeRequestUri()` also strips scheme, userinfo, host and port from absolute URLs and `//host/path` references (`https://user:pw@host/cb?x=1` is logged as `/cb`), and yields `''` for anything that is not an origin-form target or has an empty authority. Previously `//host/path` was logged as `/host/path`. - Both backends now reject an unknown log level with `Psr\Log\InvalidArgumentException`; the file fallback previously accepted any string. - Monolog log folders now receive the same `index.php` guard file as the fallback folders. +- `LoggerCleanupService` no longer follows or deletes symbolic links (previously a link inside the log directory could cause deletion of its target outside it). - `LoggerCleanupService` no longer deletes `index.php` on age alone and removes a folder holding only an old guard file together with it. - **Breaking:** `LoggerCleanupService` now defaults to the directory the logger writes to (`dirname(__DIR__, 4) . '/logs'`, the consumer project's `logs/`). Previously the default was `dirname(__DIR__, 2) . '/logs'`, which inside `vendor/` pointed at `vendor/maatify/logs` and cleaned nothing; callers relying on that default will now delete old files in the real log directory. - File-fallback log entries now record only the **path** of `REQUEST_URI` (no query string, no fragment). diff --git a/LOGGER_PACKAGE_REFERENCE.md b/LOGGER_PACKAGE_REFERENCE.md index 521fe6b..d5c7157 100644 --- a/LOGGER_PACKAGE_REFERENCE.md +++ b/LOGGER_PACKAGE_REFERENCE.md @@ -39,7 +39,7 @@ The constructor is private; the class holds one shared `Logger`. | `deleteOlderThanDays(int $days): void` | Deletes files under the directory whose modification time is older than the threshold, then removes empty sub-directories. | | `deleteOlderThanHours(int $hours): void` | Same, with an hours threshold. | -Files named `index.php` (the logger's access-guard file) are never deleted on age alone. A folder that holds only an old-enough guard file is removed together with it; a folder that still holds newer logs keeps its guard. A missing directory is ignored; deletion errors are suppressed. The service deletes files permanently. +Files named `index.php` (the logger's access-guard file) are never deleted on age alone. A folder that holds only an old-enough guard file is removed together with it; a folder that still holds newer logs keeps its guard. Symbolic links inside the directory are neither followed nor deleted, so nothing outside the log directory is ever touched. A missing directory is ignored; deletion errors are suppressed. The service deletes files permanently. ### 1.4 `Maatify\Store\File\Path` (legacy helper) diff --git a/src/LoggerCleanupService.php b/src/LoggerCleanupService.php index 49cdcbd..029098e 100644 --- a/src/LoggerCleanupService.php +++ b/src/LoggerCleanupService.php @@ -59,10 +59,11 @@ private function cleanup(int $threshold): void foreach ($iterator as $file) { /** @var \SplFileInfo $file */ - $path = $file->getRealPath(); - if ($path === false) { + // Symlinks are never followed or deleted: the target may live outside the log directory. + if ($file->isLink()) { continue; } + $path = $file->getPathname(); if ($file->isFile()) { // The access-guard file is removed only together with its folder, never on age alone if ($file->getFilename() !== self::GUARD_FILE && $file->getMTime() < $threshold) { diff --git a/tests/CleanupTest.php b/tests/CleanupTest.php index 1e0b54d..a6e09d5 100644 --- a/tests/CleanupTest.php +++ b/tests/CleanupTest.php @@ -76,4 +76,41 @@ public function testFreshFolderWithOnlyItsGuardIsKept(): void $this->assertFileExists($leaf . '/index.php'); } + + public function testSymlinkedFileOutsideRootIsNeverDeleted(): void + { + $outside = sys_get_temp_dir() . '/maatify-outside-' . bin2hex(random_bytes(4)); + mkdir($outside); + $target = $outside . '/external-file.txt'; + file_put_contents($target, 'keep me'); + $this->touchOld($target); + symlink($target, $this->dir . '/external.log'); + + try { + (new LoggerCleanupService($this->dir))->deleteOlderThanDays(1); + $this->assertFileExists($target, 'file outside the log root was deleted through a symlink'); + $this->assertSame('keep me', file_get_contents($target)); + } finally { + @unlink($this->dir . '/external.log'); + self::remove($outside); + } + } + + public function testSymlinkedDirectoryOutsideRootIsNeverTouched(): void + { + $outside = sys_get_temp_dir() . '/maatify-outside-' . bin2hex(random_bytes(4)); + mkdir($outside); + file_put_contents($outside . '/index.php', 'touchOld($outside . '/index.php'); + symlink($outside, $this->dir . '/alias'); + + try { + (new LoggerCleanupService($this->dir))->deleteOlderThanDays(1); + $this->assertDirectoryExists($outside); + $this->assertFileExists($outside . '/index.php'); + } finally { + @unlink($this->dir . '/alias'); + self::remove($outside); + } + } } From 74022f8bcc075c1ac86037e6d53dd20dcdf63749 Mon Sep 17 00:00:00 2001 From: Mohamed Abdulalim Date: Sat, 31 Oct 2026 19:50:01 +0200 Subject: [PATCH 13/13] Keep a symlinked guard file and its folder during cleanup (#2) Co-Authored-By: Claude Sonnet 5.5 --- src/LoggerCleanupService.php | 3 +++ tests/CleanupTest.php | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/LoggerCleanupService.php b/src/LoggerCleanupService.php index 029098e..24da0f4 100644 --- a/src/LoggerCleanupService.php +++ b/src/LoggerCleanupService.php @@ -84,6 +84,9 @@ private function removeIfEmpty(string $dir, int $threshold): void $entries = array_values(array_diff(scandir($dir) ?: [], ['.', '..'])); if ($entries === [self::GUARD_FILE]) { $guard = $dir . '/' . self::GUARD_FILE; + if (is_link($guard)) { + return; // symlinks are never deleted, so the folder is not empty + } $mtime = @filemtime($guard); if ($mtime !== false && $mtime < $threshold) { @unlink($guard); diff --git a/tests/CleanupTest.php b/tests/CleanupTest.php index a6e09d5..42b4a34 100644 --- a/tests/CleanupTest.php +++ b/tests/CleanupTest.php @@ -113,4 +113,27 @@ public function testSymlinkedDirectoryOutsideRootIsNeverTouched(): void self::remove($outside); } } + + public function testSymlinkNamedGuardFileIsKeptWithItsFolder(): void + { + $outside = sys_get_temp_dir() . '/maatify-outside-' . bin2hex(random_bytes(4)); + mkdir($outside); + $target = $outside . '/guard-reference.php'; + file_put_contents($target, 'dir . '/2025/01/01/01'; + symlink($target, $leaf . '/index.php'); + $this->touchOld($target); + // age the link itself, not its target, so the age check cannot be what protects it + exec('touch -h -t 202501010101 ' . escapeshellarg($leaf . '/index.php')); + + try { + (new LoggerCleanupService($this->dir))->deleteOlderThanDays(1); + $this->assertTrue(is_link($leaf . '/index.php'), 'the symlink itself was deleted'); + $this->assertDirectoryExists($leaf); + $this->assertFileExists($target); + } finally { + @unlink($leaf . '/index.php'); + self::remove($outside); + } + } }