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 new file mode 100644 index 0000000..18dbdaf --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,100 @@ +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 + + 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 + - name: Examples smoke execution + run: composer examples + + 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, 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 }} 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/.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..7ab49e4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,44 @@ +# Changelog + +## [Unreleased] + +## [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 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). + 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. +- 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. + +### 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. +- **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/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 new file mode 100644 index 0000000..5536011 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,53 @@ +# Contributing + +## Package identity and boundaries + +`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 | +|---|---|---| +| 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 | +| 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. + +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` 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: 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..d5c7157 --- /dev/null +++ b/LOGGER_PACKAGE_REFERENCE.md @@ -0,0 +1,85 @@ +# 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. This section is the complete inventory of the public classes. + +### 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 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) + +| 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`. + +### 1.3 `LoggerCleanupService` (final) + +| Member | Contract | +|---|---| +| `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. | + +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) + +`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 +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. 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. + +### 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. 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. + +## 3. Errors + +| Condition | Result | +|---|---| +| `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 | + +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..74256f6 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()`. 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. -```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 4d0ad06..ee09872 100644 --- a/composer.json +++ b/composer.json @@ -1,14 +1,15 @@ { "name": "maatify/logger", - "description": "maatify.dev logger, known by our team", - "version": "5.1.2", + "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": [ { @@ -43,14 +44,54 @@ } ], "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": { "psr-4": { "Maatify\\Logger\\": "src/", "Maatify\\Store\\File\\": "src/store/file/" } + }, + "autoload-dev": { + "psr-4": { + "Maatify\\Logger\\Tests\\": "tests/" + } + }, + "config": { + "sort-packages": true + }, + "scripts": { + "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", + "@harness", + "@examples", + "@audit:deps" + ], + "harness": "scripts/consumer-harness.sh", + "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..b506cca --- /dev/null +++ b/docs/guides/USAGE_GUIDE.md @@ -0,0 +1,36 @@ +# 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/`. 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 + +| 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, 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. 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/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 new file mode 100644 index 0000000..efbd19a --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,6 @@ +parameters: + level: max + paths: + - src + - tests + - examples 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/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/lint-php.php b/scripts/lint-php.php new file mode 100644 index 0000000..6fa714d --- /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 100755 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/scripts/run-examples.sh b/scripts/run-examples.sh new file mode 100755 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 new file mode 100644 index 0000000..c5aa162 --- /dev/null +++ b/scripts/verify-release-artifact.php @@ -0,0 +1,107 @@ + 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', '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/*") ?: []) !== []); + +// 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 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/)')); + +// 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) { + 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); diff --git a/src/Logger.php b/src/Logger.php index d52e5b7..c7f6902 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; @@ -18,6 +19,28 @@ class Logger implements LoggerInterface { private static string $extension = 'log'; + private static bool $logFullRequestUri = false; + + 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. + * + * @var list + */ + 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; @@ -41,6 +64,8 @@ public function __construct() /** * Legacy method + * + * @param string|array|Throwable $message */ public static function RecordLog( string|array|Throwable $message, @@ -51,20 +76,63 @@ 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'); + } + 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)) { $context['data'] = $message; @@ -80,15 +148,31 @@ public function log($level, $message, array $context = []): void $message = 'Exception log entry'; } + $message = (string) $message; + + $context = self::redactContext($context); + $message = self::scrubString($message); + if ($this->monolog) { // โœ… Monolog backend - $this->monolog->log($level, $message, $context); + // 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; } // โŒ fallback โ†’ ู…ู„ูุงุช try { - $logFile = $context['logFile'] ?? 'app'; + $logFile = is_string($context['logFile'] ?? null) ? $context['logFile'] : 'app'; unset($context['logFile']); $payload = [ @@ -97,7 +181,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 +223,212 @@ 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. + * + * @param null|callable(array): array $redactor + */ + public static function setRedactor(?callable $redactor): void + { + self::$redactor = $redactor; + } + + /** + * Replace the list of sensitive context keys (case-insensitive substring match). + * + * @param list $keys + */ + public static function setSensitiveKeys(array $keys): void + { + 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 { + $context = self::maskKeys($context); + if (self::$redactor !== null) { + // The hook's output is re-scanned so it cannot re-introduce sensitive data. + $context = self::maskKeys((self::$redactor)($context)); + } + 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) { + return ['truncated' => 'max depth reached']; + } + + $out = []; + foreach ($data as $key => $value) { + if (is_string($key) && self::isSensitiveKey($key)) { + $out[$key] = self::REDACTED; + } else { + $out[$key] = self::maskValue($value, $depth + 1); + } + } + 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); + } + 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. + */ + /** @return array */ + 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 + { + $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; + } + // 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, + $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, '?#')); + + // 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])); + 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); + } + + // Only origin-form targets ("/path") are logged; "*", "host:port" and the like yield '' + return str_starts_with($path, '/') ? $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( @@ -147,7 +436,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 824a967..24da0f4 100644 --- a/src/LoggerCleanupService.php +++ b/src/LoggerCleanupService.php @@ -19,11 +19,13 @@ final class LoggerCleanupService { + private const string GUARD_FILE = 'index.php'; + private string $logBasePath; public function __construct(?string $logBasePath = null) { - $this->logBasePath = $logBasePath ?? dirname(__DIR__, 2) . '/logs'; + $this->logBasePath = $logBasePath ?? dirname(__DIR__, 4) . '/logs'; } /** @@ -57,14 +59,42 @@ private function cleanup(int $threshold): void foreach ($iterator as $file) { /** @var \SplFileInfo $file */ + // Symlinks are never followed or deleted: the target may live outside the log directory. + if ($file->isLink()) { + continue; + } + $path = $file->getPathname(); 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; + 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); + $entries = []; + } + } + if ($entries === []) { + @rmdir($dir); + } + } } 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/CleanupTest.php b/tests/CleanupTest.php new file mode 100644 index 0000000..42b4a34 --- /dev/null +++ b/tests/CleanupTest.php @@ -0,0 +1,139 @@ +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'); + } + + 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); + } + } + + 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); + } + } +} diff --git a/tests/EndToEndLoggingTest.php b/tests/EndToEndLoggingTest.php new file mode 100644 index 0000000..27d69e4 --- /dev/null +++ b/tests/EndToEndLoggingTest.php @@ -0,0 +1,158 @@ +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); + 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 + { + 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($path); + } + + 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")); +$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]); +'); + 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((string) reset($files)); + + $this->assertStringContainsString('visible', $content); + foreach (['SECRET1', 'SECRET2', 'SECRET3', 'SECRET4', 'SECRET5', 'SECRET6', 'SECRET7', 'SECRET8'] as $secret) { + $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'); + } + + 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); + } + + 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/RedactionTest.php b/tests/RedactionTest.php new file mode 100644 index 0000000..c413b82 --- /dev/null +++ b/tests/RedactionTest.php @@ -0,0 +1,165 @@ + $data */ + private static function json(array $data): string + { + return json_encode($data, JSON_THROW_ON_ERROR); + } + + protected function tearDown(): void + { + Logger::setRedactor(null); + Logger::setSensitiveKeys(['password', 'passwd', 'secret', 'token', 'authorization', 'api_key', 'apikey', 'sig', 'signature', 'otp', 'cookie']); + } + + public function testSensitiveKeysAreMaskedRecursively(): void + { + $out = Logger::redactContext(['user' => 'a', 'Password' => 'P1', 'nested' => ['api_token' => 'T1']]); + $this->assertSame('a', $out['user']); + $this->assertStringNotContainsString('P1', self::json($out)); + $this->assertStringNotContainsString('T1', self::json($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 = self::json($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', self::json($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 = self::json($out); + $this->assertStringNotContainsString('SECRET', $json); + $this->assertStringContainsString('RuntimeException', $json); + $this->assertIsArray($out['exception']); + $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', self::json($out), $text); + $this->assertStringNotContainsString('dXNlcjpTRUNSRVQ', self::json($out), $text); + } + } + + 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->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([]))); + } +} diff --git a/tests/RequestUriTest.php b/tests/RequestUriTest.php new file mode 100644 index 0000000..0ad9973 --- /dev/null +++ b/tests/RequestUriTest.php @@ -0,0 +1,92 @@ +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('/p', Logger::sanitizeRequestUri('//evil.com/p?t=SECRET')); + $this->assertSame('/p', Logger::sanitizeRequestUri('//user:pass123@evil.com/p?t=SECRET')); + } + + 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('*')); + } + + 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); + } + } +}